Implement frozen S2 held-out custody prediction and scoring with synthetic acceptance

This commit is contained in:
Frank14f committed 2026-11-15 16:08:12 +08:00
1 parent 6903c07365
commit 6e4d991d78
11 files changed
+1005

No files matched your search

@@ -0,0 +1,181 @@
{
"version": "S2-custody-v1",
"execution_approved": true,
"ruling": "1794729482.815749",
"main_review_required_before_prediction": true,
"roster": "artifacts/s2-main-preparation-2026-11-15/final-roster.json",
"roster_sha256": "fb0c984f2e553343a598ce2e3c7012d3017053dc0fef58b5aaf46dd3c67a207e",
"exposure_membership": "artifacts/s2-g1-components-2026-11-15/custodian/not-known-exposed-test-subsets.json",
"exposure_membership_sha256": "8d037786040c6fc11fa80ceb0f41dfdd58478a2576404505a64aa29a2216a22f",
"exposure_audit": "artifacts/s2-custody-planning-2026-11-15/exposure-audit.json",
"models": "artifacts/s2-terminal-freeze-2026-11-15/models.json",
"models_sha256": "cd544ec7f0e49f0759660a71076566976cacdeaa66dd510aec049b2218f57faf",
"archive": "data.zip",
"archive_stat": {
"status": "official_size_and_md5_pass",
"source": "/home/frank14f/optane/MeltMind/data.zip",
"source_url": "https://zenodo.org/records/18598121",
"bytes": 32757812726,
"md5": "75ec15002234c2cdcdf4c751bdefab85",
"sha256": "d151f018294832fd80fbd23e865642cb16c860da150f245033d010c388fa0241",
"mtime_ns": 1794548962944204621,
"inode": 12582980,
"members": 1872,
"triplets": 624,
"source_tokens": 249,
"max_group": 34,
"total_uncompressed_bytes": 43966308383,
"finished_utc": "2026-11-13T08:04:57.180660+00:00",
"wall_seconds": 97.27923265600111,
"peak_rss_kib": 32056,
"crc_scope": "ZIP stored CRC inventory only; selected members checked on read; no full decompression",
"grouping_scope": "Filename source tokens, not verified independent CAD families"
},
"gpu_uuids": [
"GPU-e8853ae7-a302-6a17-bcfa-aa767e9ed20c",
"GPU-f1c9fd5a-e917-56e0-21fb-24035ba44a36",
"GPU-b8c11c01-c91f-aa0b-abf6-dad35085cc76",
"GPU-8b71b032-1b75-2891-935c-ce106a53034a"
],
"cpu_affinities": [
[
0,
1
],
[
2,
3
],
[
4,
5
],
[
6,
7
]
],
"code_sha256": {
"tools/audit_samples.py": "a3daf70ec3bcb77bf46d9dc4887d552cf7c422117880a169969780012278cd70",
"tools/freeze_g1_components.py": "d0cee60d95243ac2c59ef3f2244ba818315718c4e3d1895f2f9f064f1f7f5ecd",
"tools/prepare_s2_custody.py": "6a64c6d16760cf243b150c6dab67a5e255af4c70bc71b8726edbead2f2cebe16",
"tools/prepare_s2_incident_recovery.py": "4f772573dedc2b7921986e25eaedb14f91d98b235421829c284f3b40b85710aa",
"tools/prepare_s2_main_matrix.py": "43b48d82a813175be22be41cb63aaa5d04499000e80197c7405538eff3052ede",
"tools/prepare_s2_precision_pilot.py": "c3a71b0ff58bcea4433ff93e18ef14d3a00521438a76baaa69830a5ee8ac098a",
"tools/prepare_s2_r2.py": "ec6dd1c73bc2678aa4376c878837a957395c21b82e2da2314c4a9c4e96260caf",
"tools/prepare_s2_recovered_pilot_training.py": "ab5a4274363598ff933ff873df2b00497f069b1fb45756a1d1dba8d723294f68",
"tools/run_s2_custody_predict.py": "e5c882b3073cf6470d065757742e45ce5097fc91e03e4639bab557449805d09e",
"tools/run_s2_custody_predictions.py": "3589c64b09db4f83da7df99faf8c1aa86db17b08df86e6e1189fdffd71dae7cf",
"tools/run_s2_custody_score.py": "4e9192edcefaa5db207f52400d0ac79345095077b74947ddb86010f32a64bd88",
"tools/run_s2_encoder_diagnostic.py": "8f31d312fb53bfdb9b1804af064e463d3989f1b33c4aa7279a967ca82dd2c0a4",
"tools/run_s2_main_matrix.py": "cebd3ccdea80c2914f6bbc1c3de293870535689f224c547c656a860b64af14da",
"tools/run_s2_main_training.py": "7fb18f015ab2eaa4968ff50c8b140285f9db6eb822398b2789d6de40f1aea2e7",
"tools/run_s2_pilot_probe.py": "2360ab7b44b179144a5ecd2d691e33cd36a6ec4bfeac71452bf062e7f42f81eb",
"tools/run_s2_pilot_probe_v2.py": "61c08499346d50405d0c254de54deea24b3522256bf1c8b0aec3e9f4ddab6390",
"tools/run_s2_pilot_training.py": "d5e543478543243fe1db3475a4d4cd135fbdcf631d3bce48c4b5af8b2edafb22",
"tools/run_s2_pilot_training_v2.py": "f461cb43bc602a32677d7dcfb8a322e206531ad152fa33bb4e36ea8546a1c0f2",
"tools/run_s2_precision_continuation.py": "9fb5a22007788f0c18c77a82b6a8b76fbb53a98b49cc9251bc49a7a5b8312f2f",
"tools/run_s2_precision_pilot.py": "ac8347be1ca11f48cb67abbf5e5c78b39af46ed3a7c6f89b49098fd5e77a6904",
"tools/run_s2_r2.py": "7a93e61cef18f12f5e834bcfdfac81d2092bb74a7216221dd542d5904e71905e",
"tools/run_s2_r2_fit.py": "dd235ef8b015a58deaa89d36208c563bea425b9c4d0a0937ed6e0248f23618f8",
"tools/run_s2_recovered_pilot.py": "56962009bf5eaaee599ffea6a3d454372e0aea2842fa79eac609fd4a24ecbb39",
"tools/run_s2_recovery_chain.py": "76d0808bdb2d624cfbaadf5a3c5e7e9a0c2be5d5ac41d4ac3fd9ccd48743933c",
"tools/s2_custody_common.py": "bfa651ce5f7f2b0b74e7099ca90b6a53340c88d0a6d3ac3ddf028055d023e4ec",
"tools/s2_custody_statistics.py": "188565801f6901d0192f79aec0889e632501e672a4149d76d1835efbb9b45447",
"tools/s2_e1_supervisor.py": "6753c9ceb0b932047ba505bd15681f109e9407bdb58fd96c55e1431a3f1b4a02",
"tools/s2_gpu_idle_gate.py": "e2b1613e7e6ea398a8d555220a9365a1ad998ab4ef4b2bf8ec7cc4e31f8b4b9f",
"tools/s2_incident_recovery_manifest.py": "8cbb2e1067c2cc22762d8ae3cf192aa2c5fa7c7a199a22e7a39a25570ee1c3b1",
"tools/s2_main_data.py": "bda31f5e9335b927315292f57e6f689787eacc5b32f7fae3fa23eb13b00343f0",
"tools/s2_main_memory_guard.py": "e094f5443e11518efe9018215c11718a8e18aa462a977bf43e974b2d0b2aebb1",
"tools/s2_models/__init__.py": "a0fa1323d3553172da66c5d442c5fc4fcb0d5055c886c776928604550ea97609",
"tools/s2_models/attention.py": "7714adfccf6a0fc6b52a44aee3a50321a88898bf3d743680a1108c01e1ff8a61",
"tools/s2_models/blocks.py": "b13e986cea5f1d7f325a1638c1505197b4a105baacff5a9a515f23fcaf28ea75",
"tools/s2_models/features.py": "3b34ae61cf8012ebd58b7505a73d7aa43d8ee1890ac54f98d7917b67887a45a4",
"tools/s2_models/network.py": "5137e845d81d1223afc13bf87e03ccba1132a3baa75d5189a8f320b2752be071",
"tools/s2_models/normalization.py": "7180696d3845799e28d8c31ddef957d075de6a2e46d96a3a0f0df16fc05234a0",
"tools/s2_models/objectives.py": "5b6527a45f08690055d572335470ce5979e8bb86e1cab00de594f79ae21316b1",
"tools/s2_models_v2/__init__.py": "0302d333bcd8b33e85aaa6a4e7822e7e1ccfc66343136107fea6f4ca283ba1ec",
"tools/s2_models_v2/attention.py": "3829e34ca30942c863699c4d43fb6fa104452c6c04c4d606c11019d3dde16ffa",
"tools/s2_models_v2/blocks.py": "b13e986cea5f1d7f325a1638c1505197b4a105baacff5a9a515f23fcaf28ea75",
"tools/s2_models_v2/network.py": "a443470caeecdf529504bffab3ca8cc0b70ce44b505bad60f9c63db9709dbb83",
"tools/s2_pilot_data.py": "82c1fd18ec51757479c8fd7dda2db4d5f38c366d77fedcca3216a08998214c97",
"tools/s2_pilot_train.py": "e9cceead51a5cc092aad23409ad98909c84a62e7e10571e750d1e9be1ad3b948",
"tools/s2_precision_continuation_guard.py": "01235d897c7c03e5ffa109c58b14f5d24d128e8f1ba873e1f76cfb14e02f7a7f",
"tools/s2_precision_pilot_gpu_guard.py": "5cf0f41de34b28394dbee4672b5bd34eb9c4fe2344822aa3d648f20561d96328",
"tools/s2_r2_data.py": "a32f8987ff0848c0e052e71500f84bd4f0364a60170121f54770ceb275a98566",
"tools/s2_recovered_pilot_gpu_guard.py": "9a27f47918c865ce37e46b0be54144dc3f9ab1058e4eddc9f6fbc771f4959eb0",
"tools/s2_recovery_gpu_supervisor.py": "689c0f3179e4fcd362e546d90214829a9e4f8739abdbdf74b560763e5a392f15",
"tools/s2_recovery_monitoring.py": "442c2a9c75e8c00b30a8f2e91cb52d87c466b19a80aea9128b10c021e61b922e",
"tools/s2_recovery_supervisor.py": "f563ca3c2665f5baf0c04f296616e4640423a59b815fbb00479af0f29e57a919",
"tools/test_s2_custody.py": "362d63e12ccd88f168e8d58aabc71f6b26c3a6992e7f88d6b6ecdfc071f75158",
"tools/test_s2_main_matrix.py": "d9b05506dd6e5a8a94cccaee28c6d8239bb3c6cdbe31567be1fdd04559154feb",
"tools/test_s2_r2.py": "01d214e6e3ed04b099c30a4567521c37c4cafb0412faa83c973110c8dd600418"
},
"source_sha256": {
"artifacts/s2-terminal-freeze-2026-11-15/terminal-audit.json": "ddd32cd6cb12bc1c893d8aad4928b570f9e2162801ba5e219cb0708f82cb9465",
"artifacts/s2-terminal-freeze-2026-11-15/models.json": "cd544ec7f0e49f0759660a71076566976cacdeaa66dd510aec049b2218f57faf",
"artifacts/s2-terminal-freeze-2026-11-15/evidence-manifest.json": "34b0aa29f8e8ced0ef11ea2d8889f243f1864e7eab8ebb1015082f3b787542b2",
"artifacts/s2-main-matrix-2026-11-15/training-contract.json": "198e5711ed2e7485167068769652c866867229e09ecf0d09b21612debc3b7a56",
"artifacts/s2-r2-main-2026-11-15/contract.json": "edec86197769f44bf98f234795950f36c9fa42084ccb3c68448b63b440aa126e",
"artifacts/s2-main-preparation-2026-11-15/final-roster.json": "fb0c984f2e553343a598ce2e3c7012d3017053dc0fef58b5aaf46dd3c67a207e",
"artifacts/s2-g1-components-2026-11-15/custodian/not-known-exposed-test-subsets.json": "8d037786040c6fc11fa80ceb0f41dfdd58478a2576404505a64aa29a2216a22f",
"artifacts/s2-custody-planning-2026-11-15/exposure-audit.json": "28255a3cf04cf1f651aa7aef12e613cbd11531482ad0bc5730096af79f8f0fc0"
},
"limits": {
"gpu_seconds": 14400,
"fold_wall_seconds": 2700,
"vram_bytes": 16106127360,
"host_bytes": 17179869184,
"fold_disk_bytes": 21474836480,
"disk_bytes": 107374182400,
"custody_cpu_seconds": 36000,
"custody_wall_seconds": 10800,
"retries": 0
},
"statistics": {
"replicates": 2000,
"seed": 2026111408,
"margin": 0.1,
"percentile_method": "linear",
"aggregation": "parts equal within component, fixed seeds equal, pool components across folds",
"complete_pair": "all parts and all three fixed seeds in both arms; no backfill",
"exposure": "frozen522 membership inclUNKNOWN intersect roster intersect main validity; bool only cross-check",
"bootstrap_rng": "PCG64(SeedSequence(2026111408)); sorted component IDs, pooled not fold-stratified",
"undefined_replicates": "count and record, no replacement; interval left undefined if present",
"secondary": [
"near_wall",
"kendall_tau_b",
"last_location",
"worst_component_per_arm"
],
"primary_pool": 100,
"primary_contrast": "1-E/N",
"kendall_seed": 2026111410,
"kendall_pairs": 5000
},
"planned_neural_cells": 90,
"valid_neural_models": 89,
"NA_neural": [
{
"index": 24,
"name": "fold1-pool50-N128-seed0",
"arm": "N",
"status": "NA",
"reason": "WORKER_EXIT_1",
"guard_receipt": "artifacts/s2-main-matrix-2026-11-15/cells/fold1-pool50-N128-seed0/fold1-pool50-N128-seed0-guard-receipt.json",
"guard_sha256": "ff550868e361c18fc4d04ea5ce1f205c030b22f521b79892c64bfa09ac6c50b4",
"worker_status": "STOPPED_OR_FAILED",
"worker_returncode": 1,
"worker_cpu_seconds": 188.163453,
"checkpoint_sha256": null,
"standardizer_fingerprint": null,
"cell_wall_seconds": 211.4663818500121
}
],
"R2_models": 15,
"no_clipping": true,
"inference_precision": "FP32 same as validation",
"target": "T/t_set",
"test_label_gate": "All predictions hash-frozen, scoring code/config immutable Git commit and explicit main review receipt",
"labels_decoded": false
}
@@ -0,0 +1,9 @@
{
"status": "PASS",
"tests": 13,
"seconds": 2.614,
"command": "OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 /home/frank14f/anaconda3/envs/pycuda_3_10/bin/python -m unittest discover -s tools -p test_s2_custody.py -v",
"real_labels_read": false,
"real_models_evaluated": false,
"gpu_used": false
}
@@ -0,0 +1,72 @@
{
"membership_path": "artifacts/s2-g1-components-2026-11-15/custodian/not-known-exposed-test-subsets.json",
"membership_sha256": "8d037786040c6fc11fa80ceb0f41dfdd58478a2576404505a64aa29a2216a22f",
"frozen_public_sha_match": true,
"boolean_cross_check_mismatches": [],
"development_exposed_types": {
"bool_false": 522,
"bool_true": 102
},
"inventory_state_types": {
"str_UNKNOWN": 541,
"str_KNOWN_DEVELOPMENT_EXPOSED": 83
},
"folds": [
{
"fold": 0,
"original_candidate_parts": 108,
"original_candidate_components": 34,
"roster_excluded_parts": 4,
"retained_parts": 104,
"retained_components": 33,
"empty_components_after_part_filter": 4,
"main_model_invalid_components_pool50_EN": 0
},
{
"fold": 1,
"original_candidate_parts": 105,
"original_candidate_components": 36,
"roster_excluded_parts": 0,
"retained_parts": 105,
"retained_components": 36,
"empty_components_after_part_filter": 6,
"main_model_invalid_components_pool50_EN": 36
},
{
"fold": 2,
"original_candidate_parts": 115,
"original_candidate_components": 39,
"roster_excluded_parts": 0,
"retained_parts": 115,
"retained_components": 39,
"empty_components_after_part_filter": 4,
"main_model_invalid_components_pool50_EN": 0
},
{
"fold": 3,
"original_candidate_parts": 90,
"original_candidate_components": 40,
"roster_excluded_parts": 1,
"retained_parts": 89,
"retained_components": 40,
"empty_components_after_part_filter": 4,
"main_model_invalid_components_pool50_EN": 0
},
{
"fold": 4,
"original_candidate_parts": 104,
"original_candidate_components": 40,
"roster_excluded_parts": 0,
"retained_parts": 104,
"retained_components": 40,
"empty_components_after_part_filter": 3,
"main_model_invalid_components_pool50_EN": 0
}
],
"original_parts": 522,
"roster_removed_parts": 5,
"retained_parts": 517,
"retained_components": 188,
"metric_invalid_after_decode": "not evaluated; no labels read",
"labels_decoded": false
}
@@ -0,0 +1,37 @@
# S2 统一托管评估:执行与集中裁量包
## 已接受最终裁量与实现
Claude1794729482.815749、1794729794.605549已关闭全部科学/资源缺口。下文初始提案S5被纠正:以fb827178冻结522件成员名单(含UNKNOWN)为准,SHA8d037786040c6fc11fa80ceb0f41dfdd58478a2576404505a64aa29a2216a22f;逐件∩617roster∩主有效集。bool仅cross-check,实际0差异。保留517件/188组件;50% E/N按主有效集还排fold1,指标资格未解码前不预断。原候选/roster剔除/空组件与逐折分母在exposure-audit.json。pilot参与独立披露、不追加排除。
Bootstrap单一全有效组件抽样框、不按折分层;component ID排序,PCG64(SeedSequence(2026111408)),2000次,双方同索引、seed块随组件,linear百分位,未舍入端点六区间。参考均值0的replicate计数保留、不补抽;实现遇此情形不声称有效CI/决策。worst group按臂最大组件均值描述。
实现:s2_custody_common/statistics、run_s2_custody_predict/predictions/score、prepare_s2_custody。13项合成/元数据验收PASS,2.614s;不读取真实标签,不调用真实模型推理。测试包括失败退出前最后一次记录的VRAM峰值越限仍STOP。真实预测必须另有绑定contract SHA的main-review.json;真实解码必须全部预测哈希核验且scoring-freeze.json绑定contract/预测终态/Git提交。无label reader的推理进程与托管解码进程独立,原训练源码完全不改。
完整训练证据远端固定6903c07365c7879b3fcbe9b78d8dbc3aec695ae0。当前实现待一次主审,预测与评分未执行。
训练已完成并冻结,神经89 PASS/1 NA,R2最终15 PASS;100%池15对全有效。此阶段检验新件查询覆盖内的E/N增量与R2-G24强基线,不检验O1类型组织、真实连通或工业决策可靠性。已有研究方法与本项目差别见固定v0.2–v0.6;R2是Gre24-style图距离近似,不称复现。缺少原生CAE对照、完整场评价及工艺干预仍是边界。
## 不变的进入顺序
1. 冻结原始终态、失败、合同、89神经与15 R2有效模型哈希;失败N权重只作历史证据,不能用于预测。
2. 从无标签几何准备读取同一合格query及multiplicity;89神经模型以与验证相同的FP32推理,15 R2模型和确定性B0=Vf*t_set。每个件只用其外折模型,三个池/三seed不重fit。90计划格中一个显式NA占位。
3. 全部预测写完并哈希固定,评分源码/配置固定到Git且获裁量后才托管解码。先预测后标签,无任何结果驱动修改。
4. 独立解码器每个included件一次读取Fill_time并提取共同eligible查询;不能借用别折训练target缓存冒充本折未读。新托管输出单独保存。
5. 按冻结统计产生逐件、组件、折、汇总、次要和NA表;组件bootstrap2000次,seed2026111408,种子不重抽;报告条件于固定折、训练和选择。
## 待Claude一次裁量的明确提案(未默认为已批准)
- S1 汇总:对每个组件内等权件、每件先算count-weighted relative L2;固定3seed等权;将各折的外测组件合并后组件等权,不先给五折相等权重。另列各折误差以显示分布。
- S2 缺失:A4的全件/三seed双方有效严格生效。50%池fold1缺seed0 N会排除该折所有测试组件于E/N配对bootstrap,不用剩余2seed补齐;E原始单臂结果保留。N/R2、E/R2各用自身两臂共同有效组件并明确各自分母;确定性R2/B0不视作三份独立样本。
- S3 次要指标汇总:near-wall按同一件公式但mask=0<d/t_part<=0.25,空域/零真值范数NA并列原因;配对组件全件/三seed有效才入。Kendall用固定5000均匀i<j有放回点对、保留ties,末到位置按最小原ID解并列,欧氏距/Rg。均先seed均值、件均值再组件等权,仅描述,无新门槛。
- S4 worst group:报告最大组件均值relative L2(先件/seed等权),列组件ID、件数、所属折;不选“最坏若干”或重新调参。
- S5 not-known-exposed:按冻结roster的development_exposed标记,组件任何成员true即整组件exposed;not-known-exposed不声称untouched。是否需另并入pilot学习/验证参与记录,请明确;当前宽128按可行性裁量而非验证择优,历史试验/全库几何筛查仍披露。
- S6 推理失败:任何新预测、ID/hash、非有限值或预算失败即全阶段STOP,不自动改变模型或降精度,不继续解码;将具体错误交主审。真实模型不能在合成验收阶段运行。
- S7 独立资源提案:5个按外折的预测任务,每个最多45分钟wall、15GiB显存/16GiB进程树RSS/20GiB输出,最多4张V100、每张单worker,所有等待/初始化/R2/B0/失败计入总4 GPU-h,零重试。托管解码+评分最多10 worker CPU-h、3小时wall、16GiB RSS;总新增输出100GiB。先一个完整外折作成本检查,之后才并发其余外折;预计超限就停交裁量,不静默扩展。
## 固定报告范围
主100%池Delta=1-E/N,m=0.1、六区间;N/R2、E/R2及B0同表。25/50%学习曲线明确是组件比例并列每折实际件数/节点数;NA按pool/arm;617 included、7 excluded及节点份额,覆盖表逐件,query-only声明。宽128可行性、未测试宽度效应、AMP跳步case未记、R2第二进程身份未记、全库历史筛查、固定fold/seed条件化bootstrap均保留。
合成验收应包含:预测读入无标签、失败权重拒绝、模型/合同/预测哈希变化拒绝、预测缺件不解码、计数权重与组件权重、三seed完整配对、六区间边界、ties与最小ID、近壁空域、主arm排序和零范数。通过后固定代码再进入真实预测;解码更须全部预测冻结及最终统计裁量。
+48
View File
@@ -0,0 +1,48 @@
"""Freeze approved custody plan without evaluating models or decoding labels."""
import json
from pathlib import Path
from freeze_g1_components import sha
from s2_recovery_supervisor import save
ROOT=Path('artifacts/s2-custody-evaluation-2026-11-15')
def main():
if ROOT.exists():raise FileExistsError('Do not overwrite evaluation')
freeze=Path('artifacts/s2-terminal-freeze-2026-11-15')
audit=json.loads((freeze/'terminal-audit.json').read_text())
assert audit['status']=='FROZEN_BEFORE_TEST_PREDICTIONS' and audit['primary_pairs_valid']==15
ncpath=Path('artifacts/s2-main-matrix-2026-11-15/training-contract.json');nc=json.loads(ncpath.read_text())
rcpath=Path('artifacts/s2-r2-main-2026-11-15/contract.json');rc=json.loads(rcpath.read_text())
paths=set(nc['code_sha256'])|set(rc['code_sha256'])
paths.update(str(p) for pattern in ['*s2_custody*.py'] for p in Path('tools').glob(pattern))
paths.update(['tools/audit_samples.py'])
membership='artifacts/s2-g1-components-2026-11-15/custodian/not-known-exposed-test-subsets.json'
exposure_audit='artifacts/s2-custody-planning-2026-11-15/exposure-audit.json'
sources=[str(freeze/'terminal-audit.json'),str(freeze/'models.json'),str(freeze/'evidence-manifest.json'),str(ncpath),str(rcpath),nc['roster'],membership,exposure_audit]
c=dict(version='S2-custody-v1',execution_approved=True,ruling='1794729482.815749',
main_review_required_before_prediction=True,roster=nc['roster'],roster_sha256=nc['roster_sha256'],
exposure_membership=membership,exposure_membership_sha256=sha(membership),exposure_audit=exposure_audit,
models=str(freeze/'models.json'),models_sha256=sha(freeze/'models.json'),
archive=nc['archive'],archive_stat=nc['archive_stat'],gpu_uuids=nc['gpu_uuids'],
cpu_affinities=nc['gpu_cpu_affinities'],code_sha256={p:sha(p) for p in sorted(paths)},
source_sha256={p:sha(p) for p in sources},
limits=dict(gpu_seconds=14400,fold_wall_seconds=2700,vram_bytes=15*2**30,host_bytes=16*2**30,
fold_disk_bytes=20*2**30,disk_bytes=100*2**30,custody_cpu_seconds=36000,custody_wall_seconds=10800,retries=0),
statistics=dict(replicates=2000,seed=2026111408,margin=.1,percentile_method='linear',
aggregation='parts equal within component, fixed seeds equal, pool components across folds',
complete_pair='all parts and all three fixed seeds in both arms; no backfill',
exposure='frozen522 membership inclUNKNOWN intersect roster intersect main validity; bool only cross-check',
bootstrap_rng='PCG64(SeedSequence(2026111408)); sorted component IDs, pooled not fold-stratified',
undefined_replicates='count and record, no replacement; interval left undefined if present',
secondary=['near_wall','kendall_tau_b','last_location','worst_component_per_arm'],
primary_pool=100,primary_contrast='1-E/N',kendall_seed=2026111410,kendall_pairs=5000),
planned_neural_cells=90,valid_neural_models=89,NA_neural=audit['neural_NA'],R2_models=15,
no_clipping=True,inference_precision='FP32 same as validation',target='T/t_set',
test_label_gate='All predictions hash-frozen, scoring code/config immutable Git commit and explicit main review receipt',
labels_decoded=False)
ROOT.mkdir();save(ROOT/'contract.json',c)
print(json.dumps(dict(root=str(ROOT),contract_sha256=sha(ROOT/'contract.json'),status='PREPARED_NOT_STARTED')))
if __name__=='__main__':main()
+78
View File
@@ -0,0 +1,78 @@
"""One held-out fold, frozen models only; no target reader imported."""
import argparse
import os
from pathlib import Path
import time
import traceback
import numpy as np
from s2_custody_common import contract,checked,test_rows,prediction_inputs,expected_models,prediction_path
from s2_recovery_supervisor import save
from freeze_g1_components import sha
def load_neural(m,device):
import torch
from s2_models.normalization import BaseStandardizer
from s2_models_v2.network import QueryModel
checkpoint=torch.load(checked(m['path'],m['sha256']),map_location='cpu',weights_only=True)
assert (checkpoint['arm'],checkpoint['width'],checkpoint['seed'])==(m['arm'],m['width'],m['seed'])
d=checkpoint['standardizer']
stats=BaseStandardizer(d['fold'],d['pool'],tuple(d['learning_part_ids']),d['node_count'],tuple(d['mean']),tuple(d['std']))
assert stats.fingerprint==m['standardizer_fingerprint']==checkpoint['standardizer_fingerprint']
assert stats.fold==str(m['fold']) and stats.pool==str(m['pool'])
model=QueryModel(m['arm'],m['width'],standardizer=stats)
model.load_state_dict(checkpoint['state_dict'],strict=True)
return model.to(device).eval()
def run(root,fold):
import torch,joblib,sklearn
from threadpoolctl import threadpool_limits
root=Path(root);c=contract(root);dest=root/'folds'/str(fold);dest.mkdir(parents=True,exist_ok=False)
start=time.monotonic();cpu=time.process_time()
save(dest/'started.json',dict(pid=os.getpid(),fold=fold,unix=time.time(),contract_sha256=sha(root/'contract.json')))
try:
assert c['execution_approved'] and c['limits']['retries']==0
assert torch.cuda.is_available() and torch.cuda.device_count()==1 and 'V100' in torch.cuda.get_device_name()
assert sklearn.__version__=='1.7.2'
torch.set_num_threads(1);torch.backends.cuda.matmul.allow_tf32=False;torch.cuda.reset_peak_memory_stats()
models=expected_models(c,fold);loaded={};device=torch.device('cuda:0')
with threadpool_limits(1):
for m in models:
if m['kind']=='neural': loaded[m['name']]=load_neural(m,device)
elif m['kind']=='R2': loaded[m['name']]=joblib.load(checked(m['path'],m['sha256']))
index={};rows=test_rows(c,fold)
for i,row in enumerate(rows):
d=prediction_inputs(row)
tensors={k:torch.as_tensor(d[k],device=device,dtype=torch.long if k=='ids' else torch.float32) for k in ['base','ids','gaps','edge']}
for m in models:
if m['kind']=='neural':
with torch.inference_mode(),torch.autocast('cuda',enabled=False):
y=loaded[m['name']](tensors['base'],tensors['ids'],tensors['gaps'],tensors['edge'] if m['arm']=='E' else None).cpu().numpy().astype(np.float64)
elif m['kind']=='R2':y=loaded[m['name']].predict(d['x'])
else:y=d['x'][:,0].copy()
seconds=y*d['t_set']
if seconds.shape!=d['ids'].shape or not np.isfinite(seconds).all():raise ValueError('Invalid prediction '+m['name'])
p=prediction_path(root,m,row['case']);p.parent.mkdir(parents=True,exist_ok=True)
if p.exists():raise FileExistsError('No prediction overwrite/retry')
np.savez_compressed(p,seconds=seconds,raw_ids=d['raw_ids'],counts=d['counts'])
index[str(p)]=sha(p)
del tensors,d
torch.cuda.synchronize()
save(dest/'progress.json',dict(parts_done=i+1,parts_total=len(rows),wall_seconds=time.monotonic()-start,
peak_allocated_bytes=torch.cuda.max_memory_allocated(),peak_reserved_bytes=torch.cuda.max_memory_reserved()))
save(dest/'index.json',index)
save(dest/'result.json',dict(status='COMPLETE',fold=fold,parts=len(rows),models=len(models),predictions=len(index),
labels_read=False,model_fit=False,index_sha256=sha(dest/'index.json'),
wall_seconds=time.monotonic()-start,cpu_seconds=time.process_time()-cpu,
peak_allocated_bytes=torch.cuda.max_memory_allocated(),peak_reserved_bytes=torch.cuda.max_memory_reserved()))
return 0
except Exception as exc:
save(dest/'failure.json',dict(type=type(exc).__name__,message=str(exc),traceback=traceback.format_exc(),
peak_allocated_bytes=torch.cuda.max_memory_allocated() if torch.cuda.is_initialized() else 0,
peak_reserved_bytes=torch.cuda.max_memory_reserved() if torch.cuda.is_initialized() else 0))
raise
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('fold',type=int);a=p.parse_args();raise SystemExit(run(a.root,a.fold))
+133
View File
@@ -0,0 +1,133 @@
"""Bounded, no-retry held-out inference queue; first-fold cost checkpoint."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import psutil
from freeze_g1_components import sha
from s2_custody_common import contract,read_json,test_rows
from s2_recovery_supervisor import save,stop_group,tree_usage
from s2_recovery_gpu_supervisor import supervise
from s2_recovery_monitoring import disk_usage
from s2_main_memory_guard import PeakRecords,device_usage,active_command_pids
def guard(root,fold,slot):
c=contract(root);limits=c['limits'];uuid=c['gpu_uuids'][slot]
os.sched_setaffinity(0,c['cpu_affinities'][slot]);os.environ['PYTORCH_CUDA_ALLOC_CONF']='expandable_segments:True'
start=time.monotonic();dest=root/'guards'/str(fold);dest.mkdir(parents=True,exist_ok=False)
command=[sys.executable,'tools/run_s2_custody_predict.py',str(root),str(fold)]
done=threading.Event();tracker=PeakRecords();monitor=dict(reasons=[],child_processes={},peak_device_bytes=0,peak_tree_rss_bytes=0)
receipt=None
def reason(s):
if s not in monitor['reasons']:monitor['reasons'].append(s)
def watch():
while not done.is_set():
try:
used,_=device_usage(uuid);monitor['peak_device_bytes']=max(monitor['peak_device_bytes'],used)
if used>limits['vram_bytes']:reason('DEVICE_VRAM_LIMIT')
_,rss,_=tree_usage(os.getpid());monitor['peak_tree_rss_bytes']=max(monitor['peak_tree_rss_bytes'],rss)
if rss>limits['host_bytes']:reason('TREE_RSS_LIMIT')
if tracker.scan(root/'folds'/str(fold)):reason('RECORDED_VRAM_LIMIT')
if disk_usage(root/'predictions'/str(fold))+disk_usage(root/'folds'/str(fold))>limits['fold_disk_bytes']:reason('FOLD_DISK_LIMIT')
for p in psutil.Process().children(recursive=True):
try:monitor['child_processes'][str(p.pid)]=dict(ppid=p.ppid(),cmdline=p.cmdline())
except psutil.NoSuchProcess:pass
except Exception as exc:reason('MONITOR_ERROR:'+str(exc))
if monitor['reasons']:
for pid in active_command_pids(command):stop_group(pid)
done.wait(1)
try:
for _ in range(3):
used,util=device_usage(uuid)
if used>128*2**20 or util>0:raise RuntimeError('SELECTED_GPU_BUSY')
time.sleep(1)
thread=threading.Thread(target=watch,daemon=True);thread.start()
try:
receipt=supervise(command,dest,'worker',dict(total_cpu_seconds=86400,job_cpu_seconds=86400,
job_wall_seconds=limits['fold_wall_seconds']-(time.monotonic()-start)-5,tree_rss_bytes=limits['host_bytes'],
disk_bytes=limits['fold_disk_bytes'],max_processes=2),poll=.2,gpu_uuid=uuid)
finally:done.set();thread.join(timeout=5)
if thread.is_alive():reason('MONITOR_DID_NOT_STOP')
if tracker.scan(root/'folds'/str(fold)):reason('RECORDED_VRAM_LIMIT')
result=root/'folds'/str(fold)/'result.json'
if not result.exists() or read_json(result).get('status')!='COMPLETE':reason('MISSING_COMPLETE_RESULT')
if time.monotonic()-start>limits['fold_wall_seconds']:reason('TOTAL_FOLD_WALL_LIMIT')
if monitor['reasons'] or receipt['status']!='PASS':return 1
return 0
except Exception as exc:reason(type(exc).__name__+':'+str(exc));return 1
finally:
save(dest/'guard-result.json',dict(status='PASS' if receipt and receipt['status']=='PASS' and not monitor['reasons'] else 'STOPPED_OR_FAILED',
worker=receipt,monitor=monitor,recorded_memory=tracker.as_dict(),wall_seconds=time.monotonic()-start,fold=fold))
def run(root):
c=contract(root);limits=c['limits']
approval=read_json(root/'main-review.json');assert approval['approved'] and approval['contract_sha256']==sha(root/'contract.json')
marker=root/'predictions-started.json'
with marker.open('x') as f:json.dump(dict(pid=os.getpid(),unix=time.time()),f)
active={};completed=[];next_fold=0;charged=0.;first=False;stop=None
def launch(fold,slot):
log=(root/f'fold-{fold}-guard.log').open('x')
p=subprocess.Popen([sys.executable,__file__,str(root),'--guard',str(fold),'--slot',str(slot)],stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
log.close();active[slot]=dict(process=p,fold=fold,start=time.monotonic())
try:
while next_fold<5 or active:
for slot,v in list(active.items()):
ret=v['process'].poll()
if ret is None:continue
cost=time.monotonic()-v['start'];charged+=cost
p=root/'guards'/str(v['fold'])/'guard-result.json'
if ret or not p.exists() or read_json(p)['status']!='PASS':stop='FOLD_FAILED_'+str(v['fold'])
completed.append(dict(fold=v['fold'],charged_gpu_seconds=cost,returncode=ret));del active[slot]
if completed and not first and not active and stop is None:
nodes=[sum(r['nodes'] for r in test_rows(c,f)) for f in range(5)]
projection=charged+1.25*charged*sum(nodes[1:])/nodes[0]
save(root/'first-fold-cost.json',dict(charged_gpu_seconds=charged,projection_gpu_seconds=projection,
heuristic='first-fold full cost per test node;25percent reserve',continue_within_cap=projection<=limits['gpu_seconds']))
if projection>limits['gpu_seconds']:stop='FIRST_FOLD_COST_EXCEEDS_CAP'
first=True
live=sum(time.monotonic()-v['start'] for v in active.values())
if charged+live>limits['gpu_seconds']:stop='AGGREGATE_GPU_LIMIT'
if disk_usage(root)>limits['disk_bytes']:stop='TOTAL_DISK_LIMIT'
if stop:break
for slot in range(4):
if next_fold>=5 or slot in active or (not first and next_fold>0):continue
# Every dispatched job reserves its entire approved lifetime.
if charged+(len(active)+1)*(limits['fold_wall_seconds']+10)>limits['gpu_seconds']:
stop='INSUFFICIENT_RESERVED_GPU_BUDGET';break
launch(next_fold,slot);next_fold+=1
save(root/'predictions-progress.json',dict(completed=completed,active={s:v['fold'] for s,v in active.items()},charged_gpu_seconds=charged,
live_gpu_seconds=live,first_fold_passed=first,stop_reason=stop))
time.sleep(1)
finally:
for v in active.values():
# Stop descendants before the guard so none can outlive the queue.
try:
children=psutil.Process(v['process'].pid).children(recursive=True)
for p in reversed(children):
try:p.kill()
except psutil.NoSuchProcess:pass
except psutil.NoSuchProcess:pass
stop_group(v['process'].pid);v['process'].wait();charged+=time.monotonic()-v['start']
if stop:
save(root/'predictions-stopped.json',dict(reason=stop,completed=completed,charged_gpu_seconds=charged,labels_decoded=False));return 1
index={}
for f in range(5):
p=root/'folds'/str(f)/'index.json';d=read_json(root/'folds'/str(f)/'result.json');assert sha(p)==d['index_sha256']
index.update(read_json(p))
for p,h in index.items():assert sha(p)==h
save(root/'prediction-index.json',index)
save(root/'predictions-complete.json',dict(status='ALL_PREDICTIONS_FROZEN',contract_sha256=sha(root/'contract.json'),
prediction_index_sha256=sha(root/'prediction-index.json'),files=len(index),charged_gpu_seconds=charged,
neural_models=89,neural_NA=1,r2_models=15,B0=True,labels_decoded=False,model_fit=False))
return 0
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('--guard',type=int);p.add_argument('--slot',type=int);a=p.parse_args()
raise SystemExit(guard(a.root,a.guard,a.slot) if a.guard is not None else run(a.root))
+162
View File
@@ -0,0 +1,162 @@
"""Decode once after prediction/code freeze, then execute immutable statistics."""
import argparse
from collections import Counter
import json
import os
from pathlib import Path
import sys
import time
import traceback
import threading
from xml.etree import ElementTree as ET
from zipfile import ZipFile
import numpy as np
from audit_samples import decode_array
from freeze_g1_components import sha
from s2_custody_common import contract,read_json,checked,verify_prediction_index,test_rows,expected_models,prediction_path,prediction_inputs
from s2_custody_statistics import part_metrics,component_values,contrast
from s2_recovery_supervisor import save,supervise,stop_group
from s2_recovery_monitoring import disk_usage
def decode_custody_label(archive,case,raw_ids):
"""Called only inside gated custody; never reuse another fold's target cache."""
ids=np.asarray(raw_ids);stack=[];count=None;header=None
if ids.ndim!=1 or ids.dtype.kind not in 'iu' or not len(ids) or np.any(np.diff(ids)<=0):raise ValueError('Ascending original IDs required')
with ZipFile(archive) as z,z.open(case+'_sim.vtu') as stream:
for event,e in ET.iterparse(stream,events=('start','end')):
if event=='start':
stack.append(e.tag)
if e.tag=='VTKFile':
if e.get('byte_order')!='LittleEndian' or e.get('compressor')!='vtkZLibDataCompressor':raise ValueError('Unsupported encoding')
header=e.get('header_type','UInt32')
elif e.tag=='Piece':
if count is not None:raise ValueError('Multiple pieces')
count=int(e.get('NumberOfPoints'))
else:
if e.tag=='DataArray':
if stack[-2]=='PointData' and e.get('Name')=='Fill_time':
values=decode_array(e,header)
if values.shape!=(count,) or ids[0]<0 or ids[-1]>=count:raise ValueError('Label/ID mismatch')
values=values[ids].copy()
if not np.isfinite(values).all() or np.any(values<0):raise ValueError('Invalid eligible Fill_time')
return values
e.clear()
stack.pop()
raise ValueError('Fill_time missing')
def decode_gate(root,c):
proof,index=verify_prediction_index(root,c)
gate=read_json(root/'scoring-freeze.json')
if not gate['approved'] or not gate['git_commit'] or gate['contract_sha256']!=sha(root/'contract.json'):
raise ValueError('Scoring code/config not approved and Git-frozen')
if gate['prediction_complete_sha256']!=sha(root/'predictions-complete.json'):raise ValueError('Prediction freeze mismatch')
return proof,index
def reports(rows,roster,c):
tables=[];contrasts=[];component_tables=[]
members={p for f in read_json(checked(c['exposure_membership'],c['exposure_membership_sha256'])) for p in f['parts']}
for subset in ['all','not_known_exposed']:
for pool in [25,50,100]:
full={}
for metric in ['relative_l2','near_wall','kendall_tau_b','last_location']:
for arm in ['N','E','R2','B0']:
vals,excluded,details=component_values(rows,roster,arm,pool,metric,subset!='all',members)
folds={f:[v for k,v in vals.items() if details[k]['fold']==f] for f in range(5)}
worst=max(vals,key=vals.get) if vals and metric=='relative_l2' else None
tables.append(dict(subset=subset,pool_component_fraction=pool/100,arm=arm,metric=metric,
mean=float(np.mean(list(vals.values()))) if vals else None,components=len(vals),
included_parts=sum(details[k]['parts'] for k in vals),included_nodes=sum(details[k]['nodes'] for k in vals),
excluded_components=excluded,fold_means={f:float(np.mean(v)) if v else None for f,v in folds.items()},
worst_component=dict(component_id=worst,value=vals[worst],**details[worst]) if worst else None))
component_tables.extend(dict(subset=subset,pool=pool,arm=arm,metric=metric,component_id=k,value=v,**details[k]) for k,v in vals.items())
if metric=='relative_l2':full[arm]=(vals,excluded,details)
for ref,arm in [('N','E'),('R2','N'),('R2','E'),('B0','N'),('B0','E'),('B0','R2')]:
a,_,ad=full[ref];b,_,bd=full[arm];pair=set(a)&set(b)
result=contrast(a,b,c['statistics']['replicates'],c['statistics']['seed'])
all_ids=set(ad)|set(bd);excluded=sorted(all_ids-pair)
contrasts.append(dict(subset=subset,pool=pool,reference=ref,candidate=arm,
primary=subset=='all' and pool==100 and (ref,arm)==('N','E'),
included_folds=sorted({ad[k]['fold'] for k in pair}),excluded_components=excluded,
excluded_parts=sum(ad[k]['parts'] for k in excluded),excluded_nodes=sum(ad[k]['nodes'] for k in excluded),**result))
return tables,contrasts,component_tables
def run(root):
c=contract(root);proof,index=decode_gate(root,c)
dest=root/'custody';dest.mkdir(exist_ok=False)
save(dest/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),
scoring_freeze_sha256=sha(root/'scoring-freeze.json'),prediction_complete_sha256=sha(root/'predictions-complete.json')))
start=time.monotonic();cpu=time.process_time();decoded=[];scores=[];coverage=[]
try:
st=Path(c['archive']).stat();v=c['archive_stat']
assert (st.st_size,st.st_mtime_ns,st.st_ino)==(v['bytes'],v['mtime_ns'],v['inode'])
for fold in range(5):
for row in test_rows(c,fold):
d=prediction_inputs(row);truth=decode_custody_label(c['archive'],row['case'],d['raw_ids'])
target=dest/'labels'/(row['case']+'.npz');target.parent.mkdir(exist_ok=True)
if target.exists():raise FileExistsError('No repeated custody decode')
np.savez_compressed(target,seconds=truth,raw_ids=d['raw_ids'],counts=d['counts'])
decoded.append(dict(case=row['case'],fold=fold,path=str(target),sha256=sha(target),decoded_arrays=['Fill_time']))
for model in expected_models(c,fold):
p=prediction_path(root,model,row['case']);checked(p,index[str(p)])
with np.load(p,allow_pickle=False) as z:
if not np.array_equal(z['raw_ids'],d['raw_ids']) or not np.array_equal(z['counts'],d['counts']):raise ValueError('Prediction/query order mismatch')
metrics=part_metrics(z['seconds'],truth,d['counts'],d['near_wall'],d['raw_ids'],d['coordinates_over_Rg'],row['case'].split('_')[0])
scores.append(dict(case=row['case'],component_id=row['component_id'],fold=fold,pool=model['pool'],arm=model['arm'],seed=model['seed'],**metrics))
prep=row['preparation'];cp=Path(prep['preparation_root'])/'result.json';checked(cp,prep['result_sha256'])
pr=read_json(cp)
coverage.append(dict(case=row['case'],fold=fold,component_id=row['component_id'],nodes=row['nodes'],
**{k:pr[k] for k in ['draw_slots','unique_drawn','eligible_unique','eligible_slots','conditional_coverage','full_lumped_coverage','boundary_mass_fraction','eligible_near_wall_slots','rejection_counts_overlapping']},
positive_mass_fraction=pr['scales']['positive_mass_fraction'],exposure=row['exposure']))
save(dest/'progress.json',dict(decoded_parts=len(decoded),scored_rows=len(scores),cpu_seconds=time.process_time()-cpu,wall_seconds=time.monotonic()-start))
save(dest/'label-index.json',decoded);save(dest/'part-scores.json',scores);save(dest/'coverage.json',coverage)
roster=read_json(c['roster']);tables,contrasts,components=reports(scores,roster['parts'],c)
save(dest/'tables.json',tables);save(dest/'contrasts.json',contrasts);save(dest/'component-scores.json',components)
save(dest/'learning-pool-counts.json',roster['fold_pool_counts'])
excluded=[r for r in roster['parts'] if not r['included']]
result=dict(status='COMPLETE',decoded_parts=len(decoded),scored_rows=len(scores),primary=next(r for r in contrasts if r['primary']),
neural_useful_vs_R2=(next(r for r in contrasts if r['subset']=='all' and r['pool']==100 and r['reference']=='R2' and r['candidate']=='N').get('low') or 0)>0,
excluded_parts=excluded,excluded_nodes=sum(r['nodes'] for r in excluded),all_nodes=sum(r['nodes'] for r in roster['parts']),
neural_NA=c['NA_neural'],cpu_seconds=time.process_time()-cpu,wall_seconds=time.monotonic()-start,
limitations=['query common eligibility only, not whole-part result','fixed folds and trained seeds; no retraining variance',
'not-known-exposed is part-filtered descriptive, not untouched','historical all-corpus geometry screening and pilot fitting disclosed',
'width128 feasibility, width effect not tested','AMP skipped case not saved','R2 job118 child identity unknown',
'S2 tests E/N increment and R2 baseline, no conclusion about O1/geometry organisation'],
output_sha256={p.name:sha(p) for p in dest.glob('*.json') if p.name not in ['progress.json','started.json']})
save(dest/'result.json',result);return 0
except Exception as exc:
save(dest/'failure.json',dict(type=type(exc).__name__,message=str(exc),traceback=traceback.format_exc(),decoded_parts=len(decoded),scored_rows=len(scores)))
raise
def guarded(root):
c=contract(root);decode_gate(root,c);l=c['limits']
import psutil
done=threading.Event();reasons=[];command=[sys.executable,__file__,str(root),'--worker']
def watch():
while not done.is_set():
try:
if disk_usage(root)>l['disk_bytes']:reasons.append('TOTAL_DISK_LIMIT')
except Exception as exc:reasons.append('DISK_MONITOR_ERROR:'+str(exc))
if reasons:
for child in psutil.Process().children(recursive=True):
try:
if child.cmdline()==command:stop_group(child.pid)
except psutil.NoSuchProcess:pass
done.wait(1)
t=threading.Thread(target=watch,daemon=True);t.start()
try:
r=supervise(command,root/'custody-guard','worker',dict(total_cpu_seconds=l['custody_cpu_seconds'],
job_cpu_seconds=l['custody_cpu_seconds'],job_wall_seconds=l['custody_wall_seconds'],tree_rss_bytes=l['host_bytes'],disk_bytes=l['disk_bytes'],max_processes=2),poll=.5)
finally:done.set();t.join(timeout=3)
if reasons:r.update(status='STOPPED_OR_FAILED',stop_reason=reasons[0])
save(root/'custody-guard-result.json',r)
return 0 if r['status']=='PASS' and (root/'custody/result.json').exists() else 1
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('--worker',action='store_true');a=p.parse_args()
raise SystemExit(run(a.root) if a.worker else guarded(a.root))
+65
View File
@@ -0,0 +1,65 @@
"""Frozen evaluation inputs. This module cannot decode or load target labels."""
import json
from pathlib import Path
import numpy as np
from freeze_g1_components import sha
def read_json(path):
return json.loads(Path(path).read_text())
def checked(path, digest):
p=Path(path)
if sha(p)!=digest: raise ValueError('SHA mismatch: '+str(p))
return p
def contract(root):
c=read_json(Path(root)/'contract.json')
for p,h in {**c['code_sha256'],**c['source_sha256']}.items(): checked(p,h)
return c
def test_rows(c, fold):
rows=read_json(checked(c['roster'],c['roster_sha256']))['parts']
return sorted((r for r in rows if r['included'] and r['assignments'][fold]['role']=='test'),key=lambda r:r['case'])
def prediction_inputs(row):
"""Only base/queries/R2 features: no training-cache or archive access."""
prep=row['preparation'];root=Path(prep['preparation_root'])
for name in ['base.npy','queries.npz','r2.npz']:
checked(root/name,prep['output_sha256'][name])
base=np.load(root/'base.npy',allow_pickle=False)
with np.load(root/'queries.npz',allow_pickle=False) as q:
keep=q['eligible_s2']; ids=q['anchor_ids'][keep]
d=dict(ids=ids,raw_ids=q['raw_node_ids'][keep],counts=q['multiplicity'][keep],
gaps=q['g'][keep],edge=q['edge_summary'][keep],near_wall=q['near_wall'][keep])
with np.load(root/'r2.npz',allow_pickle=False) as q: x=q['features'][ids].copy()
if base.shape!=(row['nodes'],10) or x.shape!=(len(ids),20) or not len(ids): raise ValueError('Feature/query shape')
if not all(np.isfinite(a).all() for a in [base,x,d['gaps'],d['edge']]):raise ValueError('Nonfinite feature')
if not np.all(x[:,-1]==prep['t_set']):raise ValueError('Process setting mismatch')
if np.any(np.diff(d['raw_ids'])<=0):raise ValueError('Ascending unique original IDs required')
return dict(**d,base=base,x=x,coordinates_over_Rg=base[ids,:3],t_set=prep['t_set'])
def prediction_path(root, model, case):
return Path(root)/'predictions'/str(model['fold'])/model['name']/(case+'.npz')
def expected_models(c,fold):
models=[m for m in read_json(checked(c['models'],c['models_sha256'])) if m['fold']==fold]
models.append(dict(kind='B0',arm='B0',name=f'fold{fold}-B0',fold=fold,pool=None,seed=None))
return models
def verify_prediction_index(root,c):
root=Path(root);proof=read_json(root/'predictions-complete.json')
if proof['status']!='ALL_PREDICTIONS_FROZEN' or proof['contract_sha256']!=sha(root/'contract.json'):
raise ValueError('Predictions not frozen against current contract')
index=read_json(checked(root/'prediction-index.json',proof['prediction_index_sha256']))
expected={str(prediction_path(root,m,r['case'])) for f in range(5) for m in expected_models(c,f) for r in test_rows(c,f)}
if set(index)!=expected:raise ValueError('Missing/extra prediction files')
for p,h in index.items():checked(p,h)
return proof,index
+89
View File
@@ -0,0 +1,89 @@
"""Preregistered array-only statistics; no dataset or model access."""
from collections import defaultdict
import numpy as np
from s2_models.objectives import relative_l2
def six_region(low,high,margin=.1):
if not np.isfinite([low,high,margin]).all() or low>high or margin<=0:raise ValueError('Invalid interval')
if high<0:return 'harmful'
if low<=0:return 'no meaningful gain' if high<margin else 'insufficient evidence'
if high<margin:return 'positive but below margin'
return 'positive, size undetermined' if low<=margin else 'meaningful gain supported'
def kendall_pairs(truth,prediction,prefix,draws=5000):
t=np.asarray(truth);p=np.asarray(prediction);n=len(t)
if n<2:return dict(value=None,reason='fewer than two eligible IDs')
rng=np.random.default_rng(np.random.SeedSequence([2026111410,int(prefix)]))
# Uniform ordered distinct pairs collapse to uniform unordered i<j pairs.
i=rng.integers(0,n,draws);j=rng.integers(0,n-1,draws);j+=j>=i
lo=np.minimum(i,j);hi=np.maximum(i,j)
st=np.sign(t[hi]-t[lo]);sp=np.sign(p[hi]-p[lo])
denominator=np.sqrt(float(np.count_nonzero(st))*float(np.count_nonzero(sp)))
if denominator==0:return dict(value=None,reason='zero tau-b denominator')
return dict(value=float(np.sum(st*sp)/denominator),reason=None)
def last_location(truth,prediction,raw_ids,coordinates_over_Rg):
t=np.asarray(truth);p=np.asarray(prediction);ids=np.asarray(raw_ids)
a=np.flatnonzero(t==t.max());b=np.flatnonzero(p==p.max())
ia=a[np.argmin(ids[a])];ib=b[np.argmin(ids[b])]
return float(np.linalg.norm(np.asarray(coordinates_over_Rg)[ia]-np.asarray(coordinates_over_Rg)[ib]))
def part_metrics(prediction,truth,counts,near_wall,raw_ids,coordinates_over_Rg,prefix):
p=np.asarray(prediction);t=np.asarray(truth)
if p.shape!=t.shape or p.ndim!=1 or not len(p) or not np.isfinite(p).all() or not np.isfinite(t).all():raise ValueError('Invalid scores')
near=np.asarray(near_wall,dtype=bool)
return dict(relative_l2=relative_l2(p,t,counts,np.ones(len(t),bool)),
near_wall=relative_l2(p,t,counts,near) if near.any() else dict(value=None,reason='empty near-wall domain'),
kendall_tau_b=kendall_pairs(t,p,prefix),
last_location=dict(value=last_location(t,p,raw_ids,coordinates_over_Rg),reason=None))
def component_values(rows,roster,arm,pool,metric='relative_l2',not_known_exposed=False,frozen_members=None):
"""Complete fixed seed blocks; exposure filters parts before component means."""
if any(type(r['exposure']['development_exposed']) is not bool for r in roster):
raise ValueError('development_exposed must be bool; UNKNOWN is a separate inventory field')
if not_known_exposed and frozen_members is None:raise ValueError('Frozen exposure membership required')
main_excluded=component_values(rows,roster,arm,pool,metric,False)[1] if not_known_exposed else {}
parts=[r for r in roster if r['included'] and (not not_known_exposed or r['case'] in frozen_members)]
grouped=defaultdict(list)
for r in parts:grouped[r['component_id']].append(r)
by_key={(r['case'],r['arm'],r['pool'],r['seed']):r for r in rows}
values={};excluded={};details={}
seeds=[0,1,2] if arm in ['N','E'] else [None]
model_pool=None if arm=='B0' else pool
for component,members in sorted(grouped.items()):
block=[];reasons=[]
for member in members:
per_seed=[]
for seed in seeds:
row=by_key.get((member['case'],arm,model_pool,seed))
value=None if row is None else row[metric]['value']
if value is None:reasons.append(dict(case=member['case'],seed=seed,reason='missing prediction/model' if row is None else row[metric]['reason']))
else:per_seed.append(value)
block.append(per_seed)
details[component]=dict(parts=len(members),nodes=sum(x['nodes'] for x in members),
fold=next(a['fold'] for a in members[0]['assignments'] if a['role']=='test'))
if component in main_excluded:excluded[component]=dict(**details[component],reasons=main_excluded[component]['reasons'],main_analysis_invalid=True)
elif reasons:excluded[component]=dict(**details[component],reasons=reasons)
else:values[component]=float(np.mean(block))
return values,excluded,details
def contrast(reference,candidate,replicates=2000,seed=2026111408):
ids=sorted(set(reference)&set(candidate))
if not ids:return dict(value=None,reason='no complete paired components',components=0)
a=np.array([reference[k] for k in ids]);b=np.array([candidate[k] for k in ids])
if a.mean()<=0:return dict(value=None,reason='zero reference mean',components=len(ids))
rng=np.random.Generator(np.random.PCG64(np.random.SeedSequence(seed)));sample=rng.integers(0,len(ids),size=(replicates,len(ids)))
aa=a[sample].mean(axis=1);bb=b[sample].mean(axis=1)
undefined=np.flatnonzero(aa<=0)
if len(undefined):return dict(value=float(1-b.mean()/a.mean()),reason='undefined bootstrap replicates; no replacement or interval',
components=len(ids),undefined_replicates=len(undefined),undefined_replicate_indices=undefined.tolist(),low=None,high=None,region=None)
boot=1-bb/aa;low,high=np.percentile(boot,[2.5,97.5],method='linear')
return dict(value=float(1-b.mean()/a.mean()),low=float(low),high=float(high),components=len(ids),component_ids=ids,
reference_mean=float(a.mean()),candidate_mean=float(b.mean()),replicates=replicates,seed=seed,undefined_replicates=0,
interval='component-only percentile95 conditional on fixed folds/models/seeds',region=six_region(low,high))
+131
View File
@@ -0,0 +1,131 @@
"""Synthetic-only acceptance of custody separation and preregistered statistics."""
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import numpy as np
from freeze_g1_components import sha
from s2_custody_common import checked,prediction_inputs,verify_prediction_index
from s2_custody_statistics import six_region,kendall_pairs,last_location,part_metrics,component_values,contrast
from run_s2_custody_score import decode_gate
def roster():
return [dict(case=p,component_id=g,nodes=10,included=True,exposure=dict(development_exposed=e,inventory_state='UNKNOWN'),
assignments=[dict(fold=f,role='test' if f==fold else 'learning') for f in range(5)])
for p,g,e,fold in [('a','groupA',False,0),('b','groupA',True,0),('c','groupB',False,1)]]
def rows():
return [dict(case=p,arm=arm,pool=100,seed=s,relative_l2=dict(value=value,reason=None))
for p,value in [('a',1.),('b',3.),('c',8.)] for arm in ['N','E'] for s in [0,1,2]]
class Acceptance(unittest.TestCase):
def test_six_regions_and_exact_boundaries(self):
for l,u,want in [(-.2,-.1,'harmful'),(-.1,0,'no meaningful gain'),(0,.099,'no meaningful gain'),
(0,.1,'insufficient evidence'),(.01,.099,'positive but below margin'),(.01,.1,'positive, size undetermined'),
(.1,.2,'positive, size undetermined'),(.1000000001,.2,'meaningful gain supported')]:
self.assertEqual(six_region(l,u),want)
with self.assertRaises(ValueError):six_region(.2,.1)
def test_hierarchy_is_not_part_or_fold_weighted(self):
vals,excluded,_=component_values(rows(),roster(),'N',100)
self.assertEqual(vals,{'groupA':2.,'groupB':8.});self.assertFalse(excluded)
self.assertEqual(np.mean(list(vals.values())),5.)
def test_three_seed_complete_no_two_seed_backfill(self):
rr=[x for x in rows() if not(x['case']=='a' and x['arm']=='N' and x['seed']==0)]
n,excluded,_=component_values(rr,roster(),'N',100);e,_,_=component_values(rr,roster(),'E',100)
self.assertEqual(set(n),{'groupB'});self.assertIn('groupA',excluded)
self.assertEqual(contrast(n,e)['component_ids'],['groupB'])
def test_frozen_part_exposure_keeps_mixed_component(self):
vals,_,_=component_values(rows(),roster(),'N',100,not_known_exposed=True,frozen_members={'a','c'})
self.assertEqual(vals,{'groupA':1.,'groupB':8.})
with self.assertRaises(ValueError):component_values(rows(),roster(),'N',100,not_known_exposed=True)
bad=roster();bad[0]['exposure']['development_exposed']='UNKNOWN'
with self.assertRaises(ValueError):component_values(rows(),bad,'N',100)
def test_exposure_does_not_rescue_invalid_main_component(self):
rr=[x for x in rows() if x['case']!='b']
vals,excluded,_=component_values(rr,roster(),'N',100,not_known_exposed=True,frozen_members={'a','c'})
self.assertNotIn('groupA',vals);self.assertTrue(excluded['groupA']['main_analysis_invalid'])
def test_bootstrap_matched_indices_sorted_rng_and_ratio_of_means(self):
a={'b':2.,'a':1.};b={'a':.5,'b':1.}
r=contrast(a,b);self.assertAlmostEqual(r['value'],.5);self.assertAlmostEqual(r['low'],.5);self.assertEqual(r['component_ids'],['a','b'])
b={'a':.9,'b':.5};r=contrast(a,b)
rng=np.random.Generator(np.random.PCG64(np.random.SeedSequence(2026111408)))
ids=rng.integers(0,2,(2000,2));boot=1-np.array([.9,.5])[ids].mean(1)/np.array([1.,2.])[ids].mean(1)
np.testing.assert_array_equal([r['low'],r['high']],np.percentile(boot,[2.5,97.5],method='linear'))
def test_undefined_bootstrap_is_counted_not_replaced(self):
r=contrast({'a':0.,'b':1.},{'a':0.,'b':.5})
self.assertGreater(r['undefined_replicates'],0);self.assertIsNone(r['low'])
def test_ties_kendall_and_last_location(self):
self.assertEqual(kendall_pairs([1,1,2],[2,2,4],3)['value'],1.)
self.assertEqual(kendall_pairs([1,1,2],[4,4,2],3)['value'],-1.)
self.assertIsNone(kendall_pairs([1,1],[2,2],3)['value'])
self.assertEqual(last_location([2,2,1],[1,1,2],[20,10,30],[[0,0,0],[1,0,0],[3,0,0]]),2.)
def test_count_weighted_error_empty_slice_and_zero_norm(self):
m=part_metrics([2.,2.],[1.,2.],[3,1],[False,False],[0,1],[[0,0,0],[1,0,0]],1)
self.assertAlmostEqual(m['relative_l2']['value'],np.sqrt(3/7));self.assertIsNone(m['near_wall']['value'])
m=part_metrics([1.,1.],[0.,0.],[1,1],[True,True],[0,1],[[0,0,0],[1,0,0]],1)
self.assertIsNone(m['relative_l2']['value'])
def test_hash_change_and_no_prediction_decode_gate(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);p=root/'input';p.write_text('one');h=sha(p);p.write_text('two')
with self.assertRaises(ValueError):checked(p,h)
with patch('run_s2_custody_score.decode_custody_label',side_effect=AssertionError('label must remain sealed')) as decoder:
with self.assertRaises(FileNotFoundError):decode_gate(root,{})
decoder.assert_not_called()
def test_prediction_reader_only_uses_label_free_features(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);base=np.zeros((3,10));x=np.zeros((3,20));x[:,-1]=.4
np.save(root/'base.npy',base);np.savez(root/'r2.npz',features=x)
np.savez(root/'queries.npz',eligible_s2=[True,False,True],anchor_ids=[0,1,2],raw_node_ids=[10,11,12],
multiplicity=[2,1,3],g=np.ones((3,2)),edge_summary=np.ones((3,4)),near_wall=[True,False,False])
row=dict(nodes=3,preparation=dict(preparation_root=str(root),t_set=.4,
output_sha256={p.name:sha(p) for p in root.iterdir()}))
original=np.load;paths=[]
def audit(path,**kwargs):paths.append(Path(path).name);return original(path,**kwargs)
with patch('s2_custody_common.np.load',side_effect=audit):d=prediction_inputs(row)
self.assertEqual(set(paths),{'base.npy','r2.npz','queries.npz'});np.testing.assert_array_equal(d['raw_ids'],[10,12])
def test_frozen_real_metadata_denominators_no_label_read(self):
# Only immutable JSON membership/roster metadata, never geometry or targets.
path=Path('artifacts/s2-g1-components-2026-11-15/custodian/not-known-exposed-test-subsets.json')
self.assertEqual(sha(path),'8d037786040c6fc11fa80ceb0f41dfdd58478a2576404505a64aa29a2216a22f')
members=json.loads(path.read_text());r=json.loads(Path('artifacts/s2-main-preparation-2026-11-15/final-roster.json').read_text())['parts']
expected=[(104,33),(105,36),(115,39),(89,40),(104,40)]
for f in members:
candidates={x['case'] for x in r if x['assignments'][f['fold']]['role']=='test' and x['exposure']['development_exposed'] is False}
self.assertEqual(candidates,set(f['parts']))
keep=[x for x in r if x['included'] and x['case'] in set(f['parts'])]
self.assertEqual((len(keep),len({x['component_id'] for x in keep})),expected[f['fold']])
def test_prediction_guard_checks_final_recorded_peak(self):
import run_s2_custody_predictions as guard
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp)
c=dict(gpu_uuids=['synthetic'],cpu_affinities=[[0]],limits=dict(vram_bytes=15*2**30,host_bytes=16*2**30,
fold_disk_bytes=20*2**30,fold_wall_seconds=2700))
def fake_supervise(*args,**kwargs):
p=root/'folds/0';p.mkdir(parents=True)
(p/'result.json').write_text(json.dumps(dict(status='COMPLETE',peak_allocated_bytes=1,peak_reserved_bytes=16*2**30)))
return dict(status='PASS')
with patch.object(guard,'contract',return_value=c),patch.object(guard.os,'sched_setaffinity'),patch.object(guard.time,'sleep'),\
patch.object(guard,'device_usage',return_value=(0,0)),patch.object(guard,'tree_usage',return_value=(0,0,1)),\
patch.object(guard,'supervise',side_effect=fake_supervise),patch.object(guard,'active_command_pids',return_value=[]):
self.assertEqual(guard.guard(root,0,0),1)
r=json.loads((root/'guards/0/guard-result.json').read_text())
self.assertIn('RECORDED_VRAM_LIMIT',r['monitor']['reasons'])
if __name__=='__main__':unittest.main()