xiaojie06 commited on
Commit
9c70fe0
·
verified ·
1 Parent(s): d8632f2

Add exact model code and documentation (2/7)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. code/MANIFEST.json +0 -0
  2. code/environment_versions.json +15 -0
  3. code/snapshot/root/code/ceir_r1_20261109/EXECUTION.md +78 -0
  4. code/snapshot/root/code/ceir_r1_20261109/METHOD.md +182 -0
  5. code/snapshot/root/code/ceir_r1_20261109/ablation_matrix.json +0 -0
  6. code/snapshot/root/code/ceir_r1_20261109/acceptance_ceir.py +110 -0
  7. code/snapshot/root/code/ceir_r1_20261109/comparison_ceir.py +98 -0
  8. code/snapshot/root/code/ceir_r1_20261109/data_ceir.py +115 -0
  9. code/snapshot/root/code/ceir_r1_20261109/debug_parity_ceir.py +35 -0
  10. code/snapshot/root/code/ceir_r1_20261109/evidence_ceir.py +141 -0
  11. code/snapshot/root/code/ceir_r1_20261109/mces_ceir.py +106 -0
  12. code/snapshot/root/code/ceir_r1_20261109/model_ceir.py +170 -0
  13. code/snapshot/root/code/ceir_r1_20261109/objective_sanity_checks.py +66 -0
  14. code/snapshot/root/code/ceir_r1_20261109/objective_sanity_validation.json +15 -0
  15. code/snapshot/root/code/ceir_r1_20261109/objectives_ceir.py +167 -0
  16. code/snapshot/root/code/ceir_r1_20261109/pipeline_ceir.py +126 -0
  17. code/snapshot/root/code/ceir_r1_20261109/plan.json +182 -0
  18. code/snapshot/root/code/ceir_r1_20261109/prepare-evidence.supervisor.conf +31 -0
  19. code/snapshot/root/code/ceir_r1_20261109/prepare_ceir.py +345 -0
  20. code/snapshot/root/code/ceir_r1_20261109/reference/diagnosis.json +0 -0
  21. code/snapshot/root/code/ceir_r1_20261109/refresh_ceir.py +21 -0
  22. code/snapshot/root/code/ceir_r1_20261109/runtime_ceir.py +159 -0
  23. code/snapshot/root/code/ceir_r1_20261109/sampling_ledger_ceir.py +47 -0
  24. code/snapshot/root/code/ceir_r1_20261109/test_comparison_ceir.py +46 -0
  25. code/snapshot/root/code/ceir_r1_20261109/test_evidence_ceir.py +46 -0
  26. code/snapshot/root/code/ceir_r1_20261109/test_sampling_ledger_ceir.py +35 -0
  27. code/snapshot/root/code/ceir_r1_20261109/train_ceir.py +113 -0
  28. code/snapshot/root/code/ceir_r1_20261109/training.supervisor.conf +76 -0
  29. code/snapshot/root/code/ceir_r1_20261109/validate_plan.py +123 -0
  30. code/snapshot/root/code/ceir_r1_20261109/validation.json +51 -0
  31. code/snapshot/root/code/ceir_r1_20261109/validation_ceir.py +135 -0
  32. code/snapshot/root/code/ceir_r1_test_comparison_20261110/config.json +28 -0
  33. code/snapshot/root/code/ceir_r1_test_comparison_20261110/evaluation_runtime.py +140 -0
  34. code/snapshot/root/code/ceir_r1_test_comparison_20261110/infer.py +240 -0
  35. code/snapshot/root/code/ceir_r1_test_comparison_20261110/mces.py +115 -0
  36. code/snapshot/root/code/ceir_r1_test_comparison_20261110/parallel-models.supervisor.conf +55 -0
  37. code/snapshot/root/code/ceir_r1_test_comparison_20261110/prepare.py +78 -0
  38. code/snapshot/root/code/ceir_r1_test_comparison_20261110/supervisor.conf +55 -0
  39. code/snapshot/root/code/ceir_r1_test_comparison_20261110/test_logic.py +41 -0
  40. code/snapshot/root/code/ceir_r2_20261110/METHOD.md +133 -0
  41. code/snapshot/root/code/ceir_r2_20261110/acceptance_r2.py +102 -0
  42. code/snapshot/root/code/ceir_r2_20261110/analyze_r2.py +76 -0
  43. code/snapshot/root/code/ceir_r2_20261110/audit_r2.py +66 -0
  44. code/snapshot/root/code/ceir_r2_20261110/benchmark.supervisor.conf +12 -0
  45. code/snapshot/root/code/ceir_r2_20261110/benchmark_r2.py +29 -0
  46. code/snapshot/root/code/ceir_r2_20261110/canonical_cache_r2.py +110 -0
  47. code/snapshot/root/code/ceir_r2_20261110/config.json +46 -0
  48. code/snapshot/root/code/ceir_r2_20261110/data_r2.py +51 -0
  49. code/snapshot/root/code/ceir_r2_20261110/features_r2.py +133 -0
  50. code/snapshot/root/code/ceir_r2_20261110/mces_monitor_r2.py +17 -0
code/MANIFEST.json ADDED
The diff for this file is too large to render. See raw diff
 
code/environment_versions.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "python": "3.12.15 (main, Oct 13 2026, 16:52:04) [GCC 15.3.0]",
3
+ "packages": {
4
+ "torch": "2.6.0+cu124",
5
+ "numpy": "1.26.4",
6
+ "scipy": "1.15.3",
7
+ "rdkit": "2025.9.3",
8
+ "networkx": "3.7",
9
+ "PyYAML": "6.0.2",
10
+ "pandas": "2.3.0",
11
+ "myopic-mces": null,
12
+ "PuLP": null
13
+ },
14
+ "scope": "Observed training environment package metadata; no environment or credentials uploaded"
15
+ }
code/snapshot/root/code/ceir_r1_20261109/EXECUTION.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CEIR R1 服务器执行记录
2
+
3
+ 本次授权只运行主方案和匹配对照,两臂均由指定C03 2,000步权重继续到4,000步,即各新增2,000步。不会自动追加到6,000步,也不启动其余消融或R2。
4
+
5
+ ## 最新启动核验:已实际并行续训
6
+
7
+ 2026-11-09 的启动快照已保存于`server_receipts/STARTUP_RECEIPT.json`。这是一份带时间戳的启动事实记录,不是训练完成报告,运行中计数会继续增长。
8
+
9
+ - 17,397个共享池、139,347个教师查询全部完成;其中139,251个有效竞争视图,96个原池不具备有效竞争,按规则mask,不补真值。
10
+ - Train的252,672条实际记录与完整Validation的19,429条记录已完成离线峰组成证据准备。
11
+ - 13项CPU单测、6项数学校验及27项静态方案检查通过;后两类不能冒充GPU训练验收。
12
+ - 最终两臂288条真实Train GPU验收、断点恢复及官方Validation入口检查通过,初始分数与恢复Loss绝对差均为0。
13
+ - 启动快照时主方案累计2016步(新增16步),对照累计2027步(新增27步),两者均有真实SGD日志,非等待或排队。
14
+ - 两者启动时的首个可恢复checkpoint均已保存到累计2001步;之后每100步自动保存,不把checkpoint之后尚未落盘的日志步数冒充已保存进度。
15
+ - 主管服务、两臂训练及独立MCES/教师刷新服务已注册;原C03队列和MSG-only服务保持原PID运行,未停止或重启。
16
+ - 本地与服务器23个冻结代码/配置文件哈希一致。正式全量Validation在累计3000、4000步触发,当前尚无本轮完整效果结论。
17
+
18
+ ## 路径与事实来源
19
+
20
+ - 本地代码和设计:本目录。
21
+ - 服务器代码:`/root/xj/SpecPartition-MS/code/ceir_r1_20261109`。
22
+ - 服务器结果:`/root/xj/SpecPartition-MS/runs/ceir_r1_20261109`。
23
+ - `plan.json`、`validation.json`是原方案及静态配置检查,不是运行就绪或训练完成声明。
24
+ - 实际就绪看结果目录`READY.json`、两臂`acceptance.json`;训练看各自`status.json`、`loss.jsonl`、checkpoint和`COMPLETE.json`。
25
+
26
+ ## 已核对的源状态
27
+
28
+ 父权重SHA256为`8a2982f3821fad501ba4f39ac8b1495affeb0c1b09051f2103317f36027d48b6`。保存进度为`update=2000, epoch=0, next_step=2000`。
29
+
30
+ 父优化器有301个注册参数,其中264个已有Adam状态。这是两个不同口径,不能以其中一个代替另一个。新入口保留旧参数顺序和既有Adam状态,新模块放入独立参数组。
31
+
32
+ 两臂模型均注册18,568,595个参数;对照关闭新增模块的评分及辅助目标,不代表每步更新全部注册参数。父模型注册17,001,870个参数。
33
+
34
+ 临时实批GPU探针已测试288条真实Train记录,包括新增分支梯度和断点恢复;临时更新不计正式训练。初始分数和恢复Loss的绝对差均为0。实测峰值allocated显存:对照约706MiB,主方案约833MiB;不是整卡占用或未来所有批次峰值上限。完整准备之后还会重新进行绑定最终代码和数据的GPU验收。
35
+
36
+ ## 数据准备范围
37
+
38
+ 完全沿用父模型采样日程,从原数据游标2000继续至4000。工作清单SHA256为`b013c5b461d032b25a9d5d26e1b9058e1ade4455f9a87811144d1fd0594130bd`。
39
+
40
+ 本次2,000更新涉及252,672条不同训练记录:64,000条MSG、188,672条外部谱库。每步并非都恰好有256条外部谱图;这是原日程的分配方式,不能为了填满batch重复物理谱图。真实288条大批次用于完整GPU验收。两臂的MS顺序、数据暴露量和负例抽样预算相同。
41
+
42
+ 待制作的教师查询索引为139,347个谱图候选视图,共17,397个共享池任务。合法缺正例/缺不同身份负例的池单独mask,不注入真值、不伪造负例。原始候选及其多重条目保持不变。
43
+
44
+ 外部谱库原有公式集合是`label_conditioned_training_competition`,不是盲预测结果;这一训练监督来源保持披露。MSG与后续评估使用实际官方候选公式,不能把训练标签条件集合当作开放式公式预测。
45
+
46
+ 教师对完整可用原池评分,不使用只看全局向量的替代分数。数值路线为BF16 GNN及FP32局部匹配;分块局部结果与逐查询参考通过严格一致性检查。冻结教师可使用有界CPU原子表示缓存以减少重复编码,绑定该教师checkpoint;学生不复用过期可训练embedding。
47
+
48
+ ## 新入口的关键修复
49
+
50
+ PubChem记录同时保留原始与规范化SMILES。新适配器必须按与原data09一致的`canonical_smiles`查结构缓存,而不是优先取原始SMILES。没有为此修改原候选或原缓存。
51
+
52
+ 零初始化反向局部残差必须在父模型完成BF16局部分数乘权重之后加入。若先加FP32的零再乘权重,会改变父路径的舍入,产生约1e-3差异;当前修复后严格恢复父分数。
53
+
54
+ 有放回抽样不等于独立身份数。主方案保留原记录,显式进行身份损失计权;官方Validation排名仍让原始别名占用原名次。训练日志记录负例次数、不同key14���、来源及教师版本。
55
+
56
+ ## 运行与恢复
57
+
58
+ 准备服务分别负责化学证据与全池教师索引。门控服务只在代码冻结、完整缓存核验、两臂真实GPU及Validation入口验收完成后放行。
59
+
60
+ 主方案和对照使用独立进程、优化器、随机数状态、锁、日志及输出。每100步保存可恢复last,每500步保存里程碑;新增1,000与2,000步即累计3,000、4,000时做全量官方Validation。
61
+
62
+ 首个正式新更新也立即保存last。每次恢复记录独立attempt ID;日志不删除,若有checkpoint之后回滚重放的步数,分析时按同一update最后一次记录取值,不把重放算作额外新更新。累计暴露计数从checkpoint恢复。
63
+
64
+ 异步教师刷新在主方案累计3,000步时请求,绑定该checkpoint,只处理剩余Train工作;原索引最大年龄不超过本次2,000更新。若刷新未及完成,继续使用尚未超过年龄上限的审计索引并记录版本。到批准的4,000步端点后不再为无后续训练的任务继续刷新。
65
+
66
+ 主方案的`sampling_decisions.sqlite`逐查询/视图/采样种子固定教师版本与该行哈希,包括DataLoader提前准备的batch。已有记录在重放时不会改选后来出现的新教师;丢失已固定的行或账本将拒绝恢复,避免同一个更新因重启而悄悄换负例。账本只保存取样追踪,不重新处理结构或联网。
67
+
68
+ Validation和MCES输出独立保存,MCES固定myopic-mces1.0.0、PuLP2.9.0、threshold15、单solver线程、5秒限时,保留近似/缺失;只作评估,不用于训练隔离筛选。
69
+
70
+ 每个完整Validation输出两种视图的结构Top1/3/5/10/20/50/100/200、池内分子式Top1至10及20/50/100/200、覆盖率、宏平均,以及adduct、极性、峰数、候选量、同公式候选量、仪器和CE缺失分层。主指标是key14;完整InChIKey和canonical-isomeric-SMILES次指标本轮未实现,不冒充已经计算。配对比较使用相同checkpoint阶段、相同谱图分母,MCES限制在共同有效样本;预设guardrail只生成建议,不自动追加训练或发布模型。
71
+
72
+ `EXECUTION_CONFIG.json`记录接入后的真实运行配置,`MATCHED_VALIDATION_COMPARISON.json/.md`在完整验证和MCES陆续完成后自动更新。源目录的`plan.json`保留历史设计状态,不覆盖原记录或拿静态readiness字段冒充当前运行状态。
73
+
74
+ 整卡只有一张4090且有其他活跃任务。新任务CPU nice19、单线程、小块计算、每进程11% allocator上限及显存等待;未停止、重启或修改旧任务。共享GPU可能竞争计算时间,不承诺零速度影响。
75
+
76
+ 本轮优先保持严格损失分母和低峰值显存。批内对比用确定性gradient-cache回放;显式候选池逐视图反向,仍会在不同候选视图重复编码相同学生分子,不声称已经做到整步全池GNN只编码一次。长久缓存只用于冻结教师。当前记录共享主干与两个新头的总梯度范数,不把它们冒充每项Loss之间的完整梯度冲突审计;后者尚未实现。未来吞吐优化必须另做数值等价检查,不在本次运行中静默替换任务。
77
+
78
+ 代码、配置和父依赖哈希保存在结果目录`SOURCE_MANIFEST.json`与`source_snapshot/`,完整数据资产哈希由`prepared/ASSET_MANIFEST.json`记录。容器重建可能丢失非卷目录,应保留本地代码快照并在后续备份checkpoint;不能将目录存在当作跨recycle持久化保证。
code/snapshot/root/code/ceir_r1_20261109/METHOD.md ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SpecPartition MS CEIR 同分异构体精排方案
2
+
3
+ 更新日期:2026年11月9日。CEIR 表示 Chemical Evidence for Isomer Ranking。本方案合并C03诊断与MIST、MIST-CF、FLARE、ICEBERG、GLACIER的机制分析,给出下一轮主推方案和训练协议。它是待验证的研究方案,不是已证实最强模型。
4
+
5
+ ## 1 决策与边界
6
+
7
+ 以C03 `step_002000.pt`继续训练,不替换成C03 12k,不从随机初始化开始。C03主干、原始MS通道、有效batch和原候选协议保留。主攻正确分子式下的结构排序,并约束Mass检索和分子式任务不退化。
8
+
9
+ 当前证据:MSG Formula 17,556条中有14,685条属于池内同公式结构误排;CASMI 500条中404条属于这一类。CASMI33条真值缺失属于候选覆盖,不计为可由排序修复的问题。相关统计是诊断,不是模型增益预测。
10
+
11
+ Test与CASMI已经被查看,必须如实记录开发过程;它们不参与接下来的负例挖掘、超参数选择或停止决策。现有额外训练源只核验key14隔离,不宣称已满足官方MCES结构距离隔离。
12
+
13
+ ## 2 完整模型与首轮范围
14
+
15
+ R1主推模型联合使用五项改动:混合难负例、同公式精排约束、反向局部残差、谱图指纹监督、候选条件化子分子式证据。它们在同一步联合优化,消融顺序不表示先训练一个任务再冻结它。
16
+
17
+ R2再研究共享原子表示的片段集合与预测谱辅助、候选差异证据。合成结构扩展单列为R3数据规模实验。外部模拟器不作为R1启动依赖。
18
+
19
+ ### 2.1 保留主干
20
+
21
+ - 谱图端:继承C03的256维、6层Transformer与最多256峰的原始输入通道。
22
+ - 分子端:继承6层边门控残差MPNN、完整分子图、原子表示和现有候选特征。
23
+ - metadata:使用实验precursor、adduct、极性,以及可用的CE、仪器与缺失标志。
24
+ - 同结构多MS:按key14识别监督身份;CE不同的谱图可共享全局结构目标,但不要求其逐峰表示相同。
25
+ - 不输入SIRIUS公式分数、公式顺序、Zodiac分数、CSI分数或参考答案相似度。
26
+
27
+ ### 2.2 候选公式条件的化学组成证据
28
+
29
+ 对每个实际候选公式F,从实验MS的10个高强度有效峰产生额外证据;原始256峰通道不变。整数元素计数、质量残差、可解释性mask及适用的损失组成进入轻量证据编码器。
30
+
31
+ 先按adduct和电荷构造离子组成,不能将中性公式直接用于所有峰,也不能把任意precursor与峰的m/z差都当作中性损失。保留多重解释和未解释状态。不支持的adduct、峰电荷或组成假设必须记录mask,保留原模型分数,不伪造注释。
32
+
33
+ 同一谱图与同一公式只构造一次证据并复用到其全部结构。MSG Mass对官方池内全部不同公式处理,不截断成10个公式;MSG Formula使用该池实际公式;CASMI只使用冻结发布中的实际Top10公式,不扩大或重检索。
34
+
35
+ 证据有两条去向:
36
+
37
+ 1. 修正公式头a_F,公式监督中每个公式只出现一次。
38
+ 2. 丰富逐峰表示p_(k,F),参与候选原子局部匹配,使同一个F下不同连接结构也能得到不同分数。
39
+
40
+ 只有第一条去向会在同公式候选中成为常量,无法单独改善异构体排序。不能把这条公式常量误称为结构证据。
41
+
42
+ ### 2.3 双向局部残差
43
+
44
+ 保留父模型的峰找原子分数,新增原子找峰的有界残差。复用同一个有效峰×原子相似度矩阵,不重复加入父模型原有局部分数。
45
+
46
+ 反向残差的系数零初始化,初始模型评分应与父模型一致。padding必须mask,长度归一化,极少峰、空mask单独处理。这是统计局部关联,不是断言每个原子都产生一个可见峰。
47
+
48
+ 化学组成证据进入局部路径时使用独立零初始化残差,避免新编码器随机输出破坏C03初始排序。R2将进一步用实际原子集合表示碎片,而不把单原子当作完整碎片。
49
+
50
+ ### 2.4 谱图指纹监督
51
+
52
+ 从原始MS全局表示预测训练参考结构的2048-bit、radius2、非手性Morgan指纹。使用cosine与连续Tanimoto目标,默认内部比重为1与0.1。
53
+
54
+ 训练标签来自训练参考结构;推理只用模型预测指纹与每个候选自身指纹,不读取参考答案。先将它作为辅助监督;指纹匹配参与最终评分时使用零初始化、可关闭的校准残差,并单独消融。
55
+
56
+ 必须核验同key14的参考指纹是否一致,遇到互变异构、标准化或身份冲突,采用明确版本化标准或mask,不能默认为所有记录的指纹相同。损失按身份均衡,避免有大量MS的结构主导监督。
57
+
58
+ ### 2.5 最终评分
59
+
60
+ 最终分数为父模型分数加反向局部、组成证据、预测指纹以及公式头修正的残差。各项标度从训练/Validation校准,不根据Test池动态拟合权重。所有新排序残差零初始化,已有分数不重复相加。
61
+
62
+ 同公式的公式先验为相同常量。结构分数和同公式竞争监督必须独立成立,不允许模型只通过公式头降低总Loss。没有硬选公式、硬选簇、按真值相似度筛候选或插入真值。
63
+
64
+ ## 3 联合目标
65
+
66
+ 总目标为继承的C03目标,加小权重的Mass条件结构CE、同公式Top-gap及指纹辅助。组成证据与双向局部路径通过原有最终排序目标和公式目标学习,不为相同logits再叠加一份CE。
67
+
68
+ ### 3.1 原始目标
69
+
70
+ 保留分子式竞争、结构身份分组的MS与分子对比、最终候选池InfoNCE,以及已有独立细粒度辅助。接入前逐项确认logits、正例集合、temperature、分母和有效查询,发现完全相同监督不能改名重算。
71
+
72
+ 批内正例由key14决定。不同MS对应同key14是多正例,不同结构即使分子式相同也不是结构正例。MS-MS与分子-分子细粒度目标保留;同公式粗粒度目标不加在主检索向量上,后续如研究则使用独立投影头。
73
+
74
+ ### 3.2 同公式条件CE
75
+
76
+ 仅对存在有效跨公式负例的Mass训练池,从最终logits取真值公式子集做条件CE,起始权重0.25。Formula和真实公式池不额外重复此项;只有一个有效公式时该项mask。
77
+
78
+ 同公式常量偏置在此CE中抵消,梯度直接约束结构竞争。必须使用最终推理分数,不使用真值作为输入改写分数。
79
+
80
+ ### 3.3 同公式Top-gap
81
+
82
+ 找当前得分最高的最多3个不同key14的同公式错误结构,优化softplus(margin + S_wrong - S_positive),起始权重0.1,margin0.2,使用原始最终分数空间。它强调Top1附近竞争,但不是增加了新的标签,必须与纯池CE消融比较。
83
+
84
+ 有放回抽样的重复副本不能占满Top3名额。原池真值缺失/不可评分时屏蔽该池的正例依赖项,不插入正例。独立标签可靠的MS与分子对比/指纹监督可继续生效。
85
+
86
+ ### 3.4 有放回和重复身份
87
+
88
+ 原始CID/SMILES资产、逐样本候选、官方排名不删除。R1新增一个可消融的损失身份均衡:对抽样结果中的同key14条目用log-mean-exp聚合logits,再在身份层做竞争。它是损失权重规范,不是物理删除候选。
89
+
90
+ 均衡策略与C03原始重复计权不同,必须保留其单独开关及对照。随机抽样仍有放回,记录抽样次数、不同key14数量、重复数和来源。模型混合难采样下的池CE不是全池似然的无偏估计,不作此宣称。
91
+
92
+ 对抽样中的身份g,明确采用以下新损失约定,避免将抽样重复与独立结构混淆:
93
+
94
+ ```text
95
+ e_g = logsumexp(S_j / tau_pool, identity(j)=g) - log(number_of_draws_with_identity_g)
96
+ L_pool = logsumexp(e_g, all_sampled_identities) - e_truth
97
+ L_cond = logsumexp(e_g, formula(g)=F_truth) - e_truth
98
+ L_gap = mean(softplus(0.2 + S_g_wrong - S_truth), Top3 unique wrong identities of F_truth)
99
+ L_new = L_C03_audited + 0.25 * mean_valid(L_cond) + 0.1 * mean_valid(L_gap)
100
+ + ramp_to_0.1 * mean_identity(L_fingerprint)
101
+ ```
102
+
103
+ `S_g`为同身份原始分数的log-mean-exp;`e_g`为带池temperature的分组logit,两者不可混用标度。`L_C03_audited`在R1中使用上述可切换的身份计权规范,但只保留一份最终池InfoNCE;matched control保持父模型计权。条件项只有在其分母确实与全池不同且存在有效正负例时才启用。
104
+
105
+ 多MS的全局对比中,MS找分子使用正确身份;分子找MS覆盖该身份的所有有效MS,不能只奖励最容易的一条。每个结构身份先聚合其MS目标,再对身份平均。具体实现和temperature沿用父模型并核对,不把原子找峰与此全局双向目标混为一谈。
106
+
107
+ 所有CE均要求有效正例和至少一个不同身份/公式的有效负例,并只按实际有效查询平均。单类查询的CE即使数值为0,也不能计入有竞争监督的查询数;元素计数、指纹和其他合格独立目标可继续训练。
108
+
109
+ ## 4 数据与采样
110
+
111
+ 三个训练来源保持当前643,587条发布:MSG Train162,974条,MSP261,644条,MS2-SAN218,969条。发布应绑定manifest与哈希;这是现有发布统计,不是本轮重新审计全服务器后的新计数。
112
+
113
+ 训练标签和负候选均排除MSG Validation、Test和CASMI的heldout key14。查询官方Train候选时实施训练监督mask,不改官方Validation/Test池。相同结构的不同MS保留;不把2D检索无法区分的立体形式做假负例。
114
+
115
+ 候选按与真值无关的稳定hash乱序,同步更新训练标签。CID、原始存储顺序、PubChem返回顺序、样本ID、原始候选位置不得作为模型输入;不能用官方候选第一项作为推理答案。训练正例是否恰好占某个位置不应影响分数,需候选置换与padding验收。
116
+
117
+ MSG每个step同时使用Mass与Formula两个视图,每视图63次负例抽样:32次模型混淆、16次化学近邻、15次随机。Mass的模型混淆配额在可用时至少16次来自同公式,保留跨公式与随机竞争。
118
+
119
+ MSP/MS2-SAN保持256有效batch批内对比,从其中16条查询做显式真实公式池竞争,每条128次负例抽样,��议64模型、32化学、32随机。只使用已验收原池,缺真值不补入。
120
+
121
+ 训练公式监督使用全部合格训练查询的不同公式候选,不只使用被选作结构显式池的16条。o_data的真实公式结构池只有一个公式时,不算多公式CE;独立公式监督必须有单独、已验收、无标签注入的质量约束候选集合。未具备集合时记录监督缺口,不把真实公式池包装成公式预测训练。
122
+
123
+ 初始模型难例来自固定C03父权重的Train-only离线评分。每1000更新生成新版难例索引,checkpoint、候选hash与规则版本绑定。旧教师embedding只用于选负例,学生GNN每次正常前向反向。化学相似度仅供训练抽样,不是推理特征。
124
+
125
+ ## 5 优化与效率
126
+
127
+ 主干和旧优化器矩从父权重恢复。新增参数创建独立优化器组,不能错误恢复不存在的旧moment;学习率从父模型恢复值的0.3倍主干、1倍新模块起步,前200步ramp,均是待Validation验证的设置。control使用同一学习率策略、更新预算及查询顺序。
128
+
129
+ 公式/结构/指纹等有效任务每步共同反向传播。分别对有效查询求均值,记录任务数量和梯度范数。指纹项总权重从0增长到0.1;不自动让Loss数值最大的项获得最大权重,也不预设PCGrad必然有利。
130
+
131
+ 原C03不同来源、Mass/Formula和批内辅助的权重必须在接入时导出,不因为将某个源的loss从求和改成均值而隐式改变训练。R1先继承这些权重,新增同公式约束显式加权;独立的视图权重搜索留作可辨认的后续对照。
132
+
133
+ 一次编码每个唯一谱图和分子图,复用原子、指纹与公式证据。静态RDKit处理、子分子式准备和模型难例挖掘离线进行。训练不能联网下载。
134
+
135
+ 使用bf16或父模型已验证的混合精度,loss与logsumexp用float32;候选分块、梯度累积保持同一有效batch和同一softmax分母。只拼接标量logits,不能每块独立CE,也不能detach需要反传的分块表示。
136
+
137
+ 先测候选原子/峰总量、数据等待、H2D、GPU计算、同步与排队,再设physical microbatch和块大小。无当前硬件测量,不承诺固定显存、吞吐或训练完成时间。拒绝为了显存更满而改变训练任务难度。
138
+
139
+ ## 6 验证和实验协议
140
+
141
+ 首轮每臂从同一个C03 2k追加2000步。主推方案与匹配control先做真实batch验收;消融使用相同查询顺序、随机种子、优化器旧状态和有效batch。随后在预先定义的Validation准则下,决定是否将胜出的方案追加到累计6000新步,必要时再扩展,不默认无限加epoch。
142
+
143
+ 选模以完整MSG Validation Mass/Formula结构Top1调和均值为主;同时要求两视图单项不超过预先设置的可容忍退化阈值,报告公式Top1、MCES和缺失率。阈值在训练前锁定,不能看到Test后改。主指标相同先比较Formula Top1和有效MCES,检查有效分母一致。
144
+
145
+ 每500更新保存并做轻量日志/梯度检查;每1000更新及pilot终点做完整Validation。MCES以固定算法、阈值、超时和结构配对缓存异步计算,不在每个训练step或每个小检查点重复跑。不得把异步结果未返回写成零或已通过选模。
146
+
147
+ MSG Validation全为正离子,不能用于证明负离子调参正确。CASMI负离子只做冻结报告。后续如需负离子开发集,必须核验其结构未被父模型训练过;从父模型已经使用的Train再划一块,只能算训练诊断,不是新的未见结构验证集。
148
+
149
+ 日志需分开记录Mass、Formula、外部真实公式池的InfoNCE、条件CE、gap、公式CE/gap/元素目标、指纹目标和既有intra-modal目标;同时记录正例概率、Top-gap违例率、负例独立身份数、同公式负例数、公式候选覆盖、有效CE比例、证据注释mask覆盖、残差幅度以及每个任务对共享主干的梯度范数。总Loss大小不作为收敛或选模的唯一标准。
150
+
151
+ 报告结构Top1/3/5/10/20/50/100/200、公式Top1至10及20/50/100/200、分母、候选覆盖、可评分率和MCES。按adduct、极性、峰数、候选量、同公式候选量和来源分层。最终优胜方案与control建议做3种子复验,未复验不宣称稳定提升。
152
+
153
+ MSG官方原始候选条目继续消耗官方名次;唯一key14排名是补充诊断。CASMI冻结1,765,420候选、467/500覆盖、无256限制、无人为补真值。固定公式Top10的重新排序不称为开放式公式生成。真正的新公式枚举与候选制备只能作为另一声明清楚的评测协议。
154
+
155
+ 冻结公式集共有468/500条包含真值公式。在每条最多10个公式、全部正常评分且集合不变时,Formula Recall@10由覆盖决定,仍为93.6%;重新排序只能改善更小K。结构Recall任意K也不能超过原池467/500=93.4%。不能把这两类覆盖问题用额外Loss或真值补入“修复”。
156
+
157
+ ## 7 后续创新与扩展
158
+
159
+ R2让分子图共享原子表示生成小规模片段集合,借鉴GLACIER的共享计算和ICEBERG的碎裂证据;用已核验Train-safe教师/启发式片段做弱监督,逐步降低弱标签权重,正结构对自己的实验MS重建。错误候选参与判别排序,不要求每个负结构重建同一实验MS。
160
+
161
+ 候选差异研究采用同公式稀疏近邻或紧致微簇,只为寻找竞争候选的差异原子、连接位点及可区分碎片。所有候选保留直接分数,单例残差为0,不做完整N平方相似度矩阵,不把真值簇提前告知模型。
162
+
163
+ 具体假设是:共享证据解释共同骨架,差异证据判断候选i相对近邻j多解释了哪些峰/损失。用共享网络的D(x,i,j)-D(x,j,i)形成反对称配对残差,再按有效近邻数归一化并有界加回直接分数。近邻只由候选自身结构建立,大小和阈值只在Validation确定;该机制是待实现消融,不当作已知有效或已经证明新颖。
164
+
165
+ R3才扩展Train-safe合成结构数据。教师的MSG安全不能自动外推为CASMI安全;支持的极性/adduct分别验收,缺CE采用缺失标志或与候选身份无关的先验,不借参考结构挑选最佳CE。结构扩展与增大训练预算分别配对控制。
166
+
167
+ 创新主张是待验证的“竞争候选差异驱动的化学证据选择与共享计算”,不是声称首次使用骨架、指纹、对比学习或预测谱。
168
+
169
+ ## 8 当前就绪程度
170
+
171
+ 已有独立辅助原型:同公式Loss/采样、零初始化反向局部、指纹头;历史24项CPU单元测试通过。这不是正式训练器验收。
172
+
173
+ R1还需:Train-only模型难例索引、子分子式证据适配与离线缓存、身份均衡损失接入、新参数优化器组、真实学生GPU梯度和断点恢复验收。本轮不启动训练、不读取服务器实时状态、不修改任何现有服务。配置检查通过不表示网络已经训练可运行。
174
+
175
+ ## 9 证据入口
176
+
177
+ - [C03逐样本诊断](../../analysis_outputs/c03_2k_badcase_20261109/diagnosis.json)
178
+ - [四类方法对比与来源](../../analysis_outputs/c03_four_model_review_20261109/comparison.json)
179
+ - [MIST-CF方法](https://arxiv.org/html/2307.08240v1)
180
+ - [FLARE作者局部Loss](https://huggingface.co/spaces/HassounLab/FLARE/blob/main/flare/utils/loss.py)
181
+ - [GLACIER方法](https://arxiv.org/html/2606.29161v1)
182
+ - [v1.5审计及数据条件](https://arxiv.org/html/2606.19624v2)
code/snapshot/root/code/ceir_r1_20261109/ablation_matrix.json ADDED
The diff for this file is too large to render. See raw diff
 
code/snapshot/root/code/ceir_r1_20261109/acceptance_ceir.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real Train GPU acceptance; temporary updates are never continuation updates."""
2
+ import argparse
3
+ import gc
4
+ import json
5
+ from pathlib import Path
6
+ import time
7
+ import traceback
8
+ from runtime_ceir import *
9
+
10
+
11
+ def data_markers_complete():
12
+ names=['train_composition_ready.json','validation_composition_ready.json','teacher_ready.json','fingerprint_targets.json','ASSET_MANIFEST.json']
13
+ return all((CACHE/name).exists() for name in names)
14
+
15
+
16
+ def batch_index(plans):
17
+ return next(i for i,(_,_,p) in enumerate(plans) if len(p['odata'])==256 and len(p['msg'])==32)
18
+
19
+
20
+ def test_arm(arm,index,probe=False):
21
+ import torch
22
+ from dataclasses import replace
23
+ from data_ceir import Dataset
24
+ from model_ceir import make_model_optimizer
25
+ from objectives_ceir import train_step,amp
26
+ from prepare_ceir import load_teacher
27
+ from validation_ceir import evaluate
28
+ directory=run_dir(arm);plans=json.loads((CACHE/'workload.json').read_text())['plans']
29
+ batch=Dataset([plans[index]],arm)[0]
30
+ if len(batch['rows'])!=288 or len({r['record_id'] for r in batch['rows']})!=288:raise RuntimeError('Not a real complete logical batch')
31
+ ready_name='early_GPU_probe.json' if probe else 'acceptance.json'
32
+ with gpu_work(directory,'real_GPU_acceptance'):
33
+ model,opt,progress,parent_lr=make_model_optimizer(arm)
34
+ source=source_state();initial_steps=[float(s['step']) for s in opt.state.values() if 'step' in s]
35
+ old_parameters=len(opt.param_groups[0]['params']);registered=sum(p.numel() for p in model.parameters())
36
+ q=next(p['query'] for row in batch['rows'] for p in row['pools']);model.eval()
37
+ parent=load_teacher();parent.graph_chunk=model.graph_chunk;parent.local_chunk=model.local_chunk
38
+ with torch.inference_mode(),amp():
39
+ expected=parent.encode_batch([q])[0][0].base.float()
40
+ actual=model.encode_batch([q])[0][0].base.float()
41
+ error=(expected-actual).abs().max().item()
42
+ if error>3e-4:raise RuntimeError('Initial C03 logit parity failed: '+str(error))
43
+ perm=list(reversed(range(len(q.candidates))))
44
+ shuffled=replace(q,candidates=tuple(q.candidates[i] for i in perm))
45
+ perm_scores=model.encode_batch([shuffled])[0][0].base.float()
46
+ permutation_error=(perm_scores-actual[perm]).abs().max().item()
47
+ if permutation_error>3e-4:raise RuntimeError('Candidate permutation changed scores')
48
+ del parent;gc.collect();torch.cuda.empty_cache();restore_rng(source)
49
+ model.train();torch.cuda.reset_peak_memory_stats()
50
+ metrics=[]
51
+ # Test optimizer and auxiliary gradients without advancing the formal run.
52
+ for k in range(3 if arm=='main' else 1):
53
+ metrics.append(train_step(model,opt,batch,SOURCE_UPDATE+k,True))
54
+ if metrics[-1]['backbone_gradient_norm']<=0:raise RuntimeError('No encoder gradient')
55
+ if arm=='main':
56
+ if metrics[-1]['fingerprint_gradient_norm']<=0 or metrics[-1]['composition_gradient_norm']<=0:
57
+ raise RuntimeError('Missing joint new-head gradient after zero-gate warm start')
58
+ if not metrics[-1]['gap_valid']:raise RuntimeError('No actual same-formula competition tested')
59
+ after_steps=[float(s['step']) for p,s in opt.state.items() if 'step' in s and any(p is a for a in opt.param_groups[0]['params'])]
60
+ if not after_steps or max(after_steps)<=max(initial_steps):raise RuntimeError('Old AdamW state did not continue')
61
+ temporary=directory/'acceptance_temporary.pt'
62
+ temp_progress=dict(progress,update=SOURCE_UPDATE+len(metrics),new_updates=len(metrics))
63
+ checkpoint(temporary,model,opt,temp_progress,bind())
64
+ saved_rng=dict(torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all(),
65
+ numpy_rng=__import__('numpy').random.get_state(),python_rng=random.getstate())
66
+ next_before=train_step(model,opt,batch,temp_progress['update'],False)['loss']
67
+ del model,opt;gc.collect();torch.cuda.empty_cache()
68
+ model,opt,reloaded,_=make_model_optimizer(arm,temporary)
69
+ next_after=train_step(model,opt,batch,reloaded['update'],False)['loss']
70
+ resume_error=abs(next_before-next_after)
71
+ if resume_error>3e-4:raise RuntimeError('RNG/optimizer resume loss mismatch: '+str(resume_error))
72
+ result=dict(complete=True,binding=bind(),arm=arm,formal_updates=0,temporary_test_updates=len(metrics),
73
+ source_update=SOURCE_UPDATE,target_update=TARGET_UPDATE,real_queries=288,pool_views=metrics[0]['pool_valid'],
74
+ source_parent_sha256=PLAN['parent']['sha256'],initial_logit_max_error=error,permutation_max_error=permutation_error,
75
+ old_optimizer_registered_parameters=old_parameters,old_optimizer_state_entries=len(initial_steps),
76
+ registered_parameters=registered,resume_loss_abs_error=resume_error,metrics=metrics,
77
+ peak_allocated_mib=max(m['peak_allocated_mib'] for m in metrics),
78
+ full_preparation_verified=not probe,Validation_probe_complete=False,unix_time=time.time())
79
+ del model,opt;gc.collect();torch.cuda.empty_cache()
80
+ if not probe:
81
+ # The same scoring path must work on unchanged official pools as well.
82
+ with gpu_work(directory,'Validation_entrypoint_acceptance'):
83
+ model,opt,_,_=make_model_optimizer(arm);del opt
84
+ val=evaluate(model,arm,SOURCE_UPDATE,maximum_targets=1)
85
+ result['Validation_probe_complete']=all(val[k]['spectra']>0 for k in ('mass','formula'))
86
+ del model;gc.collect();torch.cuda.empty_cache()
87
+ if not result['Validation_probe_complete']:raise RuntimeError('Validation adapter acceptance failed')
88
+ save(directory/ready_name,result)
89
+ log_event(OUT/'acceptance_events.jsonl',dict(event='GPU_acceptance',arm=arm,probe=probe,peak_mib=result['peak_allocated_mib'],resume_error=resume_error))
90
+ print(json.dumps(dict(arm=arm,complete=True,probe=probe,parameters=registered,peak_mib=result['peak_allocated_mib'],parent_parity=error,resume_error=resume_error)),flush=True)
91
+
92
+
93
+ def run(probe=False,only_arm=None):
94
+ if not probe and not data_markers_complete():raise RuntimeError('Full pilot data preparation is incomplete')
95
+ setup_gpu();plans=json.loads((CACHE/'workload.json').read_text())['plans'];index=batch_index(plans)
96
+ for arm in ([only_arm] if only_arm else ('control','main')):test_arm(arm,index,probe)
97
+ if probe:return
98
+ accepted=[json.loads((run_dir(arm)/'acceptance.json').read_text()) for arm in ('main','control')]
99
+ binding=bind()
100
+ if any(x['binding']!=binding or not x['complete'] or not x['Validation_probe_complete'] for x in accepted):raise RuntimeError('Acceptance/code binding mismatch')
101
+ save(OUT/'READY.json',dict(complete=True,binding=binding,real_GPU_acceptance_complete=True,
102
+ all_R1_pilot_data_ready=True,formal_updates=0,unix_time=time.time()))
103
+
104
+
105
+ if __name__=='__main__':
106
+ p=argparse.ArgumentParser();p.add_argument('--early-probe',action='store_true');p.add_argument('--arm',choices=['main','control']);a=p.parse_args()
107
+ if a.arm and not a.early_probe:raise RuntimeError('One-arm execution is only a provisional probe')
108
+ try:run(a.early_probe,a.arm)
109
+ except Exception:
110
+ save(OUT/'GPU_ACCEPTANCE_FAILURE.json',dict(traceback=traceback.format_exc(),unix_time=time.time(),probe=a.early_probe));raise
code/snapshot/root/code/ceir_r1_20261109/comparison_ceir.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validation-only, matched-arm readout. Does not start or extend training."""
2
+ import gzip
3
+ import json
4
+ from pathlib import Path
5
+ import statistics
6
+ import time
7
+
8
+
9
+ def load(path):
10
+ if not path.exists():return None
11
+ if path.suffix=='.gz':
12
+ with gzip.open(path,'rt') as f:return json.load(f)
13
+ return json.loads(path.read_text())
14
+
15
+
16
+ def paired_mces(main,control):
17
+ """Exactly the same valid spectrum/view pairs, never fill missing as zero."""
18
+ a=load(main/'MCES_per_spectrum.json.gz');b=load(control/'MCES_per_spectrum.json.gz')
19
+ if a is None or b is None:return None
20
+ def index(rows):
21
+ out={(r['identifier'],r['view']):r['distance'] for r in rows}
22
+ if len(out)!=len(rows):raise RuntimeError('Duplicate MCES spectrum/view identity')
23
+ return out
24
+ aa,bb=index(a),index(b)
25
+ if aa.keys()!=bb.keys():raise RuntimeError('Unmatched Validation MCES denominators')
26
+ results={}
27
+ for view in ('mass','formula'):
28
+ keys=[key for key in aa if key[1]==view]
29
+ common=[key for key in keys if aa[key] is not None and bb[key] is not None]
30
+ ma=statistics.mean(aa[k] for k in common) if common else None
31
+ mb=statistics.mean(bb[k] for k in common) if common else None
32
+ results[view]=dict(denominator=len(keys),common_valid=len(common),main_common_mean=ma,control_common_mean=mb,
33
+ main_minus_control=ma-mb if common else None,
34
+ main_missing=sum(aa[k] is None for k in keys),control_missing=sum(bb[k] is None for k in keys))
35
+ return results
36
+
37
+
38
+ def build(out):
39
+ out=Path(out);pairs={};candidates=[];all_ready=True
40
+ for update in (3000,4000):
41
+ paths={arm:out/arm/('validation_update_%06d'%update) for arm in ('main','control')}
42
+ metrics={arm:load(path/'metrics.json') for arm,path in paths.items()}
43
+ if not all(metrics.values()):all_ready=False;continue
44
+ main,control=metrics['main'],metrics['control']
45
+ if main['binding']['runtime']!=control['binding']['runtime']:
46
+ raise RuntimeError('Comparison code/data bindings do not match')
47
+ for view in ('mass','formula'):
48
+ if main[view]['spectra']!=19429 or control[view]['spectra']!=19429:
49
+ raise RuntimeError('Not a complete matched Validation comparison')
50
+ structure={view:{k:100*(main[view]['structure'][k]['micro']-control[view]['structure'][k]['micro'])
51
+ for k in main[view]['structure']} for view in ('mass','formula')}
52
+ formula={k:100*(main['mass']['formula'][k]['micro']-control['mass']['formula'][k]['micro'])
53
+ for k in main['mass']['formula']}
54
+ harmonics={}
55
+ for arm,m in metrics.items():
56
+ a=m['mass']['structure']['1']['micro'];b=m['formula']['structure']['1']['micro']
57
+ harmonics[arm]=2*a*b/max(a+b,1e-12)
58
+ mces=paired_mces(paths['main'],paths['control'])
59
+ if mces is not None and any(r['denominator']!=19429 for r in mces.values()):
60
+ raise RuntimeError('Incomplete paired MCES readout; do not compare a truncated subset')
61
+ guardrails=dict(
62
+ both_view_structure_Top1=all(structure[v]['1']>=-.5 for v in ('mass','formula')),
63
+ mass_pool_formula_Top1=formula['1']>=-1.,
64
+ paired_MCES=None if mces is None else all(r['main_minus_control'] is not None and r['main_minus_control']<=.2 for r in mces.values()),
65
+ no_additional_MCES_missing=None if mces is None else all(r['main_missing']<=r['control_missing'] for r in mces.values()))
66
+ passed=all(value is True for value in guardrails.values())
67
+ if passed and harmonics['main']>harmonics['control']:candidates.append((harmonics['main'],update))
68
+ if mces is None:all_ready=False
69
+ pairs[str(update)]=dict(structure_delta_pp=structure,mass_pool_formula_delta_pp=formula,paired_MCES=mces,
70
+ harmonic_Top1=harmonics,guardrails=guardrails,all_guardrails_passed=passed,
71
+ metrics_files={arm:str(paths[arm]/'metrics.json') for arm in paths})
72
+ best=max(candidates)[1] if candidates and all_ready else None
73
+ return dict(protocol='MSG_full_Validation_only_no_Test_or_CASMI_selection',complete=all_ready,
74
+ pairs=pairs,recommended_main_checkpoint_update=best,
75
+ recommendation='eligible_main_improvement_on_this_seed' if best is not None else 'not_yet_demonstrated_or_pending',
76
+ additional_training_authorized=False,automatic_promotion=False,
77
+ limitations=['single_seed_not_a_significance_claim','sampled_training_pool_not_unbiased_full_pool_likelihood',
78
+ 'formula_metric_is_official_Mass_pool_ranking_not_open_formula_generation'],unix_time=time.time())
79
+
80
+
81
+ def write(out):
82
+ out=Path(out);result=build(out)
83
+ path=out/'MATCHED_VALIDATION_COMPARISON.json';temp=path.with_suffix('.tmp')
84
+ temp.write_text(json.dumps(result,indent=2,allow_nan=False)+'\n');temp.replace(path)
85
+ lines=['# CEIR R1 matched Validation comparison','',
86
+ 'Same source C03 update 2000, query schedule and 2000 new-update budget. No Test/CASMI selection.',
87
+ '', '| Cumulative update | Mass Top1 delta (pp) | Formula Top1 delta (pp) | Mass-pool formula Top1 delta (pp) | Guardrails |',
88
+ '| --- | ---: | ---: | ---: | --- |']
89
+ for update,p in result['pairs'].items():
90
+ lines.append('| %s | %.3f | %.3f | %.3f | %s |'%(update,p['structure_delta_pp']['mass']['1'],
91
+ p['structure_delta_pp']['formula']['1'],p['mass_pool_formula_delta_pp']['1'],
92
+ 'pass' if p['all_guardrails_passed'] else ('pending MCES' if p['paired_MCES'] is None else 'not all passed')))
93
+ lines+=['','Status: '+result['recommendation']+'.',
94
+ 'Full Top-K, formula Top-K, coverage, macro averages and metadata strata remain in each metrics.json.',
95
+ 'MCES compares exactly the common valid spectrum/view pairs; missing values are not zero. No automatic extra SGD or promotion.','']
96
+ target=out/'MATCHED_VALIDATION_COMPARISON.md';temporary=target.with_suffix('.tmp')
97
+ temporary.write_text('\n'.join(lines));temporary.replace(target)
98
+ return result
code/snapshot/root/code/ceir_r1_20261109/data_ceir.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read-only original data, exact parent MS order, separately seeded sampling."""
2
+ from collections import Counter
3
+ from dataclasses import replace
4
+ import json
5
+ import hashlib
6
+ import random
7
+ import sqlite3
8
+ import time
9
+
10
+ from runtime_ceir import *
11
+ from data09 import Reader,loads
12
+ from prepare_ceir import get_pool,entry_identity,entry_molecule
13
+ from evidence_ceir import query_key
14
+ from sampling_ledger_ceir import SamplingLedger
15
+
16
+
17
+ class CEIRReader(Reader):
18
+ def __init__(self,arm):
19
+ super().__init__();self.arm=arm
20
+ self.hard=readonly(CACHE/'teacher_parent.sqlite') if arm=='main' else None
21
+ self.refreshed=None
22
+ self.fp_valid=json.loads((CACHE/'fingerprint_targets.json').read_text())['valid']
23
+ self.pool_hashes={}
24
+ self.ledger=SamplingLedger(run_dir(arm)/'sampling_decisions.sqlite',
25
+ dict(parent_sha256=PLAN['parent']['sha256'],workload_sha256=json.loads((CACHE/'workload.json').read_text())['binding']['sha256'],arm=arm)) if arm=='main' else None
26
+
27
+ def teacher_body(self,rid,kind,version):
28
+ if version==SOURCE_UPDATE:db=self.hard
29
+ elif version==3000:
30
+ fresh=CACHE/'teacher_003000.sqlite'
31
+ if self.refreshed is None and fresh.exists():
32
+ candidate=readonly(fresh)
33
+ if candidate.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='hard_fp32'").fetchone():self.refreshed=candidate
34
+ else:candidate.close()
35
+ db=self.refreshed
36
+ else:raise RuntimeError('Unknown teacher version')
37
+ found=db.execute('SELECT body FROM hard_fp32 WHERE record_id=? AND kind=?',(rid,kind)).fetchone() if db is not None else None
38
+ return found[0] if found is not None else None
39
+
40
+ def sample_ceir(self,rid,seed,explicit=False,maximum_teacher_update=SOURCE_UPDATE):
41
+ row=loads(self.db.execute('SELECT body FROM samples WHERE record_id=?',(rid,)).fetchone()[0])
42
+ row['ref']=self.molecule(row['graph_hash']);row['pools']=[]
43
+ row['fingerprint_eligible']=self.fp_valid.get(row['identity'],False)
44
+ rng=random.Random(seed)
45
+ kinds=['mass','formula'] if row['source']=='MSG_Train' else (['odata'] if explicit and row['view']['pool_infonce_eligible'] else [])
46
+ if row['source']=='MSG_Train':row['formulas']=tuple(self.official(row['target'],'mass')['formula_classes'])
47
+ else:row['formulas']=tuple(row['view']['formulas'])
48
+ for kind in kinds:
49
+ group=dict(kind=kind,target=row['target']) if kind!='odata' else dict(kind=kind,path=row['view']['pool_path'],sha256=row['view']['pool_sha256'])
50
+ pool,entries,indices=get_pool(self,group)
51
+ if kind=='odata':indices=pool['safe_mass_order'][row['view']['mass_order_start']:row['view']['mass_order_stop']]
52
+ positives=[j for j in indices if entry_identity(entries[j])==row['identity']]
53
+ negatives=[j for j in indices if entry_identity(entries[j])!=row['identity']]
54
+ if not positives or not negatives:continue
55
+ budget=128 if kind=='odata' else 63;positive=rng.choice(positives)
56
+ source_counts=Counter()
57
+ teacher_update=None
58
+ if self.arm=='control':
59
+ chosen=rng.choices(negatives,k=budget);source_counts['random']=budget
60
+ else:
61
+ def choose():
62
+ newer=self.teacher_body(rid,kind,3000) if maximum_teacher_update>=3000 else None
63
+ return (3000,newer) if newer is not None else (SOURCE_UPDATE,self.teacher_body(rid,kind,SOURCE_UPDATE))
64
+ version,body=self.ledger.select(rid,kind,seed,lambda v:self.teacher_body(rid,kind,v),choose)
65
+ hard=json.loads(body)
66
+ if version>maximum_teacher_update:raise RuntimeError('Teacher checkpoint is from a future training update')
67
+ if hard['source_update']!=version:raise RuntimeError('Pinned teacher version disagrees with its row')
68
+ teacher_update=hard['source_update']
69
+ if hard['parent_sha256']!=PLAN['parent']['sha256'] or hard['query_key']!=query_key(row['query']):raise RuntimeError('Teacher binding drift')
70
+ if kind=='odata' and hard['pool_sha256']!=row['view']['pool_sha256']:raise RuntimeError('Teacher pool hash mismatch')
71
+ if kind!='odata':
72
+ name=(row['target'],kind)
73
+ if name not in self.pool_hashes:self.pool_hashes[name]=hashlib.sha256(json.dumps(pool,sort_keys=True,separators=(',',':')).encode()).hexdigest()
74
+ if hard['pool_sha256']!=self.pool_hashes[name]:raise RuntimeError('Official Train teacher-pool hash drift')
75
+ nset=set(negatives)
76
+ top=hard['top'];same=[j for _,_,j in top['same_scores'] if j in nset]
77
+ global_=[j for _,_,j in top['global_scores'] if j in nset]
78
+ chem=[j for _,_,j in top['chemical'] if j in nset]
79
+ model_n,chem_n,random_n=(64,32,32) if kind=='odata' else (32,16,15)
80
+ if not global_:raise RuntimeError('Prepared teacher has no valid wrong candidate')
81
+ same_n=model_n//2 if same else 0;chosen=[]
82
+ for values,n,label in [(same,same_n,'model_same_formula'),(global_,model_n-same_n,'model_global'),(chem,chem_n,'chemical'),(negatives,random_n,'random')]:
83
+ if n and not values:raise RuntimeError('Missing prepared '+label+' bank')
84
+ chosen.extend(rng.choices(values,k=n));source_counts[label]+=n
85
+ selected=[positive,*chosen]
86
+ # The truth's storage position is never an input feature.
87
+ permutation_rng=random.Random(seed+7919+(0 if kind=='mass' else 1))
88
+ permutation_rng.shuffle(selected)
89
+ mols=tuple(entry_molecule(self,entries[j]) for j in selected)
90
+ if any(m.identity in self.forbidden for m in mols):raise RuntimeError('Heldout negative asset')
91
+ truth_positions=[i for i,m in enumerate(mols) if m.identity==row['identity']]
92
+ if len(truth_positions)!=1:raise RuntimeError('False negative or missing selected positive')
93
+ fs=tuple(pool['formula_classes']) if kind!='odata' else tuple(sorted({m.formula for m in mols}))
94
+ q=replace(row['query'],candidates=mols,formula_candidates=fs,candidate_view='msg_'+kind if kind!='odata' else 'odata_oracle')
95
+ row['pools'].append(dict(kind=kind,query=q,truth_identity=row['identity'],truth_formula=row['formula'],positive_index=truth_positions[0],
96
+ negative_draws=len(chosen),unique_negative_key14=len({entry_identity(entries[j]) for j in chosen}),source_counts=dict(source_counts),
97
+ teacher_source_update=teacher_update,
98
+ quality_eligible=bool(row['mass_ok']),reference_injected=False))
99
+ row['query']=replace(row['query'],formula_candidates=row['formulas'])
100
+ return row
101
+
102
+
103
+ class Dataset:
104
+ def __init__(self,plans,arm,start_update=SOURCE_UPDATE):self.plans=plans;self.arm=arm;self.reader=None;self.start_update=start_update
105
+ def __len__(self):return len(self.plans)
106
+ def __getitem__(self,index):
107
+ if self.reader is None:self.reader=CEIRReader(self.arm)
108
+ epoch,step,groups=self.plans[index];started=time.monotonic();rows=[]
109
+ for source,ids in groups.items():
110
+ for j,rid in enumerate(ids):
111
+ seed=SEED+epoch*100000000+step*10000+j+(1000000 if source=='msg' else 0)
112
+ rows.append(self.reader.sample_ceir(rid,seed,source=='odata' and j<16,self.start_update+index))
113
+ if self.reader.ledger is not None:self.reader.ledger.commit()
114
+ return dict(epoch=epoch,step=step,rows=rows,data_seconds=time.monotonic()-started,
115
+ sampler_ledger_uuid=self.reader.ledger.metadata['ledger_uuid'] if self.reader.ledger is not None else None)
code/snapshot/root/code/ceir_r1_20261109/debug_parity_ceir.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read-only real Train score-component probe; no optimizer update."""
2
+ import json
3
+ import torch
4
+ from runtime_ceir import *
5
+ from data_ceir import Dataset
6
+ from acceptance_ceir import batch_index
7
+ from model_ceir import make_model_optimizer
8
+ from prepare_ceir import load_teacher
9
+ from objectives_ceir import amp
10
+
11
+
12
+ def main():
13
+ setup_gpu();plans=json.loads((CACHE/'workload.json').read_text())['plans']
14
+ batch=Dataset([plans[batch_index(plans)]],'control')[0]
15
+ q=next(p['query'] for r in batch['rows'] for p in r['pools'])
16
+ with gpu_work(OUT,'debug_initial_score_components'),torch.inference_mode(),amp():
17
+ model,opt,_,_=make_model_optimizer('main');del opt;model.eval()
18
+ parent=load_teacher();parent.graph_chunk=32;parent.local_chunk=32
19
+ a=model.encode_batch([q])[0][0];b=parent.encode_batch([q])[0][0]
20
+ fwd,rev=model.local_both(a.peaks,a.atoms)
21
+ parent_local=parent.local_scores(b.peaks,b.atoms)
22
+ original_local=model.local_scores(a.peaks,a.atoms)
23
+ condition,joint,_=model.conditioned(a.q,q,[m.formula for m in q.candidates],a.z_molecules,a.formula_scores)
24
+ residual=model.local_weight*(fwd+.3*model.ceir.reverse_gate.tanh()*rev)
25
+ data=dict(peaks=(a.peaks-b.peaks).abs().max().item(),q=(a.q-b.q).abs().max().item(),
26
+ zm=(a.z_molecules-b.z_molecules).abs().max().item(),formulas=(a.formula_scores-b.formula_scores).abs().max().item(),
27
+ local_forward=(fwd-parent_local).abs().max().item(),local_same_model=(fwd-original_local).abs().max().item(),
28
+ base=(a.base-b.base).abs().max().item(),base_manual=(a.base-(joint+model.local_weight*original_local)).abs().max().item(),
29
+ local_weight=str(model.local_weight),fwd_dtype=str(fwd.dtype),reverse_dtype=str(rev.dtype),
30
+ residual_dtype=str(residual.dtype),joint_dtype=str(joint.dtype),
31
+ gates={n:getattr(model.ceir,n).item() for n in ('reverse_gate','fingerprint_gate','composition_gate','formula_gate')})
32
+ save(OUT/'initial_parity_debug.json',data);print(json.dumps(data),flush=True)
33
+
34
+
35
+ if __name__=='__main__':main()
code/snapshot/root/code/ceir_r1_20261109/evidence_ceir.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline composition evidence: atom-conserving ion-budget mass assignments.
2
+
3
+ No model score, CID order, reference identity/formula or reference similarity is
4
+ an argument. Bounded annotations may be ambiguous/unassigned. Not a full
5
+ fragmentation/rearrangement simulator or a reproduction of MIST-CF.
6
+ """
7
+ from functools import lru_cache
8
+ import hashlib
9
+ import itertools
10
+ import json
11
+ import math
12
+ import re
13
+ import sqlite3
14
+ import zlib
15
+
16
+ import numpy as np
17
+ from rdkit import Chem
18
+
19
+ ELEMENTS=('C','H','N','O','P','S','F','Cl','Br','I','B','Si','Na')
20
+ PT=Chem.GetPeriodicTable()
21
+ MASSES=np.array([PT.GetMostCommonIsotopeMass(e) for e in ELEMENTS],dtype=np.float64)
22
+ ELECTRON=.000548579909065
23
+ RULE='ceir_ion_budget_v1_10ppm_top10_2ambiguities_max300k'
24
+ STRONG_PEAKS=10
25
+ TOKENS=20
26
+ WIDTH=32
27
+ ADDUCT={
28
+ '[M+H]+':({'H':1},1),'[M-H]-':({'H':-1},-1),
29
+ '[M+Na]+':({'Na':1},1),'[M+NH4]+':({'N':1,'H':4},1),
30
+ '[M+Cl]-':({'Cl':1},-1),'[M+FA-H]-':({'C':1,'H':1,'O':2},-1),
31
+ '[M+2H]2+':({'H':2},2),'[M-2H]2-':({'H':-2},-2)}
32
+
33
+
34
+ def counts(formula):
35
+ tokens=re.findall(r'([A-Z][a-z]?)(\d*)',formula)
36
+ if ''.join(a+b for a,b in tokens)!=formula or not tokens:raise ValueError('Invalid formula')
37
+ result=np.zeros(len(ELEMENTS),dtype=np.int16);seen=set()
38
+ for element,n in tokens:
39
+ if element not in ELEMENTS or element in seen:raise ValueError('Unsupported/repeated element')
40
+ seen.add(element);number=int(n or 1)
41
+ if number<1 or number>1000:raise ValueError('Unsupported count')
42
+ result[ELEMENTS.index(element)]=number
43
+ return result
44
+
45
+
46
+ def canonical_peaks(query):
47
+ return sorted(sorted(query.peaks,key=lambda p:(-p[1],p[0]))[:256])
48
+
49
+
50
+ def query_key(query):
51
+ data=[list(map(list,canonical_peaks(query))),query.precursor_mz,query.adduct,
52
+ query.collision_energy,query.instrument]
53
+ return hashlib.sha256(json.dumps(data,separators=(',',':'),allow_nan=False).encode()).hexdigest()
54
+
55
+
56
+ @lru_cache(maxsize=32)
57
+ def library(formula,adduct):
58
+ try:
59
+ parent=counts(formula);delta,charge=ADDUCT[adduct]
60
+ for element,n in delta.items():parent[ELEMENTS.index(element)]+=n
61
+ if (parent<0).any():return None,'invalid_ion_budget'
62
+ axes=[i for i,n in enumerate(parent) if n and ELEMENTS[i]!='H']
63
+ size=math.prod(int(parent[i])+1 for i in axes)
64
+ if size>300000:return None,'enumeration_budget_mask'
65
+ nonhydrogen=np.zeros((size,len(parent)),dtype=np.int16)
66
+ if axes:
67
+ grid=np.array(list(itertools.product(*(range(int(parent[i])+1) for i in axes))),dtype=np.int16)
68
+ nonhydrogen[:,axes]=grid
69
+ base=nonhydrogen@MASSES
70
+ return (parent,charge,nonhydrogen,base),'available'
71
+ except (ValueError,KeyError):return None,'unsupported_formula_or_adduct'
72
+
73
+
74
+ def annotate(query,formula):
75
+ features=np.zeros((TOKENS,WIDTH),dtype=np.float32)
76
+ valid=np.zeros(TOKENS,dtype=bool);indices=np.zeros(TOKENS,dtype=np.int16)
77
+ built,reason=library(formula,query.adduct)
78
+ peaks=canonical_peaks(query)
79
+ chosen=sorted(range(len(peaks)),key=lambda i:(-peaks[i][1],peaks[i][0]))[:STRONG_PEAKS]
80
+ if built is None:return dict(features=features,valid=valid,indices=indices,available=False,reason=reason,matched=0,total=len(chosen))
81
+ parent,z,nonH,base=built;hidx=ELEMENTS.index('H');matched=0
82
+ maximum=max(p[1] for p in peaks)
83
+ for order,pi in enumerate(chosen):
84
+ mz,intensity=peaks[pi];options=[]
85
+ for absolute_charge in range(1,abs(z)+1):
86
+ fz=absolute_charge*(1 if z>0 else -1)
87
+ target=mz*abs(fz)+fz*ELECTRON
88
+ hydrogen=np.rint((target-base)/MASSES[hidx]).astype(np.int32)
89
+ theoretical=(base+hydrogen*MASSES[hidx]-fz*ELECTRON)/abs(fz)
90
+ ppm=(theoretical-mz)/mz*1e6
91
+ candidates=np.flatnonzero((hydrogen>=0)&(hydrogen<=parent[hidx])&(np.abs(ppm)<=10))
92
+ for j in sorted(candidates,key=lambda k:(abs(ppm[k]),int(k)))[:2]:
93
+ vec=nonH[j].copy();vec[hidx]=hydrogen[j]
94
+ if vec.sum():options.append((abs(float(ppm[j])),float(ppm[j]),fz,vec))
95
+ options.sort(key=lambda x:(x[0],x[2],tuple(x[3])))
96
+ matched+=bool(options)
97
+ for alternative in range(2):
98
+ ti=order*2+alternative;indices[ti]=pi
99
+ if alternative and len(options)<2:continue
100
+ valid[ti]=True
101
+ if options:
102
+ _,ppm,fz,vec=options[alternative]
103
+ features[ti,:13]=np.log1p(vec)
104
+ features[ti,13:26]=np.log1p(parent-vec)
105
+ tail=[ppm/10,math.sqrt(intensity/maximum),mz/1000,fz/2,1.,math.log1p(len(options))]
106
+ else:
107
+ features[ti,13:26]=np.log1p(parent)
108
+ tail=[0.,math.sqrt(intensity/maximum),mz/1000,z/2,0.,0.]
109
+ features[ti,26:]=tail
110
+ return dict(features=features,valid=valid,indices=indices,available=True,reason=reason,matched=matched,total=len(chosen))
111
+
112
+
113
+ def encode(result):
114
+ # A compact versioned wire representation, no pickle or reference labels.
115
+ obj=dict(features=result['features'].astype(np.float16).tobytes().hex(),
116
+ valid=result['valid'].astype(np.uint8).tolist(),indices=result['indices'].tolist(),
117
+ available=result['available'],reason=result['reason'],matched=result['matched'],total=result['total'])
118
+ return zlib.compress(json.dumps(obj,separators=(',',':')).encode(),1)
119
+
120
+
121
+ def decode(blob):
122
+ obj=json.loads(zlib.decompress(blob));obj['features']=np.frombuffer(bytes.fromhex(obj['features']),dtype=np.float16).reshape(TOKENS,WIDTH).astype(np.float32)
123
+ obj['valid']=np.asarray(obj['valid'],dtype=bool);obj['indices']=np.asarray(obj['indices'],dtype=np.int64)
124
+ return obj
125
+
126
+
127
+ class EvidenceStore:
128
+ def __init__(self,paths):
129
+ self.dbs=[sqlite3.connect('file:'+str(p)+'?mode=ro',uri=True,timeout=60) for p in paths]
130
+ for db in self.dbs:db.execute('PRAGMA query_only=ON')
131
+
132
+ @lru_cache(maxsize=2048)
133
+ def get(self,key,formula):
134
+ for db in self.dbs:
135
+ row=db.execute('SELECT body FROM evidence WHERE query_key=? AND formula=?',(key,formula)).fetchone()
136
+ if row:return decode(row[0])
137
+ raise RuntimeError('Missing offline composition evidence: '+key+' '+formula)
138
+
139
+ def query(self,query):
140
+ key=query_key(query)
141
+ return [self.get(key,f) for f in query.formula_candidates]
code/snapshot/root/code/ceir_r1_20261109/mces_ceir.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Post-hoc Validation MCES only, fixed protocol and resumable pair cache."""
2
+ from concurrent.futures import ProcessPoolExecutor
3
+ import gzip
4
+ import hashlib
5
+ import importlib.metadata
6
+ import json
7
+ import math
8
+ from pathlib import Path
9
+ import sqlite3
10
+ import statistics
11
+ import time
12
+ import os
13
+
14
+ OUT=Path(os.environ.get('CEIR_OUTPUT','/root/xj/SpecPartition-MS/runs/ceir_r1_20261109'))
15
+ CACHE=OUT/'prepared'
16
+
17
+
18
+ def save(path,value):
19
+ path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
20
+ temp=path.with_suffix(path.suffix+'.tmp');temp.write_text(json.dumps(value,allow_nan=False,indent=2)+'\n');temp.replace(path)
21
+
22
+ PROTOCOL=dict(package='myopic-mces',version='1.0.0',pulp='2.9.0',threshold=15,
23
+ always_stronger_bound=True,solver='PULP_CBC_CMD',solver_threads=1,time_limit_seconds=5,
24
+ missing='null_not_zero',stereochemistry='ignored_isotope_charge_preserved')
25
+
26
+
27
+ def canonical(smiles):
28
+ from rdkit import Chem
29
+ if not smiles:return None
30
+ m=Chem.MolFromSmiles(smiles)
31
+ if m is None:return None
32
+ Chem.RemoveStereochemistry(m)
33
+ return Chem.MolToSmiles(m,canonical=True,isomericSmiles=True)
34
+
35
+
36
+ def worker(task):
37
+ from myopic_mces.myopic_mces import MCES
38
+ key,a,b=task
39
+ if a==b:return key,0.,0,None
40
+ try:
41
+ result=MCES(ind=0,s1=a,s2=b,threshold=15,solver='PULP_CBC_CMD',
42
+ solver_options={'msg':False,'threads':1,'timeLimit':5},always_stronger_bound=True,no_ilp_threshold=False)
43
+ value=float(result[1]);mode=int(result[3])
44
+ if not math.isfinite(value) or value<0:raise ValueError('Invalid MCES')
45
+ return key,value,mode,None
46
+ except Exception as exc:return key,None,None,repr(exc)
47
+
48
+
49
+ def evaluate(directory):
50
+ for name,version in [('myopic-mces','1.0.0'),('pulp','2.9.0')]:
51
+ if importlib.metadata.version(name)!=version:raise RuntimeError('MCES protocol dependency mismatch')
52
+ with gzip.open(directory/'per_spectrum_summary.json.gz','rt') as f:rows=json.load(f)
53
+ db=sqlite3.connect(CACHE/'Validation_mces_pairs.sqlite');db.execute('PRAGMA journal_mode=WAL')
54
+ db.execute('CREATE TABLE IF NOT EXISTS pairs(key TEXT PRIMARY KEY,a TEXT,b TEXT,distance REAL,mode INTEGER,error TEXT)')
55
+ inputs=[];todo={}
56
+ for r in rows:
57
+ a=canonical(r['target']);b=canonical(r.get('top1_smiles'));key=None
58
+ if a and b:
59
+ key=hashlib.sha256(json.dumps([PROTOCOL,a,b],sort_keys=True,separators=(',',':')).encode()).hexdigest()
60
+ found=db.execute('SELECT distance,error FROM pairs WHERE key=?',(key,)).fetchone()
61
+ if found is None or found[0] is None:todo[key]=(key,a,b)
62
+ inputs.append((r,key))
63
+ tasks=list(todo.values());done=0
64
+ # Bounded batches avoid pre-submitting the whole dataset and use no GPU.
65
+ with ProcessPoolExecutor(max_workers=2) as pool:
66
+ for start in range(0,len(tasks),32):
67
+ for key,value,mode,error in pool.map(worker,tasks[start:start+32]):
68
+ task=todo[key]
69
+ db.execute('INSERT OR REPLACE INTO pairs VALUES (?,?,?,?,?,?)',(key,task[1],task[2],value,mode,error));done+=1
70
+ db.commit();save(directory/'MCES_status.json',dict(phase='posthoc_Validation_only',processed_new_pairs=done,total_new_pairs=len(tasks),unix_time=time.time()))
71
+ results={};details=[]
72
+ for view in ('mass','formula'):
73
+ selected=[(r,k) for r,k in inputs if r['view']==view];values=[];modes={};missing=0
74
+ for r,key in selected:
75
+ hit=db.execute('SELECT distance,mode,error FROM pairs WHERE key=?',(key,)).fetchone() if key else None
76
+ value=hit[0] if hit else None
77
+ if value is None:missing+=1
78
+ else:values.append(value);modes[str(hit[1])]=modes.get(str(hit[1]),0)+1
79
+ details.append(dict(identifier=r['identifier'],view=view,distance=value,mode=hit[1] if hit else None,error=hit[2] if hit else 'missing_or_invalid_prediction'))
80
+ results[view]=dict(n=len(selected),valid=len(values),missing=missing,valid_mean=statistics.mean(values) if values else None,
81
+ full_mean=statistics.mean(values) if not missing and values else None,modes=modes)
82
+ temporary=directory/'MCES_per_spectrum.json.gz.tmp'
83
+ with gzip.open(temporary,'wt',compresslevel=3) as f:json.dump(details,f,separators=(',',':'))
84
+ temporary.replace(directory/'MCES_per_spectrum.json.gz')
85
+ save(directory/'MCES.json',dict(complete=True,protocol=PROTOCOL,views=results,approximation_and_time_limit_modes_preserved=True,unix_time=time.time()))
86
+ db.close()
87
+
88
+
89
+ def monitor():
90
+ while True:
91
+ found=False
92
+ for arm in ('main','control'):
93
+ for update in (3000,4000):
94
+ directory=OUT/arm/('validation_update_%06d'%update)
95
+ if (directory/'metrics.json').exists() and not (directory/'MCES.json').exists():
96
+ evaluate(directory);found=True
97
+ complete=all((OUT/arm/'COMPLETE.json').exists() and all((OUT/arm/('validation_update_%06d'%u)/'MCES.json').exists() for u in (3000,4000)) for arm in ('main','control'))
98
+ if found or complete:
99
+ from comparison_ceir import write
100
+ write(OUT)
101
+ if complete:
102
+ save(OUT/'ALL_VALIDATION_AND_MCES_COMPLETE.json',dict(complete=True,unix_time=time.time()));return
103
+ if not found:time.sleep(30)
104
+
105
+
106
+ if __name__=='__main__':monitor()
code/snapshot/root/code/ceir_r1_20261109/model_ceir.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """C03-compatible model plus zero-initialized chemical-evidence residuals."""
2
+ from dataclasses import replace
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+ from torch.nn.utils.rnn import pad_sequence
8
+
9
+ from runtime_ceir import *
10
+ from evidence_ceir import EvidenceStore,TOKENS,WIDTH
11
+ from specpartition_ms.model_v122 import BidirectionalRanker
12
+ from specpartition_ms.model import Encoded
13
+ from specpartition_ms.fast_formula_r2 import forward_batch as original_formula_forward
14
+ from coarse_losses import ProjectionBank
15
+ from kernels import install_graph_kernel
16
+
17
+
18
+ class CompositionHead(nn.Module):
19
+ def __init__(self):
20
+ super().__init__();d=128
21
+ self.feature=nn.Linear(WIDTH,d);self.peak=nn.Linear(256,d)
22
+ layer=nn.TransformerEncoderLayer(d,4,dim_feedforward=2*d,dropout=0.,activation='gelu',batch_first=True,norm_first=True)
23
+ self.encoder=nn.TransformerEncoder(layer,2,enable_nested_tensor=False)
24
+ self.output=nn.Linear(d,256)
25
+ self.formula=nn.Sequential(nn.Linear(256+d,d),nn.GELU(),nn.Linear(d,1))
26
+
27
+ def forward(self,q,peaks,assets):
28
+ active=[i for i,a in enumerate(assets) if a['available'] and a['valid'].any()]
29
+ if not active:return [None]*len(assets),q.new_zeros(len(assets))
30
+ features=q.new_tensor(np.stack([assets[i]['features'] for i in active]))
31
+ valid=torch.as_tensor(np.stack([assets[i]['valid'] for i in active]),device=q.device,dtype=torch.bool)
32
+ indices=torch.as_tensor(np.stack([assets[i]['indices'] for i in active]),device=q.device,dtype=torch.long)
33
+ encoded=self.encoder(self.feature(features)+self.peak(peaks[indices]),src_key_padding_mask=~valid)
34
+ summary=(encoded*valid[:,:,None]).sum(1)/valid.sum(1)[:,None]
35
+ values=self.formula(torch.cat((q.expand(len(active),-1),summary),-1)).squeeze(-1).tanh()
36
+ delta=q.new_zeros(len(assets)).index_copy(0,torch.tensor(active,device=q.device),values.to(q.dtype))
37
+ results=[None]*len(assets)
38
+ lifted=self.output(encoded)
39
+ for j,i in enumerate(active):results[i]=(lifted[j,valid[j]],peaks[indices[j,valid[j]]])
40
+ return results,delta
41
+
42
+
43
+ class Extensions(nn.Module):
44
+ def __init__(self):
45
+ super().__init__()
46
+ self.fingerprint=nn.Sequential(nn.Linear(256,512),nn.GELU(),nn.Linear(512,2048))
47
+ self.composition=CompositionHead()
48
+ self.reverse_gate=nn.Parameter(torch.zeros(()))
49
+ self.fingerprint_gate=nn.Parameter(torch.zeros(()))
50
+ self.composition_gate=nn.Parameter(torch.zeros(()))
51
+ self.formula_gate=nn.Parameter(torch.zeros(()))
52
+
53
+
54
+ class CEIRRanker(BidirectionalRanker):
55
+ def __init__(self,c,arm):
56
+ super().__init__(c);self.hierarchy=ProjectionBank();self.ceir=Extensions()
57
+ self.arm=arm;self.evidence=None;install_graph_kernel(self)
58
+
59
+ def install_evidence(self,validation=False):
60
+ paths=[CACHE/'train_composition.sqlite']
61
+ if validation:paths.append(CACHE/'validation_composition.sqlite')
62
+ self.evidence=EvidenceStore(paths)
63
+
64
+ def formula_batch(self,qs,queries,tokens,return_context=False):
65
+ scores=original_formula_forward(self.formula_v07,qs,queries,tokens)
66
+ contexts=[None]*len(queries)
67
+ if self.arm=='main':
68
+ if self.evidence is None:raise RuntimeError('Offline evidence store is not installed')
69
+ for i,query in enumerate(queries):
70
+ if not query.formula_candidates:continue
71
+ assets=self.evidence.query(query)
72
+ context,delta=self.ceir.composition(qs[i].float(),tokens[i].float(),assets)
73
+ scores[i]=scores[i]+self.ceir.formula_gate.tanh()*.5*delta.float()
74
+ contexts[i]=context
75
+ return (scores,contexts) if return_context else scores
76
+
77
+ def local_both(self,peaks,atoms):
78
+ qp=F.normalize(self.local_q(peaks).float(),dim=-1);forward=[];reverse=[]
79
+ for start in range(0,len(atoms),self.local_chunk):
80
+ block=atoms[start:start+self.local_chunk];padded=pad_sequence(block,batch_first=True)
81
+ z=F.normalize(self.local_a(padded).float(),dim=-1)
82
+ valid=torch.arange(padded.shape[1],device=self.device)[None,:]<torch.tensor([len(a) for a in block],device=self.device)[:,None]
83
+ cosine=(qp@z.reshape(-1,z.shape[-1]).T).reshape(qp.shape[0],z.shape[0],z.shape[1]).permute(1,0,2)
84
+ forward.append(cosine.masked_fill(~valid[:,None,:],-torch.inf).max(-1).values.mean(-1))
85
+ reverse.append(cosine.max(1).values.masked_fill(~valid,0).sum(-1)/valid.sum(-1))
86
+ return torch.cat(forward),torch.cat(reverse)
87
+
88
+ def score_encoded(self,q,peaks,query,mols,atoms,zm,formula_scores,context=None):
89
+ conditional,joint,relation_q=self.conditioned(q,query,[m.formula for m in mols],zm,formula_scores)
90
+ if not mols:return joint,conditional,relation_q
91
+ if self.arm=='control':
92
+ local=self.local_weight*self.local_scores(peaks,atoms)
93
+ return joint+local,conditional+local,relation_q
94
+ local,reverse=self.local_both(peaks,atoms)
95
+ # Preserve the parent's BF16 weighted-local rounding BEFORE adding a
96
+ # FP32 reverse residual. Adding even FP32 zero before the multiplication
97
+ # promotes `local` and changes the warm-start score by ~1e-3.
98
+ residual=self.local_weight*local
99
+ residual=residual+.3*self.local_weight.float()*self.ceir.reverse_gate.tanh()*reverse
100
+ predicted=self.ceir.fingerprint(q.float()).sigmoid()
101
+ whole=torch.as_tensor(np.stack([m.whole for m in mols]),device=q.device,dtype=torch.float32)
102
+ intersection=(whole*predicted).sum(-1)
103
+ fp_similarity=intersection/(whole.square().sum(-1)+predicted.square().sum()-intersection).clamp_min(1e-8)
104
+ residual=residual+.3*self.ceir.fingerprint_gate.tanh()*fp_similarity
105
+ if context is not None:
106
+ lookup={f:i for i,f in enumerate(query.formula_candidates)}
107
+ corrections=q.new_zeros(len(mols))
108
+ for formula in sorted({m.formula for m in mols}):
109
+ ev=context[lookup[formula]]
110
+ if ev is None:continue
111
+ ids=[i for i,m in enumerate(mols) if m.formula==formula]
112
+ chemical,raw=ev;aa=[atoms[i] for i in ids]
113
+ correction=self.local_scores(chemical,aa)-self.local_scores(raw,aa)
114
+ corrections=corrections.index_copy(0,torch.tensor(ids,device=q.device),correction.to(corrections.dtype))
115
+ residual=residual+self.ceir.composition_gate.tanh()*corrections
116
+ return joint+residual,conditional+residual,relation_q
117
+
118
+ def encode_batch(self,queries,extras=()):
119
+ tokens,qs,metas=self.spectrum.forward_batch(queries)
120
+ key=lambda m:(m.identity,m.smiles)
121
+ lookup={key(m):m for q in queries for m in q.candidates};lookup.update({key(m):m for m in extras})
122
+ keys=sorted(lookup);positions={k:i for i,k in enumerate(keys)}
123
+ u,atoms,zm=self.encode_molecules([lookup[k] for k in keys])
124
+ zq=F.normalize(self.query_projection(qs).float(),dim=-1)
125
+ fs,contexts=self.formula_batch(qs,queries,tokens,True)
126
+ encs=[]
127
+ for i,q in enumerate(queries):
128
+ indices=[positions[key(m)] for m in q.candidates];idx=torch.tensor(indices,device=self.device,dtype=torch.long)
129
+ aa=[atoms[j] for j in indices]
130
+ base,direct,context=self.score_encoded(qs[i],tokens[i],q,q.candidates,aa,zm[idx],fs[i],contexts[i])
131
+ whole=torch.as_tensor(np.stack([m.whole for m in q.candidates]),device=self.device)
132
+ anchors=torch.as_tensor(np.stack([m.anchors for m in q.candidates]),device=self.device)
133
+ enc=Encoded(q,tokens[i].float(),qs[i].float(),metas[i].float(),u[idx].float(),zq[i],zm[idx],
134
+ [a.float() for a in aa],whole,anchors,fs[i],base,direct)
135
+ enc.conditional_context_q=context;encs.append(enc)
136
+ return encs,zm[torch.tensor([positions[key(m)] for m in extras],device=self.device,dtype=torch.long)]
137
+
138
+
139
+ def make_model_optimizer(arm,checkpoint_path=None):
140
+ state=source_state() if checkpoint_path is None else torch.load(checkpoint_path,map_location='cpu',weights_only=False)
141
+ # Deterministic new-head initialization in all arms; the saved parent RNG
142
+ # is restored below, so module construction does not perturb training views.
143
+ torch.manual_seed(SEED)
144
+ model=CEIRRanker(LEGACY.C,arm)
145
+ if checkpoint_path is not None and state.get('architecture')!='CEIR_R1':raise RuntimeError('Not a complete CEIR continuation checkpoint')
146
+ result=model.load_state_dict(state['model'],strict=checkpoint_path is not None)
147
+ if result.unexpected_keys or any(not k.startswith('ceir.') for k in result.missing_keys):
148
+ raise RuntimeError('Checkpoint key mismatch: '+str(result))
149
+ if checkpoint_path is None:
150
+ for key,value in state['model'].items():
151
+ if not torch.equal(model.state_dict()[key],value):raise RuntimeError('Parent tensor changed: '+key)
152
+ old=[p for name,p in model.named_parameters() if not name.startswith('ceir.')]
153
+ new=[p for name,p in model.named_parameters() if name.startswith('ceir.')]
154
+ if checkpoint_path is None and len(old)!=sum(len(g['params']) for g in state['optimizer']['param_groups']):
155
+ raise RuntimeError('Exact old optimizer parameter ordering/count was not preserved')
156
+ model.to(LEGACY.C['device'])
157
+ optimizer=torch.optim.AdamW(old,lr=1e-5,weight_decay=LEGACY.C['weight_decay'])
158
+ original_lr=source_state()['optimizer']['param_groups'][0]['lr'] if checkpoint_path is not None else state['optimizer']['param_groups'][0]['lr']
159
+ if checkpoint_path is None:
160
+ optimizer.load_state_dict(state['optimizer'])
161
+ optimizer.add_param_group(dict(params=new,lr=original_lr))
162
+ else:
163
+ optimizer.add_param_group(dict(params=new,lr=original_lr));optimizer.load_state_dict(state['optimizer'])
164
+ for p,s in optimizer.state.items():
165
+ for key,value in s.items():
166
+ if torch.is_tensor(value) and key!='step':s[key]=value.to(p.device)
167
+ progress=dict(state['progress']);progress.setdefault('new_updates',progress['update']-SOURCE_UPDATE)
168
+ model.install_evidence(False)
169
+ restore_rng(state)
170
+ return model,optimizer,progress,float(original_lr)
code/snapshot/root/code/ceir_r1_20261109/objective_sanity_checks.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synthetic mathematical sanity checks, not an integrated training loss.
2
+
3
+ No project dataset, model checkpoint, server, PubChem or heldout input is read.
4
+ """
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+
9
+ import torch
10
+ from torch.nn import functional as F
11
+
12
+
13
+ def group_logits(scores, identities):
14
+ keys = sorted(set(identities))
15
+ return keys, torch.stack([
16
+ torch.logsumexp(scores[[i for i, k in enumerate(identities) if k == key]], 0)
17
+ - math.log(sum(k == key for k in identities)) for key in keys])
18
+
19
+
20
+ def ce(scores, identities, positive):
21
+ keys, values = group_logits(scores, identities)
22
+ return torch.logsumexp(values, 0) - values[keys.index(positive)]
23
+
24
+
25
+ def run():
26
+ checks = []
27
+ scores = torch.tensor([1.0, 1.6, 0.4], dtype=torch.float64)
28
+ original = ce(scores, ['truth', 'wrong1', 'wrong2'], 'truth')
29
+ repeated = ce(torch.tensor([1., 1.6, 1.6, 1.6, .4], dtype=torch.float64),
30
+ ['truth', 'wrong1', 'wrong1', 'wrong1', 'wrong2'], 'truth')
31
+ assert torch.allclose(original, repeated, atol=1e-12, rtol=0)
32
+ checks.append('Repeated identical negative draws do not change identity-balanced CE')
33
+ perm = [2, 0, 1]
34
+ assert torch.allclose(original, ce(scores[perm], ['wrong2', 'truth', 'wrong1'], 'truth'))
35
+ checks.append('Candidate permutation preserves identity-balanced CE')
36
+
37
+ bias = torch.tensor(4.7, dtype=torch.float64, requires_grad=True)
38
+ conditional = ce(scores + bias, ['truth', 'wrong1', 'wrong2'], 'truth')
39
+ grad = torch.autograd.grad(conditional, bias)[0]
40
+ assert abs(grad.item()) < 1e-12
41
+ checks.append('A shared same-formula scalar offset has zero conditional-CE gradient')
42
+
43
+ grad_scores = torch.tensor([1., 1.6, .4], dtype=torch.float64, requires_grad=True)
44
+ ce(grad_scores, ['truth', 'wrong1', 'wrong2'], 'truth').backward()
45
+ assert grad_scores.grad[0] < 0 and (grad_scores.grad[1:] > 0).all()
46
+ checks.append('Gradient descent raises truth and lowers both distinct wrong identities')
47
+ no_negative = ce(torch.tensor([1., 1.], requires_grad=True), ['truth', 'truth'], 'truth')
48
+ assert no_negative.item() == 0
49
+ checks.append('No distinct negative means no competitive CE signal')
50
+
51
+ positive = torch.tensor(1., requires_grad=True)
52
+ negatives = torch.tensor([1.4, 0.5])
53
+ gap = F.softplus(.2 + negatives - positive).mean()
54
+ gap.backward()
55
+ assert positive.grad < 0
56
+ checks.append('Same-formula gap pushes the positive above hard wrong scores')
57
+ return {'scope': 'synthetic CPU mathematical checks only', 'checks_passed': len(checks),
58
+ 'checks': checks, 'same_formula_bias_gradient': grad.item(),
59
+ 'integrated_loss_or_GPU_acceptance': False, 'training_started': False}
60
+
61
+
62
+ if __name__ == '__main__':
63
+ report = run()
64
+ (Path(__file__).resolve().parent / 'objective_sanity_validation.json').write_text(
65
+ json.dumps(report, ensure_ascii=False, indent=2) + '\n')
66
+ print(json.dumps(report, ensure_ascii=False))
code/snapshot/root/code/ceir_r1_20261109/objective_sanity_validation.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "scope": "synthetic CPU mathematical checks only",
3
+ "checks_passed": 6,
4
+ "checks": [
5
+ "Repeated identical negative draws do not change identity-balanced CE",
6
+ "Candidate permutation preserves identity-balanced CE",
7
+ "A shared same-formula scalar offset has zero conditional-CE gradient",
8
+ "Gradient descent raises truth and lowers both distinct wrong identities",
9
+ "No distinct negative means no competitive CE signal",
10
+ "Same-formula gap pushes the positive above hard wrong scores"
11
+ ],
12
+ "same_formula_bias_gradient": -2.220446049250313e-16,
13
+ "integrated_loss_or_GPU_acceptance": false,
14
+ "training_started": false
15
+ }
code/snapshot/root/code/ceir_r1_20261109/objectives_ceir.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Joint C03 objectives plus qualified CEIR terms, one final pool denominator."""
2
+ from collections import Counter
3
+ import math
4
+ import time
5
+ import numpy as np
6
+ import torch
7
+ from torch.nn import functional as F
8
+ from torch.nn.utils.rnn import pad_sequence
9
+ from torch.utils.checkpoint import checkpoint as recompute
10
+
11
+ from runtime_ceir import *
12
+ from kernels import grouped_contrastive
13
+ from specpartition_ms.fast_formula_r2 import auxiliary_batch
14
+
15
+ PARENT_OBJECTIVES=load_module('ceir_parent_objectives',ROOT/'rebuild/hierarchical_training_20261103/objectives.py')
16
+
17
+
18
+ def amp():return torch.autocast('cuda',dtype=torch.bfloat16,enabled=LEGACY.C['bf16'])
19
+
20
+
21
+ def molecular_views(model,mols,probability):
22
+ # The closure reinstalls the stochastic hook during backward recomputation;
23
+ # unlike checkpointing a graph after removing the hook, RNG semantics hold.
24
+ def one(dummy):
25
+ old=model.activation_checkpoint_atom_threshold
26
+ model.activation_checkpoint_atom_threshold=10**12
27
+ handle=model.graph.atom.register_forward_hook(lambda module,inputs,output:F.dropout(output,p=probability,training=True))
28
+ try:
29
+ with amp():return model.encode_molecules(mols)[0].float()
30
+ finally:handle.remove();model.activation_checkpoint_atom_threshold=old
31
+ return (recompute(one,model.graph.atom.weight,use_reentrant=False,preserve_rng_state=True),
32
+ recompute(one,model.graph.atom.weight,use_reentrant=False,preserve_rng_state=True))
33
+
34
+
35
+ PARENT_OBJECTIVES.molecular_views=molecular_views
36
+
37
+
38
+ def identity_logits(scores,identities):
39
+ keys=sorted(set(identities))
40
+ mask=torch.tensor([[key==identity for identity in identities] for key in keys],device=scores.device,dtype=torch.bool)
41
+ group=scores.float()[None,:].expand(len(keys),-1).masked_fill(~mask,-torch.inf).logsumexp(-1)-mask.sum(-1).float().log()
42
+ return keys,group
43
+
44
+
45
+ def pool_terms(score,pool,arm):
46
+ ids=[m.identity for m in pool['query'].candidates];forms=[m.formula for m in pool['query'].candidates]
47
+ truth=pool['truth_identity'];tf=pool['truth_formula'];zero=score.float().sum()*0.
48
+ if arm=='control':return torch.logsumexp(score.float(),0)-score[pool['positive_index']].float(),zero,zero
49
+ keys,values=identity_logits(score,ids);positive=keys.index(truth)
50
+ ce=values.logsumexp(0)-values[positive]
51
+ formula_by_id={key:forms[ids.index(key)] for key in keys}
52
+ if any(f!=formula_by_id[k] for k,f in zip(ids,forms)):raise RuntimeError('Identity/formula conflict')
53
+ same=[i for i,k in enumerate(keys) if formula_by_id[k]==tf]
54
+ wrong=[i for i in same if i!=positive]
55
+ conditional=zero;gap=zero
56
+ if wrong and pool['quality_eligible']:
57
+ hard=values[wrong].topk(min(3,len(wrong))).values
58
+ gap=F.softplus(.2+hard-values[positive]).mean()
59
+ if pool['kind']=='mass' and len(same)<len(keys):conditional=values[same].logsumexp(0)-values[positive]
60
+ return ce,conditional,gap
61
+
62
+
63
+ def formula_loss(model,qs,tokens,rows,total_valid,total_aux):
64
+ scores=model.formula_batch(qs,[r['query'] for r in rows],tokens)
65
+ valid=[i for i,r in enumerate(rows) if r['mass_ok'] and len(r['formulas'])>1 and r['formula'] in r['formulas']]
66
+ zero=qs.float().sum()*0.;ce=zero;gap=zero;correct=zero
67
+ if valid:
68
+ ss=pad_sequence([scores[i].float() for i in valid],batch_first=True,padding_value=-torch.inf)
69
+ pos=torch.tensor([rows[i]['formulas'].index(rows[i]['formula']) for i in valid],device=qs.device)
70
+ rid=torch.arange(len(valid),device=qs.device);ps=ss[rid,pos]
71
+ ce=(ss.logsumexp(-1)-ps).sum()/max(1,total_valid)
72
+ negative=ss.scatter(1,pos[:,None],-torch.inf);k=min(3,ss.shape[1]-1)
73
+ top=negative.topk(k,dim=-1).values
74
+ actual=qs.new_tensor([min(k,len(scores[i])-1) for i in valid])
75
+ gap=(F.softplus(.2+top-ps[:,None]).sum(-1)/actual).sum()/max(1,total_valid)
76
+ correct=(ss.argmax(-1)==pos).float().sum()
77
+ element,_,_=auxiliary_batch(model.formula_v07,qs,[r['formula'] for r in rows])
78
+ elem=element.sum()/max(1,total_aux)
79
+ return ce+.1*gap+.2*elem,dict(formula_ce=ce.detach(),formula_gap=gap.detach(),element_ce=elem.detach(),formula_correct=correct.detach())
80
+
81
+
82
+ def fingerprint_loss(model,q,rows):
83
+ if model.arm!='main':return q.sum()*0.,0
84
+ selected=[i for i,r in enumerate(rows) if r['fingerprint_eligible']]
85
+ if not selected:return q.sum()*0.,0
86
+ p=model.ceir.fingerprint(q[selected]).float().sigmoid()
87
+ y=torch.as_tensor(np.stack([rows[i]['ref'].whole for i in selected]),device=q.device,dtype=torch.float32)
88
+ inter=(p*y).sum(-1);union=p.square().sum(-1)+y.square().sum(-1)-inter
89
+ loss=1-F.cosine_similarity(p,y,dim=-1)+.1*(1-inter/union.clamp_min(1e-8))
90
+ ids=[rows[i]['identity'] for i in selected];counts=Counter(ids)
91
+ weights=q.new_tensor([1/counts[k]/len(counts) for k in ids])
92
+ return (loss*weights).sum(),len(selected)
93
+
94
+
95
+ def train_step(model,opt,batch,update,apply_update=True):
96
+ started=time.monotonic();rows=batch['rows'];queries=[r['query'] for r in rows];ids=[r['identity'] for r in rows]
97
+ reps={}
98
+ for r in rows:
99
+ if r['identity'] not in reps or r['ref'].smiles<reps[r['identity']].smiles:reps[r['identity']]=r['ref']
100
+ columns=sorted(reps);mols=[reps[k] for k in columns];w=LEGACY.C['loss_weights'];opt.zero_grad(set_to_none=True)
101
+ with torch.no_grad(),amp():
102
+ qc=torch.cat([model.spectrum.forward_batch(queries[a:a+16])[1] for a in range(0,len(rows),16)])
103
+ mc=torch.cat([model.encode_molecules(mols[a:a+32])[0] for a in range(0,len(mols),32)])
104
+ qc=qc.float().detach().requires_grad_();mc=mc.float().detach().requires_grad_()
105
+ with amp():
106
+ zq=F.normalize(model.query_projection(qc).float(),dim=-1);zm=F.normalize(model.mol_projection(mc).float(),dim=-1)
107
+ f,b=grouped_contrastive(zq@zm.T/LEGACY.C['contrastive_temperature'],ids,columns)
108
+ base=w['inbatch_ms_to_mol']*f+w['inbatch_mol_to_ms']*b
109
+ # C03 was already past its auxiliary ramp; do not restart that ramp.
110
+ auxiliary,details=PARENT_OBJECTIVES.auxiliary_loss(model,qc,mols,rows,SPEC,update,False)
111
+ fp,fp_valid=fingerprint_loss(model,qc,rows)
112
+ fp_weight=.1*min(1.,(update-SOURCE_UPDATE+1)/200.) if model.arm=='main' else 0.
113
+ (base+auxiliary+fp_weight*fp).backward();dq=qc.grad.detach();dm=mc.grad.detach()
114
+ metrics=dict(inbatch_ms_to_mol=f.detach(),inbatch_mol_to_ms=b.detach(),formula_loss=0.,formula_ce=0.,formula_gap=0.,element_ce=0.,formula_correct=0.,fingerprint_loss=fp.detach(),fingerprint_weight=fp_weight)
115
+ valid=sum(r['mass_ok'] and len(r['formulas'])>1 and r['formula'] in r['formulas'] for r in rows)
116
+ for a in range(0,len(rows),16):
117
+ block=rows[a:a+16]
118
+ with amp():
119
+ tokens,q,_=model.spectrum.forward_batch([r['query'] for r in block])
120
+ lf,d=formula_loss(model,q,tokens,block,valid,len(rows))
121
+ loss=(q*dq[a:a+len(block)]).sum()+w['formula']*lf
122
+ loss.backward();metrics['formula_loss']+=lf.detach()
123
+ for k,v in d.items():metrics[k]+=v
124
+ for a in range(0,len(mols),32):
125
+ with amp():u=model.encode_molecules(mols[a:a+32])[0];surrogate=(u*dm[a:a+len(u)]).sum()
126
+ surrogate.backward()
127
+ pools=[p for r in rows for p in r['pools']];counts=Counter(p['kind'] for p in pools)
128
+ pm={k:qc.new_zeros(()) for k in ('odata','mass','formula')};c_total=qc.new_zeros(());g_total=qc.new_zeros(())
129
+ def valid_same(p):
130
+ mm=p['query'].candidates
131
+ return p['quality_eligible'] and any(m.identity!=p['truth_identity'] and m.formula==p['truth_formula'] for m in mm)
132
+ g_count=sum(valid_same(p) for p in pools) if model.arm=='main' else 0
133
+ c_count=sum(valid_same(p) and p['kind']=='mass' and any(m.formula!=p['truth_formula'] for m in p['query'].candidates) for p in pools) if model.arm=='main' else 0
134
+ for p in pools:
135
+ with amp():
136
+ enc=model.encode_batch([p['query']])[0][0]
137
+ ce,conditional,gap=pool_terms(enc.base,p,model.arm)
138
+ weight=w[{'odata':'odata_pool','mass':'msg_mass_pool','formula':'msg_formula_pool'}[p['kind']]]
139
+ loss=weight*ce/counts[p['kind']]+.25*conditional/max(1,c_count)+.1*gap/max(1,g_count)
140
+ loss.backward();pm[p['kind']]+=ce.detach()/counts[p['kind']]
141
+ c_total+=conditional.detach()/max(1,c_count);g_total+=gap.detach()/max(1,g_count)
142
+ total=base.detach()+auxiliary.detach()+fp_weight*fp.detach()+w['formula']*metrics['formula_loss']+.25*c_total+.1*g_total
143
+ for k,v in pm.items():metrics[k+'_pool']=v;total+=w[{'odata':'odata_pool','mass':'msg_mass_pool','formula':'msg_formula_pool'}[k]]*v
144
+ metrics.update(details);metrics.update(conditional_structure_ce=c_total,same_formula_gap=g_total,loss=total)
145
+ if not torch.isfinite(total):raise RuntimeError('Nonfinite CEIR objective')
146
+ gradients={}
147
+ for name,parameters in [('backbone',[p for n,p in model.named_parameters() if not n.startswith('ceir.')]),
148
+ ('fingerprint',model.ceir.fingerprint.parameters()),('composition',model.ceir.composition.parameters())]:
149
+ gs=[p.grad.detach().float().square().sum() for p in parameters if p.grad is not None]
150
+ gradients[name+'_gradient_norm']=torch.stack(gs).sum().sqrt() if gs else total*0
151
+ for name in ('reverse_gate','fingerprint_gate','composition_gate','formula_gate'):
152
+ p=getattr(model.ceir,name);gradients[name+'_gradient']=p.grad.detach() if p.grad is not None else total*0
153
+ metrics[name]=p.detach()
154
+ norm=torch.nn.utils.clip_grad_norm_(model.parameters(),LEGACY.C['gradient_clip'],error_if_nonfinite=True)
155
+ metrics.update(gradients);metrics['gradient_norm']=norm.detach()
156
+ if apply_update:opt.step()
157
+ values=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()
158
+ result=dict(zip(metrics,values));result.update(queries=len(rows),unique_connectivity=len(columns),formula_valid=valid,
159
+ fingerprint_valid=fp_valid,conditional_valid=c_count,gap_valid=g_count,pool_valid=dict(counts),
160
+ negative_draws=sum(p['negative_draws'] for p in pools),negative_unique_key14=sum(p['unique_negative_key14'] for p in pools),
161
+ sampling_sources=dict(sum((Counter(p['source_counts']) for p in pools),Counter())),
162
+ sources=dict(Counter(r['source'] for r in rows)),data_seconds=batch['data_seconds'],
163
+ adduct_counts=dict(Counter(r['query'].adduct for r in rows)),
164
+ quality_inconsistent_queries=sum(not r['mass_ok'] for r in rows),
165
+ teacher_version_query_counts=dict(Counter(str(p['teacher_source_update']) for p in pools if p['teacher_source_update'] is not None)),
166
+ step_compute_seconds=time.monotonic()-started,peak_allocated_mib=torch.cuda.max_memory_allocated()/2**20)
167
+ return result
code/snapshot/root/code/ceir_r1_20261109/pipeline_ceir.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Managed gate: all caches -> real GPU acceptance -> both continuation arms."""
2
+ import json
3
+ import importlib.metadata
4
+ import platform
5
+ from pathlib import Path
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ import time
10
+ import traceback
11
+ from runtime_ceir import *
12
+
13
+
14
+ def provenance_snapshot():
15
+ binding=bind();dest=OUT/'source_snapshot';dest.mkdir(parents=True,exist_ok=True)
16
+ for file in HERE.iterdir():
17
+ if file.is_file() and not file.name.startswith('.') and file.suffix in ('.py','.json','.md','.conf'):shutil.copy2(file,dest/file.name)
18
+ if (HERE/'reference').exists():shutil.copytree(HERE/'reference',dest/'reference',dirs_exist_ok=True)
19
+ dependencies=dest/'parent_dependencies';dependencies.mkdir(exist_ok=True)
20
+ for name,digest in binding['dependency_sources'].items():
21
+ original=Path(name);relative=original.relative_to(ROOT)
22
+ target=dependencies/relative;target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(original,target)
23
+ if sha(target)!=digest:raise RuntimeError('Dependency snapshot mismatch')
24
+ save(OUT/'SOURCE_MANIFEST.json',dict(binding=binding,source_parent=PLAN['parent'],snapshot=str(dest),unix_time=time.time()))
25
+ save(OUT/'EXECUTION_CONFIG.json',dict(schema_version=1,status='integrated_runtime_not_the_historical_proposal',
26
+ parent=PLAN['parent'],source_update=SOURCE_UPDATE,target_update=TARGET_UPDATE,
27
+ permitted_arms=['main','control'],additional_updates_each=2000,original_base_config=LEGACY.C,
28
+ resolved_main=PLAN['loss'],sampling=PLAN['sampling'],optimizer=PLAN['optimizer'],
29
+ GPU=dict(allocator_fraction_each=.11,admission_free_mib=5500,private_R1_slots=2,
30
+ new_jobs_only_not_an_exclusive_lock_against_other_users=True),
31
+ data_scope='only_actual_2000_step_pilot_queries_and_full_official_Validation',
32
+ no_Test_or_CASMI_for_training_or_selection=True,proposal_readiness_flags_are_historical=True,
33
+ runtime_binding=binding,unix_time=time.time()))
34
+ import torch
35
+ versions={}
36
+ for package in ('torch','numpy','rdkit'):
37
+ try:versions[package]=importlib.metadata.version(package)
38
+ except importlib.metadata.PackageNotFoundError:versions[package]=None
39
+ gpu=subprocess.run(['nvidia-smi','--query-gpu=name,driver_version,memory.total',
40
+ '--format=csv,noheader'],capture_output=True,text=True,check=True).stdout.strip()
41
+ save(OUT/'ENVIRONMENT.json',dict(python=sys.version,executable=sys.executable,platform=platform.platform(),
42
+ packages=versions,torch_build_CUDA=torch.version.cuda,GPU_query=gpu,
43
+ mixed_precision='BF16_encoder_FP32_reductions',deterministic_algorithms=True,
44
+ cuda_workspace=':4096:8',student_trainable_embeddings_persisted=False))
45
+
46
+
47
+ def freeze_assets():
48
+ marker=CACHE/'ASSET_MANIFEST.json'
49
+ files=['workload.json','fingerprint_targets.json','train_composition.sqlite','validation_composition.sqlite','teacher_parent.sqlite']
50
+ if marker.exists():
51
+ prior=json.loads(marker.read_text())
52
+ for name,meta in prior['files'].items():
53
+ stat=(CACHE/name).stat()
54
+ if stat.st_size!=meta['bytes'] or stat.st_mtime_ns!=meta['mtime_ns']:
55
+ raise RuntimeError('Prepared asset changed after freeze: '+name)
56
+ return
57
+ teacher=json.loads((CACHE/'teacher_ready.json').read_text())
58
+ manifest=json.loads((CACHE/'workload.json').read_text())
59
+ expected={(rid,g['kind']) for g in manifest['pools'].values() for rid in g['record_ids']}
60
+ db=readonly(CACHE/'teacher_parent.sqlite')
61
+ actual=set(db.execute('SELECT record_id,kind FROM hard_fp32'))
62
+ if actual!=expected or teacher['queries']!=len(expected):raise RuntimeError('Incomplete or extraneous teacher query coverage')
63
+ db.close()
64
+ stats={}
65
+ for name in files:
66
+ path=CACHE/name;stat=path.stat()
67
+ meta=dict(bytes=stat.st_size,mtime_ns=stat.st_mtime_ns,sha256=sha(path))
68
+ if path.suffix=='.sqlite':
69
+ db=readonly(path);integrity=db.execute('PRAGMA quick_check').fetchall();db.close()
70
+ if integrity!=[('ok',)]:raise RuntimeError('SQLite integrity check failed: '+name)
71
+ meta['sqlite_quick_check']='ok'
72
+ stats[name]=meta
73
+ save(marker,dict(complete=True,files=stats,teacher_query_pairs=len(expected),workload_binding=manifest['binding'],unix_time=time.time()))
74
+
75
+
76
+ def pipeline():
77
+ OUT.mkdir(parents=True,exist_ok=True);CACHE.mkdir(parents=True,exist_ok=True)
78
+ while not (OUT/'CODE_RELEASE.json').exists():
79
+ save(OUT/'pipeline_status.json',dict(phase='waiting_for_frozen_code_release',formal_training_started=False,unix_time=time.time()))
80
+ time.sleep(10)
81
+ release=json.loads((OUT/'CODE_RELEASE.json').read_text())
82
+ if release['code']!=code_manifest():raise RuntimeError('Code differs from the frozen release')
83
+ names=['train_composition_ready.json','validation_composition_ready.json','teacher_ready.json']
84
+ starts={}
85
+ while not all((CACHE/name).exists() for name in names):
86
+ for service,marker in [('specpartition-ceir-r1-evidence-20261109','validation_composition_ready.json'),
87
+ ('specpartition-ceir-r1-mining-20261109','teacher_ready.json')]:
88
+ if (CACHE/marker).exists():continue
89
+ key=(service,sha(HERE/'prepare_ceir.py'))
90
+ status=subprocess.run(['supervisorctl','status',service],capture_output=True,text=True).stdout
91
+ if 'RUNNING' not in status and 'STARTING' not in status and starts.get(key,0)<3:
92
+ subprocess.run(['supervisorctl','start',service],check=False);starts[key]=starts.get(key,0)+1
93
+ missing=[name for name in names if not (CACHE/name).exists()]
94
+ save(OUT/'pipeline_status.json',dict(phase='preparing_all_pilot_caches',pending=missing,formal_training_started=False,unix_time=time.time()))
95
+ time.sleep(15)
96
+ freeze_assets();provenance_snapshot()
97
+ if not (OUT/'READY.json').exists():
98
+ save(OUT/'pipeline_status.json',dict(phase='real_GPU_acceptance',formal_training_started=False,unix_time=time.time()))
99
+ subprocess.run([sys.executable,'-u',str(HERE/'acceptance_ceir.py')],check=True,cwd=HERE)
100
+ if json.loads((OUT/'READY.json').read_text())['binding']!=bind():raise RuntimeError('Code changed after GPU acceptance')
101
+ services=['specpartition-ceir-r1-main-20261109','specpartition-ceir-r1-control-20261109',
102
+ 'specpartition-ceir-r1-mces-20261109','specpartition-ceir-r1-refresh-20261109']
103
+ # Explicitly name only this experiment's new services; never `update all`.
104
+ for service in services:
105
+ if '-main-' in service and (OUT/'main/COMPLETE.json').exists():continue
106
+ if '-control-' in service and (OUT/'control/COMPLETE.json').exists():continue
107
+ if '-mces-' in service and (OUT/'ALL_VALIDATION_AND_MCES_COMPLETE.json').exists():continue
108
+ if '-refresh-' in service and (OUT/'main/step_004000.pt').exists():continue
109
+ status=subprocess.run(['supervisorctl','status',service],capture_output=True,text=True).stdout
110
+ if 'RUNNING' not in status:subprocess.run(['supervisorctl','start',service],check=True)
111
+ while True:
112
+ updates={}
113
+ for arm in ('main','control'):
114
+ path=OUT/arm/'status.json'
115
+ updates[arm]=json.loads(path.read_text()).get('new_updates',0) if path.exists() else 0
116
+ started=all(value>=1 for value in updates.values())
117
+ save(OUT/'pipeline_status.json',dict(phase='both_arms_have_real_updates' if started else 'waiting_for_first_real_updates',
118
+ formal_training_started=started,actual_new_updates=updates,services=services,unix_time=time.time()))
119
+ if started:return
120
+ time.sleep(10)
121
+
122
+
123
+ if __name__=='__main__':
124
+ try:pipeline()
125
+ except Exception:
126
+ save(OUT/'PIPELINE_FAILURE.json',dict(traceback=traceback.format_exc(),unix_time=time.time(),other_services_modified=False));raise
code/snapshot/root/code/ceir_r1_20261109/plan.json ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "method": "SpecPartition-MS CEIR-R1",
4
+ "description": "Chemical Evidence for Isomer Ranking; recommended hypothesis, not a measured strongest model",
5
+ "status": "design_and_config_only_not_trainer_integrated",
6
+ "new_training_started": false,
7
+ "existing_services_changed": false,
8
+ "parent": {
9
+ "checkpoint": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C03_both_fine/seed_20261103/step_002000.pt",
10
+ "sha256": "8a2982f3821fad501ba4f39ac8b1495affeb0c1b09051f2103317f36027d48b6",
11
+ "source_update": 2000,
12
+ "resume_old_model_optimizer_moments_rng": true,
13
+ "new_parameters_separate_optimizer_group": true,
14
+ "strict_false_checkpoint_load_requires_explicit_whitelist": true
15
+ },
16
+ "data": {
17
+ "training_sources": ["MSG_Train", "MSP_libraries", "MS2_SAN_JSONL"],
18
+ "reference_release_spectra": {"MSG_Train": 162974, "MSP_libraries": 261644, "MS2_SAN_JSONL": 218969},
19
+ "reference_release_total": 643587,
20
+ "labels": "/workspace/xj/SpecPartition-MS/data/derived/data_release_r07_key14_20261101/train.json",
21
+ "prepared": "/workspace/xj/SpecPartition-MS/data/derived/joint_r09_inputs_20261102/train.sqlite",
22
+ "candidates": "/workspace/xj/SpecPartition-MS/data/derived/training_r08_true_formula_records_20261101/preparation.sqlite",
23
+ "heldout_registry": "/workspace/xj/SpecPartition-MS/data/derived/data_release_r07_key14_20261101/heldout_registry.json",
24
+ "live_inventory_rechecked_this_turn": false,
25
+ "exclude_heldout_key14_from_training_labels_and_negative_supervision": true,
26
+ "keep_multiple_MS_per_identity": true,
27
+ "delete_raw_candidate_records": false,
28
+ "official_MSG_Mass_Formula_both_each_step": true,
29
+ "truth_injection": false,
30
+ "network_during_training": false,
31
+ "heavy_RDKit_during_training": false,
32
+ "negative_mining_allowed_splits": ["MSG_Train", "MSP_libraries", "MS2_SAN_JSONL"]
33
+ },
34
+ "model": {
35
+ "inherit_C03_backbones": true,
36
+ "spectrum_dim": 256,
37
+ "spectrum_layers": 6,
38
+ "molecule_edge_gated_MPNN_layers": 6,
39
+ "raw_peak_limit": 256,
40
+ "reference_registered_parent_parameters": 17001870,
41
+ "new_total_parameters": null,
42
+ "new_modules": {
43
+ "reverse_local": {"enabled": true, "existing_prototype": "../specpartition-c03-isomer-refinement-20261109/local_coverage.py", "zero_initialized_residual": true, "bound": 0.3, "reuse_peak_atom_matrix": true, "assert_each_atom_is_observed_fragment": false},
44
+ "fingerprint": {"enabled": true, "existing_prototype": "../specpartition-c03-isomer-refinement-20261109/fingerprint_aux.py", "input_dim": 256, "hidden_dim": 512, "bits": 2048, "radius": 2, "chirality": false, "auxiliary_parameter_count": 1182208, "auxiliary_cosine_weight": 1.0, "auxiliary_soft_tanimoto_weight": 0.1, "scoring_residual_zero_init": true, "audit_targets_within_key14": true, "mask_invalid_empty_or_conflicting_targets": true},
45
+ "composition_evidence": {"enabled": true, "implementation_ready": false, "evidence_dim": 128, "attention_layers": 2, "heads": 4, "strong_peaks": 10, "retain_full_raw_peak_path": true, "formulas_in_MSG": "all_actual_distinct_pool_formulas_not_Top10_truncated", "formulas_in_CASMI": "frozen_actual_Top10_only", "cache_key": ["spectrum_hash", "formula", "adduct", "charge", "annotation_rule_version"], "outputs": ["formula_score_residual", "formula_conditioned_peak_tokens_for_structure_matching"], "correct_ionic_mass_and_adduct_rules": true, "ambiguous_or_unassigned_state": true, "unsupported_chemistry_masks_only_new_evidence": true, "zero_init_scoring_residuals": true},
46
+ "fragment_simulator": {"enabled": false, "stage": "R2_after_Train_safe_teacher_and_GPU_acceptance"},
47
+ "candidate_relation": {"enabled": false, "stage": "R2_sparse_difference_evidence", "hard_cluster_or_formula_filter": false, "all_candidates_keep_direct_score": true},
48
+ "synthetic_structure_expansion": {"enabled": false, "stage": "R3_separate_data_and_budget_control"}
49
+ },
50
+ "no_reference_formula_in_Mass_inference": true,
51
+ "no_reference_SMILES_or_similarity_in_inference": true,
52
+ "SIRIUS_scores_ranks_CSI_features": false,
53
+ "do_not_add_parent_peak_atom_score_twice": true,
54
+ "calibrate_formula_residual_without_duplicating_parent_prior": true,
55
+ "initial_logits_match_parent_required": true
56
+ },
57
+ "sampling": {
58
+ "odata_effective_batch": 256,
59
+ "MSG_effective_batch": 32,
60
+ "odata_explicit_queries": 16,
61
+ "MSG_negative_draws_per_view": 63,
62
+ "MSG_mix": {"model": 32, "chemical": 16, "random": 15},
63
+ "MSG_model_same_formula_quota_when_available": 16,
64
+ "odata_negative_draws": 128,
65
+ "odata_mix": {"model": 64, "chemical": 32, "random": 32},
66
+ "with_replacement": true,
67
+ "same_key14_never_negative": true,
68
+ "teacher_index_initial_checkpoint": "parent_exact_sha256",
69
+ "teacher_index_refresh_updates": 1000,
70
+ "teacher_max_staleness_updates": 2000,
71
+ "teacher_index_binds_checkpoint_pool_and_rule_hashes": true,
72
+ "teacher_missing_at_start": "fail_acceptance_not_silent_all_random_fallback",
73
+ "teacher_embeddings_only_for_sampling_not_student_backprop": true,
74
+ "sampled_pool_CE_claimed_unbiased_full_pool_likelihood": false,
75
+ "log_unique_key14_and_repetitions": true
76
+ },
77
+ "loss": {
78
+ "inherit_C03_base_objectives_and_weights": true,
79
+ "audit_equal_logits_positive_sets_denominators_no_duplicate_CE": true,
80
+ "final_score_pool_InfoNCE_once": true,
81
+ "grouped_multi_MS_positives": true,
82
+ "same_formula_is_not_structure_positive": true,
83
+ "coarse_formula_positive_loss_on_main_retrieval_embedding": false,
84
+ "formula_head_unique_formula_once": true,
85
+ "formula_supervision_for_all_eligible_queries": true,
86
+ "odata_true_formula_pool_is_not_multiformula_supervision": true,
87
+ "identity_balanced_occurrence_reduction": {"enabled": true, "operator": "logmeanexp_over_sampled_entries_per_key14", "semantics": "loss_weight_normalization_not_deletion_of_assets", "separate_ablation": true},
88
+ "conditional_structure": {"enabled": true, "weight": 0.25, "eligible_view": "mass", "requires_cross_formula_negative": true, "enabled_for_Formula_or_true_formula_odata": false},
89
+ "same_formula_gap": {"enabled": true, "weight": 0.1, "margin": 0.2, "hard_wrong_topk_unique_key14": 3, "score_space": "raw_final_score", "temperature": 1.0},
90
+ "fingerprint_auxiliary": {"enabled": true, "target_weight": 0.1, "ramp_updates": 200, "identity_balanced_mean": true},
91
+ "composition_evidence_additional_duplicate_CE": false,
92
+ "local_path_additional_duplicate_pool_CE": false,
93
+ "missing_positive_masks_positive_dependent_pool_terms": true,
94
+ "competitive_CE_requires_distinct_negative": true,
95
+ "means_and_effective_counts_use_actual_eligible_queries": true,
96
+ "no_positive_injection": true,
97
+ "hyperparameters_are_unvalidated_starting_points": true
98
+ },
99
+ "optimizer": {
100
+ "inherit_family_and_old_moments": true,
101
+ "backbone_lr_multiplier_vs_parent_restored_lr": 0.3,
102
+ "new_module_lr_multiplier_vs_parent_restored_lr": 1.0,
103
+ "warmup_new_or_changed_groups_updates": 200,
104
+ "inherit_gradient_clip": true,
105
+ "same_schedule_in_matched_control": true,
106
+ "joint_update_of_active_tasks": true
107
+ },
108
+ "efficiency": {
109
+ "unique_graph_encode_once_per_step": true,
110
+ "formula_evidence_shared_per_query_formula": true,
111
+ "offline_static_assets_and_annotations": true,
112
+ "no_full_BxBxPxA_tensor": true,
113
+ "candidate_block_size": "measure_on_real_GPU_not_predeclared_as_verified",
114
+ "single_softmax_denominator_across_blocks": true,
115
+ "do_not_detach_trainable_student_embeddings": true,
116
+ "loss_and_logsumexp_fp32": true,
117
+ "profile_data_H2D_compute_sync_and_queue_time": true,
118
+ "walltime_and_memory_claims": null
119
+ },
120
+ "experiment": {
121
+ "pilot_additional_updates": 2000,
122
+ "pilot_final_update": 4000,
123
+ "continuation_max_additional_updates_after_predeclared_selection": 6000,
124
+ "checkpoint_and_lightweight_checks_every_updates": 500,
125
+ "full_Validation_every_updates": 1000,
126
+ "MCES": "asynchronous_fixed_protocol_and_pair_cache_not_every_step",
127
+ "same_parent_seed_query_order_optimizer_and_effective_batch": true,
128
+ "ablation_sequence": ["control", "main_R1", "minus_hard_mixture", "minus_extra_isomer_losses", "minus_reverse_local", "minus_fingerprint", "minus_composition_evidence", "minus_identity_balancing"],
129
+ "later_pilot_winner_repeat_seeds": [20261109, 20261110, 20261111],
130
+ "not_all_arms_started_or_queued": true
131
+ },
132
+ "selection": {
133
+ "split": "MSG_Validation_full",
134
+ "primary": "harmonic_mean_of_Mass_and_Formula_structure_Top1",
135
+ "maximum_per_view_structure_Top1_drop_pp_vs_matched_control": 0.5,
136
+ "maximum_formula_Top1_drop_pp_vs_matched_control": 1.0,
137
+ "maximum_MCES_increase_vs_matched_control_same_valid_queries": 0.2,
138
+ "guardrails_are_predeclared_design_choices_not_significance_bounds": true,
139
+ "formula_scope": "Mass_pool_formula_ranking_not_open_generation",
140
+ "missingness_cannot_be_hidden_by_effective_mean": true,
141
+ "Test_CASMI_used_for_selection": false,
142
+ "formula_and_metadata_strata_reported_separately": true
143
+ },
144
+ "evaluation": {
145
+ "MSG_official_pools_unchanged": true,
146
+ "official_raw_aliases_still_consume_ranks": true,
147
+ "CASMI_frozen_candidates": 1765420,
148
+ "CASMI_truth_coverage": 467,
149
+ "CASMI_n": 500,
150
+ "CASMI_candidate_limit": null,
151
+ "CASMI_truth_injection": false,
152
+ "CASMI_formula_scope": "rerank_fixed_SIRIUS_Top10_not_open_formula_generation",
153
+ "CASMI_frozen_formula_truth_coverage": 468,
154
+ "CASMI_formula_Top10_cannot_improve_by_reranking_same_at_most10_formulas": true,
155
+ "secondary_structure_metrics": ["full_recomputed_InChIKey", "canonical_isomeric_SMILES"],
156
+ "primary_structure_metric": "key14_connectivity",
157
+ "structure_topk": [1,3,5,10,20,50,100,200],
158
+ "formula_topk": [1,2,3,4,5,6,7,8,9,10,20,50,100,200],
159
+ "MCES_missing_not_zero_filled": true,
160
+ "MCES_training_split_filtering_requested": false
161
+ },
162
+ "input_leakage_checks": {
163
+ "stable_hash_candidate_shuffle_without_reference": true,
164
+ "CID_original_position_PubChem_order_as_features": false,
165
+ "candidate_permutation_and_padding_invariance_required": true,
166
+ "all_sources_and_view_loss_weights_exported_from_parent": true,
167
+ "MSG_Validation_claimed_negative_mode_development_set": false,
168
+ "new_negative_development_split_must_audit_parent_training_exposure": true
169
+ },
170
+ "readiness": {
171
+ "config_is_training_entrypoint": false,
172
+ "existing_CPU_helper_tests": 24,
173
+ "formal_trainer_integration": false,
174
+ "Train_only_bound_teacher_index": false,
175
+ "composition_annotation_adapter_and_cache": false,
176
+ "identity_balanced_losses_integrated": false,
177
+ "new_parameter_optimizer_groups_integrated": false,
178
+ "real_student_GPU_forward_backward": false,
179
+ "resume_and_parent_logit_parity_acceptance": false,
180
+ "training_allowed_only_after_all_implementation_gates": true
181
+ }
182
+ }
code/snapshot/root/code/ceir_r1_20261109/prepare-evidence.supervisor.conf ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [program:specpartition-ceir-r1-evidence-20261109]
2
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_20261109
3
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u prepare_ceir.py evidence
4
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
5
+ autostart=false
6
+ autorestart=unexpected
7
+ startsecs=5
8
+ startretries=3
9
+ stopasgroup=true
10
+ killasgroup=true
11
+ stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/prepare_evidence.log
12
+ stderr_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/prepare_evidence_error.log
13
+ stdout_logfile_maxbytes=50MB
14
+ stdout_logfile_backups=2
15
+ stderr_logfile_maxbytes=20MB
16
+
17
+ [program:specpartition-ceir-r1-mining-20261109]
18
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_20261109
19
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u prepare_ceir.py mining
20
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
21
+ autostart=false
22
+ autorestart=unexpected
23
+ startsecs=5
24
+ startretries=3
25
+ stopasgroup=true
26
+ killasgroup=true
27
+ stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/prepare_mining.log
28
+ stderr_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/prepare_mining_error.log
29
+ stdout_logfile_maxbytes=50MB
30
+ stdout_logfile_backups=2
31
+ stderr_logfile_maxbytes=20MB
code/snapshot/root/code/ceir_r1_20261109/prepare_ceir.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resumable offline preparation for exactly the approved 2k continuation.
2
+
3
+ All original candidate pools and all actual formula classes survive. The work
4
+ manifest scopes the new caches to this pilot, not a claim to process unused
5
+ future epochs or the full open-formula search space.
6
+ """
7
+ import argparse
8
+ from collections import Counter,OrderedDict
9
+ from concurrent.futures import ProcessPoolExecutor
10
+ from dataclasses import replace
11
+ import hashlib
12
+ import json
13
+ import multiprocessing
14
+ from pathlib import Path
15
+ import sqlite3
16
+ import time
17
+
18
+ import numpy as np
19
+ from runtime_ceir import *
20
+ from evidence_ceir import annotate, encode, query_key, RULE
21
+ from data09 import Reader, loads
22
+
23
+
24
+ def workload():
25
+ CACHE.mkdir(parents=True,exist_ok=True);path=CACHE/'workload.json'
26
+ plans,binding=pilot_plans()
27
+ if path.exists():
28
+ if json.loads(path.read_text())['binding']!=binding:raise RuntimeError('Pilot workload changed')
29
+ return
30
+ ids={};pool_queries={};identity_graphs={};db=readonly(LEGACY.PREP/'train.sqlite')
31
+ for epoch,step,groups in plans:
32
+ for source,values in groups.items():
33
+ for j,rid in enumerate(values):
34
+ explicit=source=='odata' and j<16
35
+ ids[rid]=dict(source=source,explicit=ids.get(rid,{}).get('explicit',False) or explicit)
36
+ reader=Reader()
37
+ for number,(rid,flags) in enumerate(sorted(ids.items())):
38
+ row=loads(db.execute('SELECT body FROM samples WHERE record_id=?',(rid,)).fetchone()[0])
39
+ if row['identity'] in reader.forbidden:raise RuntimeError('Heldout training label')
40
+ identity_graphs.setdefault(row['identity'],set()).add(row['graph_hash'])
41
+ if row['source']=='MSG_Train':
42
+ for kind in ('mass','formula'):
43
+ key='msg_'+kind+':'+row['target']
44
+ pool_queries.setdefault(key,dict(kind=kind,target=row['target'],record_ids=[]))['record_ids'].append(rid)
45
+ elif flags['explicit'] and row['view']['pool_infonce_eligible']:
46
+ key='odata:'+row['view']['pool_path']
47
+ pool_queries.setdefault(key,dict(kind='odata',path=row['view']['pool_path'],sha256=row['view']['pool_sha256'],record_ids=[]))['record_ids'].append(rid)
48
+ if (number+1)%5000==0:save(CACHE/'workload_status.json',dict(phase='binding_pilot_records',records=number+1,total=len(ids)))
49
+ fingerprint_valid={}
50
+ for identity,graphs in identity_graphs.items():
51
+ fingerprints={hashlib.sha256(reader.molecule(g).whole.astype(np.uint8).tobytes()).hexdigest() for g in graphs}
52
+ fingerprint_valid[identity]=len(fingerprints)==1 and bool(reader.molecule(next(iter(graphs))).whole.sum())
53
+ save(CACHE/'fingerprint_targets.json',dict(valid=fingerprint_valid,scope='all referenced training identities in the approved pilot',
54
+ identities=len(fingerprint_valid),conflicting_or_empty=sum(not x for x in fingerprint_valid.values())))
55
+ counts=Counter(x['source'] for x in ids.values())
56
+ save(path,dict(binding=binding,plans=plans,records=ids,pools=pool_queries,record_counts=dict(counts),
57
+ scope='all actual rows/pools in parent data cursor 2000 to 4000',
58
+ parent_sha256=PLAN['parent']['sha256'],raw_pools_changed=False,
59
+ formula_training_scope='inherited_external_label_conditioned_competition_not_blind_predictions',
60
+ annotations_or_negatives_from_Test_CASMI=False))
61
+ db.close()
62
+
63
+
64
+ def one_annotation(arg):
65
+ query,formulas=arg;key=query_key(query)
66
+ return [(key,f,encode(annotate(query,f))) for f in formulas]
67
+
68
+
69
+ def evidence_tasks(split):
70
+ manifest=json.loads((CACHE/'workload.json').read_text())
71
+ if split=='train':
72
+ reader=Reader();db=reader.db
73
+ for rid in manifest['records']:
74
+ row=loads(db.execute('SELECT body FROM samples WHERE record_id=?',(rid,)).fetchone()[0])
75
+ fs=tuple(reader.official(row['target'],'mass')['formula_classes']) if row['source']=='MSG_Train' else tuple(row['view']['formulas'])
76
+ # Pool formula view may contain classes absent from this specific Mass pool.
77
+ if row['source']=='MSG_Train':fs=tuple(sorted(set(fs)|set(reader.official(row['target'],'formula')['formula_classes'])))
78
+ yield row['query'],fs
79
+ else:
80
+ # Evaluation cache reads only official Validation, never enters mining.
81
+ db=readonly(LEGACY.PREP/'validation.sqlite');fs_by_target={}
82
+ for identifier,target,blob in db.execute('SELECT identifier,target,body FROM spectra ORDER BY identifier'):
83
+ if target not in fs_by_target:
84
+ smiles=set()
85
+ for view in ('mass','formula'):smiles.update(json.loads(db.execute('SELECT body FROM pools WHERE target=? AND view=?',(target,view)).fetchone()[0]))
86
+ fs=set()
87
+ from specpartition_ms.chemistry import canonical_formula,formula_vector
88
+ for s in smiles:
89
+ f=db.execute('SELECT formula FROM aliases WHERE smiles=?',(s,)).fetchone()[0]
90
+ if f:
91
+ try:formula_vector(f);fs.add(canonical_formula(f))
92
+ except ValueError:pass
93
+ fs_by_target[target]=tuple(sorted(fs))
94
+ yield loads(blob)['query'],fs_by_target[target]
95
+
96
+
97
+ def prepare_evidence():
98
+ import zlib
99
+ for split in ('train','validation'):
100
+ marker=CACHE/(split+'_composition_ready.json')
101
+ if marker.exists():
102
+ if json.loads(marker.read_text())['rule']!=RULE:raise RuntimeError('Annotation rule changed')
103
+ continue
104
+ dest=CACHE/(split+'_composition.sqlite');db=sqlite3.connect(dest);db.execute('PRAGMA journal_mode=WAL')
105
+ db.execute('CREATE TABLE IF NOT EXISTS evidence(query_key TEXT,formula TEXT,body BLOB,PRIMARY KEY(query_key,formula))')
106
+ initial_count=db.execute('SELECT COUNT(*) FROM evidence').fetchone()[0];initial_changes=db.total_changes
107
+ started=time.monotonic();n=0;stats=Counter()
108
+ # Small chunks preserve memory and keep at most a few outstanding CPU jobs.
109
+ ctx=multiprocessing.get_context('spawn')
110
+ with ProcessPoolExecutor(max_workers=2,mp_context=ctx) as workers:
111
+ tasks=iter(evidence_tasks(split))
112
+ exhausted=False
113
+ while not exhausted:
114
+ chunk=[]
115
+ for _ in range(128):
116
+ try:q,fs=next(tasks)
117
+ except StopIteration:exhausted=True;break
118
+ key=query_key(q)
119
+ missing=[f for f in fs if not db.execute('SELECT 1 FROM evidence WHERE query_key=? AND formula=?',(key,f)).fetchone()]
120
+ if missing:chunk.append((q,missing))
121
+ n+=1
122
+ for result in workers.map(one_annotation,chunk,chunksize=4):
123
+ for key,f,blob in result:
124
+ db.execute('INSERT OR IGNORE INTO evidence VALUES (?,?,?)',(key,f,blob))
125
+ meta=json.loads(zlib.decompress(blob));stats[meta['reason']]+=1
126
+ stats['matched_peaks']+=meta['matched'];stats['annotated_peaks']+=meta['total']
127
+ db.commit()
128
+ status=dict(phase='offline_composition',split=split,queries_scanned=n,rows=initial_count+db.total_changes-initial_changes,stats=dict(stats),seconds=time.monotonic()-started,rule=RULE)
129
+ save(CACHE/'evidence_status.json',status);print(json.dumps(status),flush=True);check_disk()
130
+ count=db.execute('SELECT COUNT(*) FROM evidence').fetchone()[0]
131
+ db.execute('PRAGMA wal_checkpoint(TRUNCATE)');db.close()
132
+ save(marker,dict(complete=True,rule=RULE,queries_scanned=n,rows=count,stats=dict(stats),
133
+ stats_scope='this_run_generated_annotations_including_duplicate_requests_not_unique_cache_rows',
134
+ workload_binding=json.loads((CACHE/'workload.json').read_text())['binding']))
135
+
136
+
137
+ def get_pool(reader, group, row=None):
138
+ if group['kind']!='odata':
139
+ pool=reader.official(group['target'],group['kind'])
140
+ entries=pool['entries'];indices=[i for i,e in enumerate(entries) if e['eligible_for_training']]
141
+ return pool,entries,indices
142
+ pool=reader.pool(group['path'],group['sha256']);entries=pool['records']
143
+ indices=pool['safe_mass_order']
144
+ return pool,entries,indices
145
+
146
+
147
+ def entry_identity(entry):return entry.get('identity',entry.get('connectivity'))
148
+ def entry_formula(entry):return entry['formula']
149
+ def entry_molecule(reader,entry):
150
+ # External PubChem records preserve both raw and canonical SMILES; the
151
+ # accepted R08 feature store is keyed by canonical_smiles, exactly as data09.
152
+ return reader.molecule(entry['graph_hash']) if entry.get('graph_hash') else reader.by_smiles(entry.get('canonical_smiles') or entry.get('smiles'))
153
+
154
+
155
+ def load_teacher(checkpoint_path=None):
156
+ import torch
157
+ from coarse_losses import ProjectionBank
158
+ from kernels import install_graph_kernel
159
+ if checkpoint_path is not None:
160
+ from model_ceir import CEIRRanker
161
+ state=torch.load(checkpoint_path,map_location='cpu',weights_only=False)
162
+ if state.get('architecture')!='CEIR_R1' or state['binding']['parent_sha256']!=PLAN['parent']['sha256']:
163
+ raise RuntimeError('Refresh checkpoint lineage mismatch')
164
+ model=CEIRRanker(LEGACY.C,'main');model.load_state_dict(state['model'],strict=True)
165
+ model.install_evidence(False);model.to(LEGACY.C['device']);model.eval();model.graph_chunk=128
166
+ return model
167
+ state=source_state();model=LEGACY.make_model();model.hierarchy=ProjectionBank()
168
+ model.load_state_dict(state['model'],strict=True);install_graph_kernel(model)
169
+ model.graph_chunk=128;model.local_chunk=128
170
+ model.to(LEGACY.C['device']);model.eval();del state
171
+ return model
172
+
173
+
174
+ def teacher_local_batch(model,tokens,atoms):
175
+ """Bounded frozen-teacher QxMxPxA tile; not full student BxB alignment."""
176
+ import torch
177
+ from torch.nn import functional as F
178
+ from torch.nn.utils.rnn import pad_sequence
179
+ qp=pad_sequence([F.normalize(model.local_q(t.float()).float(),dim=-1) for t in tokens],batch_first=True)
180
+ lengths=torch.tensor([len(t) for t in tokens],device=model.device)
181
+ aa=pad_sequence([a.float() for a in atoms],batch_first=True);za=F.normalize(model.local_a(aa).float(),dim=-1)
182
+ valid=torch.arange(aa.shape[1],device=model.device)[None,:]<torch.tensor([len(a) for a in atoms],device=model.device)[:,None]
183
+ cosine=(qp.reshape(-1,qp.shape[-1])@za.reshape(-1,za.shape[-1]).T).reshape(qp.shape[0],qp.shape[1],za.shape[0],za.shape[1])
184
+ best=cosine.masked_fill(~valid[None,None,:,:],-torch.inf).max(-1).values
185
+ pmask=torch.arange(qp.shape[1],device=model.device)[None,:]<lengths[:,None]
186
+ return (best*pmask[:,:,None]).sum(1)/lengths[:,None]
187
+
188
+
189
+ class FrozenGraphCache:
190
+ """Exact-dtype CPU cache for this one frozen teacher; never a student cache."""
191
+ def __init__(self,model):
192
+ self.model=model;self.values=OrderedDict();self.bytes=0;self.maximum=384*2**20
193
+ self.hits=0;self.encoded=0
194
+
195
+ def encode(self,mols):
196
+ import torch
197
+ keys=[(m.identity,m.smiles) for m in mols]
198
+ missing={key:m for key,m in zip(keys,mols) if key not in self.values}
199
+ self.hits+=sum(key in self.values for key in keys)
200
+ if missing:
201
+ kk=sorted(missing);_,atoms,zm=self.model.encode_molecules([missing[k] for k in kk])
202
+ for i,key in enumerate(kk):
203
+ pair=(atoms[i].detach().cpu(),zm[i].detach().cpu())
204
+ self.values[key]=pair;self.bytes+=sum(t.numel()*t.element_size() for t in pair);self.encoded+=1
205
+ items=[]
206
+ for key in keys:
207
+ self.values.move_to_end(key);items.append(self.values[key])
208
+ sizes=[len(v[0]) for v in items]
209
+ all_atoms=torch.cat([v[0] for v in items]).to(self.model.device)
210
+ zm=torch.stack([v[1] for v in items]).to(self.model.device)
211
+ while self.bytes>self.maximum:
212
+ _,pair=self.values.popitem(last=False);self.bytes-=sum(t.numel()*t.element_size() for t in pair)
213
+ return list(all_atoms.split(sizes)),zm
214
+
215
+
216
+ def shortlist_update(current,scores,indices,identities,limit=64):
217
+ # Sampling identities, not deleting original candidate assets.
218
+ best={key:(float(score),int(index)) for key,score,index in current}
219
+ for score,index,identity in zip(scores,indices,identities):
220
+ value=(float(score),int(index))
221
+ if identity not in best or value[0]>best[identity][0] or (value[0]==best[identity][0] and value[1]<best[identity][1]):best[identity]=value
222
+ return [(key,v[0],v[1]) for key,v in sorted(best.items(),key=lambda x:(-x[1][0],x[0],x[1][1]))[:limit]]
223
+
224
+
225
+ def prepare_mining(checkpoint_path=None):
226
+ import torch
227
+ from specpartition_ms.fast_formula_r2 import forward_batch
228
+ setup_gpu();torch.set_float32_matmul_precision('highest')
229
+ manifest=json.loads((CACHE/'workload.json').read_text());reader=Reader()
230
+ source_update=SOURCE_UPDATE;checkpoint_sha=PLAN['parent']['sha256']
231
+ if checkpoint_path is not None:
232
+ source_update=int(torch.load(checkpoint_path,map_location='cpu',weights_only=False)['progress']['update'])
233
+ checkpoint_sha=sha(checkpoint_path)
234
+ retained={rid for _,_,p in manifest['plans'][source_update-SOURCE_UPDATE:] for values in p.values() for rid in values}
235
+ manifest['pools']={key:{**g,'record_ids':[rid for rid in g['record_ids'] if rid in retained]} for key,g in manifest['pools'].items()}
236
+ manifest['pools']={key:g for key,g in manifest['pools'].items() if g['record_ids']}
237
+ path=CACHE/('teacher_parent.sqlite' if checkpoint_path is None else 'teacher_%06d.sqlite'%source_update)
238
+ ready_path=CACHE/('teacher_ready.json' if checkpoint_path is None else 'teacher_%06d_ready.json'%source_update)
239
+ if ready_path.exists():
240
+ marker=json.loads(ready_path.read_text())
241
+ if marker.get('teacher_checkpoint_sha256',marker['parent_sha256'])!=checkpoint_sha:raise RuntimeError('Teacher version changed')
242
+ return
243
+ out=sqlite3.connect(path);out.execute('PRAGMA journal_mode=WAL')
244
+ # Retain pre-v2 rows as diagnostic evidence; never mix their precision route.
245
+ out.execute('CREATE TABLE IF NOT EXISTS hard_fp32(record_id TEXT,kind TEXT,body TEXT,PRIMARY KEY(record_id,kind))')
246
+ with gpu_work(CACHE,'initial_teacher_load'):model=load_teacher(checkpoint_path)
247
+ graph_cache=FrozenGraphCache(model)
248
+ order={rid:i for i,rid in enumerate(manifest['records'])}
249
+ groups=sorted(manifest['pools'].items(),key=lambda pair:min(order[r] for r in pair[1]['record_ids']))
250
+ started=time.monotonic();completed=0;local_checked=False
251
+ for gi,(poolkey,group) in enumerate(groups):
252
+ if checkpoint_path is not None and (OUT/'main/step_004000.pt').exists():
253
+ save(CACHE/'refresh_status.json',dict(phase='stopped_at_approved_training_endpoint',source_update=source_update,unix_time=time.time()))
254
+ out.close();return
255
+ kind=group['kind'];todo=[rid for rid in group['record_ids'] if not out.execute('SELECT 1 FROM hard_fp32 WHERE record_id=? AND kind=?',(rid,kind)).fetchone()]
256
+ if not todo:completed+=len(group['record_ids']);continue
257
+ pool,entries,eligible=get_pool(reader,group)
258
+ pool_sha=group['sha256'] if kind=='odata' else hashlib.sha256(json.dumps(pool,sort_keys=True,separators=(',',':')).encode()).hexdigest()
259
+ rows=[loads(reader.db.execute('SELECT body FROM samples WHERE record_id=?',(rid,)).fetchone()[0]) for rid in todo]
260
+ refs=[reader.molecule(r['graph_hash']) for r in rows]
261
+ # Each group is reused across its real spectra; query batching bounds memory.
262
+ for qstart in range(0,len(rows),16):
263
+ rr=rows[qstart:qstart+16];ref=refs[qstart:qstart+16];rids=todo[qstart:qstart+16]
264
+ fs=tuple(pool['formula_classes']) if kind!='odata' else tuple(sorted({entry_formula(entries[i]) for i in eligible}))
265
+ queries=[replace(r['query'],formula_candidates=fs) for r in rr]
266
+ with gpu_work(CACHE,'teacher_query_encode'),torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):
267
+ tokens,qs,_=model.spectrum.forward_batch(queries)
268
+ if checkpoint_path is None:
269
+ formula_scores=forward_batch(model.formula_v07,qs,queries,tokens);contexts=None
270
+ else:formula_scores,contexts=model.formula_batch(qs,queries,tokens,True)
271
+ tops=[dict(global_scores=[],same_scores=[],chemical=[]) for _ in rr]
272
+ allowed=[]
273
+ for r in rr:
274
+ allowed.append(set(eligible if kind!='odata' else pool['safe_mass_order'][r['view']['mass_order_start']:r['view']['mass_order_stop']]))
275
+ same_available=[any(entry_formula(entries[j])==r['formula'] and entry_identity(entries[j])!=r['identity'] for j in a) for r,a in zip(rr,allowed)]
276
+ for start in range(0,len(eligible),128):
277
+ inds=eligible[start:start+128];mols=[entry_molecule(reader,entries[j]) for j in inds]
278
+ whole=np.stack([m.whole for m in mols]);ids=[m.identity for m in mols];forms=[m.formula for m in mols]
279
+ with gpu_work(CACHE,'teacher_candidate_block'),torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):
280
+ atoms,zm=graph_cache.encode(mols)
281
+ if checkpoint_path is None:
282
+ with torch.autocast('cuda',enabled=False):
283
+ local_values=teacher_local_batch(model,tokens,atoms)
284
+ if not local_checked and len(atoms)>=32 and len(tokens)>=2:
285
+ error=(local_values[0]-model.local_scores(tokens[0].float(),[a.float() for a in atoms])).abs().max().item()
286
+ if error>1e-5:raise RuntimeError('Batched FP32 teacher local-score parity failed: '+str(error))
287
+ save(CACHE/'teacher_kernel_parity.json',dict(max_abs_error=error,tolerance=1e-5,queries=len(tokens),candidates=len(atoms),precision='FP32_local_BF16_GNN',complete=True))
288
+ local_checked=True
289
+ all_scores=[]
290
+ for qi,q in enumerate(queries):
291
+ if checkpoint_path is None:
292
+ _,joint,_=model.conditioned(qs[qi],q,forms,zm,formula_scores[qi])
293
+ all_scores.append((joint+model.local_weight*local_values[qi]).float())
294
+ else:
295
+ score,_,_=model.score_encoded(qs[qi],tokens[qi],q,mols,atoms,zm,formula_scores[qi],contexts[qi])
296
+ all_scores.append(score.float())
297
+ values=torch.stack(all_scores).cpu().numpy()
298
+ for qi,(r,target) in enumerate(zip(rr,ref)):
299
+ valid=[j for j,index in enumerate(inds) if index in allowed[qi] and ids[j]!=r['identity']]
300
+ if not valid:continue
301
+ jj=[inds[j] for j in valid];kk=[ids[j] for j in valid];ss=values[qi,valid]
302
+ tops[qi]['global_scores']=shortlist_update(tops[qi]['global_scores'],ss,jj,kk)
303
+ same=[j for j in valid if forms[j]==r['formula']]
304
+ tops[qi]['same_scores']=shortlist_update(tops[qi]['same_scores'],values[qi,same],[inds[j] for j in same],[ids[j] for j in same])
305
+ chem_indices=same if same_available[qi] else valid
306
+ inter=whole[chem_indices]@target.whole;union=whole[chem_indices].sum(1)+target.whole.sum()-inter
307
+ sim=inter/np.maximum(union,1e-8)
308
+ tops[qi]['chemical']=shortlist_update(tops[qi]['chemical'],sim,[inds[j] for j in chem_indices],[ids[j] for j in chem_indices])
309
+ del mols,atoms,zm
310
+ for qi,(rid,r,top) in enumerate(zip(rids,rr,tops)):
311
+ has_positive=any(entry_identity(entries[j])==r['identity'] for j in allowed[qi])
312
+ has_negative=any(entry_identity(entries[j])!=r['identity'] for j in allowed[qi])
313
+ pool_eligible=has_positive and has_negative
314
+ if pool_eligible and not top['global_scores']:raise RuntimeError('Missing teacher negatives despite a valid original competition pool')
315
+ value=dict(parent_sha256=PLAN['parent']['sha256'],source_update=source_update,pool_key=poolkey,
316
+ teacher_checkpoint_sha256=checkpoint_sha,
317
+ precision='FP32_local_BF16_GNN' if checkpoint_path is None else 'CEIR_R1_mixed_precision',kernel_version=2,
318
+ pool_eligible=pool_eligible,masked_reason=None if pool_eligible else 'original_pool_missing_positive_or_distinct_negative',
319
+ pool_sha256=pool_sha,pool_count=len(entries),eligible_count=len(eligible),query_key=query_key(r['query']),
320
+ candidates_scored_without_cap=len(eligible),top=top,truth_never_injected=True)
321
+ out.execute('INSERT OR REPLACE INTO hard_fp32 VALUES (?,?,?)',(rid,kind,json.dumps(value,separators=(',',':'))))
322
+ out.commit();completed+=len(rr)
323
+ status=dict(phase='Train_only_full_pool_teacher_mining',groups=gi+1,total_groups=len(groups),queries=completed,
324
+ seconds=time.monotonic()-started,parent_sha256=PLAN['parent']['sha256'],
325
+ frozen_teacher_graphs_encoded=graph_cache.encoded,graph_cache_hits=graph_cache.hits,
326
+ graph_cache_cpu_mib=graph_cache.bytes/2**20,student_embeddings_cached=False)
327
+ save(CACHE/('mining_status.json' if checkpoint_path is None else 'refresh_status.json'),status);print(json.dumps(status),flush=True);check_disk()
328
+ count=out.execute('SELECT COUNT(*) FROM hard_fp32').fetchone()[0]
329
+ expected=sum(len(g['record_ids']) for g in manifest['pools'].values())
330
+ if count!=expected:raise RuntimeError('Incomplete teacher index')
331
+ eligible_queries=sum(json.loads(r[0]).get('pool_eligible',True) for r in out.execute('SELECT body FROM hard_fp32'))
332
+ out.execute('PRAGMA wal_checkpoint(TRUNCATE)');out.close()
333
+ save(ready_path,dict(complete=True,queries=count,expected=expected,parent_sha256=PLAN['parent']['sha256'],
334
+ teacher_checkpoint_sha256=checkpoint_sha,source_update=source_update,
335
+ eligible_teacher_queries=eligible_queries,masked_noncompetitive_queries=expected-eligible_queries,
336
+ workload_binding=manifest['binding'],full_original_eligible_pools_scored=True,Test_or_CASMI_read=False,
337
+ mining_source='actual_fixed_parent_final_score_not_global_embedding_surrogate'))
338
+
339
+
340
+ if __name__=='__main__':
341
+ p=argparse.ArgumentParser();p.add_argument('phase',choices=['workload','evidence','mining']);p.add_argument('--teacher-checkpoint');a=p.parse_args()
342
+ OUT.mkdir(parents=True,exist_ok=True);CACHE.mkdir(parents=True,exist_ok=True)
343
+ if a.phase=='workload':workload()
344
+ elif a.phase=='evidence':prepare_evidence()
345
+ else:prepare_mining(a.teacher_checkpoint)
code/snapshot/root/code/ceir_r1_20261109/reference/diagnosis.json ADDED
The diff for this file is too large to render. See raw diff
 
code/snapshot/root/code/ceir_r1_20261109/refresh_ceir.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Managed asynchronous Train-only refresh at the 1000th continuation update."""
2
+ import json
3
+ import subprocess
4
+ import sys
5
+ import time
6
+ from runtime_ceir import *
7
+
8
+
9
+ def run():
10
+ path=OUT/'main/step_003000.pt'
11
+ while not path.exists():
12
+ if (OUT/'main/COMPLETE.json').exists():return
13
+ save(CACHE/'refresh_status.json',dict(phase='waiting_for_main_update_3000',unix_time=time.time()))
14
+ time.sleep(15)
15
+ if (OUT/'main/step_004000.pt').exists():return
16
+ save(CACHE/'refresh_request.json',dict(checkpoint=str(path),sha256=sha(path),source_update=3000,
17
+ allowed_splits=['MSG_Train','MSP_libraries','MS2_SAN_JSONL'],maximum_initial_teacher_age=2000,unix_time=time.time()))
18
+ subprocess.run([sys.executable,'-u',str(HERE/'prepare_ceir.py'),'mining','--teacher-checkpoint',str(path)],check=True,cwd=HERE)
19
+
20
+
21
+ if __name__=='__main__':run()
code/snapshot/root/code/ceir_r1_20261109/runtime_ceir.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Isolated CEIR runtime. Original sources, datasets and services are read-only."""
2
+ import contextlib
3
+ import fcntl
4
+ import hashlib
5
+ import importlib.util
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import random
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import time
14
+
15
+ HERE = Path(__file__).resolve().parent
16
+ PLAN = json.loads((HERE / 'plan.json').read_text())
17
+ ROOT = Path(os.environ.get('SPECPARTITION_ROOT', '/workspace/xj/SpecPartition-MS'))
18
+ OUT = Path(os.environ.get('CEIR_OUTPUT', '/root/xj/SpecPartition-MS/runs/ceir_r1_20261109'))
19
+ CACHE = OUT / 'prepared'
20
+ SEED = 20261103 # resume the actual parent's query order, not a new source epoch
21
+ SOURCE_UPDATE = 2000
22
+ TARGET_UPDATE = 4000
23
+ sys.path.insert(0, str(ROOT / 'rebuild/hierarchical_training_20261103'))
24
+ import runtime_hier as parent_runtime
25
+ SPEC, PARENT_RESOLVED, _, LEGACY = parent_runtime.bootstrap('C03_both_fine')
26
+ LEGACY.C.update(threads=1, workers=1, spectrum_chunk=16, graph_chunk=32,
27
+ local_chunk=32, pool_micro_views=1, validation_batch_views=4,
28
+ max_atoms_per_microbatch=4000)
29
+ from runtime09 import readonly, save, sha
30
+
31
+
32
+ def load_module(name, path):
33
+ spec = importlib.util.spec_from_file_location(name, path)
34
+ module = importlib.util.module_from_spec(spec)
35
+ sys.modules[name] = module
36
+ spec.loader.exec_module(module)
37
+ return module
38
+
39
+
40
+ def code_manifest():
41
+ # macOS AppleDouble metadata is not source code and is never a binding input.
42
+ files = sorted(p for suffix in ('*.py','*.conf') for p in HERE.glob(suffix) if not p.name.startswith('.')) + [HERE/'plan.json']
43
+ return {p.name: sha(p) for p in files}
44
+
45
+
46
+ def source_state():
47
+ import torch
48
+ path = Path(PLAN['parent']['checkpoint'])
49
+ if sha(path) != PLAN['parent']['sha256']:
50
+ raise RuntimeError('Not the fixed C03 2k checkpoint')
51
+ state = torch.load(path, map_location='cpu', weights_only=False)
52
+ if state['progress']['update'] != SOURCE_UPDATE:
53
+ raise RuntimeError('Wrong source update')
54
+ data_binding = LEGACY.bind()
55
+ if state['binding']['data'] != data_binding:
56
+ raise RuntimeError('Original immutable training input binding changed')
57
+ return state
58
+
59
+
60
+ def pilot_plans():
61
+ from sampling import epoch_plans, plan_hash
62
+ state = source_state(); progress = state['progress']; del state
63
+ epoch, offset = progress['epoch'], progress['next_step']
64
+ result=[]; epochs=[]
65
+ while len(result) < TARGET_UPDATE-SOURCE_UPDATE:
66
+ pp=epoch_plans(epoch, SEED)
67
+ original = ROOT/'runs/hierarchical_intra_modal_20261103/C03_both_fine'/('seed_%d'%SEED)/('sampler_epoch_%02d.json'%epoch)
68
+ digest=plan_hash(pp)
69
+ if original.exists() and json.loads(original.read_text())['sha256'] != digest:
70
+ raise RuntimeError('Parent sampler hash mismatch')
71
+ epochs.append(dict(epoch=epoch,sha256=digest,steps=len(pp)))
72
+ result.extend(pp[offset:offset+TARGET_UPDATE-SOURCE_UPDATE-len(result)])
73
+ epoch+=1;offset=0
74
+ h=hashlib.sha256(json.dumps(result,separators=(',',':'),sort_keys=True).encode()).hexdigest()
75
+ return result, dict(sha256=h,epochs=epochs,steps=len(result),source_update=SOURCE_UPDATE,target_update=TARGET_UPDATE)
76
+
77
+
78
+ def run_dir(arm):
79
+ if arm not in ('main','control'):raise ValueError('Unknown CEIR arm')
80
+ p=OUT/arm;p.mkdir(parents=True,exist_ok=True);return p
81
+
82
+
83
+ def gpu_info():
84
+ result=subprocess.run(['nvidia-smi','--query-gpu=memory.free,utilization.gpu',
85
+ '--format=csv,noheader,nounits'],capture_output=True,text=True,check=True)
86
+ free,util=result.stdout.strip().splitlines()[0].split(',')
87
+ return dict(free_mib=int(free),utilization=int(util))
88
+
89
+
90
+ @contextlib.contextmanager
91
+ def gpu_work(directory, phase, minimum_free_mib=5500):
92
+ """Only new CEIR jobs share these slots; never acquire/alter old jobs' locks."""
93
+ locks=OUT/'gpu_slots';locks.mkdir(parents=True,exist_ok=True)
94
+ streams=[(locks/('slot_%d.lock'%i)).open('a+') for i in range(2)]
95
+ held=None
96
+ try:
97
+ while held is None:
98
+ info=gpu_info()
99
+ if info['free_mib'] >= minimum_free_mib:
100
+ for stream in streams:
101
+ try:fcntl.flock(stream,fcntl.LOCK_EX|fcntl.LOCK_NB);held=stream;break
102
+ except BlockingIOError:pass
103
+ if held is None:
104
+ save(Path(directory)/'resource_status.json',dict(phase=phase,state='waiting_for_spare_GPU_memory',**info,unix_time=time.time()))
105
+ time.sleep(5)
106
+ save(Path(directory)/'resource_status.json',dict(phase=phase,state='GPU_work',**info,unix_time=time.time()))
107
+ yield
108
+ finally:
109
+ import torch
110
+ if torch.cuda.is_initialized():torch.cuda.empty_cache()
111
+ if held is not None:fcntl.flock(held,fcntl.LOCK_UN)
112
+ for stream in streams:stream.close()
113
+
114
+
115
+ def setup_gpu():
116
+ import torch
117
+ torch.set_num_threads(1);torch.set_float32_matmul_precision('high')
118
+ torch.use_deterministic_algorithms(True)
119
+ torch.cuda.set_per_process_memory_fraction(.11)
120
+ LEGACY.seed_all(SEED)
121
+
122
+
123
+ def restore_rng(state):
124
+ import numpy as np
125
+ import torch
126
+ torch.set_rng_state(state['torch_rng']);torch.cuda.set_rng_state_all(state['cuda_rng'])
127
+ np.random.set_state(state['numpy_rng']);random.setstate(state['python_rng'])
128
+
129
+
130
+ def bind():
131
+ dependencies={}
132
+ for base in (LEGACY.V09/'src/specpartition_ms',LEGACY.R2/'src/specpartition_ms',
133
+ ROOT/'rebuild/hierarchical_training_20261103',ROOT/'rebuild/intra_modal_extension'):
134
+ for file in sorted(base.glob('*.py')):dependencies[str(file)]=sha(file)
135
+ return dict(plan_sha256=sha(HERE/'plan.json'),code=code_manifest(),
136
+ parent_sha256=PLAN['parent']['sha256'],data=LEGACY.bind(),
137
+ dependency_sources=dependencies,
138
+ prepared_asset_manifest_sha256=sha(CACHE/'ASSET_MANIFEST.json') if (CACHE/'ASSET_MANIFEST.json').exists() else None,
139
+ workload=json.loads((CACHE/'workload.json').read_text())['binding'])
140
+
141
+
142
+ def check_disk():
143
+ if shutil.disk_usage(OUT).free < 8*2**30:
144
+ raise RuntimeError('CEIR output filesystem reserve <8GiB; no old files deleted')
145
+
146
+
147
+ def log_event(path, value):
148
+ value=dict(unix_time=time.time(),**value)
149
+ with Path(path).open('a') as f:f.write(json.dumps(value,allow_nan=False)+'\n')
150
+
151
+
152
+ def checkpoint(path, model, optimizer, progress, binding):
153
+ import numpy as np
154
+ import torch
155
+ path=Path(path);tmp=path.with_suffix(path.suffix+'.tmp')
156
+ torch.save(dict(model=model.state_dict(),optimizer=optimizer.state_dict(),progress=progress,
157
+ binding=binding,torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all(),
158
+ numpy_rng=np.random.get_state(),python_rng=random.getstate(),architecture='CEIR_R1'),tmp)
159
+ tmp.replace(path)
code/snapshot/root/code/ceir_r1_20261109/sampling_ledger_ceir.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Append-only teacher-version decisions, including prefetched/replayed batches."""
2
+ import hashlib
3
+ import json
4
+ from pathlib import Path
5
+ import sqlite3
6
+ import uuid
7
+
8
+
9
+ class SamplingLedger:
10
+ def __init__(self,path,binding):
11
+ self.path=Path(path);self.path.parent.mkdir(parents=True,exist_ok=True)
12
+ marker=self.path.with_suffix('.binding.json')
13
+ old=json.loads(marker.read_text()) if marker.exists() else None
14
+ if old is not None and not self.path.exists():raise RuntimeError('Sampling ledger was lost; refuse a different replay')
15
+ self.db=sqlite3.connect(self.path,timeout=60)
16
+ self.db.execute('PRAGMA journal_mode=WAL')
17
+ self.db.execute('CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,body TEXT)')
18
+ self.db.execute('CREATE TABLE IF NOT EXISTS pins(record_id TEXT,kind TEXT,seed INTEGER,source_update INTEGER,row_sha256 TEXT,PRIMARY KEY(record_id,kind,seed))')
19
+ found=self.db.execute("SELECT body FROM metadata WHERE key='binding'").fetchone()
20
+ if found is None:
21
+ if old is not None:raise RuntimeError('Sampling ledger metadata was lost')
22
+ self.metadata=dict(schema_version=1,ledger_uuid=uuid.uuid4().hex,binding=binding)
23
+ self.db.execute('INSERT INTO metadata VALUES (?,?)',('binding',json.dumps(self.metadata,sort_keys=True)))
24
+ self.db.commit()
25
+ else:self.metadata=json.loads(found[0])
26
+ if self.metadata['binding']!=binding or self.metadata['schema_version']!=1:raise RuntimeError('Sampling ledger binding changed')
27
+ if old is not None and old!=self.metadata:raise RuntimeError('Sampling ledger identity changed')
28
+ if old is None:
29
+ temporary=marker.with_suffix('.tmp');temporary.write_text(json.dumps(self.metadata,indent=2)+'\n');temporary.replace(marker)
30
+
31
+ def select(self,record_id,kind,seed,load_version,choose):
32
+ key=(record_id,kind,int(seed))
33
+ pinned=self.db.execute('SELECT source_update,row_sha256 FROM pins WHERE record_id=? AND kind=? AND seed=?',key).fetchone()
34
+ if pinned is not None:
35
+ version,digest=pinned;body=load_version(version)
36
+ if body is None or hashlib.sha256(body.encode()).hexdigest()!=digest:
37
+ raise RuntimeError('A pinned teacher row disappeared or changed')
38
+ else:
39
+ version,body=choose()
40
+ if body is None:raise RuntimeError('No prepared teacher row for sampling')
41
+ digest=hashlib.sha256(body.encode()).hexdigest()
42
+ self.db.execute('INSERT INTO pins VALUES (?,?,?,?,?)',(*key,version,digest))
43
+ return version,body
44
+
45
+ def commit(self):self.db.commit()
46
+
47
+ def close(self):self.db.close()
code/snapshot/root/code/ceir_r1_20261109/test_comparison_ceir.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import json
3
+ from pathlib import Path
4
+ import tempfile
5
+ import unittest
6
+ from comparison_ceir import build,paired_mces,write
7
+
8
+
9
+ class ComparisonTests(unittest.TestCase):
10
+ def fixture(self,out,update,arm,score,binding='same'):
11
+ directory=out/arm/('validation_update_%06d'%update);directory.mkdir(parents=True)
12
+ metric=dict(spectra=19429,structure={'1':{'micro':score}},formula={'1':{'micro':.7}})
13
+ (directory/'metrics.json').write_text(json.dumps(dict(mass=metric,formula=metric,binding={'runtime':binding})))
14
+ with gzip.open(directory/'MCES_per_spectrum.json.gz','wt') as f:
15
+ json.dump([dict(identifier=str(i),view=v,distance=10.) for v in ('mass','formula') for i in range(19429)],f)
16
+ return directory
17
+
18
+ def test_no_metrics_cannot_be_complete(self):
19
+ with tempfile.TemporaryDirectory() as d:
20
+ r=build(d);self.assertFalse(r['complete']);self.assertIsNone(r['recommended_main_checkpoint_update'])
21
+
22
+ def test_matched_improvement_and_no_automatic_extra_training(self):
23
+ with tempfile.TemporaryDirectory() as d:
24
+ out=Path(d)
25
+ for update in (3000,4000):
26
+ for arm,p in [('main',.3),('control',.2)]:self.fixture(out,update,arm,p)
27
+ r=write(out);self.assertTrue(r['complete']);self.assertEqual(r['recommended_main_checkpoint_update'],4000)
28
+ self.assertAlmostEqual(r['pairs']['3000']['structure_delta_pp']['mass']['1'],10.)
29
+ self.assertFalse(r['additional_training_authorized'])
30
+
31
+ def test_missing_mces_not_zero_and_guardrail_blocked(self):
32
+ with tempfile.TemporaryDirectory() as d:
33
+ out=Path(d);a=self.fixture(out,3000,'main',.3);b=self.fixture(out,3000,'control',.2)
34
+ with gzip.open(a/'MCES_per_spectrum.json.gz','wt') as f:
35
+ json.dump([dict(identifier=str(i),view=v,distance=None) for v in ('mass','formula') for i in range(19429)],f)
36
+ r=paired_mces(a,b)
37
+ self.assertIsNone(r['mass']['main_common_mean']);self.assertEqual(r['mass']['main_missing'],19429)
38
+ self.assertFalse(build(out)['pairs']['3000']['all_guardrails_passed'])
39
+
40
+ def test_changed_data_binding_refused(self):
41
+ with tempfile.TemporaryDirectory() as d:
42
+ out=Path(d);self.fixture(out,3000,'main',.3,'one');self.fixture(out,3000,'control',.2,'two')
43
+ with self.assertRaises(RuntimeError):build(out)
44
+
45
+
46
+ if __name__=='__main__':unittest.main()
code/snapshot/root/code/ceir_r1_20261109/test_evidence_ceir.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from types import SimpleNamespace
3
+ import numpy as np
4
+ from evidence_ceir import annotate,encode,decode,counts,MASSES,ELEMENTS,ELECTRON,query_key
5
+
6
+
7
+ def query(mz,adduct='[M+H]+'):
8
+ return SimpleNamespace(peaks=((mz,100.),(mz/2,20.)),precursor_mz=mz,adduct=adduct,collision_energy=None,instrument=None)
9
+
10
+
11
+ class EvidenceTests(unittest.TestCase):
12
+ def test_protonated_precursor_count_and_electron_mass(self):
13
+ mass=counts('CH4')@MASSES+MASSES[ELEMENTS.index('H')]-ELECTRON
14
+ result=annotate(query(mass),'CH4')
15
+ self.assertTrue(result['available']);self.assertGreaterEqual(result['matched'],1)
16
+ np.testing.assert_allclose(result['features'][0,:13],np.log1p(counts('CH5')),atol=1e-6)
17
+
18
+ def test_negative_ion_mass(self):
19
+ mass=counts('C2H6O')@MASSES-MASSES[ELEMENTS.index('H')]+ELECTRON
20
+ result=annotate(query(mass,'[M-H]-'),'C2H6O')
21
+ self.assertTrue(result['available']);self.assertGreaterEqual(result['matched'],1)
22
+ self.assertEqual(result['features'][0,29],-.5)
23
+
24
+ def test_sodium_retention(self):
25
+ mass=counts('C2H6O')@MASSES+MASSES[ELEMENTS.index('Na')]-ELECTRON
26
+ result=annotate(query(mass,'[M+Na]+'),'C2H6O')
27
+ self.assertGreaterEqual(result['matched'],1)
28
+ self.assertGreater(result['features'][0,ELEMENTS.index('Na')],0.)
29
+
30
+ def test_unknown_adduct_is_mask_not_coercion(self):
31
+ result=annotate(query(100.,'[M+K]+'),'C2H6O')
32
+ self.assertFalse(result['available']);self.assertFalse(result['valid'].any())
33
+
34
+ def test_wire_roundtrip_and_no_identity(self):
35
+ result=annotate(query(31.018),'C2H6O');restored=decode(encode(result))
36
+ np.testing.assert_allclose(restored['features'],result['features'],atol=.002)
37
+ np.testing.assert_array_equal(restored['valid'],result['valid'])
38
+ self.assertEqual(restored['available'],result['available'])
39
+
40
+ def test_peak_order_invariance(self):
41
+ q=query(47.049);r=query(47.049);r.peaks=tuple(reversed(r.peaks))
42
+ self.assertEqual(query_key(q),query_key(r))
43
+ np.testing.assert_array_equal(annotate(q,'C2H6O')['features'],annotate(r,'C2H6O')['features'])
44
+
45
+
46
+ if __name__=='__main__':unittest.main()
code/snapshot/root/code/ceir_r1_20261109/test_sampling_ledger_ceir.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import tempfile
3
+ import unittest
4
+ from sampling_ledger_ceir import SamplingLedger
5
+
6
+
7
+ class LedgerTests(unittest.TestCase):
8
+ def test_newly_available_teacher_does_not_change_replayed_query(self):
9
+ with tempfile.TemporaryDirectory() as d:
10
+ path=Path(d)/'sampling.sqlite';banks={2000:'old'}
11
+ ledger=SamplingLedger(path,{'parent':'fixed'})
12
+ self.assertEqual(ledger.select('r','mass',4,banks.get,lambda:(2000,banks[2000])),(2000,'old'))
13
+ ledger.commit();identity=ledger.metadata['ledger_uuid'];ledger.close()
14
+ banks[3000]='new';ledger=SamplingLedger(path,{'parent':'fixed'})
15
+ self.assertEqual(ledger.metadata['ledger_uuid'],identity)
16
+ self.assertEqual(ledger.select('r','mass',4,banks.get,lambda:(3000,banks[3000])),(2000,'old'))
17
+ self.assertEqual(ledger.select('next','mass',5,banks.get,lambda:(3000,banks[3000])),(3000,'new'))
18
+ ledger.close()
19
+
20
+ def test_modified_pinned_bank_row_is_refused(self):
21
+ with tempfile.TemporaryDirectory() as d:
22
+ ledger=SamplingLedger(Path(d)/'sampling.sqlite',{'parent':'fixed'})
23
+ ledger.select('r','mass',4,lambda v:'old',lambda:(2000,'old'));ledger.commit()
24
+ with self.assertRaises(RuntimeError):ledger.select('r','mass',4,lambda v:'changed',lambda:(2000,'changed'))
25
+ ledger.close()
26
+
27
+ def test_missing_ledger_or_changed_parent_is_refused(self):
28
+ with tempfile.TemporaryDirectory() as d:
29
+ path=Path(d)/'sampling.sqlite';ledger=SamplingLedger(path,{'parent':'fixed'});ledger.close()
30
+ with self.assertRaises(RuntimeError):SamplingLedger(path,{'parent':'different'})
31
+ path.unlink()
32
+ with self.assertRaises(RuntimeError):SamplingLedger(path,{'parent':'fixed'})
33
+
34
+
35
+ if __name__=='__main__':unittest.main()
code/snapshot/root/code/ceir_r1_20261109/train_ceir.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full-state continuation: two independent arms, exactly 2,000 new updates."""
2
+ import argparse
3
+ import fcntl
4
+ import json
5
+ import math
6
+ import os
7
+ from pathlib import Path
8
+ import time
9
+ import traceback
10
+ import uuid
11
+
12
+ from runtime_ceir import *
13
+
14
+
15
+ def wait_ready(directory):
16
+ while not (OUT/'READY.json').exists():
17
+ save(directory/'status.json',dict(phase='waiting_for_all_R1_data_and_GPU_acceptance',training_started=False,unix_time=time.time()))
18
+ time.sleep(10)
19
+ ready=json.loads((OUT/'READY.json').read_text())
20
+ if ready['binding']!=bind() or not ready['real_GPU_acceptance_complete']:raise RuntimeError('Ready binding changed')
21
+
22
+
23
+ def train(arm):
24
+ import torch
25
+ from torch.utils.data import DataLoader
26
+ from data_ceir import Dataset
27
+ from model_ceir import make_model_optimizer
28
+ from objectives_ceir import train_step
29
+ from validation_ceir import evaluate
30
+ directory=run_dir(arm);lock=(directory/'train.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
31
+ wait_ready(directory);setup_gpu();binding=bind();plans=json.loads((CACHE/'workload.json').read_text())['plans']
32
+ if (directory/'COMPLETE.json').exists():return
33
+ own=directory/'last.pt'
34
+ with gpu_work(directory,'restore_C03_state'):
35
+ model,opt,progress,parent_lr=make_model_optimizer(arm,own if own.exists() else None)
36
+ if own.exists():
37
+ loaded=torch.load(own,map_location='cpu',weights_only=False)
38
+ if loaded['binding']!=binding:raise RuntimeError('Resume code/data/plan binding changed')
39
+ del loaded
40
+ else:checkpoint(own,model,opt,progress,binding)
41
+ save(directory/'provenance.json',dict(parent=PLAN['parent'],source_update=SOURCE_UPDATE,target_update=TARGET_UPDATE,
42
+ parameters=sum(p.numel() for p in model.parameters()),old_optimizer_registered_parameters=len(opt.param_groups[0]['params']),
43
+ optimizer_groups=len(opt.param_groups),binding=binding,arm=arm,formal_training_started=True,
44
+ GPU_memory_fraction=.11,effective_MS_batches_preserved=True,source_cursor_continued=True,
45
+ original_sources_and_services_modified=False,teacher_index_source_update=SOURCE_UPDATE,
46
+ teacher_index_max_age_at_endpoint=2000))
47
+ attempt=uuid.uuid4().hex
48
+ resumed_at=progress['update']
49
+ log_event(directory/'events.jsonl',dict(event='resumed',attempt_id=attempt,update=resumed_at,parent_lr=parent_lr,
50
+ log_replay_policy='preserve_all_attempts_last_occurrence_per_update_for_analysis'))
51
+ save(directory/'status.json',dict(phase='restored_ready_to_continue',training_started=progress['update']>SOURCE_UPDATE,
52
+ update=progress['update'],new_updates=progress['update']-SOURCE_UPDATE,target_update=TARGET_UPDATE,unix_time=time.time()))
53
+ if progress.get('sampler_ledger_uuid'):
54
+ marker=directory/'sampling_decisions.binding.json'
55
+ if not marker.exists() or not (directory/'sampling_decisions.sqlite').exists() or json.loads(marker.read_text())['ledger_uuid']!=progress['sampler_ledger_uuid']:
56
+ raise RuntimeError('Cannot resume without the original sampling ledger')
57
+ if progress['update'] in (3000,4000) and progress['update'] not in progress.get('validated_updates',[]):
58
+ evaluate(model,arm,progress['update']);progress.setdefault('validated_updates',[]).append(progress['update'])
59
+ with gpu_work(directory,'resume_pending_validation_checkpoint'):checkpoint(own,model,opt,progress,binding)
60
+ # A separate DataLoader generator does not perturb molecular augmentation RNG.
61
+ while progress['update']<TARGET_UPDATE:
62
+ offset=progress['update']-SOURCE_UPDATE
63
+ dataset=Dataset(plans[offset:],arm,start_update=progress['update'])
64
+ generator=torch.Generator().manual_seed(SEED+offset)
65
+ loader=DataLoader(dataset,batch_size=None,num_workers=1,prefetch_factor=2,multiprocessing_context='spawn',generator=generator)
66
+ last_loop_end=time.monotonic()
67
+ for batch in loader:
68
+ started=time.monotonic();data_wait=started-last_loop_end;u=progress['update'];new=u-SOURCE_UPDATE
69
+ ledger=batch.get('sampler_ledger_uuid')
70
+ if ledger:
71
+ if progress.setdefault('sampler_ledger_uuid',ledger)!=ledger:raise RuntimeError('Sampler ledger changed during training')
72
+ ramp=min(1.,(new+1)/200.);decay=.2+.8*.5*(1+math.cos(math.pi*min(1,new/2000)))
73
+ for i,g in enumerate(opt.param_groups):g['lr']=parent_lr*(.3 if i==0 else 1.)*ramp*decay
74
+ with gpu_work(directory,'training'):
75
+ admission_wait=time.monotonic()-started
76
+ model.train();torch.cuda.reset_peak_memory_stats()
77
+ metrics=train_step(model,opt,batch,u)
78
+ progress.update(update=u+1,new_updates=new+1,epoch=batch['epoch'],next_step=batch['step']+1)
79
+ counts=progress.setdefault('new_exposures',{})
80
+ for source,n in metrics['sources'].items():counts[source]=counts.get(source,0)+n
81
+ progress.setdefault('validated_updates',[])
82
+ if progress['update']%100==0 or new==0:checkpoint(own,model,opt,progress,binding)
83
+ metrics.update(update=progress['update'],new_updates=progress['new_updates'],target_update=TARGET_UPDATE,
84
+ epoch=batch['epoch'],data_step=batch['step']+1,wall_seconds=time.monotonic()-started,
85
+ data_wait_seconds=data_wait,gpu_admission_wait_seconds=admission_wait,
86
+ old_learning_rate=opt.param_groups[0]['lr'],new_learning_rate=opt.param_groups[1]['lr'],arm=arm,
87
+ attempt_id=attempt,attempt_resumed_checkpoint_update=resumed_at)
88
+ metrics['sampler_ledger_uuid']=ledger
89
+ log_event(directory/'loss.jsonl',metrics)
90
+ if progress['new_updates']<=3 or progress['new_updates']%10==0:
91
+ save(directory/'status.json',dict(phase='training',training_started=True,update=progress['update'],new_updates=progress['new_updates'],target_update=TARGET_UPDATE,latest=metrics,unix_time=time.time()))
92
+ print(json.dumps(dict(arm=arm,update=progress['update'],loss=metrics['loss'],seconds=metrics['wall_seconds'])),flush=True)
93
+ if progress['update']%500==0:
94
+ with gpu_work(directory,'checkpoint'):checkpoint(directory/('step_%06d.pt'%progress['update']),model,opt,progress,binding)
95
+ check_disk()
96
+ if progress['update'] in (3000,4000):
97
+ with gpu_work(directory,'checkpoint_before_validation'):
98
+ checkpoint(directory/('step_%06d.pt'%progress['update']),model,opt,progress,binding)
99
+ save(directory/'status.json',dict(phase='full_Validation',training_started=True,update=progress['update'],new_updates=progress['new_updates'],unix_time=time.time()))
100
+ evaluate(model,arm,progress['update']);progress['validated_updates'].append(progress['update'])
101
+ with gpu_work(directory,'checkpoint_after_validation'):checkpoint(own,model,opt,progress,binding)
102
+ if progress['update']>=TARGET_UPDATE:break
103
+ last_loop_end=time.monotonic()
104
+ save(directory/'COMPLETE.json',dict(complete=True,update=TARGET_UPDATE,new_updates=2000,validated_updates=progress['validated_updates'],
105
+ new_exposures=progress['new_exposures'],checkpoint=str(directory/'step_004000.pt'),MCES='asynchronous_pending_or_result_file',unix_time=time.time()))
106
+ save(directory/'status.json',dict(phase='completed',update=TARGET_UPDATE,new_updates=2000,training_started=True,unix_time=time.time()))
107
+
108
+
109
+ if __name__=='__main__':
110
+ p=argparse.ArgumentParser();p.add_argument('--arm',choices=['main','control'],required=True);args=p.parse_args()
111
+ try:train(args.arm)
112
+ except Exception:
113
+ directory=run_dir(args.arm);save(directory/'failure.json',dict(traceback=traceback.format_exc(),unix_time=time.time(),resume_from_last_checkpoint=True));raise
code/snapshot/root/code/ceir_r1_20261109/training.supervisor.conf ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [program:specpartition-ceir-r1-gate-20261109]
2
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_20261109
3
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u pipeline_ceir.py
4
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
5
+ autostart=true
6
+ autorestart=unexpected
7
+ startsecs=5
8
+ startretries=3
9
+ stopasgroup=true
10
+ killasgroup=true
11
+ stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/pipeline.log
12
+ stderr_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/pipeline_error.log
13
+ stdout_logfile_maxbytes=50MB
14
+ stderr_logfile_maxbytes=20MB
15
+
16
+ [program:specpartition-ceir-r1-main-20261109]
17
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_20261109
18
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u train_ceir.py --arm main
19
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
20
+ autostart=false
21
+ autorestart=unexpected
22
+ startsecs=5
23
+ startretries=3
24
+ stopasgroup=true
25
+ killasgroup=true
26
+ stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/main.log
27
+ stderr_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/main_error.log
28
+ stdout_logfile_maxbytes=50MB
29
+ stdout_logfile_backups=4
30
+ stderr_logfile_maxbytes=30MB
31
+
32
+ [program:specpartition-ceir-r1-refresh-20261109]
33
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_20261109
34
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u refresh_ceir.py
35
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
36
+ autostart=false
37
+ autorestart=unexpected
38
+ startsecs=5
39
+ startretries=3
40
+ stopasgroup=true
41
+ killasgroup=true
42
+ stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/refresh.log
43
+ stderr_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/refresh_error.log
44
+ stdout_logfile_maxbytes=30MB
45
+ stderr_logfile_maxbytes=20MB
46
+
47
+ [program:specpartition-ceir-r1-control-20261109]
48
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_20261109
49
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u train_ceir.py --arm control
50
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
51
+ autostart=false
52
+ autorestart=unexpected
53
+ startsecs=5
54
+ startretries=3
55
+ stopasgroup=true
56
+ killasgroup=true
57
+ stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/control.log
58
+ stderr_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/control_error.log
59
+ stdout_logfile_maxbytes=50MB
60
+ stdout_logfile_backups=4
61
+ stderr_logfile_maxbytes=30MB
62
+
63
+ [program:specpartition-ceir-r1-mces-20261109]
64
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_20261109
65
+ command=/usr/bin/nice -n 19 /root/xj/SpecPartition-MS/evaluations/mces_all_20261106/.venv/bin/python -u mces_ceir.py
66
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1"
67
+ autostart=false
68
+ autorestart=unexpected
69
+ startsecs=5
70
+ startretries=3
71
+ stopasgroup=true
72
+ killasgroup=true
73
+ stdout_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/mces.log
74
+ stderr_logfile=/root/xj/SpecPartition-MS/runs/ceir_r1_20261109/logs/mces_error.log
75
+ stdout_logfile_maxbytes=30MB
76
+ stderr_logfile_maxbytes=20MB
code/snapshot/root/code/ceir_r1_20261109/validate_plan.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate the design contract and emit resolved ablations, never launch jobs.
2
+
3
+ These checks validate a proposal. They are not student model, GPU, source-data
4
+ integrity, training-completion, or literature-performance reproduction tests.
5
+ """
6
+ import copy
7
+ import argparse
8
+ import hashlib
9
+ import json
10
+ from pathlib import Path
11
+
12
+
13
+ ROOT = Path(__file__).resolve().parent
14
+ WORKSPACE = ROOT.parents[1]
15
+
16
+
17
+ def validate(c):
18
+ checks = []
19
+
20
+ def require(name, condition):
21
+ if not condition:
22
+ raise ValueError(name)
23
+ checks.append(name)
24
+
25
+ require('fixed C03 2k parent', c['parent']['source_update'] == 2000 and
26
+ c['parent']['sha256'] == '8a2982f3821fad501ba4f39ac8b1495affeb0c1b09051f2103317f36027d48b6')
27
+ require('training counts reconcile', sum(c['data']['reference_release_spectra'].values()) == c['data']['reference_release_total'] == 643587)
28
+ require('all and only Train mining sources', set(c['data']['negative_mining_allowed_splits']) == {'MSG_Train','MSP_libraries','MS2_SAN_JSONL'})
29
+ require('both MSG views', c['data']['official_MSG_Mass_Formula_both_each_step'])
30
+ require('no injection or external writes', not c['data']['truth_injection'] and not c['new_training_started'] and not c['existing_services_changed'])
31
+ require('MSG budget', sum(c['sampling']['MSG_mix'].values()) == c['sampling']['MSG_negative_draws_per_view'] == 63)
32
+ require('odata budget', sum(c['sampling']['odata_mix'].values()) == c['sampling']['odata_negative_draws'] == 128)
33
+ require('replacement and false-negative safety', c['sampling']['with_replacement'] and c['sampling']['same_key14_never_negative'])
34
+ require('pool CE once', c['loss']['final_score_pool_InfoNCE_once'] and not c['loss']['local_path_additional_duplicate_pool_CE'] and not c['loss']['composition_evidence_additional_duplicate_CE'])
35
+ require('conditional CE not duplicated', c['loss']['conditional_structure']['requires_cross_formula_negative'] and not c['loss']['conditional_structure']['enabled_for_Formula_or_true_formula_odata'])
36
+ require('structure identity not formula equality', c['loss']['same_formula_is_not_structure_positive'] and not c['loss']['coarse_formula_positive_loss_on_main_retrieval_embedding'])
37
+ ev = c['model']['new_modules']['composition_evidence']
38
+ require('evidence heads dimension', ev['evidence_dim'] % ev['heads'] == 0)
39
+ require('raw MS retained', ev['retain_full_raw_peak_path'] and c['model']['raw_peak_limit'] == 256)
40
+ require('new evidence reaches structure path', 'formula_conditioned_peak_tokens_for_structure_matching' in ev['outputs'])
41
+ require('all actual MSG formulas', ev['formulas_in_MSG'] == 'all_actual_distinct_pool_formulas_not_Top10_truncated')
42
+ require('safe Mass inputs', c['model']['no_reference_formula_in_Mass_inference'] and c['model']['no_reference_SMILES_or_similarity_in_inference'] and not c['model']['SIRIUS_scores_ranks_CSI_features'])
43
+ require('no extra heavy teacher prerequisite R1', not c['model']['new_modules']['fragment_simulator']['enabled'] and not c['model']['new_modules']['synthetic_structure_expansion']['enabled'])
44
+ require('one block denominator', c['efficiency']['single_softmax_denominator_across_blocks'] and c['efficiency']['do_not_detach_trainable_student_embeddings'])
45
+ require('Validation only selection', c['selection']['split'] == 'MSG_Validation_full' and not c['selection']['Test_CASMI_used_for_selection'])
46
+ require('CASMI frozen complete pool', c['evaluation']['CASMI_frozen_candidates'] == 1765420 and c['evaluation']['CASMI_candidate_limit'] is None and not c['evaluation']['CASMI_truth_injection'])
47
+ require('coverage denominator', c['evaluation']['CASMI_truth_coverage'] == 467 and c['evaluation']['CASMI_n'] == 500)
48
+ require('no reinterpretation of formula scope', c['evaluation']['CASMI_formula_scope'] == 'rerank_fixed_SIRIUS_Top10_not_open_formula_generation')
49
+ require('not a training command', not c['readiness']['config_is_training_entrypoint'])
50
+ require('no slot/CID shortcuts', c['input_leakage_checks']['stable_hash_candidate_shuffle_without_reference'] and not c['input_leakage_checks']['CID_original_position_PubChem_order_as_features'])
51
+ require('no negative-mode validation overclaim', not c['input_leakage_checks']['MSG_Validation_claimed_negative_mode_development_set'] and c['input_leakage_checks']['new_negative_development_split_must_audit_parent_training_exposure'])
52
+ require('no competitive-CE denominator dilution', c['loss']['competitive_CE_requires_distinct_negative'] and c['loss']['means_and_effective_counts_use_actual_eligible_queries'])
53
+ require('fixed formula coverage ceiling retained', c['evaluation']['CASMI_frozen_formula_truth_coverage'] == 468 and c['evaluation']['CASMI_formula_Top10_cannot_improve_by_reranking_same_at_most10_formulas'])
54
+ return checks
55
+
56
+
57
+ def main():
58
+ parser=argparse.ArgumentParser()
59
+ parser.add_argument('--diagnosis',type=Path)
60
+ args=parser.parse_args()
61
+ c = json.loads((ROOT / 'plan.json').read_text())
62
+ checks = validate(c)
63
+ reference=ROOT/'reference/diagnosis.json'
64
+ diagnosis=args.diagnosis or (reference if reference.exists() else WORKSPACE/'analysis_outputs/c03_2k_badcase_20261109/diagnosis.json')
65
+ diag = json.loads(diagnosis.read_text())
66
+ require_hash = diag['checkpoint_sha256'] == c['parent']['sha256']
67
+ if not require_hash:
68
+ raise ValueError('Diagnosis references a different baseline')
69
+ for name, view in diag['views'].items():
70
+ m = view['metrics']
71
+ if sum(m['error_buckets'].values()) != m['n']:
72
+ raise ValueError('Error buckets do not reconcile: ' + name)
73
+ matrix = []
74
+ for arm in c['experiment']['ablation_sequence']:
75
+ resolved = copy.deepcopy(c)
76
+ resolved['arm'] = arm
77
+ if arm == 'control':
78
+ resolved['sampling']['MSG_mix'] = {'model': 0, 'chemical': 0, 'random': 63}
79
+ resolved['sampling']['odata_mix'] = {'model': 0, 'chemical': 0, 'random': 128}
80
+ for key in ('reverse_local', 'fingerprint', 'composition_evidence'):
81
+ resolved['model']['new_modules'][key]['enabled'] = False
82
+ for key in ('identity_balanced_occurrence_reduction', 'conditional_structure', 'same_formula_gap', 'fingerprint_auxiliary'):
83
+ resolved['loss'][key]['enabled'] = False
84
+ elif arm == 'minus_hard_mixture':
85
+ resolved['sampling']['MSG_mix'] = {'model': 0, 'chemical': 0, 'random': 63}
86
+ resolved['sampling']['odata_mix'] = {'model': 0, 'chemical': 0, 'random': 128}
87
+ elif arm == 'minus_extra_isomer_losses':
88
+ resolved['loss']['conditional_structure']['enabled'] = False
89
+ resolved['loss']['same_formula_gap']['enabled'] = False
90
+ elif arm == 'minus_reverse_local':
91
+ resolved['model']['new_modules']['reverse_local']['enabled'] = False
92
+ elif arm == 'minus_fingerprint':
93
+ resolved['model']['new_modules']['fingerprint']['enabled'] = False
94
+ resolved['loss']['fingerprint_auxiliary']['enabled'] = False
95
+ elif arm == 'minus_composition_evidence':
96
+ resolved['model']['new_modules']['composition_evidence']['enabled'] = False
97
+ elif arm == 'minus_identity_balancing':
98
+ resolved['loss']['identity_balanced_occurrence_reduction']['enabled'] = False
99
+ elif arm != 'main_R1':
100
+ raise ValueError('Unknown arm: ' + arm)
101
+ validate(resolved)
102
+ matrix.append(resolved)
103
+ (ROOT / 'ablation_matrix.json').write_text(json.dumps(matrix, ensure_ascii=False, indent=2) + '\n')
104
+ gate_names = ('formal_trainer_integration','Train_only_bound_teacher_index',
105
+ 'composition_annotation_adapter_and_cache','identity_balanced_losses_integrated',
106
+ 'new_parameter_optimizer_groups_integrated','real_student_GPU_forward_backward',
107
+ 'resume_and_parent_logit_parity_acceptance')
108
+ pending = [k for k in gate_names if not c['readiness'][k]]
109
+ report = {'scope': 'local design/config consistency only',
110
+ 'diagnosis_file_sha256': hashlib.sha256(diagnosis.read_bytes()).hexdigest(),
111
+ 'config_sha256': hashlib.sha256((ROOT / 'plan.json').read_bytes()).hexdigest(),
112
+ 'checks_passed': len(checks), 'checks': checks,
113
+ 'diagnosis_buckets_reconciled': 3, 'resolved_ablation_arms': len(matrix),
114
+ 'training_ready': not pending, 'pending_implementation_gates': pending,
115
+ 'performance_improvement_measured': False, 'GPU_acceptance_performed': False,
116
+ 'new_training_started': False, 'server_state_inspected_or_modified': False}
117
+ (ROOT / 'validation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
118
+ print(json.dumps({k: report[k] for k in ('checks_passed','diagnosis_buckets_reconciled',
119
+ 'resolved_ablation_arms','training_ready','pending_implementation_gates')}, ensure_ascii=False))
120
+
121
+
122
+ if __name__ == '__main__':
123
+ main()
code/snapshot/root/code/ceir_r1_20261109/validation.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "scope": "local design/config consistency only",
3
+ "diagnosis_file_sha256": "1a031037a7eda329034dc82343ddf22593eb6e09f64edfd5d1b406fb2eb06dcb",
4
+ "config_sha256": "f2f6c2a9a196271653151f9905b4a31a9b292a22c7238da04c216415a800f757",
5
+ "checks_passed": 27,
6
+ "checks": [
7
+ "fixed C03 2k parent",
8
+ "training counts reconcile",
9
+ "all and only Train mining sources",
10
+ "both MSG views",
11
+ "no injection or external writes",
12
+ "MSG budget",
13
+ "odata budget",
14
+ "replacement and false-negative safety",
15
+ "pool CE once",
16
+ "conditional CE not duplicated",
17
+ "structure identity not formula equality",
18
+ "evidence heads dimension",
19
+ "raw MS retained",
20
+ "new evidence reaches structure path",
21
+ "all actual MSG formulas",
22
+ "safe Mass inputs",
23
+ "no extra heavy teacher prerequisite R1",
24
+ "one block denominator",
25
+ "Validation only selection",
26
+ "CASMI frozen complete pool",
27
+ "coverage denominator",
28
+ "no reinterpretation of formula scope",
29
+ "not a training command",
30
+ "no slot/CID shortcuts",
31
+ "no negative-mode validation overclaim",
32
+ "no competitive-CE denominator dilution",
33
+ "fixed formula coverage ceiling retained"
34
+ ],
35
+ "diagnosis_buckets_reconciled": 3,
36
+ "resolved_ablation_arms": 8,
37
+ "training_ready": false,
38
+ "pending_implementation_gates": [
39
+ "formal_trainer_integration",
40
+ "Train_only_bound_teacher_index",
41
+ "composition_annotation_adapter_and_cache",
42
+ "identity_balanced_losses_integrated",
43
+ "new_parameter_optimizer_groups_integrated",
44
+ "real_student_GPU_forward_backward",
45
+ "resume_and_parent_logit_parity_acceptance"
46
+ ],
47
+ "performance_improvement_measured": false,
48
+ "GPU_acceptance_performed": false,
49
+ "new_training_started": false,
50
+ "server_state_inspected_or_modified": false
51
+ }
code/snapshot/root/code/ceir_r1_20261109/validation_ceir.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Complete unchanged official Validation pools and inspectable ranked scores."""
2
+ from collections import defaultdict
3
+ from dataclasses import replace
4
+ import gzip
5
+ import hashlib
6
+ import json
7
+ import time
8
+ import torch
9
+ from runtime_ceir import *
10
+ from data09 import loads
11
+ from objectives_ceir import amp
12
+ from specpartition_ms.chemistry import canonical_formula,formula_vector
13
+
14
+ KS=(1,3,5,10,20,50,100,200)
15
+ FKS=tuple(range(1,11))+(20,50,100,200)
16
+
17
+
18
+ def metric(rows,field,ks):
19
+ result={}
20
+ for k in ks:
21
+ hit=[r[field] is not None and r[field]<=k for r in rows]
22
+ targets=defaultdict(list);identities=defaultdict(list)
23
+ for r,h in zip(rows,hit):targets[r['target']].append(h);identities[r['reference_identity']].append(h)
24
+ result[str(k)]=dict(hits=sum(hit),denominator=len(rows),micro=sum(hit)/len(rows),
25
+ target_macro=sum(sum(v)/len(v) for v in targets.values())/len(targets),
26
+ key14_macro=sum(sum(v)/len(v) for v in identities.values())/len(identities))
27
+ return result
28
+
29
+
30
+ def evaluate(model,arm,update,maximum_targets=None):
31
+ dest=run_dir(arm)/('validation_update_%06d'%update)
32
+ if maximum_targets is not None:dest=run_dir(arm)/'acceptance_validation_probe'
33
+ dest.mkdir(parents=True,exist_ok=True)
34
+ evaluation_binding=dict(runtime=bind(),arm=arm,update=update,maximum_targets=maximum_targets,
35
+ source_checkpoint_sha256=sha(run_dir(arm)/('step_%06d.pt'%update))
36
+ if maximum_targets is None else PLAN['parent']['sha256'])
37
+ protocol_path=dest/'protocol_binding.json'
38
+ if protocol_path.exists() and json.loads(protocol_path.read_text())!=evaluation_binding:
39
+ raise RuntimeError('Refusing to mix Validation predictions from different code/data/checkpoints')
40
+ save(protocol_path,evaluation_binding)
41
+ if (dest/'metrics.json').exists():return json.loads((dest/'metrics.json').read_text())
42
+ model.eval();model.install_evidence(True)
43
+ db=readonly(LEGACY.PREP/'validation.sqlite');summary=[];started=time.monotonic()
44
+ targets=[r[0] for r in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target')]
45
+ if maximum_targets is not None:targets=targets[:maximum_targets]
46
+ for ti,target in enumerate(targets):
47
+ output=dest/(hashlib.sha256(target.encode()).hexdigest()+'.json.gz')
48
+ if output.exists():
49
+ with gzip.open(output,'rt') as f:summary.extend(json.load(f)['rows'])
50
+ continue
51
+ pools={kind:json.loads(db.execute('SELECT body FROM pools WHERE target=? AND view=?',(target,kind)).fetchone()[0]) for kind in ('mass','formula')}
52
+ aliases={s:db.execute('SELECT graph_key,identity,formula,error FROM aliases WHERE smiles=?',(s,)).fetchone() for s in set(sum(pools.values(),[]))}
53
+ graphs={}
54
+ for key,identity,formula,error in aliases.values():
55
+ 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])
56
+ keys=sorted(graphs);mols=[graphs[k] for k in keys];positions={k:i for i,k in enumerate(keys)}
57
+ data=[loads(r[0]) for r in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier',(target,))];rows=[];ranked={}
58
+ with gpu_work(dest,'full_Validation_target'),torch.inference_mode(),amp():
59
+ _,atoms,zm=model.encode_molecules(mols)
60
+ for start in range(0,len(data),4):
61
+ block=data[start:start+4];tokens,qs,_=model.spectrum.forward_batch([r['query'] for r in block])
62
+ views=[];qvalues=[];pvalues=[]
63
+ for i,r in enumerate(block):
64
+ for kind in ('mass','formula'):
65
+ fs=set()
66
+ for s in pools[kind]:
67
+ f=aliases[s][2]
68
+ if f:
69
+ try:formula_vector(f);fs.add(canonical_formula(f))
70
+ except ValueError:pass
71
+ q=replace(r['query'],formula_candidates=tuple(sorted(fs)))
72
+ views.append((i,kind,q));qvalues.append(qs[i]);pvalues.append(tokens[i])
73
+ formula_scores,contexts=model.formula_batch(torch.stack(qvalues),[x[2] for x in views],pvalues,True)
74
+ for vi,(i,kind,q) in enumerate(views):
75
+ r=block[i];selected=sorted({aliases[s][0] for s in pools[kind] if aliases[s][0] is not None})
76
+ index=[positions[k] for k in selected];scores={}
77
+ if index:
78
+ values,_,_=model.score_encoded(qs[i],tokens[i],q,[graphs[k] for k in selected],[atoms[j] for j in index],zm[index],formula_scores[vi],contexts[vi])
79
+ scores=dict(zip(selected,values.float().cpu().tolist()))
80
+ expanded=[dict(smiles=s,identity=aliases[s][1],formula=aliases[s][2],score=scores.get(aliases[s][0]),scoreable=aliases[s][0] in scores) for s in pools[kind]]
81
+ expanded.sort(key=lambda c:(not c['scoreable'],-c['score'] if c['scoreable'] else 0,c['identity'] or '',c['smiles']))
82
+ rank=next((j+1 for j,c in enumerate(expanded) if c['scoreable'] and c['identity']==r['identity']),None)
83
+ fv=formula_scores[vi].float().cpu().tolist();order=sorted(range(len(fv)),key=lambda j:(-fv[j],q.formula_candidates[j]))
84
+ try:truth=canonical_formula(r['formula']);formula_vector(truth)
85
+ except ValueError:truth=None
86
+ frank=next((j+1 for j,k in enumerate(order) if q.formula_candidates[k]==truth),None)
87
+ row=dict(identifier=r['identifier'],target=target,view=kind,reference_identity=r['identity'],reference_formula=truth,
88
+ rank=rank,formula_rank=frank,candidate_count=len(expanded),formula_count=len(fv),
89
+ unscoreable=sum(not c['scoreable'] for c in expanded),adduct=q.adduct,
90
+ polarity='negative' if q.adduct.endswith('-') else 'positive',
91
+ peak_count=len(q.peaks),instrument=q.instrument,collision_energy=q.collision_energy,
92
+ same_formula_candidates=sum(c['formula']==truth for c in expanded),
93
+ reference_present_in_original_pool=any(c['identity']==r['identity'] for c in expanded),
94
+ reference_scoreable=any(c['scoreable'] and c['identity']==r['identity'] for c in expanded),
95
+ top1_smiles=expanded[0]['smiles'] if expanded and expanded[0]['scoreable'] else None)
96
+ rows.append(row);ranked[r['identifier']+'/'+kind]=dict(candidates=expanded,
97
+ formulas=[dict(formula=q.formula_candidates[j],score=fv[j],rank=k+1) for k,j in enumerate(order)])
98
+ temporary=Path(str(output)+'.tmp')
99
+ with gzip.open(temporary,'wt',compresslevel=3) as f:json.dump(dict(rows=rows,ranked=ranked),f,separators=(',',':'))
100
+ temporary.replace(output);summary.extend(rows)
101
+ save(dest/'status.json',dict(targets=ti+1,total=len(targets),spectral_views=len(summary),seconds=time.monotonic()-started,updated_unix=time.time()))
102
+ check_disk()
103
+ metrics={}
104
+ for kind in ('mass','formula'):
105
+ rr=[r for r in summary if r['view']==kind]
106
+ if maximum_targets is None and (len(rr)!=19429 or len({r['identifier'] for r in rr})!=19429):raise RuntimeError('Validation denominator mismatch')
107
+ metrics[kind]=dict(spectra=len(rr),structure=metric(rr,'rank',KS),formula=metric(rr,'formula_rank',FKS),
108
+ unscoreable_candidates=sum(r['unscoreable'] for r in rr),
109
+ original_pool_reference_coverage=sum(r['reference_present_in_original_pool'] for r in rr),
110
+ scoreable_reference_coverage=sum(r['reference_scoreable'] for r in rr),strata={})
111
+ strata=metrics[kind]['strata']
112
+ grouping={
113
+ 'adduct':lambda r:r['adduct'],
114
+ 'polarity':lambda r:r['polarity'],
115
+ 'instrument':lambda r:r['instrument'] or 'missing',
116
+ 'collision_energy_missing':lambda r:str(r['collision_energy'] is None),
117
+ 'peak_count':lambda r:'1-20' if r['peak_count']<=20 else ('21-50' if r['peak_count']<=50 else ('51-100' if r['peak_count']<=100 else '101+')),
118
+ 'candidate_count':lambda r:'1-64' if r['candidate_count']<=64 else ('65-128' if r['candidate_count']<=128 else '129+'),
119
+ 'same_formula_count':lambda r:'0' if not r['same_formula_candidates'] else ('1' if r['same_formula_candidates']==1 else ('2-32' if r['same_formula_candidates']<=32 else '33+')),
120
+ }
121
+ for name,key in grouping.items():
122
+ grouped=defaultdict(list)
123
+ for row in rr:grouped[key(row)].append(row)
124
+ strata[name]={str(k):dict(spectra=len(v),structure=metric(v,'rank',KS),formula=metric(v,'formula_rank',FKS)) for k,v in sorted(grouped.items())}
125
+ with gzip.open(dest/'per_spectrum_summary.json.gz','wt',compresslevel=3) as f:json.dump(summary,f,separators=(',',':'))
126
+ metrics.update(update=update,protocol='full_official_raw_entry_rank_2D_connectivity_no_truth_injection',
127
+ formula_scope='distinct_official_pool_formulas_not_open_generation',full_Validation=maximum_targets is None,
128
+ binding=evaluation_binding,
129
+ secondary_exact_metrics='not_computed_in_this_pilot_primary_is_key14',
130
+ MCES='queued_asynchronous_not_zero_filled',seconds=time.monotonic()-started)
131
+ save(dest/'metrics.json',metrics)
132
+ if maximum_targets is None:
133
+ x=metrics['mass']['structure']['1']['micro'];y=metrics['formula']['structure']['1']['micro'];h=2*x*y/max(x+y,1e-12)
134
+ save(dest/'selection.json',dict(selection_score=h,criterion='harmonic_mean_Mass_Formula_Top1',MCES_guardrail_pending=True))
135
+ db.close();model.install_evidence(False);model.train();return metrics
code/snapshot/root/code/ceir_r1_test_comparison_20261110/config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "experiment": "ceir_r1_test_comparison_20261110",
3
+ "root": "/workspace/xj/SpecPartition-MS",
4
+ "r1_code": "/root/xj/SpecPartition-MS/code/ceir_r1_20261109",
5
+ "r1_output": "/root/xj/SpecPartition-MS/runs/ceir_r1_20261109",
6
+ "output": "/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110",
7
+ "parent_checkpoint": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C03_both_fine/seed_20261103/step_002000.pt",
8
+ "parent_sha256": "8a2982f3821fad501ba4f39ac8b1495affeb0c1b09051f2103317f36027d48b6",
9
+ "primary_update": 3000,
10
+ "fixed_endpoint_update": 4000,
11
+ "datasets": ["msg_test", "casmi2022"],
12
+ "annotation_workers": 4,
13
+ "annotation_formula_cache": 128,
14
+ "annotation_query_chunk": 64,
15
+ "spectrum_batch": 16,
16
+ "graph_chunk": 32,
17
+ "local_chunk": 32,
18
+ "maximum_gpu_workers": 2,
19
+ "gpu_memory_fraction": 0.24,
20
+ "minimum_free_gpu_mib": 4000,
21
+ "minimum_output_disk_gib": 8,
22
+ "candidate_limit": null,
23
+ "truth_injection": false,
24
+ "test_used_for_selection": false,
25
+ "training_or_optimizer_updates": false,
26
+ "baseline_policy": "reuse_hash_bound_C03_step_002000_predictions_and_MCES",
27
+ "mces": {"package": "myopic-mces", "version": "1.0.0", "pulp": "2.9.0", "threshold": 15, "solver_threads": 1, "time_limit_seconds": 5, "workers": 4}
28
+ }
code/snapshot/root/code/ceir_r1_test_comparison_20261110/evaluation_runtime.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Isolated evaluation release; unique name avoids legacy `common` imports."""
2
+ import contextlib
3
+ import fcntl
4
+ import hashlib
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import time
12
+
13
+ HERE=Path(__file__).resolve().parent
14
+ C=json.loads((HERE/'config.json').read_text())
15
+ ROOT=Path(C['root']);OUT=Path(C['output']);R1=Path(C['r1_output'])
16
+ PREP=ROOT/'data/derived/post_training_evaluation_20261103'
17
+ sys.path.insert(0,C['r1_code'])
18
+ import runtime_ceir as runtime
19
+ from evidence_ceir import EvidenceStore,query_key,RULE
20
+ from runtime09 import readonly,sha,save
21
+ from data09 import loads
22
+
23
+ MODELS={f'{arm}_{update:06d}':dict(arm=arm,update=update,checkpoint=str(R1/arm/f'step_{update:06d}.pt'))
24
+ for arm in ('main','control') for update in (3000,4000)}
25
+
26
+
27
+ def own_code():
28
+ return {p.name:sha(p) for p in sorted([*HERE.glob('*.py'),HERE/'config.json'])}
29
+
30
+
31
+ def check_disk():
32
+ OUT.mkdir(parents=True,exist_ok=True)
33
+ if shutil.disk_usage(OUT).free<C['minimum_output_disk_gib']*2**30:
34
+ raise RuntimeError('Output disk reserve insufficient; no existing data deleted')
35
+
36
+
37
+ def universe(db,target,dataset):
38
+ from specpartition_ms.chemistry import canonical_formula,formula_vector
39
+ rows=db.execute('SELECT view,body,formulas,source FROM pools WHERE target=? ORDER BY view',(target,)).fetchall()
40
+ pools={view:json.loads(body) for view,body,_,_ in rows}
41
+ aliases={s:db.execute('SELECT graph_key,identity,formula,canonical,fullkey,error FROM aliases WHERE smiles=?',(s,)).fetchone()
42
+ for s in set(s for pool in pools.values() for s in pool)}
43
+ fs={};sources={}
44
+ for view,_,formulas,source in rows:
45
+ sources[view]=source
46
+ if dataset=='msg_test':
47
+ # Preserve the original evaluator's exact supported alias universe.
48
+ fs[view]=tuple(sorted({aliases[s][2] for s in pools[view]}-{None}))
49
+ else:
50
+ values=set()
51
+ for f in json.loads(formulas):
52
+ try:f=canonical_formula(f);formula_vector(f);values.add(f)
53
+ except (ValueError,TypeError):pass
54
+ fs[view]=tuple(sorted(values))
55
+ if any(aliases[s][0] and aliases[s][2] not in fs[view] for s in pools[view]):
56
+ raise RuntimeError('Scorable structure formula absent from fixed universe')
57
+ return pools,aliases,fs,sources
58
+
59
+
60
+ def inputs(dataset):
61
+ marker=PREP/(dataset+'_ready.json');obj=json.loads(marker.read_text())
62
+ if not obj['complete']:raise RuntimeError('Existing evaluation input is incomplete')
63
+ return dict(ready_sha256=sha(marker),binding=obj['binding'],counts=obj['counts'],
64
+ candidate_limit=None,truth_injection=False)
65
+
66
+
67
+ def freeze():
68
+ if sha(C['parent_checkpoint'])!=C['parent_sha256']:raise RuntimeError('Wrong C03 parent checkpoint')
69
+ if not json.loads((R1/'MATCHED_VALIDATION_COMPARISON.json').read_text())['complete']:
70
+ raise RuntimeError('Matched Validation comparison is incomplete')
71
+ registry=ROOT/'runs/post_training_evaluation_20261103/models/C03_both_fine.json'
72
+ baseline=json.loads(registry.read_text())
73
+ if baseline['checkpoint_sha256']!=C['parent_sha256'] or baseline['checkpoint']!=C['parent_checkpoint']:
74
+ raise RuntimeError('Existing C03 Test baseline is not the fixed parent')
75
+ models={}
76
+ for name,item in MODELS.items():
77
+ if not json.loads((R1/item['arm']/'COMPLETE.json').read_text())['complete']:
78
+ raise RuntimeError('Training is not complete')
79
+ p=Path(item['checkpoint'])
80
+ models[name]=dict(item,sha256=sha(p),bytes=p.stat().st_size,
81
+ role='primary_preselected_by_Validation' if item['update']==3000 else 'prespecified_fixed_endpoint_secondary')
82
+ frozen=dict(config=C,models=models,inputs={d:inputs(d) for d in C['datasets']},
83
+ source_code=own_code(),r1_binding=runtime.bind(),
84
+ selection='primary_update_3000_both_arms_fixed_before_any_Test_inference',
85
+ parent_sha256=C['parent_sha256'],baseline_registry=baseline,baseline_registry_sha256=sha(registry),original_assets_modified=False)
86
+ path=OUT/'FROZEN.json'
87
+ if path.exists() and json.loads(path.read_text())!=frozen:raise RuntimeError('Evaluation release binding changed')
88
+ save(path,frozen)
89
+ return frozen
90
+
91
+
92
+ @contextlib.contextmanager
93
+ def gpu_slot(directory):
94
+ check_disk();locks=OUT/'gpu_slots';locks.mkdir(parents=True,exist_ok=True)
95
+ files=[(locks/f'{i}.lock').open('a+') for i in range(C['maximum_gpu_workers'])];held=None
96
+ try:
97
+ while held is None:
98
+ text=subprocess.check_output(['nvidia-smi','--query-gpu=memory.free','--format=csv,noheader,nounits'],text=True)
99
+ if int(text.strip().splitlines()[0])>=C['minimum_free_gpu_mib']:
100
+ for f in files:
101
+ try:fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB);held=f;break
102
+ except BlockingIOError:pass
103
+ if held is None:
104
+ save(Path(directory)/'resource_status.json',dict(state='waiting_for_evaluation_GPU_slot',unix_time=time.time()))
105
+ time.sleep(2)
106
+ yield
107
+ finally:
108
+ import torch
109
+ if torch.cuda.is_initialized():torch.cuda.empty_cache()
110
+ if held is not None:fcntl.flock(held,fcntl.LOCK_UN)
111
+ for f in files:f.close()
112
+
113
+
114
+ def make_model(name):
115
+ import torch
116
+ from model_ceir import CEIRRanker
117
+ frozen=json.loads((OUT/'FROZEN.json').read_text());item=frozen['models'][name]
118
+ if sha(item['checkpoint'])!=item['sha256']:raise RuntimeError('Frozen checkpoint changed')
119
+ torch.set_num_threads(1);torch.set_float32_matmul_precision('high');torch.use_deterministic_algorithms(True)
120
+ torch.cuda.set_per_process_memory_fraction(C['gpu_memory_fraction']);runtime.LEGACY.seed_all(20261103)
121
+ state=torch.load(item['checkpoint'],map_location='cpu',weights_only=False)
122
+ if state.get('architecture')!='CEIR_R1' or state['progress']['update']!=item['update']:
123
+ raise RuntimeError('Checkpoint architecture/update mismatch')
124
+ if state['binding']!=frozen['r1_binding']:raise RuntimeError('Training checkpoint code/data binding mismatch')
125
+ model=CEIRRanker(runtime.LEGACY.C,item['arm']);model.load_state_dict(state['model'],strict=True)
126
+ del state
127
+ model.graph_chunk=C['graph_chunk'];model.local_chunk=C['local_chunk']
128
+ if item['arm']=='main':
129
+ paths=[OUT/'prepared'/(d+'_composition.sqlite') for d in C['datasets']]
130
+ for dataset in C['datasets']:
131
+ marker=json.loads((OUT/'prepared'/(dataset+'_composition_READY.json')).read_text())
132
+ if marker['rule']!=RULE or marker['inputs']!=frozen['inputs'][dataset]:raise RuntimeError('Inference evidence binding mismatch')
133
+ model.evidence=EvidenceStore(paths)
134
+ model=model.to(runtime.LEGACY.C['device']).eval()
135
+ return model,item
136
+
137
+
138
+ def amp():
139
+ import torch
140
+ return torch.autocast('cuda',dtype=torch.bfloat16,enabled=runtime.LEGACY.C['bf16'])
code/snapshot/root/code/ceir_r1_test_comparison_20261110/infer.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Complete frozen pools scored by the actual CEIR model, not its C03 subset."""
2
+ from collections import defaultdict
3
+ from dataclasses import replace
4
+ import fcntl
5
+ import gzip
6
+ import hashlib
7
+ import json
8
+ import math
9
+ from pathlib import Path
10
+ import sys
11
+ import time
12
+ import torch
13
+ from evaluation_runtime import *
14
+
15
+ sys.path.insert(0,str(ROOT/'rebuild/post_training_evaluation_20261103'))
16
+ import evaluate as original
17
+ from eval_runtime import digest,supported_formula
18
+
19
+
20
+ def gzip_save(path,obj):
21
+ path=Path(path);path.parent.mkdir(parents=True,exist_ok=True);tmp=Path(str(path)+'.tmp')
22
+ with gzip.open(tmp,'wt',compresslevel=3) as f:json.dump(obj,f,separators=(',',':'),ensure_ascii=False,allow_nan=False)
23
+ tmp.replace(path)
24
+
25
+
26
+ def score_group(model,db,data,pools,aliases,formulas):
27
+ from specpartition_ms.chemistry import ADDUCTS
28
+ values=[{v:{} for v in pools} for _ in data];formula_values=[{v:[] for v in pools} for _ in data]
29
+ errors=[None if r['query'].adduct in ADDUCTS else 'unsupported_adduct:'+r['query'].adduct for r in data]
30
+ encoded={};queries={};fs={};contexts={}
31
+ with torch.inference_mode(),amp():
32
+ valid=[i for i,e in enumerate(errors) if e is None]
33
+ for start in range(0,len(valid),C['spectrum_batch']):
34
+ ids=valid[start:start+C['spectrum_batch']]
35
+ tokens,qs,_=model.spectrum.forward_batch([data[i]['query'] for i in ids])
36
+ for j,i in enumerate(ids):encoded[i]=(qs[j],tokens[j])
37
+ view_indices=[(i,v) for i in valid for v in pools]
38
+ for start in range(0,len(view_indices),C['spectrum_batch']):
39
+ block=view_indices[start:start+C['spectrum_batch']]
40
+ qlist=[replace(data[i]['query'],formula_candidates=formulas[v]) for i,v in block]
41
+ qq=torch.stack([encoded[i][0] for i,v in block]);pp=[encoded[i][1] for i,v in block]
42
+ batch_scores,batch_context=model.formula_batch(qq,qlist,pp,True)
43
+ for j,(i,v) in enumerate(block):
44
+ if not bool(torch.isfinite(batch_scores[j]).all()):raise RuntimeError('Nonfinite formula score')
45
+ queries[i,v]=qlist[j];fs[i,v]=batch_scores[j];contexts[i,v]=batch_context[j]
46
+ keys=sorted({a[0] for a in aliases.values() if a[0]})
47
+ molecules=[loads(db.execute('SELECT body FROM graphs WHERE graph_key=?',(k,)).fetchone()[0]) for k in keys]
48
+ positions={key:i for i,key in enumerate(keys)}
49
+ if molecules:
50
+ _,atoms,zm=model.encode_molecules(molecules)
51
+ for i in valid:
52
+ q,peaks=encoded[i]
53
+ for view,pool in pools.items():
54
+ selected=sorted({aliases[s][0] for s in pool if aliases[s][0]})
55
+ ids=[positions[k] for k in selected]
56
+ if not ids:continue
57
+ # Includes reverse local, learned fingerprint and chemical
58
+ # composition residuals in main; control retains its own path.
59
+ score,_,_=model.score_encoded(q,peaks,queries[i,view],[molecules[j] for j in ids],
60
+ [atoms[j] for j in ids],zm[ids],fs[i,view],contexts[i,view])
61
+ numeric=score.float().cpu().tolist()
62
+ if not all(math.isfinite(s) for s in numeric):raise RuntimeError('Nonfinite final structure score')
63
+ values[i][view]=dict(zip(selected,numeric))
64
+ for i in valid:
65
+ for view in pools:formula_values[i][view]=fs[i,view].float().cpu().tolist()
66
+ return values,formula_values,errors
67
+
68
+
69
+ def single_query_diagnostic(name):
70
+ """Actual GPU check against the existing encode_batch reference path."""
71
+ model,item=make_model(name);db=readonly(PREP/'msg_test.sqlite')
72
+ target=db.execute('SELECT DISTINCT target FROM spectra ORDER BY target LIMIT 1').fetchone()[0]
73
+ pools,aliases,fs,_=universe(db,target,'msg_test')
74
+ pools={v:p[:16] for v,p in pools.items()}
75
+ subset={s:aliases[s] for p in pools.values() for s in p}
76
+ data=[loads(b) for b, in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier LIMIT 2',(target,))]
77
+ scores,formulas,errors=score_group(model,db,data,pools,subset,fs)
78
+ maximum=0.;checks=0
79
+ with torch.inference_mode(),amp():
80
+ for i,row in enumerate(data):
81
+ if errors[i]:continue
82
+ for view,pool in pools.items():
83
+ keys=sorted({aliases[s][0] for s in pool if aliases[s][0]})
84
+ mols=tuple(loads(db.execute('SELECT body FROM graphs WHERE graph_key=?',(k,)).fetchone()[0]) for k in keys)
85
+ q=replace(row['query'],candidates=mols,formula_candidates=fs[view])
86
+ enc=model.encode_batch([q])[0][0]
87
+ ref={(m.identity,m.smiles):s for m,s in zip(q.candidates,enc.base.float().cpu().tolist())}
88
+ for key,m in zip(keys,mols):
89
+ maximum=max(maximum,abs(scores[i][view][key]-ref[m.identity,m.smiles]));checks+=1
90
+ if maximum>0.005:raise RuntimeError('GPU inference reference parity exceeded 0.005: '+str(maximum))
91
+ db.close();return dict(passed=True,checkpoint=item,comparisons=checks,max_abs_score_difference=maximum,
92
+ tolerance=0.005,probe_only_not_full_Test=True,spectrum_batch=C['spectrum_batch'],
93
+ graph_chunk=C['graph_chunk'],local_chunk=C['local_chunk'],training_steps=0,
94
+ peak_allocated_mib=torch.cuda.max_memory_allocated()/2**20,unix_time=time.time())
95
+
96
+
97
+ def probe(name):
98
+ """Compare to frozen Validation scores with the SAME batch/graph arithmetic.
99
+
100
+ A scalar-query forward changes BF16 padding/GEMM shapes and is not a
101
+ bitwise reference for the batched Validation inference protocol.
102
+ """
103
+ from evidence_ceir import EvidenceStore
104
+ model,item=make_model(name)
105
+ if item['arm']=='main':model.evidence=EvidenceStore([runtime.CACHE/'validation_composition.sqlite'])
106
+ db=readonly(runtime.LEGACY.PREP/'validation.sqlite')
107
+ target=db.execute('SELECT DISTINCT target FROM spectra ORDER BY target LIMIT 1').fetchone()[0]
108
+ pools={view:json.loads(db.execute('SELECT body FROM pools WHERE target=? AND view=?',(target,view)).fetchone()[0])
109
+ for view in ('mass','formula')}
110
+ aliases={s:tuple(db.execute('SELECT graph_key,identity,formula,error FROM aliases WHERE smiles=?',(s,)).fetchone())
111
+ for s in set(s for pool in pools.values() for s in pool)}
112
+ aliases={s:(a[0],a[1],a[2],None,None,a[3]) for s,a in aliases.items()}
113
+ formulas={v:tuple(sorted({supported_formula(aliases[s][2]) for s in pool}-{None})) for v,pool in pools.items()}
114
+ data=[loads(b) for b, in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier LIMIT 4',(target,))]
115
+ scores,fs,errors=score_group(model,db,data,pools,aliases,formulas)
116
+ reference=R1/item['arm']/('validation_update_%06d'%item['update'])/(hashlib.sha256(target.encode()).hexdigest()+'.json.gz')
117
+ with gzip.open(reference,'rt') as f:prior=json.load(f)
118
+ maximum=0.;formula_maximum=0.;checks=0
119
+ for i,row in enumerate(data):
120
+ if errors[i]:raise RuntimeError('Unexpected error on Validation parity input')
121
+ for view,pool in pools.items():
122
+ old=prior['ranked'][row['identifier']+'/'+view]
123
+ expected={entry['smiles']:entry['score'] for entry in old['candidates']}
124
+ for smiles in pool:
125
+ actual=scores[i][view].get(aliases[smiles][0]);before=expected[smiles]
126
+ if (actual is None)!=(before is None):raise RuntimeError('Validation scoreability parity mismatch')
127
+ if actual is not None:maximum=max(maximum,abs(actual-before));checks+=1
128
+ expected_formula={entry['formula']:entry['score'] for entry in old['formulas']}
129
+ for formula,value in zip(formulas[view],fs[i][view]):
130
+ formula_maximum=max(formula_maximum,abs(value-expected_formula[formula]))
131
+ if maximum>1e-5 or formula_maximum>1e-5:
132
+ raise RuntimeError('Frozen Validation parity failed: '+str((maximum,formula_maximum)))
133
+ db.close()
134
+ return dict(passed=True,checkpoint=item,reference_prediction=str(reference),reference_sha256=sha(reference),
135
+ validation_queries=len(data),candidate_score_comparisons=checks,max_abs_score_difference=maximum,
136
+ max_abs_formula_difference=formula_maximum,tolerance=1e-5,
137
+ same_graph_union_and_same_spectrum_batch_as_saved_Validation=True,
138
+ probe_only_not_Test_results=True,training_steps=0,unix_time=time.time())
139
+
140
+
141
+ def evaluate(name,dataset):
142
+ directory=OUT/'inference'/name/dataset;directory.mkdir(parents=True,exist_ok=True)
143
+ lock=(directory/'job.lock').open('a+');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
144
+ bound=dict(model=json.loads((OUT/'FROZEN.json').read_text())['models'][name],
145
+ frozen_release_sha256=sha(OUT/'FROZEN.json'),dataset=dataset,inputs=inputs(dataset),
146
+ candidate_limit=None,truth_injection=False,ranking='original_raw_entry_rank',
147
+ spectrum_batch=C['spectrum_batch'],graph_chunk=C['graph_chunk'],local_chunk=C['local_chunk'],
148
+ score='actual_CEIRRanker.formula_batch_and_score_encoded',posthoc_MCES_enabled=True)
149
+ path=directory/'binding.json'
150
+ if path.exists() and json.loads(path.read_text())!=bound:raise RuntimeError('Refusing incompatible inference resume')
151
+ save(path,bound);binding_id=digest(bound)
152
+ if (directory/'COMPLETE.json').exists():return
153
+ with gpu_slot(directory):model,frozen=make_model(name)
154
+ db=readonly(PREP/(dataset+'.sqlite'))
155
+ targets=[r[0] for r in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target')]
156
+ started=time.monotonic();summary=[]
157
+ for ti,target in enumerate(targets):
158
+ filename=hashlib.sha256(target.encode()).hexdigest()+'.json.gz';output=directory/'per_target'/filename
159
+ if output.exists():
160
+ with gzip.open(output,'rt') as f:prior=json.load(f)
161
+ if prior['binding_id']!=binding_id:raise RuntimeError('Target prediction binding changed')
162
+ summary.extend(prior['rows']);continue
163
+ data=[loads(r[0]) for r in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier',(target,))]
164
+ pools,aliases,fs,source=universe(db,target,dataset)
165
+ with gpu_slot(directory):values,fvalues,errors=score_group(model,db,data,pools,aliases,fs)
166
+ rows=[];predictions=[]
167
+ for i,r in enumerate(data):
168
+ ref=db.execute('SELECT canonical,fullkey FROM aliases WHERE smiles=?',(r['reference_smiles'],)).fetchone()
169
+ if ref is None:raise RuntimeError('Reference evaluation alias missing')
170
+ for view,pool in pools.items():
171
+ scores,order=original.rank_entries(pool,aliases,values[i][view])
172
+ def match_rank(column,value):
173
+ return next((j+1 for j,k in enumerate(order) if scores[k] is not None and value is not None and aliases[pool[k]][column]==value),None)
174
+ rank=match_rank(1,r['identity']);truth=supported_formula(r['formula']);fv=fvalues[i][view]
175
+ order_f=sorted(range(len(fv)),key=lambda j:(-fv[j],fs[view][j]))
176
+ frank=next((j+1 for j,k in enumerate(order_f) if fs[view][k]==truth),None)
177
+ rows.append(dict(identifier=r['identifier'],target=target,view=view,reference_identity=r['identity'],
178
+ reference_smiles=r['reference_smiles'],reference_formula=r['formula'],reference_formula_supported=truth is not None,
179
+ formula_rank=frank,formula_count=len(fs[view]),reference_formula_in_pool=truth is not None and truth in fs[view],
180
+ rank=rank,canonical_rank=match_rank(3,ref[0]),inchikey_rank=match_rank(4,ref[1]),
181
+ reference_in_pool=any(aliases[s][1]==r['identity'] for s in pool),
182
+ reference_scoreable_in_pool=any(aliases[s][1]==r['identity'] and scores[j] is not None for j,s in enumerate(pool)),
183
+ candidate_count=len(pool),unscoreable=sum(s is None for s in scores),query_error=errors[i],
184
+ adduct=r['query'].adduct,polarity='negative' if r['query'].adduct.endswith('-') else 'positive',
185
+ top1_smiles=pool[order[0]] if order and scores[order[0]] is not None else None,
186
+ peak_count=len(r['query'].peaks),instrument=r['query'].instrument,collision_energy=r['query'].collision_energy,
187
+ same_formula_candidates=sum(aliases[s][2]==truth for s in pool),
188
+ recall_at_k={str(k):rank is not None and rank<=k for k in original.KS},
189
+ formula_recall_at_k={str(k):frank is not None and frank<=k for k in original.FKS},extra=r['extra']))
190
+ predictions.append(dict(identifier=r['identifier'],view=view,scores_in_raw_pool_order=scores,
191
+ ranked_raw_pool_indices=order,formulas=list(fs[view]),formula_scores=fv,ranked_formula_indices=order_f))
192
+ pool_file=OUT/'shared_pools'/dataset/filename;pool_file.parent.mkdir(parents=True,exist_ok=True)
193
+ with pool_file.with_suffix('.lock').open('a+') as shared_lock:
194
+ fcntl.flock(shared_lock,fcntl.LOCK_EX)
195
+ if not pool_file.exists():
196
+ gzip_save(pool_file,dict(target=target,pools={view:[dict(smiles=s,graph_key=aliases[s][0],key14=aliases[s][1],
197
+ formula=aliases[s][2],canonical_smiles=aliases[s][3],full_inchikey=aliases[s][4],error=aliases[s][5]) for s in pool]
198
+ for view,pool in pools.items()},source=source,candidate_order_sha256={v:digest(p) for v,p in pools.items()}))
199
+ gzip_save(output,dict(binding_id=binding_id,target=target,static_candidate_file=str(pool_file),
200
+ candidate_order_sha256={v:digest(p) for v,p in pools.items()},rows=rows,predictions=predictions))
201
+ summary.extend(rows);check_disk()
202
+ save(directory/'status.json',dict(phase='inference',targets=ti+1,total_targets=len(targets),spectral_views=len(summary),
203
+ seconds=time.monotonic()-started,unix_time=time.time()))
204
+ if ti%25==0:print(json.dumps(dict(model=name,dataset=dataset,targets=ti+1,total=len(targets))),flush=True)
205
+ db.close();expected=17556 if dataset=='msg_test' else 500
206
+ result=dict(model=name,dataset=dataset,checkpoint=frozen,binding_id=binding_id,views={},
207
+ protocol='official_raw_entry_ranking' if dataset=='msg_test' else 'frozen_blind_top10_pubchem_10ppm_full_pool',
208
+ formula_scope='supported_distinct_official_pool_formulas' if dataset=='msg_test' else 'reranking_frozen_SIRIUS_top10_formulas_not_independent_prediction',
209
+ no_test_checkpoint_selection=True,mces='authorized_separate_posthoc_job',seconds=time.monotonic()-started)
210
+ for view in sorted({r['view'] for r in summary}):
211
+ rr=[r for r in summary if r['view']==view]
212
+ if len(rr)!=expected or len({r['identifier'] for r in rr})!=expected:raise RuntimeError('Incomplete/duplicate test denominator')
213
+ result['views'][view]=original.aggregate(rr)
214
+ for key in ('adduct','polarity'):
215
+ result['views'][view]['by_'+key]={k:original.aggregate([r for r in rr if r[key]==k]) for k in sorted({r[key] for r in rr})}
216
+ if dataset=='casmi2022':
217
+ if sum(r['candidate_count'] for r in rr)!=1765420:raise RuntimeError('CASMI full pool count changed')
218
+ result['views'][view]['frozen_reference_covered']=sum(r['extra']['frozen_reference_covered'] for r in rr)
219
+ gzip_save(directory/'per_spectrum_summary.json.gz',summary);save(directory/'metrics.json',result)
220
+ save(directory/'COMPLETE.json',dict(complete=True,model=name,dataset=dataset,metrics_sha256=sha(directory/'metrics.json'),unix_time=time.time()))
221
+ del model;torch.cuda.empty_cache()
222
+
223
+
224
+ def run(arm):
225
+ OUT.mkdir(parents=True,exist_ok=True)
226
+ while not (OUT/'FROZEN.json').exists():time.sleep(2)
227
+ if arm=='main':
228
+ while not (OUT/'prepared/COMPLETE.json').exists():time.sleep(5)
229
+ acceptance=OUT/(arm+'_GPU_ACCEPTANCE.json')
230
+ if not acceptance.exists():
231
+ with gpu_slot(OUT):value=probe(f'{arm}_003000')
232
+ save(acceptance,value)
233
+ for update in (3000,4000):
234
+ for dataset in C['datasets']:evaluate(f'{arm}_{update:06d}',dataset)
235
+ save(OUT/(arm+'_INFERENCE_COMPLETE.json'),dict(complete=True,updates=[3000,4000],datasets=C['datasets'],unix_time=time.time()))
236
+
237
+
238
+ if __name__=='__main__':
239
+ import argparse
240
+ p=argparse.ArgumentParser();p.add_argument('--arm',choices=['main','control'],required=True);a=p.parse_args();run(a.arm)
code/snapshot/root/code/ceir_r1_test_comparison_20261110/mces.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed-protocol post-hoc MCES with a private copy of the existing pair cache."""
2
+ from concurrent.futures import ProcessPoolExecutor
3
+ import gzip
4
+ import hashlib
5
+ import importlib.util
6
+ import json
7
+ import math
8
+ from pathlib import Path
9
+ import sqlite3
10
+ import statistics
11
+ import sys
12
+ import time
13
+
14
+ HERE=Path(__file__).resolve().parent;C=json.loads((HERE/'config.json').read_text());OUT=Path(C['output'])
15
+ OLD=Path('/root/xj/SpecPartition-MS/evaluations/mces_all_20261106')
16
+ spec=importlib.util.spec_from_file_location('frozen_mces_baseline_engine',OLD/'evaluate_all.py')
17
+ old=importlib.util.module_from_spec(spec);sys.modules[spec.name]=old;spec.loader.exec_module(old)
18
+
19
+
20
+ def save(path,obj):
21
+ path=Path(path);path.parent.mkdir(parents=True,exist_ok=True);tmp=Path(str(path)+'.tmp')
22
+ if str(path).endswith('.gz'):
23
+ with gzip.open(tmp,'wt',compresslevel=3) as f:json.dump(obj,f,separators=(',',':'),allow_nan=False)
24
+ else:tmp.write_text(json.dumps(obj,indent=2,allow_nan=False)+'\n')
25
+ tmp.replace(path)
26
+
27
+
28
+ def digest(path):
29
+ h=hashlib.sha256()
30
+ with Path(path).open('rb') as f:
31
+ for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
32
+ return h.hexdigest()
33
+
34
+
35
+ def initialize():
36
+ folder=OUT/'mces';folder.mkdir(parents=True,exist_ok=True)
37
+ if not (folder/'pairs.sqlite').exists():
38
+ source=sqlite3.connect('file:'+str(OLD/'pairs.sqlite')+'?mode=ro',uri=True)
39
+ target=sqlite3.connect(folder/'pairs.sqlite');source.backup(target);target.close();source.close()
40
+ save(folder/'CACHE_SOURCE.json',dict(source=str(OLD/'pairs.sqlite'),copied_readonly=True,source_modified=False,
41
+ protocol_id=old.PROTOCOL_ID,unix_time=time.time()))
42
+ provenance=old.provenance(folder)
43
+ if provenance['packages']['myopic-mces']!=C['mces']['version'] or provenance['packages']['pulp']!=C['mces']['pulp']:
44
+ raise RuntimeError('MCES dependency mismatch')
45
+ original=json.loads((OLD/'provenance.json').read_text())
46
+ if original['protocol_id']!=old.PROTOCOL_ID or provenance['module_sha256']!=original['module_sha256']:
47
+ raise RuntimeError('MCES baseline engine mismatch')
48
+ return old.connect(folder)
49
+
50
+
51
+ def compute(directory,db):
52
+ with gzip.open(directory/'per_spectrum_summary.json.gz','rt') as f:rows=json.load(f)
53
+ inputs=[];todo={}
54
+ for row in rows:
55
+ truth=old.identity(row['reference_smiles']);prediction=old.identity(row.get('top1_smiles'));key=None
56
+ if truth and prediction:
57
+ key=hashlib.sha256(json.dumps([old.PROTOCOL_ID,truth[0],prediction[0]],separators=(',',':')).encode()).hexdigest()
58
+ found=db.execute('SELECT status FROM pairs WHERE id=?',(key,)).fetchone()
59
+ if found is None or found[0]!='completed':
60
+ todo[key]=(key,truth[0],prediction[0])
61
+ db.execute('INSERT OR IGNORE INTO pairs(id,s1,s2,priority) VALUES (?,?,?,0)',todo[key])
62
+ inputs.append((row,key))
63
+ db.commit();tasks=list(todo.values());done=0;started=time.monotonic()
64
+ with ProcessPoolExecutor(max_workers=C['mces']['workers']) as pool:
65
+ for start in range(0,len(tasks),128):
66
+ for key,status,value,mode,seconds,detail in pool.map(old.worker,tasks[start:start+128],chunksize=1):
67
+ db.execute('UPDATE pairs SET status=?,distance=?,mode=?,seconds=?,detail=?,attempts=attempts+1 WHERE id=?',
68
+ (status,value,mode,seconds,detail,key));done+=1
69
+ db.commit();save(directory/'MCES_status.json',dict(processed_new_pairs=done,total_new_pairs=len(tasks),
70
+ seconds=time.monotonic()-started,unix_time=time.time()))
71
+ result={};details=[]
72
+ for view in sorted({r['view'] for r in rows}):
73
+ valid=[];missing=0;modes={};unresolved=0
74
+ selected=[(r,k) for r,k in inputs if r['view']==view]
75
+ for row,key in selected:
76
+ hit=db.execute('SELECT status,distance,mode,detail FROM pairs WHERE id=?',(key,)).fetchone() if key else None
77
+ value=hit[1] if hit and hit[0]=='completed' else None
78
+ meta=json.loads(hit[3]) if hit and hit[3] else {}
79
+ if value is None:missing+=1
80
+ else:
81
+ if not math.isfinite(value) or value<0:raise RuntimeError('Invalid cached MCES')
82
+ valid.append(value);modes[str(hit[2])]=modes.get(str(hit[2]),0)+1
83
+ timed=any(s['status'] not in (1,-1) or (s['status']==1 and s['solution_status'] not in (1,2)) for s in meta.get('solver_states',[]))
84
+ unresolved+=timed
85
+ details.append(dict(identifier=row['identifier'],view=view,distance=value,mode=hit[2] if hit else None,
86
+ solver_unresolved=timed,detail=meta,missing_reason='missing_prediction' if not key else ('solver_failure' if value is None else None)))
87
+ result[view]=dict(n=len(selected),valid=len(valid),missing=missing,valid_mean=statistics.mean(valid) if valid else None,
88
+ full_mean=statistics.mean(valid) if valid and not missing else None,modes=modes,solver_unresolved=unresolved)
89
+ save(directory/'MCES_per_spectrum.json.gz',details)
90
+ save(directory/'MCES.json',dict(complete=True,protocol=old.PROTOCOL,protocol_id=old.PROTOCOL_ID,
91
+ views=result,approximation_and_timeout_modes_preserved=True,predictions_modified=False,unix_time=time.time()))
92
+
93
+
94
+ def run():
95
+ OUT.mkdir(parents=True,exist_ok=True)
96
+ while not (OUT/'FROZEN.json').exists():time.sleep(2)
97
+ db=initialize()
98
+ names=[f'{arm}_{u:06d}' for arm in ('main','control') for u in (3000,4000)]
99
+ while True:
100
+ pending=[]
101
+ for name in names:
102
+ for dataset in C['datasets']:
103
+ directory=OUT/'inference'/name/dataset
104
+ if not (directory/'MCES.json').exists():
105
+ pending.append(str(directory))
106
+ if (directory/'COMPLETE.json').exists():compute(directory,db)
107
+ all_complete=all((OUT/'inference'/name/d/'MCES.json').exists() for name in names for d in C['datasets'])
108
+ save(OUT/'MCES_progress.json',dict(complete=all_complete,pending=pending,unix_time=time.time()))
109
+ if all_complete:
110
+ save(OUT/'ALL_INFERENCE_AND_MCES_COMPLETE.json',dict(complete=True,models=names,datasets=C['datasets'],unix_time=time.time()))
111
+ db.close();return
112
+ time.sleep(5)
113
+
114
+
115
+ if __name__=='__main__':run()
code/snapshot/root/code/ceir_r1_test_comparison_20261110/parallel-models.supervisor.conf ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [program:specpartition-ceir-test-main3k-20261110]
2
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110
3
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u -c "from infer import evaluate; evaluate('main_003000','msg_test'); evaluate('main_003000','casmi2022')"
4
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
5
+ autostart=false
6
+ autorestart=false
7
+ startsecs=5
8
+ stopasgroup=true
9
+ killasgroup=true
10
+ stdout_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/main_003000.log
11
+ stderr_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/main_003000_error.log
12
+ stdout_logfile_maxbytes=20MB
13
+ stderr_logfile_maxbytes=20MB
14
+
15
+ [program:specpartition-ceir-test-main4k-20261110]
16
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110
17
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u -c "from infer import evaluate; evaluate('main_004000','msg_test'); evaluate('main_004000','casmi2022')"
18
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
19
+ autostart=false
20
+ autorestart=false
21
+ startsecs=5
22
+ stopasgroup=true
23
+ killasgroup=true
24
+ stdout_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/main_004000.log
25
+ stderr_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/main_004000_error.log
26
+ stdout_logfile_maxbytes=20MB
27
+ stderr_logfile_maxbytes=20MB
28
+
29
+ [program:specpartition-ceir-test-control3k-20261110]
30
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110
31
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u -c "from infer import evaluate; evaluate('control_003000','msg_test'); evaluate('control_003000','casmi2022')"
32
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
33
+ autostart=false
34
+ autorestart=false
35
+ startsecs=5
36
+ stopasgroup=true
37
+ killasgroup=true
38
+ stdout_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/control_003000.log
39
+ stderr_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/control_003000_error.log
40
+ stdout_logfile_maxbytes=20MB
41
+ stderr_logfile_maxbytes=20MB
42
+
43
+ [program:specpartition-ceir-test-control4k-20261110]
44
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110
45
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u -c "from infer import evaluate; evaluate('control_004000','msg_test'); evaluate('control_004000','casmi2022')"
46
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
47
+ autostart=false
48
+ autorestart=false
49
+ startsecs=5
50
+ stopasgroup=true
51
+ killasgroup=true
52
+ stdout_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/control_004000.log
53
+ stderr_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/control_004000_error.log
54
+ stdout_logfile_maxbytes=20MB
55
+ stderr_logfile_maxbytes=20MB
code/snapshot/root/code/ceir_r1_test_comparison_20261110/prepare.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Input-only Test annotations. Does not read reference SMILES/formula fields."""
2
+ from collections import Counter
3
+ from concurrent.futures import ProcessPoolExecutor
4
+ import json
5
+ import multiprocessing
6
+ import sqlite3
7
+ import time
8
+ import zlib
9
+ from evaluation_runtime import *
10
+ from evidence_ceir import annotate,encode
11
+
12
+
13
+ def initialize_worker():
14
+ from functools import lru_cache
15
+ from rdkit import RDLogger
16
+ import evidence_ceir
17
+ RDLogger.DisableLog('rdApp.*')
18
+ evidence_ceir.library=lru_cache(maxsize=C['annotation_formula_cache'])(evidence_ceir.library.__wrapped__)
19
+
20
+
21
+ def worker(task):
22
+ q,formulas=task;key=query_key(q)
23
+ return [(key,f,encode(annotate(q,f))) for f in formulas]
24
+
25
+
26
+ def tasks(dataset):
27
+ db=readonly(PREP/(dataset+'.sqlite'))
28
+ for target, in db.execute('SELECT DISTINCT target FROM spectra ORDER BY target'):
29
+ _,_,formulas,_=universe(db,target,dataset)
30
+ fs=tuple(sorted(set(f for values in formulas.values() for f in values)))
31
+ for body, in db.execute('SELECT body FROM spectra WHERE target=? ORDER BY identifier',(target,)):
32
+ # Only this label-free query object and official/frozen formula union
33
+ # enter annotation; reference identity and reference formula are unused.
34
+ yield loads(body)['query'],fs
35
+ db.close()
36
+
37
+
38
+ def prepare():
39
+ OUT.mkdir(parents=True,exist_ok=True);check_disk();frozen=freeze()
40
+ dest=OUT/'prepared';dest.mkdir(exist_ok=True)
41
+ with ProcessPoolExecutor(max_workers=C['annotation_workers'],initializer=initialize_worker,mp_context=multiprocessing.get_context('spawn')) as pool:
42
+ for dataset in C['datasets']:
43
+ marker=dest/(dataset+'_composition_READY.json')
44
+ if marker.exists():
45
+ old=json.loads(marker.read_text())
46
+ if old['inputs']!=frozen['inputs'][dataset] or old['rule']!=RULE:raise RuntimeError('Annotation binding changed')
47
+ continue
48
+ db=sqlite3.connect(dest/(dataset+'_composition.sqlite'));db.execute('PRAGMA journal_mode=WAL')
49
+ db.execute('CREATE TABLE IF NOT EXISTS evidence(query_key TEXT,formula TEXT,body BLOB,PRIMARY KEY(query_key,formula))')
50
+ scanned=0;needed=0;reason=Counter();started=time.monotonic();pending=iter(tasks(dataset));done=False
51
+ while not done:
52
+ chunk=[]
53
+ for _ in range(C['annotation_query_chunk']):
54
+ try:q,fs=next(pending)
55
+ except StopIteration:done=True;break
56
+ key=query_key(q);scanned+=1
57
+ missing=[f for f in fs if db.execute('SELECT 1 FROM evidence WHERE query_key=? AND formula=?',(key,f)).fetchone() is None]
58
+ needed+=len(fs)
59
+ if missing:chunk.append((q,missing))
60
+ for result in pool.map(worker,chunk,chunksize=2):
61
+ for key,f,blob in result:
62
+ db.execute('INSERT OR IGNORE INTO evidence VALUES (?,?,?)',(key,f,blob))
63
+ meta=json.loads(zlib.decompress(blob));reason[meta['reason']]+=1
64
+ db.commit();check_disk()
65
+ save(dest/'status.json',dict(dataset=dataset,queries_scanned=scanned,total_queries=17556 if dataset=='msg_test' else 500,
66
+ reason=dict(reason),seconds=time.monotonic()-started,unix_time=time.time()))
67
+ print(json.dumps(dict(dataset=dataset,queries=scanned,annotation_requests=needed,seconds=time.monotonic()-started)),flush=True)
68
+ expected=17556 if dataset=='msg_test' else 500
69
+ if scanned!=expected:raise RuntimeError('Annotation query denominator mismatch')
70
+ count=db.execute('SELECT COUNT(*) FROM evidence').fetchone()[0]
71
+ db.execute('PRAGMA wal_checkpoint(TRUNCATE)');db.close()
72
+ save(marker,dict(complete=True,rule=RULE,inputs=frozen['inputs'][dataset],queries=scanned,
73
+ unique_pairs=count,annotation_requests=needed,reasons_generated_this_attempt=dict(reason),
74
+ labels_used=False,reference_structure_used=False,original_pools_unchanged=True,unix_time=time.time()))
75
+ save(dest/'COMPLETE.json',dict(complete=True,datasets=C['datasets'],labels_used=False,unix_time=time.time()))
76
+
77
+
78
+ if __name__=='__main__':prepare()
code/snapshot/root/code/ceir_r1_test_comparison_20261110/supervisor.conf ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [program:specpartition-ceir-test-prepare-20261110]
2
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110
3
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u prepare.py
4
+ environment=CUDA_VISIBLE_DEVICES="",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1"
5
+ autostart=false
6
+ autorestart=false
7
+ startsecs=5
8
+ stopasgroup=true
9
+ killasgroup=true
10
+ stdout_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/prepare.log
11
+ stderr_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/prepare_error.log
12
+ stdout_logfile_maxbytes=20MB
13
+ stderr_logfile_maxbytes=20MB
14
+
15
+ [program:specpartition-ceir-test-control-20261110]
16
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110
17
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u infer.py --arm control
18
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
19
+ autostart=false
20
+ autorestart=false
21
+ startsecs=5
22
+ stopasgroup=true
23
+ killasgroup=true
24
+ stdout_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/control.log
25
+ stderr_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/control_error.log
26
+ stdout_logfile_maxbytes=20MB
27
+ stderr_logfile_maxbytes=20MB
28
+
29
+ [program:specpartition-ceir-test-main-20261110]
30
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110
31
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u infer.py --arm main
32
+ environment=OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1",CUBLAS_WORKSPACE_CONFIG=":4096:8"
33
+ autostart=false
34
+ autorestart=false
35
+ startsecs=5
36
+ stopasgroup=true
37
+ killasgroup=true
38
+ stdout_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/main.log
39
+ stderr_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/main_error.log
40
+ stdout_logfile_maxbytes=20MB
41
+ stderr_logfile_maxbytes=20MB
42
+
43
+ [program:specpartition-ceir-test-mces-20261110]
44
+ directory=/root/xj/SpecPartition-MS/code/ceir_r1_test_comparison_20261110
45
+ command=/usr/bin/nice -n 19 /root/xj/SpecPartition-MS/evaluations/mces_all_20261106/.venv/bin/python -u mces.py
46
+ environment=CUDA_VISIBLE_DEVICES="",OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",PYTHONDONTWRITEBYTECODE="1"
47
+ autostart=false
48
+ autorestart=false
49
+ startsecs=5
50
+ stopasgroup=true
51
+ killasgroup=true
52
+ stdout_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/mces.log
53
+ stderr_logfile=/root/xj/SpecPartition-MS/evaluations/ceir_r1_test_comparison_20261110/logs/mces_error.log
54
+ stdout_logfile_maxbytes=20MB
55
+ stderr_logfile_maxbytes=20MB
code/snapshot/root/code/ceir_r1_test_comparison_20261110/test_logic.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from dataclasses import replace
3
+ from types import SimpleNamespace
4
+ import unittest
5
+ import numpy as np
6
+ from evaluation_runtime import C,MODELS
7
+ from evidence_ceir import annotate,query_key
8
+
9
+
10
+ class EvaluationTests(unittest.TestCase):
11
+ def test_exact_model_set_before_Test(self):
12
+ self.assertEqual(set(MODELS),{'main_003000','main_004000','control_003000','control_004000'})
13
+
14
+ def test_no_candidate_truncation_or_truth_injection(self):
15
+ self.assertIsNone(C['candidate_limit']);self.assertFalse(C['truth_injection'])
16
+ self.assertFalse(C['test_used_for_selection']);self.assertFalse(C['training_or_optimizer_updates'])
17
+
18
+ def test_primary_checkpoint_is_preselected(self):
19
+ self.assertEqual(C['primary_update'],3000);self.assertEqual(C['fixed_endpoint_update'],4000)
20
+ self.assertEqual(len(C['parent_sha256']),64)
21
+
22
+ def test_annotation_does_not_use_reference_fields(self):
23
+ q=SimpleNamespace(peaks=((50.,1.),(80.,.5)),precursor_mz=123.4,adduct='[M+H]+',collision_energy=None,instrument=None)
24
+ before=annotate(q,'C6H12O6');key=query_key(q)
25
+ q.reference_smiles='invalid_truth_must_not_be_read';q.reference_formula='C9999';q.identity='not_a_feature'
26
+ after=annotate(q,'C6H12O6')
27
+ self.assertEqual(query_key(q),key)
28
+ np.testing.assert_array_equal(before['features'],after['features'])
29
+ np.testing.assert_array_equal(before['valid'],after['valid'])
30
+
31
+ def test_raw_aliases_still_consume_ranking_positions(self):
32
+ import sys
33
+ from pathlib import Path
34
+ sys.path.insert(0,str(Path(C['root'])/'rebuild/post_training_evaluation_20261103'))
35
+ from evaluate import rank_entries
36
+ aliases={'a':('g','same'),'b':('g','same'),'c':('h','other'),'d':(None,'missing')}
37
+ scores,order=rank_entries(['a','b','c','d'],aliases,{'g':3.,'h':2.})
38
+ self.assertEqual(order,[0,1,2,3]);self.assertIsNone(scores[3])
39
+
40
+
41
+ if __name__=='__main__':unittest.main()
code/snapshot/root/code/ceir_r2_20261110/METHOD.md ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CEIR-R2: C03-preserving chemical and connected-fragment evidence
2
+
3
+ ## Authority and scope
4
+
5
+ Independent continuation of C03 `step_002000.pt`, SHA256
6
+ `8a2982f3821fad501ba4f39ac8b1495affeb0c1b09051f2103317f36027d48b6`.
7
+ Old data, pools, checkpoints, code and services are read-only. Formal training
8
+ requires completed offline preparation and real GPU acceptance. Temporary
9
+ preflight updates never count as scientific continuation steps.
10
+
11
+ Four arms start from exactly the same old parameters, optimizer moments and RNG:
12
+
13
+ | Arm | Negative draws | New learned evidence |
14
+ | --- | --- | --- |
15
+ | A0 | Actual original C03 random sampling with replacement | None |
16
+ | A1 | Random distinct negative key14 where available | None |
17
+ | A2 | Same frozen draws as A1 | Seven chemical count distributions |
18
+ | A3 | Same frozen draws as A1 | A2 plus connected-fragment intensity and peak matching |
19
+
20
+ The independent-identity sampler is a training-only draw intervention. It does
21
+ not deduplicate or alter the raw candidate records. A0 keeps the original draw
22
+ distribution. Small pools in A1/A2/A3 use all available independent negatives;
23
+ their realized budget and original A0 repeated draws are reported, not claimed
24
+ to be identical physical compute. Positives must already exist in the original
25
+ eligible pool. No Test/CASMI structure may become a training negative.
26
+
27
+ ## Preserved supervision
28
+
29
+ The actual C03 active objective and weights are retained: formula CE, its
30
+ configured hard-formula gap and element supervision; grouped MS-to-molecule and
31
+ molecule-to-multiple-MS contrastive objectives; fine MS-MS and stochastic
32
+ molecule-molecule auxiliaries; and one final-score candidate-pool softmax CE for
33
+ each o_data, MSG Mass and MSG Formula view. Different MS of the same connectivity
34
+ are not negatives. MSG uses both official views, not a merged candidate pool.
35
+ Parent batches and data cursor are replayed verbatim; some steps have an empty
36
+ o_data group at the parent epoch boundary. Therefore the manifest, not a claim
37
+ that every step has 288 records, defines exposure.
38
+
39
+ All arms receive the same engineering correction: reinstall the molecular
40
+ dropout hook during activation recomputation. Zero-weight coarse losses are not
41
+ evaluated, but their head zero gradients are retained for AdamW semantics.
42
+ There is no duplicate same-pool CE, R1 conditional CE, R1 fingerprint auxiliary,
43
+ R1 teacher-mining index, SIRIUS score or CSI score in this release.
44
+
45
+ ## A2: chemical count evidence
46
+
47
+ The spectrum representation predicts seven 33-class distributions (0–31,
48
+ overflow 32): OH, carbonyl, ether SMARTS matches, aromatic rings, aliphatic rings,
49
+ heterocycles and components. SMARTS match counts are descriptors, not a claim
50
+ that overlapping functional-group definitions are independent observations.
51
+ Each candidate is evaluated against those distributions. The candidate count
52
+ log-probability averaged across traits, centered on the uniform distribution,
53
+ is a learned residual to the unchanged parent score. The last classifier layer
54
+ is initialized to zero, so the initial residual is exactly zero. The scale is
55
+ nonzero to avoid R1's tiny-gate/dead-gradient problem.
56
+
57
+ Reference counts are training targets only. They are not passed to inference.
58
+ The count auxiliary is averaged by independent reference connectivity, with a
59
+ maximum weight 0.05 after a 100-step ramp.
60
+
61
+ ## A3: connected cut hypotheses, not oracle fragments
62
+
63
+ At most 32 connected proper subgraphs are constructed per candidate from
64
+ deterministically selected non-ring single-bond cuts and pairs of ring cuts.
65
+ Their atom membership, cut boundaries, original atom/H masses and masks are
66
+ precomputed. Their representations pool the **current trainable GNN** atom
67
+ features; old GNN embeddings are not cached as student features.
68
+
69
+ A candidate-and-adduct/CE/instrument-conditioned intensity head predicts five
70
+ hydrogen-shift hypotheses and up to two ion-retention templates per subgraph.
71
+ It cannot read the observed spectrum when reconstructing it. Exact observed
72
+ peak locations provide a deterministic matching mask and a discriminative
73
+ fragment–peak alignment branch. Unexplained predicted intensity contributes to
74
+ the reconstruction denominator, preventing all unmatched hypotheses from being
75
+ silently discarded. The final residual readout is zero-initialized.
76
+
77
+ These are approximate fragmentation hypotheses, not guaranteed chemical
78
+ products or supervised fragment annotations. Hypothesis matching uses
79
+ `max(20 ppm, 0.02 Da)`; this is **not** the candidate generation tolerance.
80
+ The original candidate precursor 10 ppm checks and frozen pools are unchanged.
81
+ Double-charge and unsupported fragment structures retain the complete parent
82
+ score and count branch; they are not removed. Spectrum supervision is applied
83
+ only where the positive hypothesis mask explains at least 5% of non-precursor
84
+ intensity and input mass QC passes. The eligibility count is logged. A record
85
+ appearing in MSG Mass and Formula gets this auxiliary once, not twice.
86
+
87
+ ## Joint objective and numerical controls
88
+
89
+ `L = L_actual_C03 + ramp * (0.05 L_count + 0.05 L_spectrum)`
90
+ with each new term enabled only for its arm. Final pool CE is computed on the
91
+ actual final score, once. Formula learning is not frozen or replaced.
92
+
93
+ Backbone learning rate is 0.3 times the parent's saved learning rate; new heads
94
+ use 1e-4. A common 100-step ramp and predeclared 2k cosine continuation schedule
95
+ apply. The initial pilot ends at cumulative 3,000 (+1,000) updates. All 2k
96
+ prospective candidate ledgers are prepared so a Validation-authorized paired
97
+ extension will not introduce an on-the-fly sampling change.
98
+
99
+ Training chunks: spectrum 16, graph 256/local 128, 8 candidate views per microbatch;
100
+ effective source batches and original candidate budgets are not reduced.
101
+ Validation uses spectrum batch 16 and graph/local chunk 32 in every arm,
102
+ including a freshly evaluated C03 baseline. BF16 weighted-local rounding is
103
+ preserved before zero-initialized FP32 residuals are added.
104
+
105
+ The configuration is chosen from a real mixed-batch engineering probe, not a
106
+ claim of production-wide speedup: A0 was 3.56s at graph128/views4 and 2.43s at
107
+ graph256/views8; A3 was 7.27s and 5.66s respectively. Peak allocated memory was
108
+ about 1.8 GiB with the selected tile in that batch. Larger views16 did not help
109
+ A3, so it was not adopted. BF16 grouping and molecular dropout chunk shapes can
110
+ change numerical trajectories; all formal arms use the same selected setting.
111
+
112
+ The preflight found that raw asset alias strings can retain stereo while the
113
+ parent's graph reparses non-stereo canonical SMILES. An independent canonical
114
+ feature table aligns exactly to the parent atom order. Partial raw R2 features
115
+ remain as audit evidence; they are not selected by training. No original data
116
+ or candidate identity was removed or changed in this repair.
117
+
118
+ ## Acceptance and decision rules
119
+
120
+ Verify chemical sanity, original A0 draw equivalence, all-identity safety,
121
+ initial C03 score parity, candidate permutation invariance, active old/new
122
+ gradients, finite joint objectives and full-state resume reproducibility on a
123
+ real mixed 288-query batch. Complete official Validation at cumulative 3,000;
124
+ the stable-hash 128-target probes at 2,250/2,500 are diagnostics, not final
125
+ reported benchmark performance.
126
+
127
+ Select by the harmonic mean of full-Validation Mass/Formula Top1, with each
128
+ view's Top1 degradation limited to 0.2 percentage points and MCES checked.
129
+ Preserve all arms, including negative results. Report Top1/3/5/10/20/50/100/200,
130
+ pool formula Top1–10 and MCES using unchanged denominators and missing-value
131
+ policy. Test/CASMI cannot select a checkpoint. Prior Test/CASMI badcases have
132
+ informed this design, so those sets are development-exposed, not pristine final
133
+ holdouts. No improvement is promised before results exist.
code/snapshot/root/code/ceir_r2_20261110/acceptance_r2.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real GPU, initial-score, gradient and exact full-state resume acceptance."""
2
+ import argparse
3
+ import gc
4
+ import json
5
+ import time
6
+ import traceback
7
+ import uuid
8
+ from dataclasses import replace
9
+ from runtime_r2 import *
10
+
11
+
12
+ def run(provisional=False):
13
+ import torch
14
+ from data_r2 import Dataset
15
+ from model_r2_new import make_model_optimizer
16
+ from objectives_r2 import train_step
17
+ from objectives_r2 import chemical_loss
18
+ from prepare_ceir import load_teacher
19
+ from test_features_r2 import run as feature_tests
20
+ feature_tests();setup_gpu()
21
+ if provisional:
22
+ info=json.loads((PREP/'PROBE_READY.json').read_text());index=info['index'];feature_path=PREP/'probe.sqlite';bind=dict(provisional=True,code=code_manifest())
23
+ else:
24
+ if not (PREP/'READY.json').exists():raise RuntimeError('Full R2 data preparation incomplete')
25
+ info=json.loads((PREP/'PROBE_READY.json').read_text());index=info['index'];feature_path=PREP/'assets.sqlite';bind=binding()
26
+ if any((run_dir(a)/'last.pt').exists() for a in C['arms']):raise RuntimeError('Do not revise acceptance after formal continuation begins')
27
+ for arm in C['arms']:
28
+ directory=run_dir(arm);history=directory/'acceptance_history'
29
+ probe=directory/'probe_002000_0001'
30
+ if (probe/'protocol.json').exists() and json.loads((probe/'protocol.json').read_text())['binding']!=bind:
31
+ history.mkdir(exist_ok=True);probe.replace(history/('probe_before_fix_'+uuid.uuid4().hex))
32
+ report=directory/'GPU_ACCEPTANCE.json'
33
+ if report.exists() and json.loads(report.read_text())['binding']!=bind:
34
+ history.mkdir(exist_ok=True);report.replace(history/('GPU_before_fix_'+uuid.uuid4().hex+'.json'))
35
+ results=[]
36
+ for arm in C['arms']:
37
+ directory=run_dir(arm);batch=Dataset(arm,index,index+1,feature_path)[0]
38
+ if len(batch['rows'])!=288:raise RuntimeError('Not a real complete joint batch')
39
+ with gpu_work(directory,'provisional_GPU_probe' if provisional else 'full_GPU_acceptance'):
40
+ model,opt,progress,parent_lr=make_model_optimizer(arm);model.install_features(feature_path)
41
+ old_steps=[float(s['step']) for s in opt.state.values() if 'step' in s]
42
+ q=next(p['query'] for r in batch['rows'] for p in r['pools']);model.eval();parent=load_teacher()
43
+ parent.graph_chunk=model.graph_chunk;parent.local_chunk=model.local_chunk
44
+ with torch.inference_mode(),amp():
45
+ expected=parent.encode_batch([q])[0][0].base.float();actual=model.encode_batch([q])[0][0].base.float()
46
+ parity=(expected-actual).abs().max().item()
47
+ if parity>3e-4:raise RuntimeError('Initial parent score parity failed '+str(parity))
48
+ perm=list(reversed(range(len(q.candidates))))
49
+ shuffled=replace(q,candidates=tuple(q.candidates[i] for i in perm))
50
+ permuted=model.encode_batch([shuffled])[0][0].base.float()
51
+ error=(permuted-actual[perm]).abs().max().item()
52
+ if error>3e-4:raise RuntimeError('Candidate permutation leak '+str(error))
53
+ del parent;gc.collect();torch.cuda.empty_cache();restore_rng(parent_state());model.train();torch.cuda.reset_peak_memory_stats()
54
+ metrics=[train_step(model,opt,batch,C['source_update']+i) for i in range(2 if arm in ('A2','A3') else 1)]
55
+ if metrics[-1]['backbone_gradient_norm']<=0:raise RuntimeError('No backbone gradient')
56
+ if arm in ('A2','A3') and metrics[-1]['chemical_gradient_norm']<=0:raise RuntimeError('No chemical head gradient')
57
+ if arm=='A3' and (metrics[-1]['fragment_gradient_norm']<=0 or not metrics[-1]['spectrum_valid']):raise RuntimeError('No actual fragment supervision tested')
58
+ isolated={}
59
+ if arm in ('A2','A3'):
60
+ _,qcheck,_=model.spectrum.forward_batch([r['query'] for r in batch['rows'][:8]])
61
+ count=chemical_loss(model,qcheck.float(),batch['rows'][:8])
62
+ grad=torch.autograd.grad(count,model.spectrum.peak[0].weight)[0]
63
+ isolated['count_to_spectrum_encoder_norm']=float(grad.float().norm())
64
+ if isolated['count_to_spectrum_encoder_norm']<=0:raise RuntimeError('Count auxiliary does not reach the spectrum encoder')
65
+ if arm=='A3':
66
+ candidate=next(p for r in batch['rows'] for p in r['pools'] if p['spectrum_eligible'])
67
+ with amp():encoded=model.encode_batch([candidate['query']])[0][0]
68
+ grad=torch.autograd.grad(encoded.r2_spectrum[0][candidate['positive_index']],model.graph.atom.weight)[0]
69
+ isolated['spectrum_reconstruction_to_graph_encoder_norm']=float(grad.float().norm())
70
+ if isolated['spectrum_reconstruction_to_graph_encoder_norm']<=0:raise RuntimeError('Reconstruction auxiliary does not reach the graph encoder')
71
+ path=directory/'acceptance_temporary.pt';temporary_progress=dict(progress,update=C['source_update']+len(metrics),new_updates=len(metrics))
72
+ checkpoint(path,model,opt,temporary_progress,bind)
73
+ before=train_step(model,opt,batch,temporary_progress['update'],False)['loss']
74
+ del model,opt;gc.collect();torch.cuda.empty_cache()
75
+ model,opt,loaded,_=make_model_optimizer(arm,path);model.install_features(feature_path)
76
+ after=train_step(model,opt,batch,loaded['update'],False)['loss'];resume=abs(before-after)
77
+ if resume>3e-4:raise RuntimeError('Full-state RNG/optimizer resume mismatch '+str(resume))
78
+ result=dict(complete=True,provisional=provisional,arm=arm,queries=len(batch['rows']),initial_logit_max_error=parity,
79
+ candidate_permutation_max_error=error,resume_loss_abs_error=resume,parameters=sum(p.numel() for p in model.parameters()),
80
+ original_optimizer_state_entries=len(old_steps),metrics=metrics,binding=bind,formal_updates=0,
81
+ old_optimizer_step_max=max(old_steps),isolated_auxiliary_gradients=isolated,data_ledger_sha256=batch['ledger_sha256'],unix_time=time.time())
82
+ save(directory/('PROVISIONAL_GPU.json' if provisional else 'GPU_ACCEPTANCE.json'),result);results.append(result)
83
+ print(json.dumps(dict(arm=arm,parity=parity,resume=resume,parameters=result['parameters'],seconds=metrics[-1]['step_compute_seconds'],peak_mib=metrics[-1]['peak_allocated_mib'])),flush=True)
84
+ del model,opt;gc.collect();torch.cuda.empty_cache()
85
+ if not provisional:
86
+ # Validation adapter is exercised separately before training is admitted.
87
+ from validate_r2 import evaluate
88
+ for arm in ('A0','A3'):
89
+ with gpu_work(run_dir(arm),'Validation_entrypoint_acceptance'):
90
+ model,opt,_,_=make_model_optimizer(arm);del opt
91
+ val=evaluate(model,arm,C['source_update'],maximum_targets=1)
92
+ if any(not val[v]['spectra'] for v in ('mass','formula')):raise RuntimeError('Empty Validation acceptance')
93
+ del model;gc.collect();torch.cuda.empty_cache()
94
+ save(OUT/'TRAIN_READY.json',dict(complete=True,binding=binding(),all_four_arms_real_GPU_verified=True,
95
+ full_preparation_complete=True,formal_updates=0,unix_time=time.time()))
96
+
97
+
98
+ if __name__=='__main__':
99
+ p=argparse.ArgumentParser();p.add_argument('--provisional',action='store_true');a=p.parse_args()
100
+ try:run(a.provisional)
101
+ except Exception:
102
+ save(OUT/('PROVISIONAL_GPU_FAILURE.json' if a.provisional else 'GPU_FAILURE.json'),dict(traceback=traceback.format_exc(),unix_time=time.time()));raise
code/snapshot/root/code/ceir_r2_20261110/analyze_r2.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent row-level reaggregation and Validation-only selection."""
2
+ from collections import defaultdict
3
+ import gzip
4
+ import json
5
+ from pathlib import Path
6
+ import statistics
7
+ import time
8
+ from runtime_r2 import *
9
+
10
+
11
+ def rows(directory):
12
+ with gzip.open(Path(directory)/'per_spectrum_summary.json.gz','rt') as f:return json.load(f)
13
+
14
+
15
+ def aggregate(directory):
16
+ original=json.loads((Path(directory)/'metrics.json').read_text());rr=rows(directory);out={}
17
+ for view in ('mass','formula'):
18
+ selected=[r for r in rr if r['view']==view]
19
+ if len(selected)!=19429 or len({r['identifier'] for r in selected})!=19429:raise RuntimeError('Wrong Validation population')
20
+ out[view]={}
21
+ for field,kind,ks in [('rank','structure',(1,3,5,10,20,50,100,200)),('formula_rank','formula',(*range(1,11),20,50,100,200))]:
22
+ out[view][kind]={}
23
+ for k in ks:
24
+ hits=sum(r[field] is not None and r[field]<=k for r in selected);value=hits/len(selected)
25
+ if abs(value-original[view][kind][str(k)]['micro'])>1e-12:raise RuntimeError('Independent aggregate disagrees')
26
+ out[view][kind][str(k)]=dict(hits=hits,n=len(selected),value=value)
27
+ mces=json.loads((Path(directory)/'MCES.json').read_text());out['MCES']=mces['views']
28
+ x=out['mass']['structure']['1']['value'];y=out['formula']['structure']['1']['value'];out['harmonic_Top1']=2*x*y/(x+y)
29
+ return out
30
+
31
+
32
+ def selection():
33
+ baseline=aggregate(run_dir('A0')/'validation_002000')
34
+ arms={a:aggregate(run_dir(a)/'validation_003000') for a in C['arms']};control=arms['A0'];decisions={}
35
+ tolerance=C['validation_degradation_tolerance_pp']/100
36
+ for arm,current in arms.items():
37
+ structural=all(current[v]['structure']['1']['value']>=baseline[v]['structure']['1']['value']-tolerance for v in ('mass','formula'))
38
+ mces=all(current['MCES'][v]['valid']==baseline['MCES'][v]['valid'] and
39
+ current['MCES'][v]['valid_mean']<=baseline['MCES'][v]['valid_mean']+.1 for v in ('mass','formula'))
40
+ improvement=current['harmonic_Top1']>max(baseline['harmonic_Top1'],control['harmonic_Top1'])
41
+ decisions[arm]=dict(each_view_Top1_guard=structural,MCES_guard=mces,harmonic_improves_parent_and_continuation=improvement,
42
+ passes=structural and mces and improvement,harmonic_gain_vs_parent_pp=100*(current['harmonic_Top1']-baseline['harmonic_Top1']),
43
+ harmonic_gain_vs_A0_pp=100*(current['harmonic_Top1']-control['harmonic_Top1']))
44
+ passed=[a for a,d in decisions.items() if a!='A0' and d['passes']]
45
+ recommended=max(passed,key=lambda a:arms[a]['harmonic_Top1']) if passed else None
46
+ result=dict(complete=True,baseline=baseline,arms=arms,guardrails=decisions,recommended_arm=recommended,
47
+ measured_improvement=bool(recommended),test_used_for_selection=False,
48
+ rule='full_Validation_harmonic_Top1_each_view_0.2pp_and_MCES_0.1_guard',
49
+ extension_automatically_started=False,development_exposure=C['test_development_exposure'],unix_time=time.time())
50
+ save(OUT/'SELECTION.json',result)
51
+ return result
52
+
53
+
54
+ def write_test_comparison():
55
+ selection_result=json.loads((OUT/'SELECTION.json').read_text());dest=OUT/'test';models=json.loads((dest/'FROZEN.json').read_text())['models']
56
+ result=dict(complete=True,Validation_selection=selection_result['recommended_arm'],Test_used_for_selection=False,
57
+ development_exposure=C['test_development_exposure'],models={})
58
+ for name in models:
59
+ result['models'][name]={}
60
+ for dataset in ('msg_test','casmi2022'):
61
+ directory=dest/'inference'/name/dataset
62
+ if not (directory/'COMPLETE.json').exists() or not (directory/'MCES.json').exists():raise RuntimeError('Test/MCES incomplete')
63
+ metric=json.loads((directory/'metrics.json').read_text());raw=rows(directory)
64
+ expected=17556 if dataset=='msg_test' else 500
65
+ for view in {r['view'] for r in raw}:
66
+ rr=[r for r in raw if r['view']==view]
67
+ if len(rr)!=expected or len({r['identifier'] for r in rr})!=expected:raise RuntimeError('Test population mismatch')
68
+ result['models'][name][dataset]=dict(metrics=metric,MCES=json.loads((directory/'MCES.json').read_text()))
69
+ save(OUT/'ALL_RESULTS.json',result)
70
+ return result
71
+
72
+
73
+ if __name__=='__main__':
74
+ import argparse
75
+ p=argparse.ArgumentParser();p.add_argument('--test',action='store_true');a=p.parse_args()
76
+ write_test_comparison() if a.test else selection()
code/snapshot/root/code/ceir_r2_20261110/audit_r2.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scoped independent checks before formal data/GPU admission."""
2
+ from collections import Counter
3
+ import hashlib
4
+ import json
5
+ import time
6
+ from runtime_r2 import *
7
+ from data09 import Reader
8
+ import features_r2 as features
9
+
10
+
11
+ def run():
12
+ ready=json.loads((PREP/'READY.json').read_text())
13
+ if not ready.get('exact_parent_literal_alignment',{}).get('complete'):raise RuntimeError('Exact parent literal key alignment is incomplete')
14
+ if ready['feature_code_sha256']!=sha(HERE/'features_r2.py'):raise RuntimeError('Prepared feature code differs')
15
+ parent_state();db=readonly(PREP/'assets.sqlite');reader=Reader();plans=json.loads((OLD.CACHE/'workload.json').read_text())['plans'][:C['manifest_updates']]
16
+ if db.execute('PRAGMA quick_check').fetchall()!=[('ok',)]:raise RuntimeError('Prepared SQLite integrity check failed')
17
+ if db.execute('SELECT count(*) FROM canonical_features WHERE feature IS NULL OR feature_sha IS NULL').fetchone()[0]:raise RuntimeError('Incomplete static candidate cache')
18
+ safety_count=0
19
+ for identity, in db.execute('SELECT identity FROM graph_metadata'):
20
+ if identity in reader.forbidden:raise RuntimeError('Heldout structure in training-negative scope')
21
+ safety_count+=1
22
+ hashes={};stats={};expected_rows=Counter();actual_rows=Counter()
23
+ for _,_,groups in plans:
24
+ for source,ids in groups.items():expected_rows[source]+=len(ids)
25
+ for mode in ('replacement','unique'):
26
+ hashes[mode]=[];totals=Counter()
27
+ for index,(blob,) in enumerate(db.execute('SELECT body FROM batches WHERE mode=? ORDER BY idx',(mode,))):
28
+ plan=features.loads(blob);epoch,step,groups=plans[index]
29
+ expected=[rid for ids in groups.values() for rid in ids]
30
+ if [r['rid'] for r in plan['rows']]!=expected or plan['epoch']!=epoch or plan['step']!=step:raise RuntimeError('Candidate ledger data cursor drift')
31
+ hashes[mode].append(hashlib.sha256(blob).hexdigest());totals['queries']+=len(expected)
32
+ for r in plan['rows']:
33
+ for p in r['pools']:
34
+ if p['reference_injected'] or len(p['graphs'])!=p['negative_draws']+1:raise RuntimeError('Candidate count or injection mismatch')
35
+ if mode=='unique' and p['negative_draws']!=p['unique_negative_key14']:raise RuntimeError('Distinct-identity sampler contains repeats')
36
+ totals['draws']+=p['negative_draws'];totals['unique_draws']+=p['unique_negative_key14'];totals[p['kind']+'_pools']+=1
37
+ if len(hashes[mode])!=len(plans):raise RuntimeError('Wrong sampler ledger count')
38
+ stats[mode]=dict(totals)
39
+ # An independently executed original Reader, not the materializer helper.
40
+ checks=Counter();sample_indices=sorted({0,1,17,999,len(plans)-1})
41
+ for index in sample_indices:
42
+ epoch,step,groups=plans[index]
43
+ frozen=features.loads(db.execute('SELECT body FROM batches WHERE mode=? AND idx=?',('replacement',index)).fetchone()[0])
44
+ position=0
45
+ for source,ids in groups.items():
46
+ for j,rid in enumerate(ids):
47
+ seed=C['seed']+epoch*100000000+step*10000+j+(1000000 if source=='msg' else 0)
48
+ original=reader.sample(rid,seed,source=='odata' and j<16);stored=frozen['rows'][position];position+=1
49
+ if tuple(original['formulas'])!=tuple(stored['formulas']) or len(original['pools'])!=len(stored['pools']):raise RuntimeError('A0 original formula/pool selection mismatch')
50
+ for old,new in zip(original['pools'],stored['pools']):
51
+ actual=[(m.identity,m.smiles) for m in old['query'].candidates]
52
+ expected=[db.execute('SELECT identity,smiles FROM graph_metadata WHERE graph_hash=?',(g,)).fetchone() for g in new['graphs']]
53
+ if actual!=expected or tuple(old['query'].formula_candidates)!=tuple(new['formulas']):raise RuntimeError('A0 original negative draws mismatch')
54
+ checks['pool_views']+=1;checks['candidate_draws']+=len(actual)
55
+ checks['queries']+=1
56
+ save(PREP/'ledger_hashes.json',hashes)
57
+ result=dict(complete=True,parent_sha256=C['parent_sha256'],workload_sha256=sha(OLD.CACHE/'workload.json'),
58
+ prepared_database_sha256=sha(PREP/'assets.sqlite'),ledger_hashes_sha256=sha(PREP/'ledger_hashes.json'),
59
+ all_prepared_graphs_checked_against_heldout_key14=safety_count,all_steps_cursor_verified=len(plans),sampling=stats,
60
+ original_A0_sampler_parity=dict(sampled_steps=sample_indices,checks=dict(checks),mismatches=0,
61
+ scope='five actual continuation steps, not a full sampler equivalence proof'),
62
+ source_exposures=dict(expected_rows),Test_and_CASMI_labels_used=False,original_files_modified=False,unix_time=time.time())
63
+ save(PREP/'DATA_ACCEPTANCE.json',result);db.close();print(json.dumps(result),flush=True)
64
+
65
+
66
+ if __name__=='__main__':run()
code/snapshot/root/code/ceir_r2_20261110/benchmark.supervisor.conf ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [program:specpartition-r2-benchmark-20261110]
2
+ directory=/root/xj/SpecPartition-MS/code/ceir_r2_20261110
3
+ command=/usr/bin/nice -n 19 /workspace/xj/SpecPartition-MS/.venv/bin/python -u /root/xj/SpecPartition-MS/code/ceir_r2_20261110/benchmark_r2.py
4
+ environment=PROC_NAME="specpartition-r2-benchmark-20261110",OMP_NUM_THREADS="1",MKL_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",CUBLAS_WORKSPACE_CONFIG=":4096:8",PYTHONUNBUFFERED="1"
5
+ autostart=false
6
+ autorestart=false
7
+ startsecs=2
8
+ stopasgroup=true
9
+ killasgroup=true
10
+ stdout_logfile=/dev/stdout
11
+ stdout_logfile_maxbytes=0
12
+ redirect_stderr=true
code/snapshot/root/code/ceir_r2_20261110/benchmark_r2.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real mixed-batch engineering benchmark, no formal optimizer updates."""
2
+ import gc
3
+ import json
4
+ import torch
5
+ from runtime_r2 import *
6
+ from data_r2 import Dataset
7
+ from model_r2_new import make_model_optimizer
8
+ from objectives_r2 import train_step
9
+
10
+
11
+ def run():
12
+ setup_gpu();index=json.loads((PREP/'PROBE_READY.json').read_text())['index'];results=[]
13
+ for arm in ('A0','A3'):
14
+ batch=Dataset(arm,index,index+1,PREP/'probe.sqlite')[0]
15
+ with gpu_work(OUT,'engineering_benchmark'):
16
+ model,opt,_,_=make_model_optimizer(arm);model.install_features(PREP/'probe.sqlite');model.train()
17
+ for graphs,views,threshold in [(128,4,6000),(256,8,12000),(256,16,16000)]:
18
+ model.graph_chunk=graphs;LEGACY.C['graph_chunk']=graphs;LEGACY.C['pool_micro_views']=views
19
+ model.activation_checkpoint_atom_threshold=threshold;restore_rng(parent_state());torch.cuda.empty_cache();torch.cuda.reset_peak_memory_stats()
20
+ metrics=train_step(model,opt,batch,2000,False)
21
+ row=dict(arm=arm,graph_chunk=graphs,micro_views=views,threshold=threshold,
22
+ seconds=metrics['step_compute_seconds'],peak_mib=metrics['peak_allocated_mib'],loss=metrics['loss'])
23
+ results.append(row);print(json.dumps(row),flush=True)
24
+ del model,opt;gc.collect();torch.cuda.empty_cache()
25
+ save(OUT/'ENGINEERING_BENCHMARK.json',dict(complete=True,formal_optimizer_updates=0,
26
+ caution='BF16 grouping and stochastic dropout draws can change numerical trajectories; same setting is used in all formal arms',results=results))
27
+
28
+
29
+ if __name__=='__main__':run()
code/snapshot/root/code/ceir_r2_20261110/canonical_cache_r2.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recoverable canonical-key migration of this release's partial static cache.
2
+
3
+ Original sources and raw R2 rows remain untouched. The trainable parent graph
4
+ canonicalizes without stereo and reparses; reproduce its atom numbering here.
5
+ """
6
+ from collections import Counter
7
+ from concurrent.futures import ProcessPoolExecutor
8
+ import hashlib
9
+ import json
10
+ import multiprocessing
11
+ import sqlite3
12
+ import time
13
+ from rdkit import Chem
14
+ from runtime_r2 import *
15
+ import features_r2 as features
16
+
17
+
18
+ def canonicalize(smiles):
19
+ mol=Chem.MolFromSmiles(smiles)
20
+ if mol is None:raise RuntimeError('Invalid already-accepted candidate')
21
+ Chem.RemoveStereochemistry(mol)
22
+ return Chem.MolToSmiles(mol,canonical=True,isomericSmiles=False)
23
+
24
+
25
+ def normalize(task):
26
+ raw,smiles,scope,blob,digest=task;canonical=canonicalize(smiles);fk=features.key(canonical)
27
+ return raw,fk,canonical,scope,blob if smiles==canonical else None,digest if smiles==canonical else None
28
+
29
+
30
+ def generate(smiles):
31
+ body=features.dumps(features.build(smiles))
32
+ return features.key(smiles),body,hashlib.sha256(body).hexdigest()
33
+
34
+
35
+ def align_parent_literals(db):
36
+ """Canonicalization is not always idempotent for explicit stereo H.
37
+
38
+ Parent Molecule.smiles is saved before its final reparse. Retain that exact
39
+ valid string as the feature key; parse it to reproduce the saved atom order.
40
+ This changes no compound identity or candidate membership.
41
+ """
42
+ marker=PREP/'PARENT_LITERAL_ALIGNMENT.json'
43
+ if marker.exists():return json.loads(marker.read_text())
44
+ rare=db.execute('SELECT m.feature_key,m.smiles,c.canonical_key FROM molecules m JOIN canonical_aliases c ON c.raw_key=m.feature_key WHERE c.raw_key!=c.canonical_key').fetchall()
45
+ for raw,smiles,canonical in rare:
46
+ fk,body,digest=generate(smiles)
47
+ db.execute('INSERT OR IGNORE INTO canonical_features VALUES (?,?,?,?,?)',(fk,smiles,'exact_parent_literal',body,digest))
48
+ changed={r[2] for r in rare};pending=[gh for gh,fk in db.execute('SELECT graph_hash,feature_key FROM graph_metadata') if fk in changed]
49
+ from data09 import Reader
50
+ reader=Reader();fixed=0
51
+ for gh in pending:
52
+ mol=reader.molecule(gh);fk,body,digest=generate(mol.smiles)
53
+ value=features.loads(body)
54
+ if value['layout']!=features.layout(mol.mol):raise RuntimeError('Exact parent SMILES cannot reproduce atom layout')
55
+ db.execute('INSERT OR IGNORE INTO canonical_features VALUES (?,?,?,?,?)',(fk,mol.smiles,'exact_parent_literal',body,digest))
56
+ db.execute('UPDATE graph_metadata SET feature_key=?,smiles=? WHERE graph_hash=?',(fk,mol.smiles,gh));fixed+=1
57
+ uncovered=db.execute("SELECT count(*) FROM molecules m LEFT JOIN canonical_features f ON f.feature_key=m.feature_key WHERE m.scope='validation' AND f.feature_key IS NULL").fetchone()[0]
58
+ if uncovered:raise RuntimeError('Not all actual Validation Molecule.smiles have exact literal feature keys')
59
+ db.commit();result=dict(complete=True,non_idempotent_raw_aliases=len(rare),training_graph_aliases_verified=fixed,
60
+ uncovered_actual_Validation_graph_strings=0,original_candidate_identities_modified=False)
61
+ save(marker,result)
62
+ prior=PREP/'DATA_ACCEPTANCE.json'
63
+ if prior.exists():prior.replace(PREP/('DATA_ACCEPTANCE.before_literal_alignment_%d.json'%int(time.time())))
64
+ return result
65
+
66
+
67
+ def run():
68
+ db=sqlite3.connect(PREP/'assets.sqlite');db.execute('PRAGMA journal_mode=WAL')
69
+ db.execute('CREATE TABLE IF NOT EXISTS canonical_features(feature_key TEXT PRIMARY KEY,smiles TEXT,scope TEXT,feature BLOB,feature_sha TEXT)')
70
+ db.execute('CREATE INDEX IF NOT EXISTS canonical_pending ON canonical_features(feature_key) WHERE feature IS NULL')
71
+ db.execute('CREATE TABLE IF NOT EXISTS canonical_aliases(raw_key TEXT PRIMARY KEY,canonical_key TEXT,smiles TEXT)')
72
+ marker=PREP/'CANONICAL_IDENTITIES_READY.json';started=time.monotonic();done=0
73
+ ctx=multiprocessing.get_context('spawn')
74
+ with ProcessPoolExecutor(max_workers=C['prepare_workers'],mp_context=ctx) as workers:
75
+ if not marker.exists():
76
+ # A monotonically increasing raw key cursor avoids repeatedly
77
+ # scanning 3M processed rows, and resumes without losing evidence.
78
+ state=PREP/'canonical_cursor.json';after=json.loads(state.read_text())['last_key'] if state.exists() else ''
79
+ while True:
80
+ rows=db.execute('SELECT feature_key,smiles,scope,feature,feature_sha FROM molecules WHERE feature_key>? ORDER BY feature_key LIMIT 1024',(after,)).fetchall()
81
+ if not rows:break
82
+ for raw,fk,smiles,scope,blob,digest in workers.map(normalize,rows,chunksize=16):
83
+ db.execute('INSERT OR IGNORE INTO canonical_features VALUES (?,?,?,?,?)',(fk,smiles,scope,blob,digest))
84
+ db.execute('INSERT OR IGNORE INTO canonical_aliases VALUES (?,?,?)',(raw,fk,smiles));done+=1
85
+ db.commit();after=rows[-1][0];save(state,dict(last_key=after))
86
+ save(PREP/'status.json',dict(phase='parent_graph_canonical_identity_alignment',rows_this_attempt=done,seconds=time.monotonic()-started,unix_time=time.time()))
87
+ if done%16384==0:disk_check()
88
+ db.execute('UPDATE graph_metadata SET feature_key=(SELECT c.canonical_key FROM canonical_aliases c WHERE c.raw_key=graph_metadata.feature_key),smiles=(SELECT c.smiles FROM canonical_aliases c WHERE c.raw_key=graph_metadata.feature_key) WHERE EXISTS (SELECT 1 FROM canonical_aliases c WHERE c.raw_key=graph_metadata.feature_key)')
89
+ db.commit();save(marker,dict(complete=True,raw_aliases=db.execute('SELECT count(*) FROM canonical_aliases').fetchone()[0],original_raw_rows_preserved=True))
90
+ made=0
91
+ while True:
92
+ rows=db.execute('SELECT smiles FROM canonical_features WHERE feature IS NULL ORDER BY feature_key LIMIT 512').fetchall()
93
+ if not rows:break
94
+ for fk,body,digest in workers.map(generate,[r[0] for r in rows],chunksize=8):
95
+ db.execute('UPDATE canonical_features SET feature=?,feature_sha=? WHERE feature_key=?',(body,digest,fk));made+=1
96
+ db.commit();save(PREP/'status.json',dict(phase='canonical_connected_fragment_features',features_this_attempt=made,seconds=time.monotonic()-started,unix_time=time.time()))
97
+ if made%8192==0:disk_check()
98
+ literal=align_parent_literals(db)
99
+ missing=db.execute('SELECT count(*) FROM canonical_features WHERE feature IS NULL OR feature_sha IS NULL').fetchone()[0]
100
+ if missing:raise RuntimeError('Canonical feature cache incomplete')
101
+ total=db.execute('SELECT count(*) FROM canonical_features').fetchone()[0]
102
+ if db.execute('SELECT count(*) FROM graph_metadata WHERE feature_key IS NULL OR smiles IS NULL').fetchone()[0]:raise RuntimeError('Missing canonical graph mapping')
103
+ db.execute('PRAGMA wal_checkpoint(TRUNCATE)');db.close()
104
+ save(PREP/'READY.json',dict(complete=True,feature_version=features.VERSION,feature_code_sha256=sha(HERE/'features_r2.py'),feature_rows=total,
105
+ canonical_identity_alignment=json.loads(marker.read_text()),exact_parent_literal_alignment=literal,sampling=json.loads((PREP/'SAMPLING_READY.json').read_text()),
106
+ validation=json.loads((PREP/'VALIDATION_STRUCTURES_READY.json').read_text()),original_graph_store_modified=False,
107
+ partial_raw_feature_rows_preserved_for_audit=True,prepared_database_bytes=(PREP/'assets.sqlite').stat().st_size))
108
+
109
+
110
+ if __name__=='__main__':run()
code/snapshot/root/code/ceir_r2_20261110/config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release": "CEIR_R2_20261110",
3
+ "root": "/workspace/xj/SpecPartition-MS",
4
+ "source_r1": "/root/xj/SpecPartition-MS/code/ceir_r1_20261109",
5
+ "output": "/root/xj/SpecPartition-MS/runs/ceir_r2_20261110",
6
+ "parent_checkpoint": "/workspace/xj/SpecPartition-MS/runs/hierarchical_intra_modal_20261103/C03_both_fine/seed_20261103/step_002000.pt",
7
+ "parent_sha256": "8a2982f3821fad501ba4f39ac8b1495affeb0c1b09051f2103317f36027d48b6",
8
+ "arms": ["A0", "A1", "A2", "A3"],
9
+ "source_update": 2000,
10
+ "pilot_target_update": 3000,
11
+ "extension_target_update": 4000,
12
+ "manifest_updates": 2000,
13
+ "seed": 20261103,
14
+ "feature_version": "connected_cuts_r2_v1",
15
+ "fragment_count": 32,
16
+ "count_classes": 33,
17
+ "chem_weight": 0.05,
18
+ "spectrum_weight": 0.05,
19
+ "fragment_tolerance_ppm": 20.0,
20
+ "fragment_tolerance_floor_da": 0.02,
21
+ "fragment_hydrogen_shifts": [-2, -1, 0, 1, 2],
22
+ "minimum_fragment_coverage": 0.05,
23
+ "prepare_workers": 16,
24
+ "spectrum_chunk": 16,
25
+ "graph_chunk": 256,
26
+ "local_chunk": 128,
27
+ "pool_micro_views": 8,
28
+ "max_atoms_per_microbatch": 12000,
29
+ "gpu_memory_fraction": 0.42,
30
+ "minimum_free_gpu_mib": 5500,
31
+ "gpu_slots": 2,
32
+ "minimum_output_disk_gib": 8,
33
+ "backbone_lr_multiplier": 0.3,
34
+ "new_head_lr": 0.0001,
35
+ "lr_ramp_updates": 100,
36
+ "save_interval": 100,
37
+ "validation_updates": [2250, 2500, 3000],
38
+ "validation_spectrum_batch": 16,
39
+ "validation_graph_chunk": 32,
40
+ "validation_local_chunk": 32,
41
+ "validation_selection": "full_Validation_harmonic_Mass_Formula_Top1_with_each_view_and_MCES_guardrails",
42
+ "validation_degradation_tolerance_pp": 0.2,
43
+ "test_used_for_model_selection": false,
44
+ "test_development_exposure": "previous Test/CASMI badcases informed this design; not an untouched final holdout",
45
+ "original_assets_read_only": true
46
+ }
code/snapshot/root/code/ceir_r2_20261110/data_r2.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen draw ledger: no PubChem, RDKit parsing, or pool JSON in training."""
2
+ from collections import Counter
3
+ from dataclasses import replace
4
+ import time
5
+ from runtime_r2 import *
6
+ import features_r2 as features
7
+ from data09 import Reader
8
+
9
+
10
+ class Dataset:
11
+ def __init__(self,arm,start=0,stop=None,feature_path=None):
12
+ self.arm=arm;self.start=start;self.stop=C['manifest_updates'] if stop is None else stop
13
+ self.reader=None;self.db=None;self.features=None;self.feature_path=feature_path
14
+ self.ledger_hashes=None
15
+
16
+ def __len__(self):return self.stop-self.start
17
+
18
+ def __getitem__(self,index):
19
+ started=time.monotonic()
20
+ if self.reader is None:
21
+ self.reader=Reader();self.db=readonly(PREP/'assets.sqlite')
22
+ self.features=features.FeatureStore(self.feature_path or PREP/'assets.sqlite')
23
+ if self.feature_path is None:self.ledger_hashes=json.loads((PREP/'ledger_hashes.json').read_text())
24
+ mode='replacement' if self.arm=='A0' else 'unique'
25
+ offset=self.start+index
26
+ ledger=self.db.execute('SELECT body FROM batches WHERE mode=? AND idx=?',(mode,offset)).fetchone()
27
+ if ledger is None:raise RuntimeError('Missing immutable R2 sampler batch')
28
+ digest=hashlib.sha256(ledger[0]).hexdigest()
29
+ if self.ledger_hashes is not None and digest!=self.ledger_hashes[mode][offset]:raise RuntimeError('Sampler ledger changed after acceptance')
30
+ plan=features.loads(ledger[0]);rows=[]
31
+ for selected in plan['rows']:
32
+ original=self.reader.db.execute('SELECT body FROM samples WHERE record_id=?',(selected['rid'],)).fetchone()
33
+ row=loads(original[0]);ref=self.reader.molecule(selected['ref'])
34
+ if ref.identity!=row['identity'] or ref.identity in self.reader.forbidden:raise RuntimeError('Unsafe reference')
35
+ row['ref']=ref;row['formulas']=tuple(selected['formulas']);row['pools']=[]
36
+ row['query']=replace(row['query'],formula_candidates=row['formulas'])
37
+ feature=self.features.get(ref.smiles)
38
+ if feature['layout']!=features.layout(ref.mol):raise RuntimeError('Reference atom layout changed')
39
+ row['chemical_counts']=feature['counts']
40
+ for p in selected['pools']:
41
+ mols=tuple(self.reader.molecule(g) for g in p['graphs'])
42
+ if mols[0].identity!=ref.identity or any(m.identity==ref.identity for m in mols[1:]):raise RuntimeError('Missing positive or false negative')
43
+ if any(m.identity in self.reader.forbidden for m in mols):raise RuntimeError('Heldout negative')
44
+ kind=p['kind'];q=replace(row['query'],candidates=mols,formula_candidates=tuple(p['formulas']),
45
+ candidate_view='odata_oracle' if kind=='odata' else 'msg_'+kind)
46
+ eligible=bool(row['mass_ok'] and features.supported_positive(q,self.features.get(mols[0].smiles)))
47
+ row['pools'].append(dict(**p,query=q,positive_index=0,truth_identity=ref.identity,
48
+ truth_formula=row['formula'],record_id=row['record_id'],quality_eligible=bool(row['mass_ok']),spectrum_eligible=eligible))
49
+ rows.append(row)
50
+ return dict(epoch=plan['epoch'],step=plan['step'],rows=rows,mode=mode,manifest_index=offset,
51
+ ledger_sha256=digest,data_seconds=time.monotonic()-started)
code/snapshot/root/code/ceir_r2_20261110/features_r2.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned label-free static candidate descriptors and connected cut hypotheses."""
2
+ from functools import lru_cache
3
+ import hashlib
4
+ import itertools
5
+ import pickle
6
+ import sqlite3
7
+ import zlib
8
+ import numpy as np
9
+ from rdkit import Chem,RDLogger
10
+ from rdkit.Chem import rdMolDescriptors
11
+
12
+ VERSION='connected_cuts_r2_v1';K=32;TRAITS=7;CLASSES=33
13
+ RDLogger.DisableLog('rdApp.*')
14
+ PATTERNS=[Chem.MolFromSmarts(s) for s in ('[OX2H]','[CX3]=[OX1]','[#6][OX2][#6]')]
15
+ PT=Chem.GetPeriodicTable();H=PT.GetMostCommonIsotopeMass(1)
16
+
17
+
18
+ def dumps(value):return zlib.compress(pickle.dumps(value,protocol=5),1)
19
+ def loads(value):return pickle.loads(zlib.decompress(value))
20
+ def key(smiles):return hashlib.sha256(smiles.encode()).hexdigest()
21
+
22
+
23
+ def layout(mol):
24
+ atoms=[a.GetAtomicNum() for a in mol.GetAtoms()]
25
+ edges=sorted((min(b.GetBeginAtomIdx(),b.GetEndAtomIdx()),max(b.GetBeginAtomIdx(),b.GetEndAtomIdx()),str(b.GetBondType())) for b in mol.GetBonds())
26
+ return hashlib.sha256(repr((atoms,edges)).encode()).hexdigest()
27
+
28
+
29
+ def components(n,adj,removed):
30
+ seen=set();result=[]
31
+ for first in range(n):
32
+ if first in seen:continue
33
+ todo=[first];seen.add(first);part=[]
34
+ while todo:
35
+ i=todo.pop();part.append(i)
36
+ for j,bid in adj[i]:
37
+ if bid not in removed and j not in seen:seen.add(j);todo.append(j)
38
+ result.append(tuple(sorted(part)))
39
+ return result
40
+
41
+
42
+ def build(smiles):
43
+ mol=Chem.MolFromSmiles(smiles)
44
+ if mol is None:raise ValueError('Invalid candidate SMILES')
45
+ n=mol.GetNumAtoms();counts=[len(mol.GetSubstructMatches(p)) for p in PATTERNS]
46
+ counts += [rdMolDescriptors.CalcNumAromaticRings(mol),rdMolDescriptors.CalcNumAliphaticRings(mol),rdMolDescriptors.CalcNumHeterocycles(mol),len(Chem.GetMolFrags(mol))]
47
+ out=dict(version=VERSION,smiles=smiles,layout=layout(mol),atoms=n,
48
+ counts=np.asarray([min(32,v) for v in counts],dtype=np.int64),members=np.zeros((K,n),dtype=np.float32),
49
+ boundary=np.zeros((K,8),dtype=np.float32),
50
+ masses=np.zeros(K,dtype=np.float32),hydrogens=np.zeros(K,dtype=np.int16),valid=np.zeros(K,dtype=bool),
51
+ neutral_mass=rdMolDescriptors.CalcExactMolWt(mol),reason=None)
52
+ if len(Chem.GetMolFrags(mol))!=1 or Chem.GetFormalCharge(mol)!=0 or any(a.GetIsotope() for a in mol.GetAtoms()):
53
+ out['reason']='unsupported_fragment_hypothesis_structure';return out
54
+ adj=[[] for _ in range(n)]
55
+ for b in mol.GetBonds():
56
+ i,j=b.GetBeginAtomIdx(),b.GetEndAtomIdx();adj[i].append((j,b.GetIdx()));adj[j].append((i,b.GetIdx()))
57
+ bridges=[b for b in mol.GetBonds() if not b.IsInRing() and b.GetBondType()==Chem.BondType.SINGLE]
58
+ bridges.sort(key=lambda b:(-int(b.GetBeginAtom().GetAtomicNum() in (7,8,15,16))-int(b.GetEndAtom().GetAtomicNum() in (7,8,15,16)),b.GetIdx()))
59
+ ring=[b.GetIdx() for b in mol.GetBonds() if b.IsInRing()]
60
+ pairs=list(itertools.combinations(ring,2))
61
+ pairs.sort(key=lambda p:hashlib.sha256(repr(p).encode()).digest())
62
+ cuts=[(b.GetIdx(),) for b in bridges[:20]]+pairs[:12]
63
+ parts=set()
64
+ for cut in cuts:
65
+ for part in components(n,adj,set(cut)):
66
+ if 3<=len(part)<=n-2:parts.add(part)
67
+ choices=sorted(parts,key=lambda p:(len(p),p))
68
+ if len(choices)>K:choices=[choices[int(i)] for i in np.linspace(0,len(choices)-1,K).round()]
69
+ masses=[];nh=[]
70
+ for a in mol.GetAtoms():
71
+ hydrogen=a.GetTotalNumHs();nh.append(hydrogen)
72
+ masses.append(PT.GetMostCommonIsotopeMass(a.GetAtomicNum())+hydrogen*H)
73
+ for j,part in enumerate(choices):
74
+ out['members'][j,list(part)]=1/len(part)
75
+ out['masses'][j]=sum(masses[i] for i in part);out['hydrogens'][j]=sum(nh[i] for i in part);out['valid'][j]=True
76
+ chosen=set(part);aa=[mol.GetAtomWithIdx(i) for i in part]
77
+ out['boundary'][j]=[len(part)/n,sum(a.GetAtomicNum()==8 for a in aa)/len(part),
78
+ sum(a.GetAtomicNum()==7 for a in aa)/len(part),sum(v not in chosen for i in part for v,_ in adj[i])/4,
79
+ sum(a.IsInRing() for a in aa)/len(part),sum(a.GetIsAromatic() for a in aa)/len(part),
80
+ sum(nh[i] for i in part)/len(part),out['masses'][j]/max(out['neutral_mass'],1)]
81
+ out['reason']='ok' if choices else 'no_supported_connected_cut'
82
+ return out
83
+
84
+
85
+ class FeatureStore:
86
+ def __init__(self,path):
87
+ self.db=sqlite3.connect('file:'+str(path)+'?mode=ro',uri=True)
88
+ self.table='canonical_features' if self.db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='canonical_features'").fetchone() else 'molecules'
89
+ self.get=lru_cache(maxsize=12000)(self._get)
90
+
91
+ def _get(self,smiles):
92
+ row=self.db.execute('SELECT feature,feature_sha FROM '+self.table+' WHERE feature_key=?',(key(smiles),)).fetchone()
93
+ if row is None or row[0] is None:raise RuntimeError('Missing preprocessed R2 candidate feature: '+smiles[:120])
94
+ if hashlib.sha256(row[0]).hexdigest()!=row[1]:raise RuntimeError('R2 feature hash mismatch')
95
+ value=loads(row[0])
96
+ if value['version']!=VERSION or value['smiles']!=smiles:raise RuntimeError('R2 feature identity mismatch')
97
+ return value
98
+
99
+
100
+ def ion_offsets(adduct):
101
+ proton=1.007276452090935
102
+ if adduct=='[M+H]+':return (proton,None)
103
+ if adduct=='[M-H]-':return (-proton,None)
104
+ if adduct=='[M+Na]+':return (22.989220702090936,proton)
105
+ if adduct=='[M+NH4]+':return (proton,18.033825548090935)
106
+ if adduct=='[M+Cl]-':return (-proton,34.96940125990906)
107
+ if adduct=='[M+FA-H]-':return (-proton,44.99820285190906)
108
+ return (None,None)
109
+
110
+
111
+ def spectrum(query):
112
+ peaks=sorted(query.peaks,key=lambda p:(-p[1],p[0]))[:256];peaks.sort()
113
+ mz=np.asarray([p[0] for p in peaks],dtype=np.float32)
114
+ y=np.sqrt(np.asarray([p[1] for p in peaks],dtype=np.float32)/max(p[1] for p in peaks))
115
+ y[np.abs(mz-query.precursor_mz)<=max(.05,query.precursor_mz*20e-6)]=0
116
+ return mz,y
117
+
118
+
119
+ def supported_positive(query,feature):
120
+ offsets=ion_offsets(query.adduct)
121
+ if offsets[0] is None:return False
122
+ mz,y=spectrum(query)
123
+ if not y.sum():return False
124
+ masses=[]
125
+ for j in range(K):
126
+ if not feature['valid'][j]:continue
127
+ for shift in (-2,-1,0,1,2):
128
+ if feature['hydrogens'][j]+shift<0:continue
129
+ masses.extend(feature['masses'][j]+shift*H+v for v in offsets if v is not None)
130
+ if not masses:return False
131
+ mass=np.asarray(masses,dtype=np.float32)
132
+ valid=(np.abs(mz[:,None]-mass[None,:])<=np.maximum(.02,mass[None,:]*20e-6)).any(1)
133
+ return bool((y[valid].sum()/y.sum())>=.05)
code/snapshot/root/code/ceir_r2_20261110/mces_monitor_r2.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Overlap CPU-only Validation MCES with later GPU arms; finite known scope."""
2
+ import json
3
+ from pathlib import Path
4
+ import time
5
+ from mces_r2 import run,C,OUT
6
+
7
+
8
+ if __name__=='__main__':
9
+ pending=[OUT/'A0/validation_002000',*[OUT/a/'validation_003000' for a in C['arms']]]
10
+ while pending:
11
+ next_pending=[]
12
+ for directory in pending:
13
+ if (directory/'MCES.json').exists():continue
14
+ if (directory/'metrics.json').exists():run(directory)
15
+ else:next_pending.append(directory)
16
+ pending=next_pending
17
+ if pending:time.sleep(5)