diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..ee2aa99597a22854eae01da9abbfdf2b09839604 100644 --- a/.gitattributes +++ b/.gitattributes @@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +plots/all-task-progression.pdf filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..87eb3923fc53a45bea3959acc7e53e22f595aaed --- /dev/null +++ b/README.md @@ -0,0 +1,102 @@ +--- +pretty_name: Science Speedrun Astra research artifacts +tags: +- scientific-research +- agent-evaluation +- research-artifacts +--- + +# Science Speedrun: 11 completed Astra task histories + +Reproducible submitted solutions, native evaluation reports, and screened Codex logs from +GPT-6 Astra with xhigh reasoning. These are file artifacts, not a tabular training dataset. +The eleven histories contain 194 inference-distinct candidates; each has a completed +sealed evaluation. Existing additional measurements of duplicate packages are retained. + +| Task | Distinct candidates | Artifacts | +|---|---:|---| +| atomistic-materials | 3 | [Files](tasks/atomistic-materials/atomistic-materials-astra-xhigh-1h100-48h-20261020b) | +| earth-observation-pretraining-transfer | 11 | [Files](tasks/earth-observation-pretraining-transfer/earth-astra-xhigh-48h-20261020a) | +| fluid-flow-control | 11 | [Files](tasks/fluid-flow-control/fluid-flow-control-astra-xhigh-1h100-48h-20261022a) | +| fruit-fly-neuron-reconstruction | 7 | [Files](tasks/fruit-fly-neuron-reconstruction/fruit-fly-neuron-reconstruction-astra-xhigh-1h100-48h-20261022a) | +| natural-disease-progression | 13 | [Files](tasks/natural-disease-progression/ndp-astra-xhigh-48h-20261020a) | +| protein-design | 1 | [Files](tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a) | +| protein-sequence-modeling | 58 | [Files](tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a) | +| single-cell-perturbation-prediction | 17 | [Files](tasks/single-cell-perturbation-prediction/single-cell-perturbation-prediction-astra-xhigh-1h100-48h-20261020b) | +| surface-code-decoding | 45 | [Files](tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b) | +| tokamak-magnetic-control | 7 | [Files](tasks/tokamak-magnetic-control/tokamak-astra-xhigh-48h-20261020a) | +| mass-spectrometry-molecule-retrieval | 21 | [Files](tasks/mass-spectrometry-molecule-retrieval/mass-spectrometry-molecule-retrieval-astra-xhigh-1h100-48h-20261020b) | + +## Layout + +`tasks///` contains `submissions/`, `evaluations/`, `logs/`, +`finalization/`, and one `index.json`. The index maps every original snapshot and +research timestamp to its canonical package and actual evaluation, and records file +hashes, executable permissions, source commit, images, resources, and deviations. +`plots/` contains the complete-history figures and their metric/reference CSV files. +`reproduction/files/` preserves the frozen verifier/adapter source files referenced +by each evaluation. Scientific native reports are retained without rewriting scores. + +Disease submissions include their required Python/CUDA runtime. Identical large +weights and bundled dependencies are shared under `shared/package-files/`, as plain +files, so repeated checkpoint contents need only be downloaded once. Small entry-point +files remain browsable in each submission folder. Indexes map stored files back to +their original paths and executable permissions. Reconstruct a package before execution. +From a complete downloaded repository: + +```bash +python restore_submission.py tasks///index.json S001 /path/to/new/submission +``` + +To fetch just one candidate, download its `index.json` and the helper first (keeping +the directory layout), then add `--repo s42chen/sci-run` to the command above. With +`huggingface_hub` installed, the helper downloads only that candidate's missing files. +Use `--revision ` to pin the download to a specific dataset version. + +Use `GRACE_FINAL` for the separate post-budget package. The helper copies files into +a new directory, restores permissions, and checks the exported names/modes/content +fingerprint. It never executes the submitted code. Do not execute submissions merely +to inspect this archive; use the benchmark's isolated evaluation environment. + +## Interpretation and limitations + +All runs used one accessible H100 and 48 hours of charged research time. Eight of +these eleven tasks were run with reduced CPU/RAM/GPU allocations relative to their +pinned eight-GPU task configurations. Tokamak, Disease, and Earth match the original +one-GPU research requests at their recorded source commits. Runs were interrupted +and resumed; preserving the clock does not reproduce uninterrupted computation. +Beaker execution uses documented isolation/resource adaptations and may grant more +RAM than requested. Published baseline lines are reference measurements, not equal- +budget human trials. Missing or incompatible baselines are explicitly omitted. + +Protein Design retained one early submission. Its requested pretrained inference +assets were not mounted, preventing publication of a promising development hybrid. +Its result is included with that setup limitation, not presented as an unrestricted +comparison. `finalization/` is an additional submission-only window of at most five +minutes; it is not backdated into the 48-hour curves. Purple markers denote those +reviewed post-budget results; orange marks denote reused scores for duplicate snapshots. + +## Provenance and excluded material + +Submissions were produced by the evaluated agent; reports by the native scientific +scorers under the recorded adapters; logs by Codex and the harness. Organization, +indexes, plots, and the reconstruction helper were created by the operator. +Logs are screened for credentials, with redaction counts and original/exported hashes +recorded in the indexes. Authentication stores, private test inputs/labels, raw research +workspaces and unsubmitted checkpoints are excluded. Dataset inputs and separately +distributed pretrained dependencies remain at their upstream locations. Existing source +and dependency licenses continue to apply; no blanket relicensing is asserted here. + +Benchmark source: https://github.com/sunnweiwei/science-speedrun + +## Lean export + +Mass Spectrometry packages omit unused research backups and unselected generations. +The selection follows the same reviewed inference footprint used to deduplicate +evaluations. Every retained inference file, mode, and relevant verifier metadata was +checked against the recorded evaluated identity; required notes and adjacent licenses +are also retained. No model code, weights, paths, or scores were rewritten. These +trimmed packages have their own export fingerprint, with the original full-package +fingerprint and evaluated inference identity recorded separately in each index. +Other tasks retain their exact submitted package contents, with identical files shared. +Original full run artifacts remain preserved on the operator's storage. diff --git a/plots/all-task-progression.pdf b/plots/all-task-progression.pdf new file mode 100644 index 0000000000000000000000000000000000000000..3f67ef6e4e62815aab63b113720bd530f7f41995 --- /dev/null +++ b/plots/all-task-progression.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fca25907e2b06b3266d5ecd11edffdfd126115fd1d9e97d4634ddb0a4717738 +size 109557 diff --git a/plots/baseline-references.csv b/plots/baseline-references.csv new file mode 100644 index 0000000000000000000000000000000000000000..8ad4d1346e067dd13cd421fef5e3461b2b19550f --- /dev/null +++ b/plots/baseline-references.csv @@ -0,0 +1,7 @@ +task,metric,value,label,source +tokamak,reward,0.4857142857142857,Shape VC,/weka/oe-adapt-default/stevenc/science-speedrun/tasks/tokamak-magnetic-control/environment/baseline/shape_vc/RESULTS.md +ndp,reward,0.236256716,Temporal GRU,/weka/oe-adapt-default/stevenc/science-speedrun/tasks/natural-disease-progression/environment/baseline/temporal-gru/RESULTS.md +single-cell-perturbation-prediction,reward,0.10315714367910266,Mean delta,/weka/oe-adapt-default/stevenc/science-speedrun/tasks/single-cell-perturbation-prediction/environment/baseline/evaluation_history.jsonl +surface-code-decoding,reward,0.75569,AlphaQubit reproduction,/weka/oe-adapt-default/stevenc/science-speedrun/tasks/surface-code-decoding/environment/baseline/alphaqubit/RESULTS.md +mass-spectrometry-molecule-retrieval,reward,0.4045,GLACIER · 8-seed mean,/weka/oe-adapt-default/stevenc/science-speedrun/tasks/mass-spectrometry-molecule-retrieval/environment/baseline/starter/RESULTS.md +protein-sequence-modeling,reward,0.67345,Starter · 2-seed mean,/weka/oe-adapt-default/stevenc/science-speedrun/tasks/protein-sequence-modeling/environment/baseline/starter/RESULTS.md diff --git a/plots/evaluated-metrics.csv b/plots/evaluated-metrics.csv new file mode 100644 index 0000000000000000000000000000000000000000..db21f2295d8237f947c2986b295dc533cc0333b3 --- /dev/null +++ b/plots/evaluated-metrics.csv @@ -0,0 +1,768 @@ +task,metric,snapshot,research_seconds,value,evaluation_complete,first_distinct_publication,evaluation_key,score_source,phase,score_origin,publication_seconds,publication_review,active_seconds +tokamak,reward,S001,180,0.48484848484848486,True,True,full:74e3ed85279d311f3057ea2e745d4d69dba48dfde3d4f08c210fe9cb62ab7ca2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/tokamak-astra-s001-score-20261023a/results/reward.json,research,measured,0,,180 +tokamak,reward,S002,15608,0.5454545454545454,True,True,full:7e66dd217a86f5686ba6204807aef87087f95acc0cbf04b2ec8ac769692148d6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/tokamak-astra-s002-score-20261023a/results/reward.json,research,measured,0,,15608 +tokamak,reward,S003,15848,0.5454545454545454,True,True,full:7394bfd378c4f03e388ff8f34bb7dc7d4027372a0b1eb0e4d3b7527942d0a2f7,/weka/oe-adapt-default/stevenc/science-speedrun-runs/tokamak-astra-s003-score-20261023a/results/reward.json,research,measured,0,,15848 +tokamak,reward,S004,20230,0.5,True,True,full:9132353369f72ee34cc206b48c3d70e66c6f7133bd1d64b2c762e416a474fc4a,/weka/oe-adapt-default/stevenc/science-speedrun-runs/tokamak-astra-s004-score-20261023a/results/reward.json,research,measured,0,,20230 +tokamak,reward,S005,27435,0.6060606060606061,True,True,full:48d3558d98c5aa2c9573dbe117c1c817dc6af009c697ddaef2c38d55d8778c85,/weka/oe-adapt-default/stevenc/science-speedrun-runs/tokamak-astra-s005-score-20261023a/results/reward.json,research,measured,0,,27435 +tokamak,reward,S006,45632,0.7058823529411765,True,True,full:5c8230df808aabc7c8b5b0209776633306fc7da1290beae06b97b961a6e666d1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/tokamak-astra-s006-score-20261023a/results/reward.json,research,measured,0,,45632 +tokamak,reward,S007,55659,0.696969696969697,True,True,full:628a91391b6a31a9b560ad469f8bc92368e9c52d606d66a6c37ae70df1a3b82f,/weka/oe-adapt-default/stevenc/science-speedrun-runs/tokamak-astra-final-score-20261022a/results/reward.json,research,measured,0,,55659 +tokamak,reward,GRACE_FINAL,172800,0.696969696969697,True,False,full:628a91391b6a31a9b560ad469f8bc92368e9c52d606d66a6c37ae70df1a3b82f,/weka/oe-adapt-default/stevenc/science-speedrun-runs/tokamak-astra-final-score-20261022a/results/reward.json,post_budget_submission,reused,164.0379485039739,/weka/oe-adapt-default/stevenc/science-speedrun-runs/tokamak-astra-finalize-5m-20261025c/publication-review.json,172964.03794850397 +ndp,reward,S001,1395,0.27010652473925245,True,True,full:09271e702d320144251c8db27f5b0c0485cbf5a2741f48e482b0ad9e0ffcec28,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s001-20261023a/score/results/6eeb91fca25547c4b419aa0c7695b359/reward.json,research,measured,0,,1395 +ndp,reward,S002,1978,0.2826483117093603,True,True,full:cacd4c78212da4bd2aafdefe66cb2fbf14d82f2c3074f18666fc65b7e6ba0e5d,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s002-20261023a-retry1/score/results/f512ccb20cab4d4daa26ef0578ba35e9/reward.json,research,measured,0,,1978 +ndp,reward,S003,2271,0.29324134745328156,True,True,full:61da903d4ed41eb6a4b91e5ddcf798368688d984b48a08f5bdb9b3473b68f50c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s003-20261023a/score/results/9a7eab43f7f5413395f9e8d8a9924cce/reward.json,research,measured,0,,2271 +ndp,reward,S004,2802,0.28780345739729374,True,True,full:b0441ff00463f209e8059f647c191753a714d9fb810b80c4c00211a65d390e0b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s004-20261023a/score/results/5fb7ad17d5434271902db8e444899769/reward.json,research,measured,0,,2802 +ndp,reward,S005,5186,0.2959903159171605,True,True,full:6331de7a442b060afd65528a177cb1cce330497d819c25cfe906f7a5e144415e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s005-20261023a/score/results/4964c25ffa96463cb53340c04a2b1a18/reward.json,research,measured,0,,5186 +ndp,reward,S006,6611,0.29634742398840064,True,True,full:c623bc32ecd446558092dfcbc2d87810db5c515de3f5c64b335b736de14be14f,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s006-20261023a/score/results/5b967d9aec19467aaafc0f5d77c67d95/reward.json,research,measured,0,,6611 +ndp,reward,S007,7070,0.29089184653796374,True,True,full:a438a16a02655dc10c9f938434ecf56f2b1e41159a54c25a2425826ea475ed68,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s007-20261023a/score/results/2c2f50c2de3a453495addf6afc87f675/reward.json,research,measured,0,,7070 +ndp,reward,S008,14330,0.29644057071329843,True,True,full:972aaa6e1a6cb1b8ad23032ce3142c3fd92d3bcf3b181e2ecb0ad53cc736b0a4,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s008-20261023a/score/results/f80f053a5f3e464ebe9c114142e0e812/reward.json,research,measured,0,,14330 +ndp,reward,S009,14678,0.29644057071329843,True,True,full:a3dfb3049cd881e4a5481fdcceca3c1cc742b4911baabe3ea388e90fedf09f25,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s009-20261023a/score/results/35bc450ba4904f8394ededd0fe7cc533/reward.json,research,measured,0,,14678 +ndp,reward,S010,16410,0.29855690037258237,True,True,full:c1da3bcd092fde54897195196badad7d51b563ff7cb7d03e383ad967a815940e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s010-20261023a/score/results/42a60143674940aea89b9222c4562db2/reward.json,research,measured,0,,16410 +ndp,reward,S011,17055,0.29855690037258237,True,True,full:d233d9260a2fa2e1a6383753cf84104d595e812fea0606ac3a49e246a72bda0e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s011-20261023a/score/results/17d3ad85d60546f3baf6f80e7946a433/reward.json,research,measured,0,,17055 +ndp,reward,S012,18327,0.2944737045632943,True,True,full:baadb37091cf41101a6ab97017f8517a25780fdd1d0724dfe179554f3aa84788,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-s012-20261023a/score/results/e1efb6f021d5438fa0eda014a549173c/reward.json,research,measured,0,,18327 +ndp,reward,S013,69177,0.2868553424293565,True,True,full:a10c756d80c5276ad7ca458f4e8fbf2e22bc2a77edb6e1a90d55edd3536b9d35,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-20261022a/score/results/9ad0c9fbfdbc4b058677eb4b9678e9b5/reward.json,research,measured,0,,69177 +ndp,reward,GRACE_FINAL,172800,0.2868553424293565,True,False,full:a10c756d80c5276ad7ca458f4e8fbf2e22bc2a77edb6e1a90d55edd3536b9d35,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-adapted-score-20261022a/score/results/9ad0c9fbfdbc4b058677eb4b9678e9b5/reward.json,post_budget_submission,reused,189.96128027001396,/weka/oe-adapt-default/stevenc/science-speedrun-runs/ndp-astra-finalize-5m-20261025a/publication-review.json,172989.96128027 +earth,reward,S001,180,0.3878181004817611,True,True,full:322b96efb44026bc632a7811dec518c8ed08922569a70c992b09d6478a1b7026,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-s001-20261023a/score/results/reward.json,research,measured,0,,180 +earth,reward,S002,1502,0.4539948893760469,True,True,full:6c6a8bff40def49c200290bb03a48a33ded9491c5c3c1c259987a4914141df1c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-s002-20261023a/score/results/reward.json,research,measured,0,,1502 +earth,reward,S003,2342,0.44690984051766747,True,True,full:49c4feafcf055913cc63b7c2758141d95702d8d9e9a67c292b09051ec12bd845,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-s003-20261023a/score/results/reward.json,research,measured,0,,2342 +earth,reward,S004,3844,0.4848954449494664,True,True,payload:0729069f8fa0cba596645cb0f77a28d3d40bd6e166425b1d25d83e18d60b0395,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-s004-20261023a/score/results/reward.json,research,measured,0,,3844 +earth,reward,S005,4745,0.5031690913408543,True,True,payload:afa378c7bc59bd833c9a4201b661968e52fcd2c024396ff8bd9b877aa3e61f22,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-s005-20261023a/score/results/reward.json,research,measured,0,,4745 +earth,reward,S006,6007,0.51155158296519,True,True,full:eb0c20990a2723154fad3ee34d9e0399ebf2d19a722f6f8b31574b1e65b62266,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-s006-20261023a/score/results/reward.json,research,measured,0,,6007 +earth,reward,S007,16934,0.5174552033374165,True,True,full:2cc0e20d8a05c1073d30d42e1f6d24fe04960edf35af17de281e93cf6b4d78bd,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-s007-20261023a/score/results/reward.json,research,measured,0,,16934 +earth,reward,S008,31461,0.5173130545578705,True,True,full:ecbfcb62fefef0136a9c4f369abb601b1caffdf2265a5118dfb863b6086f224e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-s008-20261023a/score/results/reward.json,research,measured,0,,31461 +earth,reward,S009,48577,0.5278152913720626,True,True,full:dde6cfd13b1c7897bf870313e35d064588b925a0f8663fa8305174d041625a34,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-s009-20261023a/score/results/reward.json,research,measured,0,,48577 +earth,reward,S010,68936,0.5301956429431774,True,True,full:78fe76b1819163b443576f927637c133f207f44033e7184f60302679952f0ca4,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-s010-20261023a/score/results/reward.json,research,measured,0,,68936 +earth,reward,S011,143437,0.5276768706915618,True,True,full:dee0567fa0438507f38175e9fc0150fe8e06de85054a0c9f566a79f0dd7bd9e2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-20261022a/score/results/reward.json,research,measured,0,,143437 +earth,reward,GRACE_FINAL,172800,0.5276768706915618,True,False,full:dee0567fa0438507f38175e9fc0150fe8e06de85054a0c9f566a79f0dd7bd9e2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-adapted-score-20261022a/score/results/reward.json,post_budget_submission,reused,67.38806333299726,/weka/oe-adapt-default/stevenc/science-speedrun-runs/earth-astra-finalize-5m-20261025a/publication-review.json,172867.388063333 +atomistic-materials,reward,S001,722,0.10124752628164557,True,True,reviewed-inference-v1:838c0bf8cd40e3fef2459c33646c7a161c70e3f9d6bbc1f2d7b010be87cebe41,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s001-20261024c/score/results/reward.json,research,measured,0,,722 +atomistic-materials,reward,S002,1983,0.10100719671277757,True,False,reviewed-inference-v1:838c0bf8cd40e3fef2459c33646c7a161c70e3f9d6bbc1f2d7b010be87cebe41,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s002-20261024c/score/results/reward.json,research,measured,0,,1983 +atomistic-materials,reward,S003,2043,0.10124752628164557,True,False,reviewed-inference-v1:838c0bf8cd40e3fef2459c33646c7a161c70e3f9d6bbc1f2d7b010be87cebe41,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s001-20261024c/score/results/reward.json,research,reused,0,,2043 +atomistic-materials,reward,S004,13271,0.22770194957009973,True,True,reviewed-inference-v1:433117deb3a3bec3a8204f3b42d847a9115cbf5f5e9cb9913aa6aca8f7935bcb,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s004-20261024c/score/results/reward.json,research,measured,0,,13271 +atomistic-materials,reward,S005,18675,0.22770194957009973,True,False,reviewed-inference-v1:433117deb3a3bec3a8204f3b42d847a9115cbf5f5e9cb9913aa6aca8f7935bcb,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s004-20261024c/score/results/reward.json,research,reused,0,,18675 +atomistic-materials,reward,S006,22937,0.22770194957009973,True,False,reviewed-inference-v1:433117deb3a3bec3a8204f3b42d847a9115cbf5f5e9cb9913aa6aca8f7935bcb,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s004-20261024c/score/results/reward.json,research,reused,0,,22937 +atomistic-materials,reward,S007,33023,0.22770194957009973,True,False,reviewed-inference-v1:433117deb3a3bec3a8204f3b42d847a9115cbf5f5e9cb9913aa6aca8f7935bcb,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s004-20261024c/score/results/reward.json,research,reused,0,,33023 +atomistic-materials,reward,S008,47404,0.3090580232058038,True,True,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,47404 +atomistic-materials,reward,S009,48605,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,48605 +atomistic-materials,reward,S010,49686,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,49686 +atomistic-materials,reward,S011,51067,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,51067 +atomistic-materials,reward,S012,52747,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,52747 +atomistic-materials,reward,S013,60971,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,60971 +atomistic-materials,reward,S014,61091,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,61091 +atomistic-materials,reward,S015,71836,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,71836 +atomistic-materials,reward,S016,73757,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,73757 +atomistic-materials,reward,S017,77899,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,77899 +atomistic-materials,reward,S018,78019,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,78019 +atomistic-materials,reward,S019,82160,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,82160 +atomistic-materials,reward,S020,105873,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,105873 +atomistic-materials,reward,S021,106354,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,106354 +atomistic-materials,reward,S022,142694,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,reused,0,,142694 +atomistic-materials,reward,S023,149340,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,research,measured,0,,149340 +atomistic-materials,reward,GRACE_FINAL,172800,0.3090580232058038,True,False,reviewed-inference-v1:356f659708739a70adb960ce4f56282a44e91bf528e64c5c50bc480eed96d68b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-native-eval-s023-20261024c/score/results/reward.json,post_budget_submission,reused,121.11095505300909,/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-finalize-5m-20261025a/publication-review.json,172921.110955053 +single-cell-perturbation-prediction,reward,S001,60,2.2110637921835562e-18,True,True,full:e35754514dd96a04a00c1b2ccf4909ef85e452a993bc65c318ba80eb863ab836,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s001-20261024a/score/results/reward.json,research,measured,0,,60 +single-cell-perturbation-prediction,reward,S002,305,0.10222838274873321,True,True,full:03f001a5970b1fdd22c00d6563e9287db88f28df00626f177d7cc2d224fb9e99,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s002-20261024a/score/results/reward.json,research,measured,0,,305 +single-cell-perturbation-prediction,reward,S003,1145,0.12932478858213822,True,True,full:e3024816730d84b056709095fe784a2173df8ff5dc13ca5ea036c96bef05d4d2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s003-20261024a/score/results/reward.json,research,measured,0,,1145 +single-cell-perturbation-prediction,reward,S004,2226,0.12974472547535185,True,True,full:620d1a70f0971e47235d9eccb009630ba9245b393be7a55c0d44e0455f3e1446,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s004-20261024a/score/results/reward.json,research,measured,0,,2226 +single-cell-perturbation-prediction,reward,S005,4688,0.13105978353059652,True,True,full:d2f75cbe1a7a406e9e0802b2912a5b6743e078960eca4de4fce808a55751aa97,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s005-20261024a/score/results/reward.json,research,measured,0,,4688 +single-cell-perturbation-prediction,reward,S006,6910,0.15298305738663745,True,True,full:0f608ae9124076b3d4b7b3c75c8984c023088c0cafc253c86799d87328a32d2a,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s006-20261024a/score/results/reward.json,research,measured,0,,6910 +single-cell-perturbation-prediction,reward,S007,7053,0.13205887791797688,True,True,full:6972c92c2676ec38073109a55bb6066cb37e541ee4e60579832aaa000229791a,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s007-20261024a/score/results/reward.json,research,measured,0,,7053 +single-cell-perturbation-prediction,reward,S008,9875,0.15351434539780265,True,True,full:cb9cfc4b686b731290ec94adc84d03dd26cd4ede0c0a92c28deedcbdab6efe6e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s008-20261024a/score/results/reward.json,research,measured,0,,9875 +single-cell-perturbation-prediction,reward,S009,12636,0.1558850932152854,True,True,full:047596a5ca300f984f97f55d2a675d5269610c83ba324009a9e18d02497dfd3e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s009-20261024a/score/results/reward.json,research,measured,0,,12636 +single-cell-perturbation-prediction,reward,S010,16426,0.15648581380276916,True,True,full:c51b01b43a75c7969a02ee7213d0796cc404156688b1f539006aa027f6c0aa40,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s010-20261024a/score/results/reward.json,research,measured,0,,16426 +single-cell-perturbation-prediction,reward,S011,19667,0.15786048076211714,True,True,full:691a6f05280f7008114149734aff77bf7427fa633519711a05c8656a184caf6e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s011-20261024a/score/results/reward.json,research,measured,0,,19667 +single-cell-perturbation-prediction,reward,S012,23989,0.17148033426005074,True,True,full:a0a42c98f23fa7d817f0b09f90abad93102d6e23f39a590ffc97064255cc1d89,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s012-20261024a/score/results/reward.json,research,measured,0,,23989 +single-cell-perturbation-prediction,reward,S013,26211,0.17245308868245632,True,True,full:59088c426460efad0c9ac74b201005c1e63a960c45c6b9edb141fc792f7cc4a0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s013-20261024a/score/results/reward.json,research,measured,0,,26211 +single-cell-perturbation-prediction,reward,S014,31075,0.17245308868245632,True,True,full:c8f7cdba8b5afbe016193d68dc6fe28f1e97891c86274863653c1d323f343ffe,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s014-20261024a/score/results/reward.json,research,measured,0,,31075 +single-cell-perturbation-prediction,reward,S015,34988,0.17449742995304549,True,True,full:f47e7059a12b02869996be74bfce429139dbed950d92cb01398a8dc04f60e0a8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s015-20261024a/score/results/reward.json,research,measured,0,,34988 +single-cell-perturbation-prediction,reward,S016,44895,0.1970856602298865,True,True,full:6ecdebd0bc1fd5082691790278b331db6bb262691d61469402023bb1a6732be6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s016-20261024a/score/results/reward.json,research,measured,0,,44895 +single-cell-perturbation-prediction,reward,S017,48619,0.2039217974173724,True,True,payload:9ac44f0ff3d75af17eaaba7cb853fafaf11366aa0d8a8c49e6c62cb63ac607fd,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-s017-20261024a/score/results/reward.json,research,measured,0,,48619 +single-cell-perturbation-prediction,reward,S018,48795,0.2039217974173724,True,False,payload:9ac44f0ff3d75af17eaaba7cb853fafaf11366aa0d8a8c49e6c62cb63ac607fd,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-20261023c/score/results/reward.json,research,measured,0,,48795 +single-cell-perturbation-prediction,reward,GRACE_FINAL,172800,0.2039217974173724,True,False,payload:9ac44f0ff3d75af17eaaba7cb853fafaf11366aa0d8a8c49e6c62cb63ac607fd,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-native-eval-20261023c/score/results/reward.json,post_budget_submission,reused,249.47950981400209,/weka/oe-adapt-default/stevenc/science-speedrun-runs/single-cell-perturbation-prediction-astra-finalize-5m-20261025a/publication-review.json,173049.479509814 +surface-code-decoding,reward,S001,180,0.7404840384615384,True,True,reviewed-inference-v1:4debade469a0c2118d2a059b76f54848a6388ce0ca5fe4f415d61d64a0ace02f,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s001-20261024e/score/results/reward.json,research,measured,0,,180 +surface-code-decoding,reward,S002,541,0.7490600000000001,True,True,reviewed-inference-v1:482cd4426e3d2ff5814e2f39fd40136858b51cf38af54f9cfc93f65df6c58302,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s002-20261024e/score/results/reward.json,research,measured,0,,541 +surface-code-decoding,reward,S003,1382,0.76052,True,True,reviewed-inference-v1:9dd0feb5a0e4d9fe4f2dd756d5bf270bc616f92bd5d2bf93c297119876587241,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s003-20261024e/score/results/reward.json,research,measured,0,,1382 +surface-code-decoding,reward,S004,2104,0.7612282692307692,True,True,reviewed-inference-v1:501388598967754b031f635796a5af07760959bbef831daee6a4a5c101c1bb3d,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s004-20261024e/score/results/reward.json,research,measured,0,,2104 +surface-code-decoding,reward,S005,2464,0.7614763461538461,True,True,reviewed-inference-v1:9a8b99607b76024e51f1d997074d7def2b6b14a40e36a5c243162ca8e5603c49,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s005-20261024e/score/results/reward.json,research,measured,0,,2464 +surface-code-decoding,reward,S006,3244,0.7622503846153846,True,True,reviewed-inference-v1:33951b3a2d2f935d860ca0dcb91e4ba2f3b35be11079f7d5971169f684fd41e6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s006-20261024e/score/results/reward.json,research,measured,0,,3244 +surface-code-decoding,reward,S007,3965,0.7622434615384616,True,True,reviewed-inference-v1:cdc95a0b4509a73ff9492aa92846d10cebfdaaa6bc0152e16ed169cbe423156b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s007-20261024e/score/results/reward.json,research,measured,0,,3965 +surface-code-decoding,reward,S008,5166,0.7640157692307692,True,True,reviewed-inference-v1:1e0e0170f4be11831730e4e7ea6189f23b78ae8a2007dab950dab23591c45caf,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s008-20261024e/score/results/reward.json,research,measured,0,,5166 +surface-code-decoding,reward,S009,6127,0.7644334615384616,True,True,reviewed-inference-v1:2791b0debd7fbb1e134d0ced4c270e3445930a03d4bac74aeb6a62968f889c72,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s009-20261024e/score/results/reward.json,research,measured,0,,6127 +surface-code-decoding,reward,S010,7809,0.7649919230769231,True,True,reviewed-inference-v1:ce48e9781abc68a452635bec8333c740bc545df05b8564fe980f71e5ab746255,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s010-20261024e/score/results/reward.json,research,measured,0,,7809 +surface-code-decoding,reward,S011,8891,0.7651950000000001,True,True,reviewed-inference-v1:9d6ed8a9fcd79a255b5c164368880a98850a3920bf343a184b7b600b1c2d3201,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s011-20261024e/score/results/reward.json,research,measured,0,,8891 +surface-code-decoding,reward,S012,11773,0.765665,True,True,reviewed-inference-v1:5a6746d3e7b16bfb6d7c78b986110b23b5029cec41fc7f3f8b32907583c7b5c6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s012-20261024e/score/results/reward.json,research,measured,0,,11773 +surface-code-decoding,reward,S013,12434,0.7655980769230769,True,True,reviewed-inference-v1:548089a083f7f3d0614943817f67ed74632ed5940ea8c110f7b4e6266b4737b7,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s013-20261024e/score/results/reward.json,research,measured,0,,12434 +surface-code-decoding,reward,S014,13455,0.7655940384615385,True,True,reviewed-inference-v1:697d5c5557f7bae1327ac6796273302f44755a06215f3d131a3a08ba667b97cc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s014-20261024e/score/results/reward.json,research,measured,0,,13455 +surface-code-decoding,reward,S015,15858,0.7657261538461538,True,True,reviewed-inference-v1:daa96668ed43f03533355d7a1fce861bb6d7e95a13a9543ddc8aa87cefe401ce,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s015-20261024e/score/results/reward.json,research,measured,0,,15858 +surface-code-decoding,reward,S016,16097,0.7657609615384615,True,True,reviewed-inference-v1:c713f0148e8f1330f510a347276ba97bc9fc11867628b9be2a5740681a77372d,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s016-20261024e/score/results/reward.json,research,measured,0,,16097 +surface-code-decoding,reward,S017,16158,0.765758076923077,True,True,reviewed-inference-v1:702ca8771671ab43a2a58f87f026430ce721f857007e3680be77f88b184845e7,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s017-20261024e/score/results/reward.json,research,measured,0,,16158 +surface-code-decoding,reward,S018,19879,0.7656865384615384,True,True,reviewed-inference-v1:91feac628bcf0b35e3ff079a75c3b199a67ca4bd01d6e735d7242e8bc58f681a,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s018-20261024e/score/results/reward.json,research,measured,0,,19879 +surface-code-decoding,reward,S019,20360,0.7659542307692307,True,True,reviewed-inference-v1:454eac0edfbf677ef9e5b45bedb5fa23fa509f87620e14fe666053c1163853bb,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s019-20261024e/score/results/reward.json,research,measured,0,,20360 +surface-code-decoding,reward,S020,23541,0.7659657692307692,True,True,reviewed-inference-v1:ad528e6fabcec4452f4d9cf89a24ff69a0afd33bf586273f9caf88cbdf67c54b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s020-20261024e/score/results/reward.json,research,measured,0,,23541 +surface-code-decoding,reward,S021,24802,0.76596,True,True,reviewed-inference-v1:30c5427ec7121611f2219be04d3dce34f944a1aacb7ea0270e72e98cfe9d13ba,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s021-20261024e/score/results/reward.json,research,measured,0,,24802 +surface-code-decoding,reward,S022,27083,0.7659657692307692,True,True,reviewed-inference-v1:3382738536b634f5d6bfc73963d3c8916579ff4313b1ad5e7d4dbd3905961e23,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s022-20261024e/score/results/reward.json,research,measured,0,,27083 +surface-code-decoding,reward,S023,31588,0.765755,True,True,reviewed-inference-v1:fbe7e9c8c28ee050f1623a12241d0a02e6dacf75cb0002fde5e20fb940f5aec8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s023-20261024e/score/results/reward.json,research,measured,0,,31588 +surface-code-decoding,reward,S024,31947,0.7658503846153846,True,True,reviewed-inference-v1:2f048a1a66a0e55c7e5ff85b2812ff9ff33b816357da70ee587d22699bd6efd2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s024-20261024e/score/results/reward.json,research,measured,0,,31947 +surface-code-decoding,reward,S025,33929,0.7657634615384615,True,True,reviewed-inference-v1:666500b1a6922369e76010dc94048069e7a86b1a6f057640ff55e82e0e15f9b2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s025-20261024e/score/results/reward.json,research,measured,0,,33929 +surface-code-decoding,reward,S026,34289,0.7659188461538462,True,True,reviewed-inference-v1:cfe94499f8eb6eae7b51bf2ce37da96e1b9322412c0badabb8480ae9beb76bee,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s026-20261024e/score/results/reward.json,research,measured,0,,34289 +surface-code-decoding,reward,S027,34807,0.7658519230769231,True,True,reviewed-inference-v1:46a8e2c6efa2b98d62a928b8fb1d79343c93260422bdfc1ba202ed31e11b0c29,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s027-20261024e/score/results/reward.json,research,measured,0,,34807 +surface-code-decoding,reward,S028,37449,0.7658884615384616,True,True,reviewed-inference-v1:e76c44a8a0e5b26a3f07e3f3e950ea727b2fc16a985dcbaba759846b9f1a2be3,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s028-20261024e/score/results/reward.json,research,measured,0,,37449 +surface-code-decoding,reward,S029,40870,0.7658892307692308,True,True,reviewed-inference-v1:45cc3284049de76d4375785795dccc351964cfd03943569b4d0a1442bb880c21,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s029-20261024e/score/results/reward.json,research,measured,0,,40870 +surface-code-decoding,reward,S030,42311,0.7658953846153846,True,True,reviewed-inference-v1:8ce4ed033754ec10977ed8de77f6f28a87f10fa64532d8f44c11cdee0abbad00,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s030-20261024e/score/results/reward.json,research,measured,0,,42311 +surface-code-decoding,reward,S031,43151,0.7658942307692308,True,True,reviewed-inference-v1:c945d461c791044dd0a614ce2bec829a15c1da45d7eb4bc2b26474af1ffa3eda,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s031-20261024e/score/results/reward.json,research,measured,0,,43151 +surface-code-decoding,reward,S032,43932,0.7658188461538462,True,True,reviewed-inference-v1:bb29353ba4d8c8bd05deebcfe96906f1ff3b65ff84ad348683d225b974403916,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s032-20261024e/score/results/reward.json,research,measured,0,,43932 +surface-code-decoding,reward,S033,47413,0.765825,True,True,reviewed-inference-v1:7917bd89c4dec7f928ed8042f96b185899f6fb63d2295cdb697347b1a7ed67ae,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s033-20261024e/score/results/reward.json,research,measured,0,,47413 +surface-code-decoding,reward,S034,51195,0.765978076923077,True,True,reviewed-inference-v1:b7b535d83b670a49db8a287727f6748e9c30957b5e007cc7dbbfec1768d9f208,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s034-20261024e/score/results/reward.json,research,measured,0,,51195 +surface-code-decoding,reward,S035,53056,0.7659792307692308,True,True,reviewed-inference-v1:1cc66866c963008a713afbfd5bd9e5e3c88ac515ead3d59f10bbaf8f84e5beba,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s035-20261024e/score/results/reward.json,research,measured,0,,53056 +surface-code-decoding,reward,S036,60800,0.7659815384615385,True,True,reviewed-inference-v1:40a8468f274fb50113afb611740a6280f5c45d2254d1d6b7c9e912ccf5d5cb74,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s036-20261024e/score/results/reward.json,research,measured,0,,60800 +surface-code-decoding,reward,S037,61461,0.7659815384615385,True,False,reviewed-inference-v1:40a8468f274fb50113afb611740a6280f5c45d2254d1d6b7c9e912ccf5d5cb74,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s036-20261024e/score/results/reward.json,research,reused,0,,61461 +surface-code-decoding,reward,S038,63261,0.7659746153846154,True,True,reviewed-inference-v1:716e715bb0afdc5e5770d8139c14cc27e5d7684ae305f852fcc8598d524d9d78,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s038-20261024e/score/results/reward.json,research,measured,0,,63261 +surface-code-decoding,reward,S039,63321,0.7659746153846154,True,False,reviewed-inference-v1:716e715bb0afdc5e5770d8139c14cc27e5d7684ae305f852fcc8598d524d9d78,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s038-20261024e/score/results/reward.json,research,reused,0,,63321 +surface-code-decoding,reward,S040,68003,0.7660053846153846,True,True,reviewed-inference-v1:29c88cd53b637e291ba36aab723b898e0f4fba99cb200d3bc674376c71d5ab23,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s040-20261024e/score/results/reward.json,research,measured,0,,68003 +surface-code-decoding,reward,S041,68544,0.7660053846153846,True,True,reviewed-inference-v1:8456c1edb8021af33c0508dd4ace31247968b6c49b588dd0f15bd796647ae612,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s041-20261024e/score/results/reward.json,research,measured,0,,68544 +surface-code-decoding,reward,S042,70165,0.7659723076923077,True,True,reviewed-inference-v1:43930bb31a0982b0f67af5b93c63a9f29019b1e2ca6c9f60366dea9d6a3b06af,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s042-20261024e/score/results/reward.json,research,measured,0,,70165 +surface-code-decoding,reward,S043,79168,0.7661953846153846,True,True,reviewed-inference-v1:50ffe63da64b9cd6716ab3727bbd6fa1229f6b369696ac76be5601ea0df05346,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s043-20261024e/score/results/reward.json,research,measured,0,,79168 +surface-code-decoding,reward,S044,96907,0.7662096153846154,True,True,reviewed-inference-v1:97479ab4b730e637e6b3381d8f067c6cb9892d4d3c2589640da7d2dd8f1788e1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s044-20261024e/score/results/reward.json,research,measured,0,,96907 +surface-code-decoding,reward,S045,146985,0.7661711538461539,True,True,reviewed-inference-v1:e5dd99e0475f852a7c2f1f4e6c181aaf4d52a246ec542d02ffe27cbaac87f6d8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s045-20261024e/score/results/reward.json,research,measured,0,,146985 +surface-code-decoding,reward,S046,156469,0.7661709615384615,True,True,reviewed-inference-v1:5ad99e75862dd2dcb62b22800114c0456ba2c665b4f09132f5d67e14d4d3c72e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s046-20261024e/score/results/reward.json,research,measured,0,,156469 +surface-code-decoding,reward,S047,157611,0.7661709615384615,True,True,reviewed-inference-v1:da7c673057530384266650dd22c7622bcc9d6b89a0901742f25fc64ee1d68274,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s047-20261024e/score/results/reward.json,research,measured,0,,157611 +surface-code-decoding,reward,GRACE_FINAL,172800,0.7661709615384615,True,False,reviewed-inference-v1:da7c673057530384266650dd22c7622bcc9d6b89a0901742f25fc64ee1d68274,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-native-eval-s047-20261024e/score/results/reward.json,post_budget_submission,reused,74.97239726642147,/weka/oe-adapt-default/stevenc/science-speedrun-runs/surface-code-decoding-astra-finalize-5m-20261025a/publication-review.json,172874.97239726642 +mass-spectrometry-molecule-retrieval,reward,S001,60,0.008999772157666895,True,True,reviewed-inference-v1:a8e8381c7247a5fdb7b4c794b3ffbf0add2eb23a978ddd61b05b14aebf7d87a5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s001-20261024a/score/results/reward.json,research,measured,0,,60 +mass-spectrometry-molecule-retrieval,reward,S002,301,0.008999772157666895,True,False,reviewed-inference-v1:a8e8381c7247a5fdb7b4c794b3ffbf0add2eb23a978ddd61b05b14aebf7d87a5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s002-20261024a/score/results/reward.json,research,measured,0,,301 +mass-spectrometry-molecule-retrieval,reward,S003,782,0.11739576213260423,True,True,reviewed-inference-v1:932846a95413ba038d4afee4b9a3c9d4e8c8485f1d3f95082fe82d2b64cd00ce,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s003-20261024a/score/results/reward.json,research,measured,0,,782 +mass-spectrometry-molecule-retrieval,reward,S004,842,0.11739576213260423,True,False,reviewed-inference-v1:932846a95413ba038d4afee4b9a3c9d4e8c8485f1d3f95082fe82d2b64cd00ce,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s004-20261024a/score/results/reward.json,research,measured,0,,842 +mass-spectrometry-molecule-retrieval,reward,S005,1324,0.27016404647983594,True,True,reviewed-inference-v1:a8571801d0ba56616cefdb7aee8a8544383573b718e656a93d824c982a3816b1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s005-20261024a/score/results/reward.json,research,measured,0,,1324 +mass-spectrometry-molecule-retrieval,reward,S006,2046,0.28708133971291866,True,True,reviewed-inference-v1:f79aef6a0870b645243efabd016c2618c1eb272893f0a9534498665feca946d2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s006-20261024a/score/results/reward.json,research,measured,0,,2046 +mass-spectrometry-molecule-retrieval,reward,S007,2107,0.28708133971291866,True,False,reviewed-inference-v1:f79aef6a0870b645243efabd016c2618c1eb272893f0a9534498665feca946d2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s007-20261024a/score/results/reward.json,research,measured,0,,2107 +mass-spectrometry-molecule-retrieval,reward,S008,2589,0.32393483709273185,True,True,reviewed-inference-v1:5d366f64801e83c70bc65e5c7b03b9d6c2cb844adea03af9894877d72b4af923,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s008-20261024a/score/results/reward.json,research,measured,0,,2589 +mass-spectrometry-molecule-retrieval,reward,S009,2648,0.32393483709273185,True,False,reviewed-inference-v1:5d366f64801e83c70bc65e5c7b03b9d6c2cb844adea03af9894877d72b4af923,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s009-20261024a/score/results/reward.json,research,measured,0,,2648 +mass-spectrometry-molecule-retrieval,reward,S010,2828,0.32393483709273185,True,False,reviewed-inference-v1:5d366f64801e83c70bc65e5c7b03b9d6c2cb844adea03af9894877d72b4af923,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s010-20261024a/score/results/reward.json,research,measured,0,,2828 +mass-spectrometry-molecule-retrieval,reward,S011,2949,0.32393483709273185,True,False,reviewed-inference-v1:5d366f64801e83c70bc65e5c7b03b9d6c2cb844adea03af9894877d72b4af923,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s011-20261024a/score/results/reward.json,research,measured,0,,2949 +mass-spectrometry-molecule-retrieval,reward,S012,3068,0.32393483709273185,True,False,reviewed-inference-v1:5d366f64801e83c70bc65e5c7b03b9d6c2cb844adea03af9894877d72b4af923,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s012-20261024a/score/results/reward.json,research,measured,0,,3068 +mass-spectrometry-molecule-retrieval,reward,S013,3129,0.32393483709273185,True,False,reviewed-inference-v1:5d366f64801e83c70bc65e5c7b03b9d6c2cb844adea03af9894877d72b4af923,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s013-20261024a/score/results/reward.json,research,measured,0,,3129 +mass-spectrometry-molecule-retrieval,reward,S014,3190,0.3791866028708134,True,True,reviewed-inference-v1:61f3a639afab5dd51d1c42c2cb7c1bb10dbaa0bd5462ceae2187b0747fabba57,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s014-20261024a/score/results/reward.json,research,measured,0,,3190 +mass-spectrometry-molecule-retrieval,reward,S015,3250,0.3791866028708134,True,False,reviewed-inference-v1:61f3a639afab5dd51d1c42c2cb7c1bb10dbaa0bd5462ceae2187b0747fabba57,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s015-20261024a/score/results/reward.json,research,measured,0,,3250 +mass-spectrometry-molecule-retrieval,reward,S016,3311,0.3791866028708134,True,False,reviewed-inference-v1:61f3a639afab5dd51d1c42c2cb7c1bb10dbaa0bd5462ceae2187b0747fabba57,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s016-20261024a/score/results/reward.json,research,measured,0,,3311 +mass-spectrometry-molecule-retrieval,reward,S017,3431,0.3791866028708134,True,False,reviewed-inference-v1:61f3a639afab5dd51d1c42c2cb7c1bb10dbaa0bd5462ceae2187b0747fabba57,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s017-20261024a/score/results/reward.json,research,measured,0,,3431 +mass-spectrometry-molecule-retrieval,reward,S018,3490,0.3791866028708134,True,False,reviewed-inference-v1:61f3a639afab5dd51d1c42c2cb7c1bb10dbaa0bd5462ceae2187b0747fabba57,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s018-20261024a/score/results/reward.json,research,measured,0,,3490 +mass-spectrometry-molecule-retrieval,reward,S019,3611,0.3791866028708134,True,False,reviewed-inference-v1:61f3a639afab5dd51d1c42c2cb7c1bb10dbaa0bd5462ceae2187b0747fabba57,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s019-20261024a/score/results/reward.json,research,measured,0,,3611 +mass-spectrometry-molecule-retrieval,reward,S020,3731,0.3791866028708134,True,False,reviewed-inference-v1:61f3a639afab5dd51d1c42c2cb7c1bb10dbaa0bd5462ceae2187b0747fabba57,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s020-20261024a/score/results/reward.json,research,measured,0,,3731 +mass-spectrometry-molecule-retrieval,reward,S021,3975,0.45169742538163593,True,True,reviewed-inference-v1:0d920ba4426d1742c61b2096cfdb580b35f2056cedff16ad28ccf82a50935dd7,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s021-20261024a/score/results/reward.json,research,measured,0,,3975 +mass-spectrometry-molecule-retrieval,reward,S022,4036,0.45169742538163593,True,False,reviewed-inference-v1:0d920ba4426d1742c61b2096cfdb580b35f2056cedff16ad28ccf82a50935dd7,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s022-20261024a/score/results/reward.json,research,measured,0,,4036 +mass-spectrometry-molecule-retrieval,reward,S023,4395,0.45169742538163593,True,False,reviewed-inference-v1:0d920ba4426d1742c61b2096cfdb580b35f2056cedff16ad28ccf82a50935dd7,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s023-20261024a/score/results/reward.json,research,measured,0,,4395 +mass-spectrometry-molecule-retrieval,reward,S024,4934,0.45169742538163593,True,False,reviewed-inference-v1:0d920ba4426d1742c61b2096cfdb580b35f2056cedff16ad28ccf82a50935dd7,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s024-20261024a/score/results/reward.json,research,measured,0,,4934 +mass-spectrometry-molecule-retrieval,reward,S025,5121,0.45431761221234906,True,True,reviewed-inference-v1:94e722842a6cc6f979db16dd2a82ae4fa5e6fca04963d045e728cc4b92a928d1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s025-20261024a/score/results/reward.json,research,measured,0,,5121 +mass-spectrometry-molecule-retrieval,reward,S026,5240,0.45431761221234906,True,False,reviewed-inference-v1:94e722842a6cc6f979db16dd2a82ae4fa5e6fca04963d045e728cc4b92a928d1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s026-20261024a/score/results/reward.json,research,measured,0,,5240 +mass-spectrometry-molecule-retrieval,reward,S027,5480,0.45431761221234906,True,False,reviewed-inference-v1:94e722842a6cc6f979db16dd2a82ae4fa5e6fca04963d045e728cc4b92a928d1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s027-20261024a/score/results/reward.json,research,measured,0,,5480 +mass-spectrometry-molecule-retrieval,reward,S028,5660,0.45431761221234906,True,False,reviewed-inference-v1:94e722842a6cc6f979db16dd2a82ae4fa5e6fca04963d045e728cc4b92a928d1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s028-20261024a/score/results/reward.json,research,measured,0,,5660 +mass-spectrometry-molecule-retrieval,reward,S029,5841,0.45431761221234906,True,False,reviewed-inference-v1:94e722842a6cc6f979db16dd2a82ae4fa5e6fca04963d045e728cc4b92a928d1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s029-20261024a/score/results/reward.json,research,measured,0,,5841 +mass-spectrometry-molecule-retrieval,reward,S030,6020,0.45431761221234906,True,False,reviewed-inference-v1:94e722842a6cc6f979db16dd2a82ae4fa5e6fca04963d045e728cc4b92a928d1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s030-20261024a/score/results/reward.json,research,measured,0,,6020 +mass-spectrometry-molecule-retrieval,reward,S031,6261,0.45431761221234906,True,False,reviewed-inference-v1:94e722842a6cc6f979db16dd2a82ae4fa5e6fca04963d045e728cc4b92a928d1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s031-20261024a/score/results/reward.json,research,measured,0,,6261 +mass-spectrometry-molecule-retrieval,reward,S032,6382,0.45431761221234906,True,False,reviewed-inference-v1:94e722842a6cc6f979db16dd2a82ae4fa5e6fca04963d045e728cc4b92a928d1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s032-20261024a/score/results/reward.json,research,measured,0,,6382 +mass-spectrometry-molecule-retrieval,reward,S033,6564,0.4697539302802461,True,True,reviewed-inference-v1:b2aa2daeb6736268120edf20ddea9f74b721de3dca3bad939bd460ad7aa241c9,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s033-20261024a/score/results/reward.json,research,measured,0,,6564 +mass-spectrometry-molecule-retrieval,reward,S034,6988,0.4697539302802461,True,False,reviewed-inference-v1:b2aa2daeb6736268120edf20ddea9f74b721de3dca3bad939bd460ad7aa241c9,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s034-20261024a/score/results/reward.json,research,measured,0,,6988 +mass-spectrometry-molecule-retrieval,reward,S035,7046,0.4697539302802461,True,False,reviewed-inference-v1:b2aa2daeb6736268120edf20ddea9f74b721de3dca3bad939bd460ad7aa241c9,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s035-20261024a/score/results/reward.json,research,measured,0,,7046 +mass-spectrometry-molecule-retrieval,reward,S036,7707,0.4697539302802461,True,False,reviewed-inference-v1:b2aa2daeb6736268120edf20ddea9f74b721de3dca3bad939bd460ad7aa241c9,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s036-20261024a/score/results/reward.json,research,measured,0,,7707 +mass-spectrometry-molecule-retrieval,reward,S037,7772,0.4697539302802461,True,False,reviewed-inference-v1:b2aa2daeb6736268120edf20ddea9f74b721de3dca3bad939bd460ad7aa241c9,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s037-20261024a/score/results/reward.json,research,measured,0,,7772 +mass-spectrometry-molecule-retrieval,reward,S038,7890,0.4697539302802461,True,False,reviewed-inference-v1:b2aa2daeb6736268120edf20ddea9f74b721de3dca3bad939bd460ad7aa241c9,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s038-20261024a/score/results/reward.json,research,measured,0,,7890 +mass-spectrometry-molecule-retrieval,reward,S039,7948,0.4697539302802461,True,False,reviewed-inference-v1:b2aa2daeb6736268120edf20ddea9f74b721de3dca3bad939bd460ad7aa241c9,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s039-20261024a/score/results/reward.json,research,measured,0,,7948 +mass-spectrometry-molecule-retrieval,reward,S040,8018,0.4630325814536341,True,True,reviewed-inference-v1:513223d3655ee4d6cf24b7b5d32b10f52ea25ff10b9453b5326ea4a4799b03d8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s040-20261024a/score/results/reward.json,research,measured,0,,8018 +mass-spectrometry-molecule-retrieval,reward,S041,8134,0.4630325814536341,True,False,reviewed-inference-v1:513223d3655ee4d6cf24b7b5d32b10f52ea25ff10b9453b5326ea4a4799b03d8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s041-20261024a/score/results/reward.json,research,measured,0,,8134 +mass-spectrometry-molecule-retrieval,reward,S042,8195,0.4630325814536341,True,False,reviewed-inference-v1:513223d3655ee4d6cf24b7b5d32b10f52ea25ff10b9453b5326ea4a4799b03d8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s042-20261024a/score/results/reward.json,research,measured,0,,8195 +mass-spectrometry-molecule-retrieval,reward,S043,8323,0.4630325814536341,True,False,reviewed-inference-v1:513223d3655ee4d6cf24b7b5d32b10f52ea25ff10b9453b5326ea4a4799b03d8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s043-20261024a/score/results/reward.json,research,measured,0,,8323 +mass-spectrometry-molecule-retrieval,reward,S044,8439,0.4630325814536341,True,False,reviewed-inference-v1:513223d3655ee4d6cf24b7b5d32b10f52ea25ff10b9453b5326ea4a4799b03d8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s044-20261024a/score/results/reward.json,research,measured,0,,8439 +mass-spectrometry-molecule-retrieval,reward,S045,8798,0.4630325814536341,True,False,reviewed-inference-v1:513223d3655ee4d6cf24b7b5d32b10f52ea25ff10b9453b5326ea4a4799b03d8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s045-20261024a/score/results/reward.json,research,measured,0,,8798 +mass-spectrometry-molecule-retrieval,reward,S046,8927,0.4931077694235589,True,True,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s046-20261024a/score/results/reward.json,research,measured,0,,8927 +mass-spectrometry-molecule-retrieval,reward,S047,9052,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s047-20261024a/score/results/reward.json,research,measured,0,,9052 +mass-spectrometry-molecule-retrieval,reward,S048,9232,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s048-20261024a/score/results/reward.json,research,measured,0,,9232 +mass-spectrometry-molecule-retrieval,reward,S049,9533,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s049-20261024a/score/results/reward.json,research,measured,0,,9533 +mass-spectrometry-molecule-retrieval,reward,S050,9768,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s050-20261024a/score/results/reward.json,research,measured,0,,9768 +mass-spectrometry-molecule-retrieval,reward,S051,10019,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s051-20261024a/score/results/reward.json,research,measured,0,,10019 +mass-spectrometry-molecule-retrieval,reward,S052,10247,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s052-20261024a/score/results/reward.json,research,measured,0,,10247 +mass-spectrometry-molecule-retrieval,reward,S053,10367,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s053-20261024a/score/results/reward.json,research,measured,0,,10367 +mass-spectrometry-molecule-retrieval,reward,S054,10432,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s054-20261024a/score/results/reward.json,research,measured,0,,10432 +mass-spectrometry-molecule-retrieval,reward,S055,10856,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s055-20261024a/score/results/reward.json,research,measured,0,,10856 +mass-spectrometry-molecule-retrieval,reward,S056,11030,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s056-20261024a/score/results/reward.json,research,measured,0,,11030 +mass-spectrometry-molecule-retrieval,reward,S057,11095,0.4931077694235589,True,False,reviewed-inference-v1:a5055e7c62acf9418b450869c462b7f06dc8efdb65c7a4fd64773c9a5368e1df,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s046-20261024a/score/results/reward.json,research,reused,0,,11095 +mass-spectrometry-molecule-retrieval,reward,S058,11357,0.509170653907496,True,True,reviewed-inference-v1:79cdd481583c61d08a385ce007a3e27d54bc38dec024b09e0f741e523bc81eb5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s058-20261024a/score/results/reward.json,research,measured,0,,11357 +mass-spectrometry-molecule-retrieval,reward,S059,11661,0.509170653907496,True,False,reviewed-inference-v1:79cdd481583c61d08a385ce007a3e27d54bc38dec024b09e0f741e523bc81eb5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s058-20261024a/score/results/reward.json,research,reused,0,,11661 +mass-spectrometry-molecule-retrieval,reward,S060,11783,0.509170653907496,True,False,reviewed-inference-v1:79cdd481583c61d08a385ce007a3e27d54bc38dec024b09e0f741e523bc81eb5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s058-20261024a/score/results/reward.json,research,reused,0,,11783 +mass-spectrometry-molecule-retrieval,reward,S061,11908,0.509170653907496,True,False,reviewed-inference-v1:79cdd481583c61d08a385ce007a3e27d54bc38dec024b09e0f741e523bc81eb5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s058-20261024a/score/results/reward.json,research,reused,0,,11908 +mass-spectrometry-molecule-retrieval,reward,S062,12026,0.509170653907496,True,False,reviewed-inference-v1:79cdd481583c61d08a385ce007a3e27d54bc38dec024b09e0f741e523bc81eb5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s058-20261024a/score/results/reward.json,research,reused,0,,12026 +mass-spectrometry-molecule-retrieval,reward,S063,12089,0.509170653907496,True,False,reviewed-inference-v1:79cdd481583c61d08a385ce007a3e27d54bc38dec024b09e0f741e523bc81eb5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s058-20261024a/score/results/reward.json,research,reused,0,,12089 +mass-spectrometry-molecule-retrieval,reward,S064,12414,0.509170653907496,True,False,reviewed-inference-v1:79cdd481583c61d08a385ce007a3e27d54bc38dec024b09e0f741e523bc81eb5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s058-20261024a/score/results/reward.json,research,reused,0,,12414 +mass-spectrometry-molecule-retrieval,reward,S065,12657,0.509170653907496,True,False,reviewed-inference-v1:79cdd481583c61d08a385ce007a3e27d54bc38dec024b09e0f741e523bc81eb5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s058-20261024a/score/results/reward.json,research,reused,0,,12657 +mass-spectrometry-molecule-retrieval,reward,S066,13072,0.509170653907496,True,False,reviewed-inference-v1:79cdd481583c61d08a385ce007a3e27d54bc38dec024b09e0f741e523bc81eb5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s058-20261024a/score/results/reward.json,research,reused,0,,13072 +mass-spectrometry-molecule-retrieval,reward,S067,13323,0.509170653907496,True,False,reviewed-inference-v1:79cdd481583c61d08a385ce007a3e27d54bc38dec024b09e0f741e523bc81eb5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s058-20261024a/score/results/reward.json,research,reused,0,,13323 +mass-spectrometry-molecule-retrieval,reward,S068,13766,0.5413533834586466,True,True,reviewed-inference-v1:91f55c40f0cc6b04513426592ecd8cad29128bfb04b14f1298eff827dc3dfbc9,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s068-20261024a/score/results/reward.json,research,measured,0,,13766 +mass-spectrometry-molecule-retrieval,reward,S069,14380,0.544771018455229,True,True,reviewed-inference-v1:57f600961f6e4cb153d87ee2fd9f4cf79d0bf6a315d633b7dab931b4999bc3b1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s069-20261024a/score/results/reward.json,research,measured,0,,14380 +mass-spectrometry-molecule-retrieval,reward,S070,15418,0.544771018455229,True,False,reviewed-inference-v1:57f600961f6e4cb153d87ee2fd9f4cf79d0bf6a315d633b7dab931b4999bc3b1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s069-20261024a/score/results/reward.json,research,reused,0,,15418 +mass-spectrometry-molecule-retrieval,reward,S071,15557,0.544771018455229,True,False,reviewed-inference-v1:57f600961f6e4cb153d87ee2fd9f4cf79d0bf6a315d633b7dab931b4999bc3b1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s069-20261024a/score/results/reward.json,research,reused,0,,15557 +mass-spectrometry-molecule-retrieval,reward,S072,16563,0.544771018455229,True,False,reviewed-inference-v1:57f600961f6e4cb153d87ee2fd9f4cf79d0bf6a315d633b7dab931b4999bc3b1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s069-20261024a/score/results/reward.json,research,reused,0,,16563 +mass-spectrometry-molecule-retrieval,reward,S073,17369,0.5451697425381636,True,True,reviewed-inference-v1:587f729cbef3813d4c2e0520b4ca1f5b9d66c4478dedb639cb4ee6f0f76b86a0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s073-20261024a/score/results/reward.json,research,measured,0,,17369 +mass-spectrometry-molecule-retrieval,reward,S074,17855,0.5451697425381636,True,False,reviewed-inference-v1:587f729cbef3813d4c2e0520b4ca1f5b9d66c4478dedb639cb4ee6f0f76b86a0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s073-20261024a/score/results/reward.json,research,reused,0,,17855 +mass-spectrometry-molecule-retrieval,reward,S075,18022,0.5451697425381636,True,False,reviewed-inference-v1:587f729cbef3813d4c2e0520b4ca1f5b9d66c4478dedb639cb4ee6f0f76b86a0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s073-20261024a/score/results/reward.json,research,reused,0,,18022 +mass-spectrometry-molecule-retrieval,reward,S076,18235,0.5451697425381636,True,False,reviewed-inference-v1:587f729cbef3813d4c2e0520b4ca1f5b9d66c4478dedb639cb4ee6f0f76b86a0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s073-20261024a/score/results/reward.json,research,reused,0,,18235 +mass-spectrometry-molecule-retrieval,reward,S077,18846,0.5451697425381636,True,False,reviewed-inference-v1:587f729cbef3813d4c2e0520b4ca1f5b9d66c4478dedb639cb4ee6f0f76b86a0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s073-20261024a/score/results/reward.json,research,reused,0,,18846 +mass-spectrometry-molecule-retrieval,reward,S078,19482,0.5451697425381636,True,False,reviewed-inference-v1:587f729cbef3813d4c2e0520b4ca1f5b9d66c4478dedb639cb4ee6f0f76b86a0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s073-20261024a/score/results/reward.json,research,reused,0,,19482 +mass-spectrometry-molecule-retrieval,reward,S079,22029,0.5455684666210981,True,True,reviewed-inference-v1:f0cd05f45cd140a0db789a6220013eb6b8c62b9bae7c4fe0fce251160056810f,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s079-20261024a/score/results/reward.json,research,measured,0,,22029 +mass-spectrometry-molecule-retrieval,reward,S080,27631,0.5604921394395078,True,True,reviewed-inference-v1:fe9d93f7881973370e6814da0864493c8fdd57f870583add6acfccfe67ebb174,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s080-20261024a-setup-retry1/score/results/reward.json,research,measured,0,,27631 +mass-spectrometry-molecule-retrieval,reward,S081,96921,0.6226930963773069,True,True,reviewed-inference-v1:50989bc75ff41e33c792eaa2dbe644788672c569f59fc2d25169fd0b76918416,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s081-20261024a/score/results/reward.json,research,measured,0,,96921 +mass-spectrometry-molecule-retrieval,reward,S082,101008,0.6251424014581909,True,True,reviewed-inference-v1:d672b4861a7284c65fb9bbc7eafdfa3ac5eb7db7bcdd584008eda155a5e6e298,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s082-20261024a/score/results/reward.json,research,measured,0,,101008 +mass-spectrometry-molecule-retrieval,reward,S083,154313,0.6453634085213033,True,True,reviewed-inference-v1:c4366b6e1d77ef8d3944decfcebf488a0ae32247e9a45d2056545774fd93fd76,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s083-20261024a/score/results/reward.json,research,measured,0,,154313 +mass-spectrometry-molecule-retrieval,reward,S084,156100,0.6453634085213033,True,False,reviewed-inference-v1:c4366b6e1d77ef8d3944decfcebf488a0ae32247e9a45d2056545774fd93fd76,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-s083-20261024a/score/results/reward.json,research,reused,0,,156100 +mass-spectrometry-molecule-retrieval,reward,S085,172800,0.6450786056049214,True,True,reviewed-inference-v1:dc34f2d686599b67713fae934ee806144d39d6de94aa003fe0645fad86deb89d,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-20261023a/score/results/reward.json,research,measured,0,,172800 +mass-spectrometry-molecule-retrieval,reward,GRACE_FINAL,172800,0.6450786056049214,True,False,reviewed-inference-v1:dc34f2d686599b67713fae934ee806144d39d6de94aa003fe0645fad86deb89d,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-native-eval-20261023a/score/results/reward.json,post_budget_submission,reused,153.71884386613965,/weka/oe-adapt-default/stevenc/science-speedrun-runs/mass-spectrometry-molecule-retrieval-astra-finalize-5m-20261025a/publication-review.json,172953.71884386614 +fruit-fly-neuron-reconstruction,reward,S001,120,0.0,True,True,reviewed-inference-v1:36e14997392854018a59e419fa9bdaef569bb3ea62904e503197bfecee4ff686,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fruit-fly-neuron-reconstruction-astra-native-eval-s001-20261025a/inference/results/reward.json,research,measured,0,,120 +fruit-fly-neuron-reconstruction,reward,S002,2221,0.0008803824604714739,True,True,reviewed-inference-v1:c0b18635d9bdbd5c4cbb6f6fd7ed665b0789e71ce36cd37eaf1afa5e9d068690,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fruit-fly-neuron-reconstruction-astra-native-eval-s002-20261025a/inference/results/reward.json,research,measured,0,,2221 +fruit-fly-neuron-reconstruction,reward,S003,2761,0.000904967729445383,True,True,reviewed-inference-v1:c0e8057ca51cb53180b7d872ad0008955680afbb94d665fc247151886535fa19,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fruit-fly-neuron-reconstruction-astra-native-eval-s003-20261025a/inference/results/reward.json,research,measured,0,,2761 +fruit-fly-neuron-reconstruction,reward,S004,7683,0.0006582038613306252,True,True,reviewed-inference-v1:ec08c5e65e2b4fc4748417b687e1ec49372ba95ffa47762dfd90fc8c5735035b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fruit-fly-neuron-reconstruction-astra-native-eval-s004-20261025a/inference/results/reward.json,research,measured,0,,7683 +fruit-fly-neuron-reconstruction,reward,S005,77392,0.0004283089346972766,True,True,reviewed-inference-v1:1b3d07af915341cde67d7625b76f92cf6da7ad9cf3c1771499272477b02d220c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fruit-fly-neuron-reconstruction-astra-native-eval-s005-20261025a/inference/results/reward.json,research,measured,0,,77392 +fruit-fly-neuron-reconstruction,reward,S006,118218,0.0008661713603639959,True,True,reviewed-inference-v1:accbd07e04604130c241eb851e2ba0d8b3b568bae136192fd97b38c42de15265,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fruit-fly-neuron-reconstruction-astra-native-eval-s006-20261025a/inference/results/reward.json,research,measured,0,,118218 +fruit-fly-neuron-reconstruction,reward,S007,164218,0.0008073378477076369,True,True,reviewed-inference-v1:8ff217ca48eb1154ec5b408f64f0795b52f3fc3cbfdd514b7044e010f824ecdb,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fruit-fly-neuron-reconstruction-astra-native-eval-s007-20261025a/inference/results/reward.json,research,measured,0,,164218 +fruit-fly-neuron-reconstruction,reward,GRACE_FINAL,172800,0.0008073378477076369,True,False,reviewed-inference-v1:8ff217ca48eb1154ec5b408f64f0795b52f3fc3cbfdd514b7044e010f824ecdb,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fruit-fly-neuron-reconstruction-astra-native-eval-s007-20261025a/inference/results/reward.json,post_budget_submission,reused,112.51380108302692,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fruit-fly-neuron-reconstruction-astra-finalize-5m-20261025b/publication-review.json,172912.51380108303 +protein-sequence-modeling,reward,S001,540,0.48100178643133007,True,True,reviewed-inference-v1:2eb06fb88a39f1f71a612baffcf0374aa7e791801a9da3f93aec4b4aa700236a,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s001-20261025e-public-input-retry-20261026b/score/results/reward.json,research,measured,0,,540 +protein-sequence-modeling,reward,S002,600,0.4813773796609761,True,True,reviewed-inference-v1:95fd880a5a102af5638560aac8ab70a68915e3e75aa904360f402541d6297289,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s002-20261025e/score/results/reward.json,research,measured,0,,600 +protein-sequence-modeling,reward,S003,840,0.5416631596060237,True,True,reviewed-inference-v1:dc458f526dafc6a75fbe836d5d8b9136ceff68e4d00514926d9d483adce21d18,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s003-20261025e/score/results/reward.json,research,measured,0,,840 +protein-sequence-modeling,reward,S004,1680,0.5674829802300076,True,True,reviewed-inference-v1:e33be97d4a1f4e4cd32664741da536bc7d1c26917b6280deaad927ed6a3f3ccb,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s004-20261025e/score/results/reward.json,research,measured,0,,1680 +protein-sequence-modeling,reward,S005,3421,0.5924642429644144,True,True,reviewed-inference-v1:e65af1d744318e32874aec82cbf51d1e32a9ceba4909116011dccab1671ac6cd,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s005-20261025e/score/results/reward.json,research,measured,0,,3421 +protein-sequence-modeling,reward,S006,3961,0.5980046481841328,True,True,reviewed-inference-v1:adb8aa69b56431a1805d542094bf07f46e8602f8e2cd6d1aa249c3a44927cc55,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s006-20261025e/score/results/reward.json,research,measured,0,,3961 +protein-sequence-modeling,reward,S007,4682,0.6250680736367934,True,True,reviewed-inference-v1:105e8b39769c80578daaf638913be995165b294ec846862cdaad352f6be2dc39,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s007-20261025e/score/results/reward.json,research,measured,0,,4682 +protein-sequence-modeling,reward,S008,4982,0.6355539894548847,True,True,reviewed-inference-v1:7d90defde5a3928a20c00258ee9ea720c5910f46dde746d3e1235861c16dc515,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s008-20261025e/score/results/reward.json,research,measured,0,,4982 +protein-sequence-modeling,reward,S009,5222,0.6351741464566573,True,True,reviewed-inference-v1:3be2d67ecbb41aa3142949d8a0658a3922c4a5b4c2c426ef0305e0acb2991ffc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s009-20261025e/score/results/reward.json,research,measured,0,,5222 +protein-sequence-modeling,reward,S010,5342,0.6352981094790267,True,True,reviewed-inference-v1:d1185d0fe3f7bd00450cf8f5c922bdfa193077772bae08170db70456247e9f26,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s010-20261025e/score/results/reward.json,research,measured,0,,5342 +protein-sequence-modeling,reward,S011,5462,0.6352485122428861,True,True,reviewed-inference-v1:cdb52d7fb82b1fc0b1ede4791012b034cc4f58236f3a755c7f2b25ff6ee8870c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s011-20261025e/score/results/reward.json,research,measured,0,,5462 +protein-sequence-modeling,reward,S012,5702,0.6396471726343704,True,True,reviewed-inference-v1:89548b76c6f7053bc93f3e49c5da440278cacf9451bedc0dfa6bb3f34e07f988,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s012-20261025e/score/results/reward.json,research,measured,0,,5702 +protein-sequence-modeling,reward,S013,5762,0.6396471726343704,True,False,reviewed-inference-v1:89548b76c6f7053bc93f3e49c5da440278cacf9451bedc0dfa6bb3f34e07f988,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s012-20261025e/score/results/reward.json,research,reused,0,,5762 +protein-sequence-modeling,reward,S014,6122,0.6392635899723067,True,True,reviewed-inference-v1:de22014f187a8f04e9b98ccb2b158a68726e9e923a0954cf7bc50fd9a2a8b2e1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s014-20261025e/score/results/reward.json,research,measured,0,,6122 +protein-sequence-modeling,reward,S015,7804,0.6545967210124091,True,True,reviewed-inference-v1:9acac7fb1f1b75d2f9190daab038b2872159a3535551416aedad8fc946baa5b5,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s015-20261025e/score/results/reward.json,research,measured,0,,7804 +protein-sequence-modeling,reward,S016,8164,0.6576379677246504,True,True,reviewed-inference-v1:b617aa3e4fbdadb09de7ba6061b8578c443fbb07b130ace63301eb8fedb97167,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s016-20261025e/score/results/reward.json,research,measured,0,,8164 +protein-sequence-modeling,reward,S017,8644,0.6643052829703056,True,True,reviewed-inference-v1:27fea1650cf95d39a6849f7950249dd15a4f988828d3102d78a8e42743ed9dd1,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s017-20261025e/score/results/reward.json,research,measured,0,,8644 +protein-sequence-modeling,reward,S018,9123,0.6631516143039466,True,True,reviewed-inference-v1:024795e1fac094ccc4bcd8f68194d9bece8688223de599c697d9ee62c69dd953,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s018-20261025e/score/results/reward.json,research,measured,0,,9123 +protein-sequence-modeling,reward,S019,9424,0.663352078284409,True,True,reviewed-inference-v1:2bbf1da846b6242c3a0228c57bc28e76386f02e76a822d7f07633cd5dd240002,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s019-20261025e/score/results/reward.json,research,measured,0,,9424 +protein-sequence-modeling,reward,S020,9543,0.6638263715873876,True,True,reviewed-inference-v1:3ff5d2ab81125297a7ad14a73c57c55d503d3855d79538e35d5ff63ba6ee07d0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s020-20261025e/score/results/reward.json,research,measured,0,,9543 +protein-sequence-modeling,reward,S021,9783,0.6621032416882705,True,True,reviewed-inference-v1:3cd11e5f5ca64c1379fe4ebaa658a1fa508f9f7d711c1896eb7ed2c1bd4036ef,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s021-20261025e/score/results/reward.json,research,measured,0,,9783 +protein-sequence-modeling,reward,S022,10384,0.6606109525373466,True,True,reviewed-inference-v1:3ef3427dfa576300f5f3e1d17d3a8804f32fce39f185465fb5a57b64cd68cba0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s022-20261025e/score/results/reward.json,research,measured,0,,10384 +protein-sequence-modeling,reward,S023,10564,0.6609417657109631,True,True,reviewed-inference-v1:acf82eaf22ba72cd49325ffd5c2d0312fb130bfbb81e235c0ba661e98ba85aac,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s023-20261025e/score/results/reward.json,research,measured,0,,10564 +protein-sequence-modeling,reward,S024,10924,0.6611774036971063,True,True,reviewed-inference-v1:bfea55ecc24fb1265297375b95404892c6c6e0f0ae4db40303dd832156332392,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s024-20261025e/score/results/reward.json,research,measured,0,,10924 +protein-sequence-modeling,reward,S025,11644,0.6609701741621082,True,True,reviewed-inference-v1:a3d89eeefe774c470055f1302267c8cc2b0de9cd65c5e63c0a1fe91c63e19d42,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s025-20261025e/score/results/reward.json,research,measured,0,,11644 +protein-sequence-modeling,reward,S026,11824,0.6610922596172364,True,True,reviewed-inference-v1:ff3ccab4c4679af02e2c027b7745c61753c1ab68319bfc1d055c811563f4f17c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s026-20261025e/score/results/reward.json,research,measured,0,,11824 +protein-sequence-modeling,reward,S027,12064,0.6615925097422989,True,True,reviewed-inference-v1:31b4f7445ae627836faa6537ebda9e66a5634a40913a71374fd0250eb12d2bc7,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s027-20261025e/score/results/reward.json,research,measured,0,,12064 +protein-sequence-modeling,reward,S028,12184,0.6615860421063492,True,True,reviewed-inference-v1:747cad96272eaa7c0f3310eb4e3cdddafa75861edf71f6cdab371f05187871a0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s028-20261025e/score/results/reward.json,research,measured,0,,12184 +protein-sequence-modeling,reward,S029,12389,0.6614221238032315,True,True,reviewed-inference-v1:7f6dbadbe011c202c8180a0ab96a951a16b403a0f5befd431ee214d27da44f9e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s029-20261025e/score/results/reward.json,research,measured,0,,12389 +protein-sequence-modeling,reward,S030,12689,0.6618019668014589,True,True,reviewed-inference-v1:45b5472699cf757a65e90e776776e1e40022243daea5e53b6d13593afaaae8f7,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s030-20261025e/score/results/reward.json,research,measured,0,,12689 +protein-sequence-modeling,reward,S031,13230,0.6617685506823855,True,True,reviewed-inference-v1:cdf48e43ccedc5a7fccf484eea7f5bf2d5f9208ece20aa330f2057ff37eaa9ee,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s031-20261025e/score/results/reward.json,research,measured,0,,13230 +protein-sequence-modeling,reward,S032,17086,0.6623390819392939,True,True,reviewed-inference-v1:caed1422fc4c143fd967c6e0695d91156c9bed7b7ec230c5318310fe36b1c9ea,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s032-20261025e/score/results/reward.json,research,measured,0,,17086 +protein-sequence-modeling,reward,S033,18347,0.6623390819392939,True,True,reviewed-inference-v1:a6c9ed839169f63c9aa77b438f09115e2c836a5d09aa2aab215d786dee5fbccf,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s033-20261025e/score/results/reward.json,research,measured,0,,18347 +protein-sequence-modeling,reward,S034,20568,0.6614161470062067,True,True,reviewed-inference-v1:5997be33e04d7a99e47b1e2638defda971665f786745f1c089b21c88dcd8441f,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s034-20261025e/score/results/reward.json,research,measured,0,,20568 +protein-sequence-modeling,reward,S035,20928,0.6614161470062067,True,False,reviewed-inference-v1:5997be33e04d7a99e47b1e2638defda971665f786745f1c089b21c88dcd8441f,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s034-20261025e/score/results/reward.json,research,reused,0,,20928 +protein-sequence-modeling,reward,S036,34438,0.6614161470062067,True,True,reviewed-inference-v1:93437489ae2a3f53ab5e27f611606010f4d33774aee207dcba88068bbdf09d9e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s036-20261025e/score/results/reward.json,research,measured,0,,34438 +protein-sequence-modeling,reward,S037,34678,0.6610564219368205,True,True,reviewed-inference-v1:61643393f457137587e28aa102a537c51087c4dfda3a7aecfbc6e6f57ef45202,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s037-20261025e/score/results/reward.json,research,measured,0,,34678 +protein-sequence-modeling,reward,S038,34918,0.6610564219368205,True,False,reviewed-inference-v1:61643393f457137587e28aa102a537c51087c4dfda3a7aecfbc6e6f57ef45202,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s037-20261025e/score/results/reward.json,research,reused,0,,34918 +protein-sequence-modeling,reward,S039,35278,0.6610564219368205,True,False,reviewed-inference-v1:61643393f457137587e28aa102a537c51087c4dfda3a7aecfbc6e6f57ef45202,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s037-20261025e/score/results/reward.json,research,reused,0,,35278 +protein-sequence-modeling,reward,S040,38221,0.6636681724030057,True,True,reviewed-inference-v1:a5a0847c3e54a2113130045050586ef11e8c085a1c49509f6b0df19af06b7640,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s040-20261025e/score/results/reward.json,research,measured,0,,38221 +protein-sequence-modeling,reward,S041,38822,0.6636681724030057,True,False,reviewed-inference-v1:a5a0847c3e54a2113130045050586ef11e8c085a1c49509f6b0df19af06b7640,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s040-20261025e/score/results/reward.json,research,reused,0,,38822 +protein-sequence-modeling,reward,S042,43204,0.6636660165243558,True,True,reviewed-inference-v1:6a3f3d8ac80ca024705878827806c44a95e8cc5a2f209cba4728c8148f9b7ba0,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s042-20261025e/score/results/reward.json,research,measured,0,,43204 +protein-sequence-modeling,reward,S043,45431,0.6680975181703421,True,True,reviewed-inference-v1:5dee56b44876c84bca4c8daf1a2e5c3b7f67b0cea68eb0df81c756dfca744866,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s043-20261025e/score/results/reward.json,research,measured,0,,45431 +protein-sequence-modeling,reward,S044,45731,0.668185909194988,True,True,reviewed-inference-v1:0eb91d46a4a76a177d5ddc8be868d942c3c1ca78bfaab5cac10afd45a007dd3e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s044-20261025e/score/results/reward.json,research,measured,0,,45731 +protein-sequence-modeling,reward,S045,46031,0.6681912988916129,True,True,reviewed-inference-v1:1854bd7f946a07d19fc259acae288c1d0b3e6c8147a54550d342b77de348b061,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s045-20261025e/score/results/reward.json,research,measured,0,,46031 +protein-sequence-modeling,reward,S046,46452,0.6682062541978107,True,True,reviewed-inference-v1:a1bc5788d0dd54432671b48a7fe2e7015dfa638d3412d4f2fc69d132fae28588,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s046-20261025e/score/results/reward.json,research,measured,0,,46452 +protein-sequence-modeling,reward,S047,47233,0.6683407223790284,True,True,reviewed-inference-v1:23da91be69b6a1dba67620d1567af305f48b5c8a4f89e5fa97a011e93bec44bd,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s047-20261025e/score/results/reward.json,research,measured,0,,47233 +protein-sequence-modeling,reward,S048,49935,0.6744342787502221,True,True,reviewed-inference-v1:6400af3414fc2532ff2983af457405e123d68430553995763cc477a80e49c8b9,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s048-20261025e/score/results/reward.json,research,measured,0,,49935 +protein-sequence-modeling,reward,S049,52637,0.6745075786243189,True,True,reviewed-inference-v1:1786589b9fc880bd6d986af5e0605034656f0b1be20d117c1a52345bdfcd1805,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s049-20261025e/score/results/reward.json,research,measured,0,,52637 +protein-sequence-modeling,reward,S050,53057,0.6745291374108179,True,True,reviewed-inference-v1:70096e009050d0a4092029fce72e90f4d57350012758befa7137e3561ffb3405,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s050-20261025e/score/results/reward.json,research,measured,0,,53057 +protein-sequence-modeling,reward,S051,53359,0.6744771596572963,True,True,reviewed-inference-v1:0a905d478f45188be9349c25183f516e62d7abfce95b31be3e36f93e8ee8f67b,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s051-20261025e/score/results/reward.json,research,measured,0,,53359 +protein-sequence-modeling,reward,S052,75575,0.6749525601740145,True,True,reviewed-inference-v1:f7f5b921098e29986e03fb3fce6ff321be1261d5980ad7e59afb6b6eeb3a3893,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s052-20261025e/score/results/reward.json,research,measured,0,,75575 +protein-sequence-modeling,reward,S053,84821,0.6754008131000694,True,True,reviewed-inference-v1:5761752279d67dc9f0ca4ba5e15a75889843940dc18e083ef3097b518a183a82,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s053-20261025e/score/results/reward.json,research,measured,0,,84821 +protein-sequence-modeling,reward,S054,85001,0.6751027355455981,True,True,reviewed-inference-v1:fdd290b4f81639147c2ca81ff29547d733d70ff80b426803c8b118222f67eee7,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s054-20261025e/score/results/reward.json,research,measured,0,,85001 +protein-sequence-modeling,reward,S055,88305,0.6784794525898232,True,True,reviewed-inference-v1:8549c0f17e56cab31fd2235e2a5bec660f1c75751cc0af48a84e2b573d5211a4,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s055-20261025e/score/results/reward.json,research,measured,0,,88305 +protein-sequence-modeling,reward,S056,89326,0.6796716534832193,True,True,reviewed-inference-v1:dd90710f47a011c5ef589ff5ea87f7a6ae97d586f0406029a35d634a7f1cf8e4,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s056-20261025e/score/results/reward.json,research,measured,0,,89326 +protein-sequence-modeling,reward,S057,89937,0.6804887314915324,True,True,reviewed-inference-v1:9728d36366635a5a81e7b47d9cbaf5b170a9bb790d56c039743dcd218fe4577c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s057-20261025e/score/results/reward.json,research,measured,0,,89937 +protein-sequence-modeling,reward,S058,91127,0.6804617830084086,True,True,reviewed-inference-v1:ee139f0e669cb4e18730ae353ab337d316889a93e96e03286879bb7664ccc7a8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s058-20261025e/score/results/reward.json,research,measured,0,,91127 +protein-sequence-modeling,reward,S059,91308,0.6810948546721209,True,True,reviewed-inference-v1:0b5230ae7dd73fe801cab8728ca85877c4bf374cbe482a2bf9d006e2ed6a840d,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s059-20261025e/score/results/reward.json,research,measured,0,,91308 +protein-sequence-modeling,reward,S060,92148,0.6869191139782744,True,True,reviewed-inference-v1:93e5a2f4a147f8e9e65962c9723d17c4bdb1408aab7988c48483b2d45b16fd2f,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s060-20261025e/score/results/reward.json,research,measured,0,,92148 +protein-sequence-modeling,reward,S061,92508,0.6865098184214052,True,True,reviewed-inference-v1:d8bc79296393fba19a55bc46e8a159cad2784e65265e8684f194392008284025,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s061-20261025e/score/results/reward.json,research,measured,0,,92508 +protein-sequence-modeling,reward,S062,109201,0.6865223703070048,True,True,reviewed-inference-v1:d0615656eed3c3dbbea310dd03ec8f6b4a01116342c84cad8dc11912e437a514,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s062-20261025e-public-input-retry-20261026b/score/results/reward.json,research,measured,0,,109201 +protein-sequence-modeling,reward,S063,122828,0.6861425273087775,True,True,reviewed-inference-v1:057aa3b9382825816a3e17885bf838ebb1b3d2c1e94f216eb42aa855f7b0107e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s063-20261025e/score/results/reward.json,research,measured,0,,122828 +protein-sequence-modeling,reward,GRACE_FINAL,172800,0.6861425273087775,True,False,reviewed-inference-v1:057aa3b9382825816a3e17885bf838ebb1b3d2c1e94f216eb42aa855f7b0107e,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-native-eval-s063-20261025e/score/results/reward.json,post_budget_submission,reused,101.7002084540145,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-sequence-modeling-astra-finalize-5m-20261025e/publication-review.json,172901.700208454 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S001,120,0.2478418692946434,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S002,180,0.2478418692946434,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S003,300,0.2478418692946434,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S004,6002,0.24722639232873916,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S005,8523,0.24624517500400545,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S006,14465,0.24569194555282592,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S007,23632,0.245479334294796,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S008,28734,0.24722639232873916,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S009,29034,0.24722639232873916,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S010,57246,0.24510325223207474,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S011,68358,0.24510325223207474,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S012,79523,0.2448410952091217,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S013,90868,0.24452629923820496,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S014,101973,0.2445279148221016,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S015,118540,0.2445279148221016,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S016,131391,0.2445279148221016,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Channel_3D_Retau180/wall_shear,S017,155883,0.2445279148221016,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Channel_3D_Retau180/wall_shear,GRACE_FINAL,172800,0.2445279148221016,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S001,120,1.1371881907193877,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S002,180,1.1371881907193877,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S003,300,1.1371881907193877,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S004,6002,1.1240502400503276,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S005,8523,1.127290476662643,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S006,14465,1.1318338495054427,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S007,23632,1.1318338495054427,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S008,28734,1.1240502400503276,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S009,29034,1.1240502400503276,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S010,57246,1.1318338495054427,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S011,68358,1.1318338495054427,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S012,79523,1.1318338495054427,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S013,90868,1.1318338495054427,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S014,101973,1.1318338495054427,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S015,118540,1.1318338495054427,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S016,131391,1.1318338495054427,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Cube_3D_Re3700/drag_cd,S017,155883,1.1318338495054427,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Cube_3D_Re3700/drag_cd,GRACE_FINAL,172800,1.1318338495054427,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S001,120,1.5328965035831073,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S002,180,1.5328965035831073,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S003,300,1.5328965035831073,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S004,6002,1.5453149346193922,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S005,8523,1.450654098890971,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S006,14465,1.3477802422404943,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S007,23632,1.3477802422404943,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S008,28734,1.5453149346193922,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S009,29034,1.5453149346193922,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S010,57246,1.3477802422404943,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S011,68358,1.3477802422404943,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S012,79523,1.3477802422404943,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S013,90868,1.3477802422404943,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S014,101973,1.3477802422404943,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S015,118540,1.3477802422404943,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S016,131391,1.3477802422404943,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,S017,155883,1.3477802422404943,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Cylinder_2D_Re1000/drag_cd,GRACE_FINAL,172800,1.3477802422404943,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S001,120,1.3519312159293846,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S002,180,1.3519312159293846,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S003,300,1.3519312159293846,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S004,6002,1.2170212120665673,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S005,8523,1.3648786311311663,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S006,14465,1.3440142538137483,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S007,23632,1.3440142538137483,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S008,28734,1.2170212120665673,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S009,29034,1.2170212120665673,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S010,57246,1.3440142538137483,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S011,68358,1.3440142538137483,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S012,79523,1.3440142538137483,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S013,90868,1.3440142538137483,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S014,101973,1.3440142538137483,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S015,118540,1.3440142538137483,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S016,131391,1.3440142538137483,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,S017,155883,1.3440142538137483,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Cylinder_2D_Re200/drag_cd,GRACE_FINAL,172800,1.3440142538137483,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S001,120,1.5244128901767382,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S002,180,1.5244128901767382,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S003,300,1.5244128901767382,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S004,6002,1.564587819435299,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S005,8523,1.6107483512505398,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S006,14465,1.5923412221848952,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S007,23632,1.5923412221848952,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S008,28734,1.564587819435299,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S009,29034,1.564587819435299,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S010,57246,1.5923412221848952,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S011,68358,1.5923412221848952,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S012,79523,1.5923412221848952,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S013,90868,1.5923412221848952,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S014,101973,1.5923412221848952,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S015,118540,1.5923412221848952,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S016,131391,1.5923412221848952,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,S017,155883,1.5923412221848952,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Cylinder_2D_Re3900/drag_cd,GRACE_FINAL,172800,1.5923412221848952,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Kolmogorov_2D/tke,S001,120,3.341502660011884,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Kolmogorov_2D/tke,S002,180,3.341502660011884,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Kolmogorov_2D/tke,S003,300,3.341502660011884,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Kolmogorov_2D/tke,S004,6002,3.4285777221021654,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Kolmogorov_2D/tke,S005,8523,3.2351688259243425,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Kolmogorov_2D/tke,S006,14465,3.298892975656201,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Kolmogorov_2D/tke,S007,23632,3.298892975656201,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Kolmogorov_2D/tke,S008,28734,3.4285777221021654,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Kolmogorov_2D/tke,S009,29034,3.4285777221021654,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Kolmogorov_2D/tke,S010,57246,3.262764190094863,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Kolmogorov_2D/tke,S011,68358,3.262764190094863,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Kolmogorov_2D/tke,S012,79523,3.262764190094863,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Kolmogorov_2D/tke,S013,90868,3.262764190094863,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Kolmogorov_2D/tke,S014,101973,3.262764190094863,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Kolmogorov_2D/tke,S015,118540,3.262764190094863,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Kolmogorov_2D/tke,S016,131391,3.262764190094863,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Kolmogorov_2D/tke,S017,155883,3.262764190094863,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Kolmogorov_2D/tke,GRACE_FINAL,172800,3.262764190094863,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S001,120,0.5089318324676899,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S002,180,0.5089318324676899,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S003,300,0.5089318324676899,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S004,6002,0.6443608319659421,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S005,8523,0.6107892924257835,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S006,14465,0.6108148414933106,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S007,23632,0.6108148414933106,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S008,28734,0.6443608319659421,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S009,29034,0.6443608319659421,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S010,57246,0.6108148414933106,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S011,68358,0.6108148414933106,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S012,79523,0.6108148414933106,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S013,90868,0.6108148414933106,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S014,101973,0.6108148414933106,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S015,118540,0.6108148414933106,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S016,131391,0.6108148414933106,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,S017,155883,0.6108148414933106,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA20/gust_load_error,GRACE_FINAL,172800,0.6108148414933106,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S001,120,0.9388988712000268,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S002,180,0.9388988712000268,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S003,300,0.9388988712000268,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S004,6002,1.0407099113057525,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S005,8523,1.0896649693124039,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S006,14465,1.0847520925030132,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S007,23632,1.0847520925030132,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S008,28734,1.0407099113057525,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S009,29034,1.0407099113057525,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S010,57246,1.0847520925030132,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S011,68358,1.0847520925030132,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S012,79523,1.0847520925030132,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S013,90868,1.0847520925030132,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S014,101973,1.0847520925030132,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S015,118540,1.0847520925030132,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S016,131391,1.0847520925030132,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,S017,155883,1.0847520925030132,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,NACA0012Gust_2D_Re1000_AOA40/gust_load_error,GRACE_FINAL,172800,1.0847520925030132,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S001,120,0.21875642219489738,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S002,180,0.21875642219489738,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S003,300,0.21875642219489738,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S004,6002,0.2584625038588229,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S005,8523,0.186289461706006,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S006,14465,0.19403191119508567,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S007,23632,0.19403191119508567,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S008,28734,0.2584625038588229,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S009,29034,0.2584625038588229,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S010,57246,0.19403191119508567,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S011,68358,0.19403191119508567,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S012,79523,0.19403191119508567,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S013,90868,0.19403191119508567,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S014,101973,0.19403191119508567,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S015,118540,0.19403191119508567,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S016,131391,0.19403191119508567,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,S017,155883,0.19403191119508567,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA20/gust_load_error,GRACE_FINAL,172800,0.19403191119508567,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S001,120,0.3266111044723214,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S002,180,0.3266111044723214,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S003,300,0.3266111044723214,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S004,6002,0.30411302581407457,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S005,8523,0.30035401179574484,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S006,14465,0.3034961971287741,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S007,23632,0.3034961971287741,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S008,28734,0.30411302581407457,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S009,29034,0.30411302581407457,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S010,57246,0.3034961971287741,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S011,68358,0.3034961971287741,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S012,79523,0.3034961971287741,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S013,90868,0.3034961971287741,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S014,101973,0.3034961971287741,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S015,118540,0.3034961971287741,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S016,131391,0.3034961971287741,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,S017,155883,0.3034961971287741,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,NACA0012Gust_2D_Re100_AOA40/gust_load_error,GRACE_FINAL,172800,0.3034961971287741,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S001,120,0.40667714717335285,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S002,180,0.40667714717335285,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S003,300,0.40667714717335285,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S004,6002,0.7231825362423964,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S005,8523,0.46642627702330314,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S006,14465,0.5393891029065416,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S007,23632,0.5393891029065416,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S008,28734,0.7231825362423964,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S009,29034,0.7231825362423964,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S010,57246,0.5393891029065416,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S011,68358,0.5393891029065416,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S012,79523,0.5393891029065416,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S013,90868,0.5393891029065416,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S014,101973,0.5393891029065416,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S015,118540,0.5393891029065416,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S016,131391,0.5393891029065416,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,S017,155883,0.5393891029065416,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,NACA0012Gust_3D_Re1000_AOA20/gust_load_error,GRACE_FINAL,172800,0.5393891029065416,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S001,120,0.358408736246388,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S002,180,0.358408736246388,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S003,300,0.358408736246388,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S004,6002,0.42372300957952586,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S005,8523,0.34955601654855295,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S006,14465,0.3561817901799997,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S007,23632,0.3561817901799997,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S008,28734,0.42372300957952586,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S009,29034,0.42372300957952586,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S010,57246,0.3561817901799997,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S011,68358,0.3561817901799997,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S012,79523,0.3561817901799997,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S013,90868,0.3561817901799997,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S014,101973,0.3561817901799997,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S015,118540,0.3561817901799997,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S016,131391,0.3561817901799997,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,S017,155883,0.3561817901799997,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,NACA0012Gust_3D_Re100_AOA20/gust_load_error,GRACE_FINAL,172800,0.3561817901799997,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S001,120,1.9868127007775414,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S002,180,1.9868127007775414,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S003,300,1.9868127007775414,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S004,6002,2.220945422680008,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S005,8523,2.1923258206173535,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S006,14465,2.2139319316532506,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S007,23632,2.2139319316532506,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S008,28734,2.220945422680008,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S009,29034,2.220945422680008,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S010,57246,2.2139319316532506,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S011,68358,2.2139319316532506,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S012,79523,2.2139319316532506,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S013,90868,2.2139319316532506,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S014,101973,2.2139319316532506,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S015,118540,2.2139319316532506,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S016,131391,2.2139319316532506,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,S017,155883,2.2139319316532506,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,NACA0012_2D_Re1000_AOA20/lift_drag,GRACE_FINAL,172800,2.2139319316532506,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S001,120,1.112535155162241,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S002,180,1.112535155162241,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S003,300,1.112535155162241,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S004,6002,1.1171468664889956,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S005,8523,1.125676335790263,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S006,14465,1.0385754802868215,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S007,23632,1.0385754802868215,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S008,28734,1.1171468664889956,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S009,29034,1.1171468664889956,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S010,57246,1.0385754802868215,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S011,68358,1.0385754802868215,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S012,79523,1.0385754802868215,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S013,90868,1.0385754802868215,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S014,101973,1.0385754802868215,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S015,118540,1.0385754802868215,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S016,131391,1.0385754802868215,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,S017,155883,1.0385754802868215,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,NACA0012_2D_Re1000_AOA40/lift_drag,GRACE_FINAL,172800,1.0385754802868215,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S001,120,1.358934717817317,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S002,180,1.358934717817317,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S003,300,1.358934717817317,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S004,6002,1.4682124228138536,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S005,8523,1.2326262561990717,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S006,14465,1.2506370899300907,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S007,23632,1.2506370899300907,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S008,28734,1.4682124228138536,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S009,29034,1.4682124228138536,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S010,57246,1.2506370899300907,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S011,68358,1.2506370899300907,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S012,79523,1.2506370899300907,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S013,90868,1.2506370899300907,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S014,101973,1.2506370899300907,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S015,118540,1.2506370899300907,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S016,131391,1.2506370899300907,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,S017,155883,1.2506370899300907,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,NACA0012_2D_Re100_AOA20/lift_drag,GRACE_FINAL,172800,1.2506370899300907,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S001,120,0.9465700484642553,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S002,180,0.9465700484642553,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S003,300,0.9465700484642553,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S004,6002,0.936281253178509,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S005,8523,0.93531375868501,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S006,14465,0.9392409063192829,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S007,23632,0.9392409063192829,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S008,28734,0.936281253178509,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S009,29034,0.936281253178509,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S010,57246,0.9392409063192829,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S011,68358,0.9392409063192829,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S012,79523,0.9392409063192829,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S013,90868,0.9392409063192829,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S014,101973,0.9392409063192829,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S015,118540,0.9392409063192829,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S016,131391,0.9392409063192829,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,S017,155883,0.9392409063192829,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,NACA0012_2D_Re100_AOA40/lift_drag,GRACE_FINAL,172800,0.9392409063192829,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S001,120,6.193544171270524,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S002,180,6.193544171270524,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S003,300,6.193544171270524,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S004,6002,5.701011861951659,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S005,8523,3.5775513270613306,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S006,14465,3.365465463253448,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S007,23632,3.3910151748445267,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S008,28734,5.701011861951659,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S009,29034,5.701011861951659,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S010,57246,3.090061202759905,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S011,68358,3.090061202759905,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S012,79523,3.1049412242855743,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S013,90868,3.084626780189879,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S014,101973,3.072411738078473,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S015,118540,2.9824246018651643,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S016,131391,2.9824246018651643,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,S017,155883,2.8673078159019014,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Nozzle2D_coarse/nozzle_angle_mae,GRACE_FINAL,172800,2.8673078159019014,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S001,120,6.1940692175424426,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S002,180,6.1940692175424426,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S003,300,6.1940692175424426,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S004,6002,4.018947559158306,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S005,8523,,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S006,14465,,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S007,23632,,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S008,28734,4.018947559158306,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S009,29034,4.018947559158306,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S010,57246,2.715337242237861,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S011,68358,2.715337242237861,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S012,79523,2.715337242237861,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S013,90868,2.715337242237861,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S014,101973,2.4305546747892617,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S015,118540,2.4104221661013283,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S016,131391,2.4104221661013283,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,S017,155883,2.3776093901777133,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Nozzle2D_fine/nozzle_angle_mae,GRACE_FINAL,172800,2.3776093901777133,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S001,120,2.9379562137073068,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S002,180,2.9379562137073068,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S003,300,2.9379562137073068,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S004,6002,3.617866298780854,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S005,8523,3.3063836498674735,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S006,14465,3.591009536038067,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S007,23632,3.591009536038067,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S008,28734,3.617866298780854,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S009,29034,3.617866298780854,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S010,57246,3.591009536038067,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S011,68358,3.591009536038067,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S012,79523,3.591009536038067,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S013,90868,3.591009536038067,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S014,101973,3.591009536038067,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S015,118540,3.591009536038067,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S016,131391,3.591009536038067,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Pinball_2D_Re100/drag_cd,S017,155883,3.591009536038067,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Pinball_2D_Re100/drag_cd,GRACE_FINAL,172800,3.591009536038067,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S001,120,2.853451894194974,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S002,180,2.853451894194974,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S003,300,2.853451894194974,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S004,6002,6.835138279820303,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S005,8523,3.130550340921959,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S006,14465,4.218089982751825,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S007,23632,4.218089982751825,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S008,28734,6.835138279820303,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S009,29034,6.835138279820303,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S010,57246,4.218089982751825,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S011,68358,4.218089982751825,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S012,79523,4.218089982751825,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S013,90868,4.218089982751825,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S014,101973,4.218089982751825,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S015,118540,4.218089982751825,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S016,131391,4.218089982751825,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Pinball_2D_Re150/drag_cd,S017,155883,4.218089982751825,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Pinball_2D_Re150/drag_cd,GRACE_FINAL,172800,4.218089982751825,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S001,120,3.499244152201916,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S002,180,3.499244152201916,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S003,300,3.499244152201916,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S004,6002,3.8181887888678423,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S005,8523,2.1491877506322927,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S006,14465,1.955019819380864,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S007,23632,1.955019819380864,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S008,28734,3.8181887888678423,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S009,29034,3.8181887888678423,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S010,57246,1.955019819380864,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S011,68358,1.955019819380864,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S012,79523,1.955019819380864,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S013,90868,1.955019819380864,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S014,101973,1.955019819380864,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S015,118540,1.955019819380864,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S016,131391,1.955019819380864,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Pinball_2D_Re30/drag_cd,S017,155883,1.955019819380864,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Pinball_2D_Re30/drag_cd,GRACE_FINAL,172800,1.955019819380864,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S001,120,3.0069906367487573,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S002,180,3.0069906367487573,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S003,300,3.0069906367487573,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S004,6002,3.632545955721748,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S005,8523,2.7031886563274328,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S006,14465,2.257528051621227,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S007,23632,2.257528051621227,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S008,28734,3.632545955721748,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S009,29034,3.632545955721748,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S010,57246,2.257528051621227,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S011,68358,2.257528051621227,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S012,79523,2.257528051621227,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S013,90868,2.257528051621227,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S014,101973,2.257528051621227,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S015,118540,2.257528051621227,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S016,131391,2.257528051621227,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Pinball_2D_Re75/drag_cd,S017,155883,2.257528051621227,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Pinball_2D_Re75/drag_cd,GRACE_FINAL,172800,2.257528051621227,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S001,120,2.9974661935916727,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S002,180,2.9974661935916727,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S003,300,2.9974661935916727,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S004,6002,3.3750557222918784,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S005,8523,4.0413238702155185,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S006,14465,4.036586490688641,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S007,23632,4.036586490688641,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S008,28734,3.3750557222918784,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S009,29034,3.3750557222918784,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S010,57246,4.036586490688641,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S011,68358,4.036586490688641,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S012,79523,4.036586490688641,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S013,90868,4.036586490688641,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S014,101973,4.036586490688641,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S015,118540,4.036586490688641,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S016,131391,4.036586490688641,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Pinball_3D_Re100/drag_cd,S017,155883,4.036586490688641,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Pinball_3D_Re100/drag_cd,GRACE_FINAL,172800,4.036586490688641,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S001,120,0.6617120633361673,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S002,180,0.6617120633361673,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S003,300,0.6617120633361673,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S004,6002,0.6533706972017231,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S005,8523,0.6608723597085667,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S006,14465,0.6590988243302812,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S007,23632,0.6590988243302812,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S008,28734,0.6533706972017231,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S009,29034,0.6533706972017231,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S010,57246,0.6590988243302812,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S011,68358,0.6590988243302812,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S012,79523,0.6590988243302812,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S013,90868,0.6590988243302812,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S014,101973,0.6590988243302812,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S015,118540,0.6590988243302812,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S016,131391,0.6590988243302812,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,Sphere_3D_Re300/drag_cd,S017,155883,0.6590988243302812,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,Sphere_3D_Re300/drag_cd,GRACE_FINAL,172800,0.6590988243302812,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S001,120,2.3974232711063195,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S002,180,2.3974232711063195,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S003,300,2.3974232711063195,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S004,6002,,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S005,8523,,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S006,14465,,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S007,23632,,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S008,28734,,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S009,29034,,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S010,57246,,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S011,68358,,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S012,79523,,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S013,90868,,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S014,101973,,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S015,118540,,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S016,131391,,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,S017,155883,,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,SquareCylinder_2D_Re1000/drag_cd,GRACE_FINAL,172800,,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S001,120,1.4821182658582308,True,True,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,measured,0,,120 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S002,180,1.4821182658582308,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,180 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S003,300,1.4821182658582308,True,False,reviewed-inference-v1:bc2f88d2452065b3468341cabf26e2bf5eed7907eef5e11c7ddd1455f3a7ded2,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s001-20261025g/inference/results/reward.json,research,reused,0,,300 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S004,6002,,True,True,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,measured,0,,6002 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S005,8523,1.646419656660938,True,True,reviewed-inference-v1:5a68a20c7355c5b776c5dd336f7ce9182d87fa76f8db9be9a8d4a7fb9c3fc006,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s005-20261025g/inference/results/reward.json,research,measured,0,,8523 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S006,14465,1.6125508910415423,True,True,reviewed-inference-v1:b7f1a8b459729d143da13ac41d49a47f7f9812a42a20582a29593e3f71935574,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s006-20261025g/inference/results/reward.json,research,measured,0,,14465 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S007,23632,1.6125508910415423,True,True,reviewed-inference-v1:1b7907f009bc4f5fc100d88281cfb139fecd0a480129a125685050d8aaf8e861,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s007-20261025g/inference/results/reward.json,research,measured,0,,23632 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S008,28734,,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,28734 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S009,29034,,True,False,reviewed-inference-v1:e1f41d7e3a4e54b1f617698fbc57756e8f577809ee15216fbe2b5b47912e4638,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s004-20261025g/inference/results/reward.json,research,reused,0,,29034 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S010,57246,1.6125508910415423,True,True,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,measured,0,,57246 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S011,68358,1.6125508910415423,True,False,reviewed-inference-v1:ecfad4f3e2c9b76ccef1afea506dab24459c3dea6435af43bc0f152f2f59fda8,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s010-20261025g/inference/results/reward.json,research,reused,0,,68358 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S012,79523,1.6125508910415423,True,True,reviewed-inference-v1:1648acaede9c129bc807086bdcb26c4f9384b8a6edc40100a4950ed58957d0fc,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s012-20261025g/inference/results/reward.json,research,measured,0,,79523 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S013,90868,1.6125508910415423,True,True,reviewed-inference-v1:4cf673912d322eee51448a28f0cf55ff6b1a6e32472d1296d2699fc5d6442661,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s013-20261025g/inference/results/reward.json,research,measured,0,,90868 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S014,101973,1.6125508910415423,True,True,reviewed-inference-v1:3d6172f5f48411afae83eae71b17900b810f1bcb04efb0b8f723998c72ade5de,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s014-20261025g/inference/results/reward.json,research,measured,0,,101973 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S015,118540,1.6125508910415423,True,True,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,measured,0,,118540 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S016,131391,1.6125508910415423,True,False,reviewed-inference-v1:259536855a5ecc05bb0954809eb3942c64b5a75dba718bab7fb51126f58dfa71,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s015-20261025g/inference/results/reward.json,research,reused,0,,131391 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,S017,155883,1.6125508910415423,True,True,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,research,measured,0,,155883 +fluid-flow-control,SquareCylinder_2D_Re200/drag_cd,GRACE_FINAL,172800,1.6125508910415423,True,False,reviewed-inference-v1:f76e71f9441632ed2f4b2ff68fa5d6300d248411b630341606259e74c567826c,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-native-eval-s017-20261025g/inference/results/reward.json,post_budget_submission,reused,106.50820528296754,/weka/oe-adapt-default/stevenc/science-speedrun-runs/fluid-flow-control-astra-finalize-5m-20261025a/publication-review.json,172906.50820528297 +protein-design,unconditional_pass_rate,S001,1622,0.0,True,True,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,research,measured,0,,1622 +protein-design,unconditional_pass_rate,GRACE_FINAL,172800,0.0,True,False,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,post_budget_submission,reused,112.09387857001275,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-finalize-5m-20261025e/publication-review.json,172912.09387857 +protein-design,unconditional_diversity,S001,1622,0.0,True,True,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,research,measured,0,,1622 +protein-design,unconditional_diversity,GRACE_FINAL,172800,0.0,True,False,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,post_budget_submission,reused,112.09387857001275,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-finalize-5m-20261025e/publication-review.json,172912.09387857 +protein-design,sm_binder_pass_rate,S001,1622,0.0,True,True,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,research,measured,0,,1622 +protein-design,sm_binder_pass_rate,GRACE_FINAL,172800,0.0,True,False,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,post_budget_submission,reused,112.09387857001275,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-finalize-5m-20261025e/publication-review.json,172912.09387857 +protein-design,sm_binder_diversity,S001,1622,0.0,True,True,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,research,measured,0,,1622 +protein-design,sm_binder_diversity,GRACE_FINAL,172800,0.0,True,False,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,post_budget_submission,reused,112.09387857001275,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-finalize-5m-20261025e/publication-review.json,172912.09387857 +protein-design,ppi_binder_pass_rate,S001,1622,0.0,True,True,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,research,measured,0,,1622 +protein-design,ppi_binder_pass_rate,GRACE_FINAL,172800,0.0,True,False,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,post_budget_submission,reused,112.09387857001275,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-finalize-5m-20261025e/publication-review.json,172912.09387857 +protein-design,ppi_binder_diversity,S001,1622,0.0,True,True,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,research,measured,0,,1622 +protein-design,ppi_binder_diversity,GRACE_FINAL,172800,0.0,True,False,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,post_budget_submission,reused,112.09387857001275,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-finalize-5m-20261025e/publication-review.json,172912.09387857 +protein-design,enzyme_pass_rate,S001,1622,0.013414634146341465,True,True,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,research,measured,0,,1622 +protein-design,enzyme_pass_rate,GRACE_FINAL,172800,0.013414634146341465,True,False,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,post_budget_submission,reused,112.09387857001275,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-finalize-5m-20261025e/publication-review.json,172912.09387857 +protein-design,enzyme_diversity,S001,1622,0.12195121951219512,True,True,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,research,measured,0,,1622 +protein-design,enzyme_diversity,GRACE_FINAL,172800,0.12195121951219512,True,False,reviewed-inference-v1:7deb7852774a45d5e4390d592f68b721270322bdaa33ce54ad52b21ce62cb0f6,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-native-eval-s001-20261025e-foldseek-retry1/score/results/reward.json,post_budget_submission,reused,112.09387857001275,/weka/oe-adapt-default/stevenc/science-speedrun-runs/protein-design-astra-finalize-5m-20261025e/publication-review.json,172912.09387857 diff --git a/plots/fluid-flow-control-progression-1.png b/plots/fluid-flow-control-progression-1.png new file mode 100644 index 0000000000000000000000000000000000000000..754832689cca1e4dcabf0e9cf52f624d14138ac6 --- /dev/null +++ b/plots/fluid-flow-control-progression-1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e384d54d81cda5d18c45ef89b21926cfbbe961855bf800a9cbe0f2d3f5a63eb +size 416915 diff --git a/plots/fluid-flow-control-progression-1.svg b/plots/fluid-flow-control-progression-1.svg new file mode 100644 index 0000000000000000000000000000000000000000..b921b5bd5f8dfc477b0a35e5a75b2775cc267a16 --- /dev/null +++ b/plots/fluid-flow-control-progression-1.svg @@ -0,0 +1,3062 @@ + + + + + + + + 2026-10-26T20:50:14.084369 + image/svg+xml + + + Matplotlib v3.6.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.245 + + + + + + + + + 0.246 + + + + + + + + + 0.247 + + + + + + + + + 0.248 + + + + wall_shear (native nondimensional) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Channel_3D_Retau180 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 1.1250 + + + + + + + + + 1.1275 + + + + + + + + + 1.1300 + + + + + + + + + 1.1325 + + + + + + + + + 1.1350 + + + + + + + + + 1.1375 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Cube_3D_Re3700 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 1.35 + + + + + + + + + 1.40 + + + + + + + + + 1.45 + + + + + + + + + 1.50 + + + + + + + + + 1.55 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Cylinder_2D_Re1000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 1.225 + + + + + + + + + 1.250 + + + + + + + + + 1.275 + + + + + + + + + 1.300 + + + + + + + + + 1.325 + + + + + + + + + 1.350 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Cylinder_2D_Re200 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 1.54 + + + + + + + + + 1.56 + + + + + + + + + 1.58 + + + + + + + + + 1.60 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Cylinder_2D_Re3900 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 3.25 + + + + + + + + + 3.30 + + + + + + + + + 3.35 + + + + + + + + + 3.40 + + + + tke (native nondimensional) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Kolmogorov_2D + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.525 + + + + + + + + + 0.550 + + + + + + + + + 0.575 + + + + + + + + + 0.600 + + + + + + + + + 0.625 + + + + + + + + + 0.650 + + + + gust_load_error (coefficient) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + NACA0012Gust_2D_Re1000_AOA20 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.950 + + + + + + + + + 0.975 + + + + + + + + + 1.000 + + + + + + + + + 1.025 + + + + + + + + + 1.050 + + + + + + + + + 1.075 + + + + gust_load_error (coefficient) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + NACA0012Gust_2D_Re1000_AOA40 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.20 + + + + + + + + + 0.22 + + + + + + + + + 0.24 + + + + + + + + + 0.26 + + + + gust_load_error (coefficient) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + NACA0012Gust_2D_Re100_AOA20 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Astra xhigh · Fluid-flow control · separate native metrics · 1/3 + + + 1 H100 × 48h research. Purple diamonds sit at 48h + actual submission-window duration; they are outside the research budget. + + + Every saved snapshot is shown; orange points reuse scores, including metadata-only changes. Already-evaluated duplicates stay blue. + + + Repository baselines use different training budgets. Reported specialists are not eligible shared models + + + Axes scale independently; nearby points can overlap. Steps follow submitted packages, including regressions. Beaker execution adaptations apply. + + + Lower-edge markers are not scores: gray ticks = awaiting evaluation; red × = evaluated but no numeric result for this metric. + + + + + + + + + + + + Evaluated snapshot + + + + + + + + + + + Duplicate snapshot · reused score + + + + + + + + + + + Reviewed +5m final · reused score + + + + + + Repository test baseline + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plots/fluid-flow-control-progression-2.png b/plots/fluid-flow-control-progression-2.png new file mode 100644 index 0000000000000000000000000000000000000000..8e04d8f887736a7eccdcbe20fc399e27b2dbde9a --- /dev/null +++ b/plots/fluid-flow-control-progression-2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccf48cfd294f836bce066e2694f4d71a791095c093016bfdd915c443308556cf +size 395177 diff --git a/plots/fluid-flow-control-progression-2.svg b/plots/fluid-flow-control-progression-2.svg new file mode 100644 index 0000000000000000000000000000000000000000..ca9e3979624e8b3e77928cef8be0aa72f94f83b2 --- /dev/null +++ b/plots/fluid-flow-control-progression-2.svg @@ -0,0 +1,3049 @@ + + + + + + + + 2026-10-26T20:50:16.012511 + image/svg+xml + + + Matplotlib v3.6.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.300 + + + + + + + + + 0.305 + + + + + + + + + 0.310 + + + + + + + + + 0.315 + + + + + + + + + 0.320 + + + + + + + + + 0.325 + + + + gust_load_error (coefficient) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + NACA0012Gust_2D_Re100_AOA40 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.40 + + + + + + + + + 0.45 + + + + + + + + + 0.50 + + + + + + + + + 0.55 + + + + + + + + + 0.60 + + + + + + + + + 0.65 + + + + + + + + + 0.70 + + + + gust_load_error (coefficient) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + NACA0012Gust_3D_Re1000_AOA20 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.36 + + + + + + + + + 0.38 + + + + + + + + + 0.40 + + + + + + + + + 0.42 + + + + gust_load_error (coefficient) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + NACA0012Gust_3D_Re100_AOA20 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 2.00 + + + + + + + + + 2.05 + + + + + + + + + 2.10 + + + + + + + + + 2.15 + + + + + + + + + 2.20 + + + + lift_drag (dimensionless) · higher is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + NACA0012_2D_Re1000_AOA20 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 1.04 + + + + + + + + + 1.06 + + + + + + + + + 1.08 + + + + + + + + + 1.10 + + + + + + + + + 1.12 + + + + lift_drag (dimensionless) · higher is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + NACA0012_2D_Re1000_AOA40 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 1.25 + + + + + + + + + 1.30 + + + + + + + + + 1.35 + + + + + + + + + 1.40 + + + + + + + + + 1.45 + + + + lift_drag (dimensionless) · higher is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + NACA0012_2D_Re100_AOA20 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.936 + + + + + + + + + 0.938 + + + + + + + + + 0.940 + + + + + + + + + 0.942 + + + + + + + + + 0.944 + + + + + + + + + 0.946 + + + + lift_drag (dimensionless) · higher is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + NACA0012_2D_Re100_AOA40 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 3 + + + + + + + + + 4 + + + + + + + + + 5 + + + + + + + + + 6 + + + + nozzle_angle_mae (degrees) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Nozzle2D_coarse + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 3 + + + + + + + + + 4 + + + + + + + + + 5 + + + + + + + + + 6 + + + + nozzle_angle_mae (degrees) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Nozzle2D_fine + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Astra xhigh · Fluid-flow control · separate native metrics · 2/3 + + + 1 H100 × 48h research. Purple diamonds sit at 48h + actual submission-window duration; they are outside the research budget. + + + Every saved snapshot is shown; orange points reuse scores, including metadata-only changes. Already-evaluated duplicates stay blue. + + + Repository baselines use different training budgets. Reported specialists are not eligible shared models + + + Axes scale independently; nearby points can overlap. Steps follow submitted packages, including regressions. Beaker execution adaptations apply. + + + Lower-edge markers are not scores: gray ticks = awaiting evaluation; red × = evaluated but no numeric result for this metric. + + + + + + + + + + + + Evaluated snapshot + + + + + + + + + + + Duplicate snapshot · reused score + + + + + + + + + + + Reviewed +5m final · reused score + + + + + + Repository test baseline + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plots/fluid-flow-control-progression-3.png b/plots/fluid-flow-control-progression-3.png new file mode 100644 index 0000000000000000000000000000000000000000..b0a7417aa03e0c07a4289e964c2cc924c7acfcbd --- /dev/null +++ b/plots/fluid-flow-control-progression-3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0adc9a14ac3c75388f6926a20ec093dfec575e264eb984813f66fac5e9f26a5c +size 362879 diff --git a/plots/fluid-flow-control-progression-3.svg b/plots/fluid-flow-control-progression-3.svg new file mode 100644 index 0000000000000000000000000000000000000000..f96616ba5b980088e6f267ae42b076d8c3fb10d3 --- /dev/null +++ b/plots/fluid-flow-control-progression-3.svg @@ -0,0 +1,2559 @@ + + + + + + + + 2026-10-26T20:50:17.700208 + image/svg+xml + + + Matplotlib v3.6.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 3.0 + + + + + + + + + 3.2 + + + + + + + + + 3.4 + + + + + + + + + 3.6 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Pinball_2D_Re100 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 3 + + + + + + + + + 4 + + + + + + + + + 5 + + + + + + + + + 6 + + + + + + + + + 7 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Pinball_2D_Re150 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 2.0 + + + + + + + + + 2.5 + + + + + + + + + 3.0 + + + + + + + + + 3.5 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Pinball_2D_Re30 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 2.25 + + + + + + + + + 2.50 + + + + + + + + + 2.75 + + + + + + + + + 3.00 + + + + + + + + + 3.25 + + + + + + + + + 3.50 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Pinball_2D_Re75 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 3.0 + + + + + + + + + 3.2 + + + + + + + + + 3.4 + + + + + + + + + 3.6 + + + + + + + + + 3.8 + + + + + + + + + 4.0 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Pinball_3D_Re100 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.654 + + + + + + + + + 0.656 + + + + + + + + + 0.658 + + + + + + + + + 0.660 + + + + + + + + + 0.662 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + Sphere_3D_Re300 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 2.30 + + + + + + + + + 2.35 + + + + + + + + + 2.40 + + + + + + + + + 2.45 + + + + + + + + + 2.50 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final: no numeric result for this metric + + + SquareCylinder_2D_Re1000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 1.50 + + + + + + + + + 1.55 + + + + + + + + + 1.60 + + + + + + + + + 1.65 + + + + drag_cd (dimensionless) · lower is better + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 17 snapshots (11 measured, 6 reused) + + + Final +1m 47s · same as S017 + + + SquareCylinder_2D_Re200 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Astra xhigh · Fluid-flow control · separate native metrics · 3/3 + + + 1 H100 × 48h research. Purple diamonds sit at 48h + actual submission-window duration; they are outside the research budget. + + + Every saved snapshot is shown; orange points reuse scores, including metadata-only changes. Already-evaluated duplicates stay blue. + + + Repository baselines use different training budgets. Reported specialists are not eligible shared models + + + Axes scale independently; nearby points can overlap. Steps follow submitted packages, including regressions. Beaker execution adaptations apply. + + + Lower-edge markers are not scores: gray ticks = awaiting evaluation; red × = evaluated but no numeric result for this metric. + + + + + + + + + + + + Evaluated snapshot + + + + + + + + + + + Duplicate snapshot · reused score + + + + + + + + + + + Reviewed +5m final · reused score + + + + + + Repository test baseline + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plots/protein-design-progression.png b/plots/protein-design-progression.png new file mode 100644 index 0000000000000000000000000000000000000000..664e5d5736af99fa7e783fd7e7a976057ce97a15 --- /dev/null +++ b/plots/protein-design-progression.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b0c40c1743c668fa7207d448af4116e588b26636e7fea12d63f177b5ebbf31c +size 318254 diff --git a/plots/protein-design-progression.svg b/plots/protein-design-progression.svg new file mode 100644 index 0000000000000000000000000000000000000000..eaa7aef2ee23f9fde41b8357a73c6a2f7133489f --- /dev/null +++ b/plots/protein-design-progression.svg @@ -0,0 +1,1320 @@ + + + + + + + + 2026-10-26T20:50:19.193481 + image/svg+xml + + + Matplotlib v3.6.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + −0.04 + + + + + + + + + −0.02 + + + + + + + + + 0.00 + + + + + + + + + 0.02 + + + + + + + + + 0.04 + + + + higher is better + + + + + + + + + + 1/1 distinct · 1 snapshots (1 measured, 0 reused) + + + Final +1m 52s · same as S001 + + + unconditional_pass_rate + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + −0.04 + + + + + + + + + −0.02 + + + + + + + + + 0.00 + + + + + + + + + 0.02 + + + + + + + + + 0.04 + + + + higher is better + + + + + + + + + + 1/1 distinct · 1 snapshots (1 measured, 0 reused) + + + Final +1m 52s · same as S001 + + + unconditional_diversity + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + −0.04 + + + + + + + + + −0.02 + + + + + + + + + 0.00 + + + + + + + + + 0.02 + + + + + + + + + 0.04 + + + + higher is better + + + + + + + + + + 1/1 distinct · 1 snapshots (1 measured, 0 reused) + + + Final +1m 52s · same as S001 + + + sm_binder_pass_rate + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + −0.04 + + + + + + + + + −0.02 + + + + + + + + + 0.00 + + + + + + + + + 0.02 + + + + + + + + + 0.04 + + + + higher is better + + + + + + + + + + 1/1 distinct · 1 snapshots (1 measured, 0 reused) + + + Final +1m 52s · same as S001 + + + sm_binder_diversity + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + −0.04 + + + + + + + + + −0.02 + + + + + + + + + 0.00 + + + + + + + + + 0.02 + + + + + + + + + 0.04 + + + + higher is better + + + + + + + + + + 1/1 distinct · 1 snapshots (1 measured, 0 reused) + + + Final +1m 52s · same as S001 + + + ppi_binder_pass_rate + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + −0.04 + + + + + + + + + −0.02 + + + + + + + + + 0.00 + + + + + + + + + 0.02 + + + + + + + + + 0.04 + + + + higher is better + + + + + + + + + + 1/1 distinct · 1 snapshots (1 measured, 0 reused) + + + Final +1m 52s · same as S001 + + + ppi_binder_diversity + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.01275 + + + + + + + + + 0.01300 + + + + + + + + + 0.01325 + + + + + + + + + 0.01350 + + + + + + + + + 0.01375 + + + + + + + + + 0.01400 + + + + higher is better + + + + + + + + + + 1/1 distinct · 1 snapshots (1 measured, 0 reused) + + + Final +1m 52s · same as S001 + + + enzyme_pass_rate + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.116 + + + + + + + + + 0.118 + + + + + + + + + 0.120 + + + + + + + + + 0.122 + + + + + + + + + 0.124 + + + + + + + + + 0.126 + + + + + + + + + 0.128 + + + + higher is better + + + + + + + + + + 1/1 distinct · 1 snapshots (1 measured, 0 reused) + + + Final +1m 52s · same as S001 + + + enzyme_diversity + + + + + + + + + + + + + + + Astra xhigh · Protein design · separate native metrics + + + 1 H100 × 48h research. Purple diamonds sit at 48h + actual submission-window duration; they are outside the research budget. + + + Every saved snapshot is shown; orange points reuse scores, including metadata-only changes. Already-evaluated duplicates stay blue. + + + Repository baselines use different training budgets. Reported baseline uses a different design count + + + Axes scale independently; nearby points can overlap. Steps follow submitted packages, including regressions. Beaker execution adaptations apply. + + + Lower-edge markers are not scores: gray ticks = awaiting evaluation; red × = evaluated but no numeric result for this metric. + + + + + + + + + + + + Evaluated snapshot + + + + + + + + + + + Duplicate snapshot · reused score + + + + + + + + + + + Reviewed +5m final · reused score + + + + + + Repository test baseline + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plots/scalar-task-progression.png b/plots/scalar-task-progression.png new file mode 100644 index 0000000000000000000000000000000000000000..f5416e6b33d8be7e948272a445582a179cbb42ff --- /dev/null +++ b/plots/scalar-task-progression.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0a5bf12a0cc55c7c62359cd981f4f1ac587b78ab7012300a053026dd7ae4eec +size 489150 diff --git a/plots/scalar-task-progression.svg b/plots/scalar-task-progression.svg new file mode 100644 index 0000000000000000000000000000000000000000..a5a59f9009ab8e7d6b1fd440cc54a0db63c06e5b --- /dev/null +++ b/plots/scalar-task-progression.svg @@ -0,0 +1,4535 @@ + + + + + + + + 2026-10-26T20:50:12.203640 + image/svg+xml + + + Matplotlib v3.6.3, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.45 + + + + + + + + + 0.50 + + + + + + + + + 0.55 + + + + + + + + + 0.60 + + + + + + + + + 0.65 + + + + + + + + + 0.70 + + + + Success fraction + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 7/7 distinct · 7 snapshots (7 measured, 0 reused) + + + Final +2m 44s · same as S007 + + + + + + Shape VC 0.486 + + + Tokamak magnetic control + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.24 + + + + + + + + + 0.26 + + + + + + + + + 0.28 + + + + + + + + + 0.30 + + + + Panel recall at top 5% risk + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 13/13 distinct · 13 snapshots (13 measured, 0 reused) + + + Final +3m 10s · same as S013 + + + + + + Temporal GRU 0.236 + + + Disease progression + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.400 + + + + + + + + + 0.425 + + + + + + + + + 0.450 + + + + + + + + + 0.475 + + + + + + + + + 0.500 + + + + + + + + + 0.525 + + + + Mean accuracy / MAE-skill reward + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11/11 distinct · 11 snapshots (11 measured, 0 reused) + + + Final +1m 07s · same as S011 + + + + + + No matching combined test baseline + + + Earth observation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.10 + + + + + + + + + 0.15 + + + + + + + + + 0.20 + + + + + + + + + 0.25 + + + + + + + + + 0.30 + + + + Crystal potential reward + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 3/3 distinct · 23 snapshots (4 measured, 19 reused) + + + Final +2m 01s · same as S023 + + + + + + No reported scratch test baseline + + + Atomistic materials + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.00 + + + + + + + + + 0.05 + + + + + + + + + 0.10 + + + + + + + + + 0.15 + + + + + + + + + 0.20 + + + + Benchmark reward + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 17/17 distinct · 18 snapshots (18 measured, 0 reused) + + + Final +4m 09s · same as S018 + + + + + + Mean delta 0.103 + + + Single-cell perturbation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.740 + + + + + + + + + 0.745 + + + + + + + + + 0.750 + + + + + + + + + 0.755 + + + + + + + + + 0.760 + + + + + + + + + 0.765 + + + + + + + + + 0.770 + + + + Benchmark reward + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 45/45 distinct · 47 snapshots (45 measured, 2 reused) + + + Final +1m 15s · same as S047 + + + + + + AlphaQubit reproduction 0.756 + + + Surface-code decoding + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.0 + + + + + + + + + 0.2 + + + + + + + + + 0.4 + + + + + + + + + 0.6 + + + + Hit rate at 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 21/21 distinct · 85 snapshots (66 measured, 19 reused) + + + Final +2m 34s · same as S085 + + + + + + GLACIER · 8-seed mean 0.405 + + + Mass spectrometry + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.0000 + + + + + + + + + 0.0002 + + + + + + + + + 0.0004 + + + + + + + + + 0.0006 + + + + + + + + + 0.0008 + + + + Normalized expected run length (nERL) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 7/7 distinct · 7 snapshots (7 measured, 0 reused) + + + Final +1m 53s · same as S007 + + + + + + Baseline reports development scores only + + + Fruit-fly reconstruction + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1m + + + + + + 15m + + + + + + 1h + + + + + + 4h + + + + + + 12h + + + + + + 48h + + + + Research + submission time · log scale + + + + + + + + + + 0.45 + + + + + + + + + 0.50 + + + + + + + + + 0.55 + + + + + + + + + 0.60 + + + + + + + + + 0.65 + + + + + + + + + 0.70 + + + + Mean of 11 task rewards + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 58/58 distinct · 63 snapshots (58 measured, 5 reused) + + + Final +1m 42s · same as S063 + + + + + + Starter · 2-seed mean 0.673 + + + Protein sequence + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Astra xhigh · scalar task scores + + + 1 H100 × 48h research. Purple diamonds sit at 48h + actual submission-window duration; they are outside the research budget. + + + Every saved snapshot is shown; orange points reuse scores, including metadata-only changes. Already-evaluated duplicates stay blue. + + + Repository baselines use different training budgets. + + + Axes scale independently; nearby points can overlap. Steps follow submitted packages, including regressions. Beaker execution adaptations apply. + + + Lower-edge markers are not scores: gray ticks = awaiting evaluation; red × = evaluated but no numeric result for this metric. + + + + + + + + + + + + Evaluated snapshot + + + + + + + + + + + Duplicate snapshot · reused score + + + + + + + + + + + Reviewed +5m final · reused score + + + + + + Repository test baseline + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/reproduction/files/01/01450c9a5cfd39fb453742feae95510f9d15c90347f44cb55a09d59558d7d234/test.sh b/reproduction/files/01/01450c9a5cfd39fb453742feae95510f9d15c90347f44cb55a09d59558d7d234/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81183a60965d0b0b2a489cde59c5eb58b7c60870 --- /dev/null +++ b/reproduction/files/01/01450c9a5cfd39fb453742feae95510f9d15c90347f44cb55a09d59558d7d234/test.sh @@ -0,0 +1,17 @@ +#!/bin/bash +set -euo pipefail +OLMO_TEST_DIR=$(cd "$(dirname "$0")" && pwd) +# As in the weather verifier: the NVIDIA container runtime bind-mounts entries under +# /proc/driver/nvidia, and the kernel then refuses the fresh procfs of the model's user namespace +# ("Can't mount proc on /newroot/proc"). Detach them; the GPUs stay usable through /dev/nvidia*. +for mount in $(awk '$5 ~ /^\/proc\/driver\/nvidia/ {print $5}' /proc/self/mountinfo | sort -r); do + umount "${mount}" 2>/dev/null || echo "warning: could not detach ${mount}; the sandbox may fail" >&2 +done +# Docker exposes the allocated GPUs without setting CUDA_VISIBLE_DEVICES; name them explicitly. +if [[ -z ${CUDA_VISIBLE_DEVICES:-} ]] && command -v nvidia-smi >/dev/null; then + CUDA_VISIBLE_DEVICES=$(nvidia-smi --query-gpu=uuid --format=csv,noheader | paste -sd,) + export CUDA_VISIBLE_DEVICES +fi +OLMO_PROBES=${OLMO_PROBES:-$OLMO_TEST_DIR/../environment/evaluation/probes.py} +[[ -f "$OLMO_PROBES" ]] || OLMO_PROBES=/evaluation/probes.py +python "$OLMO_TEST_DIR/grade.py" --model "${OLMO_MODEL:-/workspace/submission}" --data "${OLMO_EVAL_DATA:-/data/eval}" --output "${OLMO_VERIFIER_OUTPUT:-/logs/verifier}" --probes "$OLMO_PROBES" diff --git a/reproduction/files/03/036c86f2674d84b404ff67c98bff5adf186dc51edffdbb4dbaa7843a845f61dd/run_unit_tests.sh b/reproduction/files/03/036c86f2674d84b404ff67c98bff5adf186dc51edffdbb4dbaa7843a845f61dd/run_unit_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..752360185656658d27d12d121400cec6b5f268bd --- /dev/null +++ b/reproduction/files/03/036c86f2674d84b404ff67c98bff5adf186dc51edffdbb4dbaa7843a845f61dd/run_unit_tests.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +exec python3 -m unittest -v test_task diff --git a/reproduction/files/03/03f3570a69ab4dabe59424d684b93b298f68b7ab981a1fc9148a08c34cc8d4e5/test_task.py b/reproduction/files/03/03f3570a69ab4dabe59424d684b93b298f68b7ab981a1fc9148a08c34cc8d4e5/test_task.py new file mode 100644 index 0000000000000000000000000000000000000000..19d1445e67f2ce884352dcb724c5a89ba9be578c --- /dev/null +++ b/reproduction/files/03/03f3570a69ab4dabe59424d684b93b298f68b7ab981a1fc9148a08c34cc8d4e5/test_task.py @@ -0,0 +1,403 @@ +"""CPU-only interface tests. Fake dynamics below are NOT HydroGym benchmark cases.""" + +import copy +import hashlib +import importlib.util +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import textwrap +import unittest +from unittest.mock import patch + + +TASK = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(TASK / "environment/evaluation")) +import evaluate +import run_maia +from protocol import InfrastructureError, Policy, PolicyError, replay_episode + +spec = importlib.util.spec_from_file_location("hydro_materialize", TASK / "environment/data/materialize.py") +materialize = importlib.util.module_from_spec(spec) +spec.loader.exec_module(materialize) + + +def fixture_suite(): + suite = json.loads((TASK / "environment/data/suite.example.json").read_text()) + # A test-only protocol fixture, never written to production data. + suite.update(status="validated", release_id="synthetic-interface-test-only") + suite["coverage"]["status"] = "complete" + suite["cases"][0].update(id="fixture-a", environment="fixture-a", horizon=3, + observation_size=1, action_size=1) + suite["cases"][0]["baseline"] = {"algorithm": "PPO", "anchor_description": "Synthetic zero action", "anchor_return": -3.0, "reference_return": 0.0} + second = copy.deepcopy(suite["cases"][0]) + second.update(id="fixture-b", environment="fixture-b") + suite["cases"].append(second) + return suite + + +class FakeEnv: + """Toy scalar feedback problem used only to check who computes the reward.""" + class Space: + shape = (1,) + low = [-1.0] + high = [1.0] + observation_space = action_space = Space() + + def reset(self, seed=None): + self.state = 1.0 + self.steps = 0 + return [self.state], {} + + def step(self, action): + self.steps += 1 + self.state += action[0] + return [self.state], -abs(self.state), False, self.steps >= 3, {"state": self.state} + + +class TaskTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + + def package(self, action="[-request['observation'][0]]", altered=""): + package = self.root / "package" + package.mkdir(exist_ok=True) + (package / "README.md").write_text("Synthetic protocol fixture, not a CFD controller.\n") + (package / "infer.sh").write_text( + f'#!/bin/sh\nexec "{sys.executable}" "$(dirname "$0")/policy.py"\n') + (package / "policy.py").write_text(textwrap.dedent(f""" + import json,sys,time + for line in sys.stdin: + request=json.loads(line) + reply={{'request_id':request['request_id']}} + if request['op']=='reset': reply['ready']=True + elif request['op']=='act': + {altered or 'pass'} + reply['action']={action} + else: + reply['closed']=True + print(json.dumps(reply),flush=True) + break + print(json.dumps(reply),flush=True) + """)) + return package + + def data(self, suite=None): + suite = suite or fixture_suite() + root = self.root / "data" + root.mkdir() + release = {"release_id": "synthetic-interface-test-only", + "cases": fixture_suite()["cases"], + "test": {"case_ids": ["fixture-a", "fixture-b"]}} + # Replace only the verifier-owned fixture identity in these synthetic + # protocol tests. Real 47-case selection/binding is tested separately. + def fixture_release(path=None): + return json.loads(Path(path).read_text()) if path is not None else release + mocked = patch.object(evaluate, "load_release", side_effect=fixture_release) + mocked.start() + self.addCleanup(mocked.stop) + suite.update(data_release_id=release["release_id"], + data_release_sha256=evaluate.data_release_hash(release)) + (root / "release.json").write_text(json.dumps(release)) + (root / "suite.json").write_text(json.dumps(suite)) + directories = [] + for case in suite["cases"]: + folder = root / "environments" / case["environment"] + folder.mkdir(parents=True, exist_ok=True) + (folder / "environment_config.yaml").write_text("test-only: true\n") + directories.append(case["environment"]) + (root / "materialized.json").write_text(json.dumps({ + "revision": evaluate.SOURCE_REVISION, "verified_directories": directories, + "data_release_id": release["release_id"], + "data_release_sha256": evaluate.data_release_hash(release)})) + return root + + def test_missing_manifest_and_binding_cannot_enable_legacy_subset(self): + data = self.data() + (data / "release.json").unlink() + suite = json.loads((data / "suite.json").read_text()) + suite.pop("data_release_id") + suite.pop("data_release_sha256") + (data / "suite.json").write_text(json.dumps(suite)) + with self.assertRaisesRegex(InfrastructureError, "Incomplete evaluation release"): + evaluate.preflight(data, require_reference=False) + + def test_receipt_must_match_current_data_release(self): + data = self.data() + receipt = json.loads((data / "materialized.json").read_text()) + receipt["data_release_id"] = "an-old-data-release" + (data / "materialized.json").write_text(json.dumps(receipt)) + with self.assertRaisesRegex(InfrastructureError, "not been materialized"): + evaluate.preflight(data, require_reference=False) + + def policy(self, package, timeout=2): + policy = Policy(package, self.root / "policy.log", timeout=timeout) + self.addCleanup(policy.abort) + policy.reset({"environment": "unseen-id"}, [1], [1], [-1.0], [1.0]) + return policy + + def test_feedback_and_episode_reset(self): + policy = self.policy(self.package()) + case = fixture_suite()["cases"][0] + for seed in (83, 12): + result = replay_episode(FakeEnv(), policy, case, seed) + self.assertEqual(result["return"], 0.0) + self.assertEqual(result["steps"], 3) + policy.close() + + def test_bad_actions(self): + for value in ("[]", "[True]", "[float('nan')]", "[2.0]", "['0']"): + with self.subTest(value=value): + policy = self.policy(self.package(action=value)) + with self.assertRaises(PolicyError): + policy.act([1.0]) + policy.abort() + + def test_wrong_id(self): + policy = self.policy(self.package(altered="reply['request_id']='wrong'")) + with self.assertRaises(PolicyError): + policy.act([1.0]) + + def test_timeout(self): + policy = self.policy(self.package(altered="time.sleep(2)"), timeout=0.2) + with self.assertRaisesRegex(PolicyError, "timeout"): + policy.act([1.0]) + + def test_invalid_observation_is_infrastructure(self): + policy = self.policy(self.package()) + for observation in ([float("nan")], [], [1.0, 2.0]): + with self.assertRaises(InfrastructureError): + policy.act(observation) + + def test_default_example_cannot_be_graded(self): + example = json.loads((TASK / "environment/data/suite.example.json").read_text()) + with self.assertRaises(InfrastructureError): + evaluate.validate_suite(example) + + def test_legacy_cache_cannot_shadow_release(self): + case = fixture_suite()["cases"][0] + data = self.data() + fake_home = self.root / "legacy-home" + with patch.object(run_maia.Path, "home", return_value=fake_home): + run_maia.check_native_cache(case, data) + cached = fake_home / ".cache" / "maiagym" / case["environment"] + cached.mkdir(parents=True) + with self.assertRaisesRegex(InfrastructureError, "shadow"): + run_maia.check_native_cache(case, data) + + def test_native_reward_and_horizon_errors(self): + case = fixture_suite()["cases"][0] + policy = self.policy(self.package()) + class BrokenReward(FakeEnv): + def step(self, action): + return [0.0], float("nan"), False, True, {} + # A nonfinite reward after the policy acted is a diverged simulation: the case fails. + with self.assertRaisesRegex(PolicyError, "diverged.*finite scalar"): + replay_episode(BrokenReward(), policy, case, 1) + with self.assertRaisesRegex(InfrastructureError, "horizon"): + replay_episode(FakeEnv(), policy, dict(case, horizon=2), 1) + + def test_reject_bad_suite(self): + transforms = [ + lambda s: s.update(cases=[]), + lambda s: s["cases"].append(copy.deepcopy(s["cases"][0])), + lambda s: s["cases"][0].update(backend="nek"), + lambda s: s["cases"][0].update(id="../escape"), + lambda s: s["cases"][0].update(horizon=0), + lambda s: s["cases"][0].update(seeds=[1, 1]), + lambda s: s["cases"][0]["baseline"].update(reference_return=None), + lambda s: s["cases"][0]["baseline"].update(reference_return=-4.0), + lambda s: s["cases"][0]["env_kwargs"].update(configuration_file="/tmp/changed"), + lambda s: s["cases"][0]["env_kwargs"].update(obs_normalization_strategy="probewise_mean_std"), + lambda s: s["cases"][0]["env_kwargs"].update(obs_normalization_strategy="customized", obs_loc=[0.0], obs_scale=[0.0]), + ] + for change in transforms: + suite = fixture_suite() + change(suite) + with self.assertRaises(InfrastructureError): + evaluate.validate_suite(suite) + + def test_incomplete_release_does_not_score_missing_submission(self): + output = self.root / "out" + with self.assertRaises(InfrastructureError): + evaluate.evaluate(self.root / "missing-data", self.root / "missing-model", output) + self.assertFalse((output / "reward.json").exists()) + self.assertTrue((output / "error.json").exists()) + + def test_missing_submission_scores_zero_only_after_preflight(self): + output = self.root / "out" + evaluate.evaluate(self.data(), self.root / "missing-model", output) + self.assertEqual(json.loads((output / "reward.json").read_text())["score"], 0) + + def test_relocation_and_scoring(self): + package = self.package() + def runner(case, suite, data, relocated, output): + self.assertNotEqual(relocated, package) + policy = Policy(relocated, output.with_suffix(".policy.log"), timeout=2) + try: + episodes = [replay_episode(FakeEnv(), policy, case, seed) for seed in case["seeds"]] + policy.close() + finally: + policy.abort() + return {"status": "ok", "episodes": episodes} + output = self.root / "out" + evaluate.evaluate(self.data(), package, output, runner=runner) + self.assertEqual(json.loads((output / "reward.json").read_text()), {"score": 1.0, "case_coverage": 1.0}) + + def test_policy_failures_remain_in_denominator(self): + suite = fixture_suite() + results = {"fixture-a": {"status": "policy_error"}, "fixture-b": { + "status": "ok", "episodes": [{"seed": seed, "return": 0.0} for seed in suite["cases"][1]["seeds"]]}} + self.assertEqual(evaluate.aggregate(suite, results), {"score": 0.5, "case_coverage": 0.5}) + del results["fixture-a"] + with self.assertRaises(InfrastructureError): + evaluate.aggregate(suite, results) + + def test_raw_replay_all_cases_without_reference_scores(self): + suite = fixture_suite() + for case in suite["cases"]: + case.pop("baseline") + with self.assertRaises(InfrastructureError): + evaluate.validate_suite(suite) + evaluate.validate_suite(suite, require_reference=False) + seen = [] + package = self.package() + package_digests = [] + def runner(case, release, data, relocated, output): + seen.append(case["id"]) + self.assertNotEqual(relocated, package) + package_digests.append(evaluate.package_hash(relocated)) + policy = Policy(relocated, output.with_suffix(".policy.log"), timeout=2) + try: + episodes = [replay_episode(FakeEnv(), policy, case, seed) for seed in case["seeds"]] + policy.close() + finally: + policy.abort() + return {"status": "ok", "episodes": episodes} + output = self.root / "raw" + evaluate.evaluate(self.data(suite), package, output, runner=runner, raw_only=True) + result = json.loads((output / "results.json").read_text()) + self.assertEqual(seen, ["fixture-a", "fixture-b"]) + self.assertEqual(len(set(package_digests)), 1) + self.assertEqual(result["suite_sha256"], evaluate.suite_hash(suite)) + self.assertEqual(result["evaluation_mode"], "native-returns") + self.assertEqual(result["case_coverage"], 1.0) + self.assertTrue(all(c["mean_return"] == 0.0 for c in result["cases"].values())) + self.assertTrue(all("score" not in c for c in result["cases"].values())) + self.assertFalse((output / "reward.json").exists()) + + def test_raw_mode_does_not_bypass_physics_or_coverage(self): + for change in (lambda s: s.update(status="draft"), + lambda s: s["coverage"].update(status="pending"), + lambda s: s["cases"][0].update(backend="jax"), + lambda s: s["cases"][0].update(horizon=0), + lambda s: s["cases"][0]["env_kwargs"].update( + obs_normalization_strategy="probewise_mean_std")): + suite = fixture_suite() + change(suite) + with self.assertRaises(InfrastructureError): + evaluate.validate_suite(suite, require_reference=False) + with self.assertRaisesRegex(InfrastructureError, "coverage"): + evaluate.aggregate(fixture_suite(), {}, normalize=False) + + def test_raw_missing_model_does_not_fabricate_a_return(self): + output = self.root / "raw-missing" + evaluate.evaluate(self.data(), self.root / "missing", output, raw_only=True) + result = json.loads((output / "results.json").read_text()) + self.assertEqual(set(result["cases"]), {"fixture-a", "fixture-b"}) + self.assertTrue(all("return" not in c for c in result["cases"].values())) + self.assertFalse((output / "reward.json").exists()) + + def test_raw_policy_error_is_not_silently_omitted(self): + suite = fixture_suite() + results = {"fixture-a": {"status": "policy_error"}, "fixture-b": { + "status": "ok", "episodes": [{"seed": seed, "return": -2.0} + for seed in suite["cases"][1]["seeds"]]}} + self.assertEqual(evaluate.aggregate(suite, results, normalize=False), {"case_coverage": 0.5}) + self.assertIsNone(results["fixture-a"]["mean_return"]) + self.assertEqual(results["fixture-b"]["mean_return"], -2.0) + + def test_release_mutation_during_replay_is_not_a_score(self): + data = self.data() + def runner(case, suite, data, relocated, output): + changed = json.loads((data / "suite.json").read_text()) + changed["policy_timeout_sec"] += 1 + (data / "suite.json").write_text(json.dumps(changed)) + return {"status": "policy_error"} + output = self.root / "changed-release" + with self.assertRaisesRegex(InfrastructureError, "release changed"): + evaluate.evaluate(data, self.package(), output, runner=runner) + self.assertFalse((output / "reward.json").exists()) + + def test_negative_gains_remain_visible(self): + suite = fixture_suite() + results = {c["id"]: {"status": "ok", "episodes": [{"seed": seed, "return": -6.0} for seed in c["seeds"]]} + for c in suite["cases"]} + self.assertEqual(evaluate.aggregate(suite, results)["score"], 0) + self.assertEqual(results["fixture-a"]["normalized_gain"], -1) + + def test_mutation_and_solver_error_are_not_scores(self): + for mode in ("mutation", "solver"): + with self.subTest(mode=mode): + def runner(case, suite, data, package, output): + if mode == "solver": + raise InfrastructureError("solver failed") + (package / "README.md").write_text("mutated") + return {"status": "policy_error"} + data = self.root / "data" + if not data.exists(): + data = self.data() + output = self.root / mode + with self.assertRaises(InfrastructureError): + evaluate.evaluate(data, self.package(), output, runner=runner) + self.assertFalse((output / "reward.json").exists()) + + def test_escaping_package_symlink(self): + package = self.package() + (package / "escape").symlink_to(self.root) + with self.assertRaises(PolicyError): + evaluate.package_hash(package) + + def test_stale_output_rejected(self): + output = self.root / "out" + output.mkdir() + (output / "reward.json").write_text('{"score":123}') + with self.assertRaises(InfrastructureError): + evaluate.evaluate(self.data(), self.package(), output) + + def test_materialize_plan_downloads_nothing(self): + destination = self.root / "do-not-create" + result = subprocess.run([sys.executable, str(materialize.CATALOG.with_name("materialize.py")), + str(destination), "--case", "Cylinder_2D_Re200"], capture_output=True, text=True, check=True) + plan = json.loads(result.stdout) + self.assertEqual(plan["mode"], "plan") + self.assertEqual(len(plan["download_commands"]), 1) + self.assertFalse(destination.exists()) + + def test_resource_checksums_and_truncation(self): + path = self.root / "asset" + path.write_bytes(b"verified") + item = {"rfilename": "asset", "size": 8, + "lfs": {"sha256": hashlib.sha256(b"verified").hexdigest()}} + materialize.verify_files(self.root, [item]) + path.write_bytes(b"modified") + with self.assertRaises(ValueError): + materialize.verify_files(self.root, [item]) + path.write_bytes(b"v") + with self.assertRaises(ValueError): + materialize.verify_files(self.root, [item]) + + def test_catalog_pins_and_inventory_is_not_suite(self): + catalog = json.loads(materialize.CATALOG.read_text()) + self.assertEqual(catalog["revision"], evaluate.SOURCE_REVISION) + self.assertEqual(len(catalog["directories"]), 89) + self.assertEqual(sum(c["has_environment_config"] for c in catalog["directories"]), 66) + self.assertNotIn("cases", catalog) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/04/0429ac4b74abdd4ed14c76efd89f119299132ba6d4fa03e1eb242e4a16df3616/container_smoke.py b/reproduction/files/04/0429ac4b74abdd4ed14c76efd89f119299132ba6d4fa03e1eb242e4a16df3616/container_smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..3ba149131767e8103549b2de0d518526d54d8d1f --- /dev/null +++ b/reproduction/files/04/0429ac4b74abdd4ed14c76efd89f119299132ba6d4fa03e1eb242e4a16df3616/container_smoke.py @@ -0,0 +1,282 @@ +#!/usr/bin/env python3 +"""Exercise actual Docker role separation with tiny synthetic inputs, not accuracy. + +Host orchestration uses only Python's standard library. Fixture generation runs +inside the already-built verifier image, whose pinned runtime supplies NumPy. +All three cases use the real supervisor, grader, and Compose topology. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import time +import uuid +from typing import Any + +TASK = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" if (Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit").is_dir() else Path(__file__).resolve().parents[1] + +# An executable without a .sh suffix also tests frozen-artifact execute bits. +DECODER = '''#!/opt/qec/.venv/bin/python +from pathlib import Path +import errno +import json +import os +import socket +import sys +import numpy as np + +assert os.getuid() == os.geteuid() == 10001, "inference must run as isolated UID" +assert os.getgid() == os.getegid() == 10001 +assert {name for _, name in socket.if_nameindex()} == {"lo"}, "network namespace is not offline" +assert not Path("/private").exists(), "grader labels leaked into inference container" +try: + list(Path("/sealed").iterdir()) +except PermissionError: + pass +else: + raise AssertionError("inference can read the trusted sealed volume") +status = Path("/proc/self/status").read_text() +assert any(line.split() == ["NoNewPrivs:", "1"] for line in status.splitlines()) +root = Path(__file__).resolve().parents[1] +assert root != Path("/workspace/submission"), "artifact was not relocated" +for target in [root / "model_config.json", Path("/opt/task/qecbench/scoring.py"), + Path("/benchmark/manifest.json"), Path("/logs/verifier/forged-reward.json"), + Path("/workspace/submission/forged-file")]: + try: + with target.open("ab"): + pass + except OSError as error: + assert error.errno in (errno.EACCES, errno.EPERM, errno.EROFS), (target, error) + else: + raise AssertionError(f"inference can modify protected path: {target}") +inputs, output = map(Path, sys.argv[1:]) +manifest = json.loads((inputs / "manifest.json").read_text()) +probability = json.loads((root / "weights/constant.json").read_text())["probability"] +assert probability == 0.1 +for condition in manifest["conditions"]: + with np.load(inputs / condition["arrays"], allow_pickle=False) as source: + assert set(source.files) == {"sample_ids", "detectors"}, "labels leaked into inference input" + ids = source["sample_ids"][::-1] + np.savez(output / (condition["name"] + ".npz"), sample_ids=ids, + probabilities=np.full(len(ids), probability, dtype=np.float32)) +print(json.dumps({"container_security_probe": "passed", "uid": os.getuid(), + "conditions": len(manifest["conditions"]), "probability": probability, + "network_interfaces": [name for _, name in socket.if_nameindex()], + "private_labels_absent": True, "sealed_volume_inaccessible": True, + "protected_paths_not_writable": True, "artifact_relocated": True, + "extensionless_executable_ran": True}), flush=True) +''' + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def write_json(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n") + + +def prepare(root: Path) -> None: + """Create unmistakably synthetic public inputs and separately held labels.""" + import numpy as np + + sys.path.insert(0, str(PROJECT)) + from baselines.alphaqubit_artifact import EXPECTED_GROUPS + from qecbench.data import SCHEMA + + inputs, labels = root / "data/verifier", root / "labels" + rows, target_rows = [], [] + for group in EXPECTED_GROUPS: + distance, basis = int(group[1]), group[4] + center = group.split("center_")[1] + for rounds in range(1, 26, 2): + name = f"surface_code_b{basis}_d{distance}_r{rounds:02}_center_{center}" + folder = inputs / "conditions" / name + folder.mkdir(parents=True) + ids = np.array([1017, 5, 991, 70], dtype=np.uint64) + np.uint64(len(rows) * 10000) + packed = np.zeros((4, (rounds * (distance ** 2 - 1) + 7) // 8), dtype=np.uint8) + np.savez(folder / "arrays.npz", sample_ids=ids, detectors=packed) + # The constant decoder does not parse circuits; still provide a valid + # Stim detector-count fixture, never an actual experimental circuit. + (folder / "circuit_ideal.stim").write_text( + "# Synthetic container plumbing fixture, not a physical experiment\nR 0\nM 0\n" + + "DETECTOR rec[-1]\n" * (rounds * (distance ** 2 - 1)) + + "OBSERVABLE_INCLUDE(0) rec[-1]\n" + ) + label_path = labels / "conditions" / f"{name}.npz" + label_path.parent.mkdir(parents=True, exist_ok=True) + np.savez(label_path, sample_ids=ids, labels=np.array([0, 0, 0, 1], dtype=np.uint8)) + rows.append({"name": name, "group": group, "distance": distance, "basis": basis, + "rounds": rounds, "shots": 4, "num_detectors": rounds * (distance ** 2 - 1), + "arrays": f"conditions/{name}/arrays.npz", "arrays_sha256": sha256(folder / "arrays.npz"), + "circuit": f"conditions/{name}/circuit_ideal.stim", "circuit_sha256": sha256(folder / "circuit_ideal.stim")}) + target_rows.append({"name": name, "shots": 4, "arrays": f"conditions/{name}.npz", "arrays_sha256": sha256(label_path)}) + write_json(inputs / "manifest.json", {"schema": SCHEMA, "split": "test", "synthetic_smoke_only": True, + "shots": 520, "conditions": list(reversed(rows))}) + write_json(labels / "manifest.json", {"schema": "surface-code-decoding-labels/v1", + "synthetic_smoke_only": True, "input_manifest_sha256": sha256(inputs / "manifest.json"), "conditions": target_rows}) + submission = root / "submission-valid" + (submission / "bin").mkdir(parents=True) + (submission / "bin/decoder").write_text(DECODER) + (submission / "bin/decoder").chmod(0o755) + (submission / "infer.sh").write_text('#!/usr/bin/env bash\nset -euo pipefail\nROOT="$(cd -- "$(dirname -- "$0")" && pwd)"\nexec "$ROOT/bin/decoder" "$1" "$2"\n') + (submission / "infer.sh").chmod(0o755) + (submission / "README.md").write_text("Synthetic constant-decoder container smoke. This artifact is not a scientific reference.\n") + (submission / "requirements.lock").write_text("Uses the verifier image's pinned NumPy runtime; no additional packages.\n") + write_json(submission / "weights/constant.json", {"probability": 0.1}) + write_json(submission / "model_config.json", {"model": "constant Bernoulli probability", "weights": "weights/constant.json"}) + write_json(submission / "training_provenance.json", {"purpose": "synthetic container security smoke only", + "fit": "Maximum likelihood on nine synthetic negative and one synthetic positive observation", "scientific_accuracy_evidence": False}) + write_json(submission / "model_manifest.json", {"schema": "surface-code-decoding-model/v1", + "checkpoints": [{"path": "weights/constant.json", "sha256": sha256(submission / "weights/constant.json")}], + "model_config": "model_config.json", "training_provenance": "training_provenance.json"}) + shutil.copytree(submission, root / "submission-invalid") + (root / "submission-invalid/model_manifest.json").write_text("[]\n") + (root / "missing-labels").mkdir() + write_json(root / "fixture.json", {"synthetic_smoke_only": True, "conditions": 130, "shots": 520, + "expected_valid_performance": 0.75, "source": "deterministic synthetic fixture; no downloaded scientific data"}) + + +def command(args: list[str], *, cwd: Path | None = None, env: dict[str, str] | None = None, + timeout: int = 600, check: bool = True) -> subprocess.CompletedProcess[str]: + print("+ " + " ".join(args), flush=True) + result = subprocess.run(args, cwd=cwd, env=env, text=True, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, timeout=timeout) + if result.stdout: + print(result.stdout, end="", flush=True) + if check and result.returncode: + raise subprocess.CalledProcessError(result.returncode, args, output=result.stdout) + return result + + +def collect_reports(container: str, destination: Path) -> None: + """Copy individual evidence files without exporting the protected artifact. + + Recursively copying /logs/verifier also exports the frozen 0555 submission + tree. Docker then cannot create its children as the unprivileged host user. + Keep those security permissions intact and request only reviewable files. + """ + for relative in ("report.json", "reward.json", "inference/inference.log"): + target = destination / relative + target.parent.mkdir(parents=True, exist_ok=True) + result = command(["docker", "cp", f"{container}:/logs/verifier/{relative}", str(target)], check=False) + if result.returncode: + # An infrastructure failure must have no reward; an invalid + # manifest has no inference log. Other copy errors remain errors. + missing = "Could not find the file" in result.stdout + if relative != "report.json" and missing: + continue + raise RuntimeError(f"Cannot collect {relative} from {container}: {result.stdout.strip()}") + + +def case_run(case: str, fixture: Path, output: Path, image: str) -> dict[str, Any]: + """Run a fresh main/grader pair and private sealed volume per scenario.""" + project = "qec-smoke-" + uuid.uuid4().hex[:12] + container = project + "-inference" + case_output = output / case + case_output.mkdir(parents=True) + submission = fixture / ("submission-invalid" if case == "invalid-submission" else "submission-valid") + labels = fixture / ("missing-labels" if case == "missing-labels" else "labels") + override = fixture / f"override-{case}.json" + write_json(override, {"services": { + "main": {"image": image, "cpus": 2, "mem_limit": "4g", "shm_size": "256m", + "volumes": [{"type": "bind", "source": str(submission), "target": "/workspace/submission", + "read_only": True, "bind": {"create_host_path": False}}]}, + "grader": {"image": image, "cpus": 2, "mem_limit": "4g", + "command": ["python", "/opt/task/tests/grader.py", "--wait-seconds", "180"]}}}) + env = dict(os.environ, TASK_DATA_DIR=str(fixture / "data"), TASK_PRIVATE_DIR=str(labels)) + compose = ["docker", "compose", "--project-name", project, "-f", str(TASK / "tests/docker-compose.yaml"), + "-f", str(TASK / "tests/docker-compose.cpu-smoke.yaml"), "-f", str(override)] + # Check the actual Compose merge: CI must not silently request a GPU. + resolved = json.loads(command(compose + ["config", "--format", "json"], env=env).stdout) + for service in resolved["services"].values(): + assert not service.get("deploy", {}).get("resources", {}).get("reservations", {}).get("devices") + assert service["network_mode"] == "none" + run: subprocess.CompletedProcess[str] | None = None + try: + command(compose + ["up", "-d", "--no-build", "grader"], env=env) + run = command(compose + ["run", "--no-deps", "--name", container, "-e", "QEC_INFERENCE_TIMEOUT_SECONDS=60", + "main", "/opt/task/tests/test.sh"], env=env, timeout=420, check=False) + (case_output / "supervisor.log").write_text(run.stdout) + collect_reports(container, case_output) + grader_logs = command(compose + ["logs", "--no-color", "grader"], env=env, check=False) + (case_output / "grader.log").write_text(grader_logs.stdout) + report_path = case_output / "report.json" + if not report_path.is_file(): + raise AssertionError(f"{case}: supervisor did not publish a report; see {case_output}") + report = json.loads(report_path.read_text()) + reward_path = case_output / "reward.json" + config = json.loads((PROJECT / "score_config.json").read_text()) + if case == "valid": + assert run.returncode == 0, run.stdout + assert report["status"] == "valid" and report["model_quality_measured"] is True + assert report["shots"] == 520 and report["conditions"] == 130 + assert report["performance"] == 0.75 and report["balanced_logical_failure"] == 0.25 + expected = max(0.0, (0.75 - config["lower_bound"]) / (config["upper_bound"] - config["lower_bound"])) + assert math.isclose(report["score"], expected, rel_tol=0, abs_tol=1e-12) + assert json.loads(reward_path.read_text())["reward"] == report["performance"] + inference_log = (case_output / "inference/inference.log").read_text() + probes = [json.loads(line) for line in inference_log.splitlines() if line.startswith('{"container_security_probe"')] + assert len(probes) == 1 and probes[0]["container_security_probe"] == "passed" + elif case == "invalid-submission": + assert run.returncode == 0 and report["status"] == "invalid_submission" + assert report["model_quality_measured"] is False and report["performance"] is None + assert json.loads(reward_path.read_text()) == {"reward": 0.0} + else: + assert run.returncode != 0 and report["status"] == "infrastructure_error" + assert report["model_quality_measured"] is False and not reward_path.exists() + return {"case": case, "status": "passed", "verifier_status": report["status"], + "supervisor_exit_code": run.returncode, "score": report.get("score"), + "scientific_accuracy_evidence": False} + finally: + command(["docker", "rm", "-f", container], check=False) + command(compose + ["down", "--volumes", "--remove-orphans"], env=env, check=False) + + +def orchestrate(args: argparse.Namespace) -> None: + started = time.monotonic() + args.output.mkdir(parents=True, exist_ok=True) + command(["docker", "version"]) + command(["docker", "compose", "version"]) + if args.build: + command(["docker", "build", "-t", args.image, "-f", str(TASK / "tests/Dockerfile"), str(TASK)], timeout=2400) + with tempfile.TemporaryDirectory(prefix="qec-container-smoke-") as temporary: + fixture = Path(temporary) + command(["docker", "run", "--rm", "--network", "none", "--user", f"{os.getuid()}:{os.getgid()}", + "--mount", f"type=bind,src={fixture},dst=/fixture", args.image, + "python", "/opt/task/tests/container_smoke.py", "--prepare", "/fixture"]) + results = [case_run(case, fixture, args.output, args.image) + for case in ("valid", "invalid-submission", "missing-labels")] + write_json(args.output / "container-smoke.json", {"schema": "surface-code-container-smoke/v1", + "status": "passed", "scientific_accuracy_evidence": False, + "scope": "Actual native Docker CPU supervisor/grader role separation and error classification on synthetic data", + "cases": results, "wall_seconds": time.monotonic() - started}) + print(f"Container smoke passed; evidence: {args.output / 'container-smoke.json'}") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare", type=Path, help="Internal: generate synthetic fixtures using the image's NumPy") + parser.add_argument("--image", default="surface-code-verifier:smoke") + parser.add_argument("--build", action="store_true", help="Build the pinned verifier image before the smoke") + parser.add_argument("--output", type=Path, default=Path("container-smoke-results")) + args = parser.parse_args() + if args.prepare: + prepare(args.prepare) + else: + args.output = args.output.resolve() + orchestrate(args) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/05/0554f498d0368ecd36ac232c40d7bcd0b9dc20ed1a901d72e300b13d501ae4d5/test_inference.py b/reproduction/files/05/0554f498d0368ecd36ac232c40d7bcd0b9dc20ed1a901d72e300b13d501ae4d5/test_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..9691d0d2986a5556bc5cc76640669d3efb3ad174 --- /dev/null +++ b/reproduction/files/05/0554f498d0368ecd36ac232c40d7bcd0b9dc20ed1a901d72e300b13d501ae4d5/test_inference.py @@ -0,0 +1,69 @@ +"""CPU regression checks for missing observations and batch independence.""" + +import argparse +import json +from pathlib import Path +import sys +import numpy as np +import torch + +p = argparse.ArgumentParser() +p.add_argument("--model", type=Path, required=True) +p.add_argument("--output", type=Path, required=True) +a = p.parse_args() +sys.path.insert(0, str(a.model.resolve())) +from infer import EncoderConfig, Modality, configure_inference, embed + +model = EncoderConfig.from_dict( + json.loads((a.model / "config.json").read_text()) +).build() +model.load_state_dict( + torch.load(a.model / "encoder.pt", map_location="cpu", weights_only=True) +) +configure_inference(model) +rng = np.random.default_rng(42) +pixels = { + "sentinel2_l2a": rng.normal(size=(3, 8, 8, 3, 12)).astype(np.float32), + "sentinel1": rng.normal(size=(3, 8, 8, 3, 2)).astype(np.float32), +} +valid = { + "sentinel2_l2a": np.ones((3, 3, 3), dtype=bool), + "sentinel1": np.ones((3, 3, 1), dtype=bool), +} +valid["sentinel1"][0] = False +valid["sentinel2_l2a"][1, 1, 1] = False +for mask in valid.values(): + mask[2] = False + + +def run(x, masks): + return embed(model, x, torch.device("cpu"), center=True, valid=masks) + + +joint = run(pixels, valid) +alone = np.concatenate( + [ + run( + {k: v[i : i + 1] for k, v in pixels.items()}, + {k: v[i : i + 1] for k, v in valid.items()}, + ) + for i in range(3) + ] +) +altered = {k: v.copy() for k, v in pixels.items()} +for name in altered: + spec = Modality.get(name) + for row, time, group in np.argwhere(~valid[name]): + for band in spec.band_sets[group].bands: + altered[name][row, :, :, time, spec.band_order.index(band)] = 100000 +perturbed = run(altered, valid) +report = { + "single_vs_batch_max_abs": float(np.max(abs(joint - alone))), + "masked_pixel_perturbation_max_abs": float(np.max(abs(joint - perturbed))), + "unobserved_row_is_zero": bool(np.all(joint[2] == 0)), +} +assert report["single_vs_batch_max_abs"] < 1e-5, report +assert report["masked_pixel_perturbation_max_abs"] < 1e-5, report +assert report["unobserved_row_is_zero"], report +a.output.write_text(json.dumps(report, indent=2)) +print(json.dumps(report, indent=2)) diff --git a/reproduction/files/05/05735f6057ba486e9a82f09c0748bf41c8c736b775acd454c0343ff826bded8a/crystal_cache.py b/reproduction/files/05/05735f6057ba486e9a82f09c0748bf41c8c736b775acd454c0343ff826bded8a/crystal_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..200c24ba5f2cf338b3e63973b14bd49bd50034b6 --- /dev/null +++ b/reproduction/files/05/05735f6057ba486e9a82f09c0748bf41c8c736b775acd454c0343ff826bded8a/crystal_cache.py @@ -0,0 +1,29 @@ +"""Per-grading-job writable HF lock directory over frozen dataset tables. + +This is the same directory-link layout used by the task's native +writable_datasets_cache helper, applied explicitly by the Beaker launcher. +No scorer functions or dataset bytes are changed. +""" +from pathlib import Path + + +def prepare(source, destination): + source = Path(source).resolve(strict=True) + destination = Path(destination) + if not source.is_dir(): + raise ValueError('Prepared dataset cache is not a directory') + if destination.resolve().is_relative_to(source): + raise ValueError('Writable cache must be outside prepared assets') + destination.mkdir(parents=True, exist_ok=False) + linked = [] + for entry in sorted(source.iterdir()): + if entry.is_dir(): + target = entry.resolve(strict=True) + if not target.is_relative_to(source): + raise ValueError('Prepared dataset directory escapes asset cache') + (destination / entry.name).symlink_to(target, target_is_directory=True) + linked.append(entry.name) + if not linked: + raise ValueError('No prepared dataset tables found') + return {'source': str(source), 'writable_cache': str(destination), + 'linked_datasets': linked, 'table_bytes_copied': False} diff --git a/reproduction/files/06/06574a519731708f2dbb71ebeb491fbdf3114f4d7af8b9eb121da35fd30c1b62/test_sharding.py b/reproduction/files/06/06574a519731708f2dbb71ebeb491fbdf3114f4d7af8b9eb121da35fd30c1b62/test_sharding.py new file mode 100644 index 0000000000000000000000000000000000000000..2b4d6a0c7ae63edb027df407c6e9dace1972c85c --- /dev/null +++ b/reproduction/files/06/06574a519731708f2dbb71ebeb491fbdf3114f4d7af8b9eb121da35fd30c1b62/test_sharding.py @@ -0,0 +1,100 @@ +"""Check lossless input shards, complete batch boundaries and merge rejection.""" + +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +import h5py +import numpy as np + +TRACK = Path(__file__).resolve().parents[1] + + +class ShardingTest(unittest.TestCase): + def test_coverage_and_rejection(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "input.h5" + pixels = np.arange(102, dtype=np.uint16).reshape(51, 2) + with h5py.File(source, "w") as h: + h.attrs["task"] = "lfmc" + h.create_dataset( + "ids", data=[str(i) for i in range(51)], dtype=h5py.string_dtype() + ) + h.create_dataset("sentinel2_l2a", data=pixels) + command = [ + sys.executable, + str(TRACK / "environment/data/shard_inputs.py"), + "--input", + str(source), + "--output", + str(root / "shards"), + "--shards", + "3", + ] + result = subprocess.run(command, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + manifest_path = root / "shards/manifest.json" + manifest = json.loads(manifest_path.read_text()) + self.assertEqual([s["start"] for s in manifest["shards"]], [0, 16, 32]) + collected = [] + for index, shard in enumerate(manifest["shards"]): + with h5py.File(root / "shards" / shard["file"]) as h: + collected.append(h["sentinel2_l2a"][:]) + ids = h["ids"].asstr()[:].astype(str) + features = np.repeat( + np.arange(shard["start"], shard["stop"], dtype=np.float32)[ + :, None + ], + 3, + axis=1, + ) + part = root / f"features/part{index:03d}" + part.mkdir(parents=True) + np.savez(part / "features.npz", ids=ids, features=features) + np.testing.assert_array_equal(np.concatenate(collected), pixels) + output = root / "merged.npz" + merge = [ + sys.executable, + str(TRACK / "docs/analysis/merge_features.py"), + "--manifest", + str(manifest_path), + "--features", + str(root / "features"), + "--output", + str(output), + ] + result = subprocess.run(merge, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + with np.load(output, allow_pickle=False) as merged: + np.testing.assert_array_equal(merged["ids"], np.arange(51).astype(str)) + np.testing.assert_array_equal(merged["features"][:, 0], np.arange(51)) + result = subprocess.run(merge, capture_output=True, text=True) + self.assertNotEqual( + result.returncode, 0, "must not overwrite existing features" + ) + output.unlink() + original = manifest_path.read_text() + manifest["start"] = 16 + manifest["full_release"] = False + manifest_path.write_text(json.dumps(manifest)) + result = subprocess.run(merge, capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("complete release", result.stderr) + manifest_path.write_text(original) + path = root / "features/part001/features.npz" + with np.load(path, allow_pickle=False) as good: + ids, features = good["ids"].copy(), good["features"].copy() + ids[0] = ids[1] + np.savez(path, ids=ids, features=features) + result = subprocess.run(merge, capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("IDs do not match", result.stderr) + self.assertFalse(output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/07/07c28629ae97a2a93f1730061d27d8d096731bcd7a9e579e00c7980e0d6afc24/test_native_replay.py b/reproduction/files/07/07c28629ae97a2a93f1730061d27d8d096731bcd7a9e579e00c7980e0d6afc24/test_native_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..9559b59cec15ad5ebbff3e336d24127c7e776dae --- /dev/null +++ b/reproduction/files/07/07c28629ae97a2a93f1730061d27d8d096731bcd7a9e579e00c7980e0d6afc24/test_native_replay.py @@ -0,0 +1,246 @@ +"""Synthetic bookkeeping/adapter tests, never substitutes for native CFD runs.""" +import json +from pathlib import Path +import sys +import subprocess +import tempfile +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'environment/evaluation')) +import case_spec +import evaluate_native as replay +from evaluate import package_hash +from protocol import InfrastructureError, PolicyError + + +class NativeProfilesTests(unittest.TestCase): + def test_exact_frozen_coverage_and_semantics(self): + spec, cases = case_spec.select_cases(['all']) + release = case_spec.load_release() + self.assertEqual([c['id'] for c in cases], [c['id'] for c in release['cases']]) + self.assertEqual(len(cases), 39) + self.assertEqual(spec['data_release_sha256'], case_spec.digest(release)) + for c, source in zip(cases, release['cases']): + self.assertEqual(c['runtime_profile'], source['runtime_profile']) + self.assertEqual(c['solver_processes'], source['required_solver_gpus']) + self.assertEqual(c['horizon'], source['selection_review']['native_episode_controls_for_costing']) + self.assertEqual(c['seeds'], [123]) + self.assertEqual(c['episode_end'], 'native') + self.assertGreaterEqual(c['timeout_sec'], 1800) + self.assertEqual({c['backend'] for c in cases}, {'maia', 'jax', 'jax-fluids'}) + self.assertEqual(max(c['observation_size'] for c in cases), 128) + self.assertEqual(max(c['action_size'] for c in cases), 24) + + def test_unknown_duplicate_and_mixed_all_rejected(self): + for names in ([], ['unknown'], ['all', 'Cylinder_2D_Re200'], + ['Cylinder_2D_Re200', 'Cylinder_2D_Re200']): + with self.subTest(names=names), self.assertRaises(InfrastructureError): + case_spec.select_cases(names) + + def test_source_rejection_precedes_policy(self): + with tempfile.TemporaryDirectory() as directory: + with self.assertRaises((InfrastructureError, OSError)): + case_spec.verify_resources(Path(directory), case_spec.select_cases(['all'])[1]) + + def test_missing_second_gpu_fails_before_native_solver_import(self): + import run_native + with tempfile.TemporaryDirectory() as directory: + args = ['run_native.py', '--case', 'Cube_3D_Re3700', '--data', directory, + '--submission', directory, '--output', directory] + with patch.object(sys, 'argv', args), patch.object(run_native, 'verify_resources'), \ + patch.object(run_native, 'local_only'), \ + patch.object(run_native.subprocess, 'check_output', return_value='["GPU-test"]'): + with self.assertRaisesRegex(RuntimeError, 'requires 2 distinct GPUs'): + run_native.main() + self.assertTrue((Path(directory) / 'launcher-error.json').exists()) + + +class NativeReplayTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.data = self.root / 'data' + self.data.mkdir() + self.package = self.root / 'candidate' + self.package.mkdir() + (self.package / 'README.md').write_text('Synthetic bookkeeping fixture, not a model.\n') + (self.package / 'infer.sh').write_text('exit 0\n') + self.names = ['Cylinder_2D_Re200', 'Channel_3D_Retau180'] + self.output = self.root / 'results' + self.verify = patch.object(replay, 'verify_resources').start() + self.addCleanup(patch.stopall) + self.snapshots = [] + + def runner(self, case, data, package, output): + self.assertNotEqual(package, self.package) + self.assertEqual(package_hash(package), package_hash(self.package)) + self.snapshots.append(str(package)) + return {'status': 'ok', 'submission_sha256': package_hash(package), 'episodes': [ + {'seed': seed, 'steps': case['horizon'], 'return': -4.0, + 'primary_metric': dict(case['primary_metric'], status='ok', value=1.25), + 'terminated': True, 'truncated': False} for seed in case['seeds']]} + + def evaluate(self, runner=None): + return replay.evaluate_native(self.data, self.package, self.output, self.names, + runner=runner or self.runner) + + def test_relocated_same_package_no_anchors_or_suite_required(self): + result = self.evaluate() + self.assertEqual(result['status'], 'ok') + self.assertEqual(result['successful_cases'], 2) + self.assertFalse(result['benchmark_validated']) + self.assertFalse(result['all_frozen_cases_selected']) + self.assertEqual(len(set(self.snapshots)), 1) + self.assertEqual(result['cases'][self.names[0]]['mean_return'], -4) + self.assertEqual(result['cases'][self.names[0]]['primary_metric']['value'], 1.25) + self.assertEqual(self.verify.call_count, 2) + self.assertFalse((self.output / 'reward.json').exists()) + self.assertFalse((self.data / 'suite.json').exists()) + + def test_all_cases_keep_one_package_and_full_accounting(self): + self.names = ['all'] + result = self.evaluate() + self.assertEqual(result['successful_cases'], 39) + self.assertTrue(result['all_frozen_cases_selected']) + self.assertFalse(result['benchmark_validated']) + self.assertEqual(len(set(self.snapshots)), 1) + + def test_failures_are_explicit_and_remaining_cases_still_run(self): + def runner(case, *args): + if case['id'] == self.names[0]: + raise InfrastructureError('Synthetic solver failure') + row = self.runner(case, *args) + row.update(status='policy_error', error='Synthetic malformed action') + row.pop('episodes') + return row + result = self.evaluate(runner) + self.assertEqual(result['status'], 'completed_with_errors') + self.assertEqual(len(result['cases']), 2) + self.assertEqual(result['cases'][self.names[0]]['status'], 'infrastructure_error') + self.assertEqual(result['cases'][self.names[1]]['status'], 'policy_error') + self.assertNotIn('mean_return', result['cases'][self.names[1]]) + self.assertFalse((self.output / 'reward.json').exists()) + + def test_missing_package_records_every_requested_case(self): + self.package = self.root / 'absent' + result = self.evaluate() + self.assertEqual(result['requested_cases'], 2) + self.assertTrue(all(r['status'] == 'policy_error' for r in result['cases'].values())) + + def test_invalid_episode_or_package_identity_rejected(self): + corruptions = [lambda row: row.update(submission_sha256='wrong'), + lambda row: row['episodes'][0].update(steps=1), + lambda row: row['episodes'][0].update(seed=0), + lambda row: row['episodes'][0].update(**{'return': float('nan')}), + lambda row: row['episodes'][0].pop('primary_metric'), + lambda row: row['episodes'][0]['primary_metric'].update(value=float('nan')), + lambda row: row['episodes'][0].update(terminated=False, truncated=False)] + for i, corrupt in enumerate(corruptions): + self.output = self.root / f'bad-{i}' + def runner(*args): + row = self.runner(*args) + corrupt(row) + return row + with self.subTest(i=i): + result = self.evaluate(runner) + self.assertTrue(all(r['status'] == 'infrastructure_error' for r in result['cases'].values())) + + def test_snapshot_mutation_rejects_entire_run(self): + def runner(case, data, package, output): + row = self.runner(case, data, package, output) + (package / 'README.md').write_text('Changed during replay') + return row + with self.assertRaisesRegex(InfrastructureError, 'snapshot mutated'): + self.evaluate(runner) + self.assertTrue((self.output / 'error.json').exists()) + self.assertFalse((self.output / 'results.json').exists()) + + def test_resource_change_rejects_results(self): + self.verify.side_effect = [None, InfrastructureError('Source changed')] + with self.assertRaisesRegex(InfrastructureError, 'Source changed'): + self.evaluate() + self.assertFalse((self.output / 'results.json').exists()) + + def test_code_change_rejects_results(self): + with patch.object(replay, 'implementation_hash', side_effect=['before', 'after']): + with self.assertRaisesRegex(InfrastructureError, 'implementation changed'): + self.evaluate() + + def test_policy_session_cleanup_and_pid_reuse_protection(self): + process = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'], start_new_session=True) + self.addCleanup(lambda: process.poll() is None and process.kill()) + ticks = Path(f'/proc/{process.pid}/stat').read_text().rsplit(')', 1)[1].split()[19] + receipt = self.root / 'policy-process.json' + receipt.write_text(json.dumps({'pid': process.pid, 'start_ticks': 'stale'})) + replay.stop_policy(self.root) + self.assertIsNone(process.poll()) + receipt.write_text(json.dumps({'pid': process.pid, 'start_ticks': ticks})) + replay.stop_policy(self.root) + self.assertEqual(process.wait(timeout=3), -9) + replay.stop_policy(self.root) + + def test_immediate_policy_exit_is_not_an_infrastructure_error(self): + import native_envs + import run_native + env, policy = Mock(), Mock() + policy.process.pid = 999999999 + case = case_spec.select_cases([self.names[0]])[1][0] + with patch.object(native_envs, 'make_env', return_value=env), \ + patch.object(run_native, 'Policy', return_value=policy), \ + patch.object(run_native, 'replay_episode', side_effect=PolicyError('Exited')): + run_native.worker(case, self.data, self.package, self.root) + self.assertEqual(json.loads((self.root / 'result.json').read_text())['status'], 'policy_error') + policy.abort.assert_called_once() + env.close.assert_called_once() + + def test_overlapping_and_stale_outputs_rejected(self): + for output in (self.data / 'output', self.package / 'output', self.root): + self.output = output + with self.subTest(output=output), self.assertRaises(InfrastructureError): + self.evaluate() + self.output = self.root / 'results' + self.output.mkdir() + (self.output / 'reward.json').write_text('{"score":1}') + with self.assertRaisesRegex(InfrastructureError, 'empty'): + self.evaluate() + + +try: + import numpy as np +except ImportError: + np = None + + +@unittest.skipIf(np is None, 'Native scalar adapters need NumPy from the task runtime') +class ReplayAdapterTests(unittest.TestCase): + def test_native_completion_and_scalar_diagnostics(self): + from native_envs import ReplayAdapter + class Env: + class Space: + dtype, shape = np.float32, (1,) + observation_space = action_space = Space() + def reset(self, seed): + self.count = 0 + return np.zeros(1), {} + def step(self, action): + self.count += 1 + return np.ones(1), np.float32(-1), self.count == 2, False, {'lift': np.array([2.])} + with tempfile.TemporaryDirectory() as directory: + env = ReplayAdapter(Env(), {'id': 'synthetic', 'horizon': 2}, Path(directory)) + env.reset(seed=123) + self.assertFalse(env.step([0])[2]) + self.assertEqual(env.step([0])[4], {'lift': 2.0}) + self.assertEqual(json.loads((Path(directory) / 'progress.json').read_text())['phase'], 'complete') + with self.assertRaises(InfrastructureError): + env.step([0]) + env.case['horizon'] = 3 + env.reset(seed=123) + env.step([0]) + with self.assertRaisesRegex(InfrastructureError, 'termination differs'): + env.step([0]) + + +if __name__ == '__main__': + unittest.main() diff --git a/reproduction/files/08/08431c3d888f0a102552f1facf1ea72135d88e504584f2531dea1a5c0c979e2f/score_extra.py b/reproduction/files/08/08431c3d888f0a102552f1facf1ea72135d88e504584f2531dea1a5c0c979e2f/score_extra.py new file mode 100644 index 0000000000000000000000000000000000000000..b5f2361522f812b1100d0978eaa968c1be27c88e --- /dev/null +++ b/reproduction/files/08/08431c3d888f0a102552f1facf1ea72135d88e504584f2531dea1a5c0c979e2f/score_extra.py @@ -0,0 +1,201 @@ +"""Score a run of extra.py against the references of the same split. + + python score_extra.py --suite kappa|mof|amorphous|cleavage|neb --run RUN_DIR \ + --inputs INPUTS_DIR --references REFERENCES_DIR + +INPUTS_DIR is the label-free split directory given to extra.py; REFERENCES_DIR holds its +references.json(.gz). The two may be the same directory (development builds). + +Missing or failed items are scored, never dropped: +- kappa: SRME as in Matbench Discovery (imaginary modes, broken symmetry and failures score 2). +- mof: MAPE of B0; each MOF's error is capped at 200 %, and a failed MOF scores the cap. +- amorphous: per-system energy RMSE (offset removed) and force RMSE, each relative to the reference + standard deviation; a failed structure scores about twice the error of predicting the mean + (energy error +-2 std, forces -F_ref). +- cleavage: relative MAE (MAE / mean |reference|); each slab's error is capped at 2 |reference|, and + a failed slab scores the cap. +- neb: barrier MAE over all paths with each error capped at 2 eV (diverging NEB runs give errors of + tens of eV); a failed path scores the cap. Also reports the converged fraction and the MAE over + converged paths. +""" +from __future__ import annotations + +import argparse +import gzip +import json +from pathlib import Path + +import numpy as np + +KAPPA_ERROR_MAX = 2.0 +MOF_CAP = 2.0 +NEB_CAP_EV = 2.0 + + +def load(path: Path): + return json.load(gzip.open(path)) if path.suffix == ".gz" else json.loads(path.read_text()) + + +def predictions(run: Path) -> dict[str, dict]: + out = {} + for f in (run / "items").glob("*.json"): + r = json.loads(f.read_text()) + out[r["id"]] = r + return out + + +def ok(p): + return p is not None and p.get("status") == "ok" + + +# ------------------------------------------------------------------------------------------ kappa +def kappa_avg(kappa) -> np.ndarray: + a = np.asarray(kappa, dtype=float) + if a.shape[-2:] == (3, 3): + return np.trace(a, axis1=-2, axis2=-1) / 3 + if a.shape[-1] == 6: + return a[..., :3].mean(axis=-1) + if a.shape[-1] == 3: + return a.mean(axis=-1) + raise ValueError(f"unexpected kappa shape {a.shape}") + + +def _finite(value, nonnegative=False): + try: + v = np.asarray(value, dtype=float) + except (TypeError, ValueError): + return None + if v.size == 0 or not np.all(np.isfinite(v)) or (nonnegative and np.any(v < 0)): + return None + return v + + +def srme_one(pred: dict | None, ref: dict) -> tuple[float, float, bool]: + """(SRME, SRD, censored) for one material, following matbench_discovery/metrics/phonons.py.""" + true_total = float(np.ravel(ref["kappa_tot_avg"])[0]) + true_mode = np.asarray(ref["mode_kappa_tot_avg"], dtype=float) + if not ok(pred): + return KAPPA_ERROR_MAX, -KAPPA_ERROR_MAX, True + censored = bool(pred.get("has_imag_ph_modes")) + expected_spg = ref.get("init_spg_num") + if not censored and pred.get("final_spg_num") and expected_spg: + censored = pred["final_spg_num"] != expected_spg + total = _finite(kappa_avg(pred["kappa_tot_rta"]) if pred.get("kappa_tot_rta") is not None else None, True) + srd = -KAPPA_ERROR_MAX + if total is not None and total.size == 1: + t = float(total.ravel()[0]) + srd = 0.0 if t + true_total == 0 else KAPPA_ERROR_MAX * (t - true_total) / (t + true_total) + if censored or total is None or total.size != 1: + return KAPPA_ERROR_MAX, srd, True + mode = _finite(kappa_avg(pred["mode_kappa_tot_rta"]) if pred.get("mode_kappa_tot_rta") is not None else None) + # Predictions are produced in the process that imports the untrusted calculator. + # The quadrature normalizer belongs to the pinned reference, never that process. + weights = _finite(ref.get("weights"), True) + if mode is None or weights is None or weights.sum() <= 0 or mode.shape != true_mode.shape: + return KAPPA_ERROR_MAX, srd, True + micro = np.abs(mode - true_mode).sum(axis=tuple(range(1, mode.ndim))) / weights.sum() + denom = np.atleast_1d(total) + np.atleast_1d(true_total) + score = float(np.ravel(np.where(denom == 0, np.where(micro == 0, 0, KAPPA_ERROR_MAX), + KAPPA_ERROR_MAX * micro / denom))[0]) + if not np.isfinite(score) or not 0 <= score <= KAPPA_ERROR_MAX: + return KAPPA_ERROR_MAX, srd, True + return score, srd, False + + +def score_kappa(pred, root): + ref = {r["material_id"]: r for r in load(root / "references.json.gz")} + rows = {m: srme_one(pred.get(m), r) for m, r in sorted(ref.items())} + srme = np.array([r[0] for r in rows.values()]); srd = np.array([r[1] for r in rows.values()]) + return {"items": len(rows), "kappa_SRME": float(srme.mean()), "kappa_SRE": float(np.abs(srd).mean()), + "kappa_SRD": float(srd.mean()), "censored_or_failed": int(sum(r[2] for r in rows.values()))} + + +# ------------------------------------------------------------------------------------------ others +def score_mof(pred, root): + ref = {r["id"]: float(r["B0_GPa"]) for r in load(root / "references.json")} + err, failed = [], 0 + for k, y in sorted(ref.items()): + p = pred.get(k) + b = p.get("B_GPa") if ok(p) else None + if b is None or not np.isfinite(b): + failed += 1; err.append(MOF_CAP) + else: + err.append(min(abs(b - y) / abs(y), MOF_CAP)) + return {"items": len(ref), "bulk_modulus_MAPE_pct": float(100 * np.mean(err)), "failed": failed} + + +def score_amorphous(pred, root): + refs = load(root / "references.json.gz") + systems = sorted({r["system"] for r in refs}) + out, failed = {"items": len(refs)}, 0 + for s in systems: + rs = [r for r in refs if r["system"] == s] + er = np.array([r["energy_per_atom"] for r in rs]) + d, fr, fp = [], [], [] + for k, r in enumerate(rs): + p = pred.get(r["id"]) + f_ref = np.asarray(r["forces"], dtype=float) + if ok(p) and np.isfinite(p["energy_per_atom"]) and np.shape(p["forces"]) == f_ref.shape \ + and np.isfinite(p["forces"]).all(): + d.append(p["energy_per_atom"] - r["energy_per_atom"]); fp.append(np.asarray(p["forces"], dtype=float)) + else: # about twice the trivial predictor's error, so failing never helps + failed += 1; d.append((1 if k % 2 == 0 else -1) * 2 * er.std()); fp.append(-f_ref) + fr.append(f_ref) + d = np.array(d) + d = d - d.mean() + fr, fp = np.concatenate(fr), np.concatenate(fp) + out[f"{s}_energy_RelRMSE_pct"] = float(100 * np.sqrt((d ** 2).mean()) / er.std()) + out[f"{s}_force_RelRMSE_pct"] = float(100 * np.sqrt(((fp - fr) ** 2).mean()) / fr.std()) + out["energy_RelRMSE_pct_mean"] = float(np.mean([out[f"{s}_energy_RelRMSE_pct"] for s in systems])) + out["force_RelRMSE_pct_mean"] = float(np.mean([out[f"{s}_force_RelRMSE_pct"] for s in systems])) + out["failed"] = failed + return out + + +def score_cleavage(pred, root): + ref = {r["id"]: float(r["cleavage_energy"]) for r in load(root / "references.json")} + y = np.array(list(ref.values())) + good = np.array([ok(pred.get(k)) and np.isfinite(pred[k]["cleavage_energy"]) for k in ref]) + p = np.array([pred[k]["cleavage_energy"] if g else np.nan for k, g in zip(ref, good)]) + err = np.where(good, np.minimum(np.abs(p - y), 2 * np.abs(y)), 2 * np.abs(y)) + return {"items": len(ref), "cleavage_relMAE_pct": float(100 * err.mean() / np.abs(y).mean()), + "cleavage_MAE_eV_A2": float(err.mean()), "cleavage_signed_eV_A2": float((p - y)[good].mean()) if good.any() else None, + "failed": int((~good).sum())} + + +def score_neb(pred, root): + ref = {r["id"]: float(r["barrier_eV"]) for r in load(root / "references.json")} + y = np.array(list(ref.values())) + good = np.array([ok(pred.get(k)) and np.isfinite(pred[k]["barrier_eV"]) for k in ref]) + p = np.array([pred[k]["barrier_eV"] if g else np.nan for k, g in zip(ref, good)]) + err = np.where(good, np.minimum(np.abs(p - y), NEB_CAP_EV), NEB_CAP_EV) + conv = np.array([g and bool(pred[k]["converged"]) for k, g in zip(ref, good)]) + return {"items": len(ref), "barrier_MAE_eV": float(err.mean()), + "barrier_MAE_converged_eV": float(np.abs(p - y)[conv].mean()) if conv.any() else None, + "converged_frac": float(conv.mean()), "failed": int(len(ref) - sum(good))} + + +SCORERS = {"kappa": score_kappa, "mof": score_mof, "amorphous": score_amorphous, + "cleavage": score_cleavage, "neb": score_neb} + + +def score(suite: str, run: Path, inputs: Path, references: Path) -> dict: + info = json.loads((run / "run.json").read_text()) + import hashlib + if info.get("inputs_manifest_sha256") != hashlib.sha256((inputs / "manifest.json").read_bytes()).hexdigest(): + raise SystemExit(f"{suite}: run was made on a different split") + return {"suite": suite, **SCORERS[suite](predictions(run), references), "complete": info["complete"]} + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--suite", choices=sorted(SCORERS), required=True) + ap.add_argument("--run", type=Path, required=True) + ap.add_argument("--inputs", type=Path, required=True) + ap.add_argument("--references", type=Path, required=True) + a = ap.parse_args() + print(json.dumps(score(a.suite, a.run, a.inputs, a.references), indent=1)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/08/08b0e3ae8a6e54b006cf60ffe74c63de172d0fa89714ff77df4f93866b1d63c1/grader.py b/reproduction/files/08/08b0e3ae8a6e54b006cf60ffe74c63de172d0fa89714ff77df4f93866b1d63c1/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..808a63f42e93c777b3256475a46820d3d903777b --- /dev/null +++ b/reproduction/files/08/08b0e3ae8a6e54b006cf60ffe74c63de172d0fa89714ff77df4f93866b1d63c1/grader.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Trusted scorer. Reads sealed predictions + private responses; never executes submission code. + +Writes to --output: + reward.json {"reward": mean over test contexts of the FINAL-subset score, ...} + report.json full per-context / per-subset / per-stratum report (operator-facing) + agent_feedback.json leaderboard-subset scores only (what the runner may return to the agent) +""" + +from __future__ import annotations + +import argparse +import json +import time +from pathlib import Path + +import numpy as np + +from cellscore import cell_eval_version, score_context, sha256 + + +def harbor_reward(values): + """Harbor parses reward.json as a flat object of finite numbers; strings, None and nested details + belong in report.json / status.json.""" + import math as _math + return {k: v for k, v in values.items() if isinstance(v, (int, float)) and _math.isfinite(v)} + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--sealed", required=True, type=lambda x: Path(x).resolve()) + ap.add_argument("--benchmark", required=True, type=lambda x: Path(x).resolve()) + ap.add_argument("--private", required=True, type=lambda x: Path(x).resolve()) + ap.add_argument("--output", required=True, type=lambda x: Path(x).resolve()) + ap.add_argument("--wait-seconds", type=int, default=14400) + ap.add_argument("--threads", type=int) + args = ap.parse_args() + ready = args.sealed.parent / "READY" + deadline = time.monotonic() + args.wait_seconds + while not ready.is_file(): + if time.monotonic() >= deadline: + raise TimeoutError("prediction snapshot was not published") + time.sleep(2) + snapshot_path = args.sealed / "snapshot.json" + if ready.read_text().strip() != sha256(snapshot_path): + raise ValueError("snapshot ready hash mismatch") + snapshot = json.loads(snapshot_path.read_text()) + contexts = sorted(p.name for p in args.private.iterdir() if (p / "responses.h5ad").exists()) + report = {"schema": "virtual-cell-zeroshot-report/v1", "cell_eval_version": cell_eval_version(), + "evaluation_mode": "isolated_model_replay", "contexts": {}} + finals, boards = [], [] + scratch = args.output / "scratch" + for ctx in contexts: + priv = args.private / ctx + pm = json.loads((priv / "manifest.json").read_text()) + if pm["responses_sha256"] != sha256(priv / "responses.h5ad"): + raise ValueError(f"{ctx}: private response checksum mismatch") + public = args.benchmark / ctx / "public" + entry = snapshot["contexts"].get(ctx) + if pm["requests_sha256"] != sha256(public / "requests.jsonl") or pm["public_basal_sha256"] != sha256(public / "basal.h5ad"): + raise ValueError(f"{ctx}: public inputs differ from the private manifest") + if not entry or entry.get("failed"): + report["contexts"][ctx] = {"status": "failed", "error": (entry or {}).get("error", "missing"), + "tier": pm["tier"], "final_score": 0.0, "leaderboard_score": 0.0} + finals.append(0.0); boards.append(0.0) + continue + pred = args.sealed / ctx / "predictions.h5ad" + if entry["predictions_sha256"] != sha256(pred) or entry["requests_sha256"] != sha256(public / "requests.jsonl") \ + or entry["basal_sha256"] != sha256(public / "basal.h5ad"): + raise ValueError(f"{ctx}: sealed snapshot provenance mismatch") + subsets = {"leaderboard": [r["request_id"] for r in pm["requests"] if r["subset"] == "leaderboard"], + "final": [r["request_id"] for r in pm["requests"] if r["subset"] == "final"]} + groups = {"stratum": {r["request_id"]: r["stratum"] for r in pm["requests"]}, + "target_seen": {r["request_id"]: ("withheld" if r["withheld"] else ("seen" if r["seen_in_training"] else "unseen")) + for r in pm["requests"]}, + "final_by_stratum": {r["request_id"]: r["stratum"] for r in pm["requests"] if r["subset"] == "final"}} + baseline_dir = priv / "noeffect" if (priv / "noeffect").exists() else None + res = score_context(pred, priv / "basal.h5ad", priv / "responses.h5ad", public / "requests.jsonl", + scratch / ctx, subsets=subsets, groups=groups, threads=args.threads, baseline_dir=baseline_dir) + final = res["subsets"]["final"]["score"]; board = res["subsets"]["leaderboard"]["score"] + report["contexts"][ctx] = {"status": "ok", "tier": pm["tier"], "chemistry": pm["chemistry"], + "final_score": final, "leaderboard_score": board, "all_score": res["all"]["score"], + "final": res["subsets"]["final"], "leaderboard": res["subsets"]["leaderboard"], + "all": res["all"], "groups": res["groups"], "inference_seconds": entry.get("seconds")} + finals.append(final); boards.append(board) + reward = float(np.mean(finals)) if finals else 0.0 + report["reward"] = reward + report["leaderboard_reward"] = float(np.mean(boards)) if boards else 0.0 + args.output.mkdir(parents=True, exist_ok=True) + (args.output / "report.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") + (args.output / "agent_feedback.json").write_text(json.dumps({ + "schema": "virtual-cell-zeroshot-feedback/v1", "cell_eval_version": report["cell_eval_version"], + "leaderboard_reward": report["leaderboard_reward"], + "contexts": {c: {"status": v["status"], "tier": v["tier"], "leaderboard_score": v["leaderboard_score"], + "leaderboard": v.get("leaderboard"), "error": v.get("error")} for c, v in report["contexts"].items()}, + }, indent=2, sort_keys=True) + "\n") + (args.output / "reward.json").write_text(json.dumps(harbor_reward({ + "reward": reward, "leaderboard_reward": report["leaderboard_reward"], + **{f"{c}_final": v["final_score"] for c, v in report["contexts"].items()}, + **{f"{c}_leaderboard": v["leaderboard_score"] for c, v in report["contexts"].items()}, + }), indent=2, sort_keys=True) + "\n") + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/0b/0b18d04b2b1f948d7d230ff451c93a205521037a985a856a979ba38d3c3d47ad/common.py b/reproduction/files/0b/0b18d04b2b1f948d7d230ff451c93a205521037a985a856a979ba38d3c3d47ad/common.py new file mode 100644 index 0000000000000000000000000000000000000000..b4f0f029c392a701abbbf6403de19810b8c8e596 --- /dev/null +++ b/reproduction/files/0b/0b18d04b2b1f948d7d230ff451c93a205521037a985a856a979ba38d3c3d47ad/common.py @@ -0,0 +1,106 @@ +"""Small, explicit interchange format. No model code is imported by the scorer.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import numpy as np +from ase import Atoms + +PROTOCOL = "atomistic-materials-v0.1" +PHONON_FIELDS = { + "max_freq": "K", + "avg_freq": "K", + "entropy": "J/(mol primitive cell K)", + "heat_capacity": "J/(mol primitive cell K)", + "free_energy": "kJ/mol primitive cell", +} +ELASTIC_FIELDS = {"bulk_modulus_vrh": "GPa", "shear_modulus_vrh": "GPa"} + + +def digest(path: Path, algorithm="sha256") -> str: + """File digest; a directory (submission) digests its sorted relative paths and file digests.""" + h = hashlib.new(algorithm) + if path.is_dir(): + for item in sorted(p for p in path.rglob("*") if p.is_file() and "__pycache__" not in p.parts): + h.update(f"{item.relative_to(path).as_posix()}\0{digest(item, algorithm)}\n".encode()) + return h.hexdigest() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def with_oom_retry(run, attempts=4, wait=20.0): + """run() again after a CUDA out-of-memory error, which other jobs on a shared GPU can cause. + + The verifier runs every suite at once, so a GPU can fill up briefly; that is not the model's + failure. Any other error, or a fourth OOM, propagates and the case is recorded as failed.""" + import gc + import time + for attempt in range(attempts): + try: + return run() + except Exception as error: + if type(error).__name__ != "OutOfMemoryError" or attempt == attempts - 1: + raise + gc.collect() + import torch + torch.cuda.empty_cache() + time.sleep(wait * (attempt + 1)) + + +def write_json(path: Path, value) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") + + +def write_rows(path: Path, rows) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w") as stream: + for row in rows: + stream.write(json.dumps(row, allow_nan=False) + "\n") + + +def read_rows(path: Path) -> list[dict]: + with path.open() as stream: + return [json.loads(line) for line in stream if line.strip()] + + +def indexed(rows: list[dict]) -> dict[str, dict]: + result = {} + for row in rows: + key = row["id"] + if key in result: + raise ValueError(f"Duplicate ID: {key}") + result[key] = row + if not result: + raise ValueError("Empty evaluation") + return result + + +def encode_atoms(atoms: Atoms) -> dict: + # Whitelist geometry: never serialize calc, info, site properties, or arrays + # such as DFT magnetic moments/charges/forces. + return { + "numbers": atoms.numbers.tolist(), + "positions": atoms.positions.tolist(), + "cell": atoms.cell.array.tolist(), + "pbc": atoms.pbc.tolist(), + } + + +def decode_atoms(data: dict) -> Atoms: + required = {"numbers", "positions", "cell", "pbc"} + if set(data) != required: + raise ValueError(f"Unexpected atomic fields: {set(data) ^ required}") + atoms = Atoms(**data) + if not len(atoms) or not np.isfinite(atoms.positions).all(): + raise ValueError("Invalid atomic coordinates") + if not np.isfinite(atoms.cell).all() or atoms.get_volume() <= 0: + raise ValueError("Invalid unit cell") + if not atoms.pbc.all(): + raise ValueError("Core tasks require fully periodic crystals") + return atoms diff --git a/reproduction/files/0c/0c445f2319b2c3aca9fa1587339f781fbc5000c4c27ee1b478e72b9d9a27538c/validate_fly_verifier.py b/reproduction/files/0c/0c445f2319b2c3aca9fa1587339f781fbc5000c4c27ee1b478e72b9d9a27538c/validate_fly_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..cff84e71132d095f56dc2ffa296f967b8c1b33da --- /dev/null +++ b/reproduction/files/0c/0c445f2319b2c3aca9fa1587339f781fbc5000c4c27ee1b478e72b9d9a27538c/validate_fly_verifier.py @@ -0,0 +1,41 @@ +"""Credential-free real-GPU canary for the adapted Pathfinder prediction boundary.""" +import json +import os +from pathlib import Path +import subprocess +import sys + +from fly_boundary import enter,cleanup + +root=Path('/workspace/research/run');root.mkdir(parents=True) +probe='''import os,socket,torch,json +from pathlib import Path +assert os.getuid()==10001 +assert not os.access('/private',os.X_OK) +try:Path('/private/suite/label-canary').read_bytes() +except PermissionError:pass +else:raise AssertionError('private label read succeeded') +try:Path('/operator/.untrusted-write').write_text('bad') +except PermissionError:pass +else:raise AssertionError('source write succeeded') +for family in (socket.AF_INET,socket.AF_INET6): + try:s=socket.socket(family,socket.SOCK_STREAM) + except PermissionError:pass + else:s.close();raise AssertionError('external socket succeeded') +assert torch.cuda.device_count()==8 +assert all('H100' in torch.cuda.get_device_name(i) for i in range(8)) +assert all(float((torch.ones(4,device=f'cuda:{i}')*2).sum())==8 for i in range(8)) +from pathlib import Path +Path('rename-a').mkdir();Path('rename-b').mkdir();Path('rename-a/x').write_text('ok') +Path('rename-a/x').rename('rename-b/x') +print('FLY_BOUNDARY_GPU_AND_PRIVATE_LABEL_CHECKS_PASSED') +''' +try: + result=subprocess.run([sys.executable,'-c',probe],cwd=root,preexec_fn=lambda:enter(root), + capture_output=True,text=True,timeout=180,check=True) + print(result.stdout) +finally:cleanup() +Path('/logs/verifier/validation.json').write_text(json.dumps({'passed':True,'valid_benchmark_result':False, + 'gpus':8,'private_labels_denied':True,'source_write_denied':True,'network_denied':True, + 'cross_directory_rename_works':True,'native_numerical_pipeline_unchanged':True})+'\n') +Path('/logs/verifier/reward.json').write_text('{"canary_passed":1}\n') diff --git a/reproduction/files/0d/0d0cbb759d4e8333988e9bdfdff8a8bccce42cff7b73d1d7ed3b23e0e2d584b5/test_release_contract.py b/reproduction/files/0d/0d0cbb759d4e8333988e9bdfdff8a8bccce42cff7b73d1d7ed3b23e0e2d584b5/test_release_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..65ad518fb53e0bc2313b50d4d0e34bac5e234ff6 --- /dev/null +++ b/reproduction/files/0d/0d0cbb759d4e8333988e9bdfdff8a8bccce42cff7b73d1d7ed3b23e0e2d584b5/test_release_contract.py @@ -0,0 +1,382 @@ +"""Executable release, grading, corruption, and label-isolation contracts.""" +from __future__ import annotations +import importlib.util +import io +import json +from pathlib import Path +import sys +import tarfile +import zipfile +import numpy as np +import pytest + +TASK = Path(__file__).resolve().parents[1] +PROJECT = Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" if (Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit").is_dir() else Path(__file__).resolve().parents[1] # environment/baseline/alphaqubit here, /opt/task in the verifier image +sys.path.insert(0, str(PROJECT)) +from qecbench.data import SCHEMA, DevelopmentDataset, load_condition, load_manifest, read_npz, sha256, write_json +from qecbench.scoring import InvalidPrediction, normalize, probabilities, score +from qecbench.stage_validation import stage +from baselines.alphaqubit_artifact import EXPECTED_GROUPS + + +def module(name: str, path: Path): + spec = importlib.util.spec_from_file_location(name, path) + result = importlib.util.module_from_spec(spec) + spec.loader.exec_module(result) + return result + + +materializer = module("qec_materializer", TASK / "environment/data/materialize.py") +supervisor = module("qec_supervisor", TASK / "tests/main_verifier.py") +grader = module("qec_grader", TASK / "tests/grader.py") + + +@pytest.fixture +def suite(tmp_path: Path): + inputs, labels, predictions = (tmp_path / name for name in ("inputs", "labels", "predictions")) + for folder in (inputs, labels, predictions): + folder.mkdir() + rows, targets = [], [] + for group in EXPECTED_GROUPS: + distance, basis = int(group[1]), group[4] + center = group.split("center_")[1] + for rounds in range(1, 26, 2): + name = f"surface_code_b{basis}_d{distance}_r{rounds:02}_center_{center}" + folder = inputs / name + folder.mkdir() + ids = np.array([991, 27, 64, 118], dtype=np.uint64) + detectors = np.zeros((4, (rounds * (distance**2 - 1) + 7) // 8), dtype=np.uint8) + np.savez(folder / "arrays.npz", sample_ids=ids, detectors=detectors) + (folder / "circuit_ideal.stim").write_text("fixture circuit\n") + target = np.array([0, 0, 0, 1], dtype=np.uint8) + np.savez(labels / f"{name}.npz", sample_ids=ids, labels=target) + np.savez(predictions / f"{name}.npz", sample_ids=ids[::-1], probabilities=np.array([1, 0, 0, 0], dtype=np.float32)) + rows.append({"name": name, "group": group, "distance": distance, "basis": basis, "rounds": rounds, + "shots": 4, "num_detectors": rounds * (distance**2 - 1), "arrays": f"{name}/arrays.npz", + "arrays_sha256": sha256(folder / "arrays.npz"), "circuit": f"{name}/circuit_ideal.stim", + "circuit_sha256": sha256(folder / "circuit_ideal.stim")}) + targets.append({"name": name, "arrays": f"{name}.npz", "arrays_sha256": sha256(labels / f"{name}.npz")}) + write_json(inputs / "manifest.json", {"schema": SCHEMA, "split": "test", "conditions": rows}) + write_json(labels / "manifest.json", {"schema": "surface-code-decoding-labels/v1", "input_manifest_sha256": sha256(inputs / "manifest.json"), "conditions": targets}) + return inputs, labels, predictions, rows + + +def test_frozen_normalization_anchors(): + config = json.loads((PROJECT / "score_config.json").read_text()) + assert normalize(config["lower_bound"], config)["score"] == 0 + assert normalize(config["upper_bound"], config)["score"] == 1 + assert normalize(1, config)["score_unclipped"] > 1 + assert normalize(1, config)["score"] == normalize(1, config)["score_unclipped"] # no upper clip (v1.1.0) + assert normalize(0, config)["score_unclipped"] < 0 + assert normalize(0, config)["score"] == 0 + + +def test_full_suite_reordering_and_perfect_score(suite): + inputs, labels, predictions, _ = suite + result = score(inputs, predictions, labels, PROJECT / "score_config.json") + assert result["shots"] == 520 + assert result["performance"] == 1 + assert result["score"] == result["score_unclipped"] > 1 # perfect decoding is above the TN anchor; no upper clip + assert result["failure_by_distance"] == {"d3": 0, "d5": 0} + + +def test_missing_prediction_is_invalid_not_infrastructure(suite): + inputs, labels, predictions, rows = suite + (predictions / f"{rows[0]['name']}.npz").unlink() + with pytest.raises(InvalidPrediction): + score(inputs, predictions, labels, PROJECT / "score_config.json") + + +@pytest.mark.parametrize("failure", ["nan", "float64", "duplicate", "extra-id", "zip-garbage", "encrypted", "compression"]) +def test_bad_outputs_fail_closed(suite, failure): + inputs, _, predictions, rows = suite + row = rows[0] + ids = load_condition(inputs, row)["sample_ids"] + values = np.zeros(4, dtype=np.float32) + if failure == "nan": + values[0] = np.nan + elif failure == "float64": + values = values.astype(np.float64) + elif failure == "duplicate": + ids[1] = ids[0] + elif failure == "extra-id": + ids[1] += 1 + path = predictions / f"{row['name']}.npz" + np.savez(path, sample_ids=ids, probabilities=values) + if failure == "zip-garbage": + path.write_bytes(b"not-a-zip") + if failure in ("encrypted", "compression"): + payload = bytearray(path.read_bytes()) + for marker, offset in ((b"PK\x03\x04", 6), (b"PK\x01\x02", 8)): + cursor = 0 + while (cursor := payload.find(marker, cursor)) >= 0: + payload[cursor + offset + (2 if failure == "compression" else 0)] = 99 if failure == "compression" else 1 + cursor += 4 + path.write_bytes(payload) + with pytest.raises(InvalidPrediction): + probabilities(predictions, row, load_condition(inputs, row)["sample_ids"]) + + +def test_trusted_label_corruption_is_infrastructure(suite): + inputs, labels, predictions, rows = suite + (labels / f"{rows[0]['name']}.npz").write_bytes(b"corrupt") + with pytest.raises(ValueError, match="Trusted label checksum"): + score(inputs, predictions, labels, PROJECT / "score_config.json") + + +def test_label_free_schema_and_development_split_guard(suite): + inputs, _, _, rows = suite + row = rows[0] + path = inputs / row["arrays"] + arrays = load_condition(inputs, row) + np.savez(path, **arrays, labels=np.zeros(4, dtype=np.uint8)) + with pytest.raises(ValueError, match="Wrong array fields"): + load_condition(inputs, row) + with pytest.raises(ValueError, match="train/validation only"): + DevelopmentDataset(inputs, "test") + + +def test_symlink_prediction_rejected(suite, tmp_path): + inputs, _, predictions, rows = suite + row = rows[0] + path = predictions / f"{row['name']}.npz" + other = tmp_path / "outside.npz" + path.replace(other) + path.symlink_to(other) + with pytest.raises(InvalidPrediction): + probabilities(predictions, row, load_condition(inputs, row)["sample_ids"]) + + +def test_npz_bomb_and_forged_shape_rejected(tmp_path): + path = tmp_path / "bomb.npz" + np.savez_compressed(path, probabilities=np.zeros(100000, dtype=np.float32)) + with pytest.raises(ValueError, match="expanded content"): + read_npz(path, 48) + stream = io.BytesIO() + np.lib.format.write_array_header_1_0(stream, {"descr": " dict[str, Any]: + """Normalize Hit@1 against fixed reference anchors, preserving overperformance.""" + if isinstance(performance, bool) or not math.isfinite(performance) or not 0 <= performance <= 1: + raise ValueError("Hit@1 must be a finite number in [0, 1]") + lower, upper = BOUNDS["lower"], BOUNDS["upper"] + if not 0 <= lower < upper <= 1: + raise ValueError("invalid benchmark score anchors") + unclipped = (performance - lower) / (upper - lower) + return { + "version": BOUNDS["version"], "metric": BOUNDS["metric"], + "direction": BOUNDS["direction"], "raw_performance": performance, + "lower_reference": lower, "upper_reference": upper, + "score": min(1.0, max(0.0, unclipped)), "unclipped_score": unclipped, + "saturation": "lower" if unclipped < 0 else "upper" if unclipped > 1 else None, + "at_or_above_upper_reference": performance >= upper, + } diff --git a/reproduction/files/0e/0e79954672aa8606568a564fd0e1f8ceb76bfbdac6fda2eadea7650396b6de06/test_policy_isolation.py b/reproduction/files/0e/0e79954672aa8606568a564fd0e1f8ceb76bfbdac6fda2eadea7650396b6de06/test_policy_isolation.py new file mode 100644 index 0000000000000000000000000000000000000000..0eee4eaaa0f42c9e0419c0a8ff6204d59a4e3fdc --- /dev/null +++ b/reproduction/files/0e/0e79954672aa8606568a564fd0e1f8ceb76bfbdac6fda2eadea7650396b6de06/test_policy_isolation.py @@ -0,0 +1,101 @@ +"""A root-run evaluator must drop the submitted policy to an unprivileged, short-lived process.""" +import os +from pathlib import Path +import sys +import tempfile +import time +import unittest +from unittest.mock import patch +ISOLATED = {'HYDROGYM_POLICY_ISOLATION': '1'} + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'environment/evaluation')) +import protocol +from protocol import InfrastructureError, Policy + +POLICY = r''' +import json, os, subprocess, sys +target = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "target.txt")).read().strip() +try: + open(target, "w").write("forged") +except OSError as error: + sys.stderr.write("write-denied %s\n" % type(error).__name__) +sys.stderr.write("uid=%d\n" % os.getuid()); sys.stderr.flush() +subprocess.Popen(["setsid", "sleep", "300"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +for line in sys.stdin: + request = json.loads(line) + reply = {"protocol": request["protocol"], "request_id": request["request_id"]} + reply.update({"reset": {"ready": True}, "act": {"action": [0.0]}, "close": {"closed": True}}[request["op"]]) + print(json.dumps(reply), flush=True) + if request["op"] == "close": + break +''' + + +def account_exists(): + try: + import pwd + pwd.getpwuid(protocol.POLICY_UID) + return True + except KeyError: + return False + + +class IsolationSwitchTests(unittest.TestCase): + def test_isolation_is_off_unless_requested(self): + with patch.dict(os.environ, {}, clear=False): + os.environ.pop('HYDROGYM_POLICY_ISOLATION', None) + self.assertIsNone(protocol.policy_account()) + + @unittest.skipIf(os.geteuid() == 0, 'checks the non-root refusal') + def test_requested_isolation_refuses_non_root(self): + with patch.dict(os.environ, ISOLATED), self.assertRaises(InfrastructureError): + protocol.policy_account() + + def test_verifier_requests_isolation_offline(self): + here = Path(__file__).resolve().parents[1] + self.assertIn('export HYDROGYM_POLICY_ISOLATION=1', (here / 'tests/test.sh').read_text()) + self.assertIn('network_mode: none', (here / 'tests/docker-compose.yaml').read_text()) + + +@unittest.skipUnless(os.geteuid() == 0 and account_exists(), 'needs root and the policy account (task image)') +class PolicyIsolationTests(unittest.TestCase): + def test_policy_runs_unprivileged_cannot_write_results_and_leaves_no_process(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + os.chmod(root, 0o755) + package = root / 'package'; package.mkdir(); os.chmod(package, 0o755) + (package / 'policy.py').write_text(POLICY) + (package / 'infer.sh').write_text('exec python3 "$(dirname "$0")/policy.py"\n') + results = root / 'results'; results.mkdir(mode=0o755) + forged = results / 'reward.json' + (package / 'target.txt').write_text(str(forged)) + for path in package.iterdir(): + path.chmod(0o444) + with patch.dict(os.environ, ISOLATED): + policy = Policy(package, root / 'policy.log', timeout=20) + policy.reset({'environment': 'x', 'family': 'x', 'seed': 1}, [1], [1], [-1.0], [1.0]) + self.assertEqual(policy.act([0.5]), [0.0]) + policy.close() + log = (root / 'policy.log').read_text() + self.assertIn(f'uid={protocol.POLICY_UID}', log) + self.assertIn('write-denied PermissionError', log) + self.assertFalse(forged.exists()) + time.sleep(0.5) + def alive(proc): # killed children re-parented to a non-reaping PID 1 stay as zombies + try: + return proc.stat().st_uid == protocol.POLICY_UID and \ + (proc / 'stat').read_text().rsplit(')', 1)[1].split()[0] != 'Z' + except FileNotFoundError: + return False + owners = [p for p in Path('/proc').iterdir() if p.name.isdigit() and alive(p)] + self.assertEqual(owners, []) + + def test_missing_account_fails_closed(self): + with tempfile.TemporaryDirectory() as tmp, patch.object(protocol, 'POLICY_UID', 54321), \ + patch.dict(os.environ, ISOLATED): + with self.assertRaises(InfrastructureError): + Policy(Path(tmp), Path(tmp) / 'policy.log', timeout=5) + + +if __name__ == '__main__': + unittest.main() diff --git a/reproduction/files/11/110a51b699d57fd0239157173866513fab41f5d1ceeb6208bc2466bfa942486f/test_prepare_hf.py b/reproduction/files/11/110a51b699d57fd0239157173866513fab41f5d1ceeb6208bc2466bfa942486f/test_prepare_hf.py new file mode 100644 index 0000000000000000000000000000000000000000..5ccd0c6793dc3326183c54c437ed88e8cfdaa663 --- /dev/null +++ b/reproduction/files/11/110a51b699d57fd0239157173866513fab41f5d1ceeb6208bc2466bfa942486f/test_prepare_hf.py @@ -0,0 +1,211 @@ +"""Offline integrity and split-isolation checks for HF preparation.""" + +import hashlib +import io +import json +from pathlib import Path +import sys +import tarfile +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/data")) +from prepare_hf import ( + copy_stream, + prepare_pretraining, + prepare_windows, + safe_path, + verify, +) + + +def archive(path, rows): + with tarfile.open(path, "w") as tar: + for name, data in rows: + data = data.encode() + m = tarfile.TarInfo(name) + m.size = len(data) + tar.addfile(m, io.BytesIO(data)) + + +class PreparationTests(unittest.TestCase): + def test_manifest_paths(self): + for name in ["../escape", "/absolute", "a/../../b", "a\\b"]: + with self.assertRaises(ValueError): + safe_path(name) + self.assertEqual(str(safe_path("archives/train.tar")), "archives/train.tar") + + def test_checksum_and_size(self): + with tempfile.TemporaryDirectory() as t: + p = Path(t) / "data" + p.write_bytes(b"abc") + entry = dict(path="data", size=3, sha256=hashlib.sha256(b"abc").hexdigest()) + verify(p, entry) + p.write_bytes(b"abd") + with self.assertRaises(ValueError): + verify(p, entry) + + def test_resume_must_match(self): + with tempfile.TemporaryDirectory() as t: + p = Path(t) / "data" + copy_stream(io.BytesIO(b"abc"), p) + copy_stream(io.BytesIO(b"abc"), p) + for value in [b"ab", b"abcd", b"xyz"]: + with self.assertRaises(ValueError): + copy_stream(io.BytesIO(value), p) + self.assertEqual(p.read_bytes(), b"abc") + + def test_selected_aliases_and_exclusions(self): + with tempfile.TemporaryDirectory() as t: + p = Path(t) + archive( + p / "a.tar", + [("root/sample_9.h5", "selected"), ("root/sample_3.h5", "excluded")], + ) + selection = dict( + source_samples=2, + kept=1, + samples=[dict(sample_index=0, source="sample_9.h5")], + excluded=["sample_3.h5"], + ) + self.assertEqual( + prepare_pretraining([p / "a.tar"], selection, p / "out"), 1 + ) + self.assertEqual((p / "out/sample_0.h5").read_text(), "selected") + self.assertEqual(len(list((p / "out").iterdir())), 1) + self.assertEqual( + prepare_pretraining([p / "a.tar"], selection, p / "out"), 1 + ) + with self.assertRaises(ValueError): + prepare_pretraining([p / "a.tar", p / "a.tar"], selection, p / "out") + + def test_missing_selected_member(self): + with tempfile.TemporaryDirectory() as t: + p = Path(t) + archive(p / "a.tar", []) + selection = dict( + source_samples=1, + kept=1, + samples=[dict(sample_index=0, source="sample_9.h5")], + excluded=[], + ) + with self.assertRaises(ValueError): + prepare_pretraining([p / "a.tar"], selection, p / "out") + + def test_native_trainval_payload_before_metadata(self): + with tempfile.TemporaryDirectory() as t: + p = Path(t) + rows = [("dataset/config.json", "{}")] + for split in ["train", "val", "test"]: + prefix = f"dataset/windows/spatial_split/{split}" + rows.extend( + [ + (prefix + "/layers/label/value", "label-" + split), + ( + prefix + "/metadata.json", + json.dumps({"options": {"split": split}}), + ), + ] + ) + archive(p / "a.tar", rows) + expected = {"train": 1, "val": 1, "test": 1} + report = prepare_windows(p / "a.tar", p / "out", expected) + self.assertFalse(report["heldout_window_payloads_read"]) + self.assertFalse((p / "out/windows/spatial_split/test").exists()) + self.assertTrue( + (p / "out/windows/spatial_split/train/layers/label/value").exists() + ) + self.assertEqual( + prepare_windows(p / "a.tar", p / "out", expected)["files"], 5 + ) + with self.assertRaises(ValueError): + prepare_windows( + p / "a.tar", p / "other", {"train": 2, "val": 1, "test": 1} + ) + + def test_unsafe_archive_member(self): + with tempfile.TemporaryDirectory() as t: + p = Path(t) + archive(p / "a.tar", [("../sample_9.h5", "x")]) + selection = dict( + source_samples=1, + kept=1, + samples=[dict(sample_index=0, source="sample_9.h5")], + excluded=[], + ) + with self.assertRaises(ValueError): + prepare_pretraining([p / "a.tar"], selection, p / "out") + + +if __name__ == "__main__": + unittest.main() + + +class DownloadPipelineTests(unittest.TestCase): + def test_hub_revision_pin_and_component_selection(self): + from types import SimpleNamespace + from unittest.mock import patch + import prepare_hf + + with tempfile.TemporaryDirectory() as t: + root = Path(t) + snapshot = root / "snapshot" + snapshot.mkdir() + payload = snapshot / "inputs" + payload.write_bytes(b"fixture") + entries = [ + dict( + path="eval/awf/inputs.h5", + size=7, + sha256=hashlib.sha256(b"fixture").hexdigest(), + components=["probe"], + ), + dict( + path="archives/unused.tar", + size=99, + sha256="0" * 64, + components=["pretrain"], + ), + ] + (snapshot / "manifest.json").write_text( + json.dumps(dict(schema_version=1, files=entries)) + ) + calls = [] + revision = "a" * 40 + + def download(repo, name, **kwargs): + calls.append((repo, name, kwargs["revision"])) + return str( + snapshot / "manifest.json" if name == "manifest.json" else payload + ) + + hub = SimpleNamespace( + HfApi=lambda: SimpleNamespace( + dataset_info=lambda *args, **kwargs: SimpleNamespace(sha=revision) + ), + hf_hub_download=download, + ) + args = [ + "prepare_hf", + "--repo", + "example/data", + "--revision", + "v1", + "--output", + str(root / "output"), + "--components", + "probe", + ] + with ( + patch.dict(sys.modules, {"huggingface_hub": hub}), + patch.object(sys, "argv", args), + ): + prepare_hf.main() + prepare_hf.main() + self.assertEqual( + (root / "output/eval/awf/inputs.h5").read_bytes(), b"fixture" + ) + self.assertTrue(all(r == revision for _, _, r in calls)) + self.assertNotIn("archives/unused.tar", [n for _, n, _ in calls]) + report = json.loads((root / "output/hf-prepared.json").read_text()) + self.assertEqual(report["revision"], revision) diff --git a/reproduction/files/12/12033212bd52ab4a3c31643ee1434fdf4b84489b59feb62322cba2c56c127ff2/replay.py b/reproduction/files/12/12033212bd52ab4a3c31643ee1434fdf4b84489b59feb62322cba2c56c127ff2/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..58658e8663827a5e6af6385e8d266c037db0ec0e --- /dev/null +++ b/reproduction/files/12/12033212bd52ab4a3c31643ee1434fdf4b84489b59feb62322cba2c56c127ff2/replay.py @@ -0,0 +1,56 @@ +"""Run exported model in a filesystem/network-isolated process.""" + +import argparse +import errno +from pathlib import Path +import shutil +import subprocess +import tempfile +import sys + +checks = Path(__file__).resolve().parents[1] / "environment/evaluation" +if not checks.is_dir(): + checks = Path(__file__).resolve().parent +if not (checks / "package_contract.py").is_file(): + checks = Path("/evaluation") +sys.path.insert(0, str(checks)) +from package_contract import InvalidSubmission, validate_features +from namespace import command, direct + +p = argparse.ArgumentParser() +p.add_argument("--model", type=Path, required=True) +p.add_argument("--input", type=Path, required=True) +p.add_argument("--output", type=Path, required=True) +p.add_argument("--no-namespace", action="store_true", + help="development only: run without Bubblewrap where user namespaces are unavailable") +a = p.parse_args() +a.output.mkdir(parents=True, exist_ok=True) +# Only unlabeled pixels and an empty output directory enter model execution. +# Previous scores/predictions in the destination are never mounted. +with tempfile.TemporaryDirectory(prefix="olmo-replay-", dir=a.output) as temp: + workspace = Path(temp) + inputs = workspace / "input" + inputs.mkdir() + outputs = workspace / "output" + outputs.mkdir() + dst = inputs / "inputs.h5" + try: + dst.hardlink_to(a.input) + except OSError as exc: + if exc.errno not in (errno.EXDEV, errno.EPERM, errno.EACCES): + raise + shutil.copyfile(a.input, dst) + if a.no_namespace: + argv, environment = direct(a.model.resolve(), inputs.resolve(), outputs.resolve()) + subprocess.run(argv, check=True, env=environment, cwd=a.model.resolve()) + else: + subprocess.run( + command(a.model.resolve(), inputs.resolve(), outputs.resolve()), check=True + ) + result = outputs / "features.npz" + try: + validate_features(result, a.input) + except InvalidSubmission as error: + print(str(error), file=sys.stderr) + raise SystemExit(42) + result.replace(a.output / "features.npz") diff --git a/reproduction/files/13/13b471d6183aced98dc4c168348cdfe26bd35c28f03f2e06f9da94345dfc7d12/run_local.py b/reproduction/files/13/13b471d6183aced98dc4c168348cdfe26bd35c28f03f2e06f9da94345dfc7d12/run_local.py new file mode 100644 index 0000000000000000000000000000000000000000..bac786101830892f838566ce1adc01279626ed53 --- /dev/null +++ b/reproduction/files/13/13b471d6183aced98dc4c168348cdfe26bd35c28f03f2e06f9da94345dfc7d12/run_local.py @@ -0,0 +1,92 @@ +"""Run the physical suites (discovery, phonons, elasticity) on local GPUs. + +One worker process per GPU pulls chunks from distributed.chunk_plan, writes each chunk with +predict.run, and distributed.merge assembles and checks the complete run: + + python run_local.py --inputs CASES.jsonl --artifact MODEL.pt [--energy-audit AUDIT.json] \ + --output OUT_DIR [--gpus 0,1,2,3] [--factory uma|module:function] +""" +from __future__ import annotations + +import argparse +import json +import multiprocessing as mp +import os +import socket +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent + + +def _worker(gpu, queue, args, chunk_root): + os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) + import sys + sys.path.insert(0, str(HERE)) + from common import write_rows + import predict + calculator = predict.load_calculator(args.factory, args.artifact, "cuda") + while True: + item = queue.get() + if item is None: + return + chunk, rows = item + directory = chunk_root / chunk["chunk_id"] + if (directory / "worker.json").exists(): + continue + staging = chunk_root / f".{chunk['chunk_id']}.tmp" + staging.mkdir(parents=True, exist_ok=True) + write_rows(staging / "inputs.jsonl", rows) + started = time.monotonic() + predict.run(staging / "inputs.jsonl", staging / "out", args.factory, args.artifact, "cuda", + args.energy_audit, calculator=calculator, verbose=False) + for name in ("run.json", "predictions.jsonl"): + (staging / "out" / name).rename(staging / name) + (staging / "out").rmdir() + (staging / "worker.json").write_text(json.dumps({ + "worker_id": f"{socket.gethostname()}-gpu{gpu}", "chunk_id": chunk["chunk_id"], + "chunk_input_sha256": chunk["input_sha256"], "seconds": time.monotonic() - started})) + staging.rename(directory) + print(json.dumps({"chunk": chunk["chunk_id"], "gpu": gpu}), flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--inputs", type=Path, required=True) + parser.add_argument("--artifact", type=Path, required=True) + parser.add_argument("--energy-audit", type=Path) + parser.add_argument("--factory", default="uma") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--gpus", default=os.environ.get("CUDA_VISIBLE_DEVICES", "0")) + args = parser.parse_args() + import sys + sys.path.insert(0, str(HERE)) + from common import digest, indexed, read_rows + from distributed import chunk_plan, merge + cases = read_rows(args.inputs) + by_id = indexed(cases) + plan = chunk_plan(cases) + chunk_root = args.output.parent / f"{args.output.name}.chunks" + chunk_root.mkdir(parents=True, exist_ok=True) + ctx = mp.get_context("spawn") + queue = ctx.Queue() + for chunk in plan: + queue.put((chunk, [by_id[key] for key in chunk["case_ids"]])) + gpus = [g for g in args.gpus.split(",") if g != ""] + for _ in gpus: + queue.put(None) + procs = [ctx.Process(target=_worker, args=(g, queue, args, chunk_root)) for g in gpus] + for p in procs: + p.start() + for p in procs: + p.join() + # Chunks left by a crashed worker must not block interpreter exit on the queue's feeder thread. + queue.cancel_join_thread() + failed = [p.exitcode for p in procs if p.exitcode] + if failed: + raise SystemExit(f"worker failed with exit code {failed[0]}") + merge(args.inputs, chunk_root, plan, args.output, digest(args.artifact)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/15/154b329ae33e35d2e254590344f029ae4b85350111b0a9a00f0e95019db0ff25/test_scaffold.py b/reproduction/files/15/154b329ae33e35d2e254590344f029ae4b85350111b0a9a00f0e95019db0ff25/test_scaffold.py new file mode 100644 index 0000000000000000000000000000000000000000..3915233709bdefde04d20a24d43b11fc049d3fb7 --- /dev/null +++ b/reproduction/files/15/154b329ae33e35d2e254590344f029ae4b85350111b0a9a00f0e95019db0ff25/test_scaffold.py @@ -0,0 +1,96 @@ +from pathlib import Path + +import numpy as np + + +TASK_ROOT = Path(__file__).resolve().parents[1] +ENVIRONMENT = TASK_ROOT / "environment" +DELPHI = ENVIRONMENT / "references" / "delphi" + + +def test_task_metadata_is_versioned() -> None: + metadata = (TASK_ROOT / "task.toml").read_text(encoding="utf-8") + assert 'name = "ai4sci/natural-disease-progression"' in metadata + assert 'input_schema = "natural-disease-progression-input/v2"' in metadata + + +def test_task_layers_exist() -> None: + assert (ENVIRONMENT / "data" / "README.md").is_file() + assert (ENVIRONMENT / "references" / "scaffold" / "data.py").is_file() + assert (ENVIRONMENT / "references" / "scaffold" / "predict.py").is_file() + assert (ENVIRONMENT / "baseline" / "temporal-gru" / "longitudinal.py").is_file() + assert (ENVIRONMENT / "evaluation" / "score.py").is_file() + + +def test_agent_surface_is_neural_architecture_development() -> None: + instruction = (TASK_ROOT / "instruction.md").read_text(encoding="utf-8") + contract = (ENVIRONMENT / "contract.md").read_text(encoding="utf-8") + dockerfile = (ENVIRONMENT / "Dockerfile").read_text(encoding="utf-8") + assert "neural architecture development track" in instruction + assert "does not obtain its final predictions from LightGBM" in instruction + assert "fixed population time scaling" in contract + assert "COPY starter /workspace/starter" not in dockerfile + assert "COPY data /workspace/data" not in dockerfile + assert "maintenance" not in dockerfile + assert "starter/tabular_baseline.py" not in dockerfile + + +def test_real_evaluator_is_present() -> None: + source = (ENVIRONMENT / "evaluation" / "score.py").read_text() + assert "from risk_scoring import score" in source + assert "panel_scoring" in source + + +def test_verifier_separates_public_and_trusted_inputs() -> None: + main = (TASK_ROOT / "tests" / "main_verifier.py").read_text() + grader = (TASK_ROOT / "tests" / "grader.py").read_text() + assert "--trusted" not in main + assert "--trusted" in grader + + +def test_harbor_entry_runs_inference_not_unit_tests() -> None: + entry = (TASK_ROOT / "tests" / "test.sh").read_text() + assert "main_verifier.py" in entry + assert "pytest" not in entry + assert "/logs/verifier" in (TASK_ROOT / "tests" / "main_verifier.py").read_text() + + +def test_verifier_requires_review_readme_without_claiming_architecture_detection() -> None: + main = (TASK_ROOT / "tests" / "main_verifier.py").read_text(encoding="utf-8") + assert "submission/README.md is required for architecture review" in main + assert "cannot establish that infer.sh actually uses" in main + + +def test_verifier_main_installs_official_starter_inference_dependencies() -> None: + dockerfile = (TASK_ROOT / "tests" / "Dockerfile").read_text(encoding="utf-8") + for dependency in ("lightgbm==4.6.0", "joblib==1.5.3"): + assert dependency in dockerfile + + +def test_compose_mounts_do_not_expose_materialization_roots() -> None: + development = (ENVIRONMENT / "docker-compose.yaml").read_text() + verifier = (TASK_ROOT / "tests" / "docker-compose.yaml").read_text() + # task.toml owns the network policy (TASK_STANDARD); the compose file must not override it. + assert "network_mode" not in development + assert 'network_mode = "no-network"' in (TASK_ROOT / "task.toml").read_text() + assert "target: /workspace/data/train" in development + assert "target: /workspace/data/public/validation" in development + assert "target: /workspace/data/trusted/validation" in development + assert "target: /data" not in development + assert "/public/test" in verifier + assert "target: /trusted/test" in verifier + assert "target: /input" in verifier + assert "target: /trusted\n" not in verifier + + +def test_delphi_demo_data_has_uint32_triples() -> None: + for split in ("train", "val"): + data = np.memmap(DELPHI / "data" / "ukb_simulated_data" / f"{split}.bin", dtype=np.uint32, mode="r") + assert data.size > 0 + assert data.size % 3 == 0 + + +def test_vendored_python_compiles() -> None: + for name in ("model.py", "train.py", "utils.py", "configurator.py"): + source = (DELPHI / name).read_text(encoding="utf-8") + compile(source, str(DELPHI / name), "exec") diff --git a/reproduction/files/15/1553aceb037cf137db93f3156f0bb339ca179b773e58552a6400ad51b1699538/main_verifier.py b/reproduction/files/15/1553aceb037cf137db93f3156f0bb339ca179b773e58552a6400ad51b1699538/main_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..3cccd5b15e05a7610500ef9223af0d70221d5dc8 --- /dev/null +++ b/reproduction/files/15/1553aceb037cf137db93f3156f0bb339ca179b773e58552a6400ad51b1699538/main_verifier.py @@ -0,0 +1,292 @@ +#!/usr/bin/env python3 +"""Run the submitted calculator through every test suite as uid 10001 and seal the predictions. + +All suites run at the same time, each with its own workers spread over every visible GPU, inside one +shared time budget: physical (WBM discovery, MDR phonons, MP elasticity) with run_local.py, and +thermal conductivity, MOF bulk modulus, amorphous AM26, cleavage and Li-migration NEB with extra.py. +The long-tailed suites (MOF, NEB) get the most workers and start their most expensive items first. The evaluator code +drives every relaxation, displacement and strain; the submission only supplies the calculator. +At the shared time limit (3 h by default) every suite stops: the cases it finished are kept and the +rest are scored as failures. A suite that crashes is sealed as it is: the grader scores its missing +cases as failures (extra suites) or marks the suite invalid (physical suites). +""" +from __future__ import annotations + +import argparse +import json +import os +import pwd +import shutil +import signal +import stat +import subprocess +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +from verifier_common import sha256, tree_sha256, write_json + +EVALUATION = Path("/evaluation") if Path("/evaluation").is_dir() else Path(__file__).resolve().parents[1] / "environment/evaluation" +EXTRA_SUITES = ("kappa", "mof", "amorphous", "cleavage", "neb") +SUITES = ("physical",) + EXTRA_SUITES +SCHEMA = "atomistic-materials-prediction-snapshot/v2" +MAX_SNAPSHOT_BYTES = 8 * 1024 ** 3 +# Workers per GPU for each suite when they all run at once. MOF (EOS of large cells) and NEB (relaxed end +# points, then a climbing-image band) dominate the wall time, so they get the most workers; relaxations +# and phono3py leave a single worker's GPU mostly idle. +WORKERS_PER_GPU = {"physical": 2, "kappa": 2, "mof": 4, "amorphous": 1, "cleavage": 1, "neb": 3} + + +def harbor_reward(values): + """Harbor parses reward.json as a flat object of finite numbers; strings, None and nested details + belong in report.json / status.json.""" + import math as _math + return {k: v for k, v in values.items() if isinstance(v, (int, float)) and _math.isfinite(v)} + + +def validate_submission(root: Path): + root = root.resolve() + entry = root / "calculator.py" + if not entry.is_file() or entry.is_symlink(): + raise FileNotFoundError("submission/calculator.py required") + for path in root.rglob("*"): + if path.is_symlink() and not path.resolve().is_relative_to(root): + raise ValueError(f"submission symlink escapes package: {path.relative_to(root)}") + + +def validate_input(root: Path): + for suite in SUITES: + inputs = root / suite / "inputs" + if not inputs.is_dir(): + raise FileNotFoundError(f"missing verifier input: {inputs}") + if any(p.name.startswith(("references", "targets")) for p in (root / suite).rglob("*")): + raise ValueError(f"untrusted input contains references: {suite}") + + +def gpu_ids(): + if os.environ.get("CUDA_VISIBLE_DEVICES"): + return os.environ["CUDA_VISIBLE_DEVICES"] + out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True).stdout + return ",".join(str(i) for i in range(max(1, sum(line.startswith("GPU ") for line in out.splitlines())))) + + +def command(suite, inputs, submission, output, gpus): + py = "/opt/venv/bin/python" + if suite == "physical": + return [py, str(EVALUATION / "run_local.py"), "--inputs", str(inputs / "cases.jsonl"), "--factory", "submission", + "--artifact", str(submission), "--output", str(output), "--gpus", gpus] + return [py, str(EVALUATION / "extra.py"), "run", "--suite", suite, "--inputs", str(inputs), "--factory", "submission", + "--artifact", str(submission), "--output", str(output), "--gpus", gpus] + + +def _agent_processes(uid): + result = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + status = (entry / "status").read_text() + real_uid = int(next(line for line in status.splitlines() if line.startswith("Uid:")).split()[1]) + state = next(line for line in status.splitlines() if line.startswith("State:")).split()[1] + except (FileNotFoundError, PermissionError, StopIteration, ValueError): + continue + if real_uid == uid and state != "Z": + result.append(int(entry.name)) + return result + + +def _stop_untrusted(uid): + # SIGKILLed GPU workers can take tens of seconds to exit while the driver tears down their CUDA + # contexts (seen at the time limit, with ~100 workers killed at once). + deadline = time.monotonic() + 180 + while True: + for pid in _agent_processes(uid): + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + remaining = _agent_processes(uid) + if not remaining: + return + if time.monotonic() >= deadline: + raise RuntimeError(f"untrusted processes survived cleanup: {remaining}") + time.sleep(0.05) + + +def run_suite(suite, args, work, gpus, timeout): + agent = pwd.getpwnam("agent") + output = work / suite + env = {"PATH": "/opt/venv/bin:/usr/local/bin:/usr/bin:/bin", "HOME": agent.pw_dir, "PYTHONUNBUFFERED": "1", + "PIP_NO_INDEX": "1", "HF_HUB_OFFLINE": "1", "OMP_NUM_THREADS": "2", + # Many workers share each GPU; fewer fragmented blocks means fewer out-of-memory retries. + "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"} + + def demote(): + os.setgid(agent.pw_gid) + os.setuid(agent.pw_uid) + started = time.monotonic() + status = "complete" + with (work / f"{suite}.log").open("wb") as log: + process = subprocess.Popen(command(suite, args.input / suite / "inputs", args.submission, output, gpus), + cwd=work, env=env, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, preexec_fn=demote) + try: + code = process.wait(timeout=max(1, timeout)) + if code: + status = f"exit {code}" + except subprocess.TimeoutExpired: + status = "timeout" + finally: + # Only this suite's process group: the other suites are still running as the same user. + # Anything that left the group is killed by the user-wide sweep after the last suite. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if process.poll() is None: + process.wait() + return {"suite": suite, "status": status, "seconds": round(time.monotonic() - started, 1)} + + +def close_unfinished(suite, args, work): + """After the shared time limit: keep what a suite finished and mark the rest as failed cases. + + Physical: merge the finished chunks; the cases of unfinished chunks become failed records. + Extra suites: write the run record the driver would have written; items without a file are + scored as failures by score_extra.""" + import sys + sys.path.insert(0, str(EVALUATION)) + from common import digest, read_rows + reason = "verifier time limit reached" + output = work / suite + if suite == "physical": + from distributed import chunk_plan, merge + if (output / "run.json").exists(): + return + inputs = args.input / suite / "inputs" / "cases.jsonl" + merge(inputs, work / "physical.chunks", chunk_plan(read_rows(inputs)), output, digest(args.submission), + unfinished_reason=reason) + return + if (output / "run.json").exists(): + return + import hashlib + done = len(list((output / "items").glob("*.json"))) if (output / "items").is_dir() else 0 + manifest = args.input / suite / "inputs" / "manifest.json" + write_json(output / "run.json", { + "protocol": "atomistic-extra-suites-v1", "suite": suite, + "inputs_manifest_sha256": hashlib.sha256(manifest.read_bytes()).hexdigest(), + "checkpoint_sha256": digest(args.submission), "factory": "submission", + "completed": done, "complete": False, "unfinished_reason": reason}) + + +def _copy_snapshot(source: Path, destination: Path): + keep = ["run.json", "predictions.jsonl"] if (source / "predictions.jsonl").exists() else None + destination.mkdir(parents=True) + if not source.exists(): + return + for path in source.rglob("*"): + mode = path.lstat().st_mode + if path.is_symlink() or not (stat.S_ISREG(mode) or stat.S_ISDIR(mode)): + raise ValueError(f"prediction output contains non-regular entry: {path.relative_to(source)}") + if keep: + for name in keep: + shutil.copyfile(source / name, destination / name) + else: + for name in ("run.json",): + if (source / name).is_file(): + shutil.copyfile(source / name, destination / name) + if (source / "items").is_dir(): + shutil.copytree(source / "items", destination / "items") + + +def _lock(root: Path): + for path in sorted(root.rglob("*"), reverse=True): + os.chown(path, 0, 0, follow_symlinks=False) + os.chmod(path, 0o500 if path.is_dir() else 0o400, follow_symlinks=False) + os.chown(root, 0, 0) + os.chmod(root, 0o500) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--submission", type=Path, required=True) + p.add_argument("--input", type=Path, required=True) + p.add_argument("--sealed", type=Path, required=True) + p.add_argument("--output", type=Path, required=True) + p.add_argument("--timeout", type=int, default=10800, help="shared limit for all suites (s)") + p.add_argument("--grader-timeout", type=int, default=7200) + p.add_argument("--suites", default=",".join(SUITES)) + p.add_argument("--workers-per-gpu", type=int, default=0, help="same for every suite (default: WORKERS_PER_GPU)") + p.add_argument("--no-wait", action="store_true") + a = p.parse_args() + a.output.mkdir(parents=True, exist_ok=True) + try: + validate_submission(a.submission) + validate_input(a.input) + except (FileNotFoundError, ValueError) as error: + # The package, not the verifier, failed: every metric is unavailable and the run scores 0. + from grader import expanded_score, flatten + aggregate = expanded_score({}, valid=False) + write_json(a.output / "report.json", {"status": "invalid_submission", "error": str(error)[:2000], + "aggregate": aggregate}) + write_json(a.output / "reward.json", harbor_reward({"reward": 0.0, "crystal_potential_score": 0.0, + "invalid_submission": True, **flatten({})})) + return + work = a.output / "main" + work.mkdir() + agent = pwd.getpwnam("agent") + os.chown(work, agent.pw_uid, agent.pw_gid) + os.chmod(work, 0o700) + # The untrusted user reads a private copy of the package, whatever the snapshot's ownership. + package = work / "submission" + shutil.copytree(a.submission, package, symlinks=True) + for path in [package, *package.rglob("*")]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + a.submission = package + # Label-free inputs, likewise copied so their host permissions cannot block the untrusted user. + inputs = work / "inputs" + shutil.copytree(a.input, inputs) + for path in [inputs, *inputs.rglob("*")]: + os.chmod(path, 0o555 if path.is_dir() else 0o444) + original_input, a.input = a.input, inputs + devices = gpu_ids().split(",") + deadline = time.monotonic() + a.timeout + suites = a.suites.split(",") + + def launch(suite): + per_gpu = a.workers_per_gpu or WORKERS_PER_GPU[suite] + run = run_suite(suite, a, work, ",".join(devices * per_gpu), int(deadline - time.monotonic())) + print(json.dumps({"event": "suite_done", "workers": per_gpu * len(devices), **run}), flush=True) + return run + with ThreadPoolExecutor(max_workers=len(suites)) as pool: + runs = list(pool.map(launch, suites)) + _stop_untrusted(agent.pw_uid) + for run in runs: + if run["status"] == "timeout": + close_unfinished(run["suite"], a, work) + temporary = a.sealed.with_name(a.sealed.name + f".tmp-{os.getpid()}") + for suite in a.suites.split(","): + _copy_snapshot(work / suite, temporary / suite) + size = sum(f.stat().st_size for f in temporary.rglob("*") if f.is_file()) + if size > MAX_SNAPSHOT_BYTES: + raise ValueError("prediction snapshot exceeds 8 GiB") + snapshot = {"schema": SCHEMA, "runs": runs, + "inputs": {s: tree_sha256(original_input / s / "inputs") for s in a.suites.split(",")}, + "predictions": {s: tree_sha256(temporary / s) for s in a.suites.split(",")}} + write_json(temporary / "snapshot.json", snapshot) + _lock(temporary) + os.replace(temporary, a.sealed) + (a.sealed.parent / "READY").write_text(sha256(a.sealed / "snapshot.json") + "\n") + if not a.no_wait: + results = a.sealed.parent / "results" + end = time.monotonic() + a.grader_timeout + while not (results / "reward.json").is_file(): + if time.monotonic() >= end: + raise TimeoutError("grader did not publish reward") + time.sleep(2) + for name in ("report.json", "reward.json"): + shutil.copyfile(results / name, a.output / name) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/15/15779511279917cfb9d960cb391c0edf6e60b35d2b247738ad7fc93a38a399a5/runtime.sh b/reproduction/files/15/15779511279917cfb9d960cb391c0edf6e60b35d2b247738ad7fc93a38a399a5/runtime.sh new file mode 100644 index 0000000000000000000000000000000000000000..42175ee49fee7a9689a88ca2698a72cd2ca73d5e --- /dev/null +++ b/reproduction/files/15/15779511279917cfb9d960cb391c0edf6e60b35d2b247738ad7fc93a38a399a5/runtime.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -eo pipefail +# Upstream image's documented MPI/solver stack; fail clearly if it changes. +source /etc/profile +module purge +module load MAIA/1.0-NVHPC-26.1 +source /home/easybuild/venvs/hydrogym_gpu/bin/activate +set -u +export OMP_NUM_THREADS=1 +export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 +export PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 +exec "$@" diff --git a/reproduction/files/16/1649bbc73b03f29924a080b6fd4830d1efa5ced52914253d1f54ab0ef86a27f2/test_resource_audit.py b/reproduction/files/16/1649bbc73b03f29924a080b6fd4830d1efa5ced52914253d1f54ab0ef86a27f2/test_resource_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..7b217a16df214a97ce24c1c84dd189b94c5e1786 --- /dev/null +++ b/reproduction/files/16/1649bbc73b03f29924a080b6fd4830d1efa5ced52914253d1f54ab0ef86a27f2/test_resource_audit.py @@ -0,0 +1,74 @@ +"""Resource coverage checks, not native CFD or scientific acceptance tests.""" + +import copy +import importlib.util +import json +from pathlib import Path +import unittest + + +DATA = Path(__file__).resolve().parents[1] / "environment/data" +spec = importlib.util.spec_from_file_location("resource_audit", DATA / "resource_audit.py") +resource_audit = importlib.util.module_from_spec(spec) +spec.loader.exec_module(resource_audit) + + +class ResourceAuditTests(unittest.TestCase): + def setUp(self): + self.coverage = json.loads((DATA / "paper-coverage.json").read_text()) + self.catalog = json.loads((DATA / "catalog.json").read_text()) + self.report = resource_audit.audit(self.coverage, self.catalog) + + def test_complete_table_accounting_does_not_exclude_cases(self): + self.assertEqual(self.report["paper_rows"], 55) + self.assertEqual(sum(self.report["resource_counts"].values()), 55) + self.assertEqual(self.report["scope_exclusions"], []) + self.assertEqual(self.report["resource_counts"]["missing_payload"], 9) + self.assertAlmostEqual(self.report["missing_payload_fraction"], 9 / 55) + self.assertNotIn("cases", self.report) + + def test_checked_in_report_matches_reproducible_audit(self): + self.assertEqual(json.loads((DATA / "resource-audit.json").read_text()), self.report) + + def test_4140_is_not_silently_4200_or_a_missing_family(self): + row = next(r for r in self.report["rows"] if r["family"] == "cavity" + and r["dimension"] == 2 and r["parameters"]["Re"] == 4200) + self.assertEqual(row["resource_status"], "parameter_mismatch") + self.assertEqual(row["candidate_payloads"], []) + self.assertIn("Cavity_2D_Re4140", row["related_not_equivalent"]) + + def test_dra_marker_and_mach_are_not_usable_payloads(self): + rows = {r["parameters"]["Mach"]: r for r in self.report["rows"] + if r["family"] == "dra2303"} + self.assertEqual(rows[0.2]["resource_status"], "partial_variant_payload") + self.assertEqual(rows[0.7]["resource_status"], "missing_payload") + self.assertEqual(len(rows[0.7]["marker_only"]), 2) + self.assertEqual(rows[0.7]["candidate_payloads"], []) + + def test_firedrake_and_marl_are_not_discarded_for_adapter_gaps(self): + row = next(r for r in self.report["rows"] if r["family"] == "cylinder" + and r["dimension"] == 2 and r["parameters"]["Re"] == 100) + self.assertEqual(len(row["candidate_payloads"]), 2) + self.assertEqual(row["resource_status"], "candidate_payload_unvalidated") + marl = [r for r in self.report["rows"] if r["family"] == "cylinder-marl"] + self.assertEqual(len(marl), 2) + self.assertTrue(all(r["candidate_payloads"] for r in marl)) + self.assertTrue(all(r["evaluation_status"] == "not_full_suite_validated" for r in marl)) + + def test_other_reynolds_number_does_not_replace_channel180(self): + catalog = copy.deepcopy(self.catalog) + catalog["directories"] = [d for d in catalog["directories"] + if d["name"] != "TCFmini_3D_Re180"] + report = resource_audit.audit(self.coverage, catalog) + row = next(r for r in report["rows"] if r["family"] == "turbulent-channel") + self.assertEqual(row["resource_status"], "parameter_mismatch") + self.assertEqual(row["related_not_equivalent"], ["TCFlarge_3D_Re207"]) + + def test_reject_inconsistent_revision(self): + self.catalog["revision"] = "different" + with self.assertRaisesRegex(ValueError, "revisions"): + resource_audit.audit(self.coverage, self.catalog) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/17/1756e9907b650c8ec13b6d0b30c3c09297586db754ebdf7f18cf6c6566514c4c/fetch_baseline.py b/reproduction/files/17/1756e9907b650c8ec13b6d0b30c3c09297586db754ebdf7f18cf6c6566514c4c/fetch_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..18d8799fa33336072ca74bad903a60cfdb170aa3 --- /dev/null +++ b/reproduction/files/17/1756e9907b650c8ec13b6d0b30c3c09297586db754ebdf7f18cf6c6566514c4c/fetch_baseline.py @@ -0,0 +1,35 @@ +"""Download the pinned baseline using existing authorized Hugging Face access.""" + +import argparse +import json +from pathlib import Path +import shutil + +from huggingface_hub import hf_hub_download + +from common import digest, write_json + + +def fetch(output: Path): + baseline = json.loads(Path(__file__).with_name("baseline.json").read_text()) + if output.exists(): + raise FileExistsError(output) + downloaded = Path( + hf_hub_download( + baseline["repository"], + baseline["filename"], + revision=baseline["revision"], + ) + ) + if digest(downloaded) != baseline["sha256"]: + raise ValueError("Baseline checkpoint checksum mismatch") + output.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(downloaded, output) + write_json(output.with_suffix(".json"), baseline) + print(output) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + fetch(parser.parse_args().output) diff --git a/reproduction/files/17/1788a1f2895aae12e5639dbf83cccffcb00b5ef9b850b60ed7bf2f37057fe140/pipeline.py b/reproduction/files/17/1788a1f2895aae12e5639dbf83cccffcb00b5ef9b850b60ed7bf2f37057fe140/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..bd11880d35ab39a164b440ad048fcdfeebe13a55 --- /dev/null +++ b/reproduction/files/17/1788a1f2895aae12e5639dbf83cccffcb00b5ef9b850b60ed7bf2f37057fe140/pipeline.py @@ -0,0 +1,550 @@ +"""The designability pipeline: LigandMPNN inverse folding plus RoseTTAFold3 refolding. + +Runs inside the trusted grader only. It never imports, executes, or links against the +delivered submission; it consumes sealed coordinates. + +Criteria follow the benchmark's per-track `success.txt` (vendored at +environment/data/targets/*/success.txt). FOUR sequences per backbone on every track - +the task's own uniform budget, against 8 for enzyme and sm_binder upstream. The +criterion is "pass if ANY sequence passes", so fewer sequences can only lower a pass +rate; these are conservative against the published numbers, never flattering. + + enzyme 4 LigandMPNN sequences, 5 predictor models. Passes if ANY model for ANY + sequence has, after aligning on the motif backbone (N, CA, C), a motif + all-atom RMSD <= 1.5 A. + sm_binder 4 LigandMPNN sequences. backbone RMSD <= 1.5 A AND backbone-aligned + ligand RMSD <= 5 A AND interface min PAE <= 1.5 AND ipTM >= 0.8. + ppi_binder 4 ProteinMPNN sequences. min inter-chain PAE <= 1.5, plus binder + backbone RMSD <= 2 A. + unconditional + 4 ProteinMPNN sequences. backbone RMSD <= 1.5 A. + +LigandMPNN is selected exactly where the context carries a ligand; ProteinMPNN +otherwise. The enzyme ligand-clash term - the one published criterion measured on the raw +design rather than on the refold - is applied by grader.py before folding, purely to skip +a fold that cannot pass. The grader adds no criterion of its own; see +environment/evaluation/RESULTS.md. + +ipTM and PAE require a complex-capable predictor, which is why RoseTTAFold3 is used +rather than ESMFold: ESMFold is single-chain and emits neither, and cannot model a +protein-ligand complex at all. + +Pinned assets +------------- +LigandMPNN github.com/dauparas/LigandMPNN @ 26ec57ac976ade5379920dbd43c7f97a91cf82de + MIT. Weights fetched by its own get_model_params.sh, mirrored in + `environment/fetch_designability_weights.sh` with pinned sha256. + + The ORIGINAL repository, deliberately - not the re-implementation in + foundry's `models/mpnn`. Upstream itself says to "use the old repositories + ... for model benchmarking/comparison until the API and public weights + stabilize", and that warning is justified: run against the foundry + re-implementation, `ligand_mpnn` returned byte-identical sequences AND + confidences with and without a ligand that had 52 of 53 atoms within 5 A + of the backbone, reporting `ligand_interface_sequence_recovery=nan`. Its + ligand conditioning is inert, and ligand conditioning is the whole point + of two of the four tracks. + +RoseTTAFold3 github.com/RosettaCommons/foundry @ b02eed6a6bdf8f44d14a80cc36e3da13c9f2291c + BSD-3, IPD/UW. Source vendored at `environment/evaluation/rf3`; + parameters are a public download (files.ipd.uw.edu), pinned by sha256 in + `environment/fetch_designability_weights.sh`. + + RF3 replaces AlphaFold 3, whose parameters are not redistributable and so + had to be mounted by the operator - which kept designability off the + agent's own scoring path entirely. RF3's parameters ship, so the criterion + an agent optimises is the criterion it is graded on. + + NOTE the consequence for comparability: the per-track thresholds below come + from RFdiffusion3's published `success.txt`, which was calibrated with + AlphaFold. Scoring with a different predictor does not preserve those + numbers' published meaning. This is a deliberate, recorded trade. +""" + +import contextlib +import json +import os +import queue +import subprocess +import sys +import tempfile +import threading +from pathlib import Path + +import numpy as np + +from common import (IPTM_MIN, INTERFACE_PAE_MAX, LIGAND_RMSD_MAX, MODELS_PER_SEQUENCE, + MOTIF_RMSD_MAX, PPI_RMSD_MAX, SAMPLING_TEMPERATURE, SC_RMSD_MAX, + SEQUENCES_PER_BACKBONE, sha256) +from geometry import kabsch_rotation, superposed_rmsd, write_allatom_pdb +from residues import THREE_TO_ONE + +LIGANDMPNN_COMMIT = "26ec57ac976ade5379920dbd43c7f97a91cf82de" +RF3_REVISION = "b02eed6a6bdf8f44d14a80cc36e3da13c9f2291c" +RF3_CHECKPOINT = "rf3_foundry_01_24_latest_remapped.ckpt" +# model_type -> the checkpoint run.py expects for it. Both are fetched by +# environment/fetch_designability_weights.sh. +LIGANDMPNN_WEIGHTS = {"ligand_mpnn": "ligandmpnn_v_32_010_25.pt", + "protein_mpnn": "proteinmpnn_v_48_020.pt"} +BINDER_CHAIN = "A" +TARGET_CHAIN = "B" + + +class ScorerUnavailable(RuntimeError): + """Raised when the pipeline cannot run. Never degrades into a zero score.""" + + +def sequence_of(restypes): + return "".join(THREE_TO_ONE.get(name, "X") for name in restypes) + + +def _het_atom_name(element, index): + """PDB columns 13-16 for a ligand atom. Always exactly four characters. + + A one-character element sits in column 14 and a two-character element starts in 13, + so ` C12` is never confused with `CL1`. The index wraps rather than overflowing the + field: a ligand with more than 999 atoms would otherwise shift every later column, + and het atom names are never read back - LigandMPNN embeds these atoms by element + (`getElements()`), not by name. + """ + body = f"{index % 100:<2d}" # two digits is all the field has room for + name = f"{element[:2]}{body}" if len(element) >= 2 else f" {element}{body}" + assert len(name) == 4, name + return name + + +def verify_assets(assets_root, ligandmpnn_root): + """Fail loudly unless every pinned scoring asset is present. + + Every message names the one command that fixes it, because this runs on whatever + cluster the operator has and a missing checkpoint must not read as a broken task. + """ + assets_root, ligandmpnn_root = Path(assets_root), Path(ligandmpnn_root) + fetch = ("bash environment/fetch_designability_weights.sh " + f"{assets_root}") + + runner = ligandmpnn_root / "run.py" + if not runner.is_file(): + raise ScorerUnavailable( + f"LigandMPNN {LIGANDMPNN_COMMIT} is not installed at {ligandmpnn_root}. " + "Both images COPY it there from environment/evaluation/ligandmpnn, which vendors that " + "revision; outside an image, point LIGANDMPNN_ROOT at that directory.") + weights = assets_root / "ligandmpnn_params" + missing = [name for name in (LIGANDMPNN_WEIGHTS.values()) + if not (weights / name).is_file()] + if missing: + raise ScorerUnavailable( + f"LigandMPNN parameters missing from {weights}: {', '.join(missing)}. " + f"Run: {fetch}") + + try: + import rf3 # noqa: F401 + except ImportError as error: + raise ScorerUnavailable( + f"RoseTTAFold3 {RF3_REVISION} is not importable ({error}). Its source is " + "vendored at environment/evaluation/rf3; put that plus " + "starter/rfd3/src on PYTHONPATH.") + checkpoint = assets_root / "rf3" / RF3_CHECKPOINT + if not checkpoint.is_file(): + raise ScorerUnavailable( + f"The RoseTTAFold3 checkpoint is not at {checkpoint}. Run: {fetch}") + + return {"ligandmpnn": str(ligandmpnn_root), "ligandmpnn_params": str(weights), + "rf3_ckpt": str(checkpoint)} + + +def resolve_devices(devices=None): + """Which GPUs grading may use - one worker per device, in physical ordinals. + + Every fold and every inverse-folding call is already an isolated subprocess, so the + only thing needed to use N GPUs is to pin each subprocess to one of them. Ids are + taken from CUDA_VISIBLE_DEVICES when the environment restricts us, which keeps them + physical: the CUDA runtime reads that variable afresh in each child, so passing one + of the parent's ids through selects the same card the parent meant. + + Returns [None] when no GPU is visible, meaning "inherit the environment" - one + worker, unpinned, which is the single-GPU behaviour this used to have. + """ + if devices: + return [str(device) for device in devices] + visible = os.environ.get("CUDA_VISIBLE_DEVICES") + if visible is not None: + return [part.strip() for part in visible.split(",") if part.strip()] or [None] + try: + import torch + count = torch.cuda.device_count() + except Exception: # noqa: BLE001 - no torch, no GPU + count = 0 + return [str(index) for index in range(count)] or [None] + + +class DesignabilityScorer: + """Structure -> LigandMPNN sequences -> RoseTTAFold3 complexes -> per-track verdict. + + Thread-safe across `evaluate` calls: each one leases a GPU for its duration and pins + its subprocesses to it, so `grader.score_track` can fold `len(self.devices)` designs + at once. Nothing else is shared - the weights live in the child processes, and every + call works in its own temporary directory. + """ + + def __init__(self, assets_root="/assets", ligandmpnn_root="/opt/ligandmpnn", + timeout=3600, devices=None): + self.paths = verify_assets(assets_root, ligandmpnn_root) + self.timeout = timeout + self.devices = resolve_devices(devices) + self._free = queue.Queue() + for device in self.devices: + self._free.put(device) + self._leased = threading.local() + + @contextlib.contextmanager + def _lease(self): + """Hold one GPU for the length of one design's scoring.""" + device = self._free.get() + self._leased.device = device + try: + yield device + finally: + self._leased.device = None + self._free.put(device) + + def _env(self): + """Child environment, pinned to this thread's leased GPU if it has one.""" + env = dict(os.environ) + device = getattr(self._leased, "device", None) + if device is not None: + env["CUDA_VISIBLE_DEVICES"] = str(device) + return env + + # ---- inverse folding ------------------------------------------------ + def design_sequences(self, track, structure, context, motif_map): + """LigandMPNN sequences for one backbone, with the ligand in context.""" + coordinates, mask, restypes = structure + count = SEQUENCES_PER_BACKBONE[track] + with tempfile.TemporaryDirectory() as scratch: + scratch = Path(scratch) + target = scratch / "design.pdb" + write_allatom_pdb(target, coordinates, mask, restypes) + # LigandMPNN reads het atoms from the same file, so append the ligand. + ligand = context.get("ligand_coords") + has_ligand = ligand is not None and np.size(ligand) > 0 + if has_ligand: + names = context.get("ligand_ccd") + label = str(names[0]) if names is not None and len(names) else "LIG" + # LigandMPNN embeds each het atom by ELEMENT + # (`data_utils.parse_PDB` -> `getElements()` -> `element_dict`), so + # labelling the whole ligand carbon would hand the model the wrong + # chemistry. The context carries the real elements; use them. + elements = context.get("ligand_elements") + lines = target.read_text().splitlines() + lines = [line for line in lines if line not in ("TER", "END")] + for index, position in enumerate(np.asarray(ligand), start=1): + x, y, z = position + element = (str(elements[index - 1]).strip().upper() + if elements is not None and len(elements) >= index + else "C") + lines.append( + f"HETATM{9000 + index:>5d} {_het_atom_name(element, index)}" + f" {label:<3s} " + f"L{1:>4d} {x:>8.3f}{y:>8.3f}{z:>8.3f} 1.00 0.00" + + " " * 10 + f"{element:>2s}") + target.write_text("\n".join(lines + ["TER", "END"]) + "\n") + + # run.py reads the checkpoint belonging to --model_type, and every + # --checkpoint_* default is RELATIVE ("./model_params/..."). Passing only + # --checkpoint_ligand_mpnn while selecting protein_mpnn therefore resolves + # against the current directory and only works if it happens to be the + # LigandMPNN root. Pass the flag that matches the model. + model_type = "ligand_mpnn" if has_ligand else "protein_mpnn" + weights = {"ligand_mpnn": ("--checkpoint_ligand_mpnn", + "ligandmpnn_v_32_010_25.pt"), + "protein_mpnn": ("--checkpoint_protein_mpnn", + "proteinmpnn_v_48_020.pt")}[model_type] + command = [ + sys.executable, str(Path(self.paths["ligandmpnn"]) / "run.py"), + "--model_type", model_type, + weights[0], + str(Path(self.paths["ligandmpnn_params"]) / weights[1]), + "--pdb_path", str(target), + "--out_folder", str(scratch), + "--batch_size", "1", + "--number_of_batches", str(count), + "--temperature", str(SAMPLING_TEMPERATURE), + "--seed", "37", + ] + if motif_map: + # Motif residues keep their declared identities; only the scaffold is + # redesigned, which is what the enzyme criterion measures. + fixed = " ".join(f"{BINDER_CHAIN}{index + 1}" for index in sorted(motif_map)) + command += ["--fixed_residues", fixed] + result = subprocess.run(command, capture_output=True, text=True, + timeout=self.timeout, env=self._env()) + if result.returncode: + raise ScorerUnavailable(f"LigandMPNN failed: {result.stderr[-500:]}") + fasta = list((scratch / "seqs").glob("*.fa")) + if not fasta: + raise ScorerUnavailable("LigandMPNN produced no sequences") + sequences = [] + for line in fasta[0].read_text().splitlines(): + if line and not line.startswith(">"): + sequences.append(line.strip().split("/")[0]) + # The first record is the input sequence echoed back. + return (sequences[1:] or sequences)[:count] + + # ---- complex prediction --------------------------------------------- + def _components(self, sequence, context, scratch): + """RF3 `components` for one designed complex, plus the chains to template.""" + components = [{"seq": sequence, "chain_id": BINDER_CHAIN}] + templates = [] + + ccd = context.get("ligand_ccd") + if ccd is not None and len(ccd): + components += [{"ccd_code": str(code)} for code in ccd] + + target = context.get("target_coords") + if target is not None and np.size(target): + # TEMPLATE the target rather than handing RF3 its bare sequence. A natural + # target chain does not fold single-sequence - measured predicted-vs-native + # CA RMSD of 5.3-17.7 A across the five benchmark targets - and an interface + # scored against an unfolded target is meaningless. RF3 is trained on + # explicit atomic templates and its docs give templating as the way to fold + # a chain without an MSA. Measured with the template: target CA RMSD 0.097 A. + target_pdb = scratch / "target.pdb" + if not target_pdb.is_file(): + write_allatom_pdb( + target_pdb, np.asarray(target), + np.asarray(context["target_mask"], dtype=bool), + [str(res) for res in context["target_restypes"]], + chain=TARGET_CHAIN) + components.append({"path": str(target_pdb)}) + templates.append(TARGET_CHAIN) + return components, templates + + def predict_all(self, name, sequences, context, seeds): + """Fold every designed sequence in ONE RF3 invocation. + + Batching matters: RF3 loads a ~2.8 GB checkpoint per process, so folding eight + sequences as eight subprocesses spends most of its wall clock loading the same + weights. `inputs` takes a LIST of jobs, so one call covers a whole design. + + Returns {job name -> [model record, ...]}, in the order given. + """ + with tempfile.TemporaryDirectory() as scratch: + scratch = Path(scratch) + jobs, names = [], [] + for index, sequence in enumerate(sequences): + components, templates = self._components(sequence, context, scratch) + job_name = f"{name}-{index}" + job = {"name": job_name, "components": components} + if templates: + job["template_selection"] = templates + jobs.append(job) + names.append(job_name) + (scratch / "input.json").write_text(json.dumps(jobs)) + + # One seed; RF3 draws `diffusion_batch_size` diffusion samples from it, so + # that is what carries MODELS_PER_SEQUENCE. `seeds` is the caller's + # statement of how many models the criterion asks for. + command = [ + sys.executable, "-c", "from rf3.cli import app; app()", "fold", + f"inputs={scratch / 'input.json'}", + f"out_dir={scratch / 'out'}", + f"ckpt_path={self.paths['rf3_ckpt']}", + f"diffusion_batch_size={max(1, len(list(seeds)))}", + "seed=37", + ] + result = subprocess.run(command, capture_output=True, text=True, + timeout=self.timeout, env=self._env()) + if result.returncode: + raise ScorerUnavailable(f"RoseTTAFold3 failed: {result.stderr[-500:]}") + + out = {} + for job_name in names: + # RF3 writes `/seed-N_sample-M/_seed-N_sample-M_model.cif` + # plus one top-ranked `_model.cif`. Read the SAMPLES: the enzyme + # criterion is "any of 5 predictor models", and matching only the ranked + # file silently reduces that to one. `*model.cif` also matches + # AlphaFold's bare `model.cif`, so either layout works. + directory = scratch / "out" / job_name + samples = sorted(directory.rglob("seed-*_sample-*/*model.cif")) + if not samples: + samples = sorted(directory.rglob("*_model.cif")) + out[job_name] = [self._read_model(path) for path in samples] + return [out[job_name] for job_name in names] + + def predict(self, name, sequence, context, seeds): + """Fold one designed complex. Returns one record per model.""" + return self.predict_all(name, [sequence], context, seeds)[0] + + def _read_model(self, model_path): + """Extract designed-chain coordinates, ligand atoms, ipTM and interface PAE.""" + try: + import gemmi + except ImportError as error: + raise ScorerUnavailable(f"gemmi is required to read predictor output: {error}") + structure = gemmi.read_structure(str(model_path)) + structure.remove_alternative_conformations() + structure.remove_hydrogens() + tabulated = gemmi.find_tabulated_residue + + backbone, ligand = [], [] + for chain in structure[0]: + for residue in chain: + info = tabulated(residue.name) + if info is not None and info.is_amino_acid(): + if chain.name != BINDER_CHAIN: + continue + atoms = {a.name: [a.pos.x, a.pos.y, a.pos.z] for a in residue} + if {"N", "CA", "C"} <= set(atoms): + backbone.append({"name": residue.name, "atoms": atoms}) + elif not residue.is_water(): + ligand.extend([a.pos.x, a.pos.y, a.pos.z] for a in residue) + + # Two layouts: `_model.cif` beside `_summary_confidences.json`, + # and `seed-N_sample-M/model.cif` beside a bare `summary_confidences.json`. + stem = model_path.name.replace("_model.cif", "") + summary = model_path.parent / f"{stem}_summary_confidences.json" + if not summary.is_file(): + summary = model_path.parent / "summary_confidences.json" + iptm = interface_pae = None + if summary.is_file(): + payload = json.loads(summary.read_text()) + iptm = payload.get("iptm") + pairs = payload.get("chain_pair_pae_min") + if isinstance(pairs, list) and pairs: + values = [pairs[i][j] for i in range(len(pairs)) + for j in range(len(pairs[i])) if i != j + and isinstance(pairs[i][j], (int, float))] + interface_pae = min(values) if values else None + return {"backbone": backbone, "ligand": np.array(ligand) if ligand else None, + "iptm": iptm, "interface_pae": interface_pae} + + # ---- per-track criteria --------------------------------------------- + @staticmethod + def _motif_arrays(residues, indices): + """Atom14-shaped coordinates and mask for selected refolded residues.""" + from residues import ATOM14, ATOM14_WIDTH, atom_slot + coordinates = np.zeros((len(indices), ATOM14_WIDTH, 3)) + mask = np.zeros((len(indices), ATOM14_WIDTH), dtype=bool) + names = [] + for row, index in enumerate(indices): + if index >= len(residues): + return None, None, None + residue = residues[index] + names.append(residue["name"]) + if residue["name"] not in ATOM14: + continue + for atom, position in residue["atoms"].items(): + slot = atom_slot(residue["name"], atom) + if slot is not None: + coordinates[row, slot] = position + mask[row, slot] = True + return coordinates, mask, names + + def _motif_recapitulation(self, model, motif_map, context): + """Align refolded motif on N/CA/C, then score all shared motif atoms.""" + reference = context["motif_coords"] + reference_mask = np.asarray(context["motif_mask"], dtype=bool) + coordinates, mask, _ = self._motif_arrays(model["backbone"], motif_map) + if coordinates is None: + return None + shared = mask & reference_mask + frame = shared.copy() + frame[:, 3:] = False # align on N, CA, C only + if frame.sum() < 3: + # These contexts mostly carry fixed catalytic TIP atoms, not backbone: 25 of + # the 41 enzyme evaluation contexts have fewer than 3 backbone atoms in + # `motif_mask` (median 1, min 0). Returning None here made the criterion + # unsatisfiable by construction for 61% of the track. `geometry.py:: + # backbone_aligned_motif_rmsd` has always had this fallback; keep the two + # in step. + frame = shared + if shared.sum() < 3: + return None + mobile, target = coordinates[frame], reference[frame] + offset_mobile, offset_target = mobile.mean(axis=0), target.mean(axis=0) + rotation = kabsch_rotation(mobile - offset_mobile, target - offset_target) + moved = (coordinates[shared] - offset_mobile) @ rotation.T + offset_target + return float(np.sqrt(np.mean(np.sum((moved - reference[shared]) ** 2, axis=1)))) + + @staticmethod + def _backbone_rmsd_and_transform(model, design_ca): + """CA RMSD of a refolded chain against the design, plus the fitted transform.""" + refolded = np.array([r["atoms"]["CA"] for r in model["backbone"]]) + if refolded.shape[0] != design_ca.shape[0] or refolded.shape[0] < 3: + return None, None + offset_mobile, offset_target = refolded.mean(axis=0), design_ca.mean(axis=0) + rotation = kabsch_rotation(refolded - offset_mobile, design_ca - offset_target) + moved = (refolded - offset_mobile) @ rotation.T + offset_target + rmsd = float(np.sqrt(np.mean(np.sum((moved - design_ca) ** 2, axis=1)))) + return rmsd, (offset_mobile, rotation, offset_target) + + def evaluate(self, track, structure, context, motif_map=None): + """Run the track's published criterion. Returns a verdict dict.""" + with self._lease(): + return self._evaluate(track, structure, context, motif_map) + + def _evaluate(self, track, structure, context, motif_map): + coordinates, mask, restypes = structure + design_ca = coordinates[:, 1] + sequences = self.design_sequences(track, structure, context, motif_map) + seeds = list(range(MODELS_PER_SEQUENCE[track])) + best = {"passed": False, "sc_rmsd": float("inf"), "iptm": None, + "interface_pae": None, "ligand_rmsd": None, "motif_rmsd": None, + "sequences_tried": 0, "reason": "no sequence satisfied the criterion"} + + # One RF3 call for the whole design, not one per sequence - see predict_all. + # This does mean every sequence is folded rather than stopping at the first + # success; the criterion is "any sequence passes", so the verdict is identical. + folded = self.predict_all("design", sequences, context, seeds) + + for number, models in enumerate(folded): + best["sequences_tried"] = number + 1 + for model in models: + rmsd, transform = self._backbone_rmsd_and_transform(model, design_ca) + if rmsd is None: + continue + record = {"sc_rmsd": rmsd, "iptm": model["iptm"], + "interface_pae": model["interface_pae"], + "ligand_rmsd": None, "motif_rmsd": None} + + if track == "enzyme": + # Passes on motif recapitulation alone, by any model of any + # sequence. The ligand-clash half of the criterion is a geometry + # check on the design and is applied by the grader. + record["motif_rmsd"] = self._motif_recapitulation( + model, motif_map or [], context) + ok = (record["motif_rmsd"] is not None + and record["motif_rmsd"] <= MOTIF_RMSD_MAX) + elif track == "sm_binder": + ligand = context.get("ligand_coords") + if model["ligand"] is not None and ligand is not None and \ + model["ligand"].shape == np.asarray(ligand).shape: + origin, rotation, destination = transform + moved = (model["ligand"] - origin) @ rotation.T + destination + record["ligand_rmsd"] = float(np.sqrt(np.mean( + np.sum((moved - np.asarray(ligand)) ** 2, axis=1)))) + ok = (rmsd <= SC_RMSD_MAX + and record["ligand_rmsd"] is not None + and record["ligand_rmsd"] <= LIGAND_RMSD_MAX + and record["interface_pae"] is not None + and record["interface_pae"] <= INTERFACE_PAE_MAX + and record["iptm"] is not None + and record["iptm"] >= IPTM_MIN) + elif track == "ppi_binder": + # success.txt gives no PAE threshold for this track; the + # sm_binder value is reused and flagged as inferred. + ok = (rmsd <= PPI_RMSD_MAX + and record["interface_pae"] is not None + and record["interface_pae"] <= INTERFACE_PAE_MAX) + else: + ok = rmsd <= SC_RMSD_MAX + + if rmsd < best["sc_rmsd"]: + best.update(record) + if ok: + best.update(record) + best["passed"] = True + best["reason"] = None + return best + return best diff --git a/reproduction/files/18/18303172092c875b81bbb92d12d0c42e94404f0ee430741b1941645320036c5f/physics.py b/reproduction/files/18/18303172092c875b81bbb92d12d0c42e94404f0ee430741b1941645320036c5f/physics.py new file mode 100644 index 0000000000000000000000000000000000000000..96074b7545e9f93f95a0644a6823d5e3e4da28da --- /dev/null +++ b/reproduction/files/18/18303172092c875b81bbb92d12d0c42e94404f0ee430741b1941645320036c5f/physics.py @@ -0,0 +1,139 @@ +"""Fixed protocols adapted from FAIRChem's MIT-licensed UMA benchmark recipes. + +See THIRD_PARTY_NOTICES.md and PROTOCOLS.md for source revision and differences. +The calculator receives geometry only. These routines never open target files. +""" + +from __future__ import annotations + +import numpy as np +from ase import units +from ase.build import make_supercell +from ase.filters import FrechetCellFilter +from ase.optimize import FIRE +from phonopy import Phonopy +from phonopy.harmonic.dynmat_to_fc import get_commensurate_points +from phonopy.structure.atoms import PhonopyAtoms +from pymatgen.analysis.elasticity import DeformedStructureSet, ElasticTensor, Strain +from pymatgen.core import Structure +from pymatgen.io.phonopy import get_pmg_structure, get_phonopy_structure + +from common import decode_atoms, encode_atoms + +THZ_TO_K = units._hplanck * 1e12 / units._k + + +def relax(atoms, calculator, *, fmax=0.02, cell=True): + atoms.calc = calculator + optimizer = FIRE(FrechetCellFilter(atoms) if cell else atoms, logfile=None) + converged = optimizer.run(fmax=fmax, steps=500) + return {"converged": bool(converged), "steps": optimizer.nsteps} + + +def discovery(case, calculator): + atoms = decode_atoms(case["atoms"]) + diagnostics = relax(atoms, calculator) + return { + "energy": float(atoms.get_potential_energy()), + "atoms": encode_atoms(atoms), + "diagnostics": diagnostics, + } + + +def make_phonon(case): + atoms = decode_atoms(case["atoms"]) + cell = PhonopyAtoms( + numbers=atoms.numbers, + positions=atoms.positions, + cell=atoms.cell.array, + masses=case["phonon"]["masses"], + ) + return Phonopy( + cell, + supercell_matrix=case["phonon"]["supercell_matrix"], + primitive_matrix=case["phonon"]["primitive_matrix"], + symprec=1e-4, + ) + + +def phonon_observables(phonon): + # Same commensurate q-points as upstream; retain negative frequencies. + qpoints = get_commensurate_points(phonon.supercell_matrix) + phonon.run_qpoints(qpoints) + frequencies = phonon.get_qpoints_dict()["frequencies"] * THZ_TO_K + phonon.run_mesh((20, 20, 20)) + phonon.run_thermal_properties(t_min=0, t_max=600, t_step=75) + thermal = phonon.get_thermal_properties_dict() + index = list(thermal["temperatures"]).index(300) + return { + "max_freq": float(frequencies.max()), + "avg_freq": float(frequencies.mean()), + **{ + key: float(thermal[key][index]) + for key in ("entropy", "heat_capacity", "free_energy") + }, + } + + +def phonons(case, calculator): + reference_geometry = make_phonon(case) # no DFT force constants + primitive = get_pmg_structure(reference_geometry.primitive).to_ase_atoms() + diagnostics = relax(primitive, calculator, fmax=0.005) + transform = ( + np.linalg.inv(reference_geometry.primitive_matrix.T) + if reference_geometry.primitive_matrix is not None + else np.eye(3) + ) + # Guard against silently truncating a nonintegral transformation. + if not np.allclose(transform, np.rint(transform), atol=1e-8): + raise ValueError("Nonintegral primitive-to-unit-cell transformation") + unitcell = make_supercell(primitive, np.rint(transform).astype(int)) + phonon = Phonopy( + get_phonopy_structure(Structure.from_ase_atoms(unitcell)), + reference_geometry.supercell_matrix, + primitive_matrix=reference_geometry.primitive_matrix, + symprec=1e-4, + ) + phonon.generate_displacements(distance=0.01) + phonon.forces = [ + calculator.get_forces(get_pmg_structure(cell).to_ase_atoms()) + for cell in phonon.supercells_with_displacements + ] + phonon.produce_force_constants(fc_calculator="traditional") + # No post-fit force-constant symmetrization, matching the UMA protocol. + diagnostics.update( + n_displacements=len(phonon.supercells_with_displacements), + supercell_atoms=len(phonon.supercell), + ) + return {**phonon_observables(phonon), "diagnostics": diagnostics} + + +def elasticity(case, calculator): + atoms = decode_atoms(case["atoms"]) + diagnostics = relax(atoms, calculator) + equilibrium_stress = atoms.get_stress(voigt=False) + deformations = DeformedStructureSet( + Structure.from_ase_atoms(atoms), + norm_strains=(-0.01, -0.005, 0.005, 0.01), + shear_strains=(-0.06, -0.03, 0.03, 0.06), + ) + stresses, relaxation_results = [], [] + for structure in deformations: + strained = structure.to_ase_atoms() + relaxation_results.append(relax(strained, calculator, cell=False)) + stresses.append(strained.get_stress(voigt=False)) + tensor = ElasticTensor.from_independent_strains( + [Strain.from_deformation(d) for d in deformations.deformations], + stresses, + eq_stress=equilibrium_stress, + ) + diagnostics["strained_relaxations"] = relaxation_results + return { + "bulk_modulus_vrh": float(tensor.k_vrh / units.GPa), + "shear_modulus_vrh": float(tensor.g_vrh / units.GPa), + "elastic_tensor_GPa": (tensor.voigt / units.GPa).tolist(), + "diagnostics": diagnostics, + } + + +CALCULATIONS = {"discovery": discovery, "phonons": phonons, "elasticity": elasticity} diff --git a/reproduction/files/18/18f409937d30e1f78dd33ca4ac2fc24db941a319443551146fb09ad505dfb472/native_settings.py b/reproduction/files/18/18f409937d30e1f78dd33ca4ac2fc24db941a319443551146fb09ad505dfb472/native_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..9f7a25f35ce2904c1e1672013d1b749b5c94a3dc --- /dev/null +++ b/reproduction/files/18/18f409937d30e1f78dd33ca4ac2fc24db941a319443551146fb09ad505dfb472/native_settings.py @@ -0,0 +1,86 @@ +"""Reviewed scalar MAIA settings; never alter geometry or replace native rewards.""" + +import math + +from protocol import InfrastructureError + + +ATTRIBUTES = { + "max_episode_steps": "max_episode_steps", + "substeps_per_action": "num_substeps_per_iteration", + "max_control": "MAX_CONTROL", + "omega": "omega", +} + + +def validate_settings(settings, horizon, episode_end="native"): + if episode_end not in ("native", "time_limit"): + raise InfrastructureError("Unknown reviewed episode_end convention") + if not isinstance(settings, dict) or set(settings) - ATTRIBUTES.keys(): + raise InfrastructureError("Unknown/invalid reviewed native settings") + for key, value in settings.items(): + if key in ("max_episode_steps", "substeps_per_action"): + minimum = 0 if key == "max_episode_steps" else 1 + if type(value) is not int or value < minimum: + raise InfrastructureError(f"Invalid native setting: {key}") + elif type(value) not in (int, float) or not math.isfinite(value) or value < 0: + raise InfrastructureError(f"Invalid native setting: {key}") + if key == "max_control" and value == 0: + raise InfrastructureError("Native actuator limit must be positive") + offset = 1 if episode_end == "native" else 0 + if "max_episode_steps" in settings and settings["max_episode_steps"] + offset != horizon: + raise InfrastructureError("Native completion setting and reviewed horizon disagree") + + +def apply_settings(env, case): + settings = case.get("native_settings", {}) + episode_end = case.get("episode_end", "native") + validate_settings(settings, case["horizon"], episode_end) + defaults = {} + for key, attribute in ATTRIBUTES.items(): + if not hasattr(env, attribute): + raise InfrastructureError(f"Pinned MAIA attribute missing: {attribute}") + value = getattr(env, attribute) + defaults[key] = int(value) if key in ("max_episode_steps", "substeps_per_action") else float(value) + for key, value in settings.items(): + setattr(env, ATTRIBUTES[key], value) + effective = {key: settings.get(key, value) for key, value in defaults.items()} + offset = 1 if episode_end == "native" else 0 + if env.max_episode_steps + offset != case["horizon"]: + raise InfrastructureError("Native horizon differs from the reviewed release") + return {"native_defaults": defaults, "effective": effective, "episode_end": episode_end} + + +def with_episode_limit(env, case): + """Apply the same reviewed boundary in training and independent evaluation. + + Legacy releases keep their native flags. Public StepCounter reconstructions + leave native max_episode_steps=horizon and truncate before native completion. + Never hide an early/native failure by relabelling it a timeout. + """ + if case.get("episode_end", "native") == "native": + return env + validate_settings(case.get("native_settings", {}), case["horizon"], case["episode_end"]) + import gymnasium as gym + + class ReviewedTimeLimit(gym.Wrapper): + def __init__(self): + super().__init__(env) + self.count = None + self.reviewed_protocol = env.reviewed_protocol + + def reset(self, **kwargs): + result = self.env.reset(**kwargs) + self.count = 0 + return result + + def step(self, action): + if self.count is None or self.count >= case["horizon"]: + raise InfrastructureError("Reset is required before another reviewed episode") + observation, reward, terminated, truncated, info = self.env.step(action) + self.count += 1 + if terminated or truncated: + raise InfrastructureError("Native completion preceded the reviewed external time limit") + return observation, reward, False, self.count == case["horizon"], info + + return ReviewedTimeLimit() diff --git a/reproduction/files/1a/1a17e381a1e20dff632e5a127d68deafe4786c27271e64de619787dff4f841c2/native_verifier.py b/reproduction/files/1a/1a17e381a1e20dff632e5a127d68deafe4786c27271e64de619787dff4f841c2/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..a55808bd5e6b677cdc1d03bf36b20bc6083fc2b0 --- /dev/null +++ b/reproduction/files/1a/1a17e381a1e20dff632e5a127d68deafe4786c27271e64de619787dff4f841c2/native_verifier.py @@ -0,0 +1,400 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import re +import shutil +import signal +import socket +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def enter_offline_namespace(): + import offline_network + record = offline_network.configure(STATE) + libc = ctypes.CDLL(None, use_errno=True) + for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)): + fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC) + try: + if libc.setns(fd, flag): + raise OSError(ctypes.get_errno(), 'enter offline verifier namespace') + finally: + os.close(fd) + if socket.if_nameindex() != [(1, 'lo')]: + raise RuntimeError('Offline verifier namespace has external interfaces') + return record + + +def validate_ready_marker(sealed_root): + """Accept either upstream seal format, always checking the exact snapshot. + +Surface-code uses JSON with a run ID. Molecular, Genome and Protein-sequence +use a plain SHA-256 line. The original scientific grader rechecks the seal. +""" + root = Path(sealed_root) + raw = (root/'READY').read_text().strip() + snapshot = root/'run/snapshot.json' + observed = hashlib.sha256(snapshot.read_bytes()).hexdigest() + if re.fullmatch('[0-9a-f]{64}', raw): + if raw != observed: + raise RuntimeError('Native seal marker is inconsistent') + return + marker = json.loads(raw) + if (not isinstance(marker, dict) or marker.get('snapshot_sha256') != observed + or not isinstance(marker.get('run_id'), str) + or json.loads(snapshot.read_text()).get('run_id') != marker['run_id']): + raise RuntimeError('Native seal marker is inconsistent') + + +def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')): + """End the native waiting supervisor only after its authenticated seal.""" + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + seconds + sealed_ready = False + try: + while process.poll() is None: + if (sealed_root / 'READY').is_file(): + validate_ready_marker(sealed_root) + sealed_ready = True + break + if time.monotonic() >= deadline: + raise TimeoutError('Verifier inference budget exhausted') + time.sleep(.1) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode) + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def copy_readonly_benchmark(source, destination, verify_contents=False): + """Change permissions only on a private local copy of the input mount.""" + source, destination = Path(source), Path(destination) + if destination.exists(): + raise RuntimeError('Expected a fresh local benchmark directory') + shutil.copytree(source, destination, symlinks=False) + hashes = {} + def digest_file(path): + digest = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(block) + return digest.hexdigest() + for path in [destination, *destination.rglob('*')]: + path.chmod(0o555 if path.is_dir() else 0o444) + if verify_contents and path.is_file(): + relative = path.relative_to(destination) + digest = digest_file(path) + if digest_file(source / relative) != digest: + raise RuntimeError(f'Local benchmark copy differs: {relative}') + hashes[str(relative)] = digest + return dict(source_permissions_modified=False, verified_file_sha256=hashes) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + adapted = cfg.get('adapted_permissions', False) + if adapted: + import adapted_boundary + adapted_boundary.no_new_privileges() + os.setgroups([]) + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + crystal_cache_receipt = None + if cfg.get('isolated_crystal_dataset_cache'): + if plan['task'] != 'crystal-structure-generation' or phase != 'score': + raise RuntimeError('Crystal cache isolation is for trusted grading only') + import crystal_cache + crystal_cache_receipt = crystal_cache.prepare( + '/scorer-assets/huggingface/datasets', os.environ['HF_DATASETS_CACHE']) + crystal_cache_receipt['asset_manifest_sha256'] = hashlib.sha256( + Path('/scorer-assets/READY.json').read_bytes()).hexdigest() + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if cfg.get('local_benchmark_copy'): + status('copying_benchmark', task=plan['task'], role=phase) + # The GPU Landlock policy grants existing root children. Create this + # local root child first, so the later policy can grant it read access. + # This is trusted input staging; no submitted code has run yet. + receipt = copy_readonly_benchmark('/source-benchmark', '/benchmark', + cfg.get('verify_benchmark_copy', False)) + runtime.write_json(STATE / 'benchmark-copy.json', receipt) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus'], strict_allocation=adapted) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + if adapted: + adapted_boundary.exact_gpu_allocation(gpu_policy) + else: + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + if cfg.get('gpu_runtime', 'torch') == 'torch' and not adapted: + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + if phase == 'inference': + status('copying_submission', task=plan['task'], role=phase) + if cfg.get('native_uid_isolation'): + # The original PDE verifier explicitly supports this UID fallback. + # The mount is below a local root-only parent, never chmod shared data. + Path('/private').chmod(0o700) + Path('/tests').chmod(0o700) + elif plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + status('checking_submission', task=plan['task'], role=phase) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + try: + agent = pwd.getpwuid(10001) + except KeyError: + subprocess.run(['/usr/sbin/useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + status('setting_submission_permissions', task=plan['task'], role=phase) + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + # Some native images precreate this empty container-local mountpoint. + # rmdir fails closed if it contains anything; never remove existing logs. + if Path('/logs/verifier').is_dir() and not Path('/logs/verifier').is_symlink(): + Path('/logs/verifier').rmdir() + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + if adapted and cfg.get('network_policy') != 'policy-children-only': + adapted_boundary.restrict_network() + elif not offline and not adapted: + runtime.deny_network() + if not adapted: + writable_roots = ['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc', + *cfg.get('writable_runtime_paths', [])] + if crystal_cache_receipt: + # The native image links /scorer-assets beneath /workspace. A + # writable ancestor defeats a read-only Landlock child rule. + # Trusted grading needs its output and scratch directories only. + writable_roots.remove('/workspace') + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets', + *cfg.get('readonly_runtime_paths', [])], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=writable_roots) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + if adapted: + source_audit = adapted_boundary.audit_source_permissions( + ['/operator', '/submission-source', '/source-benchmark', '/benchmark', '/data', '/labels', '/private'], + untrusted_uids=tuple(range(10001, 10009))) + else: + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if crystal_cache_receipt: + try: + fd = os.open('/scorer-assets/READY.json', os.O_WRONLY | os.O_CLOEXEC) + except PermissionError: + crystal_cache_receipt['asset_write_denied'] = True + else: + os.close(fd) + raise RuntimeError('Prepared scorer assets remain writable') + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' and not adapted else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())); ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + if cfg.get('gpu_runtime') == 'jax': + probe = ('import jax; import jax.numpy as jnp; ' + f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in d.device_kind for d in jax.devices("gpu")); ' + 'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 ' + 'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + if adapted and plan['task'] == 'fluid-flow-control': + # native_runtime.sh loads a module-provided libpython. Preserve + # only these runtime settings, never credentials, in the probe. + for key in ('PATH', 'LD_LIBRARY_PATH', 'OMP_NUM_THREADS', + 'OPENBLAS_NUM_THREADS', 'XLA_PYTHON_CLIENT_PREALLOCATE'): + if key in os.environ: + probe_env[key] = os.environ[key] + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + def dependency_identity(): + os.setgroups([]); os.setgid(10001); os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + cache=Path('/tmp/verifier-cache');cache.mkdir(exist_ok=True) + os.chown(cache,10001,10001) + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True, + preexec_fn=dependency_identity if cfg.get('untrusted_whole_verifier') else None) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': ('seccomp in unprivileged policy children; trusted simulator retains MPI sockets' + if cfg.get('network_policy') == 'policy-children-only' else + 'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children'), + 'offline_namespace': offline, + 'source_mounts': f'POSIX permission audit ({source_audit} entries); non-root submission' if adapted else 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan.get('label_isolated', plan['task'] != 'protein-folding-prediction'), + 'adapted_execution': adapted, + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + if cfg.get('stop_after_sealed_ready'): + # The native supervisor has already killed all model processes and + # sealed/hashes its predictions before writing READY. End only its + # wait-for-grader loop; the unchanged grader runs in a separate job. + result = run_until_sealed(cfg['command'], log, remaining) + else: + def run_identity(): + os.setgroups([]) + os.setgid(10001) + os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + os.chown(STATE / 'results', 10001, 10001) + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True, + preexec_fn=run_identity if cfg.get('untrusted_whole_verifier') else None) + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + if cfg.get('verify_crystal_assets_after'): + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted before post-score asset validation') + with (STATE / 'asset-validation-after.log').open('w') as log: + subprocess.run([cfg['driver_python'], '-c', + 'import sys;sys.path.insert(0,"/tests");from pathlib import Path;' + 'from grader import validate_assets;validate_assets(Path("/scorer-assets"));' + 'print("ORIGINAL_SCORER_ASSET_DIGEST_OK")'], + stdout=log, stderr=subprocess.STDOUT, timeout=remaining, check=True) + if hashlib.sha256(Path('/scorer-assets/READY.json').read_bytes()).hexdigest() != crystal_cache_receipt['asset_manifest_sha256']: + raise RuntimeError('Scorer asset manifest changed during grading') + crystal_cache_receipt['original_asset_digest_after'] = 'passed' + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + elapsed = time.monotonic() - entered + reward_path = STATE / 'results/reward.json' + if phase == 'score': + score_root = Path('/sealed/results') + if cfg.get('results_by_run_id'): + score_root /= json.loads(Path('/sealed/READY').read_text())['run_id'] + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = score_root / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/1c/1c96f70bde6addcf83179c92f5e5a0a4b2aeb5c8bed1c5bfea6a5a167ff575b1/grader.py b/reproduction/files/1c/1c96f70bde6addcf83179c92f5e5a0a4b2aeb5c8bed1c5bfea6a5a167ff575b1/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..a082fc4de18df05d8eba1830279c749ed010b24d --- /dev/null +++ b/reproduction/files/1c/1c96f70bde6addcf83179c92f5e5a0a4b2aeb5c8bed1c5bfea6a5a167ff575b1/grader.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Trusted labels-only service; never executes a submitted model or source.""" +from __future__ import annotations +import argparse +import json +from pathlib import Path +import sys +import time +from typing import Any +PROJECT = Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" if (Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit").is_dir() else Path(__file__).resolve().parents[1] # the baseline project: environment/baseline/alphaqubit here, /opt/task in the verifier image +sys.path.insert(0, str(PROJECT)) +from qecbench.data import contained, sha256, write_json +from qecbench.scoring import InvalidPrediction, score + + +def grade(sealed: Path, inputs: Path, labels: Path, config: Path, output: Path, + ready: dict[str, Any]) -> None: + run_id = ready["run_id"] + target = output / run_id + target.mkdir(parents=True) + try: + snapshot_path = contained(sealed, "snapshot.json") + if sha256(snapshot_path) != ready["snapshot_sha256"]: + raise ValueError("Sealed snapshot hash mismatch") + snapshot = json.loads(snapshot_path.read_text()) + if snapshot.get("schema") != "surface-code-decoding-snapshot/v1" or snapshot.get("run_id") != run_id: + raise ValueError("Sealed snapshot identity mismatch") + if snapshot.get("input_manifest_sha256") != sha256(inputs / "manifest.json"): + raise ValueError("Input/snapshot mismatch") + actual = {path.name for path in sealed.iterdir() if path.name != "snapshot.json"} + if actual != set(snapshot["files"]): + raise ValueError("Sealed snapshot file coverage mismatch") + for name, digest in snapshot["files"].items(): + if sha256(contained(sealed, name)) != digest: + raise ValueError("Sealed prediction checksum mismatch") + try: + result = score(inputs, sealed, labels, config) + except InvalidPrediction as error: + result = {"schema": "surface-code-decoding-report/v1", "status": "invalid_prediction", + "model_quality_measured": False, "score": 0.0, "score_unclipped": None, + "performance": None, "error": str(error)} + result["run_id"] = run_id + write_json(target / "report.json", result) + write_json(target / "reward.json", {"reward": result["performance"]}) # raw P; the normalized score stays in report.json + except Exception as error: + write_json(target / "report.json", {"schema": "surface-code-decoding-report/v1", "run_id": run_id, + "status": "infrastructure_error", "model_quality_measured": False, + "error": f"{type(error).__name__}: {error}"}) + write_json(target / "DONE", {"run_id": run_id}) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--sealed", type=Path, default=Path("/sealed/run")) + parser.add_argument("--input", type=Path, default=Path("/benchmark")) + parser.add_argument("--labels", type=Path, default=Path("/private")) + parser.add_argument("--config", type=Path, default=Path("/opt/task/score_config.json")) + parser.add_argument("--output", type=Path, default=Path("/sealed/results")) + parser.add_argument("--wait-seconds", type=int, default=3900) + args = parser.parse_args() + deadline = time.monotonic() + args.wait_seconds + while time.monotonic() < deadline: + ready = args.sealed.parent / "READY" + if ready.is_file(): + payload = json.loads(ready.read_text()) + run_id = payload.get("run_id", "") + if len(run_id) != 32 or any(c not in "0123456789abcdef" for c in run_id): + raise ValueError("Invalid trusted run identity") + grade(args.sealed, args.input, args.labels, args.config, args.output, payload) + return + time.sleep(0.25) + raise TimeoutError("Inference supervisor did not seal a submission") + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/1d/1d5ba0e3f6977b88e95f7c60f3e009a37ea398b47c5488deb44875335aff74e5/test_research_tools.py b/reproduction/files/1d/1d5ba0e3f6977b88e95f7c60f3e009a37ea398b47c5488deb44875335aff74e5/test_research_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..300af3d01c0e627dd8f809825e8f5c2c123bd329 --- /dev/null +++ b/reproduction/files/1d/1d5ba0e3f6977b88e95f7c60f3e009a37ea398b47c5488deb44875335aff74e5/test_research_tools.py @@ -0,0 +1,325 @@ +"""Regression tests for interrupted publication and scientific feedback.""" + +import hashlib +import importlib.util +import json +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'environment/evaluation')) + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +publication = load('publication', ROOT / 'environment/baseline/starter/publication.py') +diagnostics = load('diagnostics', ROOT / 'environment/evaluation/diagnostics.py') +sys.modules['diagnostics'] = diagnostics +score = load('validation_score', ROOT / 'environment/evaluation/score.py') +paired = load('paired_score', ROOT / 'environment/evaluation/paired_bootstrap.py') +sys.path.insert(0, str(ROOT / 'tests')) +import main_verifier + + +def build(stage, marker): + (stage / 'README.md').write_text(marker) + (stage / 'weights.pt').write_bytes(marker.encode()) + (stage / 'config.json').write_text('{}') + (stage / 'infer.sh').write_text('#!/bin/bash\nprintf "%s\\n" ' + marker + '\n') + (stage / 'model_manifest.json').write_text(json.dumps({ + 'schema': 'massspecgym-retrieval-model/v1', + 'checkpoint': {'path': 'weights.pt', 'sha256': hashlib.sha256(marker.encode()).hexdigest(), 'format': 'pytorch'}, + 'model_config': 'config.json', 'training_provenance': {'data': 'fixture', 'pretrained_assets': []}, + })) + + +class NativePublicationTests(unittest.TestCase): + def setUp(self) -> None: + import torch + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.native = load('native_publish', ROOT / 'environment/baseline/starter/glacier/publish.py') + self.checkpoint = self.root / 'trained.ckpt' + self.state = { + 'state_dict': {'fixture.weight': torch.tensor([1.0, 2.0])}, + 'hyper_parameters': json.loads((ROOT / 'environment/baseline/starter/glacier/config.json').read_text()), + 'pytorch-lightning_version': '2.6.5', 'global_step': 10, 'epoch': 1, + 'task_training': {'initialization': 'random', 'batch_size': 8, + 'data_manifest_sha256': 'a' * 64}, + } + torch.save(self.state, self.checkpoint) + self.fallback = self.root / 'fallback' + self.fallback.mkdir() + build(self.fallback, 'trained-fallback-fixture') + self.source = self.root / 'source' + (self.source / 'src/ms_pred').mkdir(parents=True) + (self.source / 'src/ms_pred/__init__.py').write_text('# source fixture\n') + (self.source / 'LICENSE').write_text('fixture license\n') + + def command(self, destination: Path) -> list[str]: + return [sys.executable, str(ROOT / 'environment/baseline/starter/glacier/publish.py'), + '--checkpoint', str(self.checkpoint), '--fallback', str(self.fallback), + '--source-root', str(self.source), '--output-dir', str(destination)] + + def assert_native_invocation(self, generation: Path, batch_size: int) -> None: + """Exercise the published adapter with bounded stand-ins for model execution.""" + native_infer = load('published_native_infer', generation / 'infer.py') + input_root, output_root = self.root / 'public-input', self.root / 'rankings' + + def run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess: + script = Path(command[1]).name + if script == 'stage_input.py': + partition = Path(command[command.index('--output-root') + 1]) + for branch in ('glacier', 'fallback'): + (partition / branch).mkdir(parents=True) + (partition / branch / 'queries.jsonl').write_text('{}\n') + elif script == 'prepare_glacier_candidates.py': + Path(command[command.index('--output') + 1]).write_text('smiles\nCCO\n') + elif script == 'merge_glacier_fallback.py': + (output_root / 'runtime.json').write_text('{}\n') + return subprocess.CompletedProcess(command, 0) + + with mock.patch.object(sys, 'argv', ['infer.py', str(input_root), str(output_root)]), \ + mock.patch.object(native_infer.subprocess, 'run', side_effect=run) as execute: + native_infer.main() + commands = [call.args[0] for call in execute.call_args_list] + predictor = next(command for command in commands if Path(command[1]).name == 'predict_smis_joint.py') + for option, value in {'--batch-size': batch_size, '--num-cpu-workers': 2, + '--feat-cache-size': 64, '--prefetch-factor': 1}.items(): + self.assertEqual(predictor[predictor.index(option) + 1], str(value)) + self.assertEqual(predictor[predictor.index('--checkpoint') + 1], str(generation / 'glacier.ckpt')) + scorer = next(command for command in commands if Path(command[1]).name == 'score_glacier_predictions.py') + self.assertEqual(scorer[scorer.index('--distance') + 1], 'entropy') + self.assertTrue(any(command[:2] == ['bash', str(generation / 'fallback/infer.sh')] for command in commands)) + self.assertFalse((output_root / 'runtime.json').exists()) + + def test_default_and_cli_override_preserve_model_and_training(self) -> None: + import torch + configs = [] + for name, override, batch_size in [('api-default', None, 64), + ('cli-default', None, 64), ('cli-small', 8, 8)]: + with self.subTest(name=name): + destination = self.root / name + if name == 'api-default': + self.native.publish(self.checkpoint, self.fallback, self.source, destination) + else: + command = self.command(destination) + if override is not None: + command.extend(['--inference-batch-size', str(override)]) + subprocess.run(command, check=True, capture_output=True, text=True) + # Publication must remain portable, including its selected generation. + relocated = self.root / (name + '-relocated') + shutil.move(destination, relocated) + manifest = main_verifier.validate_submission(relocated) + config = json.loads((relocated / manifest['model_config']).read_text()) + configs.append(config) + self.assertEqual(config['batch_size'], batch_size) + self.assertEqual(config['training'], self.state['task_training']) + self.assertEqual(config['method'], 'native-glacier-with-trained-deepsets-fallback') + self.assertEqual(config['routing'], 'released_conditions_with_usable_observation_and_supported_pool') + self.assertEqual(manifest['training_provenance'], { + 'data': 'MassSpecGym v1.5 train; validation for selection only', 'pretrained_assets': []}) + saved = torch.load(relocated / manifest['checkpoint']['path'], weights_only=False) + self.assertTrue(torch.equal(saved.pop('state_dict')['fixture.weight'], + self.state['state_dict']['fixture.weight'])) + self.assertEqual(saved, {key: value for key, value in self.state.items() if key != 'state_dict'}) + generation = (relocated / manifest['model_config']).parent + for name in ['stage_input.py', 'config.json', 'train.py']: + source = ROOT / 'environment/baseline/starter/glacier' / name + target = generation / ('stage_input.py' if name == 'stage_input.py' else 'training/' + name) + self.assertEqual(target.read_bytes(), source.read_bytes()) + self.assertEqual((generation / 'fallback/weights.pt').read_bytes(), + (self.fallback / 'weights.pt').read_bytes()) + self.assert_native_invocation(generation, batch_size) + self.assertEqual(configs[0], configs[1]) + self.assertEqual(configs[0], {**configs[2], 'batch_size': 64}) + + def test_invalid_api_batch_preserves_existing_publication(self) -> None: + destination = self.root / 'published' + self.native.publish(self.checkpoint, self.fallback, self.source, destination) + before = (destination / 'model_manifest.json').read_bytes() + for value in (0, -1, 1.5, '8', True): + with self.subTest(value=value), self.assertRaisesRegex(ValueError, 'positive integer'): + self.native.publish(self.checkpoint, self.fallback, self.source, destination, + inference_batch_size=value) + self.assertEqual((destination / 'model_manifest.json').read_bytes(), before) + + def test_invalid_cli_batch_fails_before_publication(self) -> None: + destination = self.root / 'invalid' + for value in ('0', '-1', '1.5', 'invalid'): + with self.subTest(value=value): + result = subprocess.run(self.command(destination) + ['--inference-batch-size', value], + capture_output=True, text=True) + self.assertEqual(result.returncode, 2) + self.assertIn('inference batch size must be a positive integer', result.stderr) + self.assertFalse(destination.exists()) + + +class ResearchToolsTests(unittest.TestCase): + def test_native_routes_unsupported_valid_inputs_to_the_trained_fallback(self): + native = load('native_stage', ROOT / 'environment/baseline/starter/glacier/stage_input.py') + self.assertTrue(native.supports_pool([{'smiles': 'CCO'}], {1, 6, 7, 8})) + self.assertFalse(native.supports_pool([{'smiles': 'C' * 101}], {1, 6, 7, 8})) + self.assertFalse(native.supports_observation(dict(mzs=[1500.0], intensities=[1.0], precursor_mz=200.0))) + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + source = root / 'input'; source.mkdir() + ordinary = dict(query_id='ordinary', candidate_pool_id='p', mzs=[50.0], + intensities=[1.0], precursor_mz=100.0) + queries = [ordinary, dict(ordinary, query_id='outside', mzs=[1500.0]), + dict(ordinary, query_id='large-pool', candidate_pool_id='large')] + pools = [{'candidate_pool_id': 'p', 'candidates': [{'candidate_id': 'c', 'smiles': 'CCO'}]}, + {'candidate_pool_id': 'large', 'candidates': [{'candidate_id': 'large-c', 'smiles': 'C' * 101}]}] + for filename, rows in [('queries.jsonl', queries), ('candidate_pools.jsonl', pools)]: + (source / filename).write_text(''.join(json.dumps(row) + '\n' for row in rows)) + native.partition(source, root / 'output', {1, 6, 7, 8}, lambda query: True) + self.assertEqual((root / 'output/glacier-query-ids.txt').read_text(), 'ordinary\n') + fallback = [json.loads(line) for line in (root / 'output/fallback/queries.jsonl').read_text().splitlines()] + self.assertEqual({row['query_id'] for row in fallback}, {'outside', 'large-pool'}) + self.assertEqual(len(fallback) + 1, len(queries)) + + def test_resuming_fit_state_does_not_refund_completed_validation(self): + native = load('native_train', ROOT / 'environment/baseline/starter/glacier/train.py') + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + # A fit checkpoint precedes expensive final validation/export. + self.assertEqual(native.charged_elapsed(root, 190), 190) + (root / 'result.json').write_text(json.dumps({'elapsed_seconds': 567})) + self.assertEqual(native.charged_elapsed(root, 190), 567) + # A later interrupted segment must retain its greater usage too. + self.assertEqual(native.charged_elapsed(root, 800), 800) + (root / 'budget-ledger.json').write_text(json.dumps({'elapsed_seconds': 900})) + self.assertEqual(native.charged_elapsed(root, 800), 900) + + def test_unparseable_candidate_has_a_finite_fallback_but_training_stays_strict(self): + import torch + starter = load('starter_common', ROOT / 'environment/baseline/starter/common.py') + # Invalid in every RDKit version exercises the same boundary as legacy + # valences accepted by the task's RDKit 2023 but rejected by 2025. + with self.assertRaisesRegex(ValueError, 'invalid candidate SMILES'): + starter.morgan_fingerprint('not_a_smiles') + fp = starter.morgan_fingerprint('not_a_smiles', allow_unparseable=True) + self.assertTrue(torch.isfinite(fp).all()) + self.assertEqual(tuple(fp.shape), (4096,)) + self.assertEqual(int(torch.count_nonzero(fp)), 0) + self.assertTrue(torch.equal(starter.morgan_fingerprint('CCO'), + starter.morgan_fingerprint('CCO', allow_unparseable=True))) + + def test_starter_accepts_valid_spectra_outside_its_preprocessing_window(self): + import torch + starter = load('starter_common', ROOT / 'environment/baseline/starter/common.py') + for mzs, intensities in [([1500.0], [1.0]), ([50.0, 1500.0], [0.0, 1.0])]: + with self.subTest(mzs=mzs): + encoded = starter.spectrum_tensor(dict( + mzs=mzs, intensities=intensities, precursor_mz=1600.0)) + self.assertTrue(torch.isfinite(encoded).all()) + self.assertEqual(tuple(encoded.shape), (61, 2)) + self.assertEqual(float(encoded[0, 0]), 1600.0) + self.assertEqual(int(torch.count_nonzero(encoded[1:])), 0) + with self.assertRaisesRegex(ValueError, 'maximum intensity must be positive'): + starter.spectrum_tensor(dict(mzs=[1500.0], intensities=[0.0], precursor_mz=1600.0)) + + def test_declared_external_weights_are_not_authorized_by_manifest(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + build(root, 'fixture') + manifest = main_verifier.validate_submission(root) + manifest['training_provenance']['pretrained_assets'] = [ + {'name': 'external', 'revision': 'immutable', 'license': 'MIT'}] + (root / 'model_manifest.json').write_text(json.dumps(manifest)) + with self.assertRaisesRegex(ValueError, 'no authorized pretrained'): + main_verifier.validate_submission(root) + + def test_failed_publication_preserves_previous_runnable_model(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) / 'submission' + publication.publish_directory(root, lambda stage: build(stage, 'first')) + for path in [root, *root.rglob('*')]: + if path.is_dir(): + self.assertEqual(path.stat().st_mode & 0o005, 0o005) + else: + self.assertEqual(path.stat().st_mode & 0o004, 0o004) + before = (root / 'model_manifest.json').read_bytes() + def interrupted(stage): + build(stage, 'unfinished') + raise RuntimeError('simulated preemption while exporting') + with self.assertRaises(RuntimeError): + publication.publish_directory(root, interrupted) + self.assertEqual(before, (root / 'model_manifest.json').read_bytes()) + publication.publish_directory(root, lambda stage: build(stage, 'second')) + relocated = Path(temporary) / 'elsewhere' + shutil.copytree(root, relocated) + shutil.rmtree(root) + self.assertEqual(subprocess.check_output(['bash', str(relocated / 'infer.sh')], text=True).strip(), 'second') + # A reader which captured the old manifest still has all its assets. + old = json.loads(before) + self.assertEqual((relocated / old['checkpoint']['path']).read_text(), 'first') + compact = Path(temporary) / 'compact' + publication.snapshot_package(relocated, compact) + self.assertFalse((compact / old['checkpoint']['path']).exists()) + self.assertEqual(subprocess.check_output(['bash', str(compact / 'infer.sh')], text=True).strip(), 'second') + + def test_escaping_publication_is_rejected_without_replacing_manifest(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) / 'submission' + publication.publish_directory(root, lambda stage: build(stage, 'first')) + before = (root / 'model_manifest.json').read_bytes() + def escaping(stage): + build(stage, 'bad') + (stage / 'external').symlink_to('/etc/passwd') + with self.assertRaises(ValueError): + publication.publish_directory(root, escaping) + self.assertEqual(before, (root / 'model_manifest.json').read_bytes()) + + def test_cluster_bootstrap_keeps_spectrum_weighting(self): + # One molecule has nine spectra, the other one: macro would be 0.5. + report = diagnostics.cluster_interval([1] * 9 + [0], ['A'] * 9 + ['B'], resamples=500, seed=7) + self.assertEqual(report['estimate'], 0.9) + self.assertEqual(report['molecule_groups'], 2) + self.assertEqual(report['lower'], 0) + self.assertEqual(report['upper'], 1) + self.assertEqual(report, diagnostics.cluster_interval([1] * 9 + [0], ['A'] * 9 + ['B'], resamples=500, seed=7)) + + def test_no_difference_has_zero_paired_interval(self): + report = diagnostics.cluster_interval([0, 0, 0], ['A', 'A', 'B'], resamples=100) + self.assertEqual((report['estimate'], report['lower'], report['upper']), (0, 0, 0)) + + def test_paired_report_resamples_molecules_without_changing_delta(self): + truth = {f'q{i}': 'a' for i in range(10)} + baseline = {q: 'b' for q in truth} + challenger = {q: 'a' if q != 'q9' else 'b' for q in truth} + groups = {q: 'A' if q != 'q9' else 'B' for q in truth} + report = paired.compare(truth, baseline, challenger, confidence=0.95, resamples=500, seed=7, groups=groups) + self.assertEqual(report['delta'], 0.9) + self.assertEqual(report['molecule_groups'], 2) + self.assertEqual(report['interval'], [0, 1]) + self.assertFalse(report['beats_reference']) + + def test_validation_rejects_nested_or_partial_rankings(self): + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / 'rankings.jsonl' + for ranking in [[['a'], 'b'], ['a'], ['a', 'a']]: + path.write_text(json.dumps({'query_id': 'q', 'ranking': ranking}) + '\n') + with self.assertRaises(ValueError): + score.load_rankings(path, {'q': {'pool': 'p'}}, {'p': [{'candidate_id': 'a'}, {'candidate_id': 'b'}]}) + + def test_routing_does_not_treat_missing_energy_as_zero(self): + row = {'adduct': '[M+H]+', 'instrument_type': 'Orbitrap', 'collision_energy': None} + self.assertFalse(diagnostics.released_domain(row)) + self.assertTrue(diagnostics.released_domain(dict(row, collision_energy=0.0))) + self.assertFalse(diagnostics.released_domain(dict(row, collision_energy=float('nan')))) + + +if __name__ == '__main__': + unittest.main() diff --git a/reproduction/files/1f/1f6f9a2579d1877217e9aba9c6c9eabcd30cac45975eee58c07e7a7bf00dd1ea/novelty.py b/reproduction/files/1f/1f6f9a2579d1877217e9aba9c6c9eabcd30cac45975eee58c07e7a7bf00dd1ea/novelty.py new file mode 100644 index 0000000000000000000000000000000000000000..afd11eec6b538ea06959c9e65321aff9f734bc46 --- /dev/null +++ b/reproduction/files/1f/1f6f9a2579d1877217e9aba9c6c9eabcd30cac45975eee58c07e7a7bf00dd1ea/novelty.py @@ -0,0 +1,61 @@ +"""Novelty against the fit corpus: the largest TM-score of a design to any fit chain. + +Protein-design benchmarks report novelty as the maximum TM-score of each designable design to the PDB or the +training set, computed with Foldseek in TM-align mode (lower is more novel); generative models typically sit +around 0.45-0.8 depending on the task. A design therefore passes only if, besides the published designability +criterion, its maximum TM-score to the fit corpus is below `common.NOVELTY_MAX_TM`. + +The reference is the fit corpus the agent trains on (`development/fit/structures`), mounted read-only into +the grader; its Foldseek database is built once per grading run (a few minutes on 16k structures). +""" +import os +import shutil +import subprocess +import tempfile +from pathlib import Path + +FOLDSEEK = os.environ.get("FOLDSEEK", "/opt/foldseek/bin/foldseek") + + +class FitNovelty: + def __init__(self, reference_dir, workdir=None, threads=None, foldseek=FOLDSEEK): + self.reference_dir = Path(reference_dir) + if not any(self.reference_dir.rglob("*.cif*")): + raise FileNotFoundError(f"novelty reference has no structures: {self.reference_dir}") + self.foldseek = foldseek + self.threads = str(threads or os.cpu_count() or 1) + self.work = Path(workdir or tempfile.mkdtemp(prefix="novelty-")) + self.db = self.work / "fitdb" + self._run("createdb", str(self.reference_dir), str(self.db), "--threads", self.threads) + + def _run(self, *arguments): + subprocess.run([self.foldseek, *arguments], check=True, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE) + + def max_tm(self, designs): + """designs: {key: PDB path} -> {key: max TM-score (normalized by the design) to any fit chain}.""" + if not designs: + return {} + query = Path(tempfile.mkdtemp(dir=self.work, prefix="query-")) + try: + names = {} + for index, (key, path) in enumerate(designs.items()): + name = f"q{index}" + shutil.copyfile(path, query / f"{name}.pdb") + names[name] = key + self._run("createdb", str(query), str(query / "db"), "--threads", self.threads) + # TM-align alignment of every prefilter hit; -a keeps the alignment so qtmscore can be reported. + self._run("search", str(query / "db"), str(self.db), str(query / "aln"), str(query / "tmp"), + "--alignment-type", "1", "-a", "-e", "inf", "--max-seqs", "1000", "-s", "9.5", + "--threads", self.threads) + self._run("convertalis", str(query / "db"), str(self.db), str(query / "aln"), + str(query / "hits.tsv"), "--format-output", "query,target,qtmscore") + best = {key: 0.0 for key in designs} + for line in (query / "hits.tsv").read_text().splitlines(): + name, _, score = line.split("\t") + key = names.get(name.split("_")[0]) + if key is not None: + best[key] = max(best[key], float(score)) + return best + finally: + shutil.rmtree(query, ignore_errors=True) diff --git a/reproduction/files/1f/1fb4ffce095d7d563544d2826539a9113032c80c3907c9e746c93e0dcbe677ff/make_zero_predictions.py b/reproduction/files/1f/1fb4ffce095d7d563544d2826539a9113032c80c3907c9e746c93e0dcbe677ff/make_zero_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..4c951f9f6faacbdfe861d999a73c61a0ba4aacea --- /dev/null +++ b/reproduction/files/1f/1fb4ffce095d7d563544d2826539a9113032c80c3907c9e746c93e0dcbe677ff/make_zero_predictions.py @@ -0,0 +1,12 @@ +"""Create the deterministic all-zero sanity baseline.""" +import argparse,json +from pathlib import Path +import pyarrow as pa +import pyarrow.parquet as pq + +ap=argparse.ArgumentParser();ap.add_argument("--input",type=Path,required=True);ap.add_argument("--output",type=Path,required=True);a=ap.parse_args() +m=json.loads((a.input/"manifest.json").read_text());d=len(m["scored_diseases"]);h=len(m["horizons_days"]) +ids=pq.read_table(a.input/"samples.parquet",columns=["sample_id"])["sample_id"].to_pylist() +schema=pa.schema([pa.field("sample_id",pa.string()),pa.field("disease_risk",pa.list_(pa.float32(),d*h)),pa.field("death_risk",pa.list_(pa.float32(),h))]) +row_d=[0.0]*(d*h);row_h=[0.0]*h;a.output.parent.mkdir(parents=True,exist_ok=True) +pq.write_table(pa.Table.from_pylist([{"sample_id":x,"disease_risk":row_d,"death_risk":row_h} for x in ids],schema=schema),a.output,compression="zstd") diff --git a/reproduction/files/1f/1fff1846a4ec5dcc7e2beb2eda5dbb97f35494d686a33e4a62974d482a8e583b/evaluate_native.sh b/reproduction/files/1f/1fff1846a4ec5dcc7e2beb2eda5dbb97f35494d686a33e4a62974d482a8e583b/evaluate_native.sh new file mode 100644 index 0000000000000000000000000000000000000000..304ce847c4409928424b12e5ba284549910a590e --- /dev/null +++ b/reproduction/files/1f/1fff1846a4ec5dcc7e2beb2eda5dbb97f35494d686a33e4a62974d482a8e583b/evaluate_native.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +# Bootstrap the image's Python libraries without loading CUDA solver modules. +# The Python dispatcher selects the solver runtime separately for each case. +exec bash "$root/native_runtime.sh" jax python "$root/evaluate_native.py" "$@" diff --git a/reproduction/files/22/224957d662239021e18f16650cebeefedd5515b8b94454d64fc3064e98bb1a43/test_contract.py b/reproduction/files/22/224957d662239021e18f16650cebeefedd5515b8b94454d64fc3064e98bb1a43/test_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..cc9b4dbffc809b1c9e83ca8446afeb4f35873bbe --- /dev/null +++ b/reproduction/files/22/224957d662239021e18f16650cebeefedd5515b8b94454d64fc3064e98bb1a43/test_contract.py @@ -0,0 +1,86 @@ +"""Checks ID alignment, rejection of malformed output, and test isolation.""" + +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +import numpy as np + +SCRIPT = Path(__file__).resolve().parents[1] / "environment/evaluation/probes.py" + + +class ProbeContract(unittest.TestCase): + def test_alignment_failures_and_test_isolation(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + rng = np.random.default_rng(24) + x = rng.normal(size=(110, 12)) + y = x[:, 0] * 4 + x[:, 1] * 2 + rows = [ + { + "id": f"new-id-{i}", + "label": float(y[i]), + "split": "train" if i < 70 else "val" if i < 90 else "test", + } + for i in range(110) + ] + labels = root / "labels.json" + labels.write_text(json.dumps(rows)) + ids = np.array([r["id"] for r in rows]) + features = root / "features.npz" + cmd = [ + sys.executable, + str(SCRIPT), + "--features", + str(features), + "--labels", + str(labels), + "--task", + "lfmc", + "--output", + str(root / "score.json"), + "--final-test", + ] + + def run(): + return subprocess.run(cmd, capture_output=True, text=True) + + np.savez(features, ids=ids, features=x) + self.assertEqual(run().returncode, 0) + original = json.loads((root / "score.json").read_text()) + perm = rng.permutation(len(ids)) + np.savez(features, ids=ids[perm], features=x[perm]) + self.assertEqual(run().returncode, 0) + self.assertEqual(original, json.loads((root / "score.json").read_text())) + for row in rows[90:]: + row["label"] += 100 + labels.write_text(json.dumps(rows)) + self.assertEqual(run().returncode, 0) + altered = json.loads((root / "score.json").read_text()) + self.assertEqual( + original["probe"]["selected_parameter"], + altered["probe"]["selected_parameter"], + ) + self.assertEqual( + original["probe"]["validation"], altered["probe"]["validation"] + ) + self.assertNotEqual(original["probe"]["test"], altered["probe"]["test"]) + np.savez(features, ids=ids[:-1], features=x[:-1]) + self.assertNotEqual(run().returncode, 0) + np.savez(features, ids=np.repeat(ids[:1], len(ids)), features=x) + self.assertNotEqual(run().returncode, 0) + np.savez( + features, + ids=np.concatenate([ids, ids[:1]]), + features=np.concatenate([x, x[:1]]), + ) + self.assertNotEqual(run().returncode, 0) + x[0, 0] = float("nan") + np.savez(features, ids=ids, features=x) + self.assertNotEqual(run().returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/24/24cdd224ba6133de77df91462bb66d12b3432ee2b21cd85e24379c7813b44561/check_training_recovery.py b/reproduction/files/24/24cdd224ba6133de77df91462bb66d12b3432ee2b21cd85e24379c7813b44561/check_training_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7dfdd41c3e33aa4f810792b7cbeab0b4ce7060 --- /dev/null +++ b/reproduction/files/24/24cdd224ba6133de77df91462bb66d12b3432ee2b21cd85e24379c7813b44561/check_training_recovery.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Real native-model recovery integration check; run in the GLACIER runtime.""" + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys + +import torch + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ['data-root', 'fallback', 'output']: + parser.add_argument('--' + name, type=Path, required=True) + parser.add_argument('--source-root', type=Path, default=Path('/opt/ms-pred')) + parser.add_argument('--workers', type=int, default=0) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + script = Path(__file__).resolve().parents[1] / 'environment/baseline/starter/glacier/train.py' + for name, steps, resume in [('resumed', 2, False), ('resumed', 4, True), ('continuous', 4, False)]: + command = [sys.executable, str(script), '--data-root', str(args.data_root), + '--source-root', str(args.source_root), '--work-dir', str(args.output / name), + '--fallback', str(args.fallback), '--submission-dir', str(args.output / (name + '-submission')), + '--max-steps', str(steps), '--device', 'cpu', '--workers', str(args.workers), '--batch-size', '1', + '--accumulate-grad-batches', '1', '--validate-every', '1', '--checkpoint-every', '500', + '--max-seconds', '600', '--trace-batches'] + if resume: + command += ['--resume', str(args.output / name / 'last.ckpt')] + with (args.output / f'{name}-{steps}.log').open('w') as log: + subprocess.run(command, check=True, env=dict(os.environ, OMP_NUM_THREADS='2'), stdout=log, stderr=subprocess.STDOUT) + resumed = torch.load(args.output / 'resumed/last.ckpt', map_location='cpu', weights_only=False) + continuous = torch.load(args.output / 'continuous/last.ckpt', map_location='cpu', weights_only=False) + different = [key for key, value in resumed['state_dict'].items() if not torch.equal(value, continuous['state_dict'][key])] + same_batches = ((args.output / 'resumed/batch-trace.jsonl').read_bytes() == + (args.output / 'continuous/batch-trace.jsonl').read_bytes()) + report = {'global_steps': [resumed['global_step'], continuous['global_step']], + 'magma_steps': [resumed['task_magma_step'], continuous['task_magma_step']], + 'differing_parameter_tensors': different, 'identical_batch_order_and_rng': same_batches, + 'scope': f'CPU, loader workers={args.workers}, same pinned runtime; not cross-hardware determinism'} + (args.output / 'report.json').write_text(json.dumps(report, indent=2) + '\n') + if different or not same_batches or report['global_steps'] != [4, 4] or report['magma_steps'] != [4, 4]: + raise AssertionError(report) + print(json.dumps(report, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/reproduction/files/25/25821b034a3b87b31eb7bd03c266decee1a2de037c3680796119f04c0740c63d/test_heldout_confirmation.py b/reproduction/files/25/25821b034a3b87b31eb7bd03c266decee1a2de037c3680796119f04c0740c63d/test_heldout_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..c66627246c42a18025d34023e6a7e85b962cf680 --- /dev/null +++ b/reproduction/files/25/25821b034a3b87b31eb7bd03c266decee1a2de037c3680796119f04c0740c63d/test_heldout_confirmation.py @@ -0,0 +1,220 @@ +"""A failed cohort cannot unlock test reporting; test labels cannot choose alpha.""" + +import hashlib +import json +import os +import runpy +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +import numpy as np +from sklearn.linear_model import Ridge +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler + + +class HeldoutConfirmationTest(unittest.TestCase): + def test_legacy_random_provenance(self): + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/analysis")) + check = runpy.run_path( + str(Path(__file__).resolve().parents[1] / "docs/analysis/heldout_confirmation.py") + )["is_random_initialization"] + self.assertTrue(check({"checkpoint": None})) + self.assertTrue(check({"origin": "random_initialization"})) + self.assertFalse(check({})) + self.assertFalse(check({"checkpoint": "weights.pt"})) + self.assertFalse( + check( + {"origin": "official_public_pretrained_reference", "checkpoint": None} + ) + ) + + def test_lock_gate_and_fixed_probe_parameters(self): + script = Path(__file__).resolve().parents[1] / "docs/analysis/heldout_confirmation.py" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "results").mkdir() + context = {"gpu_type": "a5000", "python_hash_seed": 0} + (root / "execution-context.json").write_text(json.dumps(context)) + seeds, loader_seeds = [12536, 12539, 12540], [3622, 3625, 3626] + pairs = [ + [f"large-random-eval-{seed}", f"train-{seed}-step6000"] + for seed in seeds + ] + recipe = {"global_batch": 64, "checkpoint_step": "step6000"} + lock = { + "selected": pairs[0][1], + "checkpoint_step": 6000, + "training_recipe": recipe, + "policy": {"development_seed": seeds[0], "execution_context": context}, + "confirmation": [ + { + "name": f"train-{seed}", + "initialization_seed": seed, + "data_seed": loader, + "paired_random": pair[0], + } + for seed, loader, pair in zip( + seeds[1:], loader_seeds[1:], pairs[1:] + ) + ], + } + comparison = { + "split": "val", + "pairs": pairs, + "initialization_seeds": seeds, + "data_seeds": loader_seeds, + "execution_context": context, + "tasks": {"lfmc": {"three_seed_criterion_met": False}}, + } + lock_path, comparison_path = root / "lock.json", root / "comparison.json" + lock_path.write_text(json.dumps(lock)) + comparison_path.write_text(json.dumps(comparison)) + cmd = [ + sys.executable, + str(script), + "--data-root", + str(root), + "--lock", + str(lock_path), + "--validation-comparison", + str(comparison_path), + "--output", + str(root / "test.json"), + ] + env = dict( + os.environ, + CUDA_VISIBLE_DEVICES="", + OMP_NUM_THREADS="1", + OPENBLAS_NUM_THREADS="1", + ) + failed = subprocess.run(cmd, env=env, capture_output=True, text=True) + self.assertNotEqual(failed.returncode, 0) + self.assertIn("Validation confirmation has not passed", failed.stderr) + self.assertFalse((root / "eval").exists()) + rng = np.random.default_rng(12) + y = rng.normal(size=100) * 3 + ids = np.array([f"id-{i}" for i in range(len(y))]) + rows = [ + { + "id": str(id_), + "label": float(y[i]), + "split": "train" if i < 60 else "val" if i < 80 else "test", + "latlon": [float(i), 0.0], + } + for i, id_ in enumerate(ids) + ] + labels = root / "eval/lfmc/labels.json" + labels.parent.mkdir(parents=True) + labels.write_text(json.dumps(rows)) + names = [n for pair in pairs for n in pair] + ["large-raw"] + for name in names: + x = rng.normal(size=(len(y), 8)) + if name.startswith("train-") or name == "large-raw": + x[:, 0] = y + feature = root / "features" / f"{name}-lfmc" / "features.npz" + feature.parent.mkdir(parents=True) + np.savez(feature, ids=ids, features=x.astype(np.float32)) + x = x.astype(np.float32).astype(np.float64) + model = make_pipeline(StandardScaler(), Ridge(alpha=1.0)).fit( + x[:60], y[:60] + ) + report = { + "features": str(feature), + "probe": { + "selected_parameter": 1.0, + "validation": { + "mae": float( + np.abs(model.predict(x[60:80]) - y[60:80]).mean() + ) + }, + }, + } + (root / "results" / f"{name}-lfmc.json").write_text(json.dumps(report)) + for seed, loader, pair in zip(seeds, loader_seeds, pairs): + for index, name in enumerate(pair): + package = root / "packages" / name + package.mkdir(parents=True) + (package / "encoder.pt").write_bytes(name.encode()) + sha = hashlib.sha256(name.encode()).hexdigest() + provenance = { + "origin": "random_initialization" + if index == 0 + else "own_from_scratch_training", + "initialization_seed": seed, + "data_seed": loader if index else None, + "training_recipe": recipe if index else None, + "variant": "v1/large", + "parameters": 307770368, + "infer_sha256": "fixture", + "encoder_sha256": sha, + } + if index == 0 and seed == seeds[0]: + del provenance["origin"] + provenance["checkpoint"] = None + (package / "provenance.json").write_text(json.dumps(provenance)) + if name == lock["selected"]: + lock["encoder_sha256"] = sha + lock_path.write_text(json.dumps(lock)) + comparison["tasks"]["lfmc"]["three_seed_criterion_met"] = True + comparison["tasks"]["lfmc"].update( + per_seed_gain=[1.0, 1.0, 1.0], + mean_seed_gain=1.0, + spatial_bootstrap_95_percent_interval=[0.1, 2.0], + seed_and_spatial_bootstrap_95_percent_interval=[0.1, 2.0], + ) + comparison["tasks"]["lfmc"][ + "seed_and_spatial_bootstrap_95_percent_interval" + ][0] = -0.1 + comparison_path.write_text(json.dumps(comparison)) + failed = subprocess.run(cmd, env=env, capture_output=True, text=True) + self.assertNotEqual(failed.returncode, 0) + self.assertIn("flag disagrees", failed.stderr) + self.assertFalse((root / "test.json").exists()) + comparison["tasks"]["lfmc"][ + "seed_and_spatial_bootstrap_95_percent_interval" + ][0] = 0.1 + comparison_path.write_text(json.dumps(comparison)) + run = subprocess.run(cmd, env=env, capture_output=True, text=True) + self.assertEqual(run.returncode, 0, run.stderr) + first = json.loads((root / "test.json").read_text()) + self.assertEqual(first["paired_random_comparison"]["rows"], 20) + self.assertEqual(first["paired_random_comparison"]["groups"], 20) + repeated = subprocess.run(cmd, env=env, capture_output=True, text=True) + self.assertNotEqual(repeated.returncode, 0) + for row in rows[80:]: + row["label"] += 100 + labels.write_text(json.dumps(rows)) + cmd[-1] = str(root / "changed-test-labels.json") + run = subprocess.run(cmd, env=env, capture_output=True, text=True) + self.assertEqual(run.returncode, 0, run.stderr) + altered = json.loads((root / "changed-test-labels.json").read_text()) + for name in names: + self.assertEqual( + first["models"][name]["selected_alpha_from_validation"], + altered["models"][name]["selected_alpha_from_validation"], + ) + self.assertEqual( + first["models"][name]["validation_mae_check"], + altered["models"][name]["validation_mae_check"], + ) + self.assertNotEqual( + first["models"][name]["test_mae"], + altered["models"][name]["test_mae"], + ) + changed = root / "packages" / pairs[1][1] / "provenance.json" + provenance = json.loads(changed.read_text()) + provenance["training_recipe"] = {"different": True} + changed.write_text(json.dumps(provenance)) + cmd[-1] = str(root / "bad-recipe.json") + run = subprocess.run(cmd, env=env, capture_output=True, text=True) + self.assertNotEqual(run.returncode, 0) + self.assertIn("Training recipe differs", run.stderr) + self.assertFalse((root / "bad-recipe.json").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/25/25c05f464584eaa649da0a0ccfb54faabe9a641664d017e924415f86681e50aa/container_smoke.py b/reproduction/files/25/25c05f464584eaa649da0a0ccfb54faabe9a641664d017e924415f86681e50aa/container_smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..a5634ecac2caf38562dbe31f9640bba339f90952 --- /dev/null +++ b/reproduction/files/25/25c05f464584eaa649da0a0ccfb54faabe9a641664d017e924415f86681e50aa/container_smoke.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Native Docker deployment checks on synthetic data, not accuracy evidence.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import time +from typing import Any +import uuid + +TASK = Path(__file__).resolve().parents[1] +INFER = r'''import json, os, socket, sys +from pathlib import Path +import torch + +source, output = map(Path, sys.argv[1:]) +assert os.getuid() == 10001 +assert {name for _, name in socket.if_nameindex()} == {"lo"} +assert not Path("/private").exists() +try: + list(Path("/sealed").iterdir()) +except PermissionError: + pass +else: + raise AssertionError("inference can access the sealed volume") +for name in ("/tests/grader.py", "/tests/score_bounds.json", "/benchmark/manifest.json", + "/workspace/submission/model_manifest.json", "/logs/verifier/reward.json"): + try: + with open(name, "ab"): + pass + except (PermissionError, OSError): + pass + else: + raise AssertionError("protected path is writable: " + name) +queries = [json.loads(line) for line in (source / "queries.jsonl").read_text().splitlines()] +assert all("true_smiles" not in row and "correct_candidate_id" not in row for row in queries) +pools = {row["candidate_pool_id"]: row["candidates"] for row in + map(json.loads, (source / "candidate_pools.jsonl").read_text().splitlines())} +state = torch.load(Path(__file__).with_name("model.pt"), map_location="cpu", weights_only=True) +config = json.loads(Path(__file__).with_name("config.json").read_text()) +with (output / "rankings.jsonl").open("w") as stream: + for row in reversed(queries): + ranking = [pools[row["candidate_pool_id"]][i]["candidate_id"] for i in state["order"].tolist()] + if config["malformed_output"]: + ranking = ranking[:1] + stream.write(json.dumps({"query_id": row["query_id"], "ranking": ranking}) + "\n") +print(json.dumps({"container_security_probe": "passed", "uid": os.getuid(), + "queries": len(queries), "network_interfaces": ["lo"], + "private_labels_absent": True, "sealed_volume_inaccessible": True, + "protected_paths_not_writable": True}), flush=True) +''' + + +def write_json(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n") + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def prepare(root: Path) -> None: + """Generate four queries and a real, tiny PyTorch checkpoint inside the image.""" + import torch + + inputs, labels, submission = root / "data/verifier", root / "labels", root / "submission-valid" + for directory in (inputs, labels, submission, root / "missing-labels"): + directory.mkdir(parents=True) + candidates = [{"candidate_id": hashlib.sha256(s.encode()).hexdigest(), "smiles": s} for s in ("C", "CC")] + queries = [{"query_id": f"synthetic-{i}", "mzs": [10.0], "intensities": [1.0], + "precursor_mz": 20.0, "adduct": "[M+H]+", "instrument_type": "synthetic", + "collision_energy": None, "candidate_pool_id": "synthetic-pool"} for i in range(4)] + (inputs / "queries.jsonl").write_text("".join(json.dumps(row) + "\n" for row in queries)) + (inputs / "candidate_pools.jsonl").write_text(json.dumps({"candidate_pool_id": "synthetic-pool", "candidates": candidates}) + "\n") + write_json(inputs / "manifest.json", {"schema": "massspecgym-retrieval-input/v1", "synthetic_smoke_only": True, + "counts": {"queries": 4, "candidate_pools": 1}, + "files": {name: digest(inputs / name) for name in ("queries.jsonl", "candidate_pools.jsonl")}}) + truths = [{"query_id": row["query_id"], "correct_candidate_id": candidates[int(i > 0)]["candidate_id"], + "true_smiles": candidates[int(i > 0)]["smiles"]} for i, row in enumerate(queries)] + (labels / "labels.jsonl").write_text("".join(json.dumps(row) + "\n" for row in truths)) + write_json(labels / "manifest.json", {"schema": "massspecgym-retrieval-private-labels/v1", + "synthetic_smoke_only": True, "files": {"labels.jsonl": digest(labels / "labels.jsonl")}}) + torch.save({"order": torch.tensor([0, 1])}, submission / "model.pt") + write_json(submission / "config.json", {"malformed_output": False}) + (submission / "infer.py").write_text(INFER) + (submission / "infer.sh").write_text('#!/usr/bin/env bash\nset -euo pipefail\nROOT="$(cd -- "$(dirname -- "$0")" && pwd)"\nexec python "$ROOT/infer.py" "$1" "$2"\n') + (submission / "README.md").write_text("Synthetic deployment fixture only; no scientific model or accuracy claim.\n") + write_json(submission / "model_manifest.json", {"schema": "massspecgym-retrieval-model/v1", + "checkpoint": {"path": "model.pt", "sha256": digest(submission / "model.pt"), "format": "pytorch"}, + "model_config": "config.json", "training_provenance": { + "data": "Synthetic constant ordering fixture, not a trained scientific baseline", "pretrained_assets": []}}) + for case in ("invalid-output", "invalid-submission"): + shutil.copytree(submission, root / f"submission-{case}") + write_json(root / "submission-invalid-output/config.json", {"malformed_output": True}) + write_json(root / "submission-invalid-submission/model_manifest.json", {}) + + +def command(args: list[str], *, env: dict[str, str] | None = None, timeout: int = 600, + check: bool = True) -> subprocess.CompletedProcess[str]: + print("+ " + " ".join(args), flush=True) + result = subprocess.run(args, env=env, text=True, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, timeout=timeout) + print(result.stdout, end="", flush=True) + if check and result.returncode: + raise subprocess.CalledProcessError(result.returncode, args, output=result.stdout) + return result + + +def case_run(case: str, fixture: Path, output: Path, image: str) -> dict[str, Any]: + project = "massspec-smoke-" + uuid.uuid4().hex[:12] + container, evidence = project + "-inference", output / case + evidence.mkdir(parents=True) + submission = fixture / ("submission-" + case if case.startswith("invalid-") else "submission-valid") + env = dict(os.environ, TASK_DATA_DIR=str(fixture / "data"), + TASK_PRIVATE_DIR=str(fixture / ("missing-labels" if case == "missing-labels" else "labels")), + MASSSPECGYM_SUBMISSION_DIR=str(submission)) + override = fixture / f"override-{case}.yaml" + # Clear GPU requests from the real local evaluation profile. !reset requires + # Compose >= 2.30 and prevents accidental GPU-dependent CPU smoke tests. + override.write_text(f'''services: + main: + image: {json.dumps(image)} + cpus: 2 + mem_limit: 4g + shm_size: 256m + gpus: !reset [] + deploy: + resources: + reservations: + devices: !reset [] + grader: + image: {json.dumps(image)} + cpus: 2 + mem_limit: 4g + command: [python, /tests/grader.py, --sealed, /sealed/run, --input, /benchmark, --labels, /private, --output, /sealed/results, --wait-seconds, '180', --mces-workers, '1'] +''') + base = ["docker", "compose", "--project-name", project, "-f", str(TASK / "tests/docker-compose.yaml"), + "-f", str(TASK / "tests/docker-compose.local.yaml")] + compose = base + ["-f", str(override)] + try: + profile = json.loads(command(base + ["config", "--format", "json"], env=env).stdout) + devices = profile["services"]["main"]["deploy"]["resources"]["reservations"]["devices"] + assert len(devices) == 1 and devices[0]["count"] == 1 and devices[0]["capabilities"] == ["gpu"] + cpu = json.loads(command(compose + ["config", "--format", "json"], env=env).stdout) + for service in cpu["services"].values(): + assert service["network_mode"] == "none" and not service.get("gpus") + assert not service.get("deploy", {}).get("resources", {}).get("reservations", {}).get("devices") + write_json(evidence / "compose.json", cpu) + command(compose + ["up", "-d", "--no-build", "grader"], env=env) + result = command(compose + ["run", "--no-deps", "--name", container, "-e", + "MASSSPECGYM_INFERENCE_TIMEOUT_SECONDS=60", "main", "/tests/test.sh"], + env=env, timeout=300, check=False) + (evidence / "supervisor.log").write_text(result.stdout) + for relative in ("report.json", "reward.json", "main/inference.log"): + target = evidence / relative + target.parent.mkdir(parents=True, exist_ok=True) + copied = command(["docker", "cp", f"{container}:/logs/verifier/{relative}", str(target)], check=False) + if copied.returncode and not (relative != "report.json" and "Could not find the file" in copied.stdout): + raise RuntimeError(f"Failed to collect {relative}: {copied.stdout}") + (evidence / "grader.log").write_text(command(compose + ["logs", "--no-color", "grader"], env=env).stdout) + report = json.loads((evidence / "report.json").read_text()) + reward = evidence / "reward.json" + if case == "missing-labels": + assert result.returncode != 0 and report["status"] == "infrastructure_error" and not reward.exists() + else: + assert result.returncode == 0 and report["status"] == {"valid": "complete", "invalid-output": "invalid_output", "invalid-submission": "invalid_submission"}[case] + hit = 0.25 if case == "valid" else 0.0 + expected = hit # the reward is the raw Hit@1 + assert report["queries"] == 4 and report["metrics"]["hit_rate_at_1"] == hit + assert math.isclose(json.loads(reward.read_text())["reward"], expected, rel_tol=0, abs_tol=1e-12) + assert report["model_quality_measured"] == (case == "valid") + if case == "valid": + assert report["metrics"]["hit_rate_at_5"] == 1.0 and math.isfinite(report["metrics"]["mces_at_1"]) + assert '"container_security_probe": "passed"' in (evidence / "main/inference.log").read_text() + return {"case": case, "status": "passed", "verifier_status": report["status"]} + finally: + command(["docker", "rm", "-f", container], check=False) + command(compose + ["down", "--volumes", "--remove-orphans"], env=env, check=False) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepare", type=Path) + parser.add_argument("--image", default="massspec-verifier:smoke") + parser.add_argument("--development-image", default="massspec-development:smoke") + parser.add_argument("--output", type=Path) + args = parser.parse_args() + if args.prepare: + prepare(args.prepare) + return + if args.output is None: + parser.error("--output is required unless --prepare is used") + started = time.monotonic() + args.output.mkdir(parents=True, exist_ok=True) + command(["docker", "version"]) + command(["docker", "compose", "version"]) + # A missing real release must fail closed. No fake full-development manifest + # is constructed to bypass the production resource completeness checks. + development = command(["docker", "run", "--rm", "--network", "none", args.development_image, "true"], check=False) + (args.output / "development.log").write_text(development.stdout) + assert development.returncode == 66 and "development manifest is missing" in development.stdout + with tempfile.TemporaryDirectory(prefix="massspec-container-smoke-") as temporary: + fixture = Path(temporary) + command(["docker", "run", "--rm", "--network", "none", "--user", f"{os.getuid()}:{os.getgid()}", + "--mount", f"type=bind,src={fixture},dst=/fixture", args.image, + "python", "/tests/container_smoke.py", "--prepare", "/fixture"]) + cases = [case_run(case, fixture, args.output, args.image) + for case in ("valid", "invalid-output", "invalid-submission", "missing-labels")] + write_json(args.output / "container-smoke.json", {"schema": "massspec-container-smoke/v1", "status": "passed", + "scope": "Native Docker CPU deployment checks with four synthetic queries; not HF materialization or scientific reproduction", + "scientific_accuracy_evidence": False, "development_missing_data_fails_closed": True, + "cases": cases, "wall_seconds": time.monotonic() - started}) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/26/266b228daba19b5dc0b9007cf12f9092945cd915db75c6d1571856e4c52291a6/native_verifier.py b/reproduction/files/26/266b228daba19b5dc0b9007cf12f9092945cd915db75c6d1571856e4c52291a6/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..fb83398eee7353d0bb93e75382859b33fb9e1adc --- /dev/null +++ b/reproduction/files/26/266b228daba19b5dc0b9007cf12f9092945cd915db75c6d1571856e4c52291a6/native_verifier.py @@ -0,0 +1,188 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import shutil +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus']) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if phase == 'inference': + if plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + subprocess.run(['useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + runtime.deny_network() + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run'], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc']) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg['command'][0], '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + subprocess.run([cfg['command'][0], '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': 'IPv4/IPv6 socket creation denied; inherited by children', + 'source_mounts': 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan['task'] != 'protein-folding-prediction', + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True) + elapsed = time.monotonic() - entered + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + reward_path = STATE / 'results/reward.json' + if phase == 'score': + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = Path('/sealed/results') / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/2a/2a3f0ef1b8b942a6d7cf4845d3fff2f0299706297d40f867c203ea1b2172cdd2/test_external_lfmc_statistics.py b/reproduction/files/2a/2a3f0ef1b8b942a6d7cf4845d3fff2f0299706297d40f867c203ea1b2172cdd2/test_external_lfmc_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..80a5b34410b20868d04f98b09882aa23db1959bd --- /dev/null +++ b/reproduction/files/2a/2a3f0ef1b8b942a6d7cf4845d3fff2f0299706297d40f867c203ea1b2172cdd2/test_external_lfmc_statistics.py @@ -0,0 +1,119 @@ +"""Synthetic checks only: never load external labels, imagery or predictions.""" + +import copy +from pathlib import Path +import sys +import unittest + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/analysis")) +from external_lfmc_statistics import aggregate_target, paired_statistics + + +class StatisticsTests(unittest.TestCase): + def fixture(self, random=(2, 2, 2), trained=(1, 1, 1)): + rows = [ + {"id": str(i), "site_id": site, "country": "country"} + for i, site in enumerate(["a", "b", "b", "b"]) + ] + ids = [r["id"] for r in rows] + labels = {"ids": ids, "values": [10.0] * 4} + pairs = [ + { + "seed": seed, + "random": {"ids": ids, "values": [10 + r] * 4}, + "trained": {"ids": ids, "values": [10 + t] * 4}, + } + for seed, (r, t) in enumerate(zip(random, trained)) + ] + return rows, labels, pairs + + def test_constant_paired_improvement(self): + result = paired_statistics(*self.fixture()) + self.assertEqual(result["mean_seed_mae_gain"], 1) + self.assertEqual(result["site_bootstrap_95_percent_interval"], [1, 1]) + self.assertEqual(result["seed_and_site_bootstrap_95_percent_interval"], [1, 1]) + self.assertTrue(result["statistical_criterion_met"]) + + def test_one_regressing_seed_cannot_be_hidden_by_mean(self): + result = paired_statistics(*self.fixture(random=(5, 5, 0))) + self.assertGreater(result["mean_seed_mae_gain"], 0) + self.assertFalse(result["statistical_criterion_met"]) + + def test_zero_gain_does_not_pass(self): + self.assertFalse( + paired_statistics(*self.fixture(trained=(2, 2, 2)))[ + "statistical_criterion_met" + ] + ) + + def test_cluster_bootstrap_against_explicit_resampled_rows(self): + rows, labels, pairs = self.fixture() + for i, pair in enumerate(pairs): + pair["random"]["values"] = [10 + i, 11, 12, 13] + pair["trained"]["values"] = [11, 10 + i, 11, 12] + result = paired_statistics(rows, labels, pairs) + rng = np.random.default_rng(42) + site_draws = rng.integers(0, 2, size=(5000, 2)) + seed_draws = rng.integers(0, 3, size=(5000, 3)) + group_rows = [np.array([0]), np.array([1, 2, 3])] + gains = np.array( + [ + np.abs(np.array(p["random"]["values"]) - 10) + - np.abs(np.array(p["trained"]["values"]) - 10) + for p in pairs + ] + ) + site_boot, joint_boot = [], [] + for sites, seeds in zip(site_draws, seed_draws): + indices = np.concatenate([group_rows[s] for s in sites]) + site_boot.append(gains[:, indices].mean()) + joint_boot.append(gains[np.ix_(seeds, indices)].mean()) + np.testing.assert_allclose( + result["site_bootstrap_95_percent_interval"], + np.quantile(site_boot, [0.025, 0.975]), + ) + np.testing.assert_allclose( + result["seed_and_site_bootstrap_95_percent_interval"], + np.quantile(joint_boot, [0.025, 0.975]), + ) + self.assertEqual(result["per_seed"][0]["random"]["mae"], 1.5) + self.assertEqual(result["per_seed"][0]["random"]["site_macro_mae"], 1.0) + + def test_alignment_nonfinite_and_seed_failures(self): + for variant in ("ids", "nan", "seed", "missing"): + with self.subTest(variant=variant): + rows, labels, pairs = copy.deepcopy(self.fixture()) + if variant == "ids": + pairs[0]["trained"]["ids"] = ["1", "0", "2", "3"] + elif variant == "nan": + pairs[0]["trained"]["values"][0] = float("nan") + elif variant == "seed": + pairs[1]["seed"] = pairs[0]["seed"] + else: + labels["values"] = labels["values"][:-1] + with self.assertRaises(ValueError): + paired_statistics(rows, labels, pairs) + + def test_target_rules_preserve_duplicates_without_upper_clip(self): + result = aggregate_target( + list( + enumerate([-10, 20, 20, 10000, None, True, "20", float("inf")], start=2) + ) + ) + self.assertEqual(result["value"], 2510) + self.assertEqual(result["valid_source_rows"], 4) + self.assertEqual(result["counts"]["lower_clipped"], 1) + self.assertEqual(len(result["excluded"]), 4) + + def test_no_valid_target_is_unscoreable(self): + result = aggregate_target([(2, None), (3, float("nan"))]) + self.assertFalse(result["scoreable"]) + self.assertIsNone(result["value"]) + with self.assertRaises(ValueError): + aggregate_target([(2, 10), (2, 10)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/2e/2e74903101e0161171160e75882a2c4299a316396063021ffbba5b9ac9d4e38e/docker-compose.local.yaml b/reproduction/files/2e/2e74903101e0161171160e75882a2c4299a316396063021ffbba5b9ac9d4e38e/docker-compose.local.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8d0b29ddefad382ebc58c14585531f10ba41d1a3 --- /dev/null +++ b/reproduction/files/2e/2e74903101e0161171160e75882a2c4299a316396063021ffbba5b9ac9d4e38e/docker-compose.local.yaml @@ -0,0 +1,12 @@ +# Native Docker replay of a frozen submission; no development mounts. +services: + main: + command: ["/opt/task/tests/test.sh"] + # Inherit exactly one GPU from the verifier base configuration. + volumes: + - type: bind + source: ${SURFACE_CODE_SUBMISSION:?Set SURFACE_CODE_SUBMISSION} + target: /workspace/submission + read_only: true + bind: + create_host_path: false diff --git a/reproduction/files/2e/2eca9186f691576067f33dda6fec9f7c53201dfc29654f1fe6b24c0b63faf352/test_screening.py b/reproduction/files/2e/2eca9186f691576067f33dda6fec9f7c53201dfc29654f1fe6b24c0b63faf352/test_screening.py new file mode 100644 index 0000000000000000000000000000000000000000..dc43543cc96c9e3698053e29f5fd95166ac48491 --- /dev/null +++ b/reproduction/files/2e/2eca9186f691576067f33dda6fec9f7c53201dfc29654f1fe6b24c0b63faf352/test_screening.py @@ -0,0 +1,232 @@ +"""Screening never changes canonical membership or admits final-test payloads.""" + +import contextlib +import io +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +import h5py +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/evaluation")) +import screening + + +class TestScreening(unittest.TestCase): + def rows(self): + return [ + { + "index": 0, + "id": "train-a", + "split": "train", + "label": 1, + "latlon": [1, 2], + }, + {"index": 1, "id": "test", "split": "test", "label": 999, "latlon": [9, 9]}, + {"index": 2, "id": "val-a", "split": "val", "label": 2, "latlon": [1, 2]}, + { + "index": 3, + "id": "train-b", + "split": "train", + "label": 3, + "latlon": [3, 4], + }, + {"index": 4, "id": "val-b", "split": "val", "label": 4, "latlon": [3, 4]}, + ] + + def test_no_test_row_is_deserialized(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "labels.json" + path.write_text(json.dumps(self.rows())) + original = json.loads + + def guarded(raw): + self.assertNotIn('"split": "test"', raw) + return original(raw) + + with patch.object(screening.json, "loads", guarded): + rows = screening.trainval_rows(path) + self.assertEqual([row["index"] for row in rows], [0, 2, 3, 4]) + + def test_seeded_site_selection_preserves_entire_sites_and_splits(self): + rows = [row for row in self.rows() if row["split"] != "test"] + selected, sites, count = screening.sample_lfmc(rows, 20260930, 0.5) + reversed_selection, _, _ = screening.sample_lfmc(rows[::-1], 20260930, 0.5) + self.assertEqual(count, 2) + self.assertEqual(len(sites), 1) + self.assertEqual(len(selected), 2) + self.assertEqual({row["split"] for row in selected}, {"train", "val"}) + self.assertEqual( + {row["id"] for row in selected}, {row["id"] for row in reversed_selection} + ) + + def test_prepare_copies_only_trainval_without_modifying_source(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + rows = self.rows() + snapshots = {} + for task in ("awf", "lfmc"): + folder = root / "data" / "eval" / task + folder.mkdir(parents=True) + (folder / "labels.json").write_text(json.dumps(rows)) + with h5py.File(folder / "inputs.h5", "w") as source: + source.attrs["task"] = task + source.create_dataset( + "ids", + data=[row["id"] for row in rows], + dtype=h5py.string_dtype(), + ) + source.create_dataset( + "pixels", + data=np.arange(10).reshape(5, 2), + chunks=(1, 2), + compression="lzf", + ) + snapshots[task] = [ + screening.sha256(folder / name) + for name in ("inputs.h5", "labels.json") + ] + output = root / "view" + try: + result = screening.prepare(root / "data", output, fraction=1) + self.assertEqual(result["test_rows_in_view"], 0) + self.assertEqual(result["kind"], "fixed_validation_view") + self.assertEqual( + screening.population(output)["kind"], "full_validation" + ) + for task in ("awf", "lfmc"): + self.assertEqual( + result["tasks"][task]["rows"], {"train": 2, "val": 2} + ) + source = root / "data" / "eval" / task + self.assertEqual( + snapshots[task], + [ + screening.sha256(source / name) + for name in ("inputs.h5", "labels.json") + ], + ) + with h5py.File(output / task / "inputs.h5", "r") as view: + self.assertEqual( + view["ids"].asstr()[:].tolist(), + ["train-a", "val-a", "train-b", "val-b"], + ) + np.testing.assert_array_equal( + view["pixels"][:], np.arange(10).reshape(5, 2)[[0, 2, 3, 4]] + ) + self.assertEqual( + (output / task / "inputs.h5").stat().st_mode & 0o222, 0 + ) + with self.assertRaises(FileExistsError): + screening.prepare(root / "data", output) + with self.assertRaises(ValueError): + screening.prepare(root / "data", root / "data" / "eval" / "view") + finally: + # Let TemporaryDirectory remove the immutable test fixture. + if output.exists(): + output.chmod(0o755) + for folder in output.iterdir(): + if folder.is_dir(): + folder.chmod(0o755) + + def test_cache_rejects_unrecorded_or_changed_input_context(self): + with tempfile.TemporaryDirectory() as tmp: + packages = [Path(tmp) / name for name in ("random", "trained")] + for package, origin in zip( + packages, ("random_initialization", "own_from_scratch_training") + ): + package.mkdir() + (package / "config.json").write_text('{"embedding_size": 2}') + (package / "infer.py").write_text("same adapter") + (package / "encoder.pt").write_bytes(b"weights") + info = { + "origin": origin, + "checkpoint": ( + None if origin == "random_initialization" else "checkpoint" + ), + "upstream": "pinned", + "initialization_seed": 12536, + "parameters": 2, + "inference_adapter_version": 3, + "infer_sha256": screening.sha256(package / "infer.py"), + "encoder_sha256": screening.sha256(package / "encoder.pt"), + } + (package / "provenance.json").write_text(json.dumps(info)) + context = { + "gpu_type": "H200", + "torch": "pinned", + "cuda": "pinned", + "batch_size": 16, + "python_hash_seed": 0, + "input_sha256": {"lfmc": "fixed-input"}, + } + self.assertTrue( + screening.check_cache(*packages, context, context, "lfmc")["compatible"] + ) + for changed in ( + {**context, "input_sha256": {}}, + {**context, "input_sha256": {"lfmc": "different-input"}}, + {**context, "batch_size": 32}, + ): + with self.assertRaises(ValueError): + screening.check_cache(*packages, context, changed, "lfmc") + (packages[1] / "config.json").write_text('{"embedding_size": 3}') + with self.assertRaisesRegex(ValueError, "architecture"): + screening.check_cache(*packages, context, context, "lfmc") + + def test_raw_baseline_forwarded_to_unchanged_comparison(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + view = root / "view" + view.mkdir() + (view / "manifest.json").write_text( + json.dumps( + { + "kind": "fixed_screening_view", + "test_rows_in_view": 0, + "population": "fixed train/validation view", + } + ) + ) + evaluation = root / "evaluation" + evaluation.mkdir() + (evaluation / "eval").symlink_to(view) + output = evaluation / "comparison.json" + + def fake_compare(command, **kwargs): + self.assertEqual(command[-2:], ["--raw-baseline", "raw"]) + self.assertEqual(Path(command[1]).name, "compare_seeds.py") + self.assertNotIn("--final-test", command) + output.write_text('{"tasks": {}}') + + argv = [ + "screening.py", + "compare", + "--view", + str(view), + "--data-root", + str(evaluation), + "--pairs", + "random:trained", + "--raw-baseline", + "raw", + "--output", + str(output), + ] + with patch.object(sys, "argv", argv), patch.object( + screening.subprocess, "run", fake_compare + ), contextlib.redirect_stdout(io.StringIO()): + screening.main() + report = json.loads(output.read_text()) + self.assertEqual(report["evaluation_population"]["kind"], "screening") + self.assertFalse( + report["evaluation_population"]["final_recipe_criterion_established"] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/30/3059c226acbbbf5286ea55495575287bafe78ad244256b19a5dcd5d3279bfba7/score.py b/reproduction/files/30/3059c226acbbbf5286ea55495575287bafe78ad244256b19a5dcd5d3279bfba7/score.py new file mode 100644 index 0000000000000000000000000000000000000000..3335a3902eeb541488137a6deccc116bca755814 --- /dev/null +++ b/reproduction/files/30/3059c226acbbbf5286ea55495575287bafe78ad244256b19a5dcd5d3279bfba7/score.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Score visible validation rankings with fixed-denominator hit rates.""" + +import argparse +import hashlib +import json +from pathlib import Path + +from diagnostics import describe +from benchmark_score import normalize + + +REFERENCE_BASELINE = "GLACIER no-CF with strict-clean MIST fallback" +# Filled from the frozen full-denominator operator replay documented in +# ../reference/reference_baseline.json. +REFERENCE_HIT_RATE_AT_1 = 0.4939052175894281 + + +def molecule_id(smiles): + return hashlib.sha256(smiles.encode()).hexdigest() + + +def jsonl(path): + with path.open() as stream: + return [json.loads(line) for line in stream if line.strip()] + + +def load_rankings(path, expected, pools): + rankings = {} + for row in jsonl(path): + if not isinstance(row, dict) or set(row) != {"query_id", "ranking"}: + raise ValueError("malformed ranking row") + query_id, ranking = row["query_id"], row["ranking"] + if not isinstance(query_id, str) or query_id not in expected or query_id in rankings: + raise ValueError("unknown or duplicate query ranking") + candidate_ids = [candidate["candidate_id"] for candidate in pools[expected[query_id]["pool"]]] + if (not isinstance(ranking, list) or any(not isinstance(value, str) for value in ranking) + or len(ranking) != len(candidate_ids) or set(ranking) != set(candidate_ids)): + raise ValueError("ranking is not an exact candidate permutation") + rankings[query_id] = ranking + return rankings + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--input-root", required=True, type=Path) + parser.add_argument("--rankings", required=True, type=Path) + parser.add_argument("--query-input", type=Path) + parser.add_argument("--mces", action="store_true") + parser.add_argument("--baseline-rankings", type=Path, help="A ranking on the same validation query set") + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + selected_queries = None + if args.query_input is not None: + selected_queries = { + row["query_id"] for row in jsonl(args.query_input / "queries.jsonl") + } + if not selected_queries: + raise ValueError("query input is empty") + pools = { + row["candidate_pool_id"]: row["candidates"] + for row in jsonl(args.input_root / "validation_candidate_pools.jsonl") + } + expected, selected_rows = {}, {} + for row in jsonl(args.input_root / "validation.jsonl"): + if selected_queries is not None and row["query_id"] not in selected_queries: + continue + expected[row["query_id"]] = { + "pool": row["candidate_pool_id"], + "correct": molecule_id(row["target_smiles"]), + "smiles": row["target_smiles"], + } + selected_rows[row["query_id"]] = row + if not expected or (selected_queries is not None and set(expected) != selected_queries): + raise ValueError("query input must be a nonempty subset of validation") + rankings, global_error = {}, None + try: + rankings = load_rankings(args.rankings, expected, pools) + except (OSError, ValueError, json.JSONDecodeError) as error: + rankings, global_error = {}, str(error) + + metrics = {} + for k in (1, 5, 20): + metrics[f"hit_rate_at_{k}"] = sum( + query_id in rankings and item["correct"] in rankings[query_id][:k] + for query_id, item in expected.items() + ) / len(expected) + if args.mces: + from myopic_mces.myopic_mces import MCES + import pulp + if not pulp.PULP_CBC_CMD(msg=False).available(): + raise RuntimeError("Pulp's bundled CBC solver is not available") + total = 0.0 + for query_id, item in expected.items(): + if query_id not in rankings: + total += 100.0 + continue + by_id = { + candidate["candidate_id"]: candidate["smiles"] + for candidate in pools[item["pool"]] + } + predicted = by_id[rankings[query_id][0]] + total += MCES( + s1=item["smiles"], s2=predicted, ind=0, threshold=15, + always_stronger_bound=True, solver="PULP_CBC_CMD", + solver_options={"msg": 0}, + )[1] + metrics["mces_at_1"] = total / len(expected) + baseline = None + if args.baseline_rankings: + baseline = load_rankings(args.baseline_rankings, expected, pools) + if set(baseline) != set(expected): + raise ValueError("paired baseline must cover the same complete validation query set") + report = { + "schema": "massspecgym-retrieval-development-report/v1", + "queries": len(expected), + "valid_rankings": len(rankings), + "global_error": global_error, + "external_reference_context": { + "name": REFERENCE_BASELINE, + "hit_rate_at_1": REFERENCE_HIT_RATE_AT_1, + "fold": "test", + "comparable_to_this_validation_report": False, + }, + "metrics": metrics, + "benchmark_score": {**normalize(metrics["hit_rate_at_1"]), + "evaluation_fold": "validation", + "comparable_to_test_reference": False}, + **describe(selected_rows, pools, rankings, {q: item['correct'] for q, item in expected.items()}, + resamples=args.bootstrap_resamples, seed=args.seed, baseline=baseline), + } + text = json.dumps(report, sort_keys=True, indent=2) + '\n' + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(text) + print(text, end='') + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/32/32b8a9d674ad68c27fee1dba07a7424698146e60d177ad778de4981abc93186e/test_training.py b/reproduction/files/32/32b8a9d674ad68c27fee1dba07a7424698146e60d177ad778de4981abc93186e/test_training.py new file mode 100644 index 0000000000000000000000000000000000000000..f928fee60c1b073b6c915056645896eb1245eba2 --- /dev/null +++ b/reproduction/files/32/32b8a9d674ad68c27fee1dba07a7424698146e60d177ad778de4981abc93186e/test_training.py @@ -0,0 +1,40 @@ +import copy +import sys +from pathlib import Path + +import numpy as np +import pytest +from ase import units +from ase.build import bulk +from pymatgen.core import Structure + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/data")) +from records import formula, mptrj_record, validate +from splits import stable_hash + + +def test_raw_total_energy_and_vasp_stress_conversion(): + atoms = bulk("Cu", cubic=True) + row = dict( + structure=Structure.from_ase_atoms(atoms).as_dict(), + uncorrected_total_energy=-12.0, + corrected_total_energy=-14.0, + energy_per_atom=-3.5, + force=np.zeros((4, 3)).tolist(), + stress=(10 * np.eye(3)).tolist(), + ) + result = mptrj_record("mp-1", "mp-1-0-0", row) + assert result["energy"] == -12.0 + assert np.allclose(result["stress"], -np.eye(3) * units.GPa) + assert validate(result) == "Cu" + row["energy_per_atom"] = -12.0 + with pytest.raises(ValueError, match="identity"): + mptrj_record("mp-1", "frame", row) + + +def test_composition_exclusion_covers_cell_changes(): + small = bulk("Cu") + large = small.repeat((2, 2, 2)) + large.rattle(0.01, seed=5) + assert formula(small) == formula(large) + assert stable_hash(formula(small)) == stable_hash(formula(large)) diff --git a/reproduction/files/34/34f9fae01dd776b90a90e00d08b2ee4d8492c717073999cd4e870a934f8fa7d4/test_task.py b/reproduction/files/34/34f9fae01dd776b90a90e00d08b2ee4d8492c717073999cd4e870a934f8fa7d4/test_task.py new file mode 100644 index 0000000000000000000000000000000000000000..11a9aa74c4ee978c15b51d248126cc2d0d4335a7 --- /dev/null +++ b/reproduction/files/34/34f9fae01dd776b90a90e00d08b2ee4d8492c717073999cd4e870a934f8fa7d4/test_task.py @@ -0,0 +1,129 @@ +"""Unit tests for the task plumbing (run inside the dev or verifier image: needs cell-eval). + + python -m pytest tests/test_task.py -q (from the task directory) +""" +import hashlib +import json +import subprocess +import sys +from pathlib import Path + +import anndata as ad +import numpy as np +import pandas as pd +import pytest +from scipy import sparse + +TASK = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(TASK / "tests")) +import cellscore # noqa: E402 + + +def test_scorer_copies_identical(): + a = (TASK / "environment" / "evaluation" / "cellscore.py").read_bytes() + b = (TASK / "tests" / "cellscore.py").read_bytes() + assert hashlib.sha256(a).hexdigest() == hashlib.sha256(b).hexdigest() + + +def test_download_manifest_wellformed(): + m = json.loads((TASK / "environment" / "data" / "download-source.json").read_text()) + for key, entry in m["files"].items(): + assert "path" in entry and ("url" in entry or "hf_repo" in entry), key + + +def _synthetic(seed=0, n_genes=300, n_basal=400, n_targets=12, n_cells=60): + rng = np.random.default_rng(seed) + base_rate = rng.gamma(2.0, 1.0, size=n_genes) + basal = rng.poisson(base_rate, size=(n_basal, n_genes)).astype(np.float32) + genes = [f"G{i}" for i in range(n_genes)] + targets = [f"T{i}" for i in range(n_targets)] + requests = [{"request_id": f"ctx:{i:04d}", "context": "ctx", "perturbation": {"type": "crispri", "target": t}, + "n_cells": n_cells, "seed": i} for i, t in enumerate(targets)] + resp_blocks, resp_targets = [], [] + effects = {} + for t in targets: + eff = np.ones(n_genes); hit = rng.choice(n_genes, 30, replace=False) + eff[hit] = rng.choice([0.2, 3.0], size=30) + effects[t] = eff + resp_blocks.append(rng.poisson(base_rate * eff, size=(80, n_genes)).astype(np.float32)) + resp_targets += [t] * 80 + basal_a = ad.AnnData(X=sparse.csr_matrix(basal), obs=pd.DataFrame({"target_gene": "non-targeting"}, index=[f"c{i}" for i in range(n_basal)]), + var=pd.DataFrame(index=genes)) + resp_a = ad.AnnData(X=sparse.csr_matrix(np.vstack(resp_blocks)), obs=pd.DataFrame({"target_gene": resp_targets}, index=[f"r{i}" for i in range(len(resp_targets))]), + var=pd.DataFrame(index=genes)) + # an "oracle" prediction: fresh draws from the true perturbed rates + pred_blocks, ids = [], [] + for r in requests: + pred_blocks.append(rng.poisson(base_rate * effects[r["perturbation"]["target"]], size=(n_cells, n_genes)).astype(np.float32)) + ids += [r["request_id"]] * n_cells + pred_a = ad.AnnData(X=sparse.csr_matrix(np.vstack(pred_blocks)), obs=pd.DataFrame({"request_id": ids}, index=[f"p{i}" for i in range(len(ids))]), + var=pd.DataFrame(index=genes)) + return basal_a, resp_a, pred_a, requests + + +def test_scorer_oracle_beats_noeffect(tmp_path): + basal, resp, pred, requests = _synthetic() + (tmp_path / "requests.jsonl").write_text("\n".join(json.dumps(r) for r in requests) + "\n") + basal.write_h5ad(tmp_path / "basal.h5ad"); resp.write_h5ad(tmp_path / "responses.h5ad"); pred.write_h5ad(tmp_path / "pred.h5ad") + noeff = cellscore.noeffect_prediction(basal, requests); noeff.write_h5ad(tmp_path / "noeffect.h5ad") + good = cellscore.score_context(tmp_path / "pred.h5ad", tmp_path / "basal.h5ad", tmp_path / "responses.h5ad", + tmp_path / "requests.jsonl", tmp_path / "out_good", threads=4) + base = cellscore.score_context(tmp_path / "noeffect.h5ad", tmp_path / "basal.h5ad", tmp_path / "responses.h5ad", + tmp_path / "requests.jsonl", tmp_path / "out_base", threads=4) + assert good["all"]["score"] > 0.3 + assert base["all"]["score"] < 0.05 + + +def test_scorer_rejects_bad_predictions(tmp_path): + basal, resp, pred, requests = _synthetic() + bad = pred[:-5].copy() # one request short of cells + with pytest.raises(ValueError): + cellscore.assemble_prediction(bad, basal, requests) + shuffled = pred.copy(); shuffled.obs["request_id"] = shuffled.obs["request_id"].map(lambda s: s.replace("ctx:", "zzz:")) + with pytest.raises(ValueError): + cellscore.assemble_prediction(shuffled, basal, requests) + wrong_genes = pred[:, ::-1].copy() + with pytest.raises(ValueError): + cellscore.assemble_prediction(wrong_genes, basal, requests) + + +def test_noeffect_package_runs(tmp_path): + basal, resp, pred, requests = _synthetic() + inp = tmp_path / "in"; inp.mkdir() + basal.write_h5ad(inp / "basal.h5ad") + (inp / "requests.jsonl").write_text("\n".join(json.dumps(r) for r in requests) + "\n") + (inp / "context.json").write_text(json.dumps({"context_id": "ctx", "chemistry": "10x_3p_v3", "n_genes": basal.n_vars})) + out = tmp_path / "out" + subprocess.run(["bash", str(TASK / "environment" / "baseline" / "noeffect" / "infer.sh"), str(inp), str(out)], check=True) + p = ad.read_h5ad(out / "predictions.h5ad") + assert p.n_obs == sum(r["n_cells"] for r in requests) + cellscore.assemble_prediction(p, basal, requests) + + +def test_publish_swaps_whole_package(tmp_path): + src = tmp_path / "pkg" + (src / "st_data").mkdir(parents=True) + (src / "infer.sh").write_text("#!/usr/bin/env bash\n") + (src / "st_data" / "train.h5ad").write_text("training-only") + out = tmp_path / "submission" + for version in ("1", "2"): + (src / "weights.txt").write_text(version) + subprocess.run([sys.executable, str(TASK / "environment" / "baseline" / "publish.py"), str(src), + "--output", str(out)], check=True, capture_output=True) + assert (out / "weights.txt").read_text() == version + assert not (out / "st_data" / "train.h5ad").exists() + assert sorted(p.name for p in tmp_path.iterdir()) == ["pkg", "submission"] # no staging leftovers + + +def test_development_mounts_follow_task_standard(): + compose = (TASK / "environment" / "docker-compose.yaml").read_text() + for entry in ("train", "test", "priors", "se600m", "manifest.json", "splits.json"): + assert f'/{entry}", target: /workspace/data/{entry}}}' in compose + assert "TASK_PRIVATE_DIR" not in compose and "network_mode" not in compose + assert "target: /workspace/research" in compose + dockerfile = (TASK / "environment" / "Dockerfile").read_text() + assert "ln -s /workspace/data/se600m /opt/se600m" in dockerfile + assert "COPY instruction.md /workspace/instruction.md" in dockerfile + verifier = (TASK / "tests" / "docker-compose.yaml").read_text() + main = verifier.split(" main:")[1].split(" grader:")[0] + assert "TASK_PRIVATE_DIR" not in main and "TASK_PRIVATE_DIR" in verifier diff --git a/reproduction/files/36/3672316bc2c989a915025f7948742278b6f30efc6ed9072c1b61fbd6226eb7a0/screening.py b/reproduction/files/36/3672316bc2c989a915025f7948742278b6f30efc6ed9072c1b61fbd6226eb7a0/screening.py new file mode 100644 index 0000000000000000000000000000000000000000..0fef6212ad84b5764d778cfc34e94235c555cabd --- /dev/null +++ b/reproduction/files/36/3672316bc2c989a915025f7948742278b6f30efc6ed9072c1b61fbd6226eb7a0/screening.py @@ -0,0 +1,392 @@ +"""Immutable full or site-sampled validation views; canonical data stays untouched.""" + +import argparse +from collections import Counter +import hashlib +import json +import math +from pathlib import Path +import re +import subprocess +import sys + +import h5py +import numpy as np + + +def sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def json_objects(path): + """Yield raw row objects without deserializing excluded final-test labels.""" + text = Path(path).read_text() + if not text.lstrip().startswith("[") or not text.rstrip().endswith("]"): + raise ValueError("Expected a JSON array of release rows") + depth, quoted, escaped, start = 0, False, False, None + for index, character in enumerate(text): + if quoted: + if escaped: + escaped = False + elif character == "\\": + escaped = True + elif character == '"': + quoted = False + elif character == '"': + quoted = True + elif character == "{": + if depth == 0: + start = index + depth += 1 + elif character == "}": + depth -= 1 + if depth < 0: + raise ValueError("Malformed release rows") + if depth == 0: + yield text[start : index + 1] + if depth or quoted: + raise ValueError("Malformed release rows") + + +def trainval_rows(path): + rows = [] + for index, raw in enumerate(json_objects(path)): + # The release's split field precedes labels. Check it before decoding a + # row, so test labels are never turned into values or passed to probes. + split = re.search(r'"split"\s*:\s*"(train|val|test)"', raw) + if split is None: + raise ValueError("Missing official split") + if split[1] == "test": + continue + row = json.loads(raw) + if row["split"] not in ("train", "val") or row["index"] != index: + raise ValueError("Unexpected release row order or split") + rows.append(row) + if len({row["id"] for row in rows}) != len(rows): + raise ValueError("Duplicate train/validation IDs") + return rows + + +def site(row): + # Same LFMC site definition as compare_seeds.py, fixed before fitting. + return tuple(np.round(np.asarray(row["latlon"], dtype=float), 6).tolist()) + + +def sample_lfmc(rows, seed, fraction): + if not 0 < fraction <= 1: + raise ValueError("Site fraction must be in (0, 1]") + sites = sorted({site(row) for row in rows}) + ranked = sorted( + sites, + key=lambda value: hashlib.sha256( + json.dumps([seed, value], separators=(",", ":")).encode() + ).digest(), + ) + selected = set(ranked[: math.ceil(len(sites) * fraction)]) + subset = [row for row in rows if site(row) in selected] + if {row["split"] for row in subset} != {"train", "val"}: + raise ValueError( + "Site sample omitted train or validation; choose its policy before scoring" + ) + return subset, sorted(selected), len(sites) + + +def copy_inputs(source_path, destination, rows, task): + """Copy selected source rows byte-for-byte, with their canonical ordering.""" + indices = [row["index"] for row in rows] + with h5py.File(source_path, "r") as source, h5py.File(destination, "x") as dest: + if source.attrs["task"] != task: + raise ValueError("Wrong input task") + if source["ids"].asstr()[indices].tolist() != [row["id"] for row in rows]: + raise ValueError("Input IDs disagree with canonical row indices") + dest.attrs.update(source.attrs) + for name, values in source.items(): + shape = (len(indices), *values.shape[1:]) + options = {} + if values.chunks: + options["chunks"] = ( + min(values.chunks[0], len(indices)), + *values.chunks[1:], + ) + if values.compression: + options["compression"] = values.compression + if values.compression_opts is not None: + options["compression_opts"] = values.compression_opts + target = dest.create_dataset( + name, shape=shape, dtype=values.dtype, **options + ) + target.attrs.update(values.attrs) + for start in range(0, len(indices), 64): + target[start : start + 64] = values[indices[start : start + 64]] + + +def prepare(data_root, output, seed=20260930, fraction=0.125): + source_root = (Path(data_root) / "eval").resolve() + output = Path(output).resolve() + if output == source_root or source_root in output.parents: + raise ValueError("Screening view must be outside canonical evaluation data") + if output.exists(): + raise FileExistsError("Refusing to overwrite a fixed screening population") + selections = {} + for task in ("awf", "lfmc"): + rows = trainval_rows(source_root / task / "labels.json") + if task == "lfmc": + rows, sites, total_sites = sample_lfmc(rows, seed, fraction) + else: + sites, total_sites = None, None + selections[task] = (rows, sites, total_sites) + output.mkdir(parents=True) + manifest = { + "kind": "fixed_validation_view" if fraction == 1 else "fixed_screening_view", + "schema_version": 1, + "population": ( + "full AWF and LFMC train/val" + if fraction == 1 + else "full AWF train/val; LFMC site-sampled train/val" + ), + "selection_seed": seed, + "lfmc_site_fraction": fraction, + "selection_method": "lowest SHA256 of compact JSON [seed, rounded latlon]; ceil(fraction * sites)", + "site_coordinates_decimals": 6, + "canonical_data_immutable": True, + "test_rows_in_view": 0, + "test_labels_deserialized": False, + "inference": {"batch_size": 16, "python_hash_seed": 0}, + "probe_protocol": "unchanged environment/evaluation/probes.py grids", + "tasks": {}, + } + for task, (rows, sites, total_sites) in selections.items(): + folder = output / task + folder.mkdir() + (folder / "labels.json").write_text(json.dumps(rows, indent=2) + "\n") + copy_inputs(source_root / task / "inputs.h5", folder / "inputs.h5", rows, task) + membership = [ + {"id": row["id"], "index": row["index"], "split": row["split"]} + for row in rows + ] + manifest["tasks"][task] = { + "source": str(source_root / task), + "rows": dict(Counter(row["split"] for row in rows)), + "canonical_indices_and_ids": membership, + "ordered_ids_sha256": hashlib.sha256( + json.dumps([row["id"] for row in rows]).encode() + ).hexdigest(), + "input_sha256": sha256(folder / "inputs.h5"), + "labels_sha256": sha256(folder / "labels.json"), + "selected_sites": sites, + "canonical_trainval_site_count": total_sites, + } + for path in folder.iterdir(): + path.chmod(0o444) + folder.chmod(0o555) + path = output / "manifest.json" + path.write_text(json.dumps(manifest, indent=2) + "\n") + path.chmod(0o444) + output.chmod(0o555) + return manifest + + +def check_cache( + random_package, candidate_package, cached_context, current_context, task +): + """Reject historical/full-view or different-architecture random caches.""" + packages = [Path(random_package), Path(candidate_package)] + provenance = [ + json.loads((path / "provenance.json").read_text()) for path in packages + ] + if ( + provenance[0].get("origin") != "random_initialization" + or provenance[0].get("checkpoint") is not None + ): + raise ValueError("Cached control must be an untrained random encoder") + if provenance[1].get("origin") != "own_from_scratch_training": + raise ValueError("Candidate must be our from-scratch trained encoder") + if json.loads((packages[0] / "config.json").read_text()) != json.loads( + (packages[1] / "config.json").read_text() + ): + raise ValueError("Cached control architecture differs") + for key in ( + "upstream", + "initialization_seed", + "parameters", + "inference_adapter_version", + "infer_sha256", + ): + if key not in provenance[0] or provenance[0][key] != provenance[1].get(key): + raise ValueError(f"Cached control differs in {key}") + for path, info in zip(packages, provenance): + if ( + sha256(path / "infer.py") != info["infer_sha256"] + or sha256(path / "encoder.pt") != info["encoder_sha256"] + ): + raise ValueError("Package files disagree with their provenance") + if provenance[1].get("training_validity") == "invalid": + raise ValueError("Known invalid candidate training") + for key in ("gpu_type", "torch", "cuda", "batch_size", "python_hash_seed"): + if key not in cached_context or cached_context[key] != current_context.get(key): + raise ValueError(f"Cached inference context differs in {key}") + if current_context["batch_size"] != 16 or current_context["python_hash_seed"] != 0: + raise ValueError("Screening requires inference batch 16 and hash seed 0") + cached_input = cached_context.get("input_sha256", {}).get(task) + if not cached_input or cached_input != current_context.get("input_sha256", {}).get( + task + ): + raise ValueError( + "Cached control has a different or unrecorded input view/batch ordering" + ) + return {"compatible": True, "task": task, "input_sha256": cached_input} + + +def population(view): + view = Path(view).resolve() + manifest = json.loads((view / "manifest.json").read_text()) + if ( + manifest.get("kind") not in ("fixed_screening_view", "fixed_validation_view") + or manifest.get("test_rows_in_view") != 0 + ): + raise ValueError("Expected fixed train/validation view") + return { + "kind": ( + "full_validation" + if manifest["kind"] == "fixed_validation_view" + else "screening" + ), + "manifest": str(view / "manifest.json"), + "manifest_sha256": sha256(view / "manifest.json"), + "description": manifest["population"], + "final_recipe_criterion_established": False, + } + + +def annotate(path, view): + report = json.loads(Path(path).read_text()) + report["evaluation_population"] = population(view) + Path(path).write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + build = commands.add_parser("prepare") + build.add_argument("--data-root", type=Path, required=True) + build.add_argument("--output", type=Path, required=True) + build.add_argument("--seed", type=int, default=20260930) + build.add_argument("--site-fraction", type=float, default=0.125) + cache = commands.add_parser("check-cache") + cache.add_argument("--random-package", type=Path, required=True) + cache.add_argument("--candidate-package", type=Path, required=True) + cache.add_argument("--cached-context", type=Path, required=True) + cache.add_argument("--current-context", type=Path, required=True) + cache.add_argument("--task", choices=["awf", "lfmc"], required=True) + probe = commands.add_parser( + "probe", help="Unchanged probe grids with explicitly labelled screening reports" + ) + probe.add_argument("--view", type=Path, required=True) + probe.add_argument("--features", type=Path, required=True) + probe.add_argument("--task", choices=["awf", "lfmc"], required=True) + probe.add_argument("--output", type=Path, required=True) + probe.add_argument("--validation-predictions", type=Path, required=True) + compare = commands.add_parser( + "compare", help="Existing paired bootstrap on the same screening view" + ) + compare.add_argument("--view", type=Path, required=True) + compare.add_argument("--data-root", type=Path, required=True) + compare.add_argument("--pairs", nargs="+", required=True) + compare.add_argument("--output", type=Path, required=True) + compare.add_argument( + "--raw-baseline", help="Optional raw-feature report name; reported separately" + ) + args = parser.parse_args() + if args.command == "prepare": + manifest = prepare(args.data_root, args.output, args.seed, args.site_fraction) + print( + json.dumps( + { + "view": str(args.output.resolve()), + "manifest_sha256": sha256(args.output / "manifest.json"), + "tasks": { + task: { + "rows": info["rows"], + "input_sha256": info["input_sha256"], + "selected_sites": ( + len(info["selected_sites"]) + if info["selected_sites"] is not None + else None + ), + } + for task, info in manifest["tasks"].items() + }, + }, + indent=2, + ) + ) + elif args.command == "check-cache": + print( + json.dumps( + check_cache( + args.random_package, + args.candidate_package, + json.loads(args.cached_context.read_text()), + json.loads(args.current_context.read_text()), + args.task, + ), + indent=2, + ) + ) + else: + population(args.view) + here = Path(__file__).resolve().parent + track = here.parent + if args.command == "probe": + info = json.loads((args.view / "manifest.json").read_text())["tasks"][ + args.task + ] + labels = args.view / args.task / "labels.json" + if sha256(labels) != info["labels_sha256"]: + raise ValueError("Fixed screening labels changed") + command = [ + sys.executable, + str( + here / "probes.py" + if (here / "probes.py").is_file() + else track / "environment/evaluation/probes.py" + ), + "--features", + str(args.features), + "--labels", + str(labels), + "--task", + args.task, + "--validation-predictions", + str(args.validation_predictions), + "--output", + str(args.output), + ] + else: + if (args.data_root / "eval").resolve() != args.view.resolve(): + raise ValueError( + "Comparison data root must point to the fixed screening view" + ) + command = [ + sys.executable, + str(here / "compare_seeds.py"), + "--data-root", + str(args.data_root), + "--pairs", + *args.pairs, + "--output", + str(args.output), + ] + if args.raw_baseline: + command.extend(["--raw-baseline", args.raw_baseline]) + subprocess.run(command, check=True, stdout=subprocess.DEVNULL) + print(json.dumps(annotate(args.output, args.view), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/36/36d5b5042944631cace845abc1d7b9177eac21c1c456eb98c9b93a7de3573d8d/cellscore.py b/reproduction/files/36/36d5b5042944631cace845abc1d7b9177eac21c1c456eb98c9b93a7de3573d8d/cellscore.py new file mode 100644 index 0000000000000000000000000000000000000000..9900edc32bd17753c7805e08751f7e4ae0203f2d --- /dev/null +++ b/reproduction/files/36/36d5b5042944631cace845abc1d7b9177eac21c1c456eb98c9b93a7de3573d8d/cellscore.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 +"""Single scoring code path for development (LOCO dev splits) and the isolated verifier. + +Wraps the pinned official `cell-eval` (0.8.2). One call scores one context: + + report = score_context(predictions, basal, responses, requests, outdir, subsets=..., baseline=...) + +Both prediction and ground truth are put on log1p(CP10k) here, then cell-eval computes the +Generalist panel; every metric is normalised against the no-effect baseline (basal cells +resampled per request) with cell-eval's own `score_agg_metrics` rule: + higher-is-better metrics: (m - m_base) / (1 - m_base); error metrics: 1 - m / m_base; +clipped at 0, NaN -> 0. The context score is the mean of the normalised panel. + +Usage (dev): python cellscore.py --predictions P.h5ad --basal B.h5ad --responses R.h5ad \ + --requests requests.jsonl --outdir OUT [--subsets subsets.json] +""" + +from __future__ import annotations + +import argparse +import hashlib +import importlib.metadata +import json +import logging +import os +from pathlib import Path + +import anndata as ad +import numpy as np +import pandas as pd +import polars as pl +from scipy import sparse + +CONTROL = "non-targeting" +PERT_COL = "target_gene" + +# The Generalist panel: DES, PDS, MAE plus the four extra Generalist metrics of VCC 2025. +PANEL = { + "des": "overlap_at_N", + "pds": "discrimination_score_l1", + "mae": "mae", + "pearson_delta": "pearson_delta", + "spearman_lfc": "de_spearman_lfc_sig", + "auprc_de": "pr_auc", + "spearman_effect": "de_spearman_sig", +} +PER_PERT_METRICS = ["overlap_at_N", "discrimination_score_l1", "mae", "pearson_delta", "de_spearman_lfc_sig", "pr_auc"] +GLOBAL_METRICS = ["de_spearman_sig"] +ERROR_METRICS = {"mae"} +# cell-eval "full" minus the metrics that are not in the panel and dominate runtime +# (e-distance / clustering need all pairwise cell distances against 10k controls per target) +SKIP_METRICS = ["pearson_edistance", "clustering_agreement", "discrimination_score_l2", "discrimination_score_cosine", + "mse", "mse_delta", "mae_delta", "overlap_at_50", "overlap_at_100", "overlap_at_200", "overlap_at_500", + "precision_at_50", "precision_at_100", "precision_at_200", "precision_at_500"] + + +def cell_eval_version() -> str: + return importlib.metadata.version("cell-eval") + + +def read_requests(path: Path) -> list[dict]: + rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()] + ids = [r["request_id"] for r in rows] + if len(set(ids)) != len(ids): + raise ValueError("duplicate request_id") + return rows + + +def sha256(path: Path) -> str: + h = hashlib.sha256() + with Path(path).open("rb") as fh: + for chunk in iter(lambda: fh.read(1 << 24), b""): + h.update(chunk) + return h.hexdigest() + + +def normlog(X) -> sparse.csr_matrix: + X = sparse.csr_matrix(X, dtype=np.float32) + totals = np.asarray(X.sum(axis=1)).ravel() + totals[totals == 0] = 1.0 + Y = sparse.diags((1e4 / totals).astype(np.float32)) @ X + Y.data = np.log1p(Y.data) + return Y.tocsr() + + +def _check_matrix(adata: ad.AnnData, name: str) -> None: + data = adata.X.data if sparse.issparse(adata.X) else np.asarray(adata.X) + if not np.isfinite(data).all() or (data < 0).any(): + raise ValueError(f"{name}: negative or non-finite values") + + +def assemble_prediction(pred: ad.AnnData, basal: ad.AnnData, requests: list[dict], keep: set[str] | None = None) -> ad.AnnData: + """Prediction cells + the basal cells as `non-targeting`, on log1p(CP10k).""" + if list(map(str, pred.var_names)) != list(map(str, basal.var_names)): + raise ValueError("prediction genes/order differ from basal input") + target_of = {r["request_id"]: r["perturbation"]["target"] for r in requests} + rid = pred.obs["request_id"].astype(str) + if set(rid) != set(target_of): + raise ValueError("prediction request_ids differ from requests.jsonl") + counts = rid.value_counts().to_dict() + for r in requests: + if counts.get(r["request_id"], 0) != r["n_cells"]: + raise ValueError(f"request {r['request_id']}: expected {r['n_cells']} cells, got {counts.get(r['request_id'], 0)}") + _check_matrix(pred, "predictions"); _check_matrix(basal, "basal") + targets = rid.map(target_of).astype(str) + mask = np.ones(pred.n_obs, dtype=bool) if keep is None else rid.isin(keep).to_numpy() + p = ad.AnnData(X=normlog(pred.X[mask]), obs=pd.DataFrame({PERT_COL: targets.to_numpy()[mask]}, + index=[f"p{i}" for i in range(int(mask.sum()))]), + var=pd.DataFrame(index=basal.var_names.astype(str))) + b = ad.AnnData(X=normlog(basal.X), obs=pd.DataFrame({PERT_COL: CONTROL}, index=[f"c{i}" for i in range(basal.n_obs)]), + var=pd.DataFrame(index=basal.var_names.astype(str))) + out = ad.concat([p, b], join="inner") + out.obs[PERT_COL] = out.obs[PERT_COL].astype(str) + out.var_names = out.var_names.astype(str) + return out + + +def assemble_real(responses: ad.AnnData, basal: ad.AnnData, requests: list[dict], keep: set[str] | None = None) -> ad.AnnData: + if list(map(str, responses.var_names)) != list(map(str, basal.var_names)): + raise ValueError("responses genes/order differ from basal") + targets = {r["perturbation"]["target"] for r in requests if keep is None or r["request_id"] in keep} + mask = responses.obs[PERT_COL].astype(str).isin(targets).to_numpy() + r = ad.AnnData(X=normlog(responses.X[mask]), + obs=pd.DataFrame({PERT_COL: responses.obs[PERT_COL].astype(str).to_numpy()[mask]}, + index=[f"r{i}" for i in range(int(mask.sum()))]), + var=pd.DataFrame(index=basal.var_names.astype(str))) + b = ad.AnnData(X=normlog(basal.X), obs=pd.DataFrame({PERT_COL: CONTROL}, index=[f"c{i}" for i in range(basal.n_obs)]), + var=pd.DataFrame(index=basal.var_names.astype(str))) + out = ad.concat([r, b], join="inner") + out.obs[PERT_COL] = out.obs[PERT_COL].astype(str) + missing = targets - set(out.obs[PERT_COL]) + if missing: + raise ValueError(f"responses lack targets: {sorted(missing)[:5]}...") + return out + + +def noeffect_prediction(basal: ad.AnnData, requests: list[dict]) -> ad.AnnData: + """B0: resample basal cells unchanged, `n_cells` per request, seeded by the request.""" + blocks, ids = [], [] + for r in requests: + rng = np.random.default_rng(int(r.get("seed", 0))) + idx = rng.choice(basal.n_obs, size=int(r["n_cells"]), replace=basal.n_obs < int(r["n_cells"])) + blocks.append(sparse.csr_matrix(basal.X[idx])) + ids.extend([r["request_id"]] * len(idx)) + X = sparse.vstack(blocks).tocsr() + obs = pd.DataFrame({"request_id": ids, PERT_COL: [r["perturbation"]["target"] for r in requests for _ in range(int(r["n_cells"]))]}, + index=[f"n{i}" for i in range(len(ids))]) + return ad.AnnData(X=X, obs=obs, var=pd.DataFrame(index=basal.var_names.astype(str))) + + +def run_cell_eval(pred: ad.AnnData, real: ad.AnnData, outdir: Path, threads: int, prefix: str, + de_real: Path | None = None) -> tuple[pl.DataFrame, pl.DataFrame]: + """de_real: optional cached real-side DE table (cell-eval's `_real_de.csv`); it depends + only on the ground truth and control cells, so the grader may reuse it across submissions.""" + from cell_eval import MetricsEvaluator + outdir.mkdir(parents=True, exist_ok=True) + evaluator = MetricsEvaluator(adata_pred=pred, adata_real=real, control_pert=CONTROL, pert_col=PERT_COL, + num_threads=threads, outdir=str(outdir), prefix=prefix, allow_discrete=False, + de_real=str(de_real) if de_real and Path(de_real).exists() else None) + results, agg = evaluator.compute(profile="full", skip_metrics=SKIP_METRICS, write_csv=True, basename="results.csv") + return results, agg + + +def _mean_over(results: pl.DataFrame, perts: set[str] | None) -> dict[str, float]: + df = results.to_pandas() + if perts is not None: + df = df[df["perturbation"].isin(perts)] + out = {} + for m in PER_PERT_METRICS: + out[m] = float(np.nanmean(df[m].to_numpy(dtype=float))) if m in df else float("nan") + return out + + +def _global(agg: pl.DataFrame) -> dict[str, float]: + df = agg.to_pandas().set_index("statistic") + return {m: float(df.loc["mean", m]) if m in df.columns else float("nan") for m in GLOBAL_METRICS} + + +def normalise(user: dict[str, float], base: dict[str, float]) -> dict[str, float]: + out = {} + for m, u in user.items(): + b = base.get(m, float("nan")) + if m in ERROR_METRICS: + v = 1.0 - (u / b) if b else float("nan") + else: + v = (u - b) / (1.0 - b) if (1.0 - b) != 0 else float("nan") + out[m] = float(np.clip(0.0 if not np.isfinite(v) else v, 0.0, None)) + return out + + +def summarise(user_results: pl.DataFrame, user_agg: pl.DataFrame, base_results: pl.DataFrame, base_agg: pl.DataFrame, + perts: set[str] | None) -> dict: + """Full-run summary (perts=None): all seven panel metrics. Group summary (perts given): only the + per-perturbation metrics, averaged over the group — the global metric (Spearman of effect size + across targets) is a property of the whole run and would leak into every group.""" + if perts is None: + raw_u = {**_mean_over(user_results, None), **_global(user_agg)} + raw_b = {**_mean_over(base_results, None), **_global(base_agg)} + panel = PANEL + else: + raw_u = _mean_over(user_results, perts) + raw_b = _mean_over(base_results, perts) + panel = {k: v for k, v in PANEL.items() if v in PER_PERT_METRICS} + norm = normalise(raw_u, raw_b) + panel_norm = {k: norm[v] for k, v in panel.items()} + return {"raw": {k: raw_u[v] for k, v in panel.items()}, "baseline_raw": {k: raw_b[v] for k, v in panel.items()}, + "normalised": panel_norm, "score": float(np.mean(list(panel_norm.values()))), + "metrics_in_score": list(panel), + "n_perturbations": int(user_results.select("perturbation").n_unique()) if perts is None else len(perts)} + + +def score_context(predictions: Path, basal: Path, responses: Path, requests_path: Path, outdir: Path, + subsets: dict[str, list[str]] | None = None, groups: dict[str, dict[str, str]] | None = None, + threads: int | None = None, baseline_dir: Path | None = None) -> dict: + """subsets: name -> request_ids scored as a self-contained cell-eval run (e.g. leaderboard/final). + groups: name -> {request_id: label}; per-label means of per-perturbation metrics from the full run.""" + threads = threads or max(1, len(os.sched_getaffinity(0)) - 1) + outdir = Path(outdir); outdir.mkdir(parents=True, exist_ok=True) + requests = read_requests(requests_path) + pred = ad.read_h5ad(predictions); bas = ad.read_h5ad(basal); resp = ad.read_h5ad(responses) + target_of = {r["request_id"]: r["perturbation"]["target"] for r in requests} + base_pred = noeffect_prediction(bas, requests) + + def one(keep: set[str] | None, tag: str): + cache = baseline_dir / tag if baseline_dir else None + de_real = cache / "real_de.csv" if cache else None + u_res, u_agg = run_cell_eval(assemble_prediction(pred, bas, requests, keep), assemble_real(resp, bas, requests, keep), + outdir / tag / "user", threads, tag, de_real) + if cache and (cache / "results.csv").exists() and (cache / "agg_results.csv").exists(): + b_res, b_agg = pl.read_csv(cache / "results.csv"), pl.read_csv(cache / "agg_results.csv") + else: + b_res, b_agg = run_cell_eval(assemble_prediction(base_pred, bas, requests, keep), assemble_real(resp, bas, requests, keep), + outdir / tag / "noeffect", threads, tag, de_real) + return u_res, u_agg, b_res, b_agg + + report = {"cell_eval_version": cell_eval_version(), "panel": PANEL, "subsets": {}, "groups": {}} + u_res, u_agg, b_res, b_agg = one(None, "all") + report["all"] = summarise(u_res, u_agg, b_res, b_agg, None) + for name, ids in (subsets or {}).items(): + keep = set(ids) + s_res, s_agg, sb_res, sb_agg = one(keep, name) + report["subsets"][name] = summarise(s_res, s_agg, sb_res, sb_agg, None) + for gname, labels in (groups or {}).items(): + report["groups"][gname] = {} + for label in sorted(set(labels.values())): + perts = {target_of[rid] for rid, lab in labels.items() if lab == label} + report["groups"][gname][label] = summarise(u_res, u_agg, b_res, b_agg, perts) + per_pert = u_res.to_pandas() + per_pert.to_csv(outdir / "per_perturbation.csv", index=False) + (outdir / "report.json").write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--predictions", required=True, type=Path) + ap.add_argument("--basal", required=True, type=Path) + ap.add_argument("--responses", required=True, type=Path) + ap.add_argument("--requests", required=True, type=Path) + ap.add_argument("--outdir", required=True, type=Path) + ap.add_argument("--subsets", type=Path, help="json: name -> [request_id]") + ap.add_argument("--groups", type=Path, help="json: name -> {request_id: label}") + ap.add_argument("--baseline-dir", type=Path) + ap.add_argument("--threads", type=int) + a = ap.parse_args(argv) + logging.basicConfig(level=logging.WARNING) + subsets = json.loads(a.subsets.read_text()) if a.subsets else None + groups = json.loads(a.groups.read_text()) if a.groups else None + report = score_context(a.predictions, a.basal, a.responses, a.requests, a.outdir, subsets, groups, a.threads, a.baseline_dir) + print(json.dumps({"score": report["all"]["score"], "normalised": report["all"]["normalised"]}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/38/3871d04d5f1cea47d8878cb439001f4605e58b98b65e1207e6f3bb2245eb1d40/run_maia.py b/reproduction/files/38/3871d04d5f1cea47d8878cb439001f4605e58b98b65e1207e6f3bb2245eb1d40/run_maia.py new file mode 100644 index 0000000000000000000000000000000000000000..292db03163741c616ea6dbaea20de6d363261498 --- /dev/null +++ b/reproduction/files/38/3871d04d5f1cea47d8878cb439001f4605e58b98b65e1207e6f3bb2245eb1d40/run_maia.py @@ -0,0 +1,136 @@ +"""Native MAIA launcher and trusted episode worker; no solver/reward substitutes.""" + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +from evaluate import preflight, write_json +from protocol import InfrastructureError, Policy, PolicyError, replay_episode +from native_settings import apply_settings, with_episode_limit + + +def check_native_cache(case, data): + # Native MAIA gives this legacy cache precedence over local_fallback_dir. + # Never silently use another resource version left in a base image. + cached = Path.home() / ".cache" / "maiagym" / case["environment"] + expected = (data / "environments" / case["environment"]).resolve() + if cached.exists() and cached.resolve() != expected: + raise InfrastructureError(f"Legacy MAIA cache would shadow pinned data: {cached}") + + +def make_env(case, data): + import numpy as np + import hydrogym.maia as maia + + check_native_cache(case, data) + env = maia.from_hf(case["environment"], use_clean_cache=False, + local_fallback_dir=str(data / "environments"), **case["env_kwargs"]) + if Path(env.env_data_path).resolve() != (data / "environments" / case["environment"]).resolve(): + raise InfrastructureError("Native environment loaded unpinned cached resources") + if int(np.prod(env.observation_space.shape)) != case["observation_size"] or int(np.prod(env.action_space.shape)) != case["action_size"]: + raise InfrastructureError("Native spaces differ from the reviewed release") + # Apply organizer-reviewed paper settings equally for training and replay. + # Never mutate the read-only source YAML or infer settings from policy files. + env.reviewed_protocol = apply_settings(env, case) + return with_episode_limit(env, case) + + +def evaluate_worker(case, suite, data, submission, output): + import numpy as np + + env = make_env(case, data) + + class Adapter: + observation_space = env.observation_space + action_space = env.action_space + + def reset(self, seed): + return env.reset(seed=seed) + + def step(self, action): + obs, reward, terminated, truncated, info = env.step( + np.asarray(action, dtype=env.action_space.dtype).reshape(env.action_space.shape)) + if np.asarray(reward).ndim != 0: + raise InfrastructureError("Native multi-agent/vector reward needs an explicitly reviewed adapter") + return obs, float(reward), terminated, truncated, info + + policy = None + result = {"status": "ok", "episodes": [], "native_protocol": env.reviewed_protocol} + try: + policy = Policy(submission, output.with_suffix(".policy.log"), suite["policy_timeout_sec"]) + for seed in case["seeds"]: + result["episodes"].append(replay_episode(Adapter(), policy, case, seed)) + policy.close() + policy = None + except PolicyError as error: + result = {"status": "policy_error", "error": str(error)} + finally: + if policy is not None: + policy.abort() + env.close() + write_json(output, result) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=["evaluate", "train"]) + parser.add_argument("--data", type=Path, default=Path("/data")) + parser.add_argument("--case", required=True) + parser.add_argument("--submission", type=Path, default=Path("/workspace/submission")) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--steps", type=int, default=100000) + parser.add_argument("--resume", type=Path, default=Path("/workspace/research/shared-ppo.zip")) + parser.add_argument("--worker", action="store_true", help=argparse.SUPPRESS) + args = parser.parse_args() + args.data, args.output = args.data.resolve(), args.output.resolve() + args.submission, args.resume = args.submission.resolve(), args.resume.resolve() + # Training and native replay depend on fixed physics, not on a learned + # reference already having achieved its target. The outer grader checks + # score anchors separately when a normalized aggregate is requested. + suite = preflight(args.data, require_reference=False) + case = next((c for c in suite["cases"] if c["id"] == args.case), None) + if case is None: + parser.error("Case is not in the fixed release") + if args.steps <= 0: + parser.error("--steps must be positive") + if args.worker: + if args.mode == "evaluate": + evaluate_worker(case, suite, args.data, args.submission, args.output) + else: + # The editable training code is not imported by the verifier. + sys.path.insert(0, "/workspace/baseline/starter") + from train import train + train(make_env(case, args.data), suite, case, args.steps, args.resume, args.submission) + return + args.output.parent.mkdir(parents=True, exist_ok=True) + # Keep solver logs/restarts beside the diagnostic output, not in source data. + scratch = Path(tempfile.mkdtemp(prefix=f"{case['id']}-", dir=args.output.parent)) + check_native_cache(case, args.data) + # Upstream snapshot_download omits revision. A fresh, offline Hub cache + # forces its explicit local fallback instead of resolving a cached main. + os.environ["HF_HUB_CACHE"] = str(scratch / "hf-cache") + os.environ["HF_HUB_OFFLINE"] = "1" + from hydrogym.maia.workspace import prepare_maia_workspace + + work, properties = prepare_maia_workspace( + case["environment"], work_dir=str(scratch), use_clean_cache=False, + local_fallback_dir=str(args.data / "environments")) + solver = ([sys.executable, str(Path(__file__).resolve().with_name("maia_gpu_rank.py"))] + if case["solver_processes"] > 1 else ["maia"]) + command = ["mpirun", "--bind-to", "none", "-np", "1", sys.executable, str(Path(__file__).resolve()), + args.mode, "--worker", "--data", str(args.data), "--case", args.case, + "--submission", str(args.submission), "--output", str(args.output), + "--steps", str(args.steps), "--resume", str(args.resume), + ":", "-np", str(case["solver_processes"]), *solver, properties, "--silent"] + environment = dict(os.environ, HF_HUB_OFFLINE="1", PYTHONDONTWRITEBYTECODE="1", + OMPI_ALLOW_RUN_AS_ROOT="1", OMPI_ALLOW_RUN_AS_ROOT_CONFIRM="1", + OMPI_MCA_coll_hcoll_enable="0") + subprocess.run(command, cwd=work, env=environment, check=True) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/39/396baecb8a37007db119c04483131a6fd884c9ee2ef4dc47805e7fc53c074a31/maia_gpu_rank.py b/reproduction/files/39/396baecb8a37007db119c04483131a6fd884c9ee2ef4dc47805e7fc53c074a31/maia_gpu_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..ee231a461084e38b1397ecc20bfc1b7c8bde37f9 --- /dev/null +++ b/reproduction/files/39/396baecb8a37007db119c04483131a6fd884c9ee2ef4dc47805e7fc53c074a31/maia_gpu_rank.py @@ -0,0 +1,62 @@ +"""One explicit CUDA device per native MAIA solver rank (Python is rank zero).""" +import ctypes +import json +import os +from pathlib import Path +import subprocess +import sys +import uuid + + +def cuda_uuids(): + driver=ctypes.CDLL('libcuda.so.1') + def check(code): + if code: + raise RuntimeError(f'CUDA device enumeration failed: {code}') + check(driver.cuInit(0)) + count=ctypes.c_int() + check(driver.cuDeviceGetCount(ctypes.byref(count))) + result=[] + for index in range(count.value): + device=ctypes.c_int() + raw=(ctypes.c_ubyte*16)() + check(driver.cuDeviceGet(ctypes.byref(device),index)) + check(driver.cuDeviceGetUuid(ctypes.byref(raw),device)) + result.append('GPU-'+str(uuid.UUID(bytes=bytes(raw)))) + return result + + +def select_device(rank,devices): + if (type(rank) is not int or not 1<=rank<=len(devices) + or len(set(devices))!=len(devices)): + raise ValueError('Need one distinct visible GPU for every MAIA solver rank') + return devices[rank-1] + + +def main(): + if sys.argv[1:]==['--list-gpus']: + print(json.dumps(cuda_uuids())) + return + rank=int(os.environ['OMPI_COMM_WORLD_RANK']) + if rank==0 and sys.argv[1:]==['--binding-check']: + return + # A fresh child reads the caller's actual CUDA visibility/order. Do not + # replace a caller's device mask with all GPUs listed by NVML/nvidia-smi. + devices=json.loads(subprocess.check_output( + [sys.executable,str(Path(__file__).resolve()),'--list-gpus'],text=True)) + selected=select_device(rank,devices) + os.environ.update(CUDA_VISIBLE_DEVICES=selected,ACC_DEVICE_NUM='0',NV_ACC_DEVICE_NUM='0') + if cuda_uuids()!=[selected]: + raise RuntimeError('CUDA rank isolation did not take effect') + record={'global_rank':rank,'visible_cuda_devices':1,'cuda_device_uuid':selected, + 'container_pid':os.getpid()} + output=Path(os.environ.get('HYDROGYM_GPU_BINDING_DIR','.')) + (output/f'gpu-binding-rank-{rank}.json').write_text(json.dumps(record,indent=2)+'\n') + print('VERIFIED_MAIA_GPU_BINDING',json.dumps(record),flush=True) + if sys.argv[1:]==['--binding-check']: + return + os.execvp('maia',['maia',*sys.argv[1:]]) + + +if __name__=='__main__': + main() diff --git a/reproduction/files/3a/3a2fb1329596e7c31b8c425bf98eac06cbc69897fc6a6ca0513b5c591ae5c957/test_aggregate.py b/reproduction/files/3a/3a2fb1329596e7c31b8c425bf98eac06cbc69897fc6a6ca0513b5c591ae5c957/test_aggregate.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf59f077051025b3c7e292ba3e4e018d64fad18 --- /dev/null +++ b/reproduction/files/3a/3a2fb1329596e7c31b8c425bf98eac06cbc69897fc6a6ca0513b5c591ae5c957/test_aggregate.py @@ -0,0 +1,146 @@ +from copy import deepcopy + +import pytest + +from aggregate import ( + REFERENCE, + REFERENCE_V2, + SUITE_INPUTS_V2, + aggregate_score, + expanded_score, +) + + +def reference_metrics(): + return { + "discovery": {"F1": REFERENCE["F1"]}, + "phonons": {"avg_freq": {"MAE": REFERENCE["avg_freq_MAE_K"]}}, + "elasticity": { + "bulk_modulus_vrh": {"MAE": REFERENCE["bulk_MAE_GPa"]}, + "shear_modulus_vrh": {"MAE": REFERENCE["shear_MAE_GPa"]}, + }, + } + + +def test_reference_perfect_and_invalid_scores(): + metrics = reference_metrics() + assert aggregate_score(metrics)["score"] == pytest.approx(50) + metrics["discovery"]["F1"] = 1.0 + metrics["phonons"]["avg_freq"]["MAE"] = 0.0 + for value in metrics["elasticity"].values(): + value["MAE"] = 0.0 + assert aggregate_score(metrics)["score"] == 100 + assert aggregate_score(metrics, valid=False)["score"] == 0 + assert aggregate_score({"phonons": metrics["phonons"]})["score"] is None + + +def test_equal_suite_weights_and_monotonic_errors(): + base = reference_metrics() + results = [] + for suite in base: + metrics = deepcopy(base) + if suite == "discovery": + metrics[suite]["F1"] = 1 - 2 * (1 - REFERENCE["F1"]) + else: + for item in metrics[suite].values(): + item["MAE"] *= 2 + result = aggregate_score(metrics) + assert 0 < result["score"] < 50 + results.append(result["score"]) + assert results == pytest.approx([results[0]] * 3) + # Correlated diagnostics and case counts must not silently change weighting. + base["phonons"].update(entropy={"MAE": 1e8}, n=100000) + assert aggregate_score(base)["score"] == pytest.approx(50) + + +@pytest.mark.parametrize("value", [float("nan"), float("inf"), -0.1, None]) +def test_invalid_errors_rejected(value): + metrics = reference_metrics() + metrics["phonons"]["avg_freq"]["MAE"] = value + with pytest.raises(ValueError, match="primary metric"): + aggregate_score(metrics) + + +def test_eight_suite_score_reference_ideal_and_equal_weights(): + assert expanded_score(REFERENCE_V2)["score"] == pytest.approx(50) + perfect = dict.fromkeys(REFERENCE_V2, 0.0) + perfect["discovery_F1"] = 1.0 + assert expanded_score(perfect)["score"] == 100 + scores = [] + for keys in SUITE_INPUTS_V2.values(): + metrics = dict(REFERENCE_V2) + for key in keys: + metrics[key] = ( + 1 - 2 * (1 - metrics[key]) + if key == "discovery_F1" + else 2 * metrics[key] + ) + scores.append(expanded_score(metrics)["score"]) + assert scores == pytest.approx([scores[0]] * 8) + assert 0 < scores[0] < 50 + # Diagnostic metrics and per-suite case counts do not change weights. + assert expanded_score( + {**REFERENCE_V2, "phonon_entropy_MAE": 1e9, "cleavage_n": 100000} + )["score"] == pytest.approx(50) + + +@pytest.mark.parametrize("value", [None, float("nan"), float("inf"), -1, True]) +def test_expanded_score_invalid_or_missing_suite_is_zero(value): + metrics = {**REFERENCE_V2, "kappa_SRME": value} + assert expanded_score(metrics)["score"] == 0 + assert expanded_score({})["score"] == 0 + assert expanded_score(REFERENCE_V2, valid=False)["score"] == 0 + + +def test_expanded_score_grader_consumes_flat_metrics(tmp_path, monkeypatch): + import json + import sys + + import grader + + report = { + "physical": { + "valid": True, + "metrics": { + "discovery": {"F1": 0.856}, + "phonons": {"avg_freq": {"MAE": 18.2}}, + "elasticity": { + "bulk_modulus_vrh": {"MAE": 5.560}, + "shear_modulus_vrh": {"MAE": 7.277}, + }, + }, + }, + "kappa": {"kappa_SRME": 0.455}, + "mof": {"bulk_modulus_MAPE_pct": 26.6}, + "amorphous": {"energy_RelRMSE_pct_mean": 8.780, "force_RelRMSE_pct_mean": 14.8}, + "cleavage": {"cleavage_relMAE_pct": 6.598}, + "neb": {"barrier_MAE_eV": 0.147}, + } + assert expanded_score(grader.flatten(report))["score"] == pytest.approx(50) + + # Exercise the output boundary: keep the aggregate and omit unavailable raw metrics. + sealed, labels, output = (tmp_path / name for name in ("sealed", "labels", "output")) + sealed.mkdir() + snapshot = {"schema": grader.SCHEMA, "runs": [], "predictions": {}, "inputs": {}} + for suite in report: + prediction = sealed / suite + inputs = labels / suite / "inputs" + prediction.mkdir() + inputs.mkdir(parents=True) + (prediction / "run.json").write_text("{}") + snapshot["predictions"][suite] = grader.tree_sha256(prediction) + snapshot["inputs"][suite] = grader.tree_sha256(inputs) + (sealed / "snapshot.json").write_text(json.dumps(snapshot)) + (tmp_path / "READY").write_text(grader.sha256(sealed / "snapshot.json")) + monkeypatch.setattr(grader, "score_physical", lambda *args: report["physical"]) + monkeypatch.setattr(grader, "score_extra", lambda suite, *args: report[suite]) + monkeypatch.setattr(sys, "argv", ["grader", "--sealed", str(sealed), + "--labels", str(labels), "--output", str(output)]) + grader.main() + reward = json.loads((output / "reward.json").read_text()) + assert reward["reward"] == pytest.approx(0.5) + assert reward["crystal_potential_score"] == pytest.approx(50) + assert reward["discovery_F1"] == report["physical"]["metrics"]["discovery"]["F1"] + assert "phonon_entropy_MAE" not in reward + assert all(isinstance(value, (int, float)) for value in reward.values()) + assert json.loads((output / "report.json").read_text())["aggregate"]["score"] == pytest.approx(50) diff --git a/reproduction/files/3c/3c61fb6736b95bc50e66721eb510e8d9a76d0c615f087c408d6720b971c158fd/test_v2.py b/reproduction/files/3c/3c61fb6736b95bc50e66721eb510e8d9a76d0c615f087c408d6720b971c158fd/test_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..35dd4f048536a7341f72c7e2cab37585a713ab67 --- /dev/null +++ b/reproduction/files/3c/3c61fb6736b95bc50e66721eb510e8d9a76d0c615f087c408d6720b971c158fd/test_v2.py @@ -0,0 +1,201 @@ +"""v2 suites: scoring of failures and caps, run binding, submission factory, verifier boundaries.""" +import gzip +import json +from pathlib import Path + +import numpy as np +import pytest + +import score_extra +from common import digest + + +def write(path: Path, value, gz=False): + path.parent.mkdir(parents=True, exist_ok=True) + if gz: + with gzip.open(path, "wt") as f: + json.dump(value, f) + else: + path.write_text(json.dumps(value)) + + +def run_dir(tmp_path, suite, inputs, items): + run = tmp_path / "run" + (run / "items").mkdir(parents=True) + for i, item in enumerate(items): + (run / "items" / f"{i}.json").write_text(json.dumps(item)) + write(run / "run.json", {"suite": suite, "complete": True, + "inputs_manifest_sha256": digest(inputs / "manifest.json")}) + return run + + +def test_neb_errors_are_capped_and_failures_score_the_cap(tmp_path): + refs = tmp_path / "refs" + write(refs / "references.json", [{"id": "a", "barrier_eV": 0.5}, {"id": "b", "barrier_eV": 0.3}, + {"id": "c", "barrier_eV": 0.4}]) + pred = {"a": {"status": "ok", "barrier_eV": 0.6, "converged": True}, + "b": {"status": "ok", "barrier_eV": 40.0, "converged": False}, # diverged NEB + "c": {"status": "failed"}} + out = score_extra.score_neb(pred, refs) + assert out["barrier_MAE_eV"] == pytest.approx((0.1 + 2.0 + 2.0) / 3) + assert out["barrier_MAE_converged_eV"] == pytest.approx(0.1) + assert out["failed"] == 1 and out["converged_frac"] == pytest.approx(1 / 3) + + +def test_failing_never_beats_a_bad_prediction(tmp_path): + refs = tmp_path / "refs" + write(refs / "references.json", [{"id": "m", "B0_GPa": 10.0}]) + worst = score_extra.score_mof({"m": {"status": "ok", "B_GPa": 1000.0}}, refs)["bulk_modulus_MAPE_pct"] + failed = score_extra.score_mof({}, refs)["bulk_modulus_MAPE_pct"] + assert failed >= worst == 200.0 + write(refs / "references.json", [{"id": "s", "cleavage_energy": 0.1}]) + bad = score_extra.score_cleavage({"s": {"status": "ok", "cleavage_energy": 5.0}}, refs) + gone = score_extra.score_cleavage({}, refs) + assert gone["cleavage_relMAE_pct"] >= bad["cleavage_relMAE_pct"] == pytest.approx(200.0) + + +def test_kappa_failures_and_broken_symmetry_score_two(): + ref = {"kappa_tot_avg": [10.0], "mode_kappa_tot_avg": np.ones((2, 3)).tolist(), "init_spg_num": 225, "weights": [1, 1]} + assert score_extra.srme_one(None, ref)[0] == 2.0 + broken = {"status": "ok", "init_spg_num": 225, "final_spg_num": 221, "kappa_tot_rta": [10, 10, 10, 0, 0, 0]} + assert score_extra.srme_one(broken, ref)[0] == 2.0 + exact = {"status": "ok", "init_spg_num": 225, "final_spg_num": 225, + "kappa_tot_rta": [10, 10, 10, 0, 0, 0], "mode_weights": [1, 1], + "mode_kappa_tot_rta": np.tile([1.0, 1.0, 1.0, 0, 0, 0], (2, 3, 1)).tolist()} + assert score_extra.srme_one(exact, ref) == (0.0, 0.0, False) + + +def test_kappa_normalization_and_initial_symmetry_are_reference_owned(): + ref = {"kappa_tot_avg": [10.0], "mode_kappa_tot_avg": np.ones((1, 2, 3)).tolist(), + "init_spg_num": 225, "weights": [1, 1]} + pred = {"status": "ok", "init_spg_num": 225, "final_spg_num": 225, + "kappa_tot_rta": [10, 10, 10, 0, 0, 0], "mode_weights": [1, 1], + "mode_kappa_tot_rta": np.tile([1.5, 1.5, 1.5, 0, 0, 0], (1, 2, 3, 1)).tolist()} + score = score_extra.srme_one(pred, ref) + assert score == pytest.approx((0.15, 0, False)) + pred["mode_weights"] = [1e12, 1e12] + assert score_extra.srme_one(pred, ref) == score + pred.update(init_spg_num=221, final_spg_num=221) + assert score_extra.srme_one(pred, ref)[0] == 2 + + +def test_pool_split_groups_supercells_and_keeps_parents_disjoint(tmp_path, monkeypatch): + import importlib.util + from ase import Atoms + from ase.db import connect + + path = Path(__file__).resolve().parents[1] / "environment/baseline/uma-mixed-replay/prepare_mixed.py" + spec = importlib.util.spec_from_file_location("mixed_selection", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + assert module.composition_key(Atoms("SiO2").symbols) == module.composition_key(Atoms("Si14O28").symbols) + shard = tmp_path / "source/frames.aselmdb" + shard.parent.mkdir() + with connect(shard) as db: + for i, formula in enumerate(("SiO2", "Si14O28")): + db.write(Atoms(formula), data={"sid": str(i), "parent": "same-parent"}) + rows = module.scan(str(shard)) + assert len({row[-1] for row in rows}) == 1 + + class SerialPool: + def __init__(self, *args): pass + def __enter__(self): return self + def __exit__(self, *args): pass + def map(self, func, items, **kwargs): return map(func, items) + + monkeypatch.setattr(module, "ProcessPoolExecutor", SerialPool) + train, dev = module.select(tmp_path, ["source"], 10, 10, 1) + assert sorted(len(x) for x in (train, dev)) == [0, 2] + + +def test_pretraining_workspace_does_not_mount_historical_weights(): + import yaml + + root = Path(__file__).resolve().parents[1] / "environment" + config = yaml.safe_load((root / "docker-compose.yaml").read_text()) + targets = {v["target"] for v in config["services"]["main"]["volumes"]} + assert targets == {"/workspace/data/pool", "/workspace/data/val", + "/workspace/data/baselines/mp-standard", "/workspace/research"} + + +def test_invalid_package_publishes_zero_versioned_score(tmp_path): + import subprocess + import sys + + script = Path(__file__).with_name("main_verifier.py") + output = tmp_path / "output" + subprocess.run([sys.executable, str(script), "--submission", str(tmp_path / "missing"), + "--input", str(tmp_path / "inputs"), "--sealed", str(tmp_path / "sealed"), + "--output", str(output)], check=True) + report = json.loads((output / "report.json").read_text()) + reward = json.loads((output / "reward.json").read_text()) + assert report["aggregate"]["version"] == "crystal-potential-score-v2" + assert reward["reward"] == reward["crystal_potential_score"] == 0 + assert reward["invalid_submission"] is True + # Harbor rejects unavailable metrics serialized as null. + assert all(isinstance(value, (int, float)) and np.isfinite(value) for value in reward.values()) + + +def test_amorphous_relative_rmse_and_missing_structures(tmp_path): + refs = tmp_path / "refs" + rows = [{"id": f"x{i}", "system": "si", "energy_per_atom": float(i), "forces": [[1.0, 0, 0], [-1.0, 0, 0]]} + for i in range(3)] + write(refs / "references.json.gz", rows, gz=True) + perfect = {r["id"]: {"status": "ok", "energy_per_atom": r["energy_per_atom"] + 5, "forces": r["forces"]} + for r in rows} + out = score_extra.score_amorphous(perfect, refs) + assert out["si_energy_RelRMSE_pct"] == pytest.approx(0) and out["si_force_RelRMSE_pct"] == pytest.approx(0) + perfect.pop("x0") + assert score_extra.score_amorphous(perfect, refs)["failed"] == 1 + nothing = score_extra.score_amorphous({}, refs) + assert nothing["si_energy_RelRMSE_pct"] > 150 and nothing["si_force_RelRMSE_pct"] > 150 + + +def test_run_bound_to_its_inputs(tmp_path): + inputs = tmp_path / "inputs" + write(inputs / "manifest.json", {"suite": "neb", "ids": ["a"]}) + refs = tmp_path / "refs" + write(refs / "references.json", [{"id": "a", "barrier_eV": 0.5}]) + run = run_dir(tmp_path, "neb", inputs, [{"id": "a", "status": "ok", "barrier_eV": 0.5, "converged": True}]) + assert score_extra.score("neb", run, inputs, refs)["barrier_MAE_eV"] == 0 + write(inputs / "manifest.json", {"suite": "neb", "ids": ["a", "b"]}) + with pytest.raises(SystemExit): + score_extra.score("neb", run, inputs, refs) + + +def test_submission_factory_and_directory_digest(tmp_path): + from predict import load_calculator + sub = tmp_path / "submission" + sub.mkdir() + (sub / "calculator.py").write_text( + "from ase.calculators.emt import EMT\n" + "def make_calculator(submission_dir, device):\n" + " assert (submission_dir / 'calculator.py').is_file()\n" + " return EMT()\n") + calc = load_calculator("submission", sub, "cpu") + assert type(calc).__name__ == "EMT" + first = digest(sub) + (sub / "weights.bin").write_bytes(b"x") + assert digest(sub) != first + + +def test_verifier_rejects_references_in_untrusted_inputs(tmp_path): + import main_verifier + for suite in main_verifier.SUITES: + (tmp_path / suite / "inputs").mkdir(parents=True) + main_verifier.validate_input(tmp_path) + (tmp_path / "kappa" / "inputs" / "references.json.gz").write_bytes(b"") + with pytest.raises(ValueError): + main_verifier.validate_input(tmp_path) + with pytest.raises(FileNotFoundError): + main_verifier.validate_submission(tmp_path) + + +def test_reward_keys_are_flat_raw_metrics(): + import grader + report = {"physical": {"metrics": {"discovery": {"F1": 0.8}, "elasticity": {"bulk_modulus_vrh": {"MAE": 5.0}}}}, + "kappa": {"kappa_SRME": 0.3}, "neb": {"valid": False}} + reward = grader.flatten(report) + assert reward["discovery_F1"] == 0.8 and reward["bulk_modulus_MAE_GPa"] == 5.0 + assert reward["kappa_SRME"] == 0.3 and reward["neb_barrier_MAE_eV"] is None + assert len(reward) == 15 diff --git a/reproduction/files/3e/3e6d6381f5b3abbd87f17b22c14c77e7d2e54a6544753a8421c1baf6b5cb1b0f/extra.py b/reproduction/files/3e/3e6d6381f5b3abbd87f17b22c14c77e7d2e54a6544753a8421c1baf6b5cb1b0f/extra.py new file mode 100644 index 0000000000000000000000000000000000000000..75668e6e3d8a787bb8d2d7070645a763fd239ee6 --- /dev/null +++ b/reproduction/files/3e/3e6d6381f5b3abbd87f17b22c14c77e7d2e54a6544753a8421c1baf6b5cb1b0f/extra.py @@ -0,0 +1,283 @@ +"""Run the v2 off-equilibrium suites with a submitted calculator (one worker per GPU). + + python extra.py run --suite kappa|mof|amorphous|cleavage|neb --inputs SPLIT_DIR \ + --artifact SUBMISSION_DIR|MODEL.pt [--factory submission|uma] --output OUT_DIR [--gpus 0,1] + +SPLIT_DIR is a `val` (development) or `test` (verifier) directory written by +environment/data/extra_suites.py. Inputs never contain reference values. Each item is written to +OUT_DIR/items/.json; OUT_DIR/run.json binds the inputs manifest, model checksum and completeness. +Protocols: +- kappa: Matbench Discovery phonondb-v1 (FIRE + FrechetCellFilter with FixSymmetry, fmax 1e-4, 300 + steps; FC2/FC3 with 0.01 A displacements; imaginary-mode gate; Wigner RTA at 300 K, phono3py 3.30). +- mof: MOFSimBench (LBFGS + FrechetCellFilter fmax 1e-3, 1000 steps; 11 volumes in +/-4 %; FIRE fmax + 1e-3 at fixed cell; Birch-Murnaghan); the calculator is summed with D3(BJ, PBE, 40 Bohr). +- amorphous: single-point energy per atom and forces on AM26 structures. +- cleavage: single points, E = (E_slab - n_slab / n_bulk * E_bulk) / (2 A). +- neb: relax end points, climbing-image NEB (improved tangent, k = 5, FIRE, fmax 0.1, 300 steps), + barrier = max(E) - min(E). +""" +from __future__ import annotations + +import argparse +import gzip +import hashlib +import json +import multiprocessing as mp +import os +import sys +import time +import traceback +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from common import digest, with_oom_retry # noqa: E402 + +PROTOCOL = "atomistic-extra-suites-v1" + + +def sha256(path: Path) -> str: + d = hashlib.sha256() + with path.open("rb") as f: + while chunk := f.read(1 << 24): + d.update(chunk) + return d.hexdigest() + + +# ------------------------------------------------------------------------------------- items +def items(suite: str, root: Path): + from ase.io import read + if suite == "kappa": + return [(a.info["material_id"], a) for a in read(root / "inputs.extxyz", index=":", format="extxyz")] + if suite == "mof": + files = json.loads((root / "manifest.json").read_text())["files"] + return [(k, root / "structures" / v) for k, v in sorted(files.items())] + if suite == "amorphous": + return [(a.info["id"], a) for a in read(root / "inputs.extxyz", index=":", format="extxyz")] + if suite == "cleavage": + return [(r["id"], r) for r in json.load(gzip.open(root / "inputs.json.gz"))] + if suite == "neb": + ids = json.loads((root / "manifest.json").read_text())["ids"] + return [(i, root / "paths" / f"{i}_init.xyz") for i in ids] + raise ValueError(suite) + + +# ------------------------------------------------------------------------------------- physics +def run_kappa(atoms, calc): + from ase.constraints import FixSymmetry + from ase.filters import FrechetCellFilter + from ase.optimize import FIRE + from moyopy import MoyoDataset + from moyopy.interface import MoyoAdapter + from phono3py.api_phono3py import Phono3py + from phonopy.structure.atoms import PhonopyAtoms + + def spg(a): + return MoyoDataset(MoyoAdapter.from_atoms(a), symprec=1e-5).number + + info = dict(atoms.info) + rec = {"init_spg_num": int(spg(atoms))} + a = atoms.copy(); a.calc = calc + a.set_constraint(FixSymmetry(a, symprec=0.01)) + opt = FIRE(FrechetCellFilter(a, mask=[True, True, True, False, False, False]), logfile=None) + opt.run(fmax=1e-4, steps=300) + a.calc = None; a.constraints = None + rec.update(final_spg_num=int(spg(a)), relax_steps=int(opt.get_number_of_steps())) + ph3 = Phono3py(PhonopyAtoms(a.get_chemical_symbols(), cell=a.cell[:], positions=a.positions), + supercell_matrix=np.asarray(info["fc3_supercell"]), + phonon_supercell_matrix=np.asarray(info["fc2_supercell"]), primitive_matrix="auto", symprec=1e-5) + ph3.mesh_numbers = tuple(info["q_point_mesh"]) + ph3.generate_displacements(distance=0.01, is_plusminus="auto") + ph3.phonon_forces = forces(ph3.phonon_supercells_with_displacements, calc) + ph3.produce_fc2(symmetrize_fc2=True) + ph3.init_phph_interaction(symmetrize_fc3q=False) + ph3.run_phonon_solver() + freqs, _, _ = ph3.get_phonon_data() + f = np.asarray(freqs, dtype=float) + imag = bool(np.all(np.isnan(f)) or np.any(f[0, 3:] < 0) or np.any(f[0, :3] < -0.01) or np.any(f[1:] < 0)) + rec["has_imag_ph_modes"] = imag + if imag or rec["final_spg_num"] != rec["init_spg_num"]: + rec["conductivity_skipped"] = True + return rec + sc = ph3.supercells_with_displacements + present = forces([s for s in sc if s is not None], calc) + full, j = [], 0 + for s in sc: + if s is None: + full.append(np.zeros((len(ph3.supercell), 3))) + else: + full.append(present[j]); j += 1 + ph3.forces = np.asarray(full) + ph3.produce_fc3(symmetrize_fc3r=True) + ph3.init_phph_interaction(symmetrize_fc3q=False) + ph3.run_thermal_conductivity(temperatures=[300.0], is_isotope=True, transport_type="MS-SMM19", boundary_mfp=1e6) + k = ph3.thermal_conductivity + extra, cv = k.get_extra_kappa_output(), np.asarray(k.mode_heat_capacities) + mp_, mc = np.asarray(extra["mode_kappa_P_RTA"][0]), np.asarray(extra["mode_kappa_C"][0]) + with np.errstate(divide="ignore", invalid="ignore"): + c = 2 * ((mc * cv[:, :, :, None, None]) / (cv[:, :, :, None, None] + cv[:, :, None, :, None])).sum(axis=2) + c[np.isnan(c)] = 0 + rec.update(kappa_tot_rta=np.asarray(extra["kappa_TOT_RTA"][0]).tolist(), + mode_weights=np.asarray(k.grid_weights).tolist(), mode_kappa_tot_rta=(c + mp_).tolist()) + return rec + + +def forces(supercells, calc): + from ase import Atoms + out = [] + for s in supercells: + a = Atoms(s.symbols, cell=s.cell, positions=s.positions, pbc=True); a.calc = calc + out.append(np.asarray(a.get_forces(), dtype=float)) + return np.asarray(out) + + +def run_mof(path, calc): + from ase import units + from ase.eos import EquationOfState + from ase.filters import FrechetCellFilter + from ase.io import read + from ase.optimize import FIRE, LBFGS + atoms = read(path); atoms.calc = calc + LBFGS(FrechetCellFilter(atoms), logfile=None).run(fmax=1e-3, steps=1000) + relaxed = atoms.copy(); vols, ens = [], [] + for s in np.linspace(0.96, 1.04, 11) ** (1 / 3): + a = relaxed.copy(); a.calc = calc; a.set_cell(relaxed.get_cell() * s, scale_atoms=True) + FIRE(a, logfile=None).run(fmax=1e-3, steps=1000) + vols.append(float(a.get_volume())); ens.append(float(a.get_potential_energy())) + v0, e0, B = EquationOfState(vols, ens, eos="birchmurnaghan").fit() + return {"B_GPa": float(B / units.GPa), "v0": float(v0), "atoms": len(relaxed), "volumes": vols, "energies": ens} + + +def run_amorphous(atoms, calc): + a = atoms.copy(); a.calc = calc + return {"energy_per_atom": float(a.get_potential_energy() / len(a)), "forces": np.asarray(a.get_forces()).round(6).tolist()} + + +def run_cleavage(row, calc): + from pymatgen.core import Structure + from pymatgen.io.ase import AseAtomsAdaptor + slab = AseAtomsAdaptor.get_atoms(Structure.from_dict(row["slab"])) + bulk = AseAtomsAdaptor.get_atoms(Structure.from_dict(row["bulk"])) + slab.calc = calc; e_slab = float(slab.get_potential_energy()) + bulk.calc = calc; e_bulk = float(bulk.get_potential_energy()) + return {"cleavage_energy": (e_slab - len(slab) / len(bulk) * e_bulk) / (2 * row["area"])} + + +def run_neb(path, calc, steps=300, fmax=0.1): + from ase.io import read + from ase.mep import NEB + from ase.optimize import FIRE + images = [im.copy() for im in read(path, index=":")] + for im in images: + im.calc = calc + FIRE(images[0], logfile=None).run(fmax=0.05, steps=500) + FIRE(images[-1], logfile=None).run(fmax=fmax, steps=steps) + neb = NEB(images, k=5.0, climb=True, method="improvedtangent", allow_shared_calculator=True) + opt = FIRE(neb, logfile=None) + converged = bool(opt.run(fmax=fmax, steps=steps)) + e = np.array([im.get_potential_energy() for im in images]) + return {"barrier_eV": float(e.max() - e.min()), "converged": converged, "neb_steps": int(opt.get_number_of_steps())} + + +RUNNERS = {"kappa": run_kappa, "mof": run_mof, "amorphous": run_amorphous, "cleavage": run_cleavage, "neb": run_neb} + + +def make_calculator(factory, artifact, suite): + sys.path.insert(0, str(HERE)) + import predict + calc = predict.load_calculator(factory, artifact, "cuda") + if suite == "mof": + from ase import units + from ase.calculators.mixing import SumCalculator + from torch_dftd.torch_dftd3_calculator import TorchDFTD3Calculator + calc = SumCalculator([calc, TorchDFTD3Calculator(device="cuda", damping="bj", xc="pbe", cutoff=40.0 * units.Bohr)]) + return calc + + +def cost(suite, item): + """Relative cost used to start the most expensive items first (MOF and NEB have long tails).""" + if suite in ("mof", "neb"): + from ase.io import read + images = read(item, index=":") + return len(images[0]) * len(images) + if suite == "kappa": + return len(item) + return 0 + + +def item_file(root: Path, key: str) -> Path: + return root / "items" / (key.replace("|", "__").replace("/", "_") + ".json") + + +def _worker(gpu, queue, args): + os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) + calc = make_calculator(args.factory, args.artifact, args.suite) + todo = dict(items(args.suite, args.inputs)) + while (key := queue.get()) is not None: + target = item_file(args.output, key) + if target.exists(): + continue + item = todo[key] + t = time.monotonic() + try: + def calculate(): + if hasattr(calc, "reset"): + calc.reset() + return RUNNERS[args.suite](item, calc) + rec = {"id": key, "status": "ok", **with_oom_retry(calculate)} + except Exception as exc: # failures are scored as failures + rec = {"id": key, "status": "failed", "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc()[-1500:]} + rec["seconds"] = time.monotonic() - t + tmp = target.with_name(f".{target.name}.tmp") + tmp.write_text(json.dumps(rec)) + tmp.rename(target) + print(json.dumps({"suite": args.suite, "id": key, "status": rec["status"], "s": round(rec["seconds"], 1)}), flush=True) + + +def run(args): + (args.output / "items").mkdir(parents=True, exist_ok=True) + gpus = [g for g in args.gpus.split(",") if g != ""] + per_gpu = max(1, args.workers_per_gpu) + slots = [g for g in gpus for _ in range(per_gpu)] + ctx = mp.get_context("spawn") + keys = [k for k, _ in sorted(items(args.suite, args.inputs), key=lambda kv: -cost(args.suite, kv[1]))] + queue = ctx.Queue() + for k in keys: + queue.put(k) + for _ in slots: + queue.put(None) + procs = [ctx.Process(target=_worker, args=(g, queue, args)) for g in slots] + for p in procs: + p.start() + for p in procs: + p.join() + queue.cancel_join_thread() # items left by crashed workers must not block exit + done = {k: json.loads(item_file(args.output, k).read_text()) for k in keys if item_file(args.output, k).exists()} + run_info = {"protocol": PROTOCOL, "suite": args.suite, "inputs_manifest_sha256": sha256(args.inputs / "manifest.json"), + "checkpoint_sha256": digest(args.artifact) if args.artifact.exists() else None, + "factory": args.factory, "items": len(keys), "completed": len(done), + "failed": sum(r["status"] != "ok" for r in done.values()), "complete": len(done) == len(keys)} + (args.output / "run.json").write_text(json.dumps(run_info, indent=1)) + print(json.dumps(run_info)) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + sub = ap.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("run") + r.add_argument("--suite", choices=sorted(RUNNERS), required=True) + r.add_argument("--inputs", type=Path, required=True) + r.add_argument("--artifact", type=Path, required=True) + r.add_argument("--factory", default="uma") + r.add_argument("--output", type=Path, required=True) + r.add_argument("--gpus", default=os.environ.get("CUDA_VISIBLE_DEVICES", "0")) + r.add_argument("--workers-per-gpu", type=int, default=1) + a = ap.parse_args() + run(a) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/40/4070f770178c08813bb36003fc5ed3848c2bd2d8266c12e83d83193e30dd3c00/run_unit_tests.sh b/reproduction/files/40/4070f770178c08813bb36003fc5ed3848c2bd2d8266c12e83d83193e30dd3c00/run_unit_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..dac857319a0d36904903f86e9da9940a863a472b --- /dev/null +++ b/reproduction/files/40/4070f770178c08813bb36003fc5ed3848c2bd2d8266c12e83d83193e30dd3c00/run_unit_tests.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +# The tests need Python >= 3.11 (tomllib); the images' default python3 is 3.10, the GLACIER runtime is 3.11. +PY=${PYTHON:-python3} +"$PY" -c 'import tomllib' 2>/dev/null || PY=/opt/glacier/bin/python +exec "$PY" -m unittest discover -v -s tests -p 'test_*.py' diff --git a/reproduction/files/41/41194ab9fbfbd47d9cecf28f0b7536a156f396783ffef6e2db9df0a505133bf5/splits.py b/reproduction/files/41/41194ab9fbfbd47d9cecf28f0b7536a156f396783ffef6e2db9df0a505133bf5/splits.py new file mode 100644 index 0000000000000000000000000000000000000000..4454f3ecf307ba00d06d0438e495f80fd8582179 --- /dev/null +++ b/reproduction/files/41/41194ab9fbfbd47d9cecf28f0b7536a156f396783ffef6e2db9df0a505133bf5/splits.py @@ -0,0 +1,344 @@ +"""Freeze composition-grouped validation/test IDs across the three public suites. + +Only identifiers, compositions and geometry sizes enter assignment. Public targets +remain evaluation data; this is an AI4Sci split, not an upstream leaderboard split. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from concurrent.futures import ThreadPoolExecutor +import csv +from fractions import Fraction +import gzip +import hashlib +import json +from math import gcd, lcm +from pathlib import Path + +import numpy as np +from pymatgen.core import Composition + +from common import decode_atoms, digest, read_rows, write_json + +VERSION = "atomistic-eval-split-v1" +DEFAULT_SPLITS = Path(__file__).resolve().parents[2] / ".data/splits/v1" +SUITES = ("discovery", "phonons", "elasticity") +PHONON_GEOMETRIES = { + "url": "https://huggingface.co/datasets/materialyze/matcalc-bench/resolve/54b2b336cccca933f51c82f47f2dbeed7bab054f/alexandria-pbe-phonon-2025.3.json.gz", + "sha256": "edbd5e2e638197f2c3863e990a51ca27d4c151f9f67b95f55348006a8f8e36b8", +} + + +def composition_key(value): + """Canonical integer element ratios, including dimers and supercells.""" + amounts = Composition(value).get_el_amt_dict() + fractions = { + k: Fraction(str(v)).limit_denominator(1000000) for k, v in amounts.items() + } + denominator = lcm(*(x.denominator for x in fractions.values())) + integers = {k: int(v * denominator) for k, v in fractions.items()} + factor = gcd(*integers.values()) + if not integers or factor <= 0 or any(x <= 0 for x in integers.values()): + raise ValueError("Invalid composition") + return "|".join(f"{k}:{integers[k] // factor}" for k in sorted(integers)) + + +def atoms_key(data): + return composition_key(Counter(decode_atoms(data).get_chemical_symbols())) + + +def stable_hash(value, seed=VERSION): + return hashlib.sha256(f"{seed}:{value}".encode()).hexdigest() + + +def source_inventory(cache): + # Imported here to keep manifest readers independent of Phonopy/downloads. + from prepare import CATALOG, MDR_ROOT, download, phonon_input + + catalog = json.loads(CATALOG.read_text()) + provenance = {} + + def source(name, item=None): + item = catalog[name] if item is None else item + path = download(item["url"], cache / name, item["sha256"]) + provenance[name] = {**item, "bytes": path.stat().st_size} + return path + + with gzip.open(source("summary.csv.gz"), "rt") as stream: + wbm = list(csv.DictReader(stream)) + with source("mdr.csv").open() as stream: + mdr = list(csv.DictReader(stream)) + with gzip.open(source("elastic.json.gz"), "rt") as stream: + elastic = json.load(stream) + with gzip.open( + source("phonon-structures.json.gz", PHONON_GEOMETRIES), "rt" + ) as stream: + mirrored = json.load(stream) + phonon_formulas = {} + for row in mirrored: + if row["mp_id"] in phonon_formulas: + raise ValueError("Duplicate MP ID in phonon geometry mirror") + # Derive composition from occupancies, not the formatting of formula strings. + amounts = Counter() + for site in row["structure"]["sites"]: + for species in site["species"]: + amounts[species["element"]] += species["occu"] + phonon_formulas[row["mp_id"]] = composition_key(amounts) + + missing = sorted({r["mp_id"] for r in mdr} - phonon_formulas.keys()) + + def missing_formula(mp_id): + name = f"mdr/{mp_id}.yaml.bz2" + url = MDR_ROOT + f"pbe/{mp_id}.yaml.bz2" + path = download(url, cache / name) + return ( + mp_id, + atoms_key(phonon_input(path)["atoms"]), + name, + {"url": url, "sha256": digest(path), "bytes": path.stat().st_size}, + ) + + # The geometry mirror has 9,865/9,958 cases; retain the remaining 93 by + # reading their original PBE YAMLs. Never silently shrink the evaluation pool. + with ThreadPoolExecutor(max_workers=8) as pool: + for mp_id, key, name, entry in pool.map(missing_formula, missing): + phonon_formulas[mp_id] = key + provenance[name] = entry + + records = [] + for suite, rows in (("discovery", wbm), ("phonons", mdr), ("elasticity", elastic)): + for row in rows: + material_id = row["material_id"] if suite == "discovery" else row["mp_id"] + key = ( + phonon_formulas[material_id] + if suite == "phonons" + else composition_key(row["formula"]) + ) + n_sites = ( + int(float(row["n_sites"])) + if suite == "discovery" + else int(row["nsites"]) + if suite == "phonons" + else len(row["structure"]["sites"]) + ) + records.append( + { + "id": f"{suite}/{material_id}", + "suite": suite, + "material_id": material_id, + "composition": key, + "n_sites": n_sites, + } + ) + if len({r["id"] for r in records}) != len(records): + raise ValueError("Duplicate evaluation case") + return sorted(records, key=lambda r: r["id"]), provenance + + +def collect_exposure(panel_paths, adaptation_paths): + """Store only metadata needed to keep previously used groups out of test.""" + groups, ids, sources = set(), set(), [] + for kind, paths in ( + ("prior_evaluation", panel_paths), + ("prior_adaptation", adaptation_paths), + ): + for path in paths: + rows = read_rows(path) + sources.append( + { + "kind": kind, + "name": path.name, + "sha256": digest(path), + "rows": len(rows), + } + ) + for row in rows: + groups.add(atoms_key(row["atoms"])) + value = ( + row["id"].split("/")[-1] + if kind == "prior_evaluation" + else row.get("parent", "") + ) + if value: + ids.add(value) + return { + "sources": sources, + "compositions": sorted(groups), + "material_ids": sorted(ids), + } + + +def assign(records, exposure, val_fraction=0.2, seed=VERSION): + if not 0 < val_fraction < 1: + raise ValueError("Validation fraction must be between zero and one") + if not records or len({r["id"] for r in records}) != len(records): + raise ValueError("Empty or duplicate evaluation inventory") + # Union composition groups when an MP ID has different stoichiometric metadata + # across releases. This guarantees shared material IDs never cross splits. + parent = {r["composition"]: r["composition"] for r in records} + + def root(key): + while parent[key] != key: + parent[key] = parent[parent[key]] + key = parent[key] + return key + + by_id = {} + for row in sorted(records, key=lambda r: r["id"]): + key = row["composition"] + previous = by_id.setdefault(row["material_id"], key) + a, b = root(key), root(previous) + parent[max(a, b)] = min(a, b) + forced = {root(x) for x in exposure["compositions"] if x in parent} + forced.update(root(by_id[x]) for x in exposure["material_ids"] if x in by_id) + result = [] + for row in sorted(records, key=lambda r: r["id"]): + group = root(row["composition"]) + is_val = ( + group in forced or int(stable_hash(group, seed), 16) / 2**256 < val_fraction + ) + result.append({**row, "group": group, "split": "val" if is_val else "test"}) + return result, forced + + +def validate_assignment(records, exposure): + if not records or len({r["id"] for r in records}) != len(records): + raise ValueError("Empty or duplicate split IDs") + if any( + r["split"] not in ("val", "test") or r["suite"] not in SUITES for r in records + ): + raise ValueError("Unknown split or suite") + for field in ("composition", "group", "material_id"): + sides = defaultdict(set) + for row in records: + sides[row[field]].add(row["split"]) + if any(len(x) != 1 for x in sides.values()): + raise ValueError(f"Validation/test overlap in {field}") + test = [r for r in records if r["split"] == "test"] + if set(exposure["compositions"]) & {r["composition"] for r in test}: + raise ValueError("Previously exposed composition in test") + if set(exposure["material_ids"]) & {r["material_id"] for r in test}: + raise ValueError("Previously exposed material ID in test") + + +def describe(records): + summary = {} + for suite in SUITES: + summary[suite] = {} + for part in ("all", "val", "test"): + rows = [ + r + for r in records + if r["suite"] == suite and (part == "all" or r["split"] == part) + ] + sizes = [r["n_sites"] for r in rows] + summary[suite][part] = { + "cases": len(rows), + "composition_groups": len({r["group"] for r in rows}), + "n_sites_median": float(np.median(sizes)), + "n_sites_p95": float(np.quantile(sizes, 0.95)), + "n_sites_max": max(sizes), + "fraction_above_32_sites": sum(n > 32 for n in sizes) / len(sizes), + } + return summary + + +def load_split(directory=DEFAULT_SPLITS): + manifest = json.loads((directory / "manifest.json").read_text()) + for name, expected in manifest["files"].items(): + if digest(directory / name) != expected: + raise ValueError(f"Split checksum mismatch: {name}") + with gzip.open(directory / "assignments.jsonl.gz", "rt") as stream: + rows = [json.loads(line) for line in stream] + exposure = json.loads((directory / "exposure.json").read_text()) + validate_assignment(rows, exposure) + counts = Counter(r["suite"] for r in rows) + if counts != {s: x["all"]["cases"] for s, x in manifest["summary"].items()}: + raise ValueError("Split population counts mismatch") + return rows, manifest + + +def build( + cache, + output, + panel_paths=(), + adaptation_paths=(), + exposure_path=None, + val_fraction=0.2, +): + if output.exists(): + raise FileExistsError(f"Refusing to overwrite frozen split: {output}") + records, provenance = source_inventory(cache) + exposure = ( + json.loads(exposure_path.read_text()) + if exposure_path + else collect_exposure(panel_paths, adaptation_paths) + ) + assigned, forced = assign(records, exposure, val_fraction) + validate_assignment(assigned, exposure) + output.mkdir(parents=True) + payload = "".join( + json.dumps(r, sort_keys=True, separators=(",", ":")) + "\n" for r in assigned + ).encode() + (output / "assignments.jsonl.gz").write_bytes(gzip.compress(payload, mtime=0)) + write_json(output / "exposure.json", exposure) + manifest = { + "version": VERSION, + "seed": VERSION, + "target_validation_fraction": val_fraction, + "assignment": "SHA256 of cross-suite composition/MP-ID group; exposed groups forced to validation", + "target_labels_used_for_assignment": False, + "forced_validation_groups": len(forced), + "summary": describe(assigned), + "sources": provenance, + "files": { + n: digest(output / n) for n in ("assignments.jsonl.gz", "exposure.json") + }, + "leaderboard_comparable": False, + "limitations": [ + "Custom AI4Sci partition of public evaluation data, not an official upstream split", + "20% is a group-hash target; case fractions differ and prior exposure increases validation", + "Previously used adaptation materials can occur in validation; test excludes their groups", + "No guarantee of independence from UMA foundation pretraining or public elemental references", + "Freeze future training exclusions against both evaluation partitions before benchmark launch", + "Only IDs/metadata are materialized here; full geometry/reference preparation is on demand", + ], + } + write_json(output / "manifest.json", manifest) + print( + json.dumps( + { + "output": str(output), + "summary": manifest["summary"], + "forced_validation_groups": len(forced), + }, + indent=2, + ) + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cache", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--prior-panels", type=Path, nargs="*", default=[]) + parser.add_argument("--prior-adaptation", type=Path, nargs="*", default=[]) + parser.add_argument( + "--exposure", + type=Path, + help="Reuse a frozen exposure inventory for exact rebuilding", + ) + parser.add_argument("--val-fraction", type=float, default=0.2) + args = parser.parse_args() + if args.exposure and (args.prior_panels or args.prior_adaptation): + parser.error("Use --exposure or prior source paths, not both") + build( + args.cache, + args.output, + args.prior_panels, + args.prior_adaptation, + args.exposure, + args.val_fraction, + ) diff --git a/reproduction/files/41/41887450057925cc17f44bf6613b573cc24cd3f8069b3c734804343743b1cde3/score.py b/reproduction/files/41/41887450057925cc17f44bf6613b573cc24cd3f8069b3c734804343743b1cde3/score.py new file mode 100644 index 0000000000000000000000000000000000000000..531cc1c984775d44c7e7396fa7de6deecc14e766 --- /dev/null +++ b/reproduction/files/41/41887450057925cc17f44bf6613b573cc24cd3f8069b3c734804343743b1cde3/score.py @@ -0,0 +1,192 @@ +"""Trusted, offline scoring; never imports a submitted model or calculator.""" + +from __future__ import annotations + +import argparse +from importlib.metadata import version +import json +from pathlib import Path + +import numpy as np +from pymatgen.io.ase import AseAtomsAdaptor +from pymatgen.entries.compatibility import MaterialsProject2020Compatibility +from pymatgen.entries.computed_entries import ComputedStructureEntry + +from common import ( + ELASTIC_FIELDS, + PHONON_FIELDS, + PROTOCOL, + decode_atoms, + digest, + indexed, + read_rows, + write_json, +) + + +def corrected_formation(prediction, target): + if version("pymatgen") != "2023.5.10": + raise ValueError( + "WBM scoring requires pymatgen 2023.5.10; use the environment/scoring project" + ) + entry = ComputedStructureEntry.from_dict(target["entry"]) + structure = AseAtomsAdaptor.get_structure(decode_atoms(prediction["atoms"])) + if entry.composition != structure.composition: + raise ValueError("Predicted structure changed composition or atom count") + entry._energy = float(prediction["energy"]) + entry._structure = structure + # Pin the complete historical oxidation-state/correction implementation. + # A newer pymatgen with strict_anions=no_check does not reproduce it. + compatibility = MaterialsProject2020Compatibility() + corrected = compatibility.process_entry(entry, clean=True) + if corrected is None: + raise ValueError(f"MP2020 rejected {entry.entry_id}") + reference = sum( + target["elemental_refs"][str(el)] * amount + for el, amount in corrected.composition.items() + ) + value = (corrected.energy - reference) / corrected.composition.num_atoms + if not np.isfinite(value): + raise ValueError("Nonfinite formation energy") + return float(value) + + +def discovery_metrics(truth, predicted): + truth, predicted = np.asarray(truth), np.asarray(predicted) + if not np.isfinite(truth).all() or not np.isfinite(predicted).all(): + raise ValueError("Nonfinite hull distances") + actual, positive = truth <= 0, predicted <= 0 + tp = int(np.sum(actual & positive)) + fp = int(np.sum(~actual & positive)) + fn = int(np.sum(actual & ~positive)) + tn = int(np.sum(~actual & ~positive)) + + def divide(numerator, denominator): + return numerator / denominator if denominator else None + + return { + "n": len(truth), + "threshold_eV_per_atom": 0.0, + "F1": divide(2 * tp, 2 * tp + fp + fn), + "precision": divide(tp, tp + fp), + "recall": divide(tp, tp + fn), + "TP": tp, + "FP": fp, + "FN": fn, + "TN": tn, + "hull_MAE_meV_per_atom": float(np.mean(np.abs(predicted - truth)) * 1000), + } + + +FAILED_FORMATION_ERROR = 1.0 # eV/atom; a failed WBM case is predicted far above the hull + + +def _usable(pred, target, fields=()): + if pred is None or pred.get("status") != "ok" or pred.get("suite") != target["suite"]: + return False + try: + return all(np.isfinite(float(pred[f])) for f in fields) + except (KeyError, TypeError, ValueError): + return False + + +def score_rows(targets, predictions): + """Every target is scored. A failed or nonfinite case predicts 0 for phonon/elastic fields and + a +1 eV/atom formation-energy error for discovery; failures are counted per suite.""" + targets, predictions = indexed(targets), indexed(predictions) + unexpected = predictions.keys() - targets.keys() + if unexpected: + raise ValueError(f"Unexpected prediction IDs: {sorted(unexpected)[:10]}") + metrics = {} + for suite, fields in (("phonons", PHONON_FIELDS), ("elasticity", ELASTIC_FIELDS)): + ids = [key for key in targets if targets[key]["suite"] == suite] + if not ids: + continue + ok = [_usable(predictions.get(key), targets[key], fields) for key in ids] + metrics[suite] = {"n": len(ids), "failed": len(ids) - sum(ok)} + for field, unit in fields.items(): + true = np.asarray([targets[key][field] for key in ids], dtype=float) + pred = np.asarray([float(predictions[key][field]) if good else 0.0 for key, good in zip(ids, ok)]) + if not np.isfinite(true).all(): + raise ValueError(f"Nonfinite reference {suite}/{field}") + metrics[suite][field] = { + "MAE": float(np.mean(np.abs(pred - true))), + "unit": unit, + } + ids = [key for key in targets if targets[key]["suite"] == "discovery"] + if ids: + true = np.array([targets[key]["e_hull"] for key in ids]) + errors, failed = [], 0 + for key in ids: + pred = predictions.get(key) + try: + if not _usable(pred, targets[key], ("energy",)): + raise ValueError("failed case") + errors.append(corrected_formation(pred, targets[key]) - targets[key]["e_form"]) + except ValueError as error: + if "pymatgen 2023.5.10" in str(error): + raise + failed += 1 + errors.append(FAILED_FORMATION_ERROR) + pred_hull = true + np.array(errors) # signed distance; never clamp to zero + metrics["discovery"] = discovery_metrics(true, pred_hull) + metrics["discovery"]["failed"] = failed + unique = np.array([targets[key]["unique_prototype"] for key in ids]) + if unique.any(): + metrics["discovery"]["unique_prototypes"] = discovery_metrics( + true[unique], pred_hull[unique] + ) + return metrics + + +def score(references: Path, predictions: Path, output: Path): + manifest = json.loads((references / "manifest.json").read_text()) + run = json.loads((predictions / "run.json").read_text()) + report = { + "protocol": PROTOCOL, + "valid": False, + "preset": manifest["preset"], + "leaderboard_comparable": False, + "scoring_versions": { + name: version(name) for name in ("numpy", "pymatgen", "ase") + }, + } + try: + if manifest["protocol"] != PROTOCOL or run["protocol"] != PROTOCOL: + raise ValueError("Protocol mismatch") + if not run["complete"] or run["inputs_sha256"] != manifest["inputs_sha256"]: + raise ValueError("Incomplete run or wrong evaluation inputs") + if digest(references / "targets.jsonl") != manifest["targets_sha256"]: + raise ValueError("Reference checksum mismatch") + if digest(predictions / "predictions.jsonl") != run["predictions_sha256"]: + raise ValueError("Prediction checksum mismatch") + targets = read_rows(references / "targets.jsonl") + rows = read_rows(predictions / "predictions.jsonl") + report["metrics"] = score_rows(targets, rows) + report["valid"] = True + report["coverage"] = {"expected": len(targets), + "successful": sum(row.get("status") == "ok" for row in rows)} + report["total_case_seconds"] = sum(row.get("seconds", 0.0) for row in rows) + report["nonconverged_initial_relaxations"] = sum( + not row.get("diagnostics", {}).get("converged", False) for row in rows + ) + report["nonconverged_strained_relaxations"] = sum( + not relaxed["converged"] + for row in rows + for relaxed in row.get("diagnostics", {}).get("strained_relaxations", []) + ) + except (ValueError, KeyError, TypeError) as error: + report["error"] = f"{type(error).__name__}: {error}" + write_json(output, report) + return report + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--references", type=Path, required=True) + parser.add_argument("--predictions", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + report = score(args.references, args.predictions, args.output) + print(json.dumps(report, indent=2, allow_nan=False)) + raise SystemExit(0 if report["valid"] else 2) diff --git a/reproduction/files/42/425d42d8f1e61edb66461569cc057c8ef8cdbff1d65267b49fe4c210332705bb/check_runner_network.py b/reproduction/files/42/425d42d8f1e61edb66461569cc057c8ef8cdbff1d65267b49fe4c210332705bb/check_runner_network.py new file mode 100644 index 0000000000000000000000000000000000000000..0b6a2179597a19acaa73e8062794178b1caf10ab --- /dev/null +++ b/reproduction/files/42/425d42d8f1e61edb66461569cc057c8ef8cdbff1d65267b49fe4c210332705bb/check_runner_network.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""Check this task against real runner staging and Harbor egress selection. + +This optional deployment check needs agent-runner, Harbor and PyYAML. It does +not start containers, contact a model API or certify runtime network isolation. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import shutil +import sys +import tempfile +import tomllib +from types import SimpleNamespace + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--runner-source", type=Path, + help="Optional agent-runner checkout; otherwise use the installed package", + ) + args = parser.parse_args() + if args.runner_source: + source = args.runner_source.resolve() / "src" + if not (source / "agent_runner/task.py").is_file(): + parser.error("--runner-source must contain src/agent_runner/task.py") + sys.path.insert(0, str(source)) + + import yaml + from agent_runner.task import stage_task + from harbor.environments.docker.docker import DockerEnvironment + from harbor.models.task.config import TaskConfig + + task = Path(__file__).resolve().parents[1] + hosts = ["api.openai.com", "auth.openai.com", "chatgpt.com"] + + def config(root: Path) -> dict: + value = tomllib.loads((root / "task.toml").read_text()) + TaskConfig.model_validate(value) + return value + + def routed_services(compose: Path) -> list[str]: + # Invoke Harbor's implementation without constructing a Docker runtime. + context = SimpleNamespace( + _environment_docker_compose_path=compose, + extra_docker_compose_paths=[], + _EGRESS_CONTROL_SERVICE_NAME=DockerEnvironment._EGRESS_CONTROL_SERVICE_NAME, + ) + return DockerEnvironment._egress_controlled_service_names(context) + + original = config(task) + assert original["environment"]["network_mode"] == "no-network" + assert original["verifier"]["environment"]["network_mode"] == "no-network" + cases = [] + with tempfile.TemporaryDirectory(prefix="massspecgym-runner-network-") as tmp: + root = Path(tmp) + for mode in ("allowlist", "no-network"): + for gpus in (0, 1, 8): + staged = stage_task( + task, root / f"{mode}-{gpus}", network=mode, + allowed_hosts=hosts if mode == "allowlist" else [], gpus=gpus, + ) + resolved = config(staged) + for table in ("environment", "agent"): + assert resolved[table]["network_mode"] == mode + assert resolved[table].get("allowed_hosts", []) == ( + hosts if mode == "allowlist" else [] + ) + verifier = resolved["verifier"] + for policy in (verifier, verifier["environment"]): + assert policy["network_mode"] == "no-network" + assert not policy.get("allowed_hosts") + development = staged / "environment/docker-compose.yaml" + expected = ["main"] if mode == "allowlist" else [] + assert routed_services(development) == expected + if mode == "no-network": + dev = yaml.safe_load(development.read_text())["services"]["main"] + assert dev["network_mode"] == "none" + final_compose = staged / "tests/docker-compose.yaml" + final = yaml.safe_load(final_compose.read_text())["services"] + for name in ("main", "grader"): + assert final[name]["network_mode"] == "none" + assert routed_services(final_compose) == [] + cases.append({"network": mode, "gpus": gpus, "status": "passed"}) + + # Reproduce the old failure through the same runner, proving this check + # observes the Compose conflict rather than only reading patched TOML. + legacy = root / "legacy" + shutil.copytree(task, legacy, symlinks=True) + compose_path = legacy / "environment/docker-compose.yaml" + compose = yaml.safe_load(compose_path.read_text()) + compose["services"]["main"]["network_mode"] = "none" + compose_path.write_text(yaml.safe_dump(compose)) + staged = stage_task( + legacy, root / "legacy-staged", network="allowlist", + allowed_hosts=hosts, gpus=0, + ) + assert config(staged)["environment"]["network_mode"] == "allowlist" + assert routed_services(staged / "environment/docker-compose.yaml") == [] + + print(json.dumps({ + "status": "passed", "profiles": cases, + "legacy_compose_conflict_reproduced": True, + "verifier_offline_in_all_profiles": True, + "scope": "Real runner staging and Harbor service selection; no containers or API calls", + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/44/4457e9027737d7b7fc4541396563758edebc103e1f2575e826ab4c35a2658f21/test_verifier_failures.py b/reproduction/files/44/4457e9027737d7b7fc4541396563758edebc103e1f2575e826ab4c35a2658f21/test_verifier_failures.py new file mode 100644 index 0000000000000000000000000000000000000000..0f776f33f06239e6fcaad79a2dac96d73ed4213e --- /dev/null +++ b/reproduction/files/44/4457e9027737d7b7fc4541396563758edebc103e1f2575e826ab4c35a2658f21/test_verifier_failures.py @@ -0,0 +1,105 @@ +"""Failures must not turn untrusted files into measured model rewards.""" + +import argparse +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import grader +import main_verifier + + +class VerifierFailureTests(unittest.TestCase): + def test_new_inputs_are_scored_without_a_false_reference_claim(self): + metrics = {'hit_rate_at_1': 1.0} + report = grader.reference_comparison(metrics, {'files': {'queries.jsonl': 'new'}}) + self.assertFalse(report['comparable']) + self.assertIsNone(report['beats_reference']) + frozen = grader.reference_comparison(metrics, {'files': grader.REFERENCE_INPUT_FILES}) + self.assertTrue(frozen['comparable']) + self.assertAlmostEqual(frozen['reference_delta_hit_at_1'], 1 - grader.REFERENCE_HIT_RATE_AT_1) + + def test_trusted_outputs_remove_stale_rewards_and_deny_other_uid_writes(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + output, sealed = root / 'logs', root / 'sealed/run' + output.mkdir(mode=0o777) + for name in ('reward.json', 'reward.txt'): + (output / name).write_text('1') + main_verifier.prepare_trusted_directories(output, sealed) + self.assertFalse((output / 'reward.json').exists()) + self.assertFalse((output / 'reward.txt').exists()) + self.assertEqual(output.stat().st_mode & 0o022, 0) + self.assertEqual(sealed.parent.stat().st_mode & 0o077, 0) + + def test_agent_failures_have_zero_reward_and_explicit_status(self): + failures = [ + ('invalid_submission', ValueError('bad hash')), + ('inference_timeout', subprocess.TimeoutExpired('infer.sh', 1)), + ('inference_failed', subprocess.CalledProcessError(7, 'infer.sh')), + ] + for status, error in failures: + with self.subTest(status=status), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + args = argparse.Namespace(output=root / 'logs', sealed=root / 'sealed/run', + input=root / 'input', submission=root / 'package', + timeout=1, no_wait=True) + with mock.patch.object(main_verifier, 'validate_input', return_value=({}, {'q': {}}, {})), \ + mock.patch.object(main_verifier, 'validate_submission', + side_effect=error if status == 'invalid_submission' else None), \ + mock.patch.object(main_verifier, 'run_submission', side_effect=error): + main_verifier.evaluate(args) + reward = json.loads((args.output / 'reward.json').read_text()) + report = json.loads((args.output / 'report.json').read_text()) + self.assertEqual(reward, {'reward': 0.0}) + self.assertEqual(report['metrics']['hit_rate_at_1'], 0) + self.assertEqual(report['metrics']['mces_at_1'], 100) + self.assertEqual(report['status'], status) + self.assertFalse(report['model_quality_measured']) + + def test_setup_error_cannot_reuse_a_previous_reward(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + args = argparse.Namespace(output=root / 'logs', sealed=root / 'sealed/run', + input=root / 'input', submission=root / 'package', + timeout=1, no_wait=True) + args.output.mkdir() + (args.output / 'reward.txt').write_text('1') + with mock.patch.object(main_verifier, 'validate_input', side_effect=ValueError('input hash mismatch')): + with self.assertRaisesRegex(ValueError, 'input hash mismatch'): + main_verifier.evaluate(args) + self.assertFalse((args.output / 'reward.txt').exists()) + self.assertFalse((args.output / 'reward.json').exists()) + + def test_non_string_query_ids_are_invalid_outputs_not_scorer_crashes(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'rankings.jsonl' + for query_id in ([], {}, None, 1): + with self.subTest(query_id=query_id): + path.write_text(json.dumps({'query_id': query_id, 'ranking': ['a']}) + '\n') + rankings, error = grader.load_rankings(path, {'q': {'candidate_pool_id': 'p'}}, {'p': {'a': 'C'}}) + self.assertEqual(rankings, {}) + self.assertIsNotNone(error) + + def test_grader_error_is_reported_without_waiting_for_timeout(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + args = argparse.Namespace(output=root / 'logs', sealed=root / 'sealed/run', + input=root / 'input', submission=root / 'package', + timeout=1, no_wait=False) + def publish_error(*unused): + result = root / 'sealed/results' + result.mkdir() + (result / 'error.json').write_text('{"error":"CBC unavailable"}') + with mock.patch.object(main_verifier, 'validate_input', return_value=({}, {'q': {}}, {})), \ + mock.patch.object(main_verifier, 'validate_submission'), \ + mock.patch.object(main_verifier, 'run_submission', return_value=root / 'predictions'), \ + mock.patch.object(main_verifier, 'seal_output', side_effect=publish_error): + with self.assertRaisesRegex(RuntimeError, 'CBC unavailable'): + main_verifier.evaluate(args) + self.assertFalse((args.output / 'reward.json').exists()) diff --git a/reproduction/files/44/44809be0699e33205590e64d86082082c1bb4f5cdf11dd94198746521e2f9e07/paired_bootstrap.py b/reproduction/files/44/44809be0699e33205590e64d86082082c1bb4f5cdf11dd94198746521e2f9e07/paired_bootstrap.py new file mode 100644 index 0000000000000000000000000000000000000000..08b42fb60dc3b6346a78335079dafe1fe284fe37 --- /dev/null +++ b/reproduction/files/44/44809be0699e33205590e64d86082082c1bb4f5cdf11dd94198746521e2f9e07/paired_bootstrap.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Paired Hit@1 bootstrap comparison for two complete ranking files.""" + +import argparse +import json +from pathlib import Path + +import numpy as np + + +def jsonl(path: Path): + with path.open(encoding="utf-8") as stream: + for line_number, line in enumerate(stream, 1): + if not line.strip(): + continue + try: + yield json.loads(line) + except json.JSONDecodeError as error: + raise ValueError(f"invalid JSON at {path}:{line_number}") from error + + +def load_truth(path: Path) -> dict[str, str]: + truth = {} + for row in jsonl(path): + query_id = row.get("query_id") + candidate_id = row.get("correct_candidate_id") + if ( + not isinstance(query_id, str) + or not isinstance(candidate_id, str) + or query_id in truth + ): + raise ValueError("invalid or duplicate label row") + truth[query_id] = candidate_id + if not truth: + raise ValueError("label file is empty") + return truth + + +def load_top1(path: Path, expected: set[str]) -> dict[str, str]: + predictions = {} + for row in jsonl(path): + if set(row) != {"query_id", "ranking"}: + raise ValueError(f"invalid ranking fields in {path}") + query_id = row["query_id"] + ranking = row["ranking"] + if ( + not isinstance(query_id, str) + or query_id not in expected + or query_id in predictions + or not isinstance(ranking, list) + or not ranking + or any(not isinstance(candidate_id, str) for candidate_id in ranking) + or len(set(ranking)) != len(ranking) + ): + raise ValueError(f"invalid or duplicate ranking in {path}") + predictions[query_id] = ranking[0] + if set(predictions) != expected: + raise ValueError(f"ranking file does not cover the label query set: {path}") + return predictions + + +def compare( + truth: dict[str, str], + baseline: dict[str, str], + challenger: dict[str, str], + *, + confidence: float, + resamples: int, + seed: int, + groups: dict[str, str] | None = None, +) -> dict: + if not 0 < confidence < 1: + raise ValueError("confidence must be between 0 and 1") + if resamples < 1: + raise ValueError("resamples must be positive") + outcomes = {"challenger_only": 0, "baseline_only": 0, "tie": 0} + baseline_hits = challenger_hits = 0 + for query_id, correct in truth.items(): + baseline_hit = baseline[query_id] == correct + challenger_hit = challenger[query_id] == correct + baseline_hits += baseline_hit + challenger_hits += challenger_hit + if challenger_hit and not baseline_hit: + outcomes["challenger_only"] += 1 + elif baseline_hit and not challenger_hit: + outcomes["baseline_only"] += 1 + else: + outcomes["tie"] += 1 + + count = len(truth) + probabilities = np.array([ + outcomes["baseline_only"], + outcomes["tie"], + outcomes["challenger_only"], + ], dtype=np.float64) / count + rng = np.random.default_rng(seed) + deltas = np.empty(resamples, dtype=np.float64) + offset = 0 + while offset < resamples: + batch = min(10_000, resamples - offset) + samples = rng.multinomial(count, probabilities, size=batch) + deltas[offset:offset + batch] = (samples[:, 2] - samples[:, 0]) / count + offset += batch + alpha = (1 - confidence) / 2 + lower, upper = np.quantile(deltas, [alpha, 1 - alpha]) + delta = (challenger_hits - baseline_hits) / count + report = { + "schema": "massspecgym-retrieval-paired-bootstrap/v1", + "queries": count, + "metric": "hit_rate_at_1", + "baseline_hit_rate": baseline_hits / count, + "challenger_hit_rate": challenger_hits / count, + "delta": delta, + "paired_outcomes": outcomes, + "confidence": confidence, + "resamples": resamples, + "seed": seed, + "interval": [float(lower), float(upper)], + "beats_reference": bool(lower > 0), + "method": "paired nonparametric percentile bootstrap; multinomial-compressed {-1,0,1} outcomes", + } + if groups is not None: + from diagnostics import cluster_interval + if set(groups) != set(truth): + raise ValueError('molecule groups must cover the exact query set') + result = cluster_interval( + [int(challenger[q] == truth[q]) - int(baseline[q] == truth[q]) for q in truth], + [groups[q] for q in truth], resamples=resamples, seed=seed, confidence=confidence, + ) + report.update(schema='massspecgym-retrieval-paired-bootstrap/v2', + interval=[result['lower'], result['upper']], + beats_reference=result['lower'] > 0, + molecule_groups=result['molecule_groups'], + method='paired molecule-cluster percentile bootstrap; spectrum-weighted Hit@1 delta') + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--labels", required=True, type=Path) + parser.add_argument("--baseline", required=True, type=Path) + parser.add_argument("--challenger", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--confidence", type=float, default=0.999) + parser.add_argument("--resamples", type=int, default=100_000) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument('--unit', choices=['molecule', 'query'], default='molecule', + help='Molecules are the default uncertainty unit; query reproduces historical reports') + args = parser.parse_args() + truth = load_truth(args.labels) + baseline = load_top1(args.baseline, set(truth)) + challenger = load_top1(args.challenger, set(truth)) + groups = None + if args.unit == 'molecule': + from rdkit import Chem, rdBase + groups = {} + for row in jsonl(args.labels): + molecule = Chem.MolFromSmiles(row['true_smiles']) + if molecule is None: + raise ValueError('cannot assign a molecule group to an invalid true SMILES') + groups[row['query_id']] = Chem.MolToInchiKey(molecule).split('-')[0] + report = compare( + truth, + baseline, + challenger, + confidence=args.confidence, + resamples=args.resamples, + seed=args.seed, + groups=groups, + ) + if groups is not None: + report['grouping'] = 'RDKit InChIKey connectivity block from private true_smiles' + report['rdkit_version'] = rdBase.rdkitVersion + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/46/466ed268310bd3f7e182f543efc44409653ca6de0b0c18d46377297e69aa7181/test.sh b/reproduction/files/46/466ed268310bd3f7e182f543efc44409653ca6de0b0c18d46377297e69aa7181/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..dd5d9baa830254b533003c55dc7bea43ef65e2e1 --- /dev/null +++ b/reproduction/files/46/466ed268310bd3f7e182f543efc44409653ca6de0b0c18d46377297e69aa7181/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +exec python /tests/main_verifier.py \ + --submission /workspace/submission \ + --input /benchmark/test \ + --sealed /sealed/run \ + --output /logs/verifier \ + --timeout "${ATOMISTIC_MATERIALS_INFERENCE_TIMEOUT_SECONDS:-10800}" diff --git a/reproduction/files/46/46a5b80c519c971bbf318cfcdb005b2a1e79d61571ca67bb1f3b744603af665a/native_channel.py b/reproduction/files/46/46a5b80c519c971bbf318cfcdb005b2a1e79d61571ca67bb1f3b744603af665a/native_channel.py new file mode 100644 index 0000000000000000000000000000000000000000..c00167871848b9ce086affc9c688d7e5fd021479 --- /dev/null +++ b/reproduction/files/46/46a5b80c519c971bbf318cfcdb005b2a1e79d61571ca67bb1f3b744603af665a/native_channel.py @@ -0,0 +1,44 @@ +"""Pinned 3D Channel with an explicit control-window clock repair. + +The upstream actuator ramp is defined on 0..50 CFD substeps, but its caller +passes the global episode clock. From the second control onward the unbounded +negative ramp increases jet amplitude throughout the episode. Reset ONLY the +clock passed to the action-window integrator. Physical fields, dt, grid, forcing, +reward, action bounds and the OUTER episode clock are unchanged. + +This is an organizer runtime profile, not an unmodified-paper reproduction. +""" +import gymnasium as gym +import jax +import numpy as np +from hydrogym.jax.envs.channel import ChannelFlowSpectralEnv + +PROFILE = 'channel-72cube-local-actuator-clock-v1' + + +class LocalActuatorClock(ChannelFlowSpectralEnv): + def _wss_with_aux(self, state, action, params): + return super()._wss_with_aux(state.replace(time=0), action, params) + + +class ChannelEnv(gym.Env): + def __init__(self, data, *, repair=True): + cls = LocalActuatorClock if repair else ChannelFlowSpectralEnv + self.native = cls({'initial_field_dir': str(data/'environments/Channel_3D_Retau180/initial_field')}) + self.params = self.native.default_params + self.key = jax.random.PRNGKey(42) + self.advance = jax.jit(lambda k, s, a: self.native.step_env(k, s, a, self.params)) + self.observation_space = gym.spaces.Box(-np.inf, np.inf, shape=(128,), dtype=np.float32) + self.action_space = gym.spaces.Box(-1, 1, shape=(24,), dtype=np.float32) + + def reset(self, seed=None, options=None): + super().reset(seed=seed) + if seed is not None: + self.key = jax.random.PRNGKey(seed) + obs, self.state = self.native.reset_env(self.key, self.params) + return np.asarray(obs, dtype=np.float32), {} + + def step(self, action): + self.key, key = jax.random.split(self.key) + obs, self.state, reward, done, info = self.advance(key, self.state, np.asarray(action,dtype=np.float32)) + return np.asarray(obs, dtype=np.float32), float(reward), bool(done), False, {} diff --git a/reproduction/files/47/47009d5c7c0427b403f72eb7dab0a906c9f55b5c0aec1a9fcc09830e7af430b3/run_unit_tests.sh b/reproduction/files/47/47009d5c7c0427b403f72eb7dab0a906c9f55b5c0aec1a9fcc09830e7af430b3/run_unit_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..19973d09d1aa3f6c30bb5f6b3f24dc3e39b241fe --- /dev/null +++ b/reproduction/files/47/47009d5c7c0427b403f72eb7dab0a906c9f55b5c0aec1a9fcc09830e7af430b3/run_unit_tests.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Unit tests in the task's runtime image (CPU only). +set -euo pipefail +task_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +image=${ATOMISTIC_TEST_IMAGE:-atomistic-materials-env:v2} +[[ "${ATOMISTIC_TEST_SKIP_BUILD:-0}" == 1 ]] || docker build -t "$image" "$task_root/environment" +exec docker run --rm -e PYTHONDONTWRITEBYTECODE=1 -v "$task_root:/task:ro" -w /task "$image" \ + python -m pytest -q -p no:cacheprovider tests "$@" diff --git a/reproduction/files/48/48680fdc223e5a049057180496756341037ba180eb3c09a6e73c141788d838de/test_delivery.py b/reproduction/files/48/48680fdc223e5a049057180496756341037ba180eb3c09a6e73c141788d838de/test_delivery.py new file mode 100644 index 0000000000000000000000000000000000000000..28910e1032dd789945a900a208e4260a422cd138 --- /dev/null +++ b/reproduction/files/48/48680fdc223e5a049057180496756341037ba180eb3c09a6e73c141788d838de/test_delivery.py @@ -0,0 +1,108 @@ +"""CPU delivery regressions; no benchmark data or model training.""" +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +import h5py +import numpy as np +import grade + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'environment/baseline/starter')) +import publish +from package_contract import InvalidSubmission, validate_features + + +class DeliveryTest(unittest.TestCase): + def fixture(self, root): + model = root / 'candidate' + model.mkdir() + for name in ['encoder.pt', 'LICENSE-OlmoEarth']: + (model / name).write_text('fixture') + for name in ['config.json', 'provenance.json']: + (model / name).write_text('{}') + (model / 'infer.py').write_text('''import argparse,h5py,numpy as np +p=argparse.ArgumentParser() +for key in ['model','input','output','device']:p.add_argument('--'+key) +a=p.parse_args() +with h5py.File(a.input) as f: ids=f['ids'].asstr()[:] +np.savez(a.output,ids=ids.astype(str),features=np.ones((len(ids),2),dtype=np.float32)) +''') + inputs = root / 'inputs.h5' + with h5py.File(inputs, 'w') as f: + f.create_dataset('ids', data=np.array(['a', 'b', 'c'], dtype=h5py.string_dtype())) + return model, inputs + + def test_atomic_publication_retains_previous_and_failed_check_preserves_live(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + model, inputs = self.fixture(root) + live = root / 'submission' + live.mkdir() # Same empty directory as the image. + publish.publish(model, live, inputs) + (model / 'encoder.pt').write_text('second') + publish.publish(model, live, inputs) + self.assertEqual((live / 'encoder.pt').read_text(), 'second') + self.assertTrue(any((p / 'encoder.pt').exists() and (p / 'encoder.pt').read_text() == 'fixture' + for p in root.glob('.submission-previous-*'))) + (model / 'infer.py').write_text('raise RuntimeError("broken candidate")') + with self.assertRaises(subprocess.CalledProcessError): + publish.publish(model, live, inputs) + self.assertEqual((live / 'encoder.pt').read_text(), 'second') + + def test_unsupported_exchange_preserves_live(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + model, inputs = self.fixture(root) + live = root / 'submission' + live.mkdir() + (live / 'keep').write_text('old') + with patch.object(publish, 'exchange', side_effect=OSError('unsupported filesystem')): + with self.assertRaises(OSError): publish.publish(model, live, inputs) + self.assertEqual((live / 'keep').read_text(), 'old') + + def test_invalid_features_and_missing_input_are_distinct(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _, inputs = self.fixture(root) + output = root / 'features.npz' + for ids, values in [(['a','a','c'], np.ones((3,2),np.float32)), + (['a','b','c'], np.full((3,2),np.nan,np.float32)), + (['a','b','c'], np.ones((3,2),np.float64))]: + np.savez(output, ids=ids, features=values) + with self.assertRaises(InvalidSubmission): validate_features(output, inputs) + with output.open('wb') as stream: + np.save(stream, np.ones(3)) + with self.assertRaises(InvalidSubmission): validate_features(output, inputs) + with self.assertRaises(FileNotFoundError): validate_features(output, root/'absent.h5') + + def test_invalid_package_zero_and_infrastructure_no_reward(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp) + model, _ = self.fixture(root) + output=root/'invalid' + command=['grade.py','--model',str(model),'--data',str(root/'missing'), '--output',str(output)] + (model/'config.json').write_text('broken') + with patch.object(sys,'argv',command): grade.main() + self.assertEqual(json.loads((output/'reward.json').read_text())['reward'],0) + (model/'config.json').write_text('{}') + output=root/'infra'; command[-1]=str(output) + with patch.object(sys,'argv',command), patch.object(grade.subprocess,'run',side_effect=FileNotFoundError('bwrap')): + with self.assertRaises(FileNotFoundError): grade.main() + self.assertFalse((output/'reward.json').exists()) + + def test_replay_invalid_output_zero(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp); model,_=self.fixture(root); output=root/'score' + command=['grade.py','--model',str(model),'--data',str(root), '--output',str(output)] + with patch.object(sys,'argv',command), patch.object(grade.subprocess,'run',return_value=subprocess.CompletedProcess([],42)): + grade.main() + self.assertEqual(json.loads((output/'report.json').read_text())['status'],'invalid_submission') + self.assertEqual(json.loads((output/'reward.json').read_text()),{'reward':0.0,'invalid_submission':1}) + + +if __name__ == '__main__': unittest.main() diff --git a/reproduction/files/48/48abddb572f3fd7910802be0658562b82f35e09e0af60a6c3d1aea750ffe842f/test_release_layout.py b/reproduction/files/48/48abddb572f3fd7910802be0658562b82f35e09e0af60a6c3d1aea750ffe842f/test_release_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..1f457b35d0aeedde44dd83b6dd3e918c42583bf9 --- /dev/null +++ b/reproduction/files/48/48abddb572f3fd7910802be0658562b82f35e09e0af60a6c3d1aea750ffe842f/test_release_layout.py @@ -0,0 +1,76 @@ +"""The AlphaQubit training code reads a development release root (the agent's /workspace/data) exactly as it +reads the raw Zenodo directory: same conditions, same train/validation rows in the same order.""" +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pytest + +from baselines import alphaqubit_data, data + +NAME = "surface_code_bX_d3_r01_center_3_5" +WIDTH = 1 # 1 round x 8 detectors -> one packed byte per shot + + +@pytest.fixture() +def roots(tmp_path: Path) -> tuple[Path, Path]: + rng = np.random.default_rng(0) + detectors = rng.integers(0, 256, size=(50_000, WIDTH), dtype=np.uint8) + labels = rng.integers(0, 2, size=50_000, dtype=np.uint8) + raw = tmp_path / "raw" / NAME + raw.mkdir(parents=True) + detectors.tofile(raw / "detection_events.b8") + (raw / "obs_flips_actual.01").write_bytes(b"".join(b"1\n" if bit else b"0\n" for bit in labels)) + for name in ("circuit_ideal.stim", "pij_from_even_for_odd.dem"): + (raw / name).write_text(f"# {name}\n") + release = tmp_path / "release" + for split in ("train", "validation"): + rows = data.hardware_split_indices(split) + folder = release / split / "conditions" / NAME + folder.mkdir(parents=True) + np.savez(folder / "arrays.npz", sample_ids=rows.astype(np.uint64), detectors=detectors[rows], labels=labels[rows]) + for name in ("circuit_ideal.stim", "pij_from_even_for_odd.dem"): + (folder / name).write_text(f"# {name}\n") + (release / split / "manifest.json").write_text(json.dumps({"split": split, "conditions": [{"name": NAME}]})) + return tmp_path / "raw", release + + +def test_release_root_is_recognised(roots: tuple[Path, Path]) -> None: + raw, release = roots + assert data.is_release_root(release) and not data.is_release_root(raw) + (condition,) = data.discover_conditions(release) + assert (condition.name, condition.group_id, condition.rounds) == (NAME, "d3_bX_center_3_5", 1) + assert condition.path == release / "train" / "conditions" / NAME + + +@pytest.mark.parametrize("loader", [data.load_hardware_packed, alphaqubit_data.load_hardware_packed]) +@pytest.mark.parametrize("split", ["train", "validation"]) +def test_release_rows_equal_raw_rows(roots: tuple[Path, Path], loader, split: str) -> None: + raw, release = roots + (from_raw,), (from_release,) = data.discover_conditions(raw), data.discover_conditions(release) + (raw_det, raw_lab), (rel_det, rel_lab) = loader(from_raw, split), loader(from_release, split) + assert raw_det.dtype == rel_det.dtype == np.uint8 and rel_lab.shape == (len(rel_det), 1) + assert np.array_equal(raw_det, rel_det) and np.array_equal(raw_lab, rel_lab) + + +def test_release_loader_refuses_test_rows(roots: tuple[Path, Path]) -> None: + (condition,) = data.discover_conditions(roots[1]) + with pytest.raises(ValueError): + data.load_release_packed(condition, "test") + + +def test_package_template_has_the_submission_layout_without_weights(tmp_path: Path) -> None: + from baselines.alphaqubit_artifact import EXPECTED_GROUPS, INFERENCE_SOURCES + from qecbench.package import write_template + template = tmp_path / "package-template" + write_template(template) + for name in ("infer.sh", "README.md", "model_config.json", "pyproject.toml", "uv.lock", "requirements.lock"): + assert (template / name).is_file(), name + assert {path.name for path in (template / "src/baselines").iterdir()} >= set(INFERENCE_SOURCES) | {"__init__.py", "metrics.py"} + assert (template / "src/qecbench/inference.py").is_file() + config = json.loads((template / "model_config.json").read_text()) + assert set(config["models"]) == set(EXPECTED_GROUPS) + assert not (template / "weights").exists() and not (template / "model_manifest.json").exists() + assert not any(template.rglob("*.npz")) diff --git a/reproduction/files/49/49343b8281a339caa84d5c2ccf269bfb52ac1e97fdff8a02a95bb25d262d2b3a/native_verifier.py b/reproduction/files/49/49343b8281a339caa84d5c2ccf269bfb52ac1e97fdff8a02a95bb25d262d2b3a/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..de555b5577761081c312aae132e0c64af6ed4133 --- /dev/null +++ b/reproduction/files/49/49343b8281a339caa84d5c2ccf269bfb52ac1e97fdff8a02a95bb25d262d2b3a/native_verifier.py @@ -0,0 +1,455 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +from concurrent.futures import ThreadPoolExecutor, as_completed +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import re +import shutil +import signal +import socket +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def enter_offline_namespace(): + import offline_network + record = offline_network.configure(STATE) + libc = ctypes.CDLL(None, use_errno=True) + for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)): + fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC) + try: + if libc.setns(fd, flag): + raise OSError(ctypes.get_errno(), 'enter offline verifier namespace') + finally: + os.close(fd) + if socket.if_nameindex() != [(1, 'lo')]: + raise RuntimeError('Offline verifier namespace has external interfaces') + return record + + +def validate_ready_marker(sealed_root): + """Accept either upstream seal format, always checking the exact snapshot. + +Surface-code uses JSON with a run ID. Molecular, Genome and Protein-sequence +use a plain SHA-256 line. The original scientific grader rechecks the seal. +""" + root = Path(sealed_root) + raw = (root/'READY').read_text().strip() + snapshot = root/'run/snapshot.json' + observed = hashlib.sha256(snapshot.read_bytes()).hexdigest() + if re.fullmatch('[0-9a-f]{64}', raw): + if raw != observed: + raise RuntimeError('Native seal marker is inconsistent') + return + marker = json.loads(raw) + if (not isinstance(marker, dict) or marker.get('snapshot_sha256') != observed + or not isinstance(marker.get('run_id'), str) + or json.loads(snapshot.read_text()).get('run_id') != marker['run_id']): + raise RuntimeError('Native seal marker is inconsistent') + + +def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')): + """End the native waiting supervisor only after its authenticated seal.""" + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + seconds + sealed_ready = False + try: + while process.poll() is None: + if (sealed_root / 'READY').is_file(): + validate_ready_marker(sealed_root) + sealed_ready = True + break + if time.monotonic() >= deadline: + raise TimeoutError('Verifier inference budget exhausted') + time.sleep(.1) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode) + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def run_verifier_command(cfg, log, entered): + """Apply the native deadline after staging when the frozen plan opts in. + + Harbor 0.23 uploads artifacts before entering the separate verifier's + asyncio.wait_for. Older Beaker plans retain their original inclusive clock. + The returned clock origin also covers any post-command validation. + """ + started = time.monotonic() if cfg.get('exclude_setup_from_budget') else entered + remaining = cfg['timeout_seconds'] - (time.monotonic() - started) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + if cfg.get('stop_after_sealed_ready'): + result = run_until_sealed(cfg['command'], log, remaining) + else: + def run_identity(): + os.setgroups([]) + os.setgid(10001) + os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + os.chown(STATE / 'results', 10001, 10001) + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True, + preexec_fn=run_identity if cfg.get('untrusted_whole_verifier') else None) + return result, started + + +def copy_submission(source, destination, workers=1): + """Copy an immutable package, preserving copytree's content and metadata. + + Only regular-file copies overlap. Links are preserved without traversal; + directory metadata is restored after every child copy has finished. + """ + if workers <= 1: + return shutil.copytree(source, destination, symlinks=True) + source, destination = Path(source), Path(destination) + destination.mkdir(parents=True) + directories = [(source, destination)] + with ThreadPoolExecutor(max_workers=workers) as pool: + pending = [] + def visit(src, dst): + with os.scandir(src) as entries: + for entry in entries: + origin, target = Path(entry.path), dst / entry.name + if entry.is_symlink(): + os.symlink(os.readlink(origin), target) + shutil.copystat(origin, target, follow_symlinks=False) + elif entry.is_dir(follow_symlinks=False): + target.mkdir() + directories.append((origin, target)) + visit(origin, target) + else: + pending.append(pool.submit(shutil.copy2, origin, target)) + visit(source, destination) + for future in as_completed(pending): + future.result() + for origin, target in reversed(directories): + shutil.copystat(origin, target) + return destination + + +def copy_readonly_benchmark(source, destination, verify_contents=False): + """Change permissions only on a private local copy of the input mount.""" + source, destination = Path(source), Path(destination) + if destination.exists(): + raise RuntimeError('Expected a fresh local benchmark directory') + shutil.copytree(source, destination, symlinks=False) + hashes = {} + def digest_file(path): + digest = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(block) + return digest.hexdigest() + for path in [destination, *destination.rglob('*')]: + path.chmod(0o555 if path.is_dir() else 0o444) + if verify_contents and path.is_file(): + relative = path.relative_to(destination) + digest = digest_file(path) + if digest_file(source / relative) != digest: + raise RuntimeError(f'Local benchmark copy differs: {relative}') + hashes[str(relative)] = digest + return dict(source_permissions_modified=False, verified_file_sha256=hashes) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + adapted = cfg.get('adapted_permissions', False) + if adapted: + import adapted_boundary + adapted_boundary.no_new_privileges() + os.setgroups([]) + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + crystal_cache_receipt = None + if cfg.get('isolated_crystal_dataset_cache'): + if plan['task'] != 'crystal-structure-generation' or phase != 'score': + raise RuntimeError('Crystal cache isolation is for trusted grading only') + import crystal_cache + crystal_cache_receipt = crystal_cache.prepare( + '/scorer-assets/huggingface/datasets', os.environ['HF_DATASETS_CACHE']) + crystal_cache_receipt['asset_manifest_sha256'] = hashlib.sha256( + Path('/scorer-assets/READY.json').read_bytes()).hexdigest() + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if cfg.get('local_benchmark_copy'): + status('copying_benchmark', task=plan['task'], role=phase) + # The GPU Landlock policy grants existing root children. Create this + # local root child first, so the later policy can grant it read access. + # This is trusted input staging; no submitted code has run yet. + receipt = copy_readonly_benchmark('/source-benchmark', '/benchmark', + cfg.get('verify_benchmark_copy', False)) + runtime.write_json(STATE / 'benchmark-copy.json', receipt) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus'], strict_allocation=adapted) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + if adapted: + adapted_boundary.exact_gpu_allocation(gpu_policy) + else: + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + if cfg.get('gpu_runtime', 'torch') == 'torch' and not adapted: + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + copy_workers = 1 + if phase == 'inference': + if (plan['task'] == 'mass-spectrometry-molecule-retrieval' + and cfg.get('exclude_setup_from_budget')): + copy_workers = min(8, cpus) + status('copying_submission', task=plan['task'], role=phase, copy_workers=copy_workers) + if cfg.get('native_uid_isolation'): + # The original PDE verifier explicitly supports this UID fallback. + # The mount is below a local root-only parent, never chmod shared data. + Path('/private').chmod(0o700) + Path('/tests').chmod(0o700) + elif plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + copy_submission('/submission-source', package, workers=copy_workers) + status('checking_submission', task=plan['task'], role=phase) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + try: + agent = pwd.getpwuid(10001) + except KeyError: + subprocess.run(['/usr/sbin/useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + status('setting_submission_permissions', task=plan['task'], role=phase) + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + # Some native images precreate this empty container-local mountpoint. + # rmdir fails closed if it contains anything; never remove existing logs. + if Path('/logs/verifier').is_dir() and not Path('/logs/verifier').is_symlink(): + Path('/logs/verifier').rmdir() + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + if adapted and cfg.get('network_policy') != 'policy-children-only': + adapted_boundary.restrict_network() + elif not offline and not adapted: + runtime.deny_network() + if not adapted: + writable_roots = ['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc', + *cfg.get('writable_runtime_paths', [])] + if crystal_cache_receipt: + # The native image links /scorer-assets beneath /workspace. A + # writable ancestor defeats a read-only Landlock child rule. + # Trusted grading needs its output and scratch directories only. + writable_roots.remove('/workspace') + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets', + *cfg.get('readonly_runtime_paths', [])], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=writable_roots) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + if adapted: + source_audit = adapted_boundary.audit_source_permissions( + ['/operator', '/submission-source', '/source-benchmark', '/benchmark', '/data', '/labels', '/private'], + untrusted_uids=tuple(range(10001, 10009))) + else: + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if crystal_cache_receipt: + try: + fd = os.open('/scorer-assets/READY.json', os.O_WRONLY | os.O_CLOEXEC) + except PermissionError: + crystal_cache_receipt['asset_write_denied'] = True + else: + os.close(fd) + raise RuntimeError('Prepared scorer assets remain writable') + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' and not adapted else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())); ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + if cfg.get('gpu_runtime') == 'jax': + probe = ('import jax; import jax.numpy as jnp; ' + f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in d.device_kind for d in jax.devices("gpu")); ' + 'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 ' + 'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + if adapted and plan['task'] == 'fluid-flow-control': + # native_runtime.sh loads a module-provided libpython. Preserve + # only these runtime settings, never credentials, in the probe. + for key in ('PATH', 'LD_LIBRARY_PATH', 'OMP_NUM_THREADS', + 'OPENBLAS_NUM_THREADS', 'XLA_PYTHON_CLIENT_PREALLOCATE'): + if key in os.environ: + probe_env[key] = os.environ[key] + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + def dependency_identity(): + os.setgroups([]); os.setgid(10001); os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + cache=Path('/tmp/verifier-cache');cache.mkdir(exist_ok=True) + os.chown(cache,10001,10001) + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True, + preexec_fn=dependency_identity if cfg.get('untrusted_whole_verifier') else None) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': ('seccomp in unprivileged policy children; trusted simulator retains MPI sockets' + if cfg.get('network_policy') == 'policy-children-only' else + 'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children'), + 'offline_namespace': offline, + 'source_mounts': f'POSIX permission audit ({source_audit} entries); non-root submission' if adapted else 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan.get('label_isolated', plan['task'] != 'protein-folding-prediction'), + 'adapted_execution': adapted, + 'scientific_scorer_modified': False, + 'submission_copy_workers': copy_workers if phase == 'inference' else None, + 'verifier_budget_scope': ('native_commands' if cfg.get('exclude_setup_from_budget') + else 'worker_including_setup')} + runtime.write_json(STATE / 'preflight.json', receipt) + command_started = time.monotonic() + status('verifying', task=plan['task'], role=phase, + setup_seconds=command_started-entered, + verifier_budget_scope=receipt['verifier_budget_scope']) + with (STATE / 'verifier.log').open('w') as log: + result, budget_started = run_verifier_command(cfg, log, entered) + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + if cfg.get('verify_crystal_assets_after'): + remaining = cfg['timeout_seconds'] - (time.monotonic() - budget_started) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted before post-score asset validation') + with (STATE / 'asset-validation-after.log').open('w') as log: + subprocess.run([cfg['driver_python'], '-c', + 'import sys;sys.path.insert(0,"/tests");from pathlib import Path;' + 'from grader import validate_assets;validate_assets(Path("/scorer-assets"));' + 'print("ORIGINAL_SCORER_ASSET_DIGEST_OK")'], + stdout=log, stderr=subprocess.STDOUT, timeout=remaining, check=True) + if hashlib.sha256(Path('/scorer-assets/READY.json').read_bytes()).hexdigest() != crystal_cache_receipt['asset_manifest_sha256']: + raise RuntimeError('Scorer asset manifest changed during grading') + crystal_cache_receipt['original_asset_digest_after'] = 'passed' + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + finished = time.monotonic() + elapsed = finished - budget_started + reward_path = STATE / 'results/reward.json' + if phase == 'score': + score_root = Path('/sealed/results') + if cfg.get('results_by_run_id'): + score_root /= json.loads(Path('/sealed/READY').read_text())['run_id'] + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = score_root / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + wall_elapsed_seconds=finished-entered, setup_seconds=command_started-entered, + verifier_budget_scope=receipt['verifier_budget_scope'], reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/49/49e0a49aeee7fef5e4304dc332982987ec80aad60c4979bb4e1400a56177319c/test_alphaqubit_training.py b/reproduction/files/49/49e0a49aeee7fef5e4304dc332982987ec80aad60c4979bb4e1400a56177319c/test_alphaqubit_training.py new file mode 100644 index 0000000000000000000000000000000000000000..4fddbdf130d60e71b3965c7b94fa60028c01b719 --- /dev/null +++ b/reproduction/files/49/49e0a49aeee7fef5e4304dc332982987ec80aad60c4979bb4e1400a56177319c/test_alphaqubit_training.py @@ -0,0 +1,171 @@ +"""Tests for sampling/optimizer resume, LER selection and anchored LAMB. + +Run with JAX_PLATFORMS=cpu to include the bitwise resume contract. +""" +from __future__ import annotations + +import json +from pathlib import Path + +import jax +import jax.numpy as jnp +import numpy as np +import pytest +import stim + +from baselines.alphaqubit_model import AlphaQubitConfig +from baselines.alphaqubit_train import ( + FACTORS, add_anchored_decay, argument_parser, curriculum_probabilities, + fit_validation, learning_rate, load_internal, load_portable, + make_update, publish_best, run_training, +) + + +def small_config() -> AlphaQubitConfig: + return AlphaQubitConfig(3, width=4, heads=1, key_size=2, value_size=2, + layers=1, conv_width=2, widening=2, feature_layers=1, + bias_width=2, bias_layers=1, readout_width=2, readout_layers=1) + + +def make_data(root: Path) -> None: + root.mkdir() + for rounds in range(1, 26, 2): + directory = root / f"surface_code_bX_d3_r{rounds:02d}_center_3_5" + directory.mkdir() + ideal = stim.Circuit.generated("surface_code:rotated_memory_x", distance=3, rounds=rounds) + noisy = stim.Circuit.generated("surface_code:rotated_memory_x", distance=3, rounds=rounds, + after_clifford_depolarization=0.01, before_measure_flip_probability=0.02) + ideal.to_file(directory / "circuit_ideal.stim") + noisy.detector_error_model(decompose_errors=True).to_file(directory / "pij_from_even_for_odd.dem") + + +def args_for(data: Path, output: Path, steps: int, resume: bool = False): + return argument_parser().parse_args([ + "--data-root", str(data), "--group", "d3_bX_center_3_5", "--output", str(output), + "--hours", "1", "--max-steps", str(steps), "--microbatch", "2", "--eval-shots", "4", + "--eval-seconds", "99999", "--seed", "17", "--allow-cpu", *( ["--resume"] if resume else []), + ]) + + +def assert_tree_equal(left, right) -> None: + assert jax.tree.structure(left) == jax.tree.structure(right) + for a, b in zip(jax.tree.leaves(left), jax.tree.leaves(right), strict=True): + np.testing.assert_array_equal(a, b) + + +def test_paper_schedules_and_literal_batch_counter_default() -> None: + probabilities = curriculum_probabilities(12_800_000) + assert probabilities.argmax() == 0 # Logistic midpoint f=0.5. + assert probabilities[0] / probabilities[-1] == pytest.approx(13.0) + assert curriculum_probabilities(200_000_000).argmax() == len(FACTORS) - 1 + assert np.sum(probabilities) == pytest.approx(1.0) + assert learning_rate(3, 0) == pytest.approx(3.46e-8) + assert learning_rate(5, 9999) == pytest.approx(2.45e-4) + assert learning_rate(5, 80000) == pytest.approx(2.45e-4 * 0.7) + assert learning_rate(5, 2000000) == pytest.approx(2.45e-4 * 0.7**5) + args = argument_parser().parse_args(["--data-root", "/tmp/data", "--group", "g", "--output", "/tmp/out", "--hours", "1"]) + assert args.batch_change_counter == "steps" and args.microbatch == 256 + + +def test_anchored_nonbias_decay_and_microbatch_accumulation() -> None: + params = {"linear": {"w": jnp.array([0.25, -0.5]), "b": jnp.array([0.125]), "offset": jnp.array([0.2])}} + anchor = jax.tree.map(lambda value: value * 0.5, params) + zeros = jax.tree.map(jnp.zeros_like, params) + direction = add_anchored_decay(zeros, params, anchor, 0.08) + np.testing.assert_allclose(direction["linear"]["w"], [0.01, -0.02]) + np.testing.assert_array_equal(direction["linear"]["b"], [0.]) + np.testing.assert_array_equal(direction["linear"]["offset"], [0.]) + assert_tree_equal(add_anchored_decay(zeros, params, params, 0.08), zeros) + + class LinearModel: + @staticmethod + def apply(weights, features): + logits = features["measurements"][:, 0, :] @ weights["linear"]["w"] + weights["linear"]["b"][0] + return {"logits": logits, "next_stabilizer_logits": jnp.zeros((len(logits), 2, 2))} + + measurements = jnp.arange(16, dtype=jnp.float32).reshape(4, 2, 2) / 8 + features = {"measurements": measurements, "events": measurements, "previous_events": measurements, + "valid_mask": jnp.ones((2, 2), dtype=bool), "is_final": jnp.array([False, True])} + labels = jnp.array([[0.], [1.], [0.], [1.]]) + outcomes = [] + # Compare the mathematical accumulation at FP32 precision: differently + # shaped GPU matmuls may otherwise select different TF32 kernels. + with jax.default_matmul_precision("highest"): + for microbatch in (1, 4): + adam, update = make_update(LinearModel(), microbatch, 0.08) + outcomes.append(update(params, adam.init(params), params, anchor, features, labels, jnp.array(1e-3))) + for a, b in zip(jax.tree.leaves(outcomes[0]), jax.tree.leaves(outcomes[1]), strict=True): + np.testing.assert_allclose(a, b, rtol=3e-6, atol=2e-7) + updated, _, ema, _ = outcomes[0] + expected_ema = jax.tree.map(lambda old, new: old + 0.0001 * (new - old), params, updated) + assert_tree_equal(ema, expected_ema) + + +def counts_for_fit(intercept: float = 0.002) -> list[dict]: + rows = [] + for rounds in range(1, 26, 2): + fidelity = np.exp(intercept + rounds * np.log(1 - 2 * 0.02)) + total = 1_000_000 + rows.append({"condition": f"surface_code_bX_d3_r{rounds:02d}_center_3_5", + "rounds": rounds, "errors": int(round((1 - fidelity) / 2 * total)), "shots": total}) + return rows + + +def test_validation_gate_never_selects_chance_or_bad_intercept() -> None: + fit = fit_validation(counts_for_fit()) + assert fit["accepted"] and fit["logical_error_per_round"] == pytest.approx(0.02, abs=1e-6) + assert fit["selection_r_squared"] > 0.999 + low_intercept = fit_validation(counts_for_fit(-0.2)) + assert not low_intercept["accepted"] + assert "intercept_below_paper_cutoff" in low_intercept["rejection_reasons"] + chance = counts_for_fit() + chance[-1]["errors"] = chance[-1]["shots"] // 2 + invalid = fit_validation(chance) + assert not invalid["accepted"] and invalid["logical_error_per_round"] is None + + +@pytest.mark.skipif( + jax.default_backend() != "cpu", + reason="Bitwise resume requires JAX_PLATFORMS=cpu; GPU JIT reductions are not bitwise stable.", +) +def test_native_training_resume_reproduces_optimizer_rng_data_and_portable_params(tmp_path: Path) -> None: + data = tmp_path / "data" + make_data(data) + interrupted, continuous = tmp_path / "resumed", tmp_path / "continuous" + options = dict(config_override=small_config(), initial_batch_size=4, final_batch_size=8) + first = run_training(args_for(data, interrupted, 2), **options) + assert first["global_steps"] == 2 and first["seen_samples"] == 8 and first["stop_reason"] == "max_steps" + before = load_internal(interrupted / "last.pkl") + assert int(before["opt_state"].count) == 2 + with pytest.raises(FileExistsError, match="Nonempty"): + run_training(args_for(data, interrupted, 3), **options) + resumed = run_training(args_for(data, interrupted, 4, resume=True), **options) + full = run_training(args_for(data, continuous, 4), **options) + a, b = load_internal(interrupted / "last.pkl"), load_internal(continuous / "last.pkl") + for key in ("params", "ema", "opt_state", "jax_rng"): + assert_tree_equal(a[key], b[key]) + assert a["numpy_rng"] == b["numpy_rng"] and a["samplers"] == b["samplers"] + assert resumed["global_steps"] == full["global_steps"] == 4 + assert resumed["seen_samples"] == full["seen_samples"] == 16 + assert int(a["opt_state"].count) == 4 + assert resumed["elapsed_seconds"] > first["elapsed_seconds"] + metadata = json.loads((interrupted / "metadata.json").read_text()) + assert len(metadata["sessions"]) == 2 and all(session.get("ended_at") for session in metadata["sessions"]) + assert metadata["sessions"][1]["resume_seen_samples"] == 8 + # Portable export is tested with an explicit synthetic accepted-selection + # fixture; tiny random models are not misrepresented as valid LER fits. + a["best_params"] = a["params"] + a["best_validation"] = {"global_steps": 4, "seen_samples": 16, "fit": fit_validation(counts_for_fit())} + publish_best(interrupted, a, metadata["identity"]) + restored, description = load_portable(interrupted / "best.npz") + assert_tree_equal(restored, a["params"]) + assert description["selected_LER"] == pytest.approx(0.02, abs=1e-6) + # Changing a semantic identity or the source fingerprints cannot resume. + altered = args_for(data, interrupted, 5, resume=True) + altered.seed += 1 + with pytest.raises(ValueError, match="identity changed"): + run_training(altered, **options) + changed_initializer = args_for(data, interrupted, 5, resume=True) + changed_initializer.init_model = interrupted / "best.npz" + with pytest.raises(ValueError, match="initializer checkpoint SHA changed"): + run_training(changed_initializer, **options) diff --git a/reproduction/files/4b/4b5267cbb4325dc7dc4c732c99d90c24f8d54253a664442fcb999937f8a76aa2/probes.py b/reproduction/files/4b/4b5267cbb4325dc7dc4c732c99d90c24f8d54253a664442fcb999937f8a76aa2/probes.py new file mode 100644 index 0000000000000000000000000000000000000000..7b63e16d9616f87a93e5323d6b77cfa3b45738fa --- /dev/null +++ b/reproduction/files/4b/4b5267cbb4325dc7dc4c732c99d90c24f8d54253a664442fcb999937f8a76aa2/probes.py @@ -0,0 +1,131 @@ +"""Frozen probes, validation-only selection, explicit final-test switch.""" + +import argparse +import json +from pathlib import Path +import numpy as np +from sklearn.linear_model import LogisticRegression, Ridge +from sklearn.metrics import ( + accuracy_score, + balanced_accuracy_score, + mean_absolute_error, + mean_squared_error, + r2_score, +) +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler + + +def metric(y, p, task): + if task == "awf": + return { + "accuracy": accuracy_score(y, p), + "balanced_accuracy": balanced_accuracy_score(y, p), + } + return { + "mae": mean_absolute_error(y, p), + "rmse": float(np.sqrt(mean_squared_error(y, p))), + "r2": r2_score(y, p), + } + + +def knn(train, y, query, k=20): + # Official cosine kNN: softmax-temperature 0.07, k=20, unstandardized embeddings. + a = train / np.maximum(np.linalg.norm(train, axis=1, keepdims=True), 1e-8) + b = query / np.maximum(np.linalg.norm(query, axis=1, keepdims=True), 1e-8) + sim = b @ a.T + ix = np.argsort(-sim, axis=1, kind="stable")[:, :k] + vals = np.take_along_axis(sim, ix, axis=1) + weights = np.exp((vals - vals.max(axis=1, keepdims=True)) / 0.07) + votes = (np.eye(9)[y[ix].astype(int)] * weights[:, :, None]).sum(axis=1) + return votes.argmax(axis=1) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--features", type=Path, required=True) + p.add_argument("--labels", type=Path, required=True) + p.add_argument("--task", choices=["awf", "lfmc"], required=True) + p.add_argument("--output", type=Path, required=True) + p.add_argument("--final-test", action="store_true") + p.add_argument("--validation-predictions", type=Path) + a = p.parse_args() + rows = json.loads(a.labels.read_text()) + z = np.load(a.features, allow_pickle=False) + if ( + z["ids"].ndim != 1 + or len(z["ids"]) != len(rows) + or len(z["features"]) != len(rows) + or len(set(z["ids"].tolist())) != len(rows) + or set(z["ids"].tolist()) != {r["id"] for r in rows} + ): + raise ValueError("IDs missing, duplicate or extra") + lookup = {s: i for i, s in enumerate(z["ids"].tolist())} + x = z["features"][[lookup[r["id"]] for r in rows]].astype(np.float64) + if x.ndim != 2 or not np.isfinite(x).all(): + raise ValueError("Nonfinite or invalid features") + y = np.array([r["label"] for r in rows]) + split = np.array([r["split"] for r in rows]) + tr, va, te = split == "train", split == "val", split == "test" + if not tr.any() or not va.any(): + raise ValueError("Missing official train or validation split") + result = { + "task": a.task, + "features": str(a.features), + "rows": {"train": int(tr.sum()), "val": int(va.sum()), "test": int(te.sum())}, + "dimension": x.shape[1], + } + constant = ( + float(np.bincount(y[tr].astype(int)).argmax()) + if a.task == "awf" + else float(y[tr].mean()) + ) + result["constant_val"] = metric(y[va], np.full(va.sum(), constant), a.task) + candidates = [] + best = None + grid = ( + [0.001, 0.01, 0.1, 1, 10, 100] + if a.task == "awf" + else [0.01, 0.1, 1, 10, 100, 1000, 10000] + ) + for param in grid: + estimator = ( + LogisticRegression(C=param, max_iter=3000, random_state=42) + if a.task == "awf" + else Ridge(alpha=param) + ) + model = make_pipeline(StandardScaler(), estimator).fit(x[tr], y[tr]) + scores = metric(y[va], model.predict(x[va]), a.task) + objective = scores["accuracy"] if a.task == "awf" else -scores["mae"] + candidates.append({"parameter": param, **scores}) + if best is None or objective > best[0]: + best = (objective, param, model, scores) + result["probe"] = { + "selected_parameter": best[1], + "validation": best[3], + "search": candidates, + } + if a.validation_predictions: + a.validation_predictions.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + a.validation_predictions, + ids=np.array([r["id"] for r in rows])[va], + predictions=best[2].predict(x[va]), + ) + result["validation_predictions"] = str(a.validation_predictions.resolve()) + if a.task == "awf": + result["knn_validation"] = metric(y[va], knn(x[tr], y[tr], x[va]), a.task) + if a.final_test: + if not te.any(): + raise ValueError( + "This release has no test split; cannot report a test score" + ) + result["probe"]["test"] = metric(y[te], best[2].predict(x[te]), a.task) + result["constant_test"] = metric(y[te], np.full(te.sum(), constant), a.task) + a.output.parent.mkdir(parents=True, exist_ok=True) + a.output.write_text(json.dumps(result, indent=2)) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/4d/4df90aa1c1aff89c2f5c851b174ffb9752f97a5acc4d04e04a6e93c8b48fa0a7/test_distributed.py b/reproduction/files/4d/4df90aa1c1aff89c2f5c851b174ffb9752f97a5acc4d04e04a6e93c8b48fa0a7/test_distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..42de044692177977aa3860e63c13cde5becb0329 --- /dev/null +++ b/reproduction/files/4d/4df90aa1c1aff89c2f5c851b174ffb9752f97a5acc4d04e04a6e93c8b48fa0a7/test_distributed.py @@ -0,0 +1,90 @@ +import pytest +from ase.build import bulk + +from common import encode_atoms, write_json, write_rows +from distributed import chunk_plan, merge +from predict import load_calculator, run + + +def cases(): + return [ + { + "id": f"discovery/copper-{i}", + "suite": "discovery", + "atoms": encode_atoms(bulk("Cu")), + } + for i in range(3) + ] + + +def test_chunk_plan_is_deterministic_and_exact(): + rows = cases() + plan = chunk_plan(rows) + assert plan == chunk_plan(rows[::-1]) + assert sorted(key for c in plan for key in c["case_ids"]) == sorted( + r["id"] for r in rows + ) + with pytest.raises(ValueError, match="Duplicate"): + chunk_plan(rows + rows[:1]) + + +def test_reused_calculator_and_strict_merge(tmp_path): + rows = cases() + plan = chunk_plan(rows) + canonical = tmp_path / "inputs.jsonl" + write_rows(canonical, rows) + chunk = plan[0] + idx = {r["id"]: r for r in rows} + chunk_inputs = tmp_path / "chunk-inputs.jsonl" + write_rows(chunk_inputs, [idx[k] for k in chunk["case_ids"]]) + destination = tmp_path / "chunks" / chunk["chunk_id"] + calculator = load_calculator("emt", None, "cpu") + run(chunk_inputs, destination, "emt", calculator=calculator, verbose=False) + (destination / "inputs.jsonl").write_bytes(chunk_inputs.read_bytes()) + write_json( + destination / "worker.json", + {"worker_id": "cpu-test", "chunk_input_sha256": chunk["input_sha256"]}, + ) + result = merge(canonical, tmp_path / "chunks", plan, tmp_path / "merged", None) + assert result["coverage"] == {"ok": 3} + assert result["suites"]["discovery"]["cases"] == 3 + # Corruption, even if all IDs remain present, cannot pass result assembly. + with (destination / "predictions.jsonl").open("a") as stream: + stream.write("\n") + with pytest.raises(ValueError, match="Corrupt"): + merge(canonical, tmp_path / "chunks", plan, tmp_path / "bad", None) + + +def test_merge_rejects_missing_or_duplicated_work(tmp_path): + path = tmp_path / "inputs.jsonl" + write_rows(path, cases()) + plan = chunk_plan(cases()) + with pytest.raises(ValueError, match="exactly cover"): + merge(path, tmp_path / "chunks", plan + plan, tmp_path / "bad", None) + with pytest.raises(FileNotFoundError): + merge(path, tmp_path / "chunks", plan, tmp_path / "missing", None) + + +def test_time_limit_merge_keeps_finished_chunks_and_fails_the_rest(tmp_path): + rows = [dict(r, id=f"discovery/copper-{i}") for i, r in enumerate(cases() * 70)] # 210 cases: 2 chunks + plan = chunk_plan(rows) + assert len(plan) == 2 + canonical = tmp_path / "inputs.jsonl" + write_rows(canonical, rows) + idx = {r["id"]: r for r in rows} + finished = plan[0] + chunk_inputs = tmp_path / "chunk-inputs.jsonl" + write_rows(chunk_inputs, [idx[k] for k in finished["case_ids"]]) + destination = tmp_path / "chunks" / finished["chunk_id"] + run(chunk_inputs, destination, "emt", calculator=load_calculator("emt", None, "cpu"), verbose=False) + (destination / "inputs.jsonl").write_bytes(chunk_inputs.read_bytes()) + write_json(destination / "worker.json", + {"worker_id": "cpu-test", "chunk_input_sha256": finished["input_sha256"]}) + with pytest.raises(FileNotFoundError): # without the time limit an unfinished chunk is an error + merge(canonical, tmp_path / "chunks", plan, tmp_path / "strict", None) + result = merge(canonical, tmp_path / "chunks", plan, tmp_path / "merged", None, + unfinished_reason="verifier time limit reached") + assert result["coverage"] == {"ok": len(finished["case_ids"]), "failed": len(plan[1]["case_ids"])} + import json + meta = json.loads((tmp_path / "merged" / "run.json").read_text()) + assert meta["complete"] and meta["unfinished_cases"] == len(plan[1]["case_ids"]) diff --git a/reproduction/files/4e/4e1fe7a4815aae07c879860ad3bd010201448c22940a0c952cf741d77a9a0924/native_verifier.py b/reproduction/files/4e/4e1fe7a4815aae07c879860ad3bd010201448c22940a0c952cf741d77a9a0924/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..131bc32bb364760f8d84f001aea2386059876cb4 --- /dev/null +++ b/reproduction/files/4e/4e1fe7a4815aae07c879860ad3bd010201448c22940a0c952cf741d77a9a0924/native_verifier.py @@ -0,0 +1,415 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import re +import shutil +import signal +import socket +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def enter_offline_namespace(): + import offline_network + record = offline_network.configure(STATE) + libc = ctypes.CDLL(None, use_errno=True) + for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)): + fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC) + try: + if libc.setns(fd, flag): + raise OSError(ctypes.get_errno(), 'enter offline verifier namespace') + finally: + os.close(fd) + if socket.if_nameindex() != [(1, 'lo')]: + raise RuntimeError('Offline verifier namespace has external interfaces') + return record + + +def validate_ready_marker(sealed_root): + """Accept either upstream seal format, always checking the exact snapshot. + +Surface-code uses JSON with a run ID. Molecular, Genome and Protein-sequence +use a plain SHA-256 line. The original scientific grader rechecks the seal. +""" + root = Path(sealed_root) + raw = (root/'READY').read_text().strip() + snapshot = root/'run/snapshot.json' + observed = hashlib.sha256(snapshot.read_bytes()).hexdigest() + if re.fullmatch('[0-9a-f]{64}', raw): + if raw != observed: + raise RuntimeError('Native seal marker is inconsistent') + return + marker = json.loads(raw) + if (not isinstance(marker, dict) or marker.get('snapshot_sha256') != observed + or not isinstance(marker.get('run_id'), str) + or json.loads(snapshot.read_text()).get('run_id') != marker['run_id']): + raise RuntimeError('Native seal marker is inconsistent') + + +def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')): + """End the native waiting supervisor only after its authenticated seal.""" + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + seconds + sealed_ready = False + try: + while process.poll() is None: + if (sealed_root / 'READY').is_file(): + validate_ready_marker(sealed_root) + sealed_ready = True + break + if time.monotonic() >= deadline: + raise TimeoutError('Verifier inference budget exhausted') + time.sleep(.1) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode) + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def run_verifier_command(cfg, log, entered): + """Apply the native deadline after staging when the frozen plan opts in. + + Harbor 0.23 uploads artifacts before entering the separate verifier's + asyncio.wait_for. Older Beaker plans retain their original inclusive clock. + The returned clock origin also covers any post-command validation. + """ + started = time.monotonic() if cfg.get('exclude_setup_from_budget') else entered + remaining = cfg['timeout_seconds'] - (time.monotonic() - started) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + if cfg.get('stop_after_sealed_ready'): + result = run_until_sealed(cfg['command'], log, remaining) + else: + def run_identity(): + os.setgroups([]) + os.setgid(10001) + os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + os.chown(STATE / 'results', 10001, 10001) + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True, + preexec_fn=run_identity if cfg.get('untrusted_whole_verifier') else None) + return result, started + + +def copy_readonly_benchmark(source, destination, verify_contents=False): + """Change permissions only on a private local copy of the input mount.""" + source, destination = Path(source), Path(destination) + if destination.exists(): + raise RuntimeError('Expected a fresh local benchmark directory') + shutil.copytree(source, destination, symlinks=False) + hashes = {} + def digest_file(path): + digest = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(block) + return digest.hexdigest() + for path in [destination, *destination.rglob('*')]: + path.chmod(0o555 if path.is_dir() else 0o444) + if verify_contents and path.is_file(): + relative = path.relative_to(destination) + digest = digest_file(path) + if digest_file(source / relative) != digest: + raise RuntimeError(f'Local benchmark copy differs: {relative}') + hashes[str(relative)] = digest + return dict(source_permissions_modified=False, verified_file_sha256=hashes) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + adapted = cfg.get('adapted_permissions', False) + if adapted: + import adapted_boundary + adapted_boundary.no_new_privileges() + os.setgroups([]) + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + crystal_cache_receipt = None + if cfg.get('isolated_crystal_dataset_cache'): + if plan['task'] != 'crystal-structure-generation' or phase != 'score': + raise RuntimeError('Crystal cache isolation is for trusted grading only') + import crystal_cache + crystal_cache_receipt = crystal_cache.prepare( + '/scorer-assets/huggingface/datasets', os.environ['HF_DATASETS_CACHE']) + crystal_cache_receipt['asset_manifest_sha256'] = hashlib.sha256( + Path('/scorer-assets/READY.json').read_bytes()).hexdigest() + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if cfg.get('local_benchmark_copy'): + status('copying_benchmark', task=plan['task'], role=phase) + # The GPU Landlock policy grants existing root children. Create this + # local root child first, so the later policy can grant it read access. + # This is trusted input staging; no submitted code has run yet. + receipt = copy_readonly_benchmark('/source-benchmark', '/benchmark', + cfg.get('verify_benchmark_copy', False)) + runtime.write_json(STATE / 'benchmark-copy.json', receipt) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus'], strict_allocation=adapted) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + if adapted: + adapted_boundary.exact_gpu_allocation(gpu_policy) + else: + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + if cfg.get('gpu_runtime', 'torch') == 'torch' and not adapted: + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + if phase == 'inference': + status('copying_submission', task=plan['task'], role=phase) + if cfg.get('native_uid_isolation'): + # The original PDE verifier explicitly supports this UID fallback. + # The mount is below a local root-only parent, never chmod shared data. + Path('/private').chmod(0o700) + Path('/tests').chmod(0o700) + elif plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + status('checking_submission', task=plan['task'], role=phase) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + try: + agent = pwd.getpwuid(10001) + except KeyError: + subprocess.run(['/usr/sbin/useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + status('setting_submission_permissions', task=plan['task'], role=phase) + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + # Some native images precreate this empty container-local mountpoint. + # rmdir fails closed if it contains anything; never remove existing logs. + if Path('/logs/verifier').is_dir() and not Path('/logs/verifier').is_symlink(): + Path('/logs/verifier').rmdir() + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + if adapted and cfg.get('network_policy') != 'policy-children-only': + adapted_boundary.restrict_network() + elif not offline and not adapted: + runtime.deny_network() + if not adapted: + writable_roots = ['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc', + *cfg.get('writable_runtime_paths', [])] + if crystal_cache_receipt: + # The native image links /scorer-assets beneath /workspace. A + # writable ancestor defeats a read-only Landlock child rule. + # Trusted grading needs its output and scratch directories only. + writable_roots.remove('/workspace') + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets', + *cfg.get('readonly_runtime_paths', [])], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=writable_roots) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + if adapted: + source_audit = adapted_boundary.audit_source_permissions( + ['/operator', '/submission-source', '/source-benchmark', '/benchmark', '/data', '/labels', '/private'], + untrusted_uids=tuple(range(10001, 10009))) + else: + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if crystal_cache_receipt: + try: + fd = os.open('/scorer-assets/READY.json', os.O_WRONLY | os.O_CLOEXEC) + except PermissionError: + crystal_cache_receipt['asset_write_denied'] = True + else: + os.close(fd) + raise RuntimeError('Prepared scorer assets remain writable') + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' and not adapted else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())); ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + if cfg.get('gpu_runtime') == 'jax': + probe = ('import jax; import jax.numpy as jnp; ' + f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in d.device_kind for d in jax.devices("gpu")); ' + 'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 ' + 'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + if adapted and plan['task'] == 'fluid-flow-control': + # native_runtime.sh loads a module-provided libpython. Preserve + # only these runtime settings, never credentials, in the probe. + for key in ('PATH', 'LD_LIBRARY_PATH', 'OMP_NUM_THREADS', + 'OPENBLAS_NUM_THREADS', 'XLA_PYTHON_CLIENT_PREALLOCATE'): + if key in os.environ: + probe_env[key] = os.environ[key] + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + def dependency_identity(): + os.setgroups([]); os.setgid(10001); os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + cache=Path('/tmp/verifier-cache');cache.mkdir(exist_ok=True) + os.chown(cache,10001,10001) + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True, + preexec_fn=dependency_identity if cfg.get('untrusted_whole_verifier') else None) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': ('seccomp in unprivileged policy children; trusted simulator retains MPI sockets' + if cfg.get('network_policy') == 'policy-children-only' else + 'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children'), + 'offline_namespace': offline, + 'source_mounts': f'POSIX permission audit ({source_audit} entries); non-root submission' if adapted else 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan.get('label_isolated', plan['task'] != 'protein-folding-prediction'), + 'adapted_execution': adapted, + 'scientific_scorer_modified': False, + 'verifier_budget_scope': ('native_commands' if cfg.get('exclude_setup_from_budget') + else 'worker_including_setup')} + runtime.write_json(STATE / 'preflight.json', receipt) + command_started = time.monotonic() + status('verifying', task=plan['task'], role=phase, + setup_seconds=command_started-entered, + verifier_budget_scope=receipt['verifier_budget_scope']) + with (STATE / 'verifier.log').open('w') as log: + result, budget_started = run_verifier_command(cfg, log, entered) + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + if cfg.get('verify_crystal_assets_after'): + remaining = cfg['timeout_seconds'] - (time.monotonic() - budget_started) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted before post-score asset validation') + with (STATE / 'asset-validation-after.log').open('w') as log: + subprocess.run([cfg['driver_python'], '-c', + 'import sys;sys.path.insert(0,"/tests");from pathlib import Path;' + 'from grader import validate_assets;validate_assets(Path("/scorer-assets"));' + 'print("ORIGINAL_SCORER_ASSET_DIGEST_OK")'], + stdout=log, stderr=subprocess.STDOUT, timeout=remaining, check=True) + if hashlib.sha256(Path('/scorer-assets/READY.json').read_bytes()).hexdigest() != crystal_cache_receipt['asset_manifest_sha256']: + raise RuntimeError('Scorer asset manifest changed during grading') + crystal_cache_receipt['original_asset_digest_after'] = 'passed' + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + finished = time.monotonic() + elapsed = finished - budget_started + reward_path = STATE / 'results/reward.json' + if phase == 'score': + score_root = Path('/sealed/results') + if cfg.get('results_by_run_id'): + score_root /= json.loads(Path('/sealed/READY').read_text())['run_id'] + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = score_root / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + wall_elapsed_seconds=finished-entered, setup_seconds=command_started-entered, + verifier_budget_scope=receipt['verifier_budget_scope'], reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/4f/4f1b8e8ddf800e9d2488fd7ae273672cf6ee62c40e63a2e407622c1e2017cdfc/aggregate.py b/reproduction/files/4f/4f1b8e8ddf800e9d2488fd7ae273672cf6ee62c40e63a2e407622c1e2017cdfc/aggregate.py new file mode 100644 index 0000000000000000000000000000000000000000..55854c2a37f0bf1a725fc52fff79ff273faf057e --- /dev/null +++ b/reproduction/files/4f/4f1b8e8ddf800e9d2488fd7ae273672cf6ee62c40e63a2e407622c1e2017cdfc/aggregate.py @@ -0,0 +1,143 @@ +"""Fixed scores: historical three-suite v1 and expanded eight-suite v2.""" + +import math + +VERSION = "crystal-potential-score-v1" +# Frozen before the scratch trial, from standard-500k-20260923-01 validation. +# HF release 1177b47d5c221602ec13216bf1dc3955ca9dc247, +# records/physical/3ep/score.json. Reuse these constants on validation AND test. +REFERENCE = { + "F1": 0.8563218390804598, + "avg_freq_MAE_K": 19.767337214745005, + "bulk_MAE_GPa": 4.852471740287598, + "shear_MAE_GPa": 9.989963350875858, +} + + +def aggregate_score(metrics, *, valid=True): + """100 is ideal; the calibration profile scores 50; failed runs score zero. + + A partial diagnostic panel has no aggregate. All raw metrics remain available. + This is a task-specific index, not an official score of the source benchmarks. + """ + result = {"version": VERSION, "score": 0.0, "higher_is_better": True} + if not valid: + return {**result, "reason": "invalid evaluation"} + if not {"discovery", "phonons", "elasticity"} <= metrics.keys(): + return {**result, "score": None, "reason": "requires all three suites"} + f1 = metrics["discovery"]["F1"] + phonon = metrics["phonons"]["avg_freq"]["MAE"] + bulk = metrics["elasticity"]["bulk_modulus_vrh"]["MAE"] + shear = metrics["elasticity"]["shear_modulus_vrh"]["MAE"] + if ( + not all( + isinstance(v, (int, float)) and math.isfinite(v) + for v in [f1, phonon, bulk, shear] + ) + or not 0 <= f1 <= 1 + or min(phonon, bulk, shear) < 0 + ): + raise ValueError("Invalid primary metric for aggregate score") + errors = { + "discovery": (1 - f1) / (1 - REFERENCE["F1"]), + "phonons": phonon / REFERENCE["avg_freq_MAE_K"], + "elasticity": 0.5 + * (bulk / REFERENCE["bulk_MAE_GPa"] + shear / REFERENCE["shear_MAE_GPa"]), + } + if not all(math.isfinite(v) for v in errors.values()): + raise ValueError("Nonfinite normalized aggregate error") + result.update( + score=100 * math.exp(-sum(math.log1p(v) for v in errors.values()) / 3), + suite_scores={k: 100 / (1 + v) for k, v in errors.items()}, + normalized_errors=errors, + reference=REFERENCE, + ) + return result + + +VERSION_V2 = "crystal-potential-score-v2" +# Frozen from the rounded VALIDATION column of PR90's MP three-epoch reference +# (uma-mp-finetune/RESULTS.md at 6d61c37). These are scale constants, not targets +# fitted to scratch results or test labels. Reuse unchanged on validation/test. +REFERENCE_V2 = { + "discovery_F1": 0.856, + "phonon_avg_freq_MAE_K": 18.2, + "bulk_modulus_MAE_GPa": 5.560, + "shear_modulus_MAE_GPa": 7.277, + "kappa_SRME": 0.455, + "mof_bulk_modulus_MAPE_pct": 26.6, + "amorphous_energy_RelRMSE_pct": 8.780, + "amorphous_force_RelRMSE_pct": 14.8, + "cleavage_relMAE_pct": 6.598, + "neb_barrier_MAE_eV": 0.147, +} +SUITE_INPUTS_V2 = { + "discovery": ("discovery_F1",), + "phonons": ("phonon_avg_freq_MAE_K",), + "elasticity": ("bulk_modulus_MAE_GPa", "shear_modulus_MAE_GPa"), + "kappa": ("kappa_SRME",), + "mof": ("mof_bulk_modulus_MAPE_pct",), + "amorphous": ("amorphous_energy_RelRMSE_pct", "amorphous_force_RelRMSE_pct"), + "cleavage": ("cleavage_relMAE_pct",), + "neb": ("neb_barrier_MAE_eV",), +} + + +def expanded_score(metrics, *, valid=True): + """Consume the grader's flat raw metrics; missing/invalid suites score zero. + + Average normalized errors within each suite, then geometrically average + 100/(1+error) across eight suites. Case counts cannot change suite weights. + The historical three-suite function above is deliberately unchanged. + """ + result = {"version": VERSION_V2, "score": 0.0, "higher_is_better": True} + if not valid: + return {**result, "reason": "invalid evaluation"} + normalized = {} + for key, reference in REFERENCE_V2.items(): + value = metrics.get(key) + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) + or value < 0 + or (key == "discovery_F1" and value > 1) + ): + return {**result, "reason": f"missing or invalid primary metric: {key}"} + normalized[key] = ( + (1 - value) / (1 - reference) + if key == "discovery_F1" + else value / reference + ) + if not math.isfinite(normalized[key]): + return {**result, "reason": f"nonfinite normalized error: {key}"} + errors = { + suite: sum(normalized[key] / len(keys) for key in keys) + for suite, keys in SUITE_INPUTS_V2.items() + } + return { + **result, + "score": 100 * math.exp(-sum(math.log1p(v) for v in errors.values()) / 8), + "suite_scores": {key: 100 / (1 + value) for key, value in errors.items()}, + "normalized_errors": errors, + "reference": REFERENCE_V2, + } + + +if __name__ == "__main__": + import argparse + import json + from pathlib import Path + + parser = argparse.ArgumentParser( + description="Score a JSON of flat validation metrics" + ) + parser.add_argument("--metrics", type=Path, required=True) + args = parser.parse_args() + print( + json.dumps( + expanded_score(json.loads(args.metrics.read_text())), + indent=2, + allow_nan=False, + ) + ) diff --git a/reproduction/files/51/51f19cc5b701394c12a4d9a487cd5f3c7eea17089a204a347803c840398e41c4/fly_boundary.py b/reproduction/files/51/51f19cc5b701394c12a4d9a487cd5f3c7eea17089a204a347803c840398e41c4/fly_boundary.py new file mode 100644 index 0000000000000000000000000000000000000000..b12bbbdbac8483eb51d80b5c2d17b3d56f72c94d --- /dev/null +++ b/reproduction/files/51/51f19cc5b701394c12a4d9a487cd5f3c7eea17089a204a347803c840398e41c4/fly_boundary.py @@ -0,0 +1,51 @@ +"""Adapt only Pathfinder prediction isolation on namespace-restricted Beaker hosts. + +The pinned verifier stages data-only weights and calls the unchanged trusted +pipeline. No submitted Python/native code is executed. Private labels remain +behind a root-only parent; prediction and its descendants run as UID10001. +""" +import json +import os +from pathlib import Path +import sys + +import adapted_boundary +import sealed_sandbox + + +def command(root, runtime, limits): + return [sys.executable, '/operator/fly_boundary.py', str(root), str(runtime), str(limits)] + + +def cleanup(): + sealed_sandbox.kill_uid() + + +def enter(root): + root=Path(root) + if root != Path('/workspace/research/run') or root.is_symlink(): + raise RuntimeError('Unexpected prediction scratch') + for p in [root,*root.rglob('*')]: + if p.is_symlink():raise RuntimeError('Unexpected link in staged prediction inputs') + os.chown(p,10001,10001) + adapted_boundary.no_new_privileges() + os.setgroups([]);os.setgid(10001);os.setuid(10001) + adapted_boundary.restrict_network() + if os.access('/private',os.X_OK):raise RuntimeError('Private labels accessible during prediction') + try: + Path('/operator/.write-probe').write_text('must fail') + except PermissionError:pass + else:raise RuntimeError('Trusted verifier source is writable') + + +def main(root,runtime,limits): + env={'PATH':'/usr/local/bin:/usr/bin:/bin','HOME':'/tmp','TMPDIR':'/tmp', + 'PYTHONDONTWRITEBYTECODE':'1','OPENBLAS_NUM_THREADS':'2','OMP_NUM_THREADS':'2', + 'CUDA_VISIBLE_DEVICES':os.environ['CUDA_VISIBLE_DEVICES']} + enter(root) + os.chdir(root) + os.execve(sys.executable,[sys.executable,'-B','/opt/pathfinder/upstream/pathfinder/single_pipeline.py', + '--root',root,'--runtime',runtime,'--limits',limits],env) + + +if __name__=='__main__':main(*sys.argv[1:]) diff --git a/reproduction/files/53/536b647e28c9c23810aa7a92a847f97e1d86231d9a6151c629ba318b9facd716/test_coverage_release.py b/reproduction/files/53/536b647e28c9c23810aa7a92a847f97e1d86231d9a6151c629ba318b9facd716/test_coverage_release.py new file mode 100644 index 0000000000000000000000000000000000000000..2740ed56cd101717a287a5011b4b7e0ab75550f6 --- /dev/null +++ b/reproduction/files/53/536b647e28c9c23810aa7a92a847f97e1d86231d9a6151c629ba318b9facd716/test_coverage_release.py @@ -0,0 +1,128 @@ +"""Synthetic selection-validator fixtures, never scientific measurement evidence.""" +import copy +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +DATA=Path(__file__).resolve().parents[1]/'environment/data' +sys.path.insert(0,str(DATA)) +import public_release as public +import coverage_release as coverage + + +class CoverageReleaseTests(unittest.TestCase): + def setUp(self): + previous=json.loads((DATA/'selection-speed-v1.json').read_text()) + self.evidence=json.loads((DATA/'cost-evidence-speed-v1.json').read_text()) + extra='Cube_3D_Re300' + record=next(r for r in self.evidence['cases'] if r['case']==extra) + # Explicit synthetic samples exercise >30 s acceptance. Do not export + # them, or confuse validator tests with completed additional CFD probes. + record.update(status='complete',container_exit_code=0,reset_seconds=50, + timing_samples_seconds=[40,44,42],seconds_per_control=42,measured_controls=3) + ids=sorted(previous['case_ids']+[extra]) + self.selection={'release_id':coverage.RELEASE_ID,'status':'frozen', + 'created':'test-fixture','max_source_bytes':500_000_000_000, + 'candidate_inventory_count':62,'cost_evidence_sha256':public.digest(self.evidence), + 'included':[{'case':n,'scientific_value':'Unit-test fixture only', + 'cost_review':'Artificial review for validator coverage', + 'runtime_profile':'synthetic-test-only'} for n in ids], + 'excluded_complete_resources':[e for e in previous['excluded_complete_resources'] if e['case']!=extra], + 'policy':{'global_seconds_per_control_cutoff':None}} + + def test_reviewed_slower_case_can_expand_first_set_under_budget(self): + result=coverage.build(self.selection,self.evidence) + self.assertEqual(result['case_count'],29) + self.assertLess(result['files']['bytes'],500_000_000_000) + self.assertEqual(result['training']['case_ids'],result['test']['case_ids']) + self.assertTrue(result['test']['one_shared_checkpoint']) + self.assertFalse(result['test']['parameter_updates']) + self.assertEqual(result['status'],'data-release-not-cfd-certified') + + def test_missing_value_cost_or_profile_review_is_rejected(self): + for field in ['scientific_value','cost_review','runtime_profile']: + selection=copy.deepcopy(self.selection) + del selection['included'][0][field] + with self.subTest(field=field),self.assertRaises(ValueError): + coverage.build(selection,self.evidence) + + def test_old_hard_cutoff_and_larger_budget_are_rejected(self): + selection=copy.deepcopy(self.selection) + selection['policy']['global_seconds_per_control_cutoff']=30 + with self.assertRaisesRegex(ValueError,'universal'): + coverage.build(selection,self.evidence) + selection=copy.deepcopy(self.selection) + selection['max_source_bytes']=501_000_000_000 + with self.assertRaisesRegex(ValueError,'budget'): + coverage.build(selection,self.evidence) + + def test_actual_source_sum_cannot_exceed_cap(self): + # All timing values here are synthetic validator fixtures only. + evidence=copy.deepcopy(self.evidence) + for record in evidence['cases']: + record.update(status='complete',container_exit_code=0,reset_seconds=1, + timing_samples_seconds=[1,1],measured_controls=2,seconds_per_control=1) + selection=copy.deepcopy(self.selection) + selection['included']=[{'case':r['case'],'scientific_value':'synthetic', + 'cost_review':'synthetic','runtime_profile':'synthetic'} + for r in sorted(evidence['cases'],key=lambda r:r['case'])] + selection['excluded_complete_resources']=[] + selection['cost_evidence_sha256']=public.digest(evidence) + with self.assertRaisesRegex(ValueError,'budget|500'): + coverage.build(selection,evidence) + + def test_incomplete_evidence_cannot_become_an_inclusion(self): + evidence=copy.deepcopy(self.evidence) + next(r for r in evidence['cases'] if r['case']=='Cube_3D_Re300')['status']='timeout' + selection=copy.deepcopy(self.selection) + selection['cost_evidence_sha256']=public.digest(evidence) + with self.assertRaisesRegex(ValueError,'clean'): + coverage.build(selection,evidence) + + def test_zero_field_response_requires_correction_before_selection(self): + evidence=copy.deepcopy(self.evidence) + next(r for r in evidence['cases'] if r['case']=='Cube_3D_Re300')['observed_field_response']=False + selection=copy.deepcopy(self.selection) + selection['cost_evidence_sha256']=public.digest(evidence) + with self.assertRaisesRegex(ValueError,'zero-field-response'): + coverage.build(selection,evidence) + + def test_two_gpu_allocation_without_distinct_rank_binding_is_rejected(self): + evidence=copy.deepcopy(self.evidence) + record=next(r for r in evidence['cases'] if r['case']=='Cube_3D_Re300') + record.update(hardware='2 H100',gpu_bindings=[ + {'visible_cuda_devices':1,'cuda_device_uuid':'same-GPU'}, + {'visible_cuda_devices':1,'cuda_device_uuid':'same-GPU'}]) + selection=copy.deepcopy(self.selection) + selection['cost_evidence_sha256']=public.digest(evidence) + with self.assertRaisesRegex(ValueError,'CUDA rank bindings'): + coverage.build(selection,evidence) + + def test_existing_cases_and_exclusion_accounting_cannot_disappear(self): + selection=copy.deepcopy(self.selection) + selection['included'].pop(0) + with self.assertRaisesRegex(ValueError,'preserve'): + coverage.build(selection,self.evidence) + selection=copy.deepcopy(self.selection) + selection['excluded_complete_resources'].pop() + with self.assertRaisesRegex(ValueError,'accounting'): + coverage.build(selection,self.evidence) + + def test_exact_coverage_loader_and_tampering_rejection(self): + expected=coverage.build(self.selection,self.evidence) + with tempfile.TemporaryDirectory() as temporary,patch.object(coverage,'build_current',return_value=expected): + path=Path(temporary)/'release.json' + path.write_text(json.dumps(expected)) + self.assertEqual(public.load_release(path),expected) + changed=copy.deepcopy(expected) + changed['test']['case_ids'].pop() + path.write_text(json.dumps(changed)) + with self.assertRaisesRegex(ValueError,'exact frozen'): + public.load_release(path) + + +if __name__=='__main__': + unittest.main() diff --git a/reproduction/files/53/538b3cc3779ef0fd584c22ee72dc9d27733b7a2a7f847824b65430110afe01f2/native_verifier.py b/reproduction/files/53/538b3cc3779ef0fd584c22ee72dc9d27733b7a2a7f847824b65430110afe01f2/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..9e768316c9426dec9d4bff925b0c448409f0431e --- /dev/null +++ b/reproduction/files/53/538b3cc3779ef0fd584c22ee72dc9d27733b7a2a7f847824b65430110afe01f2/native_verifier.py @@ -0,0 +1,260 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import shutil +import signal +import socket +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def enter_offline_namespace(): + import offline_network + record = offline_network.configure(STATE) + libc = ctypes.CDLL(None, use_errno=True) + for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)): + fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC) + try: + if libc.setns(fd, flag): + raise OSError(ctypes.get_errno(), 'enter offline verifier namespace') + finally: + os.close(fd) + if socket.if_nameindex() != [(1, 'lo')]: + raise RuntimeError('Offline verifier namespace has external interfaces') + return record + + +def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')): + """End the native waiting supervisor only after its authenticated seal.""" + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + seconds + sealed_ready = False + try: + while process.poll() is None: + if (sealed_root / 'READY').is_file(): + marker = json.loads((sealed_root / 'READY').read_text()) + snapshot = sealed_root / 'run/snapshot.json' + if (hashlib.sha256(snapshot.read_bytes()).hexdigest() != marker['snapshot_sha256'] + or json.loads(snapshot.read_text())['run_id'] != marker['run_id']): + raise RuntimeError('Native seal marker is inconsistent') + sealed_ready = True + break + if time.monotonic() >= deadline: + raise TimeoutError('Verifier inference budget exhausted') + time.sleep(.1) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode) + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus']) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + if cfg.get('gpu_runtime', 'torch') == 'torch': + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if phase == 'inference': + if cfg.get('native_uid_isolation'): + # The original PDE verifier explicitly supports this UID fallback. + # The mount is below a local root-only parent, never chmod shared data. + Path('/private').chmod(0o700) + Path('/tests').chmod(0o700) + elif plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + subprocess.run(['useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + if not offline: + runtime.deny_network() + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets'], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc', + *cfg.get('writable_runtime_paths', [])]) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + if cfg.get('gpu_runtime') == 'jax': + probe = ('import jax; import jax.numpy as jnp; ' + f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in d.device_kind for d in jax.devices("gpu")); ' + 'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 ' + 'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': 'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children', + 'offline_namespace': offline, + 'source_mounts': 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan['task'] != 'protein-folding-prediction', + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + if cfg.get('stop_after_sealed_ready'): + # The native supervisor has already killed all model processes and + # sealed/hashes its predictions before writing READY. End only its + # wait-for-grader loop; the unchanged grader runs in a separate job. + result = run_until_sealed(cfg['command'], log, remaining) + else: + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True) + elapsed = time.monotonic() - entered + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + reward_path = STATE / 'results/reward.json' + if phase == 'score': + score_root = Path('/sealed/results') + if cfg.get('results_by_run_id'): + score_root /= json.loads(Path('/sealed/READY').read_text())['run_id'] + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = score_root / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/54/54658d9fd2ef7414257e513ce23e7573b89ce6b6ad2689dde2c6142594309a01/test_seed_comparison.py b/reproduction/files/54/54658d9fd2ef7414257e513ce23e7573b89ce6b6ad2689dde2c6142594309a01/test_seed_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..e1011f6f540cc4066124f34a33602b4fb197fda7 --- /dev/null +++ b/reproduction/files/54/54658d9fd2ef7414257e513ce23e7573b89ce6b6ad2689dde2c6142594309a01/test_seed_comparison.py @@ -0,0 +1,154 @@ +"""Statistical contract: paired seeds, stored scores, and consistent gains.""" + +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +import numpy as np + +SCRIPT = Path(__file__).resolve().parents[1] / "environment/evaluation/compare_seeds.py" + + +class SeedComparisonTest(unittest.TestCase): + def test_confirmation_and_pairing_guards(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "results").mkdir() + pairs = [] + for seed in range(3): + names = [f"random-{seed}", f"trained-{seed}"] + pairs.append(":".join(names)) + for name in names: + package = root / "packages" / name + package.mkdir(parents=True) + (package / "provenance.json").write_text( + json.dumps( + { + "checkpoint": None + if name.startswith("random") + else "own-checkpoint", + "initialization_seed": seed, + "data_seed": seed + 100, + "variant": "test-fixture", + "parameters": 1, + "infer_sha256": "same-adapter", + "training_recipe": {"steps": 10}, + } + ) + ) + for task in ["awf", "lfmc"]: + directory = root / "eval" / task + directory.mkdir(parents=True) + rows = [ + { + "id": str(i), + "label": 0, + "split": "train" if i < 2 else "val", + "latlon": [float(i), float(i)], + } + for i in range(10) + ] + (directory / "labels.json").write_text(json.dumps(rows)) + for pair in pairs: + for name in pair.split(":"): + trained = name.startswith("trained") + prediction = np.full(8, 0 if trained else 1) + path = root / "results" / f"{name}-{task}-predictions.npz" + np.savez( + path, + ids=np.array([str(i) for i in range(2, 10)]), + predictions=prediction, + ) + metric = ( + {"accuracy": 1 if trained else 0} + if task == "awf" + else {"mae": 0 if trained else 1} + ) + (root / "results" / f"{name}-{task}.json").write_text( + json.dumps( + { + "probe": {"validation": metric}, + "validation_predictions": str(path), + } + ) + ) + output = root / "comparison.json" + + def run(selected): + return subprocess.run( + [ + sys.executable, + str(SCRIPT), + "--data-root", + str(root), + "--pairs", + *selected, + "--raw-baseline", + "trained-0", + "--output", + str(output), + ], + capture_output=True, + text=True, + ) + + success = run(pairs) + self.assertEqual(success.returncode, 0, success.stderr) + report = json.loads(output.read_text()) + for task in ["awf", "lfmc"]: + self.assertTrue(report["tasks"][task]["three_seed_criterion_met"]) + raw = report["tasks"][task]["raw_baseline_comparison"] + self.assertEqual(raw["mean_seed_gain"], 0) + self.assertFalse(raw["three_seed_criterion_met"]) + self.assertEqual( + report["tasks"][task][ + "seed_and_spatial_bootstrap_95_percent_interval" + ], + [1, 1], + ) + (root / "execution-context.json").write_text('{"python_hash_seed": 0}') + for pair in pairs: + for name in pair.split(":"): + for task in ["awf", "lfmc"]: + score_path = root / "results" / f"{name}-{task}.json" + score = json.loads(score_path.read_text()) + score["features"] = str( + root / "features" / f"{name}-{task}" / "features.npz" + ) + score_path.write_text(json.dumps(score)) + same_context = run(pairs) + self.assertEqual(same_context.returncode, 0, same_context.stderr) + score_path = root / "results/trained-0-awf.json" + original_score = score_path.read_text() + score = json.loads(original_score) + score["features"] = str(root / "other-context/features.npz") + score_path.write_text(json.dumps(score)) + mixed = run(pairs) + self.assertNotEqual(mixed.returncode, 0) + self.assertIn("Cannot mix execution contexts", mixed.stderr) + score_path.write_text(original_score) + duplicate = run([pairs[0], pairs[0], pairs[0]]) + self.assertNotEqual(duplicate.returncode, 0) + self.assertIn("Repeated initialization seeds", duplicate.stderr) + path = root / "results/trained-2-awf-predictions.npz" + np.savez( + path, + ids=np.array([str(i) for i in range(2, 10)]), + predictions=np.ones(8), + ) + mismatch = run(pairs) + self.assertNotEqual(mismatch.returncode, 0) + self.assertIn("Saved predictions disagree", mismatch.stderr) + provenance = root / "packages/trained-0/provenance.json" + invalid = json.loads(provenance.read_text()) + invalid["training_validity"] = "invalid" + provenance.write_text(json.dumps(invalid)) + rejected = run(pairs) + self.assertNotEqual(rejected.returncode, 0) + self.assertIn("Known invalid training implementation", rejected.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/56/56ab243ac8792b9cbc3501f1356a925215517b349269e0f1a154a78486c1c4be/test.sh b/reproduction/files/56/56ab243ac8792b9cbc3501f1356a925215517b349269e0f1a154a78486c1c4be/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..dd8ec3c8ad339bbe56e67cb41a487a43222e0611 --- /dev/null +++ b/reproduction/files/56/56ab243ac8792b9cbc3501f1356a925215517b349269e0f1a154a78486c1c4be/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +exec /opt/qec/.venv/bin/python /opt/task/tests/main_verifier.py --timeout "${QEC_INFERENCE_TIMEOUT_SECONDS:-3600}" diff --git a/reproduction/files/57/5737d65bd5c9128529706a80c7949bc018c9860fc16dc2dd75893a685a09eaf3/test_verifier_suite.py b/reproduction/files/57/5737d65bd5c9128529706a80c7949bc018c9860fc16dc2dd75893a685a09eaf3/test_verifier_suite.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc00d471b71819e4797a0c65fbb04f98f3df9f3 --- /dev/null +++ b/reproduction/files/57/5737d65bd5c9128529706a80c7949bc018c9860fc16dc2dd75893a685a09eaf3/test_verifier_suite.py @@ -0,0 +1,76 @@ +"""CPU tests of the scored verifier suite and the side-by-side GPU scheduler (no CFD).""" +from pathlib import Path +import sys +import threading +import time +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'environment/evaluation')) +from case_spec import VERIFIER_CASES, estimated_seconds, select_cases +from evaluate_native import SIDE_BY_SIDE_TIMEOUT_FACTOR, replay_cases + + +class VerifierSuiteTests(unittest.TestCase): + def test_suite_keeps_every_family_dimension_and_backend(self): + _, every = select_cases(['all']) + _, scored = select_cases(['verifier']) + self.assertEqual({c['id'] for c in scored}, set(VERIFIER_CASES)) + for key in ('family', 'backend'): + self.assertEqual({c[key] for c in scored}, {c[key] for c in every}, key) + self.assertEqual({'_2D' in c['id'] or c['id'] == 'Kolmogorov_2D' or c['id'].startswith('Nozzle2D') + for c in scored}, {True, False}) + twod = {c['id'] for c in every if '_3D' not in c['id']} + self.assertTrue(twod <= set(VERIFIER_CASES), 'every 2D case is scored') + self.assertTrue(any(c['solver_processes'] > 1 for c in scored), 'a two-GPU solver case is scored') + + def test_suite_fits_the_eight_gpu_budget(self): + _, scored = select_cases(['verifier']) + longest = max(estimated_seconds(c['id']) for c in scored) + total = sum(estimated_seconds(c['id']) * c['solver_processes'] for c in scored) + # Estimates are solo-H100 measurements; side by side the 8xH100 replay took 2 h 21 min (3.9 h on a shared host). + self.assertLess(max(longest, total / 8), 2.5 * 3600) + + def test_scheduler_never_double_books_gpus(self): + _, scored = select_cases(['verifier']) + lock, busy, seen = threading.Lock(), set(), {} + + accounts = set() + + def fake(case, env): + gpus = env['CUDA_VISIBLE_DEVICES'].split(',') + uid = env['HYDROGYM_POLICY_UID'] + with lock: + self.assertFalse(busy & set(gpus)) + self.assertNotIn(uid, accounts, 'two running cases share a policy account') + busy.update(gpus) + accounts.add(uid) + self.assertEqual(len(gpus), case['solver_processes']) + time.sleep(0.01) + with lock: + busy.difference_update(gpus) + accounts.discard(uid) + seen[case['id']] = gpus + return {'status': 'ok'} + + out = replay_cases(scored, fake, [f'GPU-{i}' for i in range(8)]) + self.assertEqual(set(out), set(VERIFIER_CASES)) + + def test_side_by_side_cases_get_a_longer_limit(self): + _, scored = select_cases(['verifier']) + limits = {} + replay_cases(scored, lambda case, env: limits.setdefault(case['id'], case['timeout_sec']) and {'status': 'ok'}, + [f'GPU-{i}' for i in range(8)]) + for case in scored: + self.assertEqual(limits[case['id']], case['timeout_sec'] * SIDE_BY_SIDE_TIMEOUT_FACTOR) + sequential = {} + replay_cases(scored, lambda case, env: sequential.setdefault(case['id'], case['timeout_sec']) and {'status': 'ok'}, []) + self.assertEqual(sequential, {c['id']: c['timeout_sec'] for c in scored}) + + def test_scheduler_falls_back_to_sequential_without_gpus(self): + _, scored = select_cases(['verifier']) + out = replay_cases(scored, lambda case, env: {'status': 'ok', 'env': env}, []) + self.assertTrue(all(row['env'] is None for row in out.values())) + + +if __name__ == '__main__': + unittest.main() diff --git a/reproduction/files/57/573aa671d951d02a6e7b5c431a22a51e245d78248598d6bb5f05fa827af0db6d/run_native.py b/reproduction/files/57/573aa671d951d02a6e7b5c431a22a51e245d78248598d6bb5f05fa827af0db6d/run_native.py new file mode 100644 index 0000000000000000000000000000000000000000..bd98c4a9daf673328b7dba13c8a3950edd8c853d --- /dev/null +++ b/reproduction/files/57/573aa671d951d02a6e7b5c431a22a51e245d78248598d6bb5f05fa827af0db6d/run_native.py @@ -0,0 +1,110 @@ +"""Private native solver launcher; invoked by evaluate_native.py, not by a model.""" +import argparse +import os +from pathlib import Path +import subprocess +import sys +import traceback + +from case_spec import local_only, select_cases, verify_resources +from evaluate import package_hash, write_json +from protocol import Policy, PolicyError, replay_episode + + +def worker(case, data, submission, output): + from native_envs import make_env, ReplayAdapter + env = make_env(case, data) + adapter = ReplayAdapter(env, case, output) + policy = None + can_close = True + result = None + before = package_hash(submission) + try: + policy = Policy(submission, output / 'policy.log', timeout=120) + pid = policy.process.pid + try: + ticks = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[19] + except FileNotFoundError: + # An immediately exiting candidate is a protocol/policy failure, + # not missing solver infrastructure. No live session to reap. + pass + else: + write_json(output / 'policy-process.json', {'pid': pid, 'start_ticks': ticks}) + episodes = [replay_episode(adapter, policy, case, seed) for seed in case['seeds']] + policy.close() + policy = None + result = {'status': 'ok', 'episodes': episodes, 'submission_sha256': before} + except PolicyError as error: + result = {'status': 'policy_error', 'error': str(error), 'submission_sha256': before} + except BaseException: + # A failing MPI collective must be aborted by main(), not followed by + # another collective close that can wait forever for a broken solver. + can_close = case['backend'] != 'maia' + raise + finally: + if policy is not None: + policy.abort() + if can_close: + if result is not None: + import sys + sys.path.insert(0, "/operator") + from fluid_cleanup import save_policy_failure + save_policy_failure(output, case, submission, before, result, package_hash, write_json) + env.close() + if package_hash(submission) != before: + raise RuntimeError('Model package mutated during native replay') + write_json(output / 'result.json', result) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--case', required=True) + p.add_argument('--data', type=Path, required=True) + p.add_argument('--submission', type=Path, required=True) + p.add_argument('--output', type=Path, required=True) + p.add_argument('--worker', action='store_true') + args = p.parse_args() + args.data, args.output, args.submission = (p.resolve() for p in (args.data, args.output, args.submission)) + spec, cases = select_cases([args.case]) + case = cases[0] + verify_resources(args.data, cases) + local_only(args.data, case, args.output) + try: + if not args.worker: + # Enumerate in a fresh child: CUDA visibility is fixed at first init. + import json + helper = Path(__file__).with_name('maia_gpu_rank.py') + devices = json.loads(subprocess.check_output([sys.executable, str(helper), '--list-gpus'], text=True)) + required = case['solver_processes'] + if len(devices) < required: + raise RuntimeError(f'{case["id"]} requires {required} distinct GPUs; allocated {len(devices)}') + selected = devices[:required] + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(selected) + write_json(args.output / 'gpu-allocation.json', {'cuda_device_uuids': selected}) + if case['backend'] != 'maia' or args.worker: + worker(case, args.data, args.submission, args.output) + return + from hydrogym.maia.workspace import prepare_maia_workspace + work, props = prepare_maia_workspace(case['environment'], + work_dir=str(args.output / 'cfd'), use_clean_cache=False, + local_fallback_dir=str(args.data / 'environments')) + solver = [sys.executable, str(Path(__file__).with_name('maia_gpu_rank.py'))] + command = ['mpirun', '--bind-to', 'none', '-np', '1', sys.executable, str(Path(__file__).resolve()), + '--worker', '--case', case['id'], '--data', str(args.data), '--output', str(args.output), + '--submission', str(args.submission), ':', '-np', str(case['solver_processes']), + *solver, props, '--silent'] + environment = dict(os.environ, OMPI_ALLOW_RUN_AS_ROOT='1', OMPI_ALLOW_RUN_AS_ROOT_CONFIRM='1', + OMPI_MCA_coll_hcoll_enable='0') + subprocess.run(command, cwd=work, env=environment, check=True) + except BaseException as error: + write_json(args.output / ('worker-error.json' if args.worker else 'launcher-error.json'), + {'status': 'infrastructure_error', 'error': str(error), 'traceback': traceback.format_exc()}) + if args.worker: + # A broken MPI environment cannot safely perform collective env.close. + from mpi4py import MPI + MPI.COMM_WORLD.Abort(1) + raise + + +if __name__ == '__main__': + main() diff --git a/reproduction/files/57/57b0f1dada46c2c014c20de3cfcfa76b878f63382b246566099aa5008a2fcfc6/docker-compose.yaml b/reproduction/files/57/57b0f1dada46c2c014c20de3cfcfa76b878f63382b246566099aa5008a2fcfc6/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..56a37ef6269854753a9c102b880ca317d8ce1462 --- /dev/null +++ b/reproduction/files/57/57b0f1dada46c2c014c20de3cfcfa76b878f63382b246566099aa5008a2fcfc6/docker-compose.yaml @@ -0,0 +1,47 @@ +volumes: + sealed: + verifier_logs: + +services: + main: + build: + context: .. + dockerfile: tests/Dockerfile + target: main + network_mode: none + volumes: + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the private test materialization}/public/test + target: /input + read_only: true + bind: + create_host_path: false + - sealed:/sealed + - verifier_logs:/logs/verifier + grader: + build: + context: .. + dockerfile: tests/Dockerfile + target: grader + network_mode: none + volumes: + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the private test materialization}/public/test + target: /input + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the private test materialization}/trusted/test + target: /trusted/test + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the private test materialization}/trusted/risk_normalization.parquet + target: /trusted/risk_normalization.parquet + read_only: true + bind: + create_host_path: false + - sealed:/sealed + command: ["python", "/tests/grader.py"] diff --git a/reproduction/files/58/5831dbfd71dc7aeff964d462529a3fbd3e52352c257a3e0d21cba8ded4f515d6/test.sh b/reproduction/files/58/5831dbfd71dc7aeff964d462529a3fbd3e52352c257a3e0d21cba8ded4f515d6/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f6d90585fc66d811aa210a1e09afd36e5c586b7 --- /dev/null +++ b/reproduction/files/58/5831dbfd71dc7aeff964d462529a3fbd3e52352c257a3e0d21cba8ded4f515d6/test.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Harbor verifier entry point (main container). The grader container runs /tests/grader.py. +set -euo pipefail +exec python /tests/main_verifier.py \ + --submission /workspace/submission \ + --benchmark /benchmark \ + --sealed /sealed/run \ + --output /logs/verifier \ + --timeout-per-context "${VCZ_INFERENCE_TIMEOUT_SECONDS:-3600}" diff --git a/reproduction/files/58/58bccbe05d8b691a50787b90aee078c5bceedee24fcfd4dc38f426c67875804a/run_unit_tests.sh b/reproduction/files/58/58bccbe05d8b691a50787b90aee078c5bceedee24fcfd4dc38f426c67875804a/run_unit_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c7ed985f335a2d6dd95ac63211d4281f21a0213 --- /dev/null +++ b/reproduction/files/58/58bccbe05d8b691a50787b90aee078c5bceedee24fcfd4dc38f426c67875804a/run_unit_tests.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Run the unit tests inside the verifier image (needs cell-eval): bash tests/run_unit_tests.sh [image] +set -euo pipefail +task=$(cd "$(dirname "$0")/.." && pwd) +image=${1:-vcz-verifier:latest} +${VCZ_DOCKER:-docker} run --rm -v "$task:/task:ro" -w /task --entrypoint python "$image" -m pytest -q /task/tests/test_task.py diff --git a/reproduction/files/59/592a92a32fdb9a6b915a815061c50875b35fdc15bc7b9c597bea3c1409995337/test_observables.py b/reproduction/files/59/592a92a32fdb9a6b915a815061c50875b35fdc15bc7b9c597bea3c1409995337/test_observables.py new file mode 100644 index 0000000000000000000000000000000000000000..52fa7523341e454c3fd4684ec8b5e9db061fe502 --- /dev/null +++ b/reproduction/files/59/592a92a32fdb9a6b915a815061c50875b35fdc15bc7b9c597bea3c1409995337/test_observables.py @@ -0,0 +1,163 @@ +"""Independent measurement-space checks of the native/global observable map. + +QEC_DATA_ROOT enables checks on every released condition using only the first +256 even training shots and 128 independent synthetic shots per condition. +""" +from __future__ import annotations + +import os +from pathlib import Path +import sys + +import numpy as np +import pytest +import stim + +PROJECT = Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" if (Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit").is_dir() else Path(__file__).resolve().parents[1] # the baseline project: environment/baseline/alphaqubit here, /opt/task in the verifier image +sys.path.insert(0, str(PROJECT)) +from baselines.data import Condition, discover_conditions +from baselines.observables import ObservableTransform + + +def _augmented_global_observable(circuit: stim.Circuit, distance: int) -> stim.Circuit: + augmented = circuit.copy() + augmented.append( + "OBSERVABLE_INCLUDE", [stim.target_rec(i) for i in range(-distance**2, 0)], 1, + ) + return augmented + + +def _check_both_representations( + transform: ObservableTransform, detectors: np.ndarray, observations: np.ndarray, +) -> None: + path = observations[:, :1] + expected_global = observations[:, 1:2] + packed = np.packbits(detectors, axis=1, bitorder="little") + global_labels = transform.path_to_global(detectors, path) + packed_labels = transform.path_to_global_packed(packed, path) + assert global_labels.dtype == packed_labels.dtype == np.uint8 + np.testing.assert_array_equal(global_labels, expected_global) + np.testing.assert_array_equal(packed_labels, expected_global) + path_probability = transform.global_to_path_probabilities(detectors, global_labels) + packed_probability = transform.global_to_path_probabilities_packed(packed, global_labels) + assert path_probability.dtype == packed_probability.dtype == np.float32 + np.testing.assert_array_equal(path_probability, path) + np.testing.assert_array_equal(packed_probability, path) + + +@pytest.mark.parametrize("distance", [3, 5]) +@pytest.mark.parametrize("basis", ["X", "Z"]) +@pytest.mark.parametrize("rounds", [1, 3, 25]) +def test_generated_measurement_parity_identity( + tmp_path: Path, distance: int, basis: str, rounds: int, +) -> None: + condition = Condition(tmp_path, "fixture", distance, basis, rounds, "fixture") + generator = f"surface_code:rotated_memory_{basis.lower()}" + ideal = stim.Circuit.generated(generator, distance=distance, rounds=rounds) + ideal.to_file(tmp_path / "circuit_ideal.stim") + noisy = stim.Circuit.generated( + generator, distance=distance, rounds=rounds, + after_clifford_depolarization=0.02, before_measure_flip_probability=0.02, + ) + transform = ObservableTransform.from_condition(condition) + augmented = _augmented_global_observable(noisy, distance) + detectors, observations = augmented.compile_detector_sampler(seed=82).sample( + 256, separate_observables=True, + ) + _check_both_representations(transform, detectors, observations) + # Probability conversion is an affine reflection, not hard thresholding. + probabilities = np.linspace(0.03, 0.97, len(detectors), dtype=np.float32)[:, None] + reflected = transform.global_to_path_probabilities(detectors, probabilities) + restored = transform.global_to_path_probabilities(detectors, reflected) + np.testing.assert_allclose(restored, probabilities, atol=6e-8) + assert np.any(np.abs(reflected - probabilities) > 0.1) + assert transform.metadata()["num_data_qubits"] == distance**2 + with pytest.raises(ValueError, match="finite"): + transform.global_to_path_probabilities(detectors, np.full_like(probabilities, np.nan)) + + +def test_non_equivalent_observable_is_rejected(tmp_path: Path) -> None: + circuit = stim.Circuit.generated("surface_code:rotated_memory_z", distance=3, rounds=3) + # A single extra data measurement changes the stabilizer equivalence class. + circuit.append("OBSERVABLE_INCLUDE", [stim.target_rec(-1)], 0) + circuit.to_file(tmp_path / "circuit_ideal.stim") + condition = Condition(tmp_path, "fixture", 3, "Z", 3, "fixture") + with pytest.raises(ValueError, match="not equivalent"): + ObservableTransform.from_condition(condition) + + +def _read_even_prefix(path: Path, width_bits: int) -> np.ndarray: + width_bytes = (width_bits + 7) // 8 + raw = np.fromfile(path, dtype=np.uint8, count=512 * width_bytes) + assert raw.size == 512 * width_bytes + return np.unpackbits( + raw.reshape(512, width_bytes)[::2], axis=1, count=width_bits, bitorder="little", + ).astype(np.bool_) + + +def test_all_hardware_and_simulation_transforms() -> None: + data_root = os.environ.get("QEC_DATA_ROOT") or os.environ.get("SYCAMORE_DATA_ROOT") + if data_root is None: + pytest.skip("Set QEC_DATA_ROOT to enable all-condition release integration checks") + conditions = discover_conditions(data_root) + assert len(conditions) == 130 + for condition in conditions: + transform = ObservableTransform.from_condition(condition) + circuit = stim.Circuit.from_file(condition.path / "circuit_ideal.stim") + measurement = _read_even_prefix(condition.path / "measurements.b8", circuit.num_measurements) + sweep = _read_even_prefix(condition.path / "sweep.b8", circuit.num_sweep_bits) + augmented = _augmented_global_observable(circuit, condition.distance) + detectors, observations = augmented.compile_m2d_converter().convert( + measurements=measurement, sweep_bits=sweep, separate_observables=True, + ) + official_detectors = _read_even_prefix(condition.path / "detection_events.b8", circuit.num_detectors) + official_path = stim.read_shot_data_file( + path=condition.path / "obs_flips_actual.01", format="01", num_observables=1, + )[:512:2] + np.testing.assert_array_equal(detectors, official_detectors) + np.testing.assert_array_equal(observations[:, :1], official_path) + _check_both_representations(transform, detectors, observations) + noisy = stim.Circuit.from_file(condition.path / "circuit_noisy.stim") + synthetic = _augmented_global_observable(noisy, condition.distance) + dets, obs = synthetic.compile_detector_sampler(seed=701 + condition.rounds).sample( + 128, separate_observables=True, + ) + _check_both_representations(transform, dets, obs) + + +def test_released_pauli_circuits_are_invariant_under_initial_sweeps() -> None: + """Validate the cache's zero-sweep population against different initial states.""" + data_root = os.environ.get("QEC_DATA_ROOT") or os.environ.get("SYCAMORE_DATA_ROOT") + if data_root is None: + pytest.skip("Set QEC_DATA_ROOT to check release-specific Pauli sweep invariance") + conditions = discover_conditions(data_root) + for distance in (3, 5): + for basis in ("X", "Z"): + condition = next(item for item in conditions if ( + item.distance == distance and item.basis == basis and item.rounds == 3 + )) + circuit = stim.Circuit.from_file(condition.path / "circuit_noisy.stim") + expected_dem = circuit.detector_error_model(decompose_errors=True).flattened() + expected = circuit.compile_detector_sampler(seed=41).sample(256, append_observables=True) + patterns = ( + np.zeros(circuit.num_sweep_bits, dtype=np.bool_), + np.ones(circuit.num_sweep_bits, dtype=np.bool_), + np.arange(circuit.num_sweep_bits) % 2 == 1, + np.random.default_rng(7).integers(0, 2, circuit.num_sweep_bits).astype(np.bool_), + ) + for bits in patterns: + fixed = stim.Circuit() + for instruction in circuit.flattened(): + targets = instruction.targets_copy() + if instruction.name == "CX" and any(target.is_sweep_bit_target for target in targets): + for control, target in zip(targets[::2], targets[1::2]): + if control.is_sweep_bit_target: + if bits[control.value]: + fixed.append("X", [target.value]) + else: + fixed.append("CX", [control, target]) + else: + fixed.append(instruction) + assert fixed.detector_error_model(decompose_errors=True).flattened() == expected_dem + actual = fixed.compile_detector_sampler(seed=41).sample(256, append_observables=True) + np.testing.assert_array_equal(actual, expected) diff --git a/reproduction/files/59/5930107545795d6f6fec4f546c18d99f85bd4cc8e172f0a38de5475cc988dd36/test_maia_gpu_rank.py b/reproduction/files/59/5930107545795d6f6fec4f546c18d99f85bd4cc8e172f0a38de5475cc988dd36/test_maia_gpu_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea582093927d69272a838f31134efaa295db8d0 --- /dev/null +++ b/reproduction/files/59/5930107545795d6f6fec4f546c18d99f85bd4cc8e172f0a38de5475cc988dd36/test_maia_gpu_rank.py @@ -0,0 +1,26 @@ +"""Rank selection tests; real CUDA visibility has a separate native preflight.""" +from pathlib import Path +import sys +import unittest + +sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'environment/evaluation')) +from maia_gpu_rank import select_device + + +class MaiaGpuRankTests(unittest.TestCase): + def test_rank_zero_is_python_and_solver_uuids_are_distinct(self): + devices=['GPU-first','GPU-second'] + self.assertEqual(select_device(1,devices),'GPU-first') + self.assertEqual(select_device(2,devices),'GPU-second') + for rank in [0,3,-1,True]: + with self.subTest(rank=rank),self.assertRaises(ValueError): + select_device(rank,devices) + + def test_missing_or_duplicate_devices_do_not_share_gpu_silently(self): + for devices in [[],['GPU-same','GPU-same']]: + with self.assertRaises(ValueError): + select_device(1,devices) + + +if __name__=='__main__': + unittest.main() diff --git a/reproduction/files/59/5934ad97f3e246fb721478ec59dd1ee5c6fc192e1768bdb1ee740d1d6fb98dc2/test_accounting.py b/reproduction/files/59/5934ad97f3e246fb721478ec59dd1ee5c6fc192e1768bdb1ee740d1d6fb98dc2/test_accounting.py new file mode 100644 index 0000000000000000000000000000000000000000..80613133798491319f8b3d54b4c75b7dfee42f18 --- /dev/null +++ b/reproduction/files/59/5934ad97f3e246fb721478ec59dd1ee5c6fc192e1768bdb1ee740d1d6fb98dc2/test_accounting.py @@ -0,0 +1,25 @@ +"""Resource gates must not reclaim running, missing, or already spent budget.""" +import pytest + +from baselines.accounting import allocation_ceiling + + +def test_pivot_reclaims_only_unused_budget() -> None: + jobs = [dict(id="1", retired=True, gpu_count=1, array_tasks=2, max_hours_per_task=24), + dict(id="2", gpu_count=2, array_tasks=1, max_hours_per_task=10)] + rows = [dict(job_id="1_0", state="FAILED", gpu_hours=18), + dict(job_id="1_1", state="CANCELLED by 10", gpu_hours=0)] + assert allocation_ceiling(jobs, rows) == 38 + assert jobs[0]["max_hours_per_task"] == 24 + + +@pytest.mark.parametrize("rows", [[], [dict(job_id="1_0", state="RUNNING", gpu_hours=18)], + [dict(job_id="1_0", state="PENDING", gpu_hours=0)]]) +def test_unsettled_usage_cannot_be_retired(rows: list[dict]) -> None: + with pytest.raises(ValueError, match="terminal accounting"): + allocation_ceiling([dict(id="1", retired=True)], rows) + + +def test_all_spent_compute_still_counts() -> None: + assert allocation_ceiling([dict(id="1", retired=True)], + [dict(job_id="1", state="TIMEOUT", gpu_hours=400)]) == 400 diff --git a/reproduction/files/59/5997f7091611ffc62f1b09614aaaea7f4d166315fd2faf612103ec05a49f4d79/paired_bootstrap.py b/reproduction/files/59/5997f7091611ffc62f1b09614aaaea7f4d166315fd2faf612103ec05a49f4d79/paired_bootstrap.py new file mode 100644 index 0000000000000000000000000000000000000000..6d2b03f3975ff9fef16b9dd426c6f47e3c29a891 --- /dev/null +++ b/reproduction/files/59/5997f7091611ffc62f1b09614aaaea7f4d166315fd2faf612103ec05a49f4d79/paired_bootstrap.py @@ -0,0 +1,159 @@ +"""Exact patient-level paired bootstrap for primary AUROC differences.""" + +from __future__ import annotations + +import argparse +import json +from datetime import timedelta +from pathlib import Path + +import numpy as np +import pyarrow.parquet as pq +import torch + +from risk_scoring import HORIZONS, read_predictions, weighted_macro_time_auroc + + +def bootstrap_difference(labels: np.ndarray, valid: np.ndarray, + reference: np.ndarray, candidate: np.ndarray, + weights: np.ndarray, device_name: str) -> np.ndarray: + """Exact batched AUROC recomputation; prediction ties remain grouped.""" + device = torch.device(device_name) + weight = torch.as_tensor(weights, dtype=torch.float32, device=device) + replicates, diseases = len(weights), labels.shape[1] + reference_sum = torch.zeros((replicates, diseases), device=device) + candidate_sum = torch.zeros_like(reference_sum) + cell_count = torch.zeros_like(reference_sum) + + def batch_auc(y_numpy, p_numpy, patient_index): + order = np.argsort(p_numpy, kind="stable") + sorted_prediction = p_numpy[order] + group = np.r_[0, np.cumsum(sorted_prediction[1:] != sorted_prediction[:-1])] + group_count = int(group[-1]) + 1 + w = weight[:, torch.as_tensor(patient_index[order], device=device)] + y = torch.as_tensor(y_numpy[order], dtype=torch.float32, device=device) + group_index = torch.as_tensor(group, dtype=torch.int64, device=device).expand(replicates, -1) + positive_group = torch.zeros((replicates, group_count), device=device) + negative_group = torch.zeros_like(positive_group) + positive_group.scatter_add_(1, group_index, w * y) + negative_group.scatter_add_(1, group_index, w * (1 - y)) + positive = positive_group.sum(1) + negative = negative_group.sum(1) + lower_negative = torch.cumsum(negative_group, 1) - negative_group + auc = (positive_group * (lower_negative + .5 * negative_group)).sum(1) + auc = auc / (positive * negative).clamp(min=1) + return auc, (positive > 0) & (negative > 0) + + for j in range(diseases): + for k in range(labels.shape[2]): + patient_index = np.flatnonzero(valid[:, j, k]) + y = labels[patient_index, j, k] + if not len(y) or y.min() == y.max(): + continue + ref_auc, scorable = batch_auc(y, reference[patient_index, j, k], patient_index) + cand_auc, candidate_scorable = batch_auc( + y, candidate[patient_index, j, k], patient_index) + if not torch.equal(scorable, candidate_scorable): + raise AssertionError("Bootstrap cell availability must depend only on labels") + keep = scorable.float() + reference_sum[:, j] += ref_auc * keep + candidate_sum[:, j] += cand_auc * keep + cell_count[:, j] += keep + disease_available = cell_count > 0 + reference_disease = reference_sum / cell_count.clamp(min=1) + candidate_disease = candidate_sum / cell_count.clamp(min=1) + difference = ((candidate_disease - reference_disease) * disease_available).sum(1) + difference /= disease_available.sum(1).clamp(min=1) + return difference.cpu().numpy() + + +def load_truth(input_dir: Path, trusted: Path): + manifest = json.loads((input_dir / "manifest.json").read_text()) + diseases = manifest["scored_diseases"] + samples = pq.read_table(input_dir / "samples.parquet").to_pylist() + ids = [row["sample_id"] for row in samples] + sample_index = {sid: i for i, sid in enumerate(ids)} + disease_index = {code: j for j, code in enumerate(diseases)} + shape = (len(ids), len(diseases), len(HORIZONS)) + y, valid = np.zeros(shape, np.uint8), np.zeros(shape, bool) + seen = set() + columns = ["sample_id", "disease_code"] + [f"{field}_{horizon}" + for horizon in HORIZONS for field in ("disease_label", "disease_valid")] + for batch in pq.ParquetFile(trusted / "label_windows.parquet").iter_batches( + batch_size=65536, columns=columns): + data = batch.to_pydict() + for row in range(batch.num_rows): + key = (data["sample_id"][row], data["disease_code"][row]) + if key in seen or key[0] not in sample_index or key[1] not in disease_index: + raise ValueError("Unknown or duplicate keyed label row") + seen.add(key) + i, j = sample_index[key[0]], disease_index[key[1]] + for k, horizon in enumerate(HORIZONS): + y[i, j, k] = data[f"disease_label_{horizon}"][row] + valid[i, j, k] = data[f"disease_valid_{horizon}"][row] + if len(seen) != len(ids) * len(diseases): + raise ValueError("Trusted labels do not cover the public key grid") + boundaries = {row["sample_id"]: row for row in pq.read_table( + trusted / "sample_boundaries.parquet").to_pylist()} + primary = [] + for sample in samples: + cutoff = sample["cutoff"].date() if hasattr(sample["cutoff"], "date") else sample["cutoff"] + row = boundaries[sample["sample_id"]] + primary.append(cutoff + timedelta(days=365) <= row["diagnosis_observation_end"] + and cutoff + timedelta(days=365) <= row["death_observation_end"]) + primary = np.asarray(primary, dtype=bool) + return ids, diseases, y[primary], valid[primary], primary + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--trusted", type=Path, required=True) + parser.add_argument("--reference", type=Path, required=True) + parser.add_argument("--candidate", type=Path, action="append", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--replicates", type=int, default=1000) + parser.add_argument("--seed", type=int, default=20260929) + parser.add_argument("--device", default="cpu", + help="cpu or cuda; batched computation is exact on either device") + args = parser.parse_args() + ids, diseases, y, valid, primary = load_truth(args.input, args.trusted) + reference, _ = read_predictions(args.reference, ids, len(diseases)) + reference = reference[primary] + unit_weight = np.ones(len(y), dtype=np.float64) + reference_point = weighted_macro_time_auroc(y, reference, valid, unit_weight) + rng = np.random.default_rng(args.seed) + weights = np.stack([np.bincount(rng.integers(0, len(y), len(y)), minlength=len(y)) + for _ in range(args.replicates)]).astype(np.float32) + result = { + "schema": "ndp-paired-patient-bootstrap-auroc/v2", + "metric": "disease-first macro time-averaged AUROC", + "replicates": args.replicates, + "seed": args.seed, + "reference": str(args.reference), + "reference_point": reference_point, + "primary_patients": len(y), + "method": ("same complete-year patients resampled with replacement for both models; " + "AUROC is exactly recomputed in every replicate; a resampled single-class " + "disease-horizon cell is unavailable for both models, followed by time-within-" + "disease then disease averaging"), + "comparisons": {}, + } + for path in args.candidate: + candidate, _ = read_predictions(path, ids, len(diseases)) + candidate = candidate[primary] + candidate_point = weighted_macro_time_auroc(y, candidate, valid, unit_weight) + point = candidate_point - reference_point + draws = bootstrap_difference(y, valid, reference, candidate, weights, args.device) + result["comparisons"][str(path)] = { + "candidate_point": candidate_point, + "candidate_minus_reference": point, + "ci95": np.quantile(draws, [.025, .975]).tolist(), + "probability_candidate_better": float(np.mean(draws > 0)), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/5e/5e4e979233c50b220a3dea6d033b09cbcd7a8cda25bf6f3bb8137dd632897a94/main_verifier.py b/reproduction/files/5e/5e4e979233c50b220a3dea6d033b09cbcd7a8cda25bf6f3bb8137dd632897a94/main_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..e63312ea6603b8d51048824e2419d8ba26925556 --- /dev/null +++ b/reproduction/files/5e/5e4e979233c50b220a3dea6d033b09cbcd7a8cda25bf6f3bb8137dd632897a94/main_verifier.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Replay untrusted inference on the public test inputs (one call per context) and seal the +predictions for the trusted grader. Never sees private responses.""" + +from __future__ import annotations + +import argparse +import json +import os +import pwd +import shutil +import signal +import subprocess +import time +from pathlib import Path + +import anndata as ad +import numpy as np +from scipy import sparse + +from cellscore import read_requests, sha256 + + +def validate_submission(root: Path) -> None: + root = root.resolve() + if not (root / "infer.sh").is_file(): + raise FileNotFoundError("submission/infer.sh is required") + for path in root.rglob("*"): + if path.is_symlink() and not path.resolve().is_relative_to(root): + raise ValueError(f"submission symlink escapes package: {path.relative_to(root)}") + + +def kill_uid(uid: int) -> None: + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit() or int(entry.name) == os.getpid(): + continue + try: + status = (entry / "status").read_text() + process_uid = int(next(x for x in status.splitlines() if x.startswith("Uid:")).split()[1]) + if process_uid == uid: + os.kill(int(entry.name), signal.SIGKILL) + except (FileNotFoundError, ProcessLookupError, PermissionError, StopIteration): + pass + + +def validate_output(path: Path, basal_path: Path, request_path: Path) -> dict: + expected = read_requests(request_path) + basal = ad.read_h5ad(basal_path, backed="r") + predicted = ad.read_h5ad(path) + if "request_id" not in predicted.obs or predicted.var_names.has_duplicates: + raise ValueError("predictions need obs.request_id and unique genes") + if list(map(str, predicted.var_names)) != list(map(str, basal.var_names)): + raise ValueError("prediction genes/order differ from input basal.h5ad") + ids = predicted.obs["request_id"].astype(str) + counts = ids.value_counts().to_dict() + if counts != {row["request_id"]: row["n_cells"] for row in expected}: + raise ValueError("prediction request IDs or per-request cell counts differ from requests.jsonl") + values = predicted.X.data if sparse.issparse(predicted.X) else np.asarray(predicted.X) + if not np.isfinite(values).all() or (values < 0).any(): + raise ValueError("predictions contain negative or non-finite values") + return {"n_cells": int(predicted.n_obs), "n_genes": int(predicted.n_vars)} + + +def run_inference(submission: Path, input_dir: Path, output_dir: Path, log_path: Path, timeout: int, gpu: str) -> None: + agent = pwd.getpwnam("agent") + output_dir.mkdir(parents=True, exist_ok=True) + os.chown(output_dir, agent.pw_uid, agent.pw_gid) + env = {"PATH": "/opt/conda/bin:/usr/local/bin:/usr/bin:/bin", "HOME": agent.pw_dir, "PYTHONUNBUFFERED": "1", + "PIP_NO_INDEX": "1", "HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1", "CUDA_VISIBLE_DEVICES": gpu, + "OMP_NUM_THREADS": os.environ.get("OMP_NUM_THREADS", "16")} + + def demote(): + os.setgid(agent.pw_gid) + os.setuid(agent.pw_uid) + + process = None + try: + with log_path.open("wb") as log: + process = subprocess.Popen(["bash", str(submission / "infer.sh"), str(input_dir), str(output_dir)], + cwd=submission, env=env, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, preexec_fn=demote) + code = process.wait(timeout=timeout) + if code: + raise subprocess.CalledProcessError(code, process.args) + finally: + if process: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + kill_uid(agent.pw_uid) + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--submission", required=True, type=lambda x: Path(x).resolve()) + ap.add_argument("--benchmark", required=True, type=lambda x: Path(x).resolve(), help="dir with one sub-dir per context") + ap.add_argument("--sealed", required=True, type=lambda x: Path(x).resolve()) + ap.add_argument("--output", required=True, type=lambda x: Path(x).resolve()) + ap.add_argument("--timeout-per-context", type=int, default=3600) + ap.add_argument("--no-wait", action="store_true") + args = ap.parse_args() + args.output.mkdir(parents=True, exist_ok=True) + try: + validate_submission(args.submission) + except (FileNotFoundError, ValueError) as error: + # An invalid package scores 0 (TASK_STANDARD.md); Harbor needs reward.json. + reason = f"{type(error).__name__}: {error}" + (args.output / "report.json").write_text(json.dumps( + {"status": "invalid_submission", "error": reason[:4000], "reward": 0.0}, indent=2) + "\n") + (args.output / "reward.json").write_text(json.dumps({"reward": 0.0, "invalid_submission": 1.0}, indent=2) + "\n") + print(f"invalid submission: {reason}") + return + # $TASK_DATA_DIR/test//public/{basal.h5ad, requests.jsonl, context.json} + contexts = sorted(p for p in args.benchmark.iterdir() if (p / "public" / "requests.jsonl").exists()) + if not contexts: + raise FileNotFoundError(f"no contexts under {args.benchmark} (expected /public/requests.jsonl)") + work = args.output / "main" + work.mkdir(exist_ok=True) + temporary = args.sealed.with_name(args.sealed.name + ".tmp") + temporary.mkdir(parents=True) + snapshot = {"schema": "virtual-cell-zeroshot-snapshot/v1", "contexts": {}} + status = {} + for ctx_dir in contexts: + ctx = ctx_dir / "public" + ctx_name = ctx_dir.name + untrusted = work / ctx_name / "untrusted-output" + t0 = time.time() + try: + run_inference(args.submission, ctx, untrusted, work / ctx_name / "inference.log", args.timeout_per_context, + os.environ.get("CUDA_VISIBLE_DEVICES", "0")) + prediction = untrusted / "predictions.h5ad" + if prediction.stat().st_size > 16 * 1024 ** 3: + raise ValueError("prediction file exceeds 16 GiB") + info = validate_output(prediction, ctx / "basal.h5ad", ctx / "requests.jsonl") + (temporary / ctx_name).mkdir() + shutil.copyfile(prediction, temporary / ctx_name / "predictions.h5ad", follow_symlinks=False) + snapshot["contexts"][ctx_name] = {"predictions_sha256": sha256(temporary / ctx_name / "predictions.h5ad"), + "requests_sha256": sha256(ctx / "requests.jsonl"), + "basal_sha256": sha256(ctx / "basal.h5ad"), **info, + "seconds": round(time.time() - t0, 1)} + status[ctx_name] = {"status": "ok", "seconds": round(time.time() - t0, 1)} + except Exception as exc: # a failed context scores 0 but must not hide the others + status[ctx_name] = {"status": "failed", "error": f"{type(exc).__name__}: {exc}", "seconds": round(time.time() - t0, 1)} + snapshot["contexts"][ctx_name] = {"failed": True, "error": status[ctx_name]["error"]} + finally: + shutil.rmtree(untrusted, ignore_errors=True) + (temporary / "snapshot.json").write_text(json.dumps(snapshot, indent=2, sort_keys=True) + "\n") + for path in temporary.rglob("*"): + path.chmod(0o444 if path.is_file() else 0o555) + temporary.chmod(0o555) + os.replace(temporary, args.sealed) + (args.output / "inference_status.json").write_text(json.dumps(status, indent=2) + "\n") + (args.sealed.parent / "READY").write_text(sha256(args.sealed / "snapshot.json") + "\n") + if not args.no_wait: + result = args.sealed.parent / "results" + deadline = time.monotonic() + 7200 + while not (result / "reward.json").is_file(): + if time.monotonic() >= deadline: + raise TimeoutError("grader did not publish rewards") + time.sleep(2) + for name in ("reward.json", "report.json", "agent_feedback.json"): + if (result / name).is_file(): + shutil.copyfile(result / name, args.output / name) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/5e/5e8cc429059895f59eae9769bdd437fc18351929e3b11c18aebc67bcbbac1e5f/test_neural.py b/reproduction/files/5e/5e8cc429059895f59eae9769bdd437fc18351929e3b11c18aebc67bcbbac1e5f/test_neural.py new file mode 100644 index 0000000000000000000000000000000000000000..ff4941e245ac3002fd39eb7569752e693fff4fe9 --- /dev/null +++ b/reproduction/files/5e/5e8cc429059895f59eae9769bdd437fc18351929e3b11c18aebc67bcbbac1e5f/test_neural.py @@ -0,0 +1,80 @@ +"""CPU numerical checks for native model fidelity and checkpoint portability. + +Run with CUDA_VISIBLE_DEVICES=-1 to keep these small checks off training GPUs. +""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import numpy as np +import pytest +import tensorflow as tf + +from baselines.neural import ( + EXPECTED_PARAMETER_COUNTS, + REFERENCE_DIR, + UPSTREAM_COMMIT, + build_model, + model_config, +) + + +def test_vendored_sources_match_pinned_hashes() -> None: + provenance = json.loads((REFERENCE_DIR / "provenance.json").read_text()) + assert provenance["commit"] == UPSTREAM_COMMIT + assert provenance["modifications"] == [] + for name, digest in provenance["files_sha256"].items(): + assert hashlib.sha256((REFERENCE_DIR / name).read_bytes()).hexdigest() == digest + + +@pytest.mark.parametrize("distance", [3, 5]) +def test_native_model_training_and_checkpoint(distance: int, tmp_path: Path) -> None: + tf.keras.backend.clear_session() + with tf.device("/CPU:0"): + model = build_model(distance, seed=74) + assert model.count_params() == EXPECTED_PARAMETER_COUNTS[distance] + assert model.output_names == ["main_output", "aux_output"] + assert model.input_shape == [ + (None, None, distance**2 - 1), + (None, (distance**2 - 1) // 2), + ] + random = np.random.default_rng(99) + inputs = { + "rec_input": random.integers( + 0, 2, size=(8, 3, distance**2 - 1) + ).astype(np.float32), + "eval_input": random.integers( + 0, 2, size=(8, (distance**2 - 1) // 2) + ).astype(np.float32), + } + labels = np.array([[0], [1]] * 4, dtype=np.float32) + targets = {"main_output": labels, "aux_output": labels} + initial_weight = model.trainable_variables[0].numpy().copy() + losses = model.train_on_batch(inputs, targets, return_dict=True) + assert all(np.isfinite(value) for value in losses.values()) + assert not np.array_equal(initial_weight, model.trainable_variables[0].numpy()) + expected = model(inputs, training=False) + assert all(np.isfinite(output.numpy()).all() for output in expected) + + checkpoint = tmp_path / f"d{distance}.weights.h5" + model.save_weights(checkpoint) + restored = build_model(distance, seed=18) + restored.load_weights(checkpoint) + actual = restored(inputs, training=False) + for before, after in zip(expected, actual): + np.testing.assert_allclose(before.numpy(), after.numpy(), rtol=0, atol=1e-7) + + +def test_width_override_and_invalid_architectures() -> None: + assert model_config(5, width=128)["model"]["LSTM"]["units"] == [128, 128] + with pytest.raises(ValueError, match="distances"): + model_config(7) + for width in (0, -1, True, 64.5): + with pytest.raises(ValueError, match="width"): + model_config(3, width=width) + for learning_rate in (0, -1, float("nan"), float("inf")): + with pytest.raises(ValueError, match="learning_rate"): + model_config(3, learning_rate=learning_rate) diff --git a/reproduction/files/5f/5f42fbed622e41223d979bd757cb153aff7ce427b5349a93f958bd38c8d31d23/conftest.py b/reproduction/files/5f/5f42fbed622e41223d979bd757cb153aff7ce427b5349a93f958bd38c8d31d23/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..deab3ecd1f644866e32fb0ed6728ee73146756e8 --- /dev/null +++ b/reproduction/files/5f/5f42fbed622e41223d979bd757cb153aff7ce427b5349a93f958bd38c8d31d23/conftest.py @@ -0,0 +1,8 @@ +"""Put the baseline project (qecbench, baselines) on sys.path: environment/baseline/alphaqubit in the +repository, /opt/task in the verifier image.""" +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +PROJECT = ROOT / "environment" / "baseline" / "alphaqubit" +sys.path.insert(0, str(PROJECT if PROJECT.is_dir() else ROOT)) diff --git a/reproduction/files/5f/5fec35388621da6a2c7289430ac353296e2f1b4c789c3a479dcae190e1aac9bb/test_external_lfmc_reconcile.py b/reproduction/files/5f/5fec35388621da6a2c7289430ac353296e2f1b4c789c3a479dcae190e1aac9bb/test_external_lfmc_reconcile.py new file mode 100644 index 0000000000000000000000000000000000000000..f2871d0c3543ec2b4c62bb5ecaba24bf03fbd5c4 --- /dev/null +++ b/reproduction/files/5f/5fec35388621da6a2c7289430ac353296e2f1b4c789c3a479dcae190e1aac9bb/test_external_lfmc_reconcile.py @@ -0,0 +1,137 @@ +"""Cohort gate must not silently drop failures or trust stale success receipts.""" + +import json +from pathlib import Path +import sys +import tempfile +import unittest + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/downstream")) +from reconcile_external_lfmc_cohort import digest, reconcile + + +def write(path, value): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value)) + + +class CohortGateTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.cohort = self.root / "cohort" + self.directory = self.cohort / "0000" + self.manifest = self.root / "manifest.json" + self.launch = self.root / "launch.json" + site = {"site_id": "site", "observations": [{"date": "2020-01-01"}]} + write(self.manifest, {"sites": [site]}) + sources = {"source.py": "pinned"} + write( + self.launch, + { + "manifest_sha256": digest(self.manifest), + "tasks": 1, + "sites": 1, + "source_sha256": sources, + }, + ) + write( + self.directory / "manifest.json", + { + "sites": [site], + "parent_task_index": 0, + "parent_manifest_sha256": digest(self.manifest), + }, + ) + scope = {"target_used": False, "model_used": False} + identity = {"site_id": "site", "date": "2020-01-01", **scope} + acquired = { + **identity, + "manifest_sha256": digest(self.directory / "manifest.json"), + } + write(self.directory / "dataset/completion.json", acquired) + verification = { + **scope, + "structural_checks_passed": True, + "periods": [ + {"modality": m, "index": i} + for m in ("sentinel1", "sentinel2") + for i in range(12) + ], + } + write(self.directory / "verification.json", verification) + arrays = { + "sentinel2_l2a": np.zeros((32, 32, 12, 12), dtype=np.float32), + "sentinel1": np.zeros((32, 32, 12, 2), dtype=np.float32), + "sentinel2_l2a_valid": np.ones((12, 3), dtype=bool), + "sentinel1_valid": np.ones((12, 1), dtype=bool), + } + (self.directory / "input").mkdir() + np.savez_compressed(self.directory / "input/input.npz", **arrays) + input_hash = digest(self.directory / "input/input.npz") + prepared = { + **acquired, + "input_sha256": input_hash, + "verification_sha256": digest(self.directory / "verification.json"), + "arrays": { + k: {"shape": list(v.shape), "dtype": str(v.dtype)} + for k, v in arrays.items() + }, + } + write(self.directory / "input/report.json", prepared) + launched = { + **identity, + "task_index": 0, + "parent_manifest_sha256": digest(self.manifest), + "source_sha256": sources, + } + write(self.directory / "launch.json", launched) + write( + self.directory / "completion.json", {**launched, "input_sha256": input_hash} + ) + + def audit(self): + return reconcile(self.manifest, self.launch, self.cohort) + + def test_complete(self): + self.assertTrue(self.audit()["all_inputs_verified"]) + + def test_missing_receipt_stays_in_manifest(self): + (self.directory / "completion.json").unlink() + result = self.audit() + self.assertFalse(result["all_inputs_verified"]) + self.assertEqual(result["counts"]["incomplete"], 1) + self.assertEqual(len(result["rows"]), 1) + + def test_failure_overrides_success(self): + write(self.directory / "failure.json", {"exit_code": 1}) + self.assertEqual(self.audit()["counts"]["failure_record_present"], 1) + + def test_modified_input_is_rejected(self): + with (self.directory / "input/input.npz").open("ab") as handle: + handle.write(b"changed") + self.assertEqual(self.audit()["counts"]["invalid"], 1) + + def test_wrong_site_is_rejected(self): + path = self.directory / "dataset/completion.json" + report = json.loads(path.read_text()) + report["site_id"] = "wrong" + write(path, report) + self.assertEqual(self.audit()["counts"]["invalid"], 1) + + def test_extra_directory_is_rejected(self): + (self.cohort / "0623").mkdir() + self.assertFalse(self.audit()["all_inputs_verified"]) + + def test_parent_change_is_rejected(self): + with self.manifest.open("a") as handle: + handle.write(" ") + with self.assertRaisesRegex(ValueError, "manifest hash"): + self.audit() + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/60/60f5bf249d2de9035968f750ab3b8d28abd0fe452edf2777ca70dc6561a50b83/panel_scoring.py b/reproduction/files/60/60f5bf249d2de9035968f750ab3b8d28abd0fe452edf2777ca70dc6561a50b83/panel_scoring.py new file mode 100644 index 0000000000000000000000000000000000000000..db14191171b822e2f823e2d106c740cc6750e4dd --- /dev/null +++ b/reproduction/files/60/60f5bf249d2de9035968f750ab3b8d28abd0fe452edf2777ca70dc6561a50b83/panel_scoring.py @@ -0,0 +1,154 @@ +"""Primary reward: case detection for serious new-onset disease at a fixed alert budget. + +For each endpoint in a prespecified clinical panel, eligible patients are complete-year patients +whose one-year label is valid (the disease is not yet recorded) and whose history carries none of +the endpoint's precursor or recoding codes. Patients are ranked by their predicted 365-day risk, +and the score is the share of next-year cases found among the top 5 % ("if 1 in 20 discharged +patients can be followed up, how many future cases are reached"). Chance is 0.05 and perfect is +1.0. The reward is the mean over the endpoints with at least MIN_POSITIVES eligible cases. That set +depends only on the frozen labels, never on predictions. + +Ties are scored by their expectation under random tie-breaking, so neither row order nor a +constant prediction can earn more than chance (ceil(0.05 n)/n, i.e. 0.05 up to rounding). +""" + +from __future__ import annotations + +import math + +import numpy as np + +ALERT_RATES = (0.05, 0.01) +PRIMARY = "panel_recall_at_5pct" +MIN_POSITIVES = 20 + +# Prespecified before any model was scored: serious outcomes where earlier anticipation can +# change care. Obstetric, substance-use, organism-supplementary, complication-of-care and symptom +# codes are excluded because they mostly continue already recorded care. The second element lists +# history codes that make a patient ineligible: precursors or recodings of the same condition, +# beyond the task's own same-code risk set. "ICD9:" entries match unmapped ICD-9 history codes by +# prefix; other entries match three-character ICD-10 categories exactly. +PANEL = { + "I50": ("heart failure", ("I11", "I13", "ICD9:428")), + "I48": ("atrial fibrillation/flutter", ("ICD9:4273",)), + "I21": ("acute myocardial infarction", ("I22", "ICD9:410", "ICD9:412")), + "I63": ("ischaemic stroke", ("I69", "ICD9:433", "ICD9:434", "ICD9:438")), + "I61": ("intracerebral haemorrhage", ("ICD9:431",)), + "I26": ("pulmonary embolism", ("ICD9:4151",)), + "I82": ("venous thrombosis", ("ICD9:453",)), + "I71": ("aortic aneurysm/dissection", ("ICD9:441",)), + "E11": ("type 2 diabetes", ("E08", "E09", "E10", "E13", "ICD9:250")), + "N18": ("chronic kidney disease", ("I12", "I13", "N19", "ICD9:585", "ICD9:403", "ICD9:404")), + "N17": ("acute kidney injury", ("ICD9:584",)), + "A41": ("sepsis", ("ICD9:038", "ICD9:99591", "ICD9:99592")), + "J18": ("pneumonia", ("ICD9:481", "ICD9:482", "ICD9:485", "ICD9:486")), + "J96": ("respiratory failure", ("ICD9:51881", "ICD9:51882", "ICD9:51884")), + "K74": ("hepatic fibrosis/cirrhosis", ("K70", "ICD9:5712", "ICD9:5715", "ICD9:5716")), + "K72": ("hepatic failure", ("ICD9:5722",)), + "F03": ("dementia", ("F01", "F02", "G30", "G31", "ICD9:290", "ICD9:2941", "ICD9:331")), + "J44": ("COPD", ("J43", "ICD9:491", "ICD9:492", "ICD9:496")), + "J84": ("interstitial lung disease", ("ICD9:515", "ICD9:516")), + "C18": ("colon cancer", ("ICD9:153",)), + "C22": ("liver cancer", ("ICD9:155",)), + "C25": ("pancreatic cancer", ("ICD9:157",)), + "C61": ("prostate cancer", ("ICD9:185",)), + "C67": ("bladder cancer", ("ICD9:188",)), + "C78": ("metastasis, respiratory/digestive", + ("C77", "C79", "C80", "ICD9:196", "ICD9:197", "ICD9:198", "ICD9:199")), + "C79": ("metastasis, other sites", + ("C77", "C78", "C80", "ICD9:196", "ICD9:197", "ICD9:198", "ICD9:199")), +} + + +def history_code(code: str) -> str: + """The history token compared with PANEL families: ICD-10 category or raw ICD-9 code.""" + return code if code.startswith("ICD9:") else code[:3] + + +def has_family_history(codes: set[str], family: tuple[str, ...]) -> bool: + icd10 = {f for f in family if not f.startswith("ICD9:")} + icd9 = tuple(f for f in family if f.startswith("ICD9:")) + return any(c in icd10 or (icd9 and c.startswith(icd9)) for c in codes) + + +def recall_at(y: np.ndarray, p: np.ndarray, rate: float) -> tuple[float, float]: + """Expected recall and PPV of flagging the top ceil(rate*n) patients, ties split evenly.""" + n, positives = len(y), int(y.sum()) + k = max(1, math.ceil(rate * n)) + threshold = np.sort(p)[::-1][k - 1] + above = p > threshold + tied = p == threshold + taken_from_tie = k - int(above.sum()) + found = float(y[above].sum()) + taken_from_tie * float(y[tied].sum()) / int(tied.sum()) + return found / max(positives, 1), found / k + + +def calibration(y: np.ndarray, p: np.ndarray) -> dict: + q = np.clip(p.astype(np.float64), 1e-6, 1 - 1e-6) + logit = np.log(q / (1 - q)) + slope = None + if 0 < y.sum() < len(y) and np.ptp(logit) > 0: + from sklearn.linear_model import LogisticRegression + slope = float(LogisticRegression(C=1e6, max_iter=1000) + .fit(logit.reshape(-1, 1), y).coef_[0, 0]) + edges = np.quantile(q, np.linspace(0, 1, 11)) + bins = np.clip(np.searchsorted(edges, q, side="right") - 1, 0, 9) + ece = float(sum(abs(y[bins == b].mean() - q[bins == b].mean()) * (bins == b).mean() + for b in range(10) if (bins == b).any())) + return {"observed_rate": float(y.mean()), "mean_prediction": float(q.mean()), + "prediction_to_observed": float(q.mean() / max(y.mean(), 1e-12)), + "slope": slope, "ece_decile": ece} + + +def panel_score(labels365: np.ndarray, valid365: np.ndarray, prediction365: np.ndarray, + complete_year: np.ndarray, disease_codes: list[str], + history: list[set[str]]) -> dict: + """labels365/valid365/prediction365: [samples, diseases] at the 365-day horizon.""" + from sklearn.metrics import average_precision_score, roc_auc_score + endpoints = {} + for code, (name, family) in PANEL.items(): + if code not in disease_codes: + continue + j = disease_codes.index(code) + excluded = np.fromiter((has_family_history(h, family) for h in history), bool, + count=len(history)) + eligible = valid365[:, j] & complete_year & ~excluded + y = labels365[eligible, j].astype(np.int64) + p = prediction365[eligible, j].astype(np.float64) + entry = {"name": name, "eligible": int(eligible.sum()), "positives": int(y.sum()), + "family_history_excluded": int((valid365[:, j] & complete_year & excluded).sum()), + "in_reward": bool(y.sum() >= MIN_POSITIVES)} + if 0 < y.sum() < len(y): + for rate in ALERT_RATES: + recall, ppv = recall_at(y, p, rate) + tag = f"{round(rate * 100)}pct" + entry[f"recall_at_{tag}"] = recall + entry[f"ppv_at_{tag}"] = ppv + entry.update(auroc=float(roc_auc_score(y, p)), + auprc=float(average_precision_score(y, p)), + prevalence=float(y.mean()), calibration=calibration(y, p)) + endpoints[code] = entry + scored = [e for e in endpoints.values() if e["in_reward"]] + + def mean(key): + return float(np.mean([e[key] for e in scored])) if scored else None + + slopes = [e["calibration"]["slope"] for e in scored if e["calibration"]["slope"] is not None] + return { + PRIMARY: mean("recall_at_5pct"), + "panel_recall_at_1pct": mean("recall_at_1pct"), + "panel_ppv_at_5pct": mean("ppv_at_5pct"), + "panel_auroc": mean("auroc"), + "panel_auprc": mean("auprc"), + "panel_calibration_slope_median": float(np.median(slopes)) if slopes else None, + "panel_prediction_to_observed_median": float(np.median( + [e["calibration"]["prediction_to_observed"] for e in scored])) if scored else None, + "panel_ece_decile": mean_of(scored, "ece_decile"), + "endpoints_in_reward": [c for c, e in endpoints.items() if e["in_reward"]], + "min_positives": MIN_POSITIVES, + "endpoints": endpoints, + } + + +def mean_of(scored: list[dict], key: str): + return float(np.mean([e["calibration"][key] for e in scored])) if scored else None diff --git a/reproduction/files/61/61287cb85afb881d53bce5f625a68a183e8763f69229a778429fcbb0137ba3d5/check_submission.py b/reproduction/files/61/61287cb85afb881d53bce5f625a68a183e8763f69229a778429fcbb0137ba3d5/check_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..6295fcb61888750d33f77d6085e3c7ed71d50582 --- /dev/null +++ b/reproduction/files/61/61287cb85afb881d53bce5f625a68a183e8763f69229a778429fcbb0137ba3d5/check_submission.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Contract smoke check: run a package's infer.sh on one input directory in a scratch location +(relocated copy, no workspace access) and validate the output exactly as the verifier does. + + python check_submission.py --package /workspace/submission --input /workspace/data/test/ctx_far/public +""" +import argparse +import json +import os +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +import anndata as ad +import numpy as np +from scipy import sparse + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from cellscore import read_requests # noqa: E402 + + +def validate(pred_path: Path, basal_path: Path, requests_path: Path) -> dict: + expected = read_requests(requests_path) + basal = ad.read_h5ad(basal_path, backed="r") + pred = ad.read_h5ad(pred_path) + problems = [] + if "request_id" not in pred.obs: + problems.append("obs.request_id missing") + if pred.var_names.has_duplicates: + problems.append("duplicate genes") + if list(map(str, pred.var_names)) != list(map(str, basal.var_names)): + problems.append("gene order differs from basal.h5ad") + if "request_id" in pred.obs: + counts = pred.obs["request_id"].astype(str).value_counts().to_dict() + want = {r["request_id"]: r["n_cells"] for r in expected} + if counts != want: + missing = sorted(set(want) - set(counts))[:5] + extra = sorted(set(counts) - set(want))[:5] + wrong = [k for k in want if k in counts and counts[k] != want[k]][:5] + problems.append(f"request/cell-count mismatch: missing={missing} extra={extra} wrong_count={wrong}") + values = pred.X.data if sparse.issparse(pred.X) else np.asarray(pred.X) + if not np.isfinite(values).all() or (values < 0).any(): + problems.append("negative or non-finite values") + if values.size and values.max() < 15 and not np.allclose(values, np.round(values)): + problems.append("values look log-normalised; the contract requires count-scale output") + return {"ok": not problems, "problems": problems, "n_cells": int(pred.n_obs), "n_genes": int(pred.n_vars)} + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--package", required=True, type=Path) + ap.add_argument("--input", required=True, type=Path) + ap.add_argument("--timeout", type=int, default=3600) + ap.add_argument("--keep", action="store_true") + a = ap.parse_args() + tmp = Path(tempfile.mkdtemp(prefix="vcz-check-")) + pkg = tmp / "package" + shutil.copytree(a.package, pkg, symlinks=False) + out = tmp / "out" + env = {"PATH": os.environ["PATH"], "HOME": str(tmp), "PYTHONUNBUFFERED": "1", "PIP_NO_INDEX": "1", + "HF_HUB_OFFLINE": "1", "SE600M_DIR": os.environ.get("SE600M_DIR", "/opt/se600m"), + "CUDA_VISIBLE_DEVICES": os.environ.get("CUDA_VISIBLE_DEVICES", "0")} + t0 = time.time() + proc = subprocess.run(["bash", str(pkg / "infer.sh"), str(a.input.resolve()), str(out)], cwd=pkg, env=env, + capture_output=True, text=True, timeout=a.timeout) + result = {"exit_code": proc.returncode, "seconds": round(time.time() - t0, 1), "scratch": str(tmp)} + if proc.returncode != 0: + result.update(ok=False, problems=["infer.sh failed"], stderr_tail=proc.stderr[-4000:]) + else: + result.update(validate(out / "predictions.h5ad", a.input / "basal.h5ad", a.input / "requests.jsonl")) + print(json.dumps(result, indent=2)) + if not a.keep: + shutil.rmtree(tmp, ignore_errors=True) + sys.exit(0 if result.get("ok") else 1) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/62/629fbfbb19a3f524c269dd118a3cf448e1ee5154fabd4536034c5a3ea120a92c/native_envs.py b/reproduction/files/62/629fbfbb19a3f524c269dd118a3cf448e1ee5154fabd4536034c5a3ea120a92c/native_envs.py new file mode 100644 index 0000000000000000000000000000000000000000..7f4a13281ac73f6cfb362757305b73ed50f3a788 --- /dev/null +++ b/reproduction/files/62/629fbfbb19a3f524c269dd118a3cf448e1ee5154fabd4536034c5a3ea120a92c/native_envs.py @@ -0,0 +1,175 @@ +"""MAIA, JAX and JAX-Fluids bindings for one shared action-only contract.""" +from pathlib import Path + +from protocol import InfrastructureError + + +def kolmogorov(): + import gymnasium as gym + import jax + import numpy as np + jax.config.update('jax_enable_x64', True) + from hydrogym.jax.envs.kolmogorov import KolmogorovFlow + + class KolmogorovEnv(gym.Env): + def __init__(self): + self.native = KolmogorovFlow(env_config={}, flow_config={}) + self.params = self.native.default_params.replace(reward_alpha=1.0) + self.key = jax.random.PRNGKey(123) + self.advance = jax.jit(lambda k, s, a: self.native.step_env(k, s, a, self.params)) + self.observation_space = gym.spaces.Box(-np.inf, np.inf, shape=(64,), dtype=np.float64) + self.action_space = gym.spaces.Box(-.5, .5, shape=(4,), dtype=np.float64) + + def reset(self, seed=None, options=None): + super().reset(seed=seed) + self.key = jax.random.PRNGKey(123 if seed is None else seed) + obs, self.state = self.native.reset_env(self.key, self.params) + return np.asarray(obs, dtype=np.float64), {} + + def step(self, action): + self.key, key = jax.random.split(self.key) + obs, self.state, reward, done, info = self.advance( + key, self.state, np.asarray(action, dtype=np.float64)) + return np.asarray(obs, dtype=np.float64), float(reward), bool(done), False, info + return KolmogorovEnv() + + +def nozzle(case, data): + import hydrogym.jaxfluids.envs.nozzle as module + from native_resource_bindings import bind_nozzle_restart + original = module.build_tvc_runtime_setup + if case['environment'] == 'Nozzle2D_fine': + def setup_with_source_restart(**kwargs): + setup = original(**kwargs) + restart = Path(setup.restart_file_path).resolve() + if not restart.is_relative_to(data / 'environments' / case['environment']): + raise InfrastructureError('Nozzle restart escaped the selected source') + # The upstream named tuple contains a mutable config dict. + updated = bind_nozzle_restart(case['environment'], setup.case_setup_dict, str(restart)) + setup.case_setup_dict.update(updated) + return setup + module.build_tvc_runtime_setup = setup_with_source_restart + try: + env = module.Nozzle2D({'environment_name': case['environment'], + 'use_clean_cache': False, 'local_fallback_dir': str(data / 'environments')}) + finally: + module.build_tvc_runtime_setup = original + if Path(env.env_data_path).resolve() != data / 'environments' / case['environment']: + raise InfrastructureError('Nozzle loaded a different source') + return env + + +def make_env(case, data): + import numpy as np + profile = case['runtime_profile'] + backend = case['backend'] + if backend == 'maia': + from run_maia import make_env as make_maia + env = make_maia(case, data) + expected = {'max_episode_steps': profile['native_max_episode_steps'], + 'substeps_per_action': profile['substeps_per_control'], + 'max_control': profile['max_control'], 'omega': profile['omega']} + if env.reviewed_protocol['native_defaults'] != expected: + raise InfrastructureError('MAIA source dynamics differ from the frozen profile') + elif case['environment'] == 'Channel_3D_Retau180': + from native_channel import ChannelEnv + env = ChannelEnv(data) + for key, expected in profile['params'].items(): + if getattr(env.params, key) != expected: + raise InfrastructureError(f'Channel parameter changed: {key}') + elif case['environment'] == 'Kolmogorov_2D': + env = kolmogorov() + for key, expected in profile['params'].items(): + if isinstance(expected, str) and expected in ('inf', '-inf'): + expected = float(expected) + if getattr(env.params, key) != expected: + raise InfrastructureError(f'Kolmogorov parameter changed: {key}') + if env.native.flow.Re != 200 or tuple(env.native.flow.grid_size) != (64, 64): + raise InfrastructureError('Kolmogorov grid/Re changed') + elif backend == 'jax-fluids': + env = nozzle(case, data) + from omegaconf import OmegaConf + actual = OmegaConf.to_container(env.conf, resolve=True) + if actual != profile['source_configuration']: + raise InfrastructureError('Nozzle source configuration changed') + else: + raise InfrastructureError(f'Backend not implemented: {backend}') + if (list(env.observation_space.shape) != case['observation_shape'] or + list(env.action_space.shape) != case['action_shape']): + raise InfrastructureError('Native observation/action spaces changed') + if backend != 'maia': + import jax + if len(jax.devices()) != case['solver_processes'] or any(device.platform != 'gpu' for device in jax.devices()): + raise InfrastructureError('Native JAX evaluation requires the allocated GPU') + return env + + +class ReplayAdapter: + """Strict complete-episode checking, scalar diagnostics and progress receipts.""" + def __init__(self, env, case, output): + self.env, self.case, self.output = env, case, output + self.observation_space, self.action_space = env.observation_space, env.action_space + self.count = None + self.captured_physical = None + self.capture_reward = case.get('backend') == 'maia' and 'primary_metric' in case + if self.capture_reward: + # Pinned MaiaFlowEnv.step discards get_reward()'s objective dict and + # returns info={}. Capture the existing force read in that call; + # never make a second MPI/CFD query or change the native reward. + base = getattr(env, 'unwrapped', env) + original_reward = base.get_reward + def recorded_reward(): + reward, objective = original_reward() + from metrics import sample + self.captured_physical = sample(base, self.case, objective, reward) + return reward, objective + base.get_reward = recorded_reward + + def report(self, phase): + from evaluate import write_json + write_json(self.output / 'progress.json', {'case': self.case['id'], 'phase': phase, + 'step': self.count, 'horizon': self.case['horizon']}) + + def reset(self, seed): + self.count = 0 + self.physical_samples = [] + self.report('reset') + result = self.env.reset(seed=seed) + self.report('control') + return result + + def step(self, action): + import numpy as np + if self.count is None or self.count >= self.case['horizon']: + raise InfrastructureError('Reset required before another native step') + self.captured_physical = None + obs, reward, done, truncated, info = self.env.step( + np.asarray(action, dtype=self.action_space.dtype).reshape(self.action_space.shape)) + self.count += 1 + if np.asarray(reward).ndim != 0: + raise InfrastructureError('Native vector reward has no reviewed scalar adapter') + if bool(done or truncated) != (self.count == self.case['horizon']): + raise InfrastructureError(f'Native termination differs from frozen horizon: {self.count}') + scalar_info = {} + if 'primary_metric' in self.case: + from metrics import sample + physical = self.captured_physical if self.capture_reward else sample(self.env, self.case, info, reward) + if physical is None: + raise InfrastructureError('MAIA did not expose this step\'s physical objective') + self.physical_samples.append(physical) + scalar_info.update(physical) + for key, value in info.items(): + if isinstance(value, (str, dict)) or value is None: + continue + a = np.asarray(value) + if a.size == 1 and np.issubdtype(a.dtype, np.number): + scalar_info[key] = float(a.reshape(-1)[0]) + if not np.all(np.isfinite(np.asarray(obs))) or not np.isfinite(reward): + raise InfrastructureError(f'Nonfinite native observation/reward at control {self.count}') + if self.count == 1 or self.count % 10 == 0 or done or truncated: + self.report('complete' if done or truncated else 'control') + return obs, float(reward), bool(done), bool(truncated), scalar_info + + def evaluation_metrics(self): + from metrics import summarize + return summarize(self.case['primary_metric'], self.physical_samples, self.case['horizon']) diff --git a/reproduction/files/62/62cbf959583b3e30c62bcd8a383a7f19c19f81c49994782684f70e8275c25173/test_harbor_physical.py b/reproduction/files/62/62cbf959583b3e30c62bcd8a383a7f19c19f81c49994782684f70e8275c25173/test_harbor_physical.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c3f1ecad9aa4a15f620a26f4cf7de4ad1db31f --- /dev/null +++ b/reproduction/files/62/62cbf959583b3e30c62bcd8a383a7f19c19f81c49994782684f70e8275c25173/test_harbor_physical.py @@ -0,0 +1,138 @@ +"""CPU interface tests; synthetic numbers are not reported baseline results.""" +import copy +from pathlib import Path +import sys +import json +from tempfile import TemporaryDirectory +import unittest + +sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'environment/evaluation')) +from case_spec import select_cases +from harbor_verify import physical_rewards, verify +from protocol import InfrastructureError, PolicyError + + +class PhysicalHarborTests(unittest.TestCase): + def fixture(self,names=('all',)): + _,cases=select_cases(list(names)) + return {'cases':{c['id']:{'status':'ok','primary_metric': + dict(c['primary_metric'],status='ok',value=1.25)} for c in cases}} + + def test_complete_reward_has_exactly_39_named_physical_values(self): + rewards=physical_rewards(self.fixture(),['all']) + self.assertEqual(rewards.pop('failed_cases'),0) + self.assertEqual(len(rewards),39) + self.assertNotIn('score',rewards) + self.assertEqual(rewards['Cylinder_2D_Re200/drag_cd'],1.25) + self.assertEqual(rewards['NACA0012_2D_Re100_AOA20/lift_drag'],1.25) + + def test_missing_case_cannot_be_silently_dropped(self): + result=self.fixture();result['cases'].pop('Cylinder_3D_Re3900') + with self.assertRaises(InfrastructureError):physical_rewards(result,['all']) + + def test_policy_and_infrastructure_errors_are_distinct(self): + result=self.fixture();result['cases']['Cylinder_2D_Re200']={'status':'infrastructure_error'} + with self.assertRaises(InfrastructureError):physical_rewards(result,['all']) + # A policy error fails its case only; every other case keeps its physical value. + result=self.fixture();result['cases']['Cylinder_2D_Re200']={'status':'policy_error'} + rewards=physical_rewards(result,['all']) + self.assertEqual(rewards['Cylinder_2D_Re200/failed'],1) + self.assertNotIn('Cylinder_2D_Re200/drag_cd',rewards) + self.assertEqual(rewards['failed_cases'],1) + self.assertEqual(rewards['NACA0012_2D_Re100_AOA20/lift_drag'],1.25) + + def test_all_cases_failed_is_a_policy_error(self): + result=self.fixture() + for name in result['cases']:result['cases'][name]={'status':'policy_error'} + with self.assertRaises(PolicyError):physical_rewards(result,['all']) + + def test_nonfinite_and_wrong_units_rejected(self): + for change in [dict(value=float('nan')),dict(value=True),dict(units='wrong')]: + result=self.fixture();result['cases']['Cylinder_2D_Re200']['primary_metric'].update(change) + with self.assertRaises(InfrastructureError):physical_rewards(result,['all']) + + def test_invalid_physical_regime_is_not_a_zero_or_reward(self): + result=self.fixture() + result['cases']['NACA0012_2D_Re100_AOA20']['primary_metric'].update(status='invalid_operating_regime',value=None) + rewards=physical_rewards(result,['all']) + self.assertEqual(rewards['NACA0012_2D_Re100_AOA20/failed'],1) + self.assertNotIn('NACA0012_2D_Re100_AOA20/lift_drag',rewards) + + def test_subset_is_explicit_and_keeps_original_units(self): + result=self.fixture();result['cases']={'Nozzle2D_fine':result['cases']['Nozzle2D_fine']} + self.assertEqual(physical_rewards(result,['Nozzle2D_fine']),{'Nozzle2D_fine/nozzle_angle_mae':1.25,'failed_cases':0}) + + def test_verifier_default_is_the_scored_suite_and_writes_numeric_file(self): + with TemporaryDirectory() as folder: + def fake(data,submission,output,names): + self.assertEqual(names,['verifier']) + return self.fixture(names) + reward=verify('/unused-data','/unused-submission',folder,evaluator=fake) + self.assertEqual(json.loads((Path(folder)/'reward.json').read_text()),reward) + self.assertEqual(json.loads((Path(folder)/'grading.json').read_text())['scope'],'verifier-suite') + self.assertEqual(len(reward),26+1) + + def test_complete_suite_is_still_gradable(self): + with TemporaryDirectory() as folder: + reward=verify('/unused','/unused2',folder,['all'],evaluator=lambda *a:self.fixture()) + self.assertEqual(json.loads((Path(folder)/'grading.json').read_text())['scope'],'full-39') + self.assertEqual(len(reward),39+1) + + def test_policy_error_preserves_diagnostic_and_marks_invalid(self): + with TemporaryDirectory() as folder: + def fake(data,submission,output,names): + result=self.fixture(names) + for name in result['cases']:result['cases'][name]={'status':'policy_error'} + return result + self.assertEqual(verify('/unused','/unused2',folder,evaluator=fake),{'invalid_submission':1}) + # Harbor needs a numeric reward.json; an invalid package has no physical metrics. + self.assertEqual(json.loads((Path(folder)/'reward.json').read_text()),{'invalid_submission':1}) + self.assertEqual(json.loads((Path(folder)/'grading-error.json').read_text())['status'],'policy_error') + + + +class DivergenceTests(unittest.TestCase): + """Invalid simulation state after the policy acts fails the case, not the suite.""" + + class Space: + def __init__(self, n): + import numpy as np + self.shape, self.low, self.high = (n,), np.full(n, -1.0), np.full(n, 1.0) + + class Env: + def __init__(self, fail_at): + self.observation_space = self.action_space = DivergenceTests.Space(1) + self.fail_at, self.steps = fail_at, 0 + def reset(self, seed=None): + return [0.0], {} + def step(self, action): + self.steps += 1 + if self.steps == self.fail_at: + raise InfrastructureError('Missing/invalid per-body force measurements') + return [0.0], 1.0, self.steps == 3, False, {} + + class Policy: + def __init__(self, bad_first=False): + self.bad_first = bad_first + def reset(self, *args): + pass + def act(self, observation): + if self.bad_first: + raise InfrastructureError('Nonfinite/invalid native observation') + return [0.0] + + def test_divergence_after_actions_is_a_policy_error(self): + from protocol import replay_episode + case = {'environment': 'x', 'family': 'f', 'horizon': 3} + with self.assertRaises(PolicyError): + replay_episode(self.Env(fail_at=2), self.Policy(), case, 0) + self.assertEqual(replay_episode(self.Env(fail_at=0), self.Policy(), case, 0)['steps'], 3) + + def test_invalid_state_before_the_first_action_stays_infrastructure(self): + from protocol import replay_episode + case = {'environment': 'x', 'family': 'f', 'horizon': 3} + with self.assertRaises(InfrastructureError): + replay_episode(self.Env(fail_at=0), self.Policy(bad_first=True), case, 0) + + +if __name__=='__main__':unittest.main() diff --git a/reproduction/files/63/6333d808fabdc5a2c93c4f07b0fce71a5ab1b22a9590ddc3cf96049287663593/docker-compose.yaml b/reproduction/files/63/6333d808fabdc5a2c93c4f07b0fce71a5ab1b22a9590ddc3cf96049287663593/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2b3e98c90b57976e30f3c19d1eeadaf7aed40c58 --- /dev/null +++ b/reproduction/files/63/6333d808fabdc5a2c93c4f07b0fce71a5ab1b22a9590ddc3cf96049287663593/docker-compose.yaml @@ -0,0 +1,161 @@ +volumes: + sealed: + verifier_logs: + +services: + main: + build: + context: .. + dockerfile: tests/Dockerfile + network_mode: none + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] + shm_size: "64gb" + volumes: + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/physical/inputs + target: /benchmark/test/physical/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/kappa/inputs + target: /benchmark/test/kappa/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/mof/inputs + target: /benchmark/test/mof/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/amorphous/inputs + target: /benchmark/test/amorphous/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/cleavage/inputs + target: /benchmark/test/cleavage/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/neb/inputs + target: /benchmark/test/neb/inputs + read_only: true + bind: + create_host_path: false + - sealed:/sealed + - verifier_logs:/logs/verifier + healthcheck: + test: + - CMD-SHELL + - >- + test -d /benchmark/test/physical/inputs && + test -d /benchmark/test/kappa/inputs && + test -d /benchmark/test/mof/inputs && + test -d /benchmark/test/amorphous/inputs && + test -d /benchmark/test/cleavage/inputs && + test -d /benchmark/test/neb/inputs && + test ! -e /benchmark/test/physical/references && + test -z "$$(ls -A /labels 2>/dev/null)" + interval: 5s + timeout: 5s + retries: 3 + + grader: + build: + context: .. + dockerfile: tests/Dockerfile + network_mode: none + command: + - python + - /tests/grader.py + - --sealed + - /sealed/run + - --labels + - /labels + - --output + - /sealed/results + volumes: + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/physical/inputs + target: /labels/physical/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/kappa/inputs + target: /labels/kappa/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/mof/inputs + target: /labels/mof/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/amorphous/inputs + target: /labels/amorphous/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/cleavage/inputs + target: /labels/cleavage/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized release (public tree)}/test/neb/inputs + target: /labels/neb/inputs + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the materialized release (verifier-only tree)}/test/physical/references + target: /labels/physical/references + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the materialized release (verifier-only tree)}/test/kappa/references + target: /labels/kappa/references + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the materialized release (verifier-only tree)}/test/mof/references + target: /labels/mof/references + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the materialized release (verifier-only tree)}/test/amorphous/references + target: /labels/amorphous/references + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the materialized release (verifier-only tree)}/test/cleavage/references + target: /labels/cleavage/references + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the materialized release (verifier-only tree)}/test/neb/references + target: /labels/neb/references + read_only: true + bind: + create_host_path: false + - sealed:/sealed diff --git a/reproduction/files/63/633bf48d017941ca2525b7d62b47bb0d379531fe2f3e86ce98720a7c7d38073a/smoke_verifier.py b/reproduction/files/63/633bf48d017941ca2525b7d62b47bb0d379531fe2f3e86ce98720a7c7d38073a/smoke_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..3c2fc24f19b5284781ccaf5ec4b4b126e7ff265c --- /dev/null +++ b/reproduction/files/63/633bf48d017941ca2525b7d62b47bb0d379531fe2f3e86ce98720a7c7d38073a/smoke_verifier.py @@ -0,0 +1,45 @@ +"""Prepare a tiny synthetic two-phase Docker verifier smoke fixture.""" + +import argparse +import shutil +import sys +from pathlib import Path + +from fixture_data import fixture_source + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "environment" / "data")) +sys.path.insert(0, str(ROOT / "environment" / "references" / "scaffold")) +sys.path.insert(0, str(ROOT / "docs" / "maintenance" / "legacy-neural")) + +from audit import run as audit_run +from materialize import run as materialize_run +from baseline import train + + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument("--output",type=Path,required=True) + args=parser.parse_args() + root=args.output + source,materialized,submission=root/"source",root/"output",root/"submission" + fixture_source(source) + audit_run(source,materialized,ROOT/"environment"/"data"/"cms-2018-gem.zip") + materialize_run(source,materialized,1) + submission.mkdir(parents=True,exist_ok=True) + starter=ROOT/"environment"/"references"/"scaffold" + for name in ("infer.sh", "predict.py", "data.py", "README.md"): + shutil.copy2(starter/name,submission/name) + shutil.copy2(ROOT/"docs"/"maintenance"/"legacy-neural"/"baseline.py", submission/"model.py") + shutil.copy2(ROOT/"docs"/"maintenance"/"legacy-neural"/"adapter.py", submission/"adapter.py") + shutil.copy2(ROOT/"docs"/"maintenance"/"legacy-neural"/"train_baseline.py", submission/"train.py") + (submission/"config.json").write_text('{"fixture_only": true}\n') + train(materialized/"train",materialized/"manifest.json",submission/"model.pt", + epochs=1,batch_size=2,max_samples=4) + (root/"sealed").mkdir(exist_ok=True) + (root/"results").mkdir(exist_ok=True) + print(root) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/68/680ec12531da9bd47cf394ff743ac53b6496a0bf06aa3d29121545393a61dd7d/grade.py b/reproduction/files/68/680ec12531da9bd47cf394ff743ac53b6496a0bf06aa3d29121545393a61dd7d/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..038170dfbbb30ba43c8f919cf2d0848231722f6c --- /dev/null +++ b/reproduction/files/68/680ec12531da9bd47cf394ff743ac53b6496a0bf06aa3d29121545393a61dd7d/grade.py @@ -0,0 +1,192 @@ +"""Independent inference, frozen probes, and numeric reward.""" + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys + +checks = Path(__file__).resolve().parents[1] / "environment/evaluation" +if not checks.is_dir(): + checks = Path(__file__).resolve().parent +if not (checks / "package_contract.py").is_file(): + checks = Path("/evaluation") +sys.path.insert(0, str(checks)) +from package_contract import InvalidSubmission, validate_package + + +def digest(path): + with Path(path).open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def fingerprints(model, data, output, probes): + """Bind deferred scoring to the exact independently replayed artifacts.""" + tests = Path(__file__).resolve().parent + return { + "model": { + name: digest(model / name) + for name in [ + "encoder.pt", + "config.json", + "infer.py", + "provenance.json", + "LICENSE-OlmoEarth", + ] + }, + "unlabeled_inputs": { + task: digest(data / task / "inputs.h5") for task in ["awf", "lfmc"] + }, + "features": { + task: digest(output / task / "features.npz") for task in ["awf", "lfmc"] + }, + "verifier": { + name: digest(tests / name) + for name in ["grade.py", "replay.py", "namespace.py"] + }, + "probes": digest(probes), + "package_contract": digest(checks / "package_contract.py"), + } + + +def validate_manifest(manifest, model, data, output, probes): + if manifest.get("schema_version") != 1 or manifest.get("phase") != "inference": + raise ValueError("Unsupported independent inference manifest") + if manifest.get("fingerprints") != fingerprints(model, data, output, probes): + raise ValueError("Independent replay artifacts or verifier code changed") + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", type=Path, required=True) + p.add_argument("--data", type=Path, required=True) + p.add_argument("--output", type=Path, required=True) + phase = p.add_mutually_exclusive_group() + phase.add_argument( + "--inference-only", + action="store_true", + help="Replay both full input releases without reading labels", + ) + phase.add_argument( + "--score-existing", + action="store_true", + help="CPU scoring of an exact, manifest-verified prior replay", + ) + p.add_argument( + "--probes", + type=Path, + default=Path(__file__).resolve().parents[1] + / "environment/evaluation/probes.py", + ) + a = p.parse_args() + a.output.mkdir(parents=True, exist_ok=True) + manifest_path = a.output / "inference-manifest.json" + if (a.output / "reward.json").exists(): + raise ValueError("Scoring already completed; preserve the existing result") + try: + evaluate(a, manifest_path) + except InvalidSubmission as error: + # Harbor reads reward.json as a flat object of numbers; the reason goes to report.json. + report = {"reward": 0.0, "status": "invalid_submission", "reason": str(error)} + (a.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + (a.output / "reward.json").write_text(json.dumps({"reward": 0.0, "invalid_submission": 1}, indent=2) + "\n") + print(json.dumps(report)) + + +def evaluate(a, manifest_path): + validate_package(a.model) + if a.score_existing: + manifest = json.loads(manifest_path.read_text()) + validate_manifest(manifest, a.model, a.data, a.output, a.probes) + else: + if manifest_path.exists() or any( + (a.output / task / "features.npz").exists() for task in ["awf", "lfmc"] + ): + raise ValueError( + "Replay output already exists; use a fresh output directory" + ) + for task in ["awf", "lfmc"]: + out = a.output / task + out.mkdir(exist_ok=True) + replay_result = subprocess.run( + [ + sys.executable, + str(Path(__file__).with_name("replay.py")), + "--model", + str(a.model), + "--input", + str(a.data / task / "inputs.h5"), + "--output", + str(out), + ], + check=False, + ) + if replay_result.returncode == 42: + raise InvalidSubmission("Isolated replay produced invalid features") + replay_result.check_returncode() + manifest = { + "schema_version": 1, + "phase": "inference", + "recorded_utc": datetime.now(timezone.utc).isoformat(), + "slurm_job_id": os.environ.get("SLURM_JOB_ID"), + "slurm_partition": os.environ.get("SLURM_JOB_PARTITION"), + "python_hash_seed": os.environ.get("OLMO_INFERENCE_HASHSEED"), + "fingerprints": fingerprints(a.model, a.data, a.output, a.probes), + "labels_read": False, + } + manifest_path.write_text(json.dumps(manifest, indent=2) + "\n") + if a.inference_only: + print( + json.dumps( + {"inference_manifest": str(manifest_path), "test_metrics_used": False} + ) + ) + return + scores = {} + for task in ["awf", "lfmc"]: + out = a.output / task + cmd = [ + sys.executable, + str(a.probes), + "--features", + str(out / "features.npz"), + "--labels", + str(a.data / task / "labels.json"), + "--task", + task, + "--output", + str(out / "metrics.json"), + ] + if task == "lfmc": + cmd += ["--final-test"] + subprocess.run(cmd, check=True) + scores[task] = json.loads((out / "metrics.json").read_text()) + awf = scores["awf"]["probe"]["validation"]["accuracy"] + lfmc = scores["lfmc"]["probe"]["test"]["mae"] + constant = scores["lfmc"]["constant_test"]["mae"] + skill = max(0.0, 1 - lfmc / max(constant, 1e-12)) + result = { + "reward": 0.5 * (awf + skill), + "awf_validation_accuracy": awf, + "lfmc_test_mae": lfmc, + "lfmc_test_mae_skill": skill, + } + # Harbor reads reward.json as a flat object of numbers; provenance hashes go to report.json. + report = { + **result, + "status": "scored", + "inference_manifest_sha256": digest(manifest_path), + "label_file_sha256": { + task: digest(a.data / task / "labels.json") for task in ["awf", "lfmc"] + }, + } + (a.output / "report.json").write_text(json.dumps(report, indent=2)) + (a.output / "reward.json").write_text(json.dumps(result, indent=2)) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/68/686461c9b611a2e71d1ccc41f064990f8ba7e90ea759514a7002fea6906df817/grader.py b/reproduction/files/68/686461c9b611a2e71d1ccc41f064990f8ba7e90ea759514a7002fea6906df817/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..345c736fcfa4611c22e77db195d7dabbdceefd49 --- /dev/null +++ b/reproduction/files/68/686461c9b611a2e71d1ccc41f064990f8ba7e90ea759514a7002fea6906df817/grader.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Trusted labels-only service; never executes submitted model code.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys +import time + +import duckdb +import numpy as np + +from common import sha256, write_json + +sys.path.insert(0, "/evaluation") +from panel_scoring import PRIMARY # noqa: E402 +from risk_scoring import read_normalization, score # noqa: E402 + + +def validate_private_split(input_dir: Path, trusted: Path, + normalization: Path) -> None: + manifest = json.loads((input_dir / "manifest.json").read_text()) + if manifest.get("split") != "test": + raise ValueError("Trusted grader accepts only the test input manifest") + diseases = manifest.get("scored_diseases") + if not isinstance(diseases, list) or not diseases: + raise ValueError("Public test manifest has no scored diseases") + public = (input_dir / "samples.parquet").as_posix() + labels = (trusted / "label_windows.parquet").as_posix() + boundaries = (trusted / "sample_boundaries.parquet").as_posix() + db = duckdb.connect() + coverage = db.execute(f"""SELECT + (SELECT count(*) FROM read_parquet('{public}')), + (SELECT count(DISTINCT sample_id) FROM read_parquet('{public}')), + (SELECT count(*) FROM read_parquet('{labels}')), + (SELECT count(DISTINCT (sample_id,disease_code)) FROM read_parquet('{labels}')), + (SELECT count(*) FROM read_parquet('{boundaries}')), + (SELECT count(*) FROM read_parquet('{boundaries}') WHERE split<>'test'), + (SELECT count(*) FROM read_parquet('{public}') p ANTI JOIN + read_parquet('{labels}') l USING(sample_id)), + (SELECT count(*) FROM read_parquet('{public}') p ANTI JOIN + read_parquet('{boundaries}') b USING(sample_id))""").fetchone() + db.close() + expected_pairs = coverage[0] * len(diseases) + if (not coverage[0] or coverage[0] != coverage[1] + or coverage[2] != expected_pairs or coverage[3] != expected_pairs + or coverage[4] != coverage[0] or any(coverage[5:])): + raise ValueError(f"Test public/trusted split coverage is invalid: {coverage}") + read_normalization(normalization, diseases) + + +def grade(args: argparse.Namespace, ready: dict) -> None: + run_id = ready["run_id"] + target = args.output / run_id + target.mkdir(parents=True) + try: + snapshot_path = args.sealed / "snapshot.json" + if sha256(snapshot_path) != ready["snapshot_sha256"]: + raise ValueError("Sealed snapshot hash mismatch") + snapshot = json.loads(snapshot_path.read_text()) + if (snapshot.get("schema") != "natural-disease-progression-prediction-snapshot/v1" + or snapshot.get("run_id") != run_id): + raise ValueError("Sealed snapshot identity mismatch") + if snapshot.get("input_manifest_sha256") != sha256(args.input / "manifest.json"): + raise ValueError("Sealed prediction input mismatch") + prediction = args.sealed / "predictions.parquet" + if snapshot.get("predictions_sha256") != sha256(prediction): + raise ValueError("Sealed prediction hash mismatch") + if {path.name for path in args.sealed.iterdir()} != { + "snapshot.json", "predictions.parquet"}: + raise ValueError("Unexpected file in sealed prediction snapshot") + if not args.normalization.is_file(): + raise FileNotFoundError("Frozen train-only normalization is missing") + validate_private_split(args.input, args.trusted, args.normalization) + try: + report = score(args.input, args.trusted, prediction, args.bootstrap, + args.normalization) + reward = report["panel"][PRIMARY] + if reward is None or not np.isfinite(reward) or not 0.0 <= reward <= 1.0: + raise ValueError(f"Primary {PRIMARY} is unavailable") + report.update({"schema": "natural-disease-progression-report/v3", + "status": "scored", "model_quality_measured": True, + "run_id": run_id, "reward": reward}) + write_json(target / "report.json", report) + write_json(target / "reward.json", {"reward": reward}) + except ValueError as error: + write_json(target / "report.json", { + "schema": "natural-disease-progression-report/v3", + "status": "invalid_prediction", "model_quality_measured": False, + "run_id": run_id, "error": str(error), + }) + write_json(target / "reward.json", {"reward": 0.0}) + except Exception as error: + write_json(target / "report.json", { + "schema": "natural-disease-progression-report/v3", + "status": "infrastructure_error", "model_quality_measured": False, + "run_id": run_id, "error": f"{type(error).__name__}: {error}", + }) + write_json(target / "DONE", {"run_id": run_id}) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--input", type=Path, default=Path("/input")) + parser.add_argument("--trusted", type=Path, default=Path("/trusted/test")) + parser.add_argument("--normalization", type=Path, + default=Path("/trusted/risk_normalization.parquet")) + parser.add_argument("--sealed", type=Path, default=Path("/sealed/run")) + parser.add_argument("--output", type=Path, default=Path("/sealed/results")) + parser.add_argument("--bootstrap", type=int, default=0) + parser.add_argument("--wait-seconds", type=int, default=42600) + args = parser.parse_args() + deadline = time.monotonic() + args.wait_seconds + ready_path = args.sealed.parent / "READY" + while time.monotonic() < deadline: + if ready_path.is_file(): + ready = json.loads(ready_path.read_text()) + run_id = ready.get("run_id", "") + if len(run_id) != 32 or any(c not in "0123456789abcdef" for c in run_id): + raise ValueError("Invalid trusted run identity") + grade(args, ready) + return + time.sleep(0.25) + raise TimeoutError("Inference supervisor did not seal a submission") + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/6b/6b0adba5a784d981d6728a3986511bf5d96f4d9a70f4f893ec2234e8f494bec6/test_lfmc_official_head.py b/reproduction/files/6b/6b0adba5a784d981d6728a3986511bf5d96f4d9a70f4f893ec2234e8f494bec6/test_lfmc_official_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f1442e426cf8bdabb7b07d52d33887b9a638eaa4 --- /dev/null +++ b/reproduction/files/6b/6b0adba5a784d981d6728a3986511bf5d96f4d9a70f4f893ec2234e8f494bec6/test_lfmc_official_head.py @@ -0,0 +1,73 @@ +"""Official LFMC UNet/loss consume differentiable masked spatial features.""" + +from pathlib import Path +import sys +import unittest +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/downstream")) +from masked_spatial import spatial_features +from olmoearth_pretrain.nn.flexi_vit import EncoderConfig +from rslearn.models.component import FeatureMaps +from rslearn.models.unet import UNetDecoder +from rslearn.train.model_context import ModelContext, RasterImage +from rslearn.train.tasks.per_pixel_regression import PerPixelRegressionHead + + +class TestHead(unittest.TestCase): + def test_official_unet_masked_loss_and_backprop(self): + torch.set_num_threads(2) + torch.manual_seed(11) + encoder = EncoderConfig( + supported_modality_names=["sentinel2_l2a", "sentinel1"], + embedding_size=32, + num_heads=4, + depth=1, + drop_path=0, + ).build() + # Preserve official decoder widths/depth; only fixture encoder width is small. + decoder = UNetDecoder( + in_channels=[[4, 32]], + out_channels=1, + conv_layers_per_resolution=2, + num_channels={8: 512, 4: 512, 2: 256, 1: 128}, + ) + head = PerPixelRegressionHead() + pixels = { + "sentinel2_l2a": torch.randn(2, 8, 8, 2, 12), + "sentinel1": torch.randn(2, 8, 8, 2, 2), + } + valid = { + "sentinel2_l2a": torch.ones(2, 2, 3, dtype=torch.bool), + "sentinel1": torch.ones(2, 2, 1, dtype=torch.bool), + } + for v in valid.values(): + v[1] = False + features = spatial_features(encoder, pixels, valid) + context = ModelContext(inputs=[], metadatas=[]) + logits = decoder(FeatureMaps([features]), context) + self.assertEqual(tuple(logits.feature_maps[0].shape), (2, 1, 8, 8)) + targets = [] + for value in [40.0, 70.0]: + y = torch.full((1, 1, 8, 8), -1.0) + y[0, 0, 4, 4] = value + mask = torch.zeros_like(y, dtype=torch.bool) + mask[0, 0, 4, 4] = True + targets.append({"values": RasterImage(y), "valid": RasterImage(mask)}) + result = head(logits, context, targets) + expected = ( + (logits.feature_maps[0][:, 0, 4, 4] - torch.tensor([40.0, 70.0])) ** 2 + ).mean() + torch.testing.assert_close(result.loss_dict["regress"], expected) + result.loss_dict["regress"].backward() + for module in [encoder, decoder]: + grads = [p.grad for p in module.parameters() if p.grad is not None] + self.assertTrue( + grads + and all(torch.isfinite(g).all() for g in grads) + and any(torch.any(g != 0) for g in grads) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/6b/6b2e2d15ea19a89fd239cc1c54320796e18574a39de200038664eaf838d622f3/test_recomputation.py b/reproduction/files/6b/6b2e2d15ea19a89fd239cc1c54320796e18574a39de200038664eaf838d622f3/test_recomputation.py new file mode 100644 index 0000000000000000000000000000000000000000..98b3d633483b6beceeb9ce1077ee24f7906f5064 --- /dev/null +++ b/reproduction/files/6b/6b2e2d15ea19a89fd239cc1c54320796e18574a39de200038664eaf838d622f3/test_recomputation.py @@ -0,0 +1,81 @@ +"""Check checkpoint wrapping preserves stochastic outputs, gradients and keys.""" + +import argparse +import os +import tempfile +import copy +import json +import sys +from pathlib import Path +import torch +from olmoearth_pretrain.nn.attention import Block + +parser = argparse.ArgumentParser() +parser.add_argument("--fsdp", action="store_true") +parser.add_argument("--cross-attention", action="store_true") +parser.add_argument("--keyword-input", action="store_true") +args = parser.parse_args() +if args.fsdp: + if ( + os.environ.get("EARTH_SLURM_PARTITION") + and os.environ.get("SLURM_JOB_PARTITION") != os.environ["EARTH_SLURM_PARTITION"] + ): + raise RuntimeError("CUDA tests require configured-gpu-partition") + from torch.distributed.fsdp import MixedPrecisionPolicy + + torch.cuda.set_device(0) + rendezvous = tempfile.TemporaryDirectory() + torch.distributed.init_process_group( + "nccl", init_method=f"file://{rendezvous.name}/init", rank=0, world_size=1 + ) +torch.set_num_threads(4) +torch.manual_seed(42) +block = Block(dim=64, num_heads=4, drop_path=0.1, cross_attn=args.cross_attention) +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/baseline/starter")) +from recomputation import wrap_block + +wrapped = wrap_block(copy.deepcopy(block)) +assert list(block.state_dict()) == list(wrapped.state_dict()) +x = torch.randn(3, 8, 64) +if args.fsdp: + x = x.cuda() + for module in (block, wrapped): + module.cuda() + module.apply_fsdp( + mp_policy=MixedPrecisionPolicy( + param_dtype=torch.bfloat16, reduce_dtype=torch.float32 + ) + ) +context = {"y": torch.randn(3, 6, 64, device=x.device)} if args.cross_attention else {} +outputs, gradients = [], [] +for module in (block, wrapped): + torch.manual_seed(123) + output = module(x=x, **context) if args.keyword_input else module(x, **context) + output.square().mean().backward() + outputs.append(output.detach()) + gradients.append( + torch.cat( + [ + (p.grad.full_tensor() if args.fsdp else p.grad).flatten() + for p in module.parameters() + ] + ) + ) +assert torch.equal(outputs[0], outputs[1]) +assert torch.equal(gradients[0], gradients[1]) +print( + json.dumps( + { + "fsdp": args.fsdp, + "cross_attention": args.cross_attention, + "keyword_input": args.keyword_input, + "output_max_abs": float((outputs[0] - outputs[1]).abs().max()), + "gradient_max_abs": float((gradients[0] - gradients[1]).abs().max()), + "state_dict_keys_equal": True, + } + ) +) + +if args.fsdp: + torch.distributed.destroy_process_group() + rendezvous.cleanup() diff --git a/reproduction/files/6e/6e06a35585dc307cd2eb30dfd7c7e3d11c08f906fd2d83f519b122968ba28195/run_unit_tests.sh b/reproduction/files/6e/6e06a35585dc307cd2eb30dfd7c7e3d11c08f906fd2d83f519b122968ba28195/run_unit_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..79b5f086ebfe68c400ffe82499d35a919ef5fa92 --- /dev/null +++ b/reproduction/files/6e/6e06a35585dc307cd2eb30dfd7c7e3d11c08f906fd2d83f519b122968ba28195/run_unit_tests.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +if [[ -d /task/tests ]]; then + exec python3 -m pytest -q -p no:cacheprovider /task/tests +fi +cd "$(dirname "$0")/.." +exec python3 -m pytest -q -p no:cacheprovider tests diff --git a/reproduction/files/6e/6e1eea60a792b39e07b3f6c87b67a86d532a563cf21f4efc6b7881387a9b3e35/stage_validation.py b/reproduction/files/6e/6e1eea60a792b39e07b3f6c87b67a86d532a563cf21f4efc6b7881387a9b3e35/stage_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..1b8fd17101bc20aa9f87662b53d62f05a4c7a6ad --- /dev/null +++ b/reproduction/files/6e/6e1eea60a792b39e07b3f6c87b67a86d532a563cf21f4efc6b7881387a9b3e35/stage_validation.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Stage labeled development validation data as contract-compatible input.""" + +import argparse +import hashlib +import json +from pathlib import Path +import random +import shutil + + +def sha256(path): + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--input-root", required=True, type=Path) + parser.add_argument("--output-root", required=True, type=Path) + parser.add_argument("--limit", type=int) + parser.add_argument("--sample-size", type=int, help="Uniform deterministic spectrum sample, instead of a file prefix") + parser.add_argument("--seed", type=int, default=0) + parser.add_argument( + "--query-id-file", + type=Path, + help="Optional newline-delimited allowlist of validation query IDs.", + ) + args = parser.parse_args() + if args.limit is not None and args.limit <= 0: + raise ValueError("limit must be positive") + if sum(value is not None for value in [args.limit, args.sample_size, args.query_id_file]) > 1: + raise ValueError('choose one of limit, sample-size or query-id-file') + selected_query_ids = None + if args.query_id_file is not None: + selected_query_ids = { + line.strip() + for line in args.query_id_file.read_text(encoding="utf-8").splitlines() + if line.strip() + } + if not selected_query_ids: + raise ValueError("query ID allowlist is empty") + if args.sample_size is not None: + identifiers = [json.loads(line)['query_id'] for line in (args.input_root / 'validation.jsonl').open() if line.strip()] + if not 1 <= args.sample_size <= len(identifiers): + raise ValueError('sample-size must fit the validation fold') + selected_query_ids = set(random.Random(args.seed).sample(sorted(identifiers), args.sample_size)) + output = args.output_root.resolve() + output.mkdir(parents=True, exist_ok=False) + queries = output / "queries.jsonl" + selected_pools = set() + query_count = 0 + with (args.input_root / "validation.jsonl").open() as source, queries.open("w") as target: + for line in source: + if args.limit is not None and query_count >= args.limit: + break + row = json.loads(line) + if ( + selected_query_ids is not None + and row["query_id"] not in selected_query_ids + ): + continue + for key in ("target_smiles", "target_inchikey", "target_formula"): + row.pop(key) + target.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n") + selected_pools.add(row["candidate_pool_id"]) + query_count += 1 + if selected_query_ids is not None and query_count != len(selected_query_ids): + found = { + json.loads(line)["query_id"] + for line in queries.read_text(encoding="utf-8").splitlines() + if line.strip() + } + missing = sorted(selected_query_ids - found) + raise ValueError(f"unknown validation query IDs: {missing[:5]}") + pools = output / "candidate_pools.jsonl" + if args.limit is None and selected_query_ids is None: + shutil.copyfile(args.input_root / "validation_candidate_pools.jsonl", pools) + pool_count = sum(1 for line in pools.open() if line.strip()) + else: + pool_count = 0 + with (args.input_root / "validation_candidate_pools.jsonl").open() as source, pools.open("w") as target: + for line in source: + row = json.loads(line) + if row["candidate_pool_id"] in selected_pools: + target.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n") + pool_count += 1 + manifest = { + "schema": "massspecgym-retrieval-input/v1", + "source": "development validation", + "counts": {"queries": query_count, "candidate_pools": pool_count}, + "files": { + "queries.jsonl": sha256(queries), + "candidate_pools.jsonl": sha256(pools), + }, + } + if args.sample_size is not None: + manifest['selection'] = {'method': 'uniform spectrum sample', 'size': args.sample_size, 'seed': args.seed} + (output / "manifest.json").write_text( + json.dumps(manifest, sort_keys=True, separators=(",", ":")) + "\n" + ) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/6e/6e2958b889b59b4e9ea2dc9fd5a522e885276efb4020af500bbe593bfeeb0288/diagnostics.py b/reproduction/files/6e/6e2958b889b59b4e9ea2dc9fd5a522e885276efb4020af500bbe593bfeeb0288/diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..121271e7a7e672ac93d292545a1d799b1a701247 --- /dev/null +++ b/reproduction/files/6e/6e2958b889b59b4e9ea2dc9fd5a522e885276efb4020af500bbe593bfeeb0288/diagnostics.py @@ -0,0 +1,66 @@ +"""Validation-only condition diagnostics and molecule-cluster uncertainty.""" + +from collections import defaultdict +import math + +import numpy as np + + +def released_domain(row): + energy = row.get('collision_energy') + return (row.get('adduct') == '[M+H]+' + and row.get('instrument_type') in {'Orbitrap', 'QTOF'} + and isinstance(energy, (int, float)) and math.isfinite(energy)) + + +def cluster_interval(outcomes, groups, *, resamples=2000, seed=0, confidence=0.95): + """Resample molecules, retaining the official spectrum-weighted statistic.""" + if len(outcomes) != len(groups) or not groups or resamples < 1 or not 0 < confidence < 1: + raise ValueError('invalid cluster-bootstrap inputs') + grouped = defaultdict(lambda: [0.0, 0]) + for outcome, group in zip(outcomes, groups): + grouped[group][0] += outcome + grouped[group][1] += 1 + values = np.asarray(list(grouped.values()), dtype=float) + rng = np.random.default_rng(seed) + draws = [] + for offset in range(0, resamples, 128): + indices = rng.integers(len(values), size=(min(128, resamples - offset), len(values))) + sample = values[indices].sum(axis=1) + draws.extend((sample[:, 0] / sample[:, 1]).tolist()) + alpha = (1 - confidence) / 2 + low, high = np.quantile(draws, [alpha, 1 - alpha]) + return {'estimate': float(np.mean(outcomes)), 'lower': float(low), 'upper': float(high), + 'confidence': confidence, 'resamples': resamples, 'seed': seed, + 'molecule_groups': len(values), 'queries': len(groups), + 'grouping': 'supplied target_inchikey connectivity block', + 'statistic': 'spectrum-weighted mean; molecules sampled with replacement'} + + +def describe(rows, pools, rankings, correct, *, resamples=2000, seed=0, baseline=None): + strata = {name: defaultdict(list) for name in + ['adduct', 'instrument_type', 'collision_energy', 'candidate_pool_size', 'routing_domain']} + hits, groups, differences = [], [], [] + for query_id, row in rows.items(): + hit = int(query_id in rankings and rankings[query_id][0] == correct[query_id]) + hits.append(hit) + groups.append(row['target_inchikey'].split('-')[0]) + if baseline is not None: + differences.append(hit - int(query_id in baseline and baseline[query_id][0] == correct[query_id])) + energy = row.get('collision_energy') + energy_bin = ('missing' if energy is None else '<20' if energy < 20 else + '20-39.999' if energy < 40 else '40-59.999' if energy < 60 else '>=60') + size = len(pools[row['candidate_pool_id']]) + labels = {'adduct': row['adduct'], 'instrument_type': row['instrument_type'], + 'collision_energy': energy_bin, + 'candidate_pool_size': '1-32' if size <= 32 else '33-128' if size <= 128 else '129-256', + 'routing_domain': 'glacier_released' if released_domain(row) else 'fallback'} + for name, label in labels.items(): + strata[name][label].append(hit) + result = {'strata': {name: {label: {'queries': len(values), 'hit_rate_at_1': sum(values) / len(values)} + for label, values in sorted(bins.items())} + for name, bins in strata.items()}, + 'uncertainty': cluster_interval(hits, groups, resamples=resamples, seed=seed)} + if baseline is not None: + result['paired_baseline_delta'] = cluster_interval(differences, groups, resamples=resamples, seed=seed) + return result diff --git a/reproduction/files/70/705567c00753eb049e4b1b837eb23d165c5f1037b0692c6068c20d08373456d1/test_longitudinal_v2.py b/reproduction/files/70/705567c00753eb049e4b1b837eb23d165c5f1037b0692c6068c20d08373456d1/test_longitudinal_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..7eac20d47f0dfb90821bb65143d32fb5947ae944 --- /dev/null +++ b/reproduction/files/70/705567c00753eb049e4b1b837eb23d165c5f1037b0692c6068c20d08373456d1/test_longitudinal_v2.py @@ -0,0 +1,102 @@ +import json +import sys +from datetime import date +from pathlib import Path + +import numpy as np +import pyarrow as pa +import pyarrow.parquet as pq +import pytest +import torch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "environment" / "baseline" / "temporal-gru")) + +from longitudinal import (HORIZONS, LongitudinalRiskModel, _load_labels_aligned, + _numeric_value, _select_sequence, _sequence_delta, collate) + + +def test_v2_protocol_is_versioned_and_patient_weighted(): + protocol = json.loads((ROOT / "environment" / "data" / "protocols" / "longitudinal-v2.json").read_text()) + assert protocol["index_time"] == "second_eligible_live_adult_discharge" + assert protocol["samples_per_patient"] == 1 + assert protocol["selection_uses_future_information"] is False + assert protocol["horizons_days"] == list(HORIZONS) + + +def test_history_spanning_selection_keeps_old_and_recent_events(): + selected = _select_sequence(2000, 512) + assert len(selected) == 512 + assert selected[0] == 0 + assert selected[-1] == 1999 + assert (selected[1:] > selected[:-1]).all() + assert sum(selected >= 1744) == 256 + + +def test_missing_numeric_is_mean_imputed_with_explicit_indicator(): + stats = {"lab:L:mmol/L": [10.0, 2.0]} + assert _numeric_value("lab", "lab:L:mmol/L", "14", stats) == (2.0, 0.0) + assert _numeric_value("lab", "lab:L:mmol/L", "not-a-number", stats) == (0.0, 1.0) + assert _numeric_value("lab", "lab:unknown:mmol/L", "0", stats) == (0.0, 1.0) + assert _numeric_value("diagnosis", "diagnosis:A00", None, stats) == (0.0, 0.0) + + +def test_sequence_gap_uses_event_time_order(): + # Backwards-from-cutoff time decreases for oldest-to-newest event order. + assert _sequence_delta(np.asarray([5.0, 4.5, 1.0], np.float32)).tolist() == [0.0, .5, 3.5] + + +def test_label_loader_aligns_keys_and_rejects_duplicates(tmp_path): + rows = [] + for sid in ("b", "a"): + for disease in ("B", "A"): + row = {"sample_id": sid, "disease_code": disease, + "cutoff": date(2020, 1, 1), + "diagnosis_observation_end": date(2022, 1, 1), + "death_observation_end": date(2022, 1, 1)} + for horizon in HORIZONS: + row[f"disease_label_{horizon}"] = sid == "b" and disease == "B" + row[f"disease_valid_{horizon}"] = True + row[f"death_label_{horizon}"] = sid == "b" + row[f"death_valid_{horizon}"] = True + rows.append(row) + path = tmp_path / "labels.parquet" + pq.write_table(pa.Table.from_pylist(rows), path) + loaded = _load_labels_aligned(path, ["a", "b"], ["A", "B"]) + assert loaded["y"][:, :, -1].tolist() == [[0, 0], [0, 1]] + assert loaded["death_y"][:, -1].tolist() == [0, 1] + assert loaded["primary"].tolist() == [1, 1] + pq.write_table(pa.Table.from_pylist(rows + [rows[0]]), path) + with pytest.raises(ValueError, match="duplicated"): + _load_labels_aligned(path, ["a", "b"], ["A", "B"]) + + +def _row(): + return {"id": "x", "age": torch.tensor(70.0), "sex": torch.tensor(1.0), + "all_code": torch.tensor([2,3,4],dtype=torch.int32), + "all_mod": torch.tensor([1,2,1],dtype=torch.uint8), + "all_value": torch.tensor([0.0,.5,0.0]), + "all_missing": torch.tensor([0.0,1.0,0.0]), + "seq_code": torch.tensor([2,3,4,0],dtype=torch.int32), + "seq_mod": torch.tensor([1,2,1,0],dtype=torch.uint8), + "seq_value": torch.tensor([0.0,.5,0.0,0.0]), + "seq_missing": torch.tensor([0.0,1.0,0.0,0.0]), + "seq_time": torch.tensor([3.0,2.0,1.0,0.0]), + "seq_delta": torch.tensor([0.0,1.0,1.0,0.0]), + "seq_len": torch.tensor(3,dtype=torch.int16)} + + +def test_diagnosis_ablation_removes_other_modalities_and_risk_is_monotone(): + batch = collate([_row()], diagnosis_only=True) + assert batch["all_mod"].tolist() == [1,1] + assert batch["seq_code"][0,:2].tolist() == [2,4] + assert batch["seq_value"][0,:2].tolist() == [0.0,0.0] + assert batch["seq_missing"][0,:2].tolist() == [0.0,0.0] + assert batch["seq_time"][0,:2].tolist() == [3.0,1.0] + assert batch["seq_delta"][0,:2].tolist() == [0.0,2.0] + model = LongitudinalRiskModel(vocab=8,diseases=3,kind="temporal") + disease, death = model(batch) + assert disease.shape == (1,3,len(HORIZONS)) + assert death.shape == (1,len(HORIZONS)) + assert torch.all(torch.diff(disease,dim=2) >= 0) + assert torch.all(torch.diff(death,dim=1) >= 0) diff --git a/reproduction/files/70/70bb340258c349bcaa5cb43924db70a74232e70629e216adf29ff4dbcee7f595/test_awf_pair_gate.py b/reproduction/files/70/70bb340258c349bcaa5cb43924db70a74232e70629e216adf29ff4dbcee7f595/test_awf_pair_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..f604824c1f440f8e90802ae2b860612a81c20450 --- /dev/null +++ b/reproduction/files/70/70bb340258c349bcaa5cb43924db70a74232e70629e216adf29ff4dbcee7f595/test_awf_pair_gate.py @@ -0,0 +1,115 @@ +"""The full-run gate rejects incomplete or mismatched integration pilots.""" + +import json +from pathlib import Path +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/analysis")) +from verify_awf_pair import verify + + +class TestGate(unittest.TestCase): + def test_complete_pair_and_failed_boundaries(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + receipt = { + "stage": "integration pilot, not scientific evidence", + "outputs": ["trained", "random"], + "package_names": { + "trained": "trained-package", + "random": "random-package", + }, + "head_and_loader_seed": 8123, + "validation_rng_seed": 73491, + "source_sha256": { + "environment/downstream/train_awf.py": "train", + "environment/downstream/portable_encoder.py": "adapter", + "results/protocol-audit/awf-large-candidate.yaml": "config", + }, + } + for name in ["trained", "random"]: + out = root / name + out.mkdir() + package = root / f"{name}-package" + package.mkdir() + provenance = { + "origin": "own_from_scratch_training" + if name == "trained" + else "random_initialization", + "encoder_sha256": name, + "initialization_seed": 12536, + "variant": "v1/large", + "parameters": 307770368, + } + (package / "provenance.json").write_text(json.dumps(provenance)) + values = { + "settings": { + "pilot": True, + "max_epochs": 22, + "seed": 8123, + "limit_train_batches": 2, + "limit_val_batches": 2, + "num_workers": 0, + "validation_rng_seed": 73491, + "test_used": False, + "train_source_sha256": "train", + "adapter_source_sha256": "adapter", + "config_sha256": "config", + "package": str(package), + "dataset": "same-dataset", + }, + "initialization": { + "encoder_file_sha256": name, + "encoder_state_digest": name, + "head_state_digest": "same-head", + }, + "data-coverage": {"train": 1115, "val": 344}, + "unfreeze-boundary": { + "epoch": 20, + "frozen_weights_unchanged": True, + }, + "completion": { + "epochs": 22, + "encoder_changed": True, + "final_encoder_state_digest": name + "-changed", + "test_used": False, + }, + "epochs": [ + { + "epoch": i, + "encoder_trainable_parameters": 0 if i < 20 else 307770368, + "lr": [1e-4] if i < 20 else [1e-4, 1e-5], + } + for i in range(22) + ], + } + for k, v in values.items(): + (out / f"{k}.json").write_text(json.dumps(v)) + self.assertTrue(verify(root, receipt)["gate_passed"]) + cases = [ + ("completion", "encoder_changed", False), + ("initialization", "head_state_digest", "different-head"), + ("unfreeze-boundary", "frozen_weights_unchanged", False), + ("settings", "test_used", True), + ("settings", "adapter_source_sha256", "changed-code"), + ] + for file, key, value in cases: + p = root / "random" / f"{file}.json" + original = p.read_text() + changed = json.loads(original) + changed[key] = value + p.write_text(json.dumps(changed)) + with self.assertRaises(ValueError): + verify(root, receipt) + p.write_text(original) + p = root / "random/epochs.json" + epochs = json.loads(p.read_text()) + p.write_text(json.dumps(epochs[:20])) + with self.assertRaisesRegex(ValueError, "full unfreeze"): + verify(root, receipt) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/71/7122dd81b812093c24810035a10bac899f56dc137ad53293308aef32fa5d54aa/test.sh b/reproduction/files/71/7122dd81b812093c24810035a10bac899f56dc137ad53293308aef32fa5d54aa/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..69407db74482d033beceda0208d965e38ec488d2 --- /dev/null +++ b/reproduction/files/71/7122dd81b812093c24810035a10bac899f56dc137ad53293308aef32fa5d54aa/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +exec python3 /tests/main_verifier.py \ + --submission /workspace/submission \ + --input /benchmark \ + --sealed /sealed/run \ + --output /logs/verifier \ + --timeout "${PROTEIN_DESIGN_INFERENCE_TIMEOUT_SECONDS:-21600}" diff --git a/reproduction/files/71/7199c7b26252a169a68144459dc90e6ac43d9d0d90861337d55827eeef2df974/test_research_release.py b/reproduction/files/71/7199c7b26252a169a68144459dc90e6ac43d9d0d90861337d55827eeef2df974/test_research_release.py new file mode 100644 index 0000000000000000000000000000000000000000..0d8a2e09459398dd134b4e14e22d56c58f63f813 --- /dev/null +++ b/reproduction/files/71/7199c7b26252a169a68144459dc90e6ac43d9d0d90861337d55827eeef2df974/test_research_release.py @@ -0,0 +1,158 @@ +"""Research v2 metadata/integration tests, not CFD or trained-policy scores.""" +import copy +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +DATA = Path(__file__).resolve().parents[1] / "environment/data" +sys.path.insert(0, str(DATA)) +import hour_release +import public_release as public +import research_release as research + + +class ResearchReleaseTests(unittest.TestCase): + def setUp(self): + self.selection = research.read("selection-research-v2.json") + self.evidence = research.read("cost-evidence-coverage-v1.json") + self.prior = hour_release.build_current() + + def build(self, selection=None, evidence=None): + return research.build(selection or self.selection, evidence or self.evidence, self.prior) + + def test_current_default_matches_frozen_build_and_full_membership(self): + release = public.load_release() + self.assertEqual(release, research.build_current()) + self.assertEqual(release["release_id"], research.RELEASE_ID) + self.assertEqual(release["case_count"], 39) + self.assertEqual(sum(c["dimension"] == 3 for c in release["cases"]), 19) + self.assertEqual(release["files"], {"count": 558, "bytes": 453756315982}) + self.assertEqual(release["backend_counts"], {"jax": 2, "jax-fluids": 2, "maia": 35}) + self.assertEqual(release["training"]["case_ids"], release["test"]["case_ids"]) + self.assertTrue(release["test"]["one_shared_checkpoint"]) + self.assertTrue(release["test"]["all_selected_cases_required"]) + self.assertFalse(release["test"]["cost_tiers_are_optional"]) + + def test_cost_status_is_not_completed_training_or_evaluation(self): + release = self.build() + self.assertEqual(release["status"], "data-release-not-cfd-certified") + self.assertEqual(release["test"]["execution_manifest_status"], + "requires_native_protocol_binding_and_full_replay") + self.assertEqual(sum("training_evidence_reference" in c for c in release["cases"]), 19) + self.assertEqual(sum(c["required_solver_gpus"] == 2 for c in release["cases"]), 3) + self.assertFalse(release["reference_training_budget"]["agent_training_limit"]) + self.assertEqual(release["reference_training_budget"]["total_controls"], 156000) + + def test_all_62_complete_resources_have_unique_decisions(self): + release = self.build() + selected = {c["id"] for c in release["cases"]} + excluded = {c["environment"] for c in release["exclusions"] + if c.get("resource_status") == "required_payloads_present"} + self.assertFalse(selected & excluded) + self.assertEqual(len(selected | excluded), 62) + cavity = next(c for c in release["exclusions"] if c.get("environment") == "Cavity_2D_Re7500") + self.assertEqual(cavity["reason"], "nonfinite_native_episode") + + def test_rebuilt_old_hour_manifest_and_other_archives_remain_exact(self): + self.assertEqual(public.load_release(DATA / "release-hour-v1.json"), self.prior) + for name, expected in [ + ("hour", "b5c398208b0bd4bcbd8ae5fe67daff3066a0d83cf1f090a711a3eec2ada1c11f"), + ("coverage", "365e9531671ae4eb24491e880f7e6c1d9768013b5da2bb389df9342525ca1896"), + ("speed", "23c53782f87b91c9be8babee3cab5e7cd16730c9dc79eb46d1b19c796be82890"), + ("500gb", "226b7059b4b6b34bb4a8f169374f2a6bc74bc4f780b22ccbc3171c06b34778f3")]: + self.assertEqual(public.digest(public.load_release(DATA / f"release-{name}-v1.json")), expected) + + def test_unapproved_or_changed_budget_rejected(self): + for mutate in [lambda p: p.update(status="draft"), + lambda p: p["policy"].update(max_source_bytes=501000000000)]: + selection = copy.deepcopy(self.selection) + mutate(selection) + with self.assertRaises(ValueError): + self.build(selection) + + def test_cannot_drop_change_or_duplicate_a_case(self): + for mutate in [lambda p: p["cases"].pop(), + lambda p: p["cases"].append(p["cases"][0]), + lambda p: p["contract"]["evaluation_case_ids"].pop(), + lambda p: p["contract"].update(all_selected_cases_required=False)]: + selection = copy.deepcopy(self.selection) + mutate(selection) + with self.assertRaises(ValueError): + self.build(selection) + + def test_unknown_cost_and_one_step_probe_cannot_qualify(self): + for field, value in [("status", "timeout"), ("reset_seconds", None), + ("timing_samples_seconds", [1.0]), ("observed_field_response", False)]: + evidence = copy.deepcopy(self.evidence) + next(r for r in evidence["cases"] if r["case"] == "Cube_3D_Re300")[field] = value + with self.subTest(field=field), self.assertRaises(ValueError): + self.build(evidence=evidence) + + def test_two_gpu_results_cannot_be_called_single_gpu(self): + selection = copy.deepcopy(self.selection) + next(c for c in selection["cases"] if c["case"] == "Cube_3D_Re3700")["hardware"] = "1 H100" + with self.assertRaisesRegex(ValueError, "hardware"): + self.build(selection) + evidence = copy.deepcopy(self.evidence) + record = next(r for r in evidence["cases"] if r["case"] == "Cube_3D_Re3700") + record["gpu_bindings"][1]["cuda_device_uuid"] = record["gpu_bindings"][0]["cuda_device_uuid"] + with self.assertRaisesRegex(ValueError, "rank bindings"): + self.build(evidence=evidence) + + def test_false_training_claim_cost_tampering_or_missing_exclusion_rejected(self): + for mutate in [lambda p: p["cases"][0].update(full_4000_step_training_validated=True), + lambda p: p["cases"][0].update(whole_experiment_planning_hours=0.0), + lambda p: p["cases"][0].update(tier="multigpu_exception"), + lambda p: p["excluded_complete_resources"].pop()]: + selection = copy.deepcopy(self.selection) + mutate(selection) + with self.assertRaises(ValueError): + self.build(selection) + + def test_channel_repair_preserved_without_changing_native_source(self): + release = self.build() + self.assertEqual(release["source"]["organizer_runtime_adapters"], + self.prior["source"]["organizer_runtime_adapters"]) + old = {c["id"]: c for c in self.prior["cases"]} + for case in release["cases"]: + if case["id"] in old: + self.assertEqual(case["files_sha256"], old[case["id"]]["files_sha256"]) + self.assertEqual(case["runtime_profile"], old[case["id"]]["runtime_profile"]) + + def test_default_materialization_plan_is_pinned_and_nonmutating(self): + with tempfile.TemporaryDirectory() as temporary: + destination = Path(temporary) / "data" + result = subprocess.run([sys.executable, str(DATA / "materialize.py"), str(destination)], + capture_output=True, text=True, check=True) + plan = json.loads(result.stdout) + self.assertEqual(plan["data_release_id"], research.RELEASE_ID) + self.assertEqual(plan["bytes"], 453756315982) + self.assertEqual(len(plan["directories"]), 39) + self.assertFalse(destination.exists()) + for command in plan["download_commands"]: + self.assertEqual(command[0], "hf") + self.assertEqual(command[command.index("--revision") + 1], plan["download_source"]["revision"]) + self.assertEqual(command[2], plan["download_source"]["repo_id"]) + + def test_partial_suite_and_tampered_release_are_rejected(self): + release = self.build() + suite = {"data_release_id": research.RELEASE_ID, "data_release_sha256": public.digest(release), + "cases": [{"id": c["id"], "environment": c["environment"], "backend": c["backend"]} + for c in release["cases"]]} + public.validate_suite_binding(release, suite) + suite["cases"].pop() + with self.assertRaisesRegex(ValueError, "exact frozen"): + public.validate_suite_binding(release, suite) + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / "release.json" + release["test"]["normalizer_updates"] = True + path.write_text(json.dumps(release)) + with self.assertRaisesRegex(ValueError, "exact frozen"): + public.load_release(path) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/75/75efd4e46ab0f70864d8c8532f8701a6690f50101bdf97148380837761c2392a/test.sh b/reproduction/files/75/75efd4e46ab0f70864d8c8532f8701a6690f50101bdf97148380837761c2392a/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c493e8b388397d5a23a38b6ddfdc7ac19b2f068f --- /dev/null +++ b/reproduction/files/75/75efd4e46ab0f70864d8c8532f8701a6690f50101bdf97148380837761c2392a/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +exec python /tests/main_verifier.py \ + --submission /workspace/submission \ + --input /benchmark \ + --sealed /sealed/run \ + --output /logs/verifier \ + --timeout "${MASSSPECGYM_INFERENCE_TIMEOUT_SECONDS:-18000}" diff --git a/reproduction/files/76/76c9cd5ba2e530afc453b8ee6d23a291a980d68bbbca3f07b46c5cfad82f4dad/metrics.py b/reproduction/files/76/76c9cd5ba2e530afc453b8ee6d23a291a980d68bbbca3f07b46c5cfad82f4dad/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..ead8af76e8e07bc12f3758e5913ed076e8e599ea --- /dev/null +++ b/reproduction/files/76/76c9cd5ba2e530afc453b8ee6d23a291a980d68bbbca3f07b46c5cfad82f4dad/metrics.py @@ -0,0 +1,119 @@ +"""Trusted PEER task scoring; pure Python, never imports a submission. + +Kept byte-identical with environment/evaluation/metrics.py so development +self-evaluation matches the grader. +""" +import math + +TASKS = ("fluorescence", "stability", "beta_lactamase", "solubility", + "subcellular_localization", "binary_localization", "fold", + "secondary_structure", "yeast_ppi", "human_ppi", "ppi_affinity") +CLASSES = {"solubility": 2, "subcellular_localization": 10, "binary_localization": 2, + "fold": 1195, "yeast_ppi": 2, "human_ppi": 2} +SPEARMAN_TASKS = ("fluorescence", "stability", "beta_lactamase") + + +def probabilities(values, n): + if (not isinstance(values, list) or len(values) != n + or any(type(x) not in (int, float) or not math.isfinite(x) or x < 0 for x in values) + or sum(values) <= 0): + raise ValueError("invalid scores") + total = sum(values) + return [x / total for x in values] + + +def finite_number(value): + if type(value) not in (int, float) or not math.isfinite(value): + raise ValueError("invalid number") + return float(value) + + +def average_ranks(values): + order = sorted(range(len(values)), key=values.__getitem__) + ranks = [0.0] * len(values) + start = 0 + while start < len(order): + stop = start + while stop + 1 < len(order) and values[order[stop + 1]] == values[order[start]]: + stop += 1 + rank = (start + stop) / 2 + 1 + for index in range(start, stop + 1): + ranks[order[index]] = rank + start = stop + 1 + return ranks + + +def spearman(truth, predicted): + if len(truth) < 2: + return 0.0 + a, b = average_ranks(truth), average_ranks(predicted) + mean_a, mean_b = sum(a) / len(a), sum(b) / len(b) + covariance = sum((x - mean_a) * (y - mean_b) for x, y in zip(a, b)) + scale = math.sqrt(sum((x - mean_a) ** 2 for x in a) * sum((y - mean_b) ** 2 for y in b)) + return covariance / scale if scale > 0 else 0.0 + + +def classification_metrics(truth, raw_scores, n): + guesses = [max(range(n), key=probabilities(scores, n).__getitem__) for scores in raw_scores] + recalls, f1s = [], [] + for label in range(n): + tp = sum(t == label and g == label for t, g in zip(truth, guesses)) + fp = sum(t != label and g == label for t, g in zip(truth, guesses)) + fn = sum(t == label and g != label for t, g in zip(truth, guesses)) + if tp + fn: + recalls.append(tp / (tp + fn)) + f1s.append(2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0) + accuracy = sum(t == g for t, g in zip(truth, guesses)) / len(truth) + return {"accuracy": accuracy, + "balanced_accuracy": sum(recalls) / len(recalls) if recalls else 0.0, + "macro_f1": sum(f1s) / n, + "reward": accuracy} + + +def score_task(task, truth, found, ppi_affinity_std=None): + """truth/found: example_id -> label / prediction dict. Raises on malformed input.""" + if set(found) != set(truth): + raise ValueError("missing or unknown predictions") + ids = sorted(truth) + labels = [truth[i] for i in ids] + predictions = [found[i] for i in ids] + if task in CLASSES: + if any(not isinstance(p, dict) or set(p) != {"scores"} for p in predictions): + raise ValueError("bad classification prediction") + return classification_metrics(labels, [p["scores"] for p in predictions], CLASSES[task]) + if task in SPEARMAN_TASKS or task == "ppi_affinity": + if any(not isinstance(p, dict) or set(p) != {"value"} for p in predictions): + raise ValueError("bad regression prediction") + values = [finite_number(p["value"]) for p in predictions] + rho = spearman(labels, values) + if task == "ppi_affinity": + rmse = math.sqrt(sum((t - v) ** 2 for t, v in zip(labels, values)) / len(labels)) + return {"rmse": rmse, "spearman": rho, + "reward": math.exp(-rmse / max(ppi_affinity_std, 1e-12))} + return {"spearman": rho, "reward": max(rho, 0.0)} + # secondary_structure + correct = total = 0 + for label, prediction in zip(labels, predictions): + if not isinstance(prediction, dict) or set(prediction) != {"ss3_scores"}: + raise ValueError("bad ss3 prediction") + scores = prediction["ss3_scores"] + if not isinstance(scores, list) or len(scores) != len(label["ss3"]): + raise ValueError("ss3 prediction length mismatch") + for target, valid, residue_scores in zip(label["ss3"], label["valid_mask"], scores): + guess = max(range(3), key=probabilities(residue_scores, 3).__getitem__) + if valid: + total += 1 + correct += guess == target + if not total: + raise ValueError("no valid residues") + accuracy = correct / total + return {"accuracy": accuracy, "valid_residues": total, "reward": accuracy} + + +def flatten_metrics(prefix, value, output): + if isinstance(value, dict): + for key, item in value.items(): + if key != "invalid_reason": + flatten_metrics(prefix + "_" + key if prefix else key, item, output) + elif type(value) in (int, float) and math.isfinite(value): + output[prefix] = value diff --git a/reproduction/files/77/772a115d5ac05fe4b249b78e4de93b3cdd900e0c95d0607a7829054015b0989c/test_task.py b/reproduction/files/77/772a115d5ac05fe4b249b78e4de93b3cdd900e0c95d0607a7829054015b0989c/test_task.py new file mode 100644 index 0000000000000000000000000000000000000000..d647be5b518fe0568d170f6f81d9a981839ebe46 --- /dev/null +++ b/reproduction/files/77/772a115d5ac05fe4b249b78e4de93b3cdd900e0c95d0607a7829054015b0989c/test_task.py @@ -0,0 +1,797 @@ +"""Synthetic materialization, contract, scoring, and layout tests.""" + +import argparse +import csv +import hashlib +import importlib.util +import json +from pathlib import Path +import py_compile +import sqlite3 +import subprocess +import sys +import tarfile +import tempfile +import tomllib +import unittest +from unittest import mock + + +TASK_ROOT = Path(__file__).resolve().parents[1] +TEST_ROOT = Path(__file__).resolve().parent +DATA_ROOT = TASK_ROOT / "environment/data" +sys.path.insert(0, str(TEST_ROOT)) +import common +import grader +import main_verifier + + +def import_path(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +materialize = import_path("massspecgym_materialize", DATA_ROOT / "materialize.py") +paired_bootstrap = import_path( + "massspecgym_paired_bootstrap", + TASK_ROOT / "environment/evaluation/paired_bootstrap.py", +) + + +def file_sha(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +class TaskTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + + def make_source(self): + source = self.root / "source" + dataset = source / materialize.DATASET_RELATIVE + candidates = source / materialize.CANDIDATES_RELATIVE + dataset.parent.mkdir(parents=True, exist_ok=True) + candidates.parent.mkdir(parents=True, exist_ok=True) + fieldnames = [ + "identifier", "mzs", "intensities", "smiles", "inchikey", "formula", + "precursor_mz", "adduct", "instrument_type", "collision_energy", "fold", + ] + rows = [ + { + "identifier": "q-train", "mzs": "50,100", "intensities": "0.5,1", + "smiles": "CCC", "inchikey": "TRAINKEY000001", "formula": "C3H8", + "precursor_mz": "45", "adduct": "[M+H]+", "instrument_type": "QTOF", + "collision_energy": "20", "fold": "train", + }, + { + "identifier": "q-val", "mzs": "60,110", "intensities": "0.3,1", + "smiles": "CCN", "inchikey": "VALKEY00000001", "formula": "C2H7N", + "precursor_mz": "46", "adduct": "[M+H]+", "instrument_type": "Orbitrap", + "collision_energy": "", "fold": "val", + }, + { + "identifier": "q-test", "mzs": "70,120", "intensities": "0.2,1", + "smiles": "CCO", "inchikey": "TESTKEY0000001", "formula": "C2H6O", + "precursor_mz": "47", "adduct": "[M+H]+", "instrument_type": "", + "collision_energy": "30", "fold": "test", + }, + ] + with dataset.open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=fieldnames, delimiter="\t") + writer.writeheader() + writer.writerows(rows) + pool = ["CCN", "CCO", "CCC"] + candidates.write_text(json.dumps({"CCN": pool, "CCO": pool, "CCC": pool})) + return source, dataset, candidates + + def prepare(self, suffix=""): + source, dataset, candidates = self.make_source() + public = self.root / f"public{suffix}" + private = self.root / f"private{suffix}" + args = argparse.Namespace( + source_root=source, + output_root=public, + private_label_root=private, + dataset_sha256=file_sha(dataset), + candidates_sha256=file_sha(candidates), + ) + report = materialize.materialize(args) + return public, private, report + + def test_native_layout_and_declared_budget(self): + config = tomllib.loads((TASK_ROOT / "task.toml").read_text()) + self.assertEqual(config["artifacts"], ["/workspace/submission"]) + self.assertEqual(config["agent"]["timeout_sec"], 172800.0) + self.assertEqual(config["environment"]["gpus"], 8) + self.assertEqual(config["environment"]["gpu_types"], ["H100"]) + self.assertGreaterEqual(config["environment"]["memory_mb"], 524288) # a floor; more is fine + self.assertEqual(config["environment"]["network_mode"], "no-network") + self.assertEqual(config["verifier"]["environment_mode"], "separate") + self.assertEqual( + config["verifier"]["environment"]["network_mode"], "no-network" + ) + self.assertEqual(config["task"]["authors"], [{"name": "T0-RSI contributors"}]) + self.assertEqual( + config["metadata"]["reference_hit_rate_at_1"], + 0.4939052175894281, + ) + for relative in ( + "instruction.md", "docs/baseline_score.json", "docs/compute-profiles.toml", + "environment/contract.md", + "environment/Dockerfile", "environment/entrypoint.sh", + "environment/data/materialize.py", "environment/baseline/starter/train.py", + "environment/references/README.md", + "environment/references/reference_baseline.json", + "tests/test.sh", "tests/run_unit_tests.sh", "tests/grader.py", + ): + self.assertTrue((TASK_ROOT / relative).is_file(), relative) + + profiles = tomllib.loads((TASK_ROOT / "docs/compute-profiles.toml").read_text()) + self.assertEqual(profiles["schema_version"], "agent-runner-compute-profiles/v1") + self.assertEqual(profiles["default"], "default") + self.assertEqual(profiles["profiles"]["default"]["gpus"], "task") + + reference = json.loads( + (TASK_ROOT / "environment/references/reference_baseline.json").read_text() + ) + self.assertEqual(reference["schema"], "massspecgym-retrieval-reference/v4") + self.assertEqual( + reference["name"], + "GLACIER no-CF with strict-clean MIST fallback", + ) + self.assertEqual(reference["primary_target"], 0.4939052175894281) + self.assertEqual( + reference["glacier_hybrid_replay"]["formal_full_test_replay"] + ["metrics"]["hit_rate_at_1"], + 0.4939052175894281, + ) + self.assertTrue( + reference["glacier_hybrid_replay"]["determinism"]["byte_identical"] + ) + baseline_score = json.loads((TASK_ROOT / "docs" / "baseline_score.json").read_text()) + self.assertEqual(baseline_score["reward"], 1.0) + self.assertEqual(baseline_score["metrics"]["hit_rate_at_1"], 0.4939052175894281) + self.assertEqual( + reference["strict_clean_top5_max_replay"]["metrics"]["hit_rate_at_1"], + 0.39872408293460926, + ) + reference_inference = ( + TASK_ROOT / "environment/references/scripts/predict_mist.py" + ).read_text() + self.assertIn('set_pooling="cls"', reference_inference) + reference_runner = ( + TASK_ROOT / "environment/references/scripts/run_reference.sh" + ).read_text() + self.assertIn('MASS_SPEC_FORMULA_TOP_K:-5', reference_runner) + self.assertIn('MASS_SPEC_FINGERPRINT_THRESHOLD:-0.20346222817897797', + reference_runner) + self.assertIn('MASS_SPEC_MIST_CHECKPOINT:-', reference_runner) + self.assertIn('--formula-top-k "$formula_top_k"', reference_runner) + self.assertIn('--formula-aggregation "$formula_aggregation"', reference_runner) + self.assertIn('--checkpoint "$mist_checkpoint"', reference_runner) + + def test_materializer_separates_labels_and_is_deterministic(self): + public, private, report = self.prepare("-a") + self.assertEqual(report["train_queries"], 1) + self.assertEqual(report["validation_queries"], 1) + self.assertEqual(report["test_queries"], 1) + train = common.jsonl(public / "development/train.jsonl")[0] + validation = common.jsonl(public / "development/validation.jsonl")[0] + query = common.jsonl(public / "verifier/queries.jsonl")[0] + label = common.jsonl(private / "labels.jsonl")[0] + self.assertEqual(train["target_smiles"], "CCC") + self.assertEqual(validation["target_smiles"], "CCN") + self.assertNotIn("target_smiles", query) + self.assertNotIn("formula", query) + self.assertNotIn("inchikey", query) + self.assertEqual(label["correct_candidate_id"], common.candidate_id("CCO")) + val_pool = common.jsonl(public / "development/validation_candidate_pools.jsonl")[0] + test_pool = common.jsonl(public / "verifier/candidate_pools.jsonl")[0] + self.assertEqual(val_pool, test_pool) + + public_b, private_b, _ = self.prepare("-b") + first = { + str(path.relative_to(public)): path.read_bytes() + for path in public.rglob("*") if path.is_file() + } + second = { + str(path.relative_to(public_b)): path.read_bytes() + for path in public_b.rglob("*") if path.is_file() + } + self.assertEqual(first, second) + self.assertEqual((private / "labels.jsonl").read_bytes(), + (private_b / "labels.jsonl").read_bytes()) + + def test_materializer_reuses_only_a_valid_complete_pair(self): + public, private, expected = self.prepare("-reuse") + source = self.root / "source" + dataset = source / materialize.DATASET_RELATIVE + candidates = source / materialize.CANDIDATES_RELATIVE + args = argparse.Namespace( + source_root=source, + output_root=public, + private_label_root=private, + dataset_sha256=file_sha(dataset), + candidates_sha256=file_sha(candidates), + reuse_valid_existing=True, + ) + self.assertEqual(materialize.materialize(args), expected) + (public / "verifier/queries.jsonl").write_text("tampered\n") + with self.assertRaisesRegex(ValueError, "SHA-256 mismatch"): + materialize.materialize(args) + + def test_input_validation_and_fixed_denominator_scoring(self): + public, private, _ = self.prepare("-score") + _, queries, pools = common.validate_input(public / "verifier") + labels = grader.load_labels(private / "labels.jsonl", set(queries)) + query_id = next(iter(queries)) + pool = pools[queries[query_id]["candidate_pool_id"]] + correct = labels[query_id]["correct_candidate_id"] + ranking = [correct] + sorted(set(pool) - {correct}) + metrics = grader.score( + {query_id: ranking}, queries, pools, labels, compute_mces=False + ) + self.assertEqual(metrics, { + "hit_rate_at_1": 1.0, + "hit_rate_at_5": 1.0, + "hit_rate_at_20": 1.0, + }) + missing = grader.score({}, queries, pools, labels, compute_mces=False) + self.assertEqual(missing["hit_rate_at_1"], 0.0) + self.assertEqual(missing["hit_rate_at_20"], 0.0) + + def test_trusted_grader_publishes_normalized_reward_and_preserves_raw_metrics(self): + public, private, _ = self.prepare("-normalized") + _, queries, pools = common.validate_input(public / "verifier") + labels = grader.load_labels(private / "labels.jsonl", set(queries)) + predictions = self.root / "predictions" + predictions.mkdir() + rows = [] + for query_id, query in queries.items(): + truth = labels[query_id]["correct_candidate_id"] + candidates = list(pools[query["candidate_pool_id"]]) + rows.append({"query_id": query_id, "ranking": [truth] + [c for c in candidates if c != truth]}) + (predictions / "rankings.jsonl").write_text("\n".join(json.dumps(row) for row in rows) + "\n") + sealed = self.root / "seal/run" + sealed.parent.mkdir() + main_verifier.seal_output(predictions, sealed, public / "verifier/manifest.json") + args = argparse.Namespace(sealed=sealed, input=public / "verifier", labels=private, + output=self.root / "score", wait_seconds=1, mces_workers=1) + report = grader.run(args, compute_mces=False) + self.assertEqual(json.loads((args.output / "reward.json").read_text()), {"reward": 1.0}) + self.assertEqual(report["metrics"]["hit_rate_at_1"], 1.0) + self.assertGreater(report["benchmark_score"]["unclipped_score"], 1.0) + self.assertEqual(report["benchmark_score"]["saturation"], "upper") + self.assertFalse(report["reference_comparison"]["comparable"]) + + def test_unknown_or_partial_ranking_is_global_error(self): + public, _, _ = self.prepare("-invalid") + _, queries, pools = common.validate_input(public / "verifier") + path = self.root / "rankings.jsonl" + path.write_text('{"query_id":"unknown","ranking":[]}\n') + rankings, error = grader.load_rankings(path, queries, pools) + self.assertEqual(rankings, {}) + self.assertIn("unknown", error) + query_id = next(iter(queries)) + path.write_text(json.dumps({"query_id": query_id, "ranking": []}) + "\n") + rankings, error = grader.load_rankings(path, queries, pools) + self.assertEqual(rankings, {}) + self.assertIn("exact candidate permutation", error) + + def test_mces_deduplicates_structure_pairs_without_changing_weights(self): + queries = { + "q1": {"candidate_pool_id": "pool"}, + "q2": {"candidate_pool_id": "pool"}, + "q3": {"candidate_pool_id": "pool"}, + } + pools = {"pool": {"predicted": "CC", "correct": "CCC"}} + labels = { + query_id: { + "correct_candidate_id": "correct", + "true_smiles": "CCC", + } + for query_id in queries + } + rankings = { + "q1": ["predicted", "correct"], + "q2": ["predicted", "correct"], + } + + class ImmediateExecutor: + def __init__(self, max_workers): + self.max_workers = max_workers + + def __enter__(self): + return self + + def __exit__(self, *_): + return False + + def map(self, function, values, chunksize): + return map(function, values) + + with ( + mock.patch.object(grader, "ProcessPoolExecutor", ImmediateExecutor), + mock.patch.object(grader, "_mces", return_value=7.0) as compute, + ): + metrics = grader.score( + rankings, queries, pools, labels, compute_mces=True, workers=2 + ) + compute.assert_called_once_with(("CCC", "CC")) + self.assertEqual(metrics["mces_at_1"], (7.0 + 7.0 + 100.0) / 3) + + def test_paired_bootstrap_uses_query_level_outcomes(self): + truth = {"q1": "a", "q2": "a", "q3": "a", "q4": "a"} + baseline = {"q1": "a", "q2": "b", "q3": "a", "q4": "b"} + challenger = {"q1": "b", "q2": "a", "q3": "a", "q4": "a"} + report = paired_bootstrap.compare( + truth, baseline, challenger, + confidence=0.9, resamples=10_000, seed=7, + ) + self.assertEqual(report["baseline_hit_rate"], 0.5) + self.assertEqual(report["challenger_hit_rate"], 0.75) + self.assertEqual(report["delta"], 0.25) + self.assertEqual(report["paired_outcomes"], { + "challenger_only": 2, + "baseline_only": 1, + "tie": 1, + }) + + def test_submission_manifest_is_relocation_safe_and_checksum_bound(self): + package = self.root / "submission" + package.mkdir() + (package / "infer.sh").write_text("#!/usr/bin/env bash\nexit 0\n") + (package / "README.md").write_text("# Synthetic package\n") + (package / "model.pt").write_bytes(b"checkpoint") + (package / "model_config.json").write_text("{}\n") + manifest = { + "schema": "massspecgym-retrieval-model/v1", + "checkpoint": { + "path": "model.pt", + "sha256": common.sha256(package / "model.pt"), + "format": "pytorch", + }, + "model_config": "model_config.json", + "training_provenance": { + "data": "synthetic", + "pretrained_assets": [], + }, + } + common.write_json(package / "model_manifest.json", manifest) + self.assertEqual(main_verifier.validate_submission(package), manifest) + (package / "README.md").unlink() + with self.assertRaisesRegex(FileNotFoundError, "README.md"): + main_verifier.validate_submission(package) + (package / "README.md").write_text("# Synthetic package\n") + (package / "model.pt").write_bytes(b"changed") + with self.assertRaisesRegex(ValueError, "checksum"): + main_verifier.validate_submission(package) + + def test_python_sources_compile_without_importing_heavy_dependencies(self): + for path in TASK_ROOT.rglob("*.py"): + py_compile.compile(str(path), doraise=True) + + def test_reference_patches_are_well_formed(self): + patches = TASK_ROOT / "environment/references/patches" + for path in sorted(patches.glob("*.patch")): + subprocess.run( + ["git", "apply", "--stat", str(path)], + check=True, + capture_output=True, + text=True, + ) + lock = json.loads( + (TASK_ROOT / "environment/references/environment-lock.json").read_text() + ) + asset_helper = ( + TASK_ROOT / "environment/references/scripts/prepare_reference_assets.sh" + ).read_text() + for relative, digest in lock["patched_source_sha256"].items(): + self.assertIn(relative.split("/", 1)[1], asset_helper) + self.assertIn(digest, asset_helper) + + def test_reference_formula_loader_supports_published_top_five(self): + module = import_path( + "massspecgym_predict_mist", + TASK_ROOT / "environment/references/scripts/predict_mist.py", + ) + predictions = self.root / "formulae.jsonl" + predictions.write_text(json.dumps({ + "identifier": "query", + "formulas": ["C", "CH2", "CH4", "C2H2", "C2H4"], + }) + "\n") + self.assertEqual(module.load_formulas([predictions], 1), {"query": ["C"]}) + self.assertEqual( + module.load_formulas([predictions], 5), + {"query": ["C", "CH2", "CH4", "C2H2", "C2H4"]}, + ) + conditioned = { + "query": [ + (1, module.np.asarray([0.2, 0.8], dtype=module.np.float32)), + (0, module.np.asarray([0.9, 0.1], dtype=module.np.float32)), + ] + } + maximum = module.aggregate_conditioned_fingerprints(conditioned, "max") + mean = module.aggregate_conditioned_fingerprints(conditioned, "mean") + self.assertEqual(maximum["query"].tolist(), [0.8999999761581421, 0.800000011920929]) + self.assertEqual(mean["query"].tolist(), [0.550000011920929, 0.45000001788139343]) + + def test_contract_requires_full_candidate_permutation(self): + contract = (TASK_ROOT / "environment/contract.md").read_text() + self.assertIn("contain every candidate ID", contract) + self.assertIn("Missing query rankings", contract) + self.assertIn("MCES distance 100", contract) + compose = (TASK_ROOT / "tests/docker-compose.yaml").read_text() + main_section, grader_section = compose.split(" grader:", 1) + self.assertNotIn("MASSSPECGYM_SUBMISSION_DIR", main_section) + self.assertIn("/workspace/submission", (TASK_ROOT / "tests/test.sh").read_text()) + self.assertNotIn("/workspace/submission", grader_section) + self.assertIn("network_mode: none", grader_section) + + def test_candidate_order_control_is_a_complete_permutation(self): + public, _, _ = self.prepare("-order-control") + output = self.root / "order-control.jsonl" + subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/make_candidate_order_control.py" + ), + "--queries", + str(public / "verifier/queries.jsonl"), + "--candidate-pools", + str(public / "verifier/candidate_pools.jsonl"), + "--output", + str(output), + ], + check=True, + capture_output=True, + ) + row = common.jsonl(output)[0] + query = common.jsonl(public / "verifier/queries.jsonl")[0] + pool = common.jsonl(public / "verifier/candidate_pools.jsonl")[0] + self.assertEqual(row["query_id"], query["query_id"]) + self.assertEqual( + row["ranking"], + [candidate["candidate_id"] for candidate in pool["candidates"]], + ) + + def test_glacier_adapters_preserve_the_contract_and_published_domain(self): + public, private, _ = self.prepare("-glacier") + development = public / "development" + query_ids = self.root / "validation-query-ids.txt" + query_ids.write_text("q-val\n") + staged = self.root / "staged-validation" + subprocess.run( + [ + sys.executable, + str(TASK_ROOT / "environment/evaluation/stage_validation.py"), + "--input-root", + str(development), + "--output-root", + str(staged), + "--query-id-file", + str(query_ids), + ], + check=True, + capture_output=True, + ) + staged_query = common.jsonl(staged / "queries.jsonl")[0] + self.assertEqual(staged_query["query_id"], "q-val") + self.assertNotIn("target_smiles", staged_query) + + glacier_input = self.root / "glacier-input" + glacier_input.mkdir() + query = common.jsonl(public / "verifier/queries.jsonl")[0] + query["instrument_type"] = "Orbitrap" + common.write_json(glacier_input / "queries.jsonl", query) + (glacier_input / "candidate_pools.jsonl").write_bytes( + (public / "verifier/candidate_pools.jsonl").read_bytes() + ) + candidate_table = self.root / "glacier-candidates.tsv" + subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/prepare_glacier_candidates.py" + ), + "--input-root", + str(glacier_input), + "--output", + str(candidate_table), + "--eligible-only", + ], + check=True, + capture_output=True, + ) + with candidate_table.open(newline="") as stream: + rows = list(csv.DictReader(stream, delimiter="\t")) + self.assertEqual(len(rows), 3) + self.assertEqual({row["spec"] for row in rows}, {"q-test"}) + self.assertFalse(any("target" in key for key in rows[0])) + + ranking = [row["candidate_id"] for row in rows] + fallback = self.root / "fallback.jsonl" + glacier = self.root / "glacier.jsonl" + common.write_json( + fallback, {"query_id": "q-test", "ranking": ranking[::-1]} + ) + common.write_json(glacier, {"query_id": "q-test", "ranking": ranking}) + merged = self.root / "merged" + merged.mkdir() + subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/merge_glacier_fallback.py" + ), + "--input-root", + str(glacier_input), + "--glacier", + str(glacier), + "--fallback", + str(fallback), + "--output-root", + str(merged), + ], + check=True, + capture_output=True, + ) + self.assertEqual(common.jsonl(merged / "rankings.jsonl")[0]["ranking"], ranking) + + protocol = subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/audit_glacier_protocol.py" + ), + "--labels", + str(private / "labels.jsonl"), + "--queries", + str(glacier_input / "queries.jsonl"), + "--candidate-pools", + str(glacier_input / "candidate_pools.jsonl"), + "--rankings", + str(glacier), + ], + check=True, + capture_output=True, + text=True, + ) + protocol_report = json.loads(protocol.stdout) + self.assertEqual(protocol_report["queries"], 1) + self.assertIn("exact_candidate_id", protocol_report["metrics"]) + + # A production runner stages MIST only for the complement of GLACIER's + # domain. An empty fallback is therefore valid for this all-eligible + # one-query fixture and must not be indexed eagerly during the merge. + fallback.write_text("", encoding="utf-8") + partial_merged = self.root / "partial-merged" + subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/merge_glacier_fallback.py" + ), + "--input-root", + str(glacier_input), + "--glacier", + str(glacier), + "--fallback", + str(fallback), + "--output-root", + str(partial_merged), + ], + check=True, + capture_output=True, + ) + self.assertEqual( + common.jsonl(partial_merged / "rankings.jsonl")[0]["ranking"], + ranking, + ) + + query["instrument_type"] = "" + common.write_json(glacier_input / "queries.jsonl", query) + staged_fallback = self.root / "staged-fallback" + subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/stage_glacier_fallback.py" + ), + "--input-root", + str(glacier_input), + "--output-root", + str(staged_fallback), + ], + check=True, + capture_output=True, + ) + _, fallback_queries, fallback_pools = common.validate_input(staged_fallback) + self.assertEqual(set(fallback_queries), {"q-test"}) + self.assertEqual(len(fallback_pools), 1) + with self.assertRaises(subprocess.CalledProcessError): + subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/merge_glacier_fallback.py" + ), + "--input-root", + str(glacier_input), + "--glacier", + str(glacier), + "--fallback", + str(fallback), + "--output-root", + str(self.root / "should-not-exist"), + ], + check=True, + capture_output=True, + ) + + glacier_runner = ( + TASK_ROOT / "environment/references/scripts/run_glacier_reference.sh" + ).read_text() + self.assertIn("MASS_SPEC_GLACIER_FEATURE_CACHE_SIZE:-64", glacier_runner) + self.assertIn("MASS_SPEC_GLACIER_PREFETCH_FACTOR:-1", glacier_runner) + self.assertIn("MASS_SPEC_REFERENCE_PYTHON", glacier_runner) + self.assertIn( + "5a47cecca707d3abd5a49c7dbac99d100aa2a586d5d4f848f1e8e35140d7db11", + glacier_runner, + ) + + def test_synthetic_archive_packs_losslessly(self): + source = self.root / "packed-source/msg_synth_filt" + (source / "subformulae").mkdir(parents=True) + labels = ( + "spec\tsmiles\tinchikey\tformula\n" + "s1\tCCO\tKEY\tC2H6O\n" + "s2\tnot-a-smiles\tOTHER\tC2H6O\n" + ) + payload = { + "cand_form": "C2H6O", + "cand_ion": "[M+H]+", + "output_tbl": None, + } + (source / "labels.csv").write_text(labels) + (source / "subformulae/s1.json").write_text(json.dumps(payload)) + (source / "subformulae/s2.json").write_text(json.dumps(payload)) + archive = self.root / "synthetic.tar.gz" + with tarfile.open(archive, "w:gz") as stream: + stream.add(source, arcname="msg_synth_filt") + output = self.root / "packed" + subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/pack_synthetic_subformulae.py" + ), + "--archive", + str(archive), + "--output-root", + str(output), + "--expected-rows", + "2", + ], + check=True, + capture_output=True, + ) + self.assertEqual((output / "labels.csv").read_text(), labels) + with sqlite3.connect(output / "subformulae.sqlite") as connection: + stored = connection.execute( + "SELECT payload FROM subformulae WHERE spec = 's1'" + ).fetchone()[0] + self.assertEqual(json.loads(stored), payload) + + experimental = self.root / "experimental.tsv" + split = self.root / "split.tsv" + experimental.write_text("spec\tinchikey\nheldout\tKEY-AAAA-B\n") + split.write_text("name\tsplit\nheldout\ttest\n") + filtered = self.root / "filtered.tsv" + filter_report = self.root / "filter-report.json" + subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/filter_synthetic_heldout.py" + ), + "--labels", + str(experimental), + "--split", + str(split), + "--synthetic-labels", + str(output / "labels.csv"), + "--database", + str(output / "subformulae.sqlite"), + "--output-labels", + str(filtered), + "--output-report", + str(filter_report), + ], + check=True, + capture_output=True, + ) + self.assertEqual(len(filtered.read_text().splitlines()), 1) + report = json.loads(filter_report.read_text()) + self.assertEqual(report["removed_rows"], 2) + self.assertEqual(report["removed_heldout_rows"], 1) + self.assertEqual(report["removed_invalid_smiles_rows"], 1) + with sqlite3.connect(output / "subformulae.sqlite") as connection: + self.assertEqual( + connection.execute("SELECT COUNT(*) FROM subformulae").fetchone()[0], + 0, + ) + + # The operator-facing augmentation materializer uses the pinned + # MassSpecGym TSV directly, without extracting the label-bearing + # processed experimental archive into the agent-visible data root. + output_tsv = self.root / "packed-tsv" + subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/pack_synthetic_subformulae.py" + ), + "--archive", + str(archive), + "--output-root", + str(output_tsv), + "--expected-rows", + "2", + ], + check=True, + capture_output=True, + ) + boundary = self.root / "massspecgym.tsv" + boundary.write_text( + "identifier\tinchikey\tfold\nheldout\tKEY-AAAA-B\ttest\n" + ) + filtered_tsv = self.root / "filtered-tsv.tsv" + filter_report_tsv = self.root / "filter-report-tsv.json" + subprocess.run( + [ + sys.executable, + str( + TASK_ROOT + / "environment/references/scripts/filter_synthetic_heldout.py" + ), + "--experimental-tsv", + str(boundary), + "--synthetic-labels", + str(output_tsv / "labels.csv"), + "--database", + str(output_tsv / "subformulae.sqlite"), + "--output-labels", + str(filtered_tsv), + "--output-report", + str(filter_report_tsv), + ], + check=True, + capture_output=True, + ) + self.assertEqual(json.loads(filter_report_tsv.read_text())["removed_rows"], 2) + augmentation_script = ( + TASK_ROOT / "environment/data/prepare_synthetic_augmentation.sh" + ).read_text() + self.assertIn("--experimental-tsv", augmentation_script) + self.assertIn("--expected-synthetic-rows 2333485", augmentation_script) + self.assertIn("verify_synthetic_augmentation.py", augmentation_script) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/78/780862f2dbeeaf8f849d5ed04eed1fcd9108384e0d288f668b25663c00eb0b2d/score.py b/reproduction/files/78/780862f2dbeeaf8f849d5ed04eed1fcd9108384e0d288f668b25663c00eb0b2d/score.py new file mode 100644 index 0000000000000000000000000000000000000000..5845904a4c60d0751c2e06118bffe253db847073 --- /dev/null +++ b/reproduction/files/78/780862f2dbeeaf8f849d5ed04eed1fcd9108384e0d288f668b25663c00eb0b2d/score.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""CLI for the trusted scorer.""" + +import argparse +from pathlib import Path +import json + +from panel_scoring import PRIMARY +from risk_scoring import score + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--trusted", type=Path, required=True) + parser.add_argument("--normalization", type=Path, + help="Frozen train-only risk normalization parquet") + parser.add_argument("--predictions", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--bootstrap", type=int, default=0, + help="Optional patient bootstrap replicates; disabled by default") + args = parser.parse_args() + report = score(args.input, args.trusted, args.predictions, args.bootstrap, + args.normalization) + args.output.mkdir(parents=True, exist_ok=True) + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + primary = report["panel"][PRIMARY] + reward = primary if primary is not None else 0.0 + (args.output / "reward.json").write_text( + json.dumps({"reward": reward}, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/78/7871a838cb151da0bf7231e7f20444af04c2ad69bbc8193a1d530c01f50d0a67/harbor_verify.py b/reproduction/files/78/7871a838cb151da0bf7231e7f20444af04c2ad69bbc8193a1d530c01f50d0a67/harbor_verify.py new file mode 100644 index 0000000000000000000000000000000000000000..12d0bc0115546251c8c3654e7a6e2ee467d149d6 --- /dev/null +++ b/reproduction/files/78/7871a838cb151da0bf7231e7f20444af04c2ad69bbc8193a1d530c01f50d0a67/harbor_verify.py @@ -0,0 +1,91 @@ +"""Harbor bridge: independently replay one package and export physical metrics. + +No reward anchors, suite.json, candidate-provided scores, or mixed-unit aggregate. +The default is all 39 cases. Explicit subsets are development checks only. +""" +import argparse +import math +from pathlib import Path + +from case_spec import select_cases +from evaluate import write_json +from evaluate_native import evaluate_native +from metrics import definition +from protocol import InfrastructureError, PolicyError + + +def physical_rewards(result, names): + _, cases = select_cases(names) + expected = {c['id'] for c in cases} + if set(result.get('cases', {})) != expected: + raise InfrastructureError('Missing/extra cases: never grade a partial table as the requested suite') + infrastructure = [name for name, row in result['cases'].items() + if row.get('status') not in ('ok', 'policy_error')] + if infrastructure: + raise InfrastructureError(f'Native infrastructure errors: {infrastructure}') + reward = {} + failed = [] + for name, row in sorted(result['cases'].items()): + metric = row.get('primary_metric', {}) + if row.get('status') == 'policy_error': + failed.append(name) + continue + if any(metric.get(k) != v for k, v in definition(name).items()): + raise InfrastructureError(f'Missing/changed primary metric definition: {name}') + if metric.get('status') == 'invalid_operating_regime': + failed.append(name) + continue + value = metric.get('value') + if metric.get('status') != 'ok' or type(value) not in (int, float) or not math.isfinite(value): + raise InfrastructureError(f'Missing/nonfinite physical metric: {name}') + # Preserve the user's physical metric, its units and sign. Directions are + # stored in results.json and METRICS.md; no synthetic cross-unit sum. + reward[f'{name}/{metric["id"]}'] = value + if not reward: + raise PolicyError(f'No case produced a valid result: {failed}') + # A failed case (policy error, diverged simulation, invalid operating regime) has no physical + # metric; it is flagged and counted as a failure while every other case keeps its value. + for name in failed: + reward[f'{name}/failed'] = 1 + reward['failed_cases'] = len(failed) + return reward + + +def verify(data, submission, output, names=None, evaluator=evaluate_native): + names = ['verifier'] if names is None else names + result = evaluator(data, submission, output, names) + try: + reward = physical_rewards(result, names) + except (InfrastructureError, PolicyError) as error: + write_json(Path(output)/'grading-error.json', { + 'status': 'policy_error' if isinstance(error, PolicyError) else 'infrastructure_error', + 'error': str(error), 'accepted': False}) + if isinstance(error, PolicyError): + # The package is invalid: Harbor needs a numeric reward.json; there are no physical metrics. + write_json(Path(output)/'reward.json', {'invalid_submission': 1}) + return {'invalid_submission': 1} + raise + write_json(Path(output)/'reward.json', reward) + write_json(Path(output)/'grading.json', { + 'format': 'hydrogym-harbor-physical/v1', 'accepted': True, + 'scope': {('verifier',): 'verifier-suite', ('all',): 'full-39'}.get(tuple(names), 'development-subset'), + 'case_count': len(reward) - 1 - sum(k.endswith('/failed') for k in reward), + 'failed_cases': sorted(k[:-len('/failed')] for k in reward if k.endswith('/failed')), + 'aggregate_score': None, + 'note': 'Raw per-case primary metrics. Follow each metric direction; do not average unlike units.'}) + return reward + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--data', type=Path, default=Path('/data')) + parser.add_argument('--submission', type=Path, default=Path('/workspace/submission')) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--case', action='append', + help='Development subset (repeat), or all for the complete 39; default: the scored verifier suite') + args = parser.parse_args() + verify(args.data, args.submission, args.output, args.case) + + +if __name__ == '__main__': + main() diff --git a/reproduction/files/78/78cd92a008764f147aabf0ecedf02e9b39f796f057b556617aa6c6dc2b282e15/compare_seeds.py b/reproduction/files/78/78cd92a008764f147aabf0ecedf02e9b39f796f057b556617aa6c6dc2b282e15/compare_seeds.py new file mode 100644 index 0000000000000000000000000000000000000000..b5910777fefc39ba3bbc90b7c55f664aa7d6d677 --- /dev/null +++ b/reproduction/files/78/78cd92a008764f147aabf0ecedf02e9b39f796f057b556617aa6c6dc2b282e15/compare_seeds.py @@ -0,0 +1,247 @@ +"""Paired validation comparisons, conditional on the declared training recipe.""" + +import argparse +import json +from pathlib import Path +import numpy as np +from sklearn.linear_model import LogisticRegression, Ridge +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler + + +def prediction(root, name, task, rows, train, validation, y, enforce_context=True): + result = json.loads((root / "results" / f"{name}-{task}.json").read_text()) + if enforce_context and (root / "execution-context.json").exists(): + expected = { + "features": root / "features" / f"{name}-{task}" / "features.npz", + "validation_predictions": root + / "results" + / f"{name}-{task}-predictions.npz", + } + if any( + key not in result or Path(result[key]).resolve() != path.resolve() + for key, path in expected.items() + ): + raise ValueError( + "Cannot mix execution contexts in paired encoder comparisons" + ) + if "test" in result["probe"]: + raise ValueError("Use validation-only reports") + if "validation_predictions" in result: + data = np.load(result["validation_predictions"], allow_pickle=False) + ids = [row["id"] for row in rows if row["split"] == "val"] + if data["ids"].tolist() != ids: + raise ValueError("Prediction IDs are not aligned") + predicted = data["predictions"] + errors = ( + np.abs(predicted - y[validation]) + if task == "lfmc" + else (predicted != y[validation]).astype(float) + ) + expected = ( + result["probe"]["validation"]["mae"] + if task == "lfmc" + else 1 - result["probe"]["validation"]["accuracy"] + ) + if abs(errors.mean() - expected) > 1e-8: + raise ValueError("Saved predictions disagree with score") + return errors + if task == "awf": + raise ValueError( + "AWF requires saved predictions; refitting can change near-boundary decisions" + ) + data = np.load(result["features"], allow_pickle=False) + ids = data["ids"].tolist() + if len(set(ids)) != len(rows) or set(ids) != {r["id"] for r in rows}: + raise ValueError("Feature IDs do not match evaluation release") + lookup = {key: index for index, key in enumerate(ids)} + x = data["features"][[lookup[row["id"]] for row in rows]].astype(np.float64) + parameter = result["probe"]["selected_parameter"] + estimator = ( + Ridge(alpha=parameter) + if task == "lfmc" + else LogisticRegression(C=parameter, max_iter=3000, random_state=42) + ) + model = make_pipeline(StandardScaler(), estimator).fit(x[train], y[train]) + predicted = model.predict(x[validation]) + return ( + np.abs(predicted - y[validation]) + if task == "lfmc" + else (predicted != y[validation]).astype(float) + ) + + +def summarize_gains(gains, inverse, group_count, task, validation): + gains = np.stack(gains) + rng = np.random.default_rng(42) + samples = rng.integers(0, group_count, size=(5000, group_count)) + totals = np.bincount(inverse, weights=gains.mean(axis=0)) + counts = np.bincount(inverse) + bootstrap = totals[samples].sum(axis=1) / counts[samples].sum(axis=1) + interval = np.quantile(bootstrap, [0.025, 0.975]).tolist() + seed_totals = np.stack([np.bincount(inverse, weights=gain) for gain in gains]) + seed_draws = rng.integers(0, len(gains), size=(5000, len(gains))) + joint = seed_totals[seed_draws[:, :, None], samples[:, None, :]].sum( + axis=(1, 2) + ) / (len(gains) * counts[samples].sum(axis=1)) + joint_interval = np.quantile(joint, [0.025, 0.975]).tolist() + return { + "metric_reduction": "mae" if task == "lfmc" else "error_rate", + "groups": group_count, + "rows": int(validation.sum()), + "per_seed_gain": gains.mean(axis=1).tolist(), + "mean_seed_gain": float(gains.mean()), + "spatial_bootstrap_95_percent_interval": interval, + "seed_and_spatial_bootstrap_95_percent_interval": joint_interval, + "three_seed_criterion_met": len(gains) >= 3 + and bool((gains.mean(axis=1) > 0).all()) + and interval[0] > 0 + and joint_interval[0] > 0, + } + + +def validate_confirmation_recipes(recipes): + """Keep single-pair diagnostics available; require complete declared locks.""" + if len(recipes) <= 1: + return + if any( + isinstance(recipe, dict) and recipe.get("recipe_complete") is False + for recipe in recipes + ): + raise ValueError("Confirmation requires complete training recipe provenance") + if any(recipe is None for recipe in recipes) or any( + recipe != recipes[0] for recipe in recipes + ): + raise ValueError("Confirmation runs must have the same locked training recipe") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument( + "--pairs", + nargs="+", + required=True, + help="random-name:trained-name for each paired seed", + ) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument( + "--raw-baseline", help="Optional raw-feature report name; reported separately" + ) + args = parser.parse_args() + pairs = [pair.split(":") for pair in args.pairs] + if any(len(pair) != 2 for pair in pairs): + raise ValueError("Expected random:trained pairs") + seeds = [ + json.loads( + (args.data_root / "packages" / trained / "provenance.json").read_text() + )["initialization_seed"] + for _, trained in pairs + ] + if len(set(seeds)) != len(seeds): + raise ValueError( + "Repeated initialization seeds cannot count as independent runs" + ) + recipes = [ + json.loads( + (args.data_root / "packages" / trained / "provenance.json").read_text() + ).get("training_recipe") + for _, trained in pairs + ] + validate_confirmation_recipes(recipes) + loader_seeds = [ + json.loads( + (args.data_root / "packages" / trained / "provenance.json").read_text() + ).get("data_seed") + for _, trained in pairs + ] + if len(pairs) > 1 and ( + any(seed is None for seed in loader_seeds) + or len(set(loader_seeds)) != len(loader_seeds) + ): + raise ValueError("Confirmation runs require distinct recorded loader seeds") + report = { + "pairs": pairs, + "initialization_seeds": seeds, + "data_seeds": loader_seeds, + "split": "val", + "bootstrap_replicates": 5000, + "limitation": "Conditional on adaptive validation development; not independent holdout proof.", + "tasks": {}, + } + context = args.data_root / "execution-context.json" + if context.exists(): + report["execution_context"] = json.loads(context.read_text()) + for task in ("awf", "lfmc"): + rows = json.loads((args.data_root / "eval" / task / "labels.json").read_text()) + y = np.array([row["label"] for row in rows]) + train = np.array([row["split"] == "train" for row in rows]) + validation = np.array([row["split"] == "val" for row in rows]) + coords = np.array([row["latlon"] for row in rows])[validation] + # LFMC: resample sites; AWF: 0.1-degree spatial blocks, not individual nearby pixels. + groups = np.round(coords, 6) if task == "lfmc" else np.floor(coords / 0.1) + unique, inverse = np.unique(groups, axis=0, return_inverse=True) + gains = [] + trained_errors = [] + for random, trained in pairs: + provenance = [ + json.loads( + (args.data_root / "packages" / name / "provenance.json").read_text() + ) + for name in (random, trained) + ] + if any(p.get("training_validity") == "invalid" for p in provenance): + raise ValueError( + "Known invalid training implementation cannot count as a candidate" + ) + if ( + provenance[0]["checkpoint"] is not None + or provenance[1]["checkpoint"] is None + ): + raise ValueError( + "Expected random initialization and own trained checkpoint" + ) + if provenance[1].get("origin") == "official_public_pretrained_reference": + raise ValueError( + "Public pretrained references cannot count as our from-scratch runs" + ) + for key in ("variant", "parameters", "initialization_seed", "infer_sha256"): + if provenance[0][key] != provenance[1][key]: + raise ValueError(f"Unpaired {key}") + trained_errors.append( + prediction(args.data_root, trained, task, rows, train, validation, y) + ) + gains.append( + prediction(args.data_root, random, task, rows, train, validation, y) + - trained_errors[-1] + ) + report["tasks"][task] = summarize_gains( + gains, inverse, len(unique), task, validation + ) + if args.raw_baseline: + raw_errors = prediction( + args.data_root, + args.raw_baseline, + task, + rows, + train, + validation, + y, + enforce_context=False, + ) + report["tasks"][task]["raw_baseline_comparison"] = { + "baseline": args.raw_baseline, + **summarize_gains( + [raw_errors - errors for errors in trained_errors], + inverse, + len(unique), + task, + validation, + ), + } + args.output.write_text(json.dumps(report, indent=2)) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/79/7964c932230208ca1229df089f2a1ea5eece21f33c931a7f3ccd5cc07a7758e5/test_concurrent_verifier.py b/reproduction/files/79/7964c932230208ca1229df089f2a1ea5eece21f33c931a7f3ccd5cc07a7758e5/test_concurrent_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..b774abc1b4164b287c5047301f70adbbe6e79971 --- /dev/null +++ b/reproduction/files/79/7964c932230208ca1229df089f2a1ea5eece21f33c931a7f3ccd5cc07a7758e5/test_concurrent_verifier.py @@ -0,0 +1,53 @@ +"""The verifier runs every suite at once: worker table, out-of-memory retries, item order.""" +import pytest + +import common +import main_verifier + + +class OutOfMemoryError(RuntimeError): + """Stands in for torch.cuda.OutOfMemoryError, matched by name.""" + + +@pytest.fixture(autouse=True) +def no_cuda(monkeypatch): + import types + import sys + fake = types.SimpleNamespace(cuda=types.SimpleNamespace(empty_cache=lambda: None)) + monkeypatch.setitem(sys.modules, "torch", fake) + monkeypatch.setattr("time.sleep", lambda seconds: None) + + +def test_every_suite_has_workers(): + assert set(main_verifier.WORKERS_PER_GPU) == set(main_verifier.SUITES) + assert all(n >= 1 for n in main_verifier.WORKERS_PER_GPU.values()) + + +def test_out_of_memory_is_retried(): + calls = [] + + def run(): + calls.append(1) + if len(calls) < 3: + raise OutOfMemoryError("CUDA out of memory") + return {"ok": True} + assert common.with_oom_retry(run) == {"ok": True} + assert len(calls) == 3 + + +def test_persistent_out_of_memory_fails_the_case(): + def run(): + raise OutOfMemoryError("CUDA out of memory") + with pytest.raises(OutOfMemoryError): + common.with_oom_retry(run, attempts=2) + + +def test_other_errors_are_not_retried(): + calls = [] + + def run(): + calls.append(1) + raise ValueError("model error") + with pytest.raises(ValueError): + common.with_oom_retry(run) + assert len(calls) == 1 diff --git a/reproduction/files/7a/7a2e219854bc4060e38b99ca3ab3c329584658b502e76b9edef03a4c4fc807f8/test_native_settings.py b/reproduction/files/7a/7a2e219854bc4060e38b99ca3ab3c329584658b502e76b9edef03a4c4fc807f8/test_native_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..60be2e4873be326326f4d5c362d19c2d6cf7d698 --- /dev/null +++ b/reproduction/files/7a/7a2e219854bc4060e38b99ca3ab3c329584658b502e76b9edef03a4c4fc807f8/test_native_settings.py @@ -0,0 +1,62 @@ +"""CPU regression tests for explicit, identical training/replay physics settings.""" + +from pathlib import Path +import sys +from types import SimpleNamespace +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/evaluation")) +from native_settings import apply_settings, validate_settings +from protocol import InfrastructureError + + +class NativeSettingsTests(unittest.TestCase): + def env(self): + return SimpleNamespace(max_episode_steps=200, num_substeps_per_iteration=200, + MAX_CONTROL=0.25, omega=0.0) + + def test_paper_protocol_and_original_defaults(self): + env = self.env() + settings = {"max_episode_steps": 199, "substeps_per_action": 170, + "max_control": 0.25, "omega": 1.0} + audit = apply_settings(env, {"horizon": 200, "native_settings": settings}) + self.assertEqual(audit["effective"], settings) + self.assertEqual(audit["native_defaults"]["omega"], 0) + self.assertEqual(env.num_substeps_per_iteration, 170) + self.assertEqual(env.max_episode_steps + 1, 200) + + def test_defaults_are_not_silently_changed(self): + env = self.env() + audit = apply_settings(env, {"horizon": 201}) + self.assertEqual(audit["native_defaults"], audit["effective"]) + with self.assertRaisesRegex(InfrastructureError, "horizon"): + apply_settings(self.env(), {"horizon": 200}) + + def test_explicit_time_limit_preserves_native_limit(self): + env = self.env() + case = {"horizon": 200, "episode_end": "time_limit", + "native_settings": {"max_episode_steps": 200}} + audit = apply_settings(env, case) + self.assertEqual(env.max_episode_steps, 200) + self.assertEqual(audit["episode_end"], "time_limit") + self.assertEqual(audit["effective"]["max_episode_steps"], 200) + + def test_reject_mixed_or_unknown_boundary_conventions(self): + for settings, convention in [({"max_episode_steps": 199}, "time_limit"), + ({"max_episode_steps": 200}, "native"), + ({}, "automatic"), ({}, True), ({}, None)]: + with self.subTest(settings=settings, convention=convention), self.assertRaises(InfrastructureError): + validate_settings(settings, 200, convention) + + def test_invalid_or_unreviewed_overrides(self): + invalid = [{"Re": 4200}, {"reward_function": "replacement"}, + {"substeps_per_action": 0}, {"substeps_per_action": 1.5}, + {"omega": float("nan")}, {"omega": True}, {"omega": -1}, + {"max_control": 0}, {"max_episode_steps": 200}, [], None] + for settings in invalid: + with self.subTest(settings=settings), self.assertRaises(InfrastructureError): + validate_settings(settings, 200) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/7a/7a3fd8c2af32e0c14c2e5d7de43a5af27055599d524e7a1d16ebd0d36425e23c/test_schedule_prefix.py b/reproduction/files/7a/7a3fd8c2af32e0c14c2e5d7de43a5af27055599d524e7a1d16ebd0d36425e23c/test_schedule_prefix.py new file mode 100644 index 0000000000000000000000000000000000000000..71e230abdb7b8a96a7b76d3b3eb4bc3e3fd3d782 --- /dev/null +++ b/reproduction/files/7a/7a3fd8c2af32e0c14c2e5d7de43a5af27055599d524e7a1d16ebd0d36425e23c/test_schedule_prefix.py @@ -0,0 +1,54 @@ +"""An early checkpoint must retain the original cosine schedule horizon.""" + +import copy +from pathlib import Path +import sys +import unittest + +from olmo_core.optim.scheduler import CosWithWarmup + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/baseline/starter")) +from export import checkpoint_recipe + + +class SchedulePrefixTest(unittest.TestCase): + def test_native_schedule_and_recipe_match(self): + full = CosWithWarmup(warmup=100) + prefix = CosWithWarmup(warmup=100, t_max=2000) + expected = [full.get_lr(1e-4, step, 2000) for step in range(1, 501)] + actual = [prefix.get_lr(1e-4, step, 500) for step in range(1, 501)] + self.assertEqual(actual, expected) + self.assertNotEqual(full.get_lr(1e-4, 500, 500), expected[-1]) + config = { + "dataset": {"h5py_dir": "9923"}, + "train_module": { + "optim_config": {"lr": 1e-4}, + "scheduler": full.as_config_dict(), + "rank_microbatch_size": 32, + }, + "data_loader": { + "global_batch_size": 64, + "num_dataset_repeats_per_epoch": 32, + }, + "trainer": {"max_duration": {"unit": "steps", "value": 2000}}, + } + short = copy.deepcopy(config) + short["trainer"]["max_duration"]["value"] = 500 + short["train_module"]["scheduler"] = prefix.as_config_dict() + preflight = { + "world_size": 2, + "training_implementation": {"recomputation_version": 2}, + } + self.assertEqual( + checkpoint_recipe(config, preflight, 500), + checkpoint_recipe(short, preflight, 500), + ) + short["train_module"]["scheduler"] = full.as_config_dict() + self.assertNotEqual( + checkpoint_recipe(config, preflight, 500), + checkpoint_recipe(short, preflight, 500), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/7d/7dca5604e270c52dd2687b3cac0f42ac41bc73a6bf2ae845936dfcdf391c6bfa/test_trainval_extract.py b/reproduction/files/7d/7dca5604e270c52dd2687b3cac0f42ac41bc73a6bf2ae845936dfcdf391c6bfa/test_trainval_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa9661fc119e9d4b495c8a1d14cd0ad70d681b2 --- /dev/null +++ b/reproduction/files/7d/7dca5604e270c52dd2687b3cac0f42ac41bc73a6bf2ae845936dfcdf391c6bfa/test_trainval_extract.py @@ -0,0 +1,59 @@ +"""Never extract heldout payloads when preparing downstream development data.""" + +import io +import json +from pathlib import Path +import sys +import tarfile +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/downstream")) +from extract_trainval import extract + + +class TestExtract(unittest.TestCase): + def test_heldout_payload_skipped(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "source.tar" + with tarfile.open(archive, "w") as tar: + files = {"lfmc/config.json": b"{}"} + for split in ["train", "val", "test"]: + prefix = f"lfmc/windows/spatial_split/{split}" + files[prefix + "/metadata.json"] = json.dumps( + {"options": {"split": split}} + ).encode() + files[prefix + "/layers/labels/value/geotiff.tif"] = b"payload" + # Real release may place payloads before metadata. + for name, data in reversed(list(files.items())): + info = tarfile.TarInfo(name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + original = tarfile.TarFile.extractfile + accesses = [] + + def track(tar, member): + accesses.append(member.name) + return original(tar, member) + + with patch.object(tarfile.TarFile, "extractfile", track): + report = extract( + archive, root / "output", {"train": 1, "val": 1, "test": 1} + ) + self.assertFalse((root / "output/windows/spatial_split/test").exists()) + self.assertTrue( + ( + root + / "output/windows/spatial_split/train/layers/labels/value/geotiff.tif" + ).exists() + ) + self.assertFalse(any("/test/layers/" in n for n in accesses)) + self.assertFalse(report["heldout_window_payloads_read"]) + with self.assertRaises(ValueError): + extract(archive, root / "output") + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/7e/7e7d6b7106b9d865633fcb89765a80ddf87af5ce06c4d589f83bf30aafea8d4c/test.sh b/reproduction/files/7e/7e7d6b7106b9d865633fcb89765a80ddf87af5ce06c4d589f83bf30aafea8d4c/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bb209986dd6ebc0e59f5a33dd6b1cbf8d10541d2 --- /dev/null +++ b/reproduction/files/7e/7e7d6b7106b9d865633fcb89765a80ddf87af5ce06c4d589f83bf30aafea8d4c/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +exec python3 /tests/main_verifier.py \ + --submission /workspace/submission \ + --input /benchmark \ + --sealed /sealed/run \ + --output /logs/verifier \ + --timeout "${PEER_PROTEIN_INFERENCE_TIMEOUT_SECONDS:-85800}" diff --git a/reproduction/files/7e/7e98e6da362c0f2b025f570a57c13f59a4a6947bb24c6c15c4e6278ab1ba225b/protocol.py b/reproduction/files/7e/7e98e6da362c0f2b025f570a57c13f59a4a6947bb24c6c15c4e6278ab1ba225b/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..468e011a9a93ad56b4ac3b3a9971f591b62f59a2 --- /dev/null +++ b/reproduction/files/7e/7e98e6da362c0f2b025f570a57c13f59a4a6947bb24c6c15c4e6278ab1ba225b/protocol.py @@ -0,0 +1,257 @@ +"""Bounded, resident action-only policy protocol. No CFD or ML dependencies.""" + +import json +import math +import os +from pathlib import Path +import pwd +import select +import shutil +import signal +import subprocess +import tempfile +import time +import sys +sys.path.insert(0, "/operator") +from adapted_boundary import restrict_network + + +PROTOCOL = "hydrogym-policy/v1" +MAX_LINE = 64 * 1024 * 1024 +# When HYDROGYM_POLICY_ISOLATION=1 (exported by the Harbor verifier, tests/test.sh), +# the submitted policy runs as this unprivileged account, so it can neither rewrite +# results nor outlive its case: every process of the account is killed when the policy +# closes. Cases replayed side by side therefore each get their own account +# (HYDROGYM_POLICY_UID, set by evaluate_native.replay_cases). A missing account fails closed. +POLICY_UID = int(os.environ.get("HYDROGYM_POLICY_UID", "10001")) +ISOLATION_ENV = "HYDROGYM_POLICY_ISOLATION" + + +class PolicyError(RuntimeError): + pass + + +class InfrastructureError(RuntimeError): + pass + + +def numbers(values): + return isinstance(values, list) and all( + type(v) in (int, float) and math.isfinite(v) for v in values) + + +def unpack(value): + if hasattr(value, "tolist"): + value = value.tolist() + if isinstance(value, (list, tuple)): + return [number for part in value for number in unpack(part)] + return [float(value)] + + +def policy_account(): + """Unprivileged account for the policy process, or None when isolation is off.""" + if os.environ.get(ISOLATION_ENV) != "1": + return None + if os.geteuid() != 0: + raise InfrastructureError("Policy isolation requires a root-run evaluator") + try: + account = pwd.getpwuid(POLICY_UID) + except KeyError as error: + raise InfrastructureError(f"No unprivileged policy account (uid {POLICY_UID})") from error + if account.pw_uid == 0 or account.pw_gid == 0: + raise InfrastructureError("Policy account must not be root") + return account + + +def _demote(account): + def drop(): + os.setgroups([]) + os.setgid(account.pw_gid) + os.setuid(account.pw_uid) + # Only the trusted simulator retains MPI sockets. Policy children are offline. + restrict_network() + return drop + + +def kill_account_processes(uid): + """SIGKILL every process owned by uid (daemonized leftovers escape the process group).""" + for entry in Path("/proc").iterdir(): + if entry.name.isdigit(): + try: + if entry.stat().st_uid == uid: + os.kill(int(entry.name), signal.SIGKILL) + except (FileNotFoundError, ProcessLookupError, PermissionError): + pass + + +class Policy: + def __init__(self, package, stderr_path, timeout=120): + self.timeout = timeout + self.buffer = b"" + self.sequence = 0 + self.stderr = Path(stderr_path).open("wb") + # A predictor spawned inside MPMD must not accidentally rejoin its MPI world. + env = {k: v for k, v in os.environ.items() + if not k.startswith(("OMPI_", "PMI_", "PMIX_", "MPI_"))} + cwd, demote, self.home = "/tmp", None, None + try: + self.account = policy_account() + except InfrastructureError: + self.stderr.close() + raise + if self.account is not None: + self.home = tempfile.mkdtemp(prefix="hydrogym-policy-") + os.chown(self.home, self.account.pw_uid, self.account.pw_gid) + env.update(HOME=self.home, TMPDIR=self.home, USER=self.account.pw_name, + LOGNAME=self.account.pw_name) + cwd, demote = self.home, _demote(self.account) + try: + self.process = subprocess.Popen( + ["bash", str(Path(package).resolve() / "infer.sh")], cwd=cwd, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.stderr, + start_new_session=True, env=env, bufsize=0, preexec_fn=demote) + except OSError as error: + self.stderr.close() + if self.home: + shutil.rmtree(self.home, ignore_errors=True) + raise PolicyError(f"Could not launch policy: {error}") from error + os.set_blocking(self.process.stdin.fileno(), False) + os.set_blocking(self.process.stdout.fileno(), False) + + def ask(self, op, **payload): + self.sequence += 1 + request_id = f"request-{self.sequence}" + raw = (json.dumps(dict(protocol=PROTOCOL, op=op, request_id=request_id, **payload), + allow_nan=False) + "\n").encode() + if len(raw) > MAX_LINE: + raise InfrastructureError("Observation exceeds the declared protocol limit") + deadline = time.monotonic() + self.timeout + remaining = memoryview(raw) + while remaining: + left = deadline - time.monotonic() + if left <= 0 or not select.select([], [self.process.stdin], [], left)[1]: + raise PolicyError("Policy stdin timeout") + try: + count = os.write(self.process.stdin.fileno(), remaining) + remaining = remaining[count:] + except (BrokenPipeError, OSError) as error: + raise PolicyError("Policy closed stdin") from error + while b"\n" not in self.buffer: + left = deadline - time.monotonic() + if left <= 0 or not select.select([self.process.stdout], [], [], left)[0]: + raise PolicyError("Policy response timeout") + chunk = os.read(self.process.stdout.fileno(), min(65536, MAX_LINE + 1)) + if not chunk: + raise PolicyError("Policy exited before replying") + self.buffer += chunk + if len(self.buffer) > MAX_LINE: + raise PolicyError("Policy response exceeds protocol limit") + line, self.buffer = self.buffer.split(b"\n", 1) + try: + response = json.loads(line) + except (ValueError, UnicodeError) as error: + raise PolicyError("Policy stdout is not JSON-lines") from error + if not isinstance(response, dict) or response.get("request_id") != request_id: + raise PolicyError("Wrong/missing response request_id") + return response + + def reset(self, context, observation_shape, action_shape, low, high): + self.low, self.high = low, high + for shape in (observation_shape, action_shape): + if not shape or any(type(n) is not int or n <= 0 for n in shape): + raise InfrastructureError("Invalid native observation/action shape") + self.observation_size = math.prod(observation_shape) + if not numbers(low) or not numbers(high) or len(low) != len(high): + raise InfrastructureError("Invalid native action bounds") + if len(low) != math.prod(action_shape): + raise InfrastructureError("Native action shape and bounds disagree") + if any(a > b for a, b in zip(low, high)): + raise InfrastructureError("Reversed native action bounds") + reply = self.ask("reset", context=context, observation_shape=list(observation_shape), + action_shape=list(action_shape), action_low=low, action_high=high) + if reply.get("ready") is not True: + raise PolicyError("Policy did not acknowledge reset") + + def act(self, observation): + if not numbers(observation) or len(observation) != self.observation_size: + raise InfrastructureError("Nonfinite/invalid native observation") + action = self.ask("act", observation=observation).get("action") + if not numbers(action) or len(action) != len(self.low): + raise PolicyError("Nonfinite or wrong-sized action") + if any(x < a or x > b for x, a, b in zip(action, self.low, self.high)): + raise PolicyError("Action outside native environment bounds") + return action + + def close(self): + try: + if self.process.poll() is None: + reply = self.ask("close") + if reply.get("closed") is not True: + raise PolicyError("Policy did not acknowledge close") + try: + code = self.process.wait(timeout=self.timeout) + except subprocess.TimeoutExpired as error: + raise PolicyError("Policy did not exit after close") from error + if code: + raise PolicyError(f"Policy close exit code {code}") + else: + raise PolicyError("Policy exited before close") + finally: + self.abort() + + def abort(self): + # Kill any descendants even if the original process has already exited. + try: + os.killpg(self.process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if self.account is not None: + kill_account_processes(self.account.pw_uid) + shutil.rmtree(self.home, ignore_errors=True) + self.process.wait() + self.process.stdin.close() + self.process.stdout.close() + self.stderr.close() + + +def replay_episode(env, policy, case, seed): + """Only the trusted environment supplies returns; the policy supplies actions.""" + started = time.monotonic() + observation, _ = env.reset(seed=seed) + policy.reset({"environment": case["environment"], "family": case["family"], "seed": seed}, + env.observation_space.shape, env.action_space.shape, + unpack(env.action_space.low), unpack(env.action_space.high)) + reward_sum = 0.0 + terminated = truncated = False + info = {} + for step in range(case["horizon"]): + # Once the policy has acted, an invalid simulation state (nonfinite observation, force or + # reward) is the outcome of its actions: the case fails, the rest of the suite is scored. + # Invalid state before the first action, or a broken solver process, stays infrastructure. + try: + action = policy.act(unpack(observation)) + except InfrastructureError as error: + if step == 0: + raise + raise PolicyError(f"Simulation diverged under the policy's actions by step {step}: {error}") from error + try: + observation, reward, terminated, truncated, info = env.step(action) + if type(reward) not in (int, float) or not math.isfinite(reward): + raise InfrastructureError("Native reward must be one finite scalar") + reward_sum += reward + if not math.isfinite(reward_sum): + raise InfrastructureError("Nonfinite accumulated return") + except InfrastructureError as error: + raise PolicyError(f"Simulation diverged under the policy's actions at step {step + 1}: {error}") from error + if terminated or truncated: + break + if not (terminated or truncated): + raise InfrastructureError("Native episode did not finish within its reviewed horizon") + diagnostics = {k: float(v) for k, v in info.items() + if type(v) in (int, float) and math.isfinite(v)} + result = {"seed": seed, "return": reward_sum, "steps": step + 1, + "terminated": bool(terminated), "truncated": bool(truncated), + "wall_time_sec": time.monotonic() - started, "diagnostics": diagnostics} + if 'primary_metric' in case: + result['primary_metric'] = env.evaluation_metrics() + return result diff --git a/reproduction/files/7f/7fdeaf978d3f364d7a45788825727e1014b716a48e6bd9111857b999f3cd4978/fluid_cleanup.py b/reproduction/files/7f/7fdeaf978d3f364d7a45788825727e1014b716a48e6bd9111857b999f3cd4978/fluid_cleanup.py new file mode 100644 index 0000000000000000000000000000000000000000..86697143c629c896e696c67ef6d933256c223e16 --- /dev/null +++ b/reproduction/files/7f/7fdeaf978d3f364d7a45788825727e1014b716a48e6bd9111857b999f3cd4978/fluid_cleanup.py @@ -0,0 +1,59 @@ +"""Reap MPI only after a trusted worker has recorded a native PolicyError. + +No timeout, exception, or solver crash is converted into a policy outcome. +""" +import hashlib +import json +from pathlib import Path +import subprocess +import time + + +def save_policy_failure(output, case, submission, before, result, package_hash, write_json): + if case['backend'] != 'maia' or result.get('status') != 'policy_error': + return + if package_hash(submission) != before or result.get('submission_sha256') != before: + raise RuntimeError('Submission changed before failed-policy cleanup') + write_json(output / 'result.json', result) + write_json(output / 'policy-error-ready.json', { + 'case_id':case['id'], 'submission_sha256':before, + 'result_sha256':hashlib.sha256((output/'result.json').read_bytes()).hexdigest()}) + + +def wait_native(process, *, case, output, submission_sha256, started=None): + deadline=(time.monotonic() if started is None else started)+case['timeout_sec'] + marker=Path(output)/'policy-error-ready.json' + while True: + if marker.is_file(): + receipt=json.loads(marker.read_text());path=Path(output)/'result.json' + result=json.loads(path.read_text()) + if (case['backend']!='maia' or receipt['case_id']!=case['id'] + or receipt['submission_sha256']!=submission_sha256 + or receipt['result_sha256']!=hashlib.sha256(path.read_bytes()).hexdigest() + or result.get('submission_sha256')!=submission_sha256 + or result.get('status')!='policy_error' or not isinstance(result.get('error'),str)): + raise RuntimeError('Invalid trusted failed-policy cleanup receipt') + # The native caller's unchanged finally block kills/reaps this + # process group and its separately recorded policy session. + return 0 + code=process.poll() + if code is not None:return code + if time.monotonic()>=deadline: + raise subprocess.TimeoutExpired(process.args,case['timeout_sec']) + time.sleep(min(.1,max(0,deadline-time.monotonic()))) + + +def patch_worker(source, patch): + path=source/'run_native.py' + patch(path,' can_close = True\n',' can_close = True\n result = None\n') + patch(path,' if can_close:\n env.close()', + ' if can_close:\n if result is not None:\n' + ' import sys\n sys.path.insert(0, "/operator")\n' + ' from fluid_cleanup import save_policy_failure\n' + ' save_policy_failure(output, case, submission, before, result, package_hash, write_json)\n' + ' env.close()') + path=source/'evaluate_native.py' + patch(path," code = process.wait(timeout=case['timeout_sec'])", + ' sys.path.insert(0, "/operator")\n' + ' from fluid_cleanup import wait_native\n' + ' code = wait_native(process, case=case, output=output, submission_sha256=package_hash(package), started=start)') diff --git a/reproduction/files/80/80478ef5e30d4112e37654c5f1d65290ba2406abf37b87b4913ba40a7ed05ec8/main_verifier.py b/reproduction/files/80/80478ef5e30d4112e37654c5f1d65290ba2406abf37b87b4913ba40a7ed05ec8/main_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..0e64b4707f63b9341f10d3ec98a54a8ee6b87c34 --- /dev/null +++ b/reproduction/files/80/80478ef5e30d4112e37654c5f1d65290ba2406abf37b87b4913ba40a7ed05ec8/main_verifier.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +"""Run an untrusted offline submission and seal only bounded predictions.""" + +import argparse +import json +import os +from pathlib import Path +import pwd +import shutil +import signal +import stat +import subprocess +import time + +from common import SNAPSHOT_SCHEMA, sha256, validate_input, write_json +from metrics import TASKS + +MAX_OUTPUT_BYTES = 512 * 1024 * 1024 + + +def validate_submission(root): + root = root.resolve() + for required in ("infer.sh", "README.md"): + if not (root / required).is_file() or (root / required).is_symlink(): + raise FileNotFoundError(f"submission/{required} is required") + for path in root.rglob("*"): + if path.is_symlink() and not path.resolve().is_relative_to(root): + raise ValueError(f"submission symlink escapes package: {path.relative_to(root)}") + + +def kill_agent_processes(uid): + proc = Path("/proc") + if not proc.is_dir(): + return + for entry in proc.iterdir(): + if not entry.name.isdigit() or int(entry.name) == os.getpid(): + continue + try: + status = (entry / "status").read_text() + process_uid = int(next(line for line in status.splitlines() + if line.startswith("Uid:")).split()[1]) + if process_uid == uid: + os.kill(int(entry.name), signal.SIGKILL) + except (FileNotFoundError, ProcessLookupError, PermissionError, StopIteration): + pass + + +def run_submission(submission, input_root, work, timeout): + agent = pwd.getpwnam("agent") + if os.geteuid() != 0: + raise PermissionError( + "the verifier must run as root inside its own container so it can " + f"drop to the unprivileged 'agent' user before executing the " + f"submission; running as uid {os.geteuid()} cannot isolate untrusted " + "code. Run tests/Dockerfile under a normal Docker daemon.") + output = work / "untrusted-output" + output.mkdir() + os.chown(output, agent.pw_uid, agent.pw_gid) + env = { + "PATH": "/opt/conda/bin:/usr/local/bin:/usr/bin:/bin", + "HOME": agent.pw_dir, + "PYTHONUNBUFFERED": "1", + "PIP_NO_INDEX": "1", + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + "CUDA_VISIBLE_DEVICES": os.environ.get("CUDA_VISIBLE_DEVICES", "0"), + } + + def demote(): + os.setgid(agent.pw_gid) + os.setgroups([agent.pw_gid]) + os.setuid(agent.pw_uid) + # Never take the drop on faith. Some sandboxes (apptainer's LD_PRELOAD + # fakeroot, for one) let setuid report success while the process keeps + # its original privileges — which would run an untrusted submission as + # root while looking perfectly healthy. Verify, and refuse to run if the + # drop is not real and irrevocable. Raising here fails the Popen. + if os.getuid() != agent.pw_uid or os.geteuid() != agent.pw_uid: + raise RuntimeError("privilege drop did not take effect") + try: + os.setuid(0) + except OSError: + pass + else: + raise RuntimeError("root could be regained after the privilege drop") + + process = None + try: + with (work / "inference.log").open("wb") as log: + process = subprocess.Popen( + ["bash", str(submission / "infer.sh"), str(input_root), str(output)], + cwd=submission, env=env, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, preexec_fn=demote, + ) + code = process.wait(timeout=timeout) + if code: + raise subprocess.CalledProcessError(code, process.args) + except subprocess.TimeoutExpired: + if process: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=5) + raise + finally: + if process: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if process.poll() is None: + process.wait(timeout=5) + kill_agent_processes(agent.pw_uid) + return output + + +def validate_output_tree(root): + total = 0 + for directory, names, files in os.walk(root, followlinks=False): + for name in names + files: + path = Path(directory) / name + info = path.lstat() + if stat.S_ISLNK(info.st_mode) or not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)): + raise ValueError("untrusted output contains a symlink or special file") + if stat.S_ISREG(info.st_mode): + total += info.st_size + if total > MAX_OUTPUT_BYTES: + raise ValueError("prediction output exceeds 512 MiB") + + +def seal_predictions(untrusted, sealed, input_manifest): + if sealed.exists(): + raise FileExistsError("sealed destination already exists") + validate_output_tree(untrusted) + temporary = sealed.with_name(sealed.name + f".tmp-{os.getpid()}") + temporary.mkdir(parents=True) + hashes = {} + for task in TASKS: + source = untrusted / "predictions" / f"{task}.jsonl" + if not source.is_file() or source.is_symlink(): + continue + if not source.resolve().is_relative_to(untrusted.resolve()): + raise ValueError("prediction path escapes output root") + destination = temporary / f"{task}.jsonl" + shutil.copyfile(source, destination, follow_symlinks=False) + hashes[destination.name] = sha256(destination) + destination.chmod(0o444) + snapshot = { + "schema": SNAPSHOT_SCHEMA, + "input_manifest_sha256": sha256(input_manifest), + "files": hashes, + } + write_json(temporary / "snapshot.json", snapshot) + (temporary / "snapshot.json").chmod(0o444) + temporary.chmod(0o555) + os.replace(temporary, sealed) + (sealed.parent / "READY").write_text(sha256(sealed / "snapshot.json") + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--submission", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--input", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--sealed", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--output", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--timeout", type=int, default=85800) + parser.add_argument("--no-wait", action="store_true") + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=True) + os.chmod(args.output, 0o777) + args.sealed.parent.mkdir(parents=True, exist_ok=True) + validate_input(args.input) + try: + validate_submission(args.submission) + work = args.output / "main" + work.mkdir() + untrusted = run_submission(args.submission, args.input, work, args.timeout) + seal_predictions(untrusted, args.sealed, args.input / "manifest.json") + except (FileNotFoundError, ValueError, subprocess.SubprocessError) as error: + # An invalid package, a failed infer.sh or a timeout scores 0 (TASK_STANDARD.md); Harbor needs reward.json. + reason = f"{type(error).__name__}: {error}" + write_json(args.output / "report.json", {"status": "invalid_submission", "error": reason[:4000], "reward": 0.0}) + write_json(args.output / "reward.json", {"reward": 0.0, "invalid_submission": 1.0}) + (args.sealed.parent / "INVALID").write_text(reason + "\n") + print(f"invalid submission: {reason}") + return + if not args.no_wait: + results = args.sealed.parent / "results" + deadline = time.monotonic() + 600 + while not (results / "reward.json").is_file(): + if time.monotonic() >= deadline: + raise TimeoutError("trusted grader did not publish reward.json") + time.sleep(1) + for name in ("report.json", "reward.json"): + shutil.copyfile(results / name, args.output / name) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/80/80815e55202a57003f8136d3aa5958d0b31c3bcba51c07c50984b08007ddb70a/docker-compose.yaml b/reproduction/files/80/80815e55202a57003f8136d3aa5958d0b31c3bcba51c07c50984b08007ddb70a/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..22e50894c987e8251fade6b15b44409876703c75 --- /dev/null +++ b/reproduction/files/80/80815e55202a57003f8136d3aa5958d0b31c3bcba51c07c50984b08007ddb70a/docker-compose.yaml @@ -0,0 +1,22 @@ +# The controller supplies a submission snapshot and collects /logs/verifier. +services: + main: + build: + context: .. + dockerfile: tests/Dockerfile + # Same outer-container namespace settings as the weather verifier: bwrap's user namespace needs + # an unmasked /proc (systempaths=unconfined) and tests/test.sh detaches the NVIDIA runtime's + # /proc/driver/nvidia mounts before the model runs. The inner model namespace drops + # capabilities and unshares the network. + security_opt: + - seccomp:unconfined + - apparmor:unconfined + - systempaths=unconfined + cap_add: [SYS_ADMIN] + volumes: + - type: bind + source: "${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR}" + target: /data/eval + read_only: true + bind: + create_host_path: false diff --git a/reproduction/files/80/80aa721b938c6fbb0c7a0a275c74956da39d27fc305245b07aad4752fa7768a5/grader.py b/reproduction/files/80/80aa721b938c6fbb0c7a0a275c74956da39d27fc305245b07aad4752fa7768a5/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..ab5c2e2b6c63a0fb96b73797faa7b8bc667cc9a8 --- /dev/null +++ b/reproduction/files/80/80aa721b938c6fbb0c7a0a275c74956da39d27fc305245b07aad4752fa7768a5/grader.py @@ -0,0 +1,408 @@ +#!/usr/bin/env python3 +"""Trusted designability grader. + +Consumes sealed backbone coordinates and the public conditioning contexts. It never +imports or executes the submission. + +Failure policy +-------------- +An individual design that is malformed or geometrically invalid counts as a FAILED +design, not a void track: for a generative model, per-sample failure is the +measurement. A malformed *index* (bad schema, unknown or duplicate example_id) is a +contract violation and zeroes that track. Designs the model never emitted stay in the +denominator, so an empty submission scores zero rather than scoring nothing. + +A scorer that cannot run at all is an infrastructure error and exits nonzero; it never +degrades into a zero pass rate. + +Reporting +--------- +Every track reports a `pass_rate` - the mean per-target fraction of requested designs +that satisfy the track's PUBLISHED criterion, and nothing besides it - with `diversity` +alongside. The task applied geometry and conditioning gates of its own before folding until +2026-09-26; they are gone, because they discarded most of the signal while inventing a +second criterion nobody publishes. See environment/evaluation/RESULTS.md. There is deliberately NO +composite: the four tracks are judged by different published criteria, and the +`unconditional` track is synthetic to this task, so any weighted mean would be a number +this task invented rather than one it measured. See environment/evaluation/RESULTS.md. +""" + +import argparse +import concurrent.futures +import json +import math +import os +import time +from pathlib import Path + +import numpy as np + +from common import (DESIGN_FIELDS, LIGAND_CLASH_MIN, MOTIF_RMSD_MAX, MOTIF_TRACKS, NOVELTY_MAX_TM, + PLDDT_MIN, REPORT_SCHEMA, SC_RMSD_MAX, SNAPSHOT_SCHEMA, TRACKS, + jsonl, sha256, write_json) +from geometry import (cluster_designs, minimum_distance, parse_allatom_pdb) +from pipeline import ScorerUnavailable + +MAX_CONTEXT_BYTES = 64 * 1024 * 1024 + + +def harbor_reward(values): + """Harbor parses reward.json as a flat object of finite numbers; strings, None and nested details + belong in report.json / status.json.""" + import math as _math + return {k: v for k, v in values.items() if isinstance(v, (int, float)) and _math.isfinite(v)} + + +def load_context(path): + """Load one conditioning context; pickle is disabled and shapes are checked.""" + path = Path(path) + if not path.is_file() or path.is_symlink() or path.stat().st_size > MAX_CONTEXT_BYTES: + raise ValueError(f"unsafe context file: {path.name}") + with np.load(path, allow_pickle=False) as handle: + context = {key: handle[key] for key in handle.files} + for key, value in context.items(): + # Residue-name arrays are text; only numeric arrays get a finiteness check, + # and only numeric arrays are promoted to float64 for the geometry code. + if value.dtype.kind in "fiu": + context[key] = value.astype(np.float64) + if not np.all(np.isfinite(context[key])): + raise ValueError(f"non-finite context array: {key}") + elif value.dtype.kind not in "USb": # text labels and boolean masks + raise ValueError(f"unsupported context array type: {key}") + return context + + +def validate_request(track, structure, motif_map, context): + """Did the submission answer the request? Returns (reason_or_None, detail dict). + + This is contract validation, NOT a scoring criterion. The motif map has to name one + distinct in-range residue per motif position, carrying the requested residue + identities, or `pipeline._motif_recapitulation` has nothing to measure against. + Nothing here judges quality: geometry and placement are settled by the refold. + """ + detail = {} + if track not in MOTIF_TRACKS: + return None, detail + coordinates, _, restypes = structure + motif = context.get("motif_coords") + motif_types = context.get("motif_restypes") + if motif is None or context.get("motif_mask") is None or motif_types is None: + raise ValueError("context is missing the motif specification") + size = motif.shape[0] + if (not isinstance(motif_map, list) or len(motif_map) != size + or any(type(index) is not int for index in motif_map) + or len(set(motif_map)) != size + or any(not 0 <= index < coordinates.shape[0] for index in motif_map)): + return "motif_map must list one distinct in-range residue per motif position", detail + requested = [str(name) for name in motif_types] + placed = [restypes[index] for index in motif_map] + if placed != requested: + return (f"motif residue identities differ: placed {placed} " + f"for requested {requested}"), detail + return None, detail + + +def published_raw_criterion(track, structure, motif_map, context): + """The ONE published criterion measured on the raw design, not on the refold. + + enzyme success.txt criterion 2: "No ligand clashes. A ligand clash is any non-motif + backbone atom (N, CA or C) within 1.5 A of the closest ligand atom." No other + track's success.txt names a term on the raw backbone; they are all measured on the + refolded model, which `pipeline.DesignabilityScorer` owns. + + Checked before folding purely to save the fold, never to add a requirement: it is a + conjunct of the criterion, so the verdict is the same either way. It rejected 52% of + enzyme designs on the 2026-09-26 reference run (86 of the 164 that view then held), + which is most of the grading cost this track would otherwise spend on designs that + cannot pass. + """ + detail = {} + if track != "enzyme": + return None, detail + coordinates, _, _ = structure + ligand = context.get("ligand_coords") + if ligand is None or np.size(ligand) == 0: + raise ValueError(f"{track} context is missing ligand coordinates") + placed = set(motif_map or ()) + keep = np.array([index not in placed for index in range(coordinates.shape[0])]) + backbone = coordinates[keep][:, :3].reshape(-1, 3) if keep.any() else np.empty((0, 3)) + detail["ligand_min_distance"] = minimum_distance(backbone, ligand) + if detail["ligand_min_distance"] < LIGAND_CLASH_MIN: + return (f"non-motif backbone clashes with ligand at " + f"{detail['ligand_min_distance']:.2f} A"), detail + return None, detail + + +def fold_designs(scorer, track, context, to_fold): + """Score `to_fold` through the predictor, `scorer.devices` designs at a time. + + Returns {order -> verdict or the exception it raised}, so the caller can replay them + in submission order. Threads are the right tool despite the GIL: every worker spends + its time waiting on a `subprocess.run` for LigandMPNN and RoseTTAFold3, and + `DesignabilityScorer.evaluate` leases a distinct GPU per call. + + One worker is the degenerate case and takes the direct path, so a single-GPU run + behaves exactly as it did before and needs no thread pool at all. + """ + workers = min(len(getattr(scorer, "devices", [None])), len(to_fold)) or 1 + if workers == 1: + return {order: scorer.evaluate(track, structure, context, motif_map) + for order, structure, motif_map in to_fold} + + verdicts = {} + with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: + futures = { + pool.submit(scorer.evaluate, track, structure, context, motif_map): order + for order, structure, motif_map in to_fold} + for future in concurrent.futures.as_completed(futures): + order = futures[future] + try: + verdicts[order] = future.result() + except BaseException as error: # noqa: BLE001 - re-raised in order + # A scorer that cannot run is infrastructure failure, never a zero score + # (see the module docstring), so it must reach the caller. Carrying it + # instead of raising here keeps WHICH design failed deterministic. + verdicts[order] = error + return verdicts + + +def score_track(track, sealed_path, requests, context_root, scorer, novelty=None): + """Score every requested design for one track. + + With `novelty` (novelty.FitNovelty) a designable design passes only if its maximum TM-score to the fit + corpus is below NOVELTY_MAX_TM; diversity is then measured over those passing designs.""" + outcome = {"designs_requested": 0, "designs_returned": 0, "designs_valid": 0, + "designs_designable": 0, "conditioning_satisfied": 0, "failures": {}} + if novelty is not None: + outcome["designs_novel"] = 0 + try: + submitted = {} + for row in jsonl(sealed_path): + if (set(row) != {"example_id", "designs"} + or row["example_id"] not in requests + or row["example_id"] in submitted + or not isinstance(row["designs"], list)): + raise ValueError("malformed, unknown, or duplicate design record") + submitted[row["example_id"]] = row["designs"] + except (OSError, ValueError, json.JSONDecodeError) as error: + return {"pass_rate": 0.0, "diversity": 0.0, + "invalid_reason": str(error), **outcome} + + per_target_success, per_target_diversity = [], [] + structures_root = sealed_path.parent / "structures" + designable = {} # example_id -> [(order, CA trace, PDB path)], in submission order + + for example_id, request in sorted(requests.items()): + requested = request["num_designs"] + outcome["designs_requested"] += requested + context = load_context(Path(context_root) / request["context_path"]) + designs = submitted.get(example_id, [])[:requested] + outcome["designs_returned"] += len(designs) + paths = {} + + # Pass 1, sequential and cheap: parse, validate the request, and apply the one + # published criterion measured on the raw design. Anything that survives has to + # be folded, which is the only expensive part. + to_fold = [] + for order, design in enumerate(designs): + if (not isinstance(design, dict) or not set(design) <= DESIGN_FIELDS + or "structure_path" not in design): + outcome["failures"]["malformed_design_record"] = \ + outcome["failures"].get("malformed_design_record", 0) + 1 + continue + try: + path = (structures_root / design["structure_path"]).resolve() + if not path.is_relative_to(structures_root.resolve()): + raise ValueError("structure path escapes the sealed snapshot") + structure = parse_allatom_pdb(path, request["design_length"]) + outcome["designs_valid"] += 1 + motif = design.get("motif_map") + reason, _ = validate_request(track, structure, motif, context) + if reason is None: + outcome["conditioning_satisfied"] += 1 + reason, _ = published_raw_criterion(track, structure, motif, context) + except (OSError, ValueError) as error: + outcome["failures"][str(error)[:80]] = \ + outcome["failures"].get(str(error)[:80], 0) + 1 + continue + if reason: + outcome["failures"][reason[:80]] = outcome["failures"].get(reason[:80], 0) + 1 + continue + motif_map = design.get("motif_map") if track in MOTIF_TRACKS else None + to_fold.append((order, structure, motif_map)) + paths[order] = path + + # Pass 2, parallel: the pipeline owns the criterion, because the predictor is the + # only thing that can judge it. The grader adds NOTHING to it - no geometry gate, + # no motif RMSD on the raw design, no ligand burial, no hotspot contact. Those + # were this task's own inventions and they deleted most of the signal: 59% of + # designable enzyme designs and every designable ppi binder. See RESULTS.md. + # + # One design per worker, one GPU per worker. Designs are independent and every + # fold is already its own subprocess, so this is the whole cost of using more + # than one card. Parallelism is confined to HERE: the verdicts are collected and + # then replayed in submission order below, because `cluster_designs` is a greedy + # walk whose cluster count depends on the order it sees backbones in. A pass rate + # that changed with scheduling would not be reproducible. + verdicts = fold_designs(scorer, track, context, to_fold) + + for order, structure, _ in to_fold: + verdict = verdicts[order] + if isinstance(verdict, BaseException): + raise verdict + if verdict.get("passed"): + outcome["designs_designable"] += 1 + designable.setdefault(example_id, []).append( + (order, structure[0][:, 1], paths[order])) # CA trace + else: + parts = [f"scRMSD {verdict['sc_rmsd']:.2f}"] if np.isfinite( + verdict.get("sc_rmsd", float("inf"))) else [] + for label, key in (("ipTM", "iptm"), ("PAE", "interface_pae"), + ("ligRMSD", "ligand_rmsd"), ("motif", "motif_rmsd")): + value = verdict.get(key) + if isinstance(value, (int, float)): + parts.append(f"{label} {value:.2f}") + # Keep the stated reason alongside the numbers. Dropping it whenever any + # numeric field was present hid which term actually failed - the metrics + # reported are the best over all sequences, so they need not be the ones + # that lost. + if verdict.get("reason"): + parts.append(str(verdict["reason"])) + key = ("not designable (" + ", ".join(parts) + ")" if parts + else "not designable") + outcome["failures"][key] = outcome["failures"].get(key, 0) + 1 + + # Novelty, batched over the track: one Foldseek search of every designable design against the fit corpus. + max_tm = {} + if novelty is not None: + max_tm = novelty.max_tm({(example_id, order): path for example_id, rows in designable.items() + for order, _, path in rows}) + if max_tm: + outcome["novelty_max_tm_mean"] = float(np.mean(list(max_tm.values()))) + for example_id, request in sorted(requests.items()): + passing = [] + for order, trace, _ in designable.get(example_id, []): + score = max_tm.get((example_id, order)) + if score is not None and score >= NOVELTY_MAX_TM: + key = f"near-copy of a fit-corpus structure (max TM >= {NOVELTY_MAX_TM})" + outcome["failures"][key] = outcome["failures"].get(key, 0) + 1 + continue + passing.append(trace) + if novelty is not None: + outcome["designs_novel"] += len(passing) + per_target_success.append(len(passing) / request["num_designs"]) + per_target_diversity.append(cluster_designs(passing) / len(passing) if passing else 0.0) + + pass_rate = float(np.mean(per_target_success)) if per_target_success else 0.0 + diversity = float(np.mean(per_target_diversity)) if per_target_diversity else 0.0 + # Reported side by side, never blended. Mode coverage answers a different question + # from foldability, and folding the two into one number would hide which moved. + # On `unconditional` diversity is the anti-degeneracy readout: a generator emitting + # one designable fold repeatedly reaches pass_rate 1.0 with diversity near zero. + outcome.update({"pass_rate": pass_rate, "diversity": diversity}) + outcome["invalid_reason"] = None + return outcome + + +def flatten(prefix, value, output): + if isinstance(value, dict): + for key, item in value.items(): + if key not in ("invalid_reason", "failures"): + flatten(f"{prefix}_{key}" if prefix else key, item, output) + elif type(value) in (int, float) and math.isfinite(value): + output[prefix] = float(value) + + +def main(scorer=None): + parser = argparse.ArgumentParser() + parser.add_argument("--sealed", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--contexts", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--output", required=True, type=lambda x: Path(x).resolve()) + # The image sets both of these, so the defaults are right inside a container. They + # are overridable because the grader also has to run OUTSIDE one - reproducing a + # known answer on another cluster is the only way to check that a build scores the + # same. score.py and benchmark/designability/run_designability.py already read these + # env vars, and pipeline.py's own "not installed" message tells the operator to set + # LIGANDMPNN_ROOT; until this was added, the trusted grader was the one component + # that ignored it. + parser.add_argument("--assets", default=os.environ.get( + "PROTEIN_DESIGN_ASSETS", "/assets"), + help="LigandMPNN + RoseTTAFold3 parameters; see " + "environment/fetch_designability_weights.sh") + parser.add_argument("--ligandmpnn", default=os.environ.get( + "LIGANDMPNN_ROOT", "/opt/ligandmpnn"), + help="LigandMPNN checkout (the vendored environment/evaluation/ligandmpnn)") + parser.add_argument("--reference", default=os.environ.get( + "PROTEIN_DESIGN_NOVELTY_REFERENCE", "/reference/fit"), + help="fit-corpus structures for the novelty gate (development/fit/structures, read-only)") + parser.add_argument("--wait-seconds", type=int, default=129600) + # One design folded per worker, one GPU leased per worker. The default is however + # many devices are visible, so a 1-GPU host behaves exactly as it did before and an + # 8-GPU verifier uses all eight without being told to. Set it to 1 to force the + # serial path. + parser.add_argument("--workers", type=int, default=None, + help="designs to fold concurrently (default: visible GPUs)") + arguments = parser.parse_args() + + ready = arguments.sealed.parent / "READY" + deadline = time.monotonic() + arguments.wait_seconds + while not ready.is_file(): + if time.monotonic() >= deadline: + raise TimeoutError("design snapshot was not published") + time.sleep(1) + + snapshot_path = arguments.sealed / "snapshot.json" + if ready.read_text().strip() != sha256(snapshot_path): + raise ValueError("snapshot ready hash mismatch") + snapshot = json.loads(snapshot_path.read_text()) + if (set(snapshot) != {"schema", "input_manifest_sha256", "files", "structures"} + or snapshot["schema"] != SNAPSHOT_SCHEMA): + raise ValueError("invalid snapshot schema") + for name, digest in snapshot["files"].items(): + if sha256(arguments.sealed / name) != digest: + raise ValueError(f"sealed design hash mismatch: {name}") + + from common import validate_input + _, requests = validate_input(arguments.contexts) + + if scorer is None: + from pipeline import DesignabilityScorer, resolve_devices + devices = resolve_devices() + if arguments.workers: + # Fewer workers than devices: keep the first N. More workers than devices: + # round-robin them, which is legitimate only if the GPUs have memory for it. + devices = [devices[index % len(devices)] + for index in range(arguments.workers)] + scorer = DesignabilityScorer(assets_root=arguments.assets, + ligandmpnn_root=arguments.ligandmpnn, + devices=devices) + print(f"grading with {len(devices)} worker(s) on device(s) " + f"{', '.join(str(d) for d in devices)}", flush=True) + + from novelty import FitNovelty + novelty = FitNovelty(arguments.reference) + details = {track: score_track(track, arguments.sealed / f"{track}.jsonl", + requests[track], arguments.contexts, scorer, novelty) + for track in TRACKS} + + arguments.output.mkdir(parents=True, exist_ok=True) + write_json(arguments.output / "report.json", { + "schema": REPORT_SCHEMA, + "thresholds": {"sc_rmsd_max": SC_RMSD_MAX, "plddt_min": PLDDT_MIN, + "motif_rmsd_max": MOTIF_RMSD_MAX, "novelty_max_tm": NOVELTY_MAX_TM}, + "tracks": details, + }) + # reward.json is the file CONTRIBUTING requires; it carries the per-track numeric + # metrics. No composite key: see the module docstring. + flat = {} + for track, result in details.items(): + flatten(track, result, flat) + write_json(arguments.output / "reward.json", harbor_reward(flat)) + + +if __name__ == "__main__": + try: + main() + except ScorerUnavailable as error: + # Infrastructure failure: exit nonzero so it cannot be read as a measured score. + raise SystemExit(f"designability scorer unavailable: {error}") diff --git a/reproduction/files/82/823b8cf939d37380a6b9076f9981bdbb7e2eac8bf7139a1e9db32978c94cc959/residues.py b/reproduction/files/82/823b8cf939d37380a6b9076f9981bdbb7e2eac8bf7139a1e9db32978c94cc959/residues.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6dc9011c9005ec9de0ba9a7f5c2c7710cce7fc --- /dev/null +++ b/reproduction/files/82/823b8cf939d37380a6b9076f9981bdbb7e2eac8bf7139a1e9db32978c94cc959/residues.py @@ -0,0 +1,66 @@ +"""Atom14 residue constants. + +Each residue is represented by up to 14 heavy atoms in a residue-type-specific order, +the representation RFdiffusion3 uses. Slots 0-3 are always the backbone N, CA, C, O, +so backbone-only logic stays valid on an all-atom array. Tryptophan fills all 14. +""" + +ATOM14 = { + "ALA": ["N", "CA", "C", "O", "CB"], + "ARG": ["N", "CA", "C", "O", "CB", "CG", "CD", "NE", "CZ", "NH1", "NH2"], + "ASN": ["N", "CA", "C", "O", "CB", "CG", "OD1", "ND2"], + "ASP": ["N", "CA", "C", "O", "CB", "CG", "OD1", "OD2"], + "CYS": ["N", "CA", "C", "O", "CB", "SG"], + "GLN": ["N", "CA", "C", "O", "CB", "CG", "CD", "OE1", "NE2"], + "GLU": ["N", "CA", "C", "O", "CB", "CG", "CD", "OE1", "OE2"], + "GLY": ["N", "CA", "C", "O"], + "HIS": ["N", "CA", "C", "O", "CB", "CG", "ND1", "CD2", "CE1", "NE2"], + "ILE": ["N", "CA", "C", "O", "CB", "CG1", "CG2", "CD1"], + "LEU": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2"], + "LYS": ["N", "CA", "C", "O", "CB", "CG", "CD", "CE", "NZ"], + "MET": ["N", "CA", "C", "O", "CB", "CG", "SD", "CE"], + "PHE": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2", "CE1", "CE2", "CZ"], + "PRO": ["N", "CA", "C", "O", "CB", "CG", "CD"], + "SER": ["N", "CA", "C", "O", "CB", "OG"], + "THR": ["N", "CA", "C", "O", "CB", "OG1", "CG2"], + "TRP": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2", "NE1", "CE2", "CE3", + "CZ2", "CZ3", "CH2"], + "TYR": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2", "CE1", "CE2", "CZ", "OH"], + "VAL": ["N", "CA", "C", "O", "CB", "CG1", "CG2"], +} + +# OXT, the C-terminal carboxyl oxygen, is deliberately absent: it occurs once per +# chain and AlphaFold's atom14 layout omits it too. Parsers skip it rather than fail. +IGNORED_ATOMS = {"OXT"} + +ATOM14_WIDTH = 14 +BACKBONE_SLOTS = (0, 1, 2, 3) +BACKBONE_ATOMS = ("N", "CA", "C", "O") + +RESTYPES = tuple(sorted(ATOM14)) +RESTYPE_INDEX = {name: index for index, name in enumerate(RESTYPES)} + +THREE_TO_ONE = { + "ALA": "A", "ARG": "R", "ASN": "N", "ASP": "D", "CYS": "C", "GLN": "Q", + "GLU": "E", "GLY": "G", "HIS": "H", "ILE": "I", "LEU": "L", "LYS": "K", + "MET": "M", "PHE": "F", "PRO": "P", "SER": "S", "THR": "T", "TRP": "W", + "TYR": "Y", "VAL": "V", +} + +# Alternative naming for symmetric sidechain tips: these pairs are indistinguishable +# by the physics, so a motif RMSD must take the better of the two assignments. +SYMMETRIC_SWAPS = { + "ARG": [("NH1", "NH2")], + "ASP": [("OD1", "OD2")], + "GLU": [("OE1", "OE2")], + "PHE": [("CD1", "CD2"), ("CE1", "CE2")], + "TYR": [("CD1", "CD2"), ("CE1", "CE2")], +} + + +def atom_slot(residue_name, atom_name): + """Index of `atom_name` within the residue's atom14 layout, or None.""" + names = ATOM14.get(residue_name) + if names is None or atom_name not in names: + return None + return names.index(atom_name) diff --git a/reproduction/files/82/828b2f01bdb7b287d4b87abd2deae08374eaa97969aecdfbc9fe6d7928e530aa/test_hour_release.py b/reproduction/files/82/828b2f01bdb7b287d4b87abd2deae08374eaa97969aecdfbc9fe6d7928e530aa/test_hour_release.py new file mode 100644 index 0000000000000000000000000000000000000000..7266da63e34d412a522f5de64a49f1d094c2f378 --- /dev/null +++ b/reproduction/files/82/828b2f01bdb7b287d4b87abd2deae08374eaa97969aecdfbc9fe6d7928e530aa/test_hour_release.py @@ -0,0 +1,98 @@ +"""The historical hour release retains its source identity and cost budgets.""" +import copy +import json +from pathlib import Path +import sys +import unittest + +DATA = Path(__file__).resolve().parents[1]/'environment/data' +sys.path.insert(0,str(DATA)) +import hour_release as hour +import public_release as public + + +@unittest.skipUnless((DATA/'cost-evidence-hour-v1.json').exists(), 'Evidence not exported yet') +class HourReleaseTests(unittest.TestCase): + def setUp(self): + self.evidence=hour.read('cost-evidence-hour-v1.json') + self.release=hour.build(self.evidence) + + def test_current_exact_membership_and_regime(self): + archive = DATA/'release-hour-v1.json' + self.assertEqual(public.load_release(archive) if archive.exists() else public.load_release(),self.release) + self.assertEqual(self.release['case_count'],19) + self.assertEqual(self.release['training']['case_ids'],self.release['test']['case_ids']) + self.assertTrue(self.release['test']['one_shared_checkpoint']) + self.assertFalse(self.release['test']['parameter_updates']) + self.assertFalse(self.release['test']['normalizer_updates']) + self.assertEqual(self.release['backend_counts'],{'jax':1,'jax-fluids':1,'maia':17}) + self.assertEqual(self.release['files']['bytes'],1_286_356_479) + self.assertEqual(self.release['files']['count'],233) + self.assertLess(self.release['files']['bytes'],500_000_000_000) + + def test_short_round_and_each_larger_phase_fit_explicit_budget(self): + total=0.0 + for c in self.release['cases']: + b=c['reference_training_budgets'] + self.assertEqual(b['single_case_research']['controls'],20000) + self.assertLessEqual(b['single_case_research']['planning_seconds_with_25pct_reserve'],36000) + total+=b['short_multitask_phase']['planning_seconds_with_25pct_reserve'] + self.assertLessEqual(total,36000) + self.assertEqual(total,self.release['reference_training_budget']['short_round_serial_single_h100_planning_seconds']) + self.assertEqual(self.release['reference_training_budget']['short_round_total_controls'],76000) + self.assertFalse(self.release['reference_training_budget']['paper_convergence_claim']) + self.assertFalse(self.release['reference_training_budget']['agent_training_limit']) + + def test_no_single_step_probe_can_replace_real_training(self): + for field,value in [('training_controls',6),('ppo_epochs',0),('changed_parameter_tensors',0), + ('training_seconds',0),('status','failed')]: + evidence=copy.deepcopy(self.evidence) + evidence['cases'][0]['training'][field]=value + with self.subTest(field=field),self.assertRaises(ValueError): + hour.build(evidence) + + def test_no_partial_or_nonfinite_episode(self): + for field,value in [('return',float('nan')),('controls',2),('status','failed')]: + evidence=copy.deepcopy(self.evidence) + replay=evidence['cases'][0]['replay'] + replay[field]=value + with self.subTest(field=field),self.assertRaises(ValueError): + hour.build(evidence) + + def test_no_slow_or_extra_task_and_no_disguised_two_gpu_cost(self): + for mutate in [lambda e:e['cases'][0].update(case='Cylinder_3D_Re3900'), + lambda e:e['cases'][0].update(hardware='2 H100'), + lambda e:e['cases'][0].update(previous_seconds_per_control=88.976), + lambda e:e['cases'].pop()]: + evidence=copy.deepcopy(self.evidence) + mutate(evidence) + with self.assertRaises(ValueError): + hour.build(evidence) + + def test_all_prior_manifests_preserved(self): + for filename,digest in [ + ('release-coverage-v1.json','365e9531671ae4eb24491e880f7e6c1d9768013b5da2bb389df9342525ca1896'), + ('release-speed-v1.json','23c53782f87b91c9be8babee3cab5e7cd16730c9dc79eb46d1b19c796be82890'), + ('release-500gb-v1.json','226b7059b4b6b34bb4a8f169374f2a6bc74bc4f780b22ccbc3171c06b34778f3')]: + self.assertEqual(public.digest(public.load_release(DATA/filename)),digest) + + def test_data_membership_does_not_claim_full_evaluator_certification(self): + self.assertEqual(self.release['status'],'data-release-not-cfd-certified') + self.assertEqual(self.release['test']['execution_manifest_status'], + 'requires_native_protocol_binding_and_full_replay') + self.assertFalse(self.release['test']['independent_hidden_split']) + + def test_runtime_repair_is_explicit_and_uncontrolled_failure_is_not_called_slow(self): + adapter=self.release['source']['organizer_runtime_adapters']['Channel_3D_Retau180'] + self.assertEqual(adapter['profile'],'channel-72cube-local-actuator-clock-v1') + cavity=next(c for c in self.release['exclusions'] if c.get('environment')=='Cavity_2D_Re7500') + self.assertEqual(cavity['reason'],'nonfinite_native_uncontrolled_full_episode') + self.assertNotIn('Cavity_2D_Re7500',self.release['training']['case_ids']) + evidence=copy.deepcopy(self.evidence) + evidence['channel_clock_check']['zero_final_field_max_abs_differences']['U']=1.0 + with self.assertRaisesRegex(ValueError,'invariance'): + hour.build(evidence) + + +if __name__=='__main__': + unittest.main() diff --git a/reproduction/files/82/82f5ae35bb8b47e4f455333427b7559f9b89fec1df06c2cceb8ec0946b6fcd6a/test_alphaqubit_artifact.py b/reproduction/files/82/82f5ae35bb8b47e4f455333427b7559f9b89fec1df06c2cceb8ec0946b6fcd6a/test_alphaqubit_artifact.py new file mode 100644 index 0000000000000000000000000000000000000000..063d004782444d30356340f2d5b5181f28ed1413 --- /dev/null +++ b/reproduction/files/82/82f5ae35bb8b47e4f455333427b7559f9b89fec1df06c2cceb8ec0946b6fcd6a/test_alphaqubit_artifact.py @@ -0,0 +1,247 @@ +"""Synthetic-only artifact integrity and relocated native JAX replay checks.""" +from __future__ import annotations + +import hashlib +import fcntl +import io +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any + +import jax +import numpy as np +import pytest +import stim + +from baselines.alphaqubit_artifact import ( + EXPECTED_GROUPS, INFERENCE_SOURCES, LABEL_MODE, SEMANTIC_SOURCES, TASK_ROOT, + freeze_package, load_model, read_parameters, sha256_file, verify_package, +) +from baselines.alphaqubit_data import AlphaQubitLayout +from baselines.alphaqubit_model import AlphaQubitConfig, transformed_model +from baselines.alphaqubit_predict import predict_condition +from baselines.data import Condition, discover_conditions, hardware_split_indices +from baselines.score_neural import validate_inference_metadata, validate_prediction + + +GROUP = "d3_bX_center_3_5" + + +def write_json(path: Path, record: Any) -> None: + path.write_text(json.dumps(record, sort_keys=True, allow_nan=False)) + + +def make_condition(root: Path, rounds: int) -> Condition: + name = f"surface_code_bX_d3_r{rounds:02d}_center_3_5" + path = root / name + path.mkdir(parents=True) + ideal = stim.Circuit.generated("surface_code:rotated_memory_x", distance=3, rounds=rounds) + ideal.to_file(path / "circuit_ideal.stim") + # Deliberately provide only detector/circuit inputs. No raw readout, labels, + # sweep values or training noise models exist anywhere in this fixture. + rng = np.random.default_rng(70 + rounds) + packed = np.packbits((rng.random((50_000, ideal.num_detectors)) < 0.1).astype(np.uint8), axis=1, bitorder="little") + (path / "detection_events.b8").write_bytes(packed.tobytes()) + return Condition(path, name, 3, "X", rounds, GROUP) + + +@pytest.fixture(scope="module") +def native_fixture(tmp_path_factory: pytest.TempPathFactory) -> tuple[Path, Condition]: + root = tmp_path_factory.mktemp("alphaqubit-native") + condition = make_condition(root / "data", 1) + layout = AlphaQubitLayout.from_condition(condition) + config = AlphaQubitConfig(3, width=4, heads=1, key_size=2, value_size=2, + layers=1, conv_width=2, widening=2, feature_layers=1, bias_width=2, + bias_layers=1, readout_width=2, readout_layers=1) + features = layout.decode_packed_features(np.zeros((2, 1), dtype=np.uint8)) + model = transformed_model(config, layout.metadata()) + parameters = model.init(jax.random.PRNGKey(49), features) + source = {name: sha256_file(TASK_ROOT / "baselines" / name) for name in SEMANTIC_SOURCES} + for stage in ("pretrain", "finetune"): + folder = root / "models" / GROUP / stage + folder.mkdir(parents=True) + identity = {"group": GROUP, "stage": stage, "distance": 3, "label_mode": LABEL_MODE, + "model_config": config.to_dict(), "geometry": layout.metadata(), "source_sha256": source, + "data": {"synthetic_fixture": True}, "protocol": {"selection": "fixture validation selection"}} + identity_sha = hashlib.sha256(json.dumps(identity, sort_keys=True, allow_nan=False).encode()).hexdigest() + np.savez(folder / "best.npz", **{f"{module}/{name}": np.asarray(value, dtype=np.float32) + for module, leaves in parameters.items() for name, value in leaves.items()}) + validation = {"global_steps": 12, "seen_samples": 48, "complete": True, + "selected_best": True, "fit": {"accepted": True, "logical_error_per_round": 0.04}, + "per_condition": {condition.name: {"errors": 2, "total": 50}}} + best = {"schema_version": 1, "identity_sha256": identity_sha, + **{key: identity[key] for key in ("model_config", "geometry", "label_mode", "group", "stage", "distance", "source_sha256")}, + "global_steps": 12, "seen_samples": 48, "selected_LER": 0.04, "validation": validation, + "selection": "lowest accepted validation fitted LER using EMA", "checkpoint_sha256": sha256_file(folder / "best.npz")} + metadata = {"identity": identity, "identity_sha256": identity_sha, + **{key: identity[key] for key in ("group", "stage", "distance", "label_mode")}, + "sessions": [{"ended_at": "2026-09-19T00:00:00+00:00", "stop_reason": "max_steps"}]} + progress = {"identity_sha256": identity_sha, "status": "stopped", "stop_reason": "max_steps", + "global_steps": 15, "best_step": 12, "best_LER": 0.04} + for name, record in (("best.json", best), ("metadata.json", metadata), ("progress.json", progress)): + write_json(folder / name, record) + return root, condition + + +def copy_models(tmp_path: Path, native_fixture: tuple[Path, Condition]) -> Path: + result = tmp_path / "models" + shutil.copytree(native_fixture[0] / "models", result) + return result + + +def test_freeze_both_stages_is_idempotent_and_contains_only_portable_payloads(tmp_path: Path, native_fixture: tuple[Path, Condition]) -> None: + models = copy_models(tmp_path, native_fixture) + output = tmp_path / "package" + manifest = freeze_package(models, "both", output, GROUP) + assert verify_package(output) == manifest == freeze_package(models, "both", output, GROUP) + assert set(manifest["models"]) == {f"{GROUP}/pretrain", f"{GROUP}/finetune"} + assert {f"baselines/{name}" for name in INFERENCE_SOURCES}.issubset(manifest["files"]) + assert {"README.md", "pyproject.toml", "uv.lock"}.issubset(manifest["files"]) + assert not any("train.py" in name or name.endswith(("pkl", "keras")) for name in manifest["files"]) + assert manifest["models"][f"{GROUP}/pretrain"]["data_provenance"] == {"synthetic_fixture": True} + assert len(EXPECTED_GROUPS) == 10 + # Runtime-generated content is allowed, not silently mistaken for payload. + (output / ".venv").mkdir() + (output / ".venv" / "python").symlink_to(sys.executable) + (output / "baselines" / "__pycache__").mkdir(exist_ok=True) + (output / "baselines" / "__pycache__" / "module.pyc").write_bytes(b"cache") + verify_package(output) + + +@pytest.mark.parametrize("corruption", ["weight", "source", "extra", "missing", "symlink", "unsafe_path", "manifest_selection"]) +def test_package_rejects_artifact_tampering(tmp_path: Path, native_fixture: tuple[Path, Condition], corruption: str) -> None: + output = tmp_path / "package" + freeze_package(copy_models(tmp_path, native_fixture), "pretrain", output, GROUP) + if corruption == "weight": + (output / "models" / GROUP / "pretrain" / "model.npz").write_bytes(b"corrupt weights") + elif corruption == "source": + with (output / "baselines" / "alphaqubit_model.py").open("a") as handle: + handle.write("\n# changed\n") + elif corruption == "extra": + (output / "undeclared.txt").write_text("extra") + elif corruption == "missing": + (output / "README.md").unlink() + elif corruption == "symlink": + (output / "README.md").unlink() + (output / "README.md").symlink_to(native_fixture[0] / "models" / GROUP / "pretrain" / "best.json") + elif corruption == "unsafe_path": + manifest = json.loads((output / "manifest.json").read_text()) + manifest["files"]["../escape"] = {"bytes": 0, "sha256": "0" * 64} + write_json(output / "manifest.json", manifest) + else: + manifest = json.loads((output / "manifest.json").read_text()) + manifest["models"][f"{GROUP}/pretrain"]["selection"]["selected_LER"] = 0.001 + write_json(output / "manifest.json", manifest) + with pytest.raises(ValueError): + verify_package(output) + + +@pytest.mark.parametrize("mismatch", ["identity", "checkpoint_hash", "running", "unfinished", "best_step", "best_ler", "selection", "source", "config"]) +def test_freeze_rejects_unbound_or_unfinished_selections(tmp_path: Path, native_fixture: tuple[Path, Condition], mismatch: str) -> None: + models = copy_models(tmp_path, native_fixture) + folder = models / GROUP / "pretrain" + records = {name: json.loads((folder / name).read_text()) for name in ("best.json", "metadata.json", "progress.json")} + best, metadata, progress = records.values() + if mismatch == "identity": + best["identity_sha256"] = "0" * 64 + elif mismatch == "checkpoint_hash": + best["checkpoint_sha256"] = "0" * 64 + elif mismatch == "running": + progress["status"] = "training" + elif mismatch == "unfinished": + del metadata["sessions"][-1]["ended_at"] + elif mismatch == "best_step": + progress["best_step"] += 1 + elif mismatch == "best_ler": + progress["best_LER"] = 0.03 + elif mismatch == "selection": + best["validation"]["fit"]["accepted"] = False + elif mismatch == "source": + best["source_sha256"]["alphaqubit_model.py"] = "0" * 64 + else: + best["model_config"]["width"] = 320 + for name, record in records.items(): + write_json(folder / name, record) + with pytest.raises(ValueError): + freeze_package(models, "pretrain", tmp_path / "rejected", GROUP) + assert not (tmp_path / "rejected").exists() + assert not list(tmp_path.glob(".rejected.*")) + + +@pytest.mark.parametrize("leaves", [{"badkey": np.ones(1, np.float32)}, {"a/w": np.ones(1, np.float64)}, {"a/w": np.array([np.nan], np.float32)}]) +def test_portable_parameters_reject_malformed_or_nonfinite_leaves(leaves: dict[str, np.ndarray]) -> None: + stream = io.BytesIO() + np.savez(stream, **leaves) + with pytest.raises(ValueError): + read_parameters(stream.getvalue()) + + +def test_active_training_lock_and_nonidentical_existing_package_refused(tmp_path: Path, native_fixture: tuple[Path, Condition]) -> None: + models = copy_models(tmp_path, native_fixture) + lock_path = models / GROUP / "pretrain" / ".training.lock" + output = tmp_path / "package" + with lock_path.open("w") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + with pytest.raises(ValueError, match="lock"): + freeze_package(models, "pretrain", output, GROUP) + manifest = freeze_package(models, "pretrain", output, GROUP) + with pytest.raises(ValueError, match="not identical"): + freeze_package(models, "both", output, GROUP) + assert verify_package(output) == manifest + + +def test_relocated_native_cli_replays_after_original_model_deletion_without_labels(tmp_path: Path, native_fixture: tuple[Path, Condition]) -> None: + models = copy_models(tmp_path, native_fixture) + data = tmp_path / "detector-only" + conditions = [make_condition(data, rounds) for rounds in range(1, 26, 2)] + model, parameters, metadata = load_model(models / GROUP / "pretrain" / "best.npz") + apply = jax.jit(lambda params, features: jax.nn.sigmoid(model.apply(params, features)["logits"])) + expected_indices, expected_probabilities = predict_condition(apply, parameters, metadata["geometry"], conditions[0], "validation", 512) + package = tmp_path / "original-package" + freeze_package(models, "pretrain", package, GROUP) + relocated = tmp_path / "moved" / "portable" + relocated.parent.mkdir() + shutil.move(str(package), relocated) + shutil.rmtree(models) + output = tmp_path / "predictions" + environment = {**os.environ, "JAX_PLATFORMS": "cpu", "CUDA_VISIBLE_DEVICES": "", "PYTHONPATH": ""} + result = subprocess.run([sys.executable, "-m", "baselines.alphaqubit_predict", "--package", ".", + "--data-root", str(data), "--split", "validation", "--output", str(output), "--group", GROUP, + "--batch-size", "512"], cwd=relocated, env=environment, capture_output=True, text=True, timeout=180) + assert result.returncode == 0, result.stdout + result.stderr + assert json.loads(result.stdout.splitlines()[-1])["status"] == "complete" + record = json.loads((output / "metadata.json").read_text()) + assert record["model_label_mode"] == record["prediction_label_mode"] == LABEL_MODE + assert record["hardware"]["devices"][0]["platform"] == "cpu" + with np.load(output / f"{conditions[0].name}.npz") as saved: + np.testing.assert_array_equal(saved["shot_indices"], expected_indices) + np.testing.assert_array_equal(saved["probabilities"], expected_probabilities) + assert not list(data.rglob("*actual*")) and not list(data.rglob("*measurement*")) + hashes, counts = {}, {} + condition_map = {condition.name: condition for condition in discover_conditions(data)} + for name in condition_map: + path = output / f"{name}.npz" + split, ids, probabilities = validate_prediction(path) + assert split == "validation" + assert len(ids) == len(probabilities) == 5120 + hashes[name] = sha256_file(path) + counts[name] = {"total": len(ids), "errors": 0} + assert len(validate_inference_metadata(output, "validation", condition_map, hashes, counts)) == 1 + # Reject a truthful prediction mode paired with a contradictory checkpoint. + record["checkpoint_metadata"]["label_mode"] = "qrennd_global_data_parity" + write_json(output / "metadata.json", record) + with pytest.raises(ValueError, match="Checkpoint identity"): + validate_inference_metadata(output, "validation", condition_map, hashes, counts) + verify_package(relocated) + + +def test_wrong_geometry_rejected_before_detector_read(native_fixture: tuple[Path, Condition]) -> None: + root, condition = native_fixture + model, parameters, record = load_model(root / "models" / GROUP / "pretrain" / "best.npz") + wrong = {**record["geometry"], "logical_axis": 1 - record["geometry"]["logical_axis"]} + with pytest.raises(ValueError, match="geometry"): + predict_condition(model.apply, parameters, wrong, condition, "validation", 512) diff --git a/reproduction/files/83/833cd96ca014c4695c441d8a4dd9d8211f1c59e1a20578ce3790d3cd888c141e/namespace.py b/reproduction/files/83/833cd96ca014c4695c441d8a4dd9d8211f1c59e1a20578ce3790d3cd888c141e/namespace.py new file mode 100644 index 0000000000000000000000000000000000000000..f1c4f776f8aa3a853bd7fd74a883544b4f76f138 --- /dev/null +++ b/reproduction/files/83/833cd96ca014c4695c441d8a4dd9d8211f1c59e1a20578ce3790d3cd888c141e/namespace.py @@ -0,0 +1,137 @@ +"""Offline model replay with only runtime, package, unlabeled inputs and output.""" + +import os +from pathlib import Path +import sys +import sysconfig + + +def command(package, inputs, outputs): + # The interpreter and installed model dependencies are explicitly declared. + prefix = Path(sys.prefix).resolve() + base = Path(sys.base_prefix).resolve() + cmd = [ + "bwrap", + "--unshare-all", + "--die-with-parent", + "--new-session", + "--cap-drop", + "ALL", + "--clearenv", + ] + for name in ["/usr", "/bin", "/lib", "/lib64", "/sys"]: + if Path(name).exists(): + cmd += ["--ro-bind", name, name] + # Hide nonstandard /usr subtrees (e.g. shared storage) from offline inference. + standard = { + "bin", + "sbin", + "lib", + "lib32", + "lib64", + "libexec", + "local", + "share", + "include", + "src", + "games", + } + for child in Path("/usr").iterdir(): + # External symlink targets are absent unless explicitly mounted below. + # Do not mount over links such as RHEL's /usr/tmp -> ../var/tmp: their + # target may not exist inside the isolated filesystem. + if child.is_dir() and not child.is_symlink() and child.name not in standard: + cmd += ["--tmpfs", str(child)] + cmd += ["--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--dir", "/etc"] + for path in [base, prefix]: + cmd += ["--ro-bind", str(path), str(path)] + if Path("/etc/ld.so.cache").exists(): + cmd += ["--ro-bind", "/etc/ld.so.cache", "/etc/ld.so.cache"] + for path in sorted(Path("/dev").glob("nvidia*")): + cmd += ["--dev-bind", str(path), str(path)] + cmd += [ + "--ro-bind", + str(package), + "/model", + "--ro-bind", + str(inputs), + "/inputs", + "--bind", + str(outputs), + "/outputs", + "--chdir", + "/model", + ] + site = Path(sysconfig.get_paths()["purelib"]) + runtime_libraries = [ + site / "torch/lib", + *sorted((site / "nvidia").glob("*/lib")), + prefix / "lib", + ] + runtime_libraries = [str(p) for p in runtime_libraries if p.is_dir()] + environment = dict( + PATH=f"{prefix}/bin:/usr/bin:/bin", + PYTHON=str(prefix / "bin/python"), + HOME="/tmp", + PYTHONNOUSERSITE="1", + PYTHONDONTWRITEBYTECODE="1", + PYTHONUNBUFFERED="1", + OMP_NUM_THREADS="4", + OPENBLAS_NUM_THREADS="4", + PIP_NO_INDEX="1", + SLURM_JOB_PARTITION=os.environ.get("SLURM_JOB_PARTITION", ""), + LD_LIBRARY_PATH=":".join( + runtime_libraries + ["/usr/lib/x86_64-linux-gnu", "/usr/lib64"] + ), + ) + # Pass the GPU selection through only when the scheduler set one: an empty CUDA_VISIBLE_DEVICES + # hides every GPU (Docker/Harbor expose the allocated GPUs without setting the variable). + if "CUDA_VISIBLE_DEVICES" in os.environ: + environment["CUDA_VISIBLE_DEVICES"] = os.environ["CUDA_VISIBLE_DEVICES"] + hash_seed = os.environ.get("OLMO_INFERENCE_HASHSEED") + if hash_seed is not None: + if not hash_seed.isdigit() or int(hash_seed) >= 2**32: + raise ValueError("OLMO_INFERENCE_HASHSEED must be a uint32") + environment["PYTHONHASHSEED"] = hash_seed + injected = Path("/.singularity.d/libs") + if injected.is_dir(): + cmd += ["--dir", "/tmp/driver-libs"] + for path in sorted(injected.iterdir()): + if path.name.startswith(("libcuda.", "libnvidia-")) and path.is_file(): + cmd += [ + "--ro-bind", + str(path.resolve()), + "/tmp/driver-libs/" + path.name, + ] + environment["LD_LIBRARY_PATH"] = ( + "/tmp/driver-libs:" + environment["LD_LIBRARY_PATH"] + ) + for key, value in environment.items(): + cmd += ["--setenv", key, value] + return cmd + [ + str(prefix / "bin/python"), + "/model/infer.py", + "--model", + "/model", + "--input", + "/inputs/inputs.h5", + "--output", + "/outputs/features.npz", + ] + + +def direct(package, inputs, outputs): + """Development fallback without Bubblewrap: the same entry point, a clean environment and the + real paths. It gives no isolation and is never used by the verifier (tests/test.sh).""" + sandboxed = command(package, inputs, outputs) + environment = {} + for i, word in enumerate(sandboxed): + if word == "--setenv": + environment[sandboxed[i + 1]] = sandboxed[i + 2] + environment.pop("LD_LIBRARY_PATH", None) # the sandbox's library view; use the image's own + if "CUDA_VISIBLE_DEVICES" in os.environ: + environment["CUDA_VISIBLE_DEVICES"] = os.environ["CUDA_VISIBLE_DEVICES"] + python = sandboxed[-8] + argv = [python, str(Path(package) / "infer.py"), "--model", str(package), + "--input", str(Path(inputs) / "inputs.h5"), "--output", str(Path(outputs) / "features.npz")] + return argv, environment diff --git a/reproduction/files/83/83450b428913d6bf45cc097f9cc2cde89255047faf362fb71fc028748da904c0/docker-compose.yaml b/reproduction/files/83/83450b428913d6bf45cc097f9cc2cde89255047faf362fb71fc028748da904c0/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0a4b86179dcead8abf42b6f433cca34774d3881f --- /dev/null +++ b/reproduction/files/83/83450b428913d6bf45cc097f9cc2cde89255047faf362fb71fc028748da904c0/docker-compose.yaml @@ -0,0 +1,48 @@ +volumes: + sealed: + verifier_logs: +services: + main: + build: + context: .. + dockerfile: tests/Dockerfile + network_mode: none + shm_size: "16gb" + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: 1 + capabilities: [gpu] + volumes: + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the public surface-code materialization}/verifier + target: /benchmark + read_only: true + bind: + create_host_path: false + - sealed:/sealed + - verifier_logs:/logs/verifier + grader: + build: + context: .. + dockerfile: tests/Dockerfile + network_mode: none + cpus: 4 + mem_limit: "16g" + command: ["python", "/opt/task/tests/grader.py"] + volumes: + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the public surface-code materialization}/verifier + target: /benchmark + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the grader label directory} + target: /private + read_only: true + bind: + create_host_path: false + - sealed:/sealed diff --git a/reproduction/files/83/83eb47a2732b13efe1042a44a3eb4b2fa58e7da8be2fd6ba72ced591572b25f8/test_sharded_launcher.py b/reproduction/files/83/83eb47a2732b13efe1042a44a3eb4b2fa58e7da8be2fd6ba72ced591572b25f8/test_sharded_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..49d93175fa684bed8e35ef636fbbe6b94dc13188 --- /dev/null +++ b/reproduction/files/83/83eb47a2732b13efe1042a44a3eb4b2fa58e7da8be2fd6ba72ced591572b25f8/test_sharded_launcher.py @@ -0,0 +1,82 @@ +"""Check array dependencies, fixed inference hashing and CPU-only merge requests.""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +class ShardedLauncherTest(unittest.TestCase): + def test_submission_and_context_guards(self): + track = Path(__file__).resolve().parents[1] + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + package = root / "packages/model" + package.mkdir(parents=True) + for name in ["encoder.pt", "config.json", "infer.py", "LICENSE-OlmoEarth"]: + (package / name).touch() + (package / "provenance.json").write_text("{}") + source = root / "eval/lfmc/inputs.h5" + source.parent.mkdir(parents=True) + source.touch() + shards = root / "shards" + shards.mkdir() + (shards / "part000.h5").touch() + (shards / "manifest.json").write_text( + json.dumps( + { + "source": str(source), + "source_rows": 16, + "start": 0, + "stop": 16, + "batch_size": 16, + "full_release": True, + "shards": [{"file": "part000.h5", "start": 0, "stop": 16}], + } + ) + ) + fake = root / "sbatch" + fake.write_text( + f"#!{sys.executable}\nimport json,os,sys\nfrom pathlib import Path\np=Path(os.environ['FAKE_SLURM_LOG'])\na=json.loads(p.read_text()) if p.exists() else []\na.append({{'argv':sys.argv[1:], 'hash_seed':os.environ.get('OLMO_INFERENCE_HASHSEED')}})\np.write_text(json.dumps(a))\nprint(2000+len(a))\n" + ) + fake.chmod(0o755) + log = root / "calls.json" + env = dict( + os.environ, PATH=f"{root}:{os.environ['PATH']}", FAKE_SLURM_LOG=str(log) + ) + command = [ + sys.executable, + str(track / "docs/slurm/submit_sharded_eval.py"), + "--root", + str(root), + "--name", + "model", + "--shard-inputs", + str(shards), + "--upstream", + str(root / "runtime"), + "--parsable", + ] + result = subprocess.run(command, env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), "2003") + calls = json.loads(log.read_text()) + self.assertEqual(len(calls), 3) + for call in calls: + self.assertIn("--partition=" + os.environ.get("EARTH_SLURM_PARTITION", "gpu"), call["argv"]) + self.assertEqual(call["hash_seed"], "0") + self.assertIn("--gres=gpu:1", calls[0]["argv"]) + self.assertIn("--array=0-0", calls[0]["argv"]) + self.assertIn("--gres=gpu:1", calls[1]["argv"]) + self.assertFalse(any(v.startswith("--gres=") for v in calls[2]["argv"])) + self.assertIn("--dependency=afterok:2001:2002", calls[2]["argv"]) + repeated = subprocess.run(command, env=env, capture_output=True, text=True) + self.assertNotEqual(repeated.returncode, 0) + self.assertEqual(len(json.loads(log.read_text())), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/85/85f8a0a3aa9d2c3c8ae9f896ebf6ade0a28c9a8c0069e148c01e5a633ed8746b/test_standard.py b/reproduction/files/85/85f8a0a3aa9d2c3c8ae9f896ebf6ade0a28c9a8c0069e148c01e5a633ed8746b/test_standard.py new file mode 100644 index 0000000000000000000000000000000000000000..d05a7e896f434f2f1727b1532974f432d0cf6373 --- /dev/null +++ b/reproduction/files/85/85f8a0a3aa9d2c3c8ae9f896ebf6ade0a28c9a8c0069e148c01e5a633ed8746b/test_standard.py @@ -0,0 +1,116 @@ +import sys +from pathlib import Path +import copy +from collections import Counter + +import numpy as np +from ase.build import bulk + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/data")) +from prepare_standard import PrioritySelection, priority +from common import encode_atoms +from splits import atoms_key + + +def test_full_reservoir_is_order_independent_and_honors_parent_caps(): + atoms = encode_atoms(bulk("Cu")) + group = atoms_key(atoms) + rows = [ + dict( + id=f"source/{p}/{f}", + parent=str(p), + source="source", + atoms=atoms, + energy=0.0, + forces=np.zeros((1, 3)).tolist(), + stress=np.zeros((3, 3)).tolist(), + ) + for p in range(8) + for f in range(9) + ] + results = [] + for ordered in [ + rows, + rows[::-1], + sorted(rows, key=lambda r: priority("other:" + r["id"])), + ]: + select = PrioritySelection( + {"train": 13, "val": 13}, (set(), set()), parent_cap=2 + ) + for row in ordered: + select.offer(copy.deepcopy(row), group) + chosen = list(select.rows[select.split(group)].values()) + assert len(chosen) == 13 + assert max(Counter(r["parent"] for r in chosen).values()) <= 2 + results.append({r["id"] for r in chosen}) + assert results[0] == results[1] == results[2] + expected = [] + counts = Counter() + for row in sorted(rows, key=lambda r: priority(r["id"])): + if counts[row["parent"]] < 2: + expected.append(row["id"]) + counts[row["parent"]] += 1 + if len(expected) == 13: + break + assert results[0] == set(expected) + + +def test_standard_selection_excludes_both_physical_partitions(): + select = PrioritySelection({"train": 1, "val": 1}, ({"Cu:1"}, {"blocked"})) + assert not select.eligible("x", "ok", "Cu:1") + assert not select.eligible("x", "blocked", "Al:1") + + +def test_compact_panels_retain_frozen_splits_and_exact_sizes(): + import json + from panels import DEFAULT_PANELS, COUNTS, select + import pytest + from splits import load_split + + if not DEFAULT_PANELS.exists(): + pytest.skip("Materialize --components protocol for frozen-release checks") + rows, _ = load_split() + manifest = json.loads(DEFAULT_PANELS.read_text()) + sides = {} + for split, suites in COUNTS.items(): + selected = [] + for suite, count in suites.items(): + population = [ + r for r in rows if r["split"] == split and r["suite"] == suite + ] + panel = select(population, count) + assert panel == manifest["panels"][split][suite] + assert select(population[::-1], count) == panel + assert all(x["selected"] >= 1 for x in panel["strata"].values()) + selected.extend(r for r in population if r["id"] in set(panel["ids"])) + sides[split] = {r["group"] for r in selected} + assert not sides["val"] & sides["test"] + + +def test_learning_curve_aggregation_averages_losses_not_reduced_metrics(tmp_path): + import json + import pytest + + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/baseline/uma-mp-finetune")) + from plot_learning_curves import aggregate + + for rank, loss in [(0, 1.0), (1, 3.0)]: + (tmp_path / f"steps-rank-{rank}.jsonl").write_text( + json.dumps({"step": 1, "loss": loss}) + "\n" + ) + (tmp_path / f"validation-rank-{rank}.jsonl").write_text( + json.dumps( + { + "step": 1, + "weights": "model", + "metrics": {"val/loss": loss, "val/omat.val,forces,mae": 0.05}, + } + ) + + "\n" + ) + train, val = aggregate(tmp_path, world_size=2) + assert train[0]["loss"] == val[0]["metrics"]["val/loss"] == 2.0 + assert val[0]["metrics"]["val/omat.val,forces,mae"] == 0.05 + (tmp_path / "steps-rank-1.jsonl").unlink() + with pytest.raises(ValueError, match="Missing train ranks"): + aggregate(tmp_path, world_size=2) diff --git a/reproduction/files/86/86cfc178ff1d6a183ec1388efbaa0ef281ce276c6e191f66a82c4275a8cbc682/distributed.py b/reproduction/files/86/86cfc178ff1d6a183ec1388efbaa0ef281ce276c6e191f66a82c4275a8cbc682/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..bbab086ec4030c5a226f536c9b8ae80cc4fe4f48 --- /dev/null +++ b/reproduction/files/86/86cfc178ff1d6a183ec1388efbaa0ef281ce276c6e191f66a82c4275a8cbc682/distributed.py @@ -0,0 +1,159 @@ +"""Deterministic chunking and strict result assembly for independent GPU workers.""" + +from __future__ import annotations + +from collections import Counter, defaultdict +import hashlib +import json +from pathlib import Path + +from common import PROTOCOL, digest, indexed, read_rows, write_json, write_rows + +CHUNK_SIZES = {"discovery": 128, "phonons": 4, "elasticity": 8} + + +def chunk_plan(cases): + indexed(cases) + groups = defaultdict(list) + for case in cases: + if case["suite"] not in CHUNK_SIZES: + raise ValueError(f"Unknown suite: {case['suite']}") + groups[case["suite"]].append(case) + per_suite = {} + for suite, rows in groups.items(): + rows.sort( + key=lambda r: hashlib.sha256( + f"gpu-chunks-v1:{r['id']}".encode() + ).hexdigest() + ) + size = CHUNK_SIZES[suite] + per_suite[suite] = [rows[i : i + size] for i in range(0, len(rows), size)] + # Interleave suites; the cloud queue sends each next chunk to any free GPU. + chunks = [] + for i in range(max(map(len, per_suite.values()))): + for suite in CHUNK_SIZES: + if i >= len(per_suite.get(suite, [])): + continue + rows = per_suite[suite][i] + payload = json.dumps(rows, sort_keys=True, separators=(",", ":")) + sha = hashlib.sha256(payload.encode()).hexdigest() + chunks.append( + { + "chunk_id": f"{suite}-{i:05d}-{sha[:12]}", + "suite": suite, + "input_sha256": sha, + "case_ids": [r["id"] for r in rows], + } + ) + flattened = [key for chunk in chunks for key in chunk["case_ids"]] + if len(flattened) != len(cases) or set(flattened) != {r["id"] for r in cases}: + raise ValueError("Chunk plan lost or duplicated cases") + return chunks + + +def merge(inputs: Path, chunks_root: Path, plan, output: Path, checkpoint_sha256: str, + unfinished_reason: str | None = None): + """Merge finished chunks. With `unfinished_reason` (the verifier's time limit), a chunk that never + finished contributes one failed record per case instead of stopping the merge.""" + if output.exists(): + raise FileExistsError(output) + cases = indexed(read_rows(inputs)) + expected_ids = [key for chunk in plan for key in chunk["case_ids"]] + if len(expected_ids) != len(set(expected_ids)) or set(expected_ids) != cases.keys(): + raise ValueError("Chunk plan does not exactly cover evaluation IDs") + all_predictions, chunk_reports = [], [] + reference_metadata = None + required_same = ( + "factory", + "checkpoint_sha256", + "versions", + "energy_audit", + "energy_audit_sha256", + ) + unfinished = 0 + for chunk in plan: + directory = chunks_root / chunk["chunk_id"] + if unfinished_reason and not (directory / "worker.json").is_file(): + all_predictions.extend({"id": key, "suite": cases[key]["suite"], "status": "failed", + "error": unfinished_reason, "seconds": 0.0} for key in chunk["case_ids"]) + unfinished += len(chunk["case_ids"]) + continue + metadata = json.loads((directory / "run.json").read_text()) + worker = json.loads((directory / "worker.json").read_text()) + if metadata["protocol"] != PROTOCOL or not metadata["complete"]: + raise ValueError( + f"Incomplete/protocol-mismatched chunk: {chunk['chunk_id']}" + ) + if metadata["checkpoint_sha256"] != checkpoint_sha256: + raise ValueError("Mixed model checkpoints") + if worker["chunk_input_sha256"] != chunk["input_sha256"]: + raise ValueError("Wrong chunk input identity") + if digest(directory / "predictions.jsonl") != metadata["predictions_sha256"]: + raise ValueError("Corrupt chunk predictions") + if digest(directory / "inputs.jsonl") != metadata["inputs_sha256"]: + raise ValueError("Corrupt chunk inputs") + chunk_inputs = read_rows(directory / "inputs.jsonl") + if chunk_inputs != [cases[key] for key in chunk["case_ids"]]: + raise ValueError("Chunk geometry/order differs from canonical inputs") + predictions = read_rows(directory / "predictions.jsonl") + ids = indexed(predictions) + if set(ids) != set(chunk["case_ids"]) or metadata["cases"] != len(ids): + raise ValueError("Missing/extra cases in chunk output") + if any(r["suite"] != cases[r["id"]]["suite"] for r in predictions): + raise ValueError("Prediction suite mismatch") + comparable = {key: metadata.get(key) for key in required_same} + if reference_metadata is None: + reference_metadata = comparable + elif reference_metadata != comparable: + raise ValueError( + "Workers used inconsistent environments or energy conventions" + ) + all_predictions.extend(predictions) + chunk_reports.append(worker) + indexed(all_predictions) + all_predictions.sort(key=lambda r: r["id"]) + write_rows(output / "predictions.jsonl", all_predictions) + metadata = { + "protocol": PROTOCOL, + **(reference_metadata or {}), + "inputs_sha256": digest(inputs), + "cases": len(all_predictions), + "complete": True, + "device": "cuda", + "distributed": True, + "predictions_sha256": digest(output / "predictions.jsonl"), + "unfinished_cases": unfinished, + } + write_json(output / "run.json", metadata) + workers = {r["worker_id"] for r in chunk_reports} + timing = { + "worker_instances": len(workers), + "chunks": len(chunk_reports), + "suites": {}, + } + for suite in CHUNK_SIZES: + rows = [r for r in all_predictions if r["suite"] == suite] + if not rows: + continue + durations = sorted(r["seconds"] for r in rows) + timing["suites"][suite] = { + "cases": len(rows), + "successful": sum(r["status"] == "ok" for r in rows), + "failed": sum(r["status"] != "ok" for r in rows), + "total_case_seconds": sum(durations), + "mean_case_seconds": sum(durations) / len(rows), + "median_case_seconds": durations[len(rows) // 2], + "max_case_seconds": max(durations), + "nonconverged_initial": sum( + r["status"] == "ok" + and not r.get("diagnostics", {}).get("converged", False) + for r in rows + ), + } + timing["coverage"] = dict(Counter(r["status"] for r in all_predictions)) + timing["case_gpu_worker_hours"] = sum(r["seconds"] for r in all_predictions) / 3600 + timing["note"] = ( + "Case time includes CPU portions while a GPU worker is reserved; this is not provider-billed time. Failed cases are retained." + ) + write_json(output / "timing.json", timing) + return timing diff --git a/reproduction/files/87/871477d16455a7741cb21ded6707456d4c3a4202b23f14c64556d03c1a26b751/test_alphaqubit_data.py b/reproduction/files/87/871477d16455a7741cb21ded6707456d4c3a4202b23f14c64556d03c1a26b751/test_alphaqubit_data.py new file mode 100644 index 0000000000000000000000000000000000000000..0e54810f38a4a7c9191433a2ffdbf826b3bb2fb5 --- /dev/null +++ b/reproduction/files/87/871477d16455a7741cb21ded6707456d4c3a4202b23f14c64556d03c1a26b751/test_alphaqubit_data.py @@ -0,0 +1,208 @@ +"""Paper input semantics, exact replay, canonical geometry and even-only labels.""" +from __future__ import annotations + +import os +from pathlib import Path +import sys +from typing import Any + +import numpy as np +import pytest +import stim + +PROJECT = Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" if (Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit").is_dir() else Path(__file__).resolve().parents[1] # the baseline project: environment/baseline/alphaqubit here, /opt/task in the verifier image +sys.path.insert(0, str(PROJECT)) +from baselines.alphaqubit_data import ( # noqa: E402 + AlphaQubitLayout, AlphaQubitSampler, _scale_dem, load_hardware, load_hardware_packed, +) +from baselines.data import Condition, discover_conditions, group_conditions, hardware_split_indices # noqa: E402 + + +def make_condition(root: Path, distance: int = 3, basis: str = "X", rounds: int = 3) -> Condition: + name = f"surface_code_b{basis}_d{distance}_r{rounds:02d}_center_3_5" + folder = root / name + folder.mkdir() + generator = f"surface_code:rotated_memory_{basis.lower()}" + ideal = stim.Circuit.generated(generator, distance=distance, rounds=rounds) + noisy = stim.Circuit.generated(generator, distance=distance, rounds=rounds, + after_clifford_depolarization=0.01, + before_measure_flip_probability=0.02, + after_reset_flip_probability=0.01) + ideal.to_file(folder / "circuit_ideal.stim") + noisy.to_file(folder / "circuit_noisy.stim") + dem = noisy.detector_error_model(decompose_errors=True) + dem.to_file(folder / "circuit_detector_error_model.dem") + dem.to_file(folder / "pij_from_even_for_odd.dem") + return Condition(folder, name, distance, basis, rounds, f"d{distance}_b{basis}_center_3_5") + + +@pytest.fixture(scope="module") +def hardware_root() -> Path: + value = os.environ.get("QEC_DATA_ROOT") or os.environ.get("SYCAMORE_DATA_ROOT") + if value is None: + pytest.skip("Set QEC_DATA_ROOT for circuit/allowed-even Sycamore integration checks") + return Path(value) + + +@pytest.mark.parametrize("distance,basis,rounds", [(3, "X", 1), (3, "Z", 3), (5, "X", 3), (5, "Z", 25)]) +def test_known_measurement_history_roundtrip_and_final_masks(tmp_path: Path, distance: int, basis: str, rounds: int) -> None: + condition = make_condition(tmp_path, distance, basis, rounds) + layout = AlphaQubitLayout.from_condition(condition) + rng = np.random.default_rng(23) + measurements = rng.integers(0, 2, size=(17, rounds + 1, distance**2 - 1), dtype=np.uint8) + measurements[:, 0, ~layout.on_basis] = 0 # Published initial off-basis gauge. + measurements[:, -1, ~layout.on_basis] = 0 + previous = np.concatenate([np.zeros_like(measurements[:, :1]), measurements[:, :-1]], axis=1) + events = measurements ^ previous + events[:, -1, ~layout.on_basis] = 0 # Undefined final checks are not events. + circuit = stim.Circuit.from_file(condition.path / "circuit_ideal.stim") + spatial = {tuple(coords): slot for slot, coords in enumerate(layout.physical_stabilizer_coords)} + detectors = np.empty((17, circuit.num_detectors), dtype=np.uint8) + for detector, (x, y, time) in circuit.get_detector_coordinates().items(): + detectors[:, detector] = events[:, int(time), spatial[(x, y)]] + features = layout.decode_features(detectors) + np.testing.assert_array_equal(features["measurements"], measurements) + np.testing.assert_array_equal(features["events"], events) + np.testing.assert_array_equal(features["previous_events"][:, 1:], events[:, :-1]) + assert np.count_nonzero(features["previous_events"][:, 0]) == 0 + assert features["valid_mask"].shape == (rounds + 1, distance**2 - 1) + assert features["valid_mask"][:-1].all(), "First off-basis zeros must not use final-missing embeddings" + np.testing.assert_array_equal(features["valid_mask"][-1], layout.on_basis) + np.testing.assert_array_equal(features["is_final"], [False] * rounds + [True]) + for key in ("measurements", "events", "previous_events"): + assert features[key].dtype == np.float32 + packed = np.packbits(detectors, axis=1, bitorder="little") + for key, expected in features.items(): + np.testing.assert_array_equal(layout.decode_packed_features(packed)[key], expected) + + +@pytest.mark.parametrize("source", ["pij", "xeb", "dem", "circuit"]) +def test_curriculum_sampler_exact_resume_and_noise_zero(tmp_path: Path, source: str) -> None: + condition = make_condition(tmp_path) + sampler = AlphaQubitSampler(condition, seed=71, noise_source=source) + empty, labels = sampler.sample_packed(256, factor=0) + assert empty.dtype == labels.dtype == np.uint8 + assert not np.any(empty) and not np.any(labels) + sampler.sample_packed(128, factor=0.5) + state = sampler.state_dict() + expected = [sampler.sample_packed(shots, factor) for shots, factor in ((67, 0.7), (512, 1.0), (128, 0.5))] + restored = AlphaQubitSampler(condition, seed=71, noise_source=source) + restored.load_state_dict(state) + for (shots, factor), (detectors, labels) in zip(((67, 0.7), (512, 1.0), (128, 0.5)), expected): + actual_dets, actual_labels = restored.sample_packed(shots, factor) + np.testing.assert_array_equal(actual_dets, detectors) + np.testing.assert_array_equal(actual_labels, labels) + assert sum(np.count_nonzero(values[0]) for values in expected) > 0 + assert restored.state_dict() == sampler.state_dict() + features, y = sampler.sample(32, 0.6) + assert features["measurements"].shape == (32, 4, 8) + assert y.shape == (32, 1) and y.dtype == np.float32 + altered = {**state, "seed": 99} + with pytest.raises(ValueError, match="source/configuration"): + restored.load_state_dict(altered) + with pytest.raises(ValueError, match="draw_index"): + restored.load_state_dict({**state, "draw_index": -1}) + + +def test_dem_scaling_preserves_correlated_hyperedges(tmp_path: Path) -> None: + condition = make_condition(tmp_path, distance=5) + dem = stim.DetectorErrorModel.from_file(condition.path / "circuit_detector_error_model.dem") + scaled = _scale_dem(dem, 0.6) + errors = 0 + decomposed = 0 + for original, changed in zip(dem.flattened(), scaled): + assert original.type == changed.type + assert original.targets_copy() == changed.targets_copy() + if original.type == "error": + assert changed.args_copy()[0] == pytest.approx(original.args_copy()[0] * 0.6) + errors += 1 + decomposed += any(target.is_separator() for target in original.targets_copy()) + else: + assert original == changed + assert errors > 0 and decomposed > 0 + + +def test_hardware_loader_never_parses_poisoned_odd_labels(tmp_path: Path) -> None: + condition = make_condition(tmp_path) + width = (condition.rounds * (condition.distance**2 - 1) + 7) // 8 + packed = np.zeros((50_000, width), dtype=np.uint8) + packed[:, 0] = np.arange(50_000, dtype=np.uint64) % 256 + packed.tofile(condition.path / "detection_events.b8") + labels = np.empty((50_000, 2), dtype=np.uint8) + labels[:, 1] = 10 + labels[::2, 0] = 48 + np.arange(25_000) % 2 + labels[1::2, 0] = ord("!") # Any full-file label parser must reject this. + labels.tofile(condition.path / "obs_flips_actual.01") + for split in ("train", "validation"): + selected, actual = load_hardware_packed(condition, split) + indices = hardware_split_indices(split) + np.testing.assert_array_equal(selected, packed[indices]) + np.testing.assert_array_equal(actual[:, 0], labels[indices, 0] - 48) + with pytest.raises(ValueError, match="even rows only"): + load_hardware(condition, "test") # type: ignore[arg-type] + + +def test_all_real_geometries_have_canonical_paths_and_consistent_order(hardware_root: Path) -> None: + groups = group_conditions(hardware_root) + assert sum(map(len, groups.values())) == 130 + for conditions in groups.values(): + reference = AlphaQubitLayout.from_condition(conditions[0]) + for condition in conditions: + layout = AlphaQubitLayout.from_condition(condition) + assert layout.logical_index == 0 + assert layout.logical_axis == (1 if condition.basis == "X" else 0) + np.testing.assert_array_equal(layout.stabilizer_positions, reference.stabilizer_positions) + assert len(set(map(tuple, layout.stabilizer_positions))) == condition.distance**2 - 1 + assert np.all((layout.stabilizer_positions >= 0) & (layout.stabilizer_positions <= condition.distance)) + assert set(map(tuple, layout.data_positions)) == {(i, j) for i in range(condition.distance) for j in range(condition.distance)} + assert np.count_nonzero(layout.stabilizer_types == 0) == (condition.distance**2 - 1) // 2 + assert layout.metadata()["logical_index"] == 0 + + +def read_selected_bits(path: Path, bits: int, indices: np.ndarray) -> np.ndarray: + mapped = np.memmap(path, dtype=np.uint8, mode="r", shape=(50_000, (bits + 7) // 8)) + return np.unpackbits(np.array(mapped[indices]), axis=1, count=bits, bitorder="little").astype(np.bool_) + + +@pytest.mark.parametrize("distance,basis", [(3, "X"), (5, "Z")]) +def test_even_measurements_sweeps_reproduce_official_events_labels_and_gauged_syndromes(hardware_root: Path, distance: int, basis: str) -> None: + condition = next(item for item in discover_conditions(hardware_root) if item.distance == distance and item.basis == basis and item.rounds == 3) + layout = AlphaQubitLayout.from_condition(condition) + circuit = stim.Circuit.from_file(condition.path / "circuit_ideal.stim") + indices = np.arange(0, 256, 2, dtype=np.int64) # Only 128 allowed even shots. + measurements = read_selected_bits(condition.path / "measurements.b8", circuit.num_measurements, indices) + sweeps = read_selected_bits(condition.path / "sweep.b8", circuit.num_sweep_bits, indices) + converter = circuit.compile_m2d_converter() + detectors, labels = converter.convert(measurements=measurements, sweep_bits=sweeps, separate_observables=True) + selected_dets, selected_labels = load_hardware_packed(condition, "train") + np.testing.assert_array_equal(detectors, np.unpackbits(selected_dets[:128], axis=1, count=circuit.num_detectors, bitorder="little")) + np.testing.assert_array_equal(labels, selected_labels[:128]) + features = layout.decode_features(detectors) + + # Independently reconstruct raw stabilizer readouts from measurement-record + # indices, then remove the reference/sweep frame and initial off-basis gauge. + spatial = {tuple(coords): slot for slot, coords in enumerate(layout.physical_stabilizer_coords)} + qubits = circuit.get_final_qubit_coordinates() + raw = np.zeros((128, condition.rounds + 1, layout.num_stabilizers), dtype=np.bool_) + offset = frame = 0 + first_data = circuit.num_measurements - distance**2 + for instruction in circuit.flattened(): + if instruction.name == "M": + targets = instruction.targets_copy() + if frame < condition.rounds: + for local, target in enumerate(targets): + raw[:, frame, spatial[tuple(qubits[target.value][:2])]] = measurements[:, offset + local] + offset += len(targets) + frame += 1 + elif instruction.name == "DETECTOR" and instruction.gate_args_copy()[2] == condition.rounds: + x, y, _ = instruction.gate_args_copy() + data_indices = [offset + target.value for target in instruction.targets_copy() if offset + target.value >= first_data] + raw[:, -1, spatial[(x, y)]] = np.logical_xor.reduce(measurements[:, data_indices], axis=1) + raw[:, :-1, ~layout.on_basis] ^= raw[:, :1, ~layout.on_basis].copy() + reference_events, _ = converter.convert(measurements=np.zeros_like(measurements), sweep_bits=sweeps, separate_observables=True) + reference_grid = np.zeros_like(raw) + for detector, (x, y, time) in circuit.get_detector_coordinates().items(): + reference_grid[:, int(time), spatial[(x, y)]] = reference_events[:, detector] + expected = raw ^ np.logical_xor.accumulate(reference_grid, axis=1) + expected[:, -1, ~layout.on_basis] = 0 + np.testing.assert_array_equal(features["measurements"], expected) diff --git a/reproduction/files/8c/8c1da063778598a0b0f3d969d7ba441673713c8ea87c7f989a2a9f3a862e77bc/test_report.py b/reproduction/files/8c/8c1da063778598a0b0f3d969d7ba441673713c8ea87c7f989a2a9f3a862e77bc/test_report.py new file mode 100644 index 0000000000000000000000000000000000000000..c42dc54a99fe06224ae3294224dd5488ed32b503 --- /dev/null +++ b/reproduction/files/8c/8c1da063778598a0b0f3d969d7ba441673713c8ea87c7f989a2a9f3a862e77bc/test_report.py @@ -0,0 +1,108 @@ +"""Rendering contracts for partial evidence and finalized score artifacts.""" +from __future__ import annotations + +import json +from pathlib import Path +import sys + +PROJECT = Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" if (Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit").is_dir() else Path(__file__).resolve().parents[1] # the baseline project: environment/baseline/alphaqubit here, /opt/task in the verifier image +sys.path.insert(0, str(PROJECT)) +from baselines.report import render_report + + +def test_partial_report_does_not_claim_neural_completion_or_zero_actual_usage(tmp_path: Path) -> None: + evidence = tmp_path / "evidence" + evidence.mkdir() + (tmp_path / "campaign.json").write_text(json.dumps({ + "max_actual_allocated_gpu_hours": 384, "max_concurrent_gpus": 8, + "jobs": [{"id": "1", "name": "training", "gpu_count": 1, + "array_tasks": 2, "max_hours_per_task": 2}], + })) + html = render_report(tmp_path, "run", evidence_root=evidence) + assert "held-out evaluation pending" in html + assert "full held-out scores available" not in html + assert "partial; missing actuals are not zero" in html + assert "4.00 GPU-hours" in html + assert "This page does not poll jobs or run evaluation" in html + + +def test_final_scores_and_untrusted_values_render_without_raw_markup_or_nonfinite_numbers(tmp_path: Path) -> None: + evidence, campaign = tmp_path / "evidence", tmp_path / "run" + evidence.mkdir() + campaign.mkdir() + attack = "" + (evidence / "classical-summary.json").write_text(json.dumps({ + "verification": {"all_130_conditions_verified": True}, + "methods": {attack: {"macro": {}, "group_fits": {"group": { + "logical_error_per_round": float("nan"), + "zero_round_fidelity": float("inf"), "diagnostic_flags": [attack], + }}}}, + })) + score = { + "split": "test", "conditions": 130, "total_shots": 3_250_000, + "summary": {"status": "ok", "macro": { + "d3": {"logical_error_per_round": 0.03, "ci95": [0.029, 0.031]}, + "d5": {"logical_error_per_round": 0.02, "ci95": [0.019, 0.021]}, + }, "per_group": {}}, + "calibration": {"macro": {"d3": {"negative_log_likelihood": 0.12, "brier_score": 0.04}}}, + "paired_comparisons": {"pymatching_correlated_selected": { + "status": "ok", "comparisons": {"d3": { + "logical_error_per_round_a_minus_b": -0.003, + "ci95": [-0.004, -0.002], + }}, + }}, + } + (campaign / "scores-pretrain.json").write_text(json.dumps(score)) + html = render_report(tmp_path, "run", evidence_root=evidence) + assert attack not in html and "<script id='untrusted'>" in html + assert "full held-out scores available; inspect fit diagnostics" in html + assert "held-out evaluation pending" in html # Fine-tuning remains pending. + assert "3.000" in html and "[2.900, 3.100]" in html + assert "-0.300" in html and "[-0.400, -0.200]" in html + assert "0.12000" in html and "0.04000" in html + assert "invalid" in html + assert ">nan<" not in html and ">inf<" not in html + + +def test_accounting_snapshot_overrides_incomplete_submission_ledger_and_marks_job_states(tmp_path: Path) -> None: + evidence = tmp_path / "evidence" + evidence.mkdir() + (tmp_path / "campaign.json").write_text(json.dumps({ + "max_actual_allocated_gpu_hours": 384, "max_concurrent_gpus": 8, + "jobs": [{"id": "1", "name": "pretrain", "gpu_count": 1, + "array_tasks": 3, "max_hours_per_task": 24}], + })) + (tmp_path / "accounting.json").write_text(json.dumps({ + "updated_utc": "2026-09-19T06:00:00+00:00", + "actual_allocated_gpu_hours": 12.375, "active_allocated_gpus": 0, + "declared_allocation_ceiling_gpu_hours": 72, "remaining_actual_gpu_hours": 371.625, + "records": [ + {"job_id": "1_0", "state": "FAILED", "gpu_hours": 12.375}, + {"job_id": "1_1", "state": "CANCELLED", "gpu_hours": 0}, + {"job_id": "1_2", "state": "PENDING", "reason": "DependencyNeverSatisfied", "gpu_hours": 0}, + ], + })) + html = render_report(tmp_path, "run", evidence_root=evidence) + assert "Actual allocated GPU-hours: 12.375" in html + assert "2026-09-19T06:00:00+00:00" in html + assert "Remaining actual budget: 371.625" in html + assert "Recorded actuals sum to 0.000" not in html + assert "Failed / interrupted · FAILED" in html + assert "Cancelled · CANCELLED" in html + assert "Dependency blocked" in html + assert "held-out evaluation pending" in html + + +def test_incomplete_representative_gate_is_waiting_not_failed(tmp_path: Path) -> None: + evidence, campaign = tmp_path / "evidence", tmp_path / "run" + evidence.mkdir() + campaign.mkdir() + (campaign / "representative-gate.json").write_text(json.dumps({ + "passed": False, "checked_utc": "2026-09-19T06:00:00Z", + "groups": {"group": {"passed": False, "checks": {"stage_stopped": False}}}, + })) + html = render_report(tmp_path, "run", evidence_root=evidence) + assert "waiting_for_completed_stages" in html + assert "this waiting result is not a failed training job" in html + assert "failed" not in html + assert "held-out evaluation pending" in html diff --git a/reproduction/files/8e/8e57015132121782179b8df4a5ce50b67eb4694492c658b6a56bdbcd9cb14b90/docker-compose.yaml b/reproduction/files/8e/8e57015132121782179b8df4a5ce50b67eb4694492c658b6a56bdbcd9cb14b90/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a004ecb0e97dae56f919fd09d5c474387c6a5f7a --- /dev/null +++ b/reproduction/files/8e/8e57015132121782179b8df4a5ce50b67eb4694492c658b6a56bdbcd9cb14b90/docker-compose.yaml @@ -0,0 +1,77 @@ +# Verifier (TASK_STANDARD.md). TASK_PRIVATE_DIR is the operator's materialized root; its +# `evaluation` view is verifier-only and is never mounted into the agent's container. +# `main` replays the submission and seals the backbones; `grader` scores them and never +# executes submission code. Both are networkless. +volumes: + sealed: + verifier_logs: + +services: + main: + build: + context: .. + dockerfile: tests/Dockerfile + network_mode: none + shm_size: "16gb" + volumes: + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the materialized protein-design root}/evaluation + target: /benchmark + read_only: true + bind: + create_host_path: false + # Pretrained assets the agent DECLARES rather than ships (environment/contract.md). + # The image creates an EMPTY /pretrained, which is all the `trained_generator` + # paradigm needs. The `predictor_inversion` and `hybrid` paradigms are REFUSED + # without at least one declared asset, and each declared asset must resolve to a + # real file under this path in BOTH the development and the verification + # container. To support them, create the directory on the host, put the assets in + # it, and uncomment: + # + # - type: bind + # source: ${TASK_PRETRAINED_DIR:?Set TASK_PRETRAINED_DIR} + # target: /pretrained + # read_only: true + # bind: + # create_host_path: false + - sealed:/sealed + - verifier_logs:/logs/verifier + gpus: all + healthcheck: + test: ["CMD-SHELL", "test -s /benchmark/manifest.json"] + interval: 5s + timeout: 5s + retries: 3 + + # Trusted scorer. Carries the folding weights in-image and never executes the + # submission. + grader: + build: + context: .. + dockerfile: tests/Dockerfile + network_mode: none + shm_size: "16gb" + command: ["python3", "/tests/grader.py", "--sealed", "/sealed/run", + "--contexts", "/benchmark", "--assets", "/assets", + "--reference", "/reference/fit", + "--output", "/sealed/results"] + volumes: + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the materialized protein-design root}/evaluation + target: /benchmark + read_only: true + bind: + create_host_path: false + # The novelty gate's reference: the fit corpus the agent trains on (the same files it sees). + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the materialized protein-design root}/development/fit/structures + target: /reference/fit + read_only: true + bind: + create_host_path: false + # No /assets mount: LigandMPNN and RoseTTAFold3 parameters are public downloads + # baked into the image by environment/fetch_designability_weights.sh. (There is no + # PROTEIN_DESIGN_EVAL_ASSETS_DIR override any more - nothing reads it. To use a + # pre-fetched host copy, bind it at /assets and pass `--assets` to grader.py.) + - sealed:/sealed + gpus: all diff --git a/reproduction/files/8f/8f6b8c40d89d2581c1cacccdbc2bcf5116e53ea53342f30a383856bb1d4bbf3f/run_loco.py b/reproduction/files/8f/8f6b8c40d89d2581c1cacccdbc2bcf5116e53ea53342f30a383856bb1d4bbf3f/run_loco.py new file mode 100644 index 0000000000000000000000000000000000000000..5949339c51b86cb1375c0725f2b107474bea4d69 --- /dev/null +++ b/reproduction/files/8f/8f6b8c40d89d2581c1cacccdbc2bcf5116e53ea53342f30a383856bb1d4bbf3f/run_loco.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Leave-one-context-out development evaluation with the verifier's scoring code. + +For each held-out training context C: (optionally) run a training command with the other +contexts, then run the package's infer.sh on train/C/dev_split and score it against +dev_split/responses.h5ad. Writes OUT//report.json and OUT/summary.json. + + python run_loco.py --package /workspace/baseline/meandelta --outdir /workspace/research/loco/b1 \ + --train-cmd "python build_table.py --data {data} --contexts {train_contexts}" +""" +import argparse +import json +import os +import shlex +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from cellscore import score_context # noqa: E402 + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--package", required=True, type=Path) + ap.add_argument("--data", type=Path, default=Path("/workspace/data")) + ap.add_argument("--contexts", nargs="+", default=["k562", "jurkat", "hct116", "hek293t"]) + ap.add_argument("--holdout", nargs="*", help="subset of contexts to hold out (default: all)") + ap.add_argument("--outdir", required=True, type=Path) + ap.add_argument("--train-cmd", help="run in the package dir per fold; {data} {train_contexts} {holdout} are substituted") + ap.add_argument("--threads", type=int) + a = ap.parse_args() + summary = {} + for held in (a.holdout or a.contexts): + train = [c for c in a.contexts if c != held] + fold = a.outdir / held + fold.mkdir(parents=True, exist_ok=True) + t0 = time.time() + if a.train_cmd: + cmd = a.train_cmd.format(data=a.data, train_contexts=" ".join(train), holdout=held) + with (fold / "train.log").open("w") as fh: + subprocess.run(shlex.split(cmd), cwd=a.package, stdout=fh, stderr=subprocess.STDOUT, check=True) + split = a.data / "train" / held / "dev_split" + out = Path(tempfile.mkdtemp(prefix="predictions-", dir=fold)) # on the research disk, not /tmp + with (fold / "inference.log").open("w") as fh: + subprocess.run(["bash", str(a.package / "infer.sh"), str(split), str(out)], cwd=a.package, + stdout=fh, stderr=subprocess.STDOUT, check=True, + env={**os.environ, "SE600M_DIR": os.environ.get("SE600M_DIR", "/opt/se600m")}) + baseline_dir = split / "noeffect" if (split / "noeffect").exists() else None # shipped no-effect + real DE cache + report = score_context(out / "predictions.h5ad", split / "basal.h5ad", split / "responses.h5ad", + split / "requests.jsonl", fold / "score", threads=a.threads, baseline_dir=baseline_dir) + summary[held] = {"score": report["all"]["score"], "normalised": report["all"]["normalised"], + "raw": report["all"]["raw"], "seconds": round(time.time() - t0, 1)} + print(f"[loco] holdout {held}: score {report['all']['score']:.4f} {report['all']['normalised']}") + summary["mean_score"] = sum(v["score"] for v in summary.values()) / len(summary) + (a.outdir / "summary.json").write_text(json.dumps(summary, indent=2) + "\n") + print(json.dumps({k: (v["score"] if isinstance(v, dict) else v) for k, v in summary.items()}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/90/90355abe5b2f28e2e096ad923f63a193d3b7812ce5c6a7f6851cd450201c293f/test_data_manifest_contract.py b/reproduction/files/90/90355abe5b2f28e2e096ad923f63a193d3b7812ce5c6a7f6851cd450201c293f/test_data_manifest_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..639c43de152061895e535d5d1168490d5fbabc30 --- /dev/null +++ b/reproduction/files/90/90355abe5b2f28e2e096ad923f63a193d3b7812ce5c6a7f6851cd450201c293f/test_data_manifest_contract.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import json +from pathlib import Path +import sys + +import pytest + + +DATA_DIR = Path("/task/environment/data") +sys.path.insert(0, str(DATA_DIR)) +from validate_longitudinal_v2 import validate_manifest_contract # noqa: E402 + + +def write_contract(root: Path) -> None: + horizons = list(range(30, 361, 30)) + [365] + diseases = ["A00", "B00"] + (root / "public/validation").mkdir(parents=True) + (root / "public/test").mkdir(parents=True) + (root / "manifest.json").write_text(json.dumps({ + "schema": "natural-disease-progression/v2", + "protocol": "longitudinal-v2", + "horizons_days": horizons, + "scored_diseases": diseases, + "num_scored_diseases": len(diseases), + "primary_metric": "macro_time_averaged_auroc", + })) + for split in ("validation", "test"): + (root / f"public/{split}/manifest.json").write_text(json.dumps({ + "protocol": "longitudinal-v2", + "horizons_days": horizons, + "scored_diseases": diseases, + "split": split, + "primary_metric": "macro_time_averaged_auroc", + })) + + +def test_manifest_contract_accepts_active_protocol(tmp_path: Path) -> None: + write_contract(tmp_path) + _, diseases = validate_manifest_contract(tmp_path) + assert diseases == ["A00", "B00"] + + +@pytest.mark.parametrize("field,value", [ + ("protocol", "legacy"), + ("horizons_days", [365]), + ("primary_metric", "age_sex_normalized_disease_time_brier"), + ("scored_diseases", ["B00", "A00"]), +]) +def test_manifest_contract_rejects_stale_or_misaligned_split( + tmp_path: Path, field: str, value: object, +) -> None: + write_contract(tmp_path) + path = tmp_path / "public/validation/manifest.json" + manifest = json.loads(path.read_text()) + manifest[field] = value + path.write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match=field): + validate_manifest_contract(tmp_path) diff --git a/reproduction/files/93/9323fa7eaeb26194022798df420c13d099db7ea2381974fc510abd27bf02891c/evaluate.py b/reproduction/files/93/9323fa7eaeb26194022798df420c13d099db7ea2381974fc510abd27bf02891c/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..29372db9000aea9d396f2dec6bd53a58a44c393e --- /dev/null +++ b/reproduction/files/93/9323fa7eaeb26194022798df420c13d099db7ea2381974fc510abd27bf02891c/evaluate.py @@ -0,0 +1,269 @@ +"""Trusted release preflight, relocated replay, and known-task score aggregation.""" + +import argparse +import hashlib +import json +import math +import os +from pathlib import Path +import re +import shutil +import signal +import subprocess +import sys +import tempfile + +from protocol import InfrastructureError, PolicyError, numbers +from native_settings import validate_settings + +# The verifier image owns this sibling data specification; candidate code does +# not choose the benchmark membership or mutate its inclusion/exclusion list. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "data")) +from public_release import load_release, digest as data_release_hash, validate_suite_binding + + +SOURCE_REVISION = "cf5ef6748443ae72e9647f398487e98d421a7243" + + +def write_json(path, value): + # External readers can inspect progress without observing half-written JSON. + payload = json.dumps(value, indent=2, allow_nan=False) + "\n" + fd, temporary = tempfile.mkstemp(prefix=f'.{path.name}-', dir=path.parent) + try: + with os.fdopen(fd, 'w') as stream: + os.fchmod(stream.fileno(), 0o644) + stream.write(payload) + os.replace(temporary, path) + finally: + Path(temporary).unlink(missing_ok=True) + + +def suite_hash(suite): + return hashlib.sha256(json.dumps(suite, sort_keys=True, separators=(",", ":"), + allow_nan=False).encode()).hexdigest() + + +def validate_suite(suite, *, require_reference=True): + if suite.get("status") != "validated" or suite.get("coverage", {}).get("status") != "complete": + raise InfrastructureError("Evaluation release is not validated/full-coverage; do not run a formal agent session") + if not suite.get("release_id") or suite.get("source_revision") != SOURCE_REVISION: + raise InfrastructureError("Missing release identity or wrong upstream resource revision") + if not suite.get("cases"): + raise InfrastructureError("Empty evaluation suite") + timeout = suite.get("policy_timeout_sec", 120) + if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0: + raise InfrastructureError("Invalid policy timeout") + ids = set() + for case in suite["cases"]: + for field in ("id", "environment", "family"): + if not isinstance(case.get(field), str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", case[field]): + raise InfrastructureError(f"Unsafe/missing case {field}") + if case["id"] in ids: + raise InfrastructureError("Duplicate evaluation case") + ids.add(case["id"]) + if case.get("backend") != "maia": + raise InfrastructureError(f"Backend not integrated: {case.get('backend')}; never silently skip a case") + for key in ("horizon", "solver_processes", "observation_size", "action_size", "timeout_sec"): + if type(case.get(key)) is not int or case[key] <= 0: + raise InfrastructureError(f"Invalid {key} in {case['id']}") + validate_settings(case.get("native_settings", {}), case["horizon"], + case.get("episode_end", "native")) + seeds = case.get("seeds") + if not isinstance(seeds, list) or not seeds or any(type(s) is not int or s < 0 for s in seeds) or len(set(seeds)) != len(seeds): + raise InfrastructureError("Invalid evaluation seeds") + if not case.get("initialization") or not case.get("provenance"): + raise InfrastructureError("Missing initialization/protocol provenance") + kwargs = case.get("env_kwargs", {}) + allowed = {"probe_locations", "obs_normalization_strategy", "obs_loc", "obs_scale"} + if set(kwargs) - allowed or not kwargs.get("probe_locations") or not numbers(kwargs["probe_locations"]): + raise InfrastructureError("Missing reviewed sensors or unsafe environment overrides") + strategy = kwargs.get("obs_normalization_strategy", "none") + if strategy not in ("none", "U_inf", "customized"): + raise InfrastructureError("Evaluation normalization must be fixed, never fitted during replay") + if strategy == "customized": + for key in ("obs_loc", "obs_scale"): + if not numbers(kwargs.get(key)) or len(kwargs[key]) != case["observation_size"]: + raise InfrastructureError("Missing/invalid frozen normalization statistics") + if any(x <= 0 for x in kwargs["obs_scale"]): + raise InfrastructureError("Frozen normalization scale must be positive") + if not require_reference: + continue + baseline = case.get("baseline", {}) + anchor, reference = baseline.get("anchor_return"), baseline.get("reference_return") + if not isinstance(baseline.get("anchor_description"), str) or not baseline["anchor_description"].strip(): + raise InfrastructureError("Missing native uncontrolled/fixed-control anchor definition") + if any(type(x) not in (int, float) or not math.isfinite(x) for x in (anchor, reference)) or reference <= anchor: + raise InfrastructureError("Missing measured reference anchors or nonpositive normalization gap") + if baseline.get("algorithm") not in ("PPO", "DDPG", "TD3", "GPPO"): + raise InfrastructureError("Reference algorithm must be a reproduced native baseline") + + +def preflight(data, *, require_reference=True): + try: + suite = json.loads((data / "suite.json").read_text()) + release_path = data / "release.json" + # A missing manifest must not reopen legacy, arbitrary-subset grading. + release = load_release(release_path) + if release != load_release(): + raise InfrastructureError("Mounted data release differs from the verifier's frozen selection") + validate_suite_binding(release, suite) + validate_suite(suite, require_reference=require_reference) + receipt = json.loads((data / "materialized.json").read_text()) + if receipt.get("revision") != SOURCE_REVISION: + raise InfrastructureError("Resources have not been verified at the pinned revision") + if (receipt.get("data_release_id") != release["release_id"] or + receipt.get("data_release_sha256") != data_release_hash(release)): + raise InfrastructureError("Frozen release resources have not been materialized/verified") + verified = set(receipt.get("verified_directories", [])) + for case in suite["cases"]: + directory = data / "environments" / case["environment"] + if case["environment"] not in verified or not (directory / "environment_config.yaml").is_file(): + raise InfrastructureError(f"Unverified/missing resource: {case['environment']}") + return suite + except (OSError, ValueError, KeyError, TypeError) as error: + raise InfrastructureError(f"Incomplete evaluation release at {data}: {error}") from error + + +def package_hash(root): + root = root.resolve() + if not root.is_dir(): + raise PolicyError("No submission directory") + digest = hashlib.sha256() + for path in sorted(root.rglob("*")): + if not path.resolve().is_relative_to(root): + raise PolicyError("Submission contains an escaping symlink") + if path.is_dir(): + continue + if not path.is_file(): + raise PolicyError("Submission contains a missing link or special file") + digest.update(path.relative_to(root).as_posix().encode() + b"\0") + digest.update(str(path.stat().st_size).encode() + b"\0") + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + for required in ("infer.sh", "README.md"): + if not (root / required).is_file() or not (root / required).stat().st_size: + raise PolicyError(f"Missing submission {required}") + return digest.hexdigest() + + +def aggregate(suite, results, *, normalize=True): + expected = {case["id"] for case in suite["cases"]} + if set(results) != expected: + raise InfrastructureError("Incomplete/extra result coverage") + scores = [] + valid = 0 + for case in suite["cases"]: + result = results[case["id"]] + if result.get("status") == "policy_error": + if normalize: + result["score"] = 0.0 + scores.append(0.0) + else: + result["mean_return"] = None + continue + if result.get("status") != "ok": + raise InfrastructureError("A solver/setup error is not a model score") + episodes = result.get("episodes", []) + if [e.get("seed") for e in episodes] != case["seeds"]: + raise InfrastructureError("Wrong/missing evaluation episodes") + values = [e["return"] for e in episodes] + if any(type(x) not in (int, float) or not math.isfinite(x) for x in values): + raise InfrastructureError("Nonfinite/missing native return") + mean = sum(values) / len(values) + if not math.isfinite(mean): + raise InfrastructureError("Nonfinite mean return") + result["mean_return"] = mean + valid += 1 + if not normalize: + continue + anchors = case["baseline"] + gain = (mean - anchors["anchor_return"]) / (anchors["reference_return"] - anchors["anchor_return"]) + if not math.isfinite(gain): + raise InfrastructureError("Nonfinite normalized return") + result.update(mean_return=mean, normalized_gain=gain, score=max(0.0, gain)) + scores.append(result["score"]) + if not normalize: + return {"case_coverage": valid / len(suite["cases"])} + return {"score": sum(scores) / len(scores), "case_coverage": valid / len(scores)} + + +def run_case(case, suite, data, package, output): + command = [sys.executable, str(Path(__file__).with_name("run_maia.py")), "evaluate", + "--data", str(data), "--case", case["id"], "--submission", str(package), + "--output", str(output)] + with output.with_suffix(".log").open("wb") as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + try: + code = process.wait(timeout=case["timeout_sec"]) + except subprocess.TimeoutExpired as error: + raise InfrastructureError(f"CFD case timeout: {case['id']}") from error + finally: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + if code or not output.is_file(): + raise InfrastructureError(f"CFD case execution failed: {case['id']}; see {output.with_suffix('.log')}") + return json.loads(output.read_text()) + + +def evaluate(data, submission, output, runner=run_case, *, raw_only=False): + output.mkdir(parents=True, exist_ok=True) + if any(output.iterdir()): + raise InfrastructureError("Evaluation output directory must be empty") + try: + suite = preflight(data, require_reference=not raw_only) + release_digest = suite_hash(suite) + identity = {"release_id": suite["release_id"], "source_revision": SOURCE_REVISION, + "suite_sha256": release_digest, + "evaluation_mode": "native-returns" if raw_only else "normalized-score"} + try: + digest = package_hash(submission) + except PolicyError as error: + write_json(output / "results.json", dict(identity, status="policy_error", error=str(error), + case_coverage=0.0, cases={case["id"]: {"status": "policy_error", "error": str(error)} + for case in suite["cases"]})) + if not raw_only: + write_json(output / "reward.json", {"score": 0.0, "case_coverage": 0.0}) + return + with tempfile.TemporaryDirectory(prefix="hydrogym-replay-") as temporary: + package = Path(temporary) / "submission" + shutil.copytree(submission, package, symlinks=True) + if package_hash(package) != digest or package_hash(submission) != digest: + raise InfrastructureError("Submission changed while snapshotting; retry a stable version") + results = {} + for case in suite["cases"]: + results[case["id"]] = runner(case, suite, data, package, output / f"{case['id']}.json") + if package_hash(package) != digest: + raise InfrastructureError("Model package mutated during replay") + if suite_hash(preflight(data, require_reference=not raw_only)) != release_digest: + raise InfrastructureError("Evaluation release changed during replay") + rewards = aggregate(suite, results, normalize=not raw_only) + write_json(output / "results.json", dict(identity, submission_sha256=digest, + status="ok", case_coverage=rewards["case_coverage"], cases=results)) + if not raw_only: + write_json(output / "reward.json", rewards) + except Exception as error: + write_json(output / "error.json", {"status": "infrastructure_error", "error": str(error)}) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--data", type=Path, default=Path("/data")) + parser.add_argument("--submission", type=Path, default=Path("/workspace/submission")) + parser.add_argument("--output", type=Path, default=Path("/logs/verifier")) + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--raw-only", action="store_true", + help="Evaluate every declared case without reference anchors; no aggregate reward file") + args = parser.parse_args() + if args.preflight: + print(json.dumps(preflight(args.data.resolve(), require_reference=not args.raw_only), indent=2)) + else: + evaluate(args.data.resolve(), args.submission.resolve(), args.output.resolve(), raw_only=args.raw_only) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/94/94b7974c6ebfa301107b3d3ff99943c6b0092c08ba919ffe35d652b78c3a566f/test.sh b/reproduction/files/94/94b7974c6ebfa301107b3d3ff99943c6b0092c08ba919ffe35d652b78c3a566f/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..508639d28d80f3c8d12d9ad05acc915dd2008fc7 --- /dev/null +++ b/reproduction/files/94/94b7974c6ebfa301107b3d3ff99943c6b0092c08ba919ffe35d652b78c3a566f/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +test ! -e /logs/verifier/reward.json +export HYDROGYM_POLICY_ISOLATION=1 +bash /opt/hydrogym-task/evaluation/native_runtime.sh maia python \ + /opt/hydrogym-task/evaluation/harbor_verify.py \ + --data /data --submission /workspace/submission --output /logs/verifier/replay +cp /logs/verifier/replay/reward.json /logs/verifier/reward.json diff --git a/reproduction/files/96/9605e12b3d2b1e65d3efcba981f10cbd03fbf21feef75b6ec3b820af9f95726b/offline_network.py b/reproduction/files/96/9605e12b3d2b1e65d3efcba981f10cbd03fbf21feef75b6ec3b820af9f95726b/offline_network.py new file mode 100644 index 0000000000000000000000000000000000000000..893851e6caf304722df84d00f44fc94553c814d8 --- /dev/null +++ b/reproduction/files/96/9605e12b3d2b1e65d3efcba981f10cbd03fbf21feef75b6ec3b820af9f95726b/offline_network.py @@ -0,0 +1,111 @@ +"""A shared loopback-only network namespace for distributed research tools. + +The root supervisor creates a child user/network namespace with identity UID/GID +maps. A narrowly scoped setuid helper enters only that namespace, then drops all +privileges before executing the sandbox helper. Codex API traffic stays outside. +""" +import ctypes +import fcntl +import json +import os +from pathlib import Path +import select +import signal +import socket +import struct +import sys +import time + +CLONE_NEWUSER = 0x10000000 +CLONE_NEWNET = 0x40000000 + + +def configure(state): + state = Path(state) + for name in ("offline-net.pid", "network-access.json"): + previous = state / name + if previous.exists() or previous.is_symlink(): + info = previous.lstat() + if previous.is_symlink() or info.st_uid != 0: + raise RuntimeError("Untrusted previous network namespace policy") + previous.unlink() + ready_r, ready_w = os.pipe() + go_r, go_w = os.pipe() + pid = os.fork() + if pid == 0: + os.close(ready_r) + os.close(go_w) + try: + libc = ctypes.CDLL(None, use_errno=True) + if libc.unshare(CLONE_NEWUSER | CLONE_NEWNET): + raise OSError(ctypes.get_errno(), "unshare user/network namespace") + # Nested container runtimes can bind an ancestor's procfs. Use the + # PID visible through that procfs for namespace handles and maps. + proc_pid = int(os.readlink("/proc/self")) + os.write(ready_w, f"U{proc_pid}\n".encode()) + if os.read(go_r, 1) != b"M": + raise RuntimeError("Namespace maps were not installed") + os.close(go_r) + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + request = struct.pack("16sH22s", b"lo", 0, b"") + current = fcntl.ioctl(sock, 0x8913, request) + flags = struct.unpack_from("H", current, 16)[0] + fcntl.ioctl(sock, 0x8914, struct.pack("16sH22s", b"lo", flags | 1, b"")) + assert socket.if_nameindex() == [(1, "lo")] + record = {"pid": proc_pid, "net_inode": os.stat("/proc/self/ns/net").st_ino, + "user_inode": os.stat("/proc/self/ns/user").st_ino, + "interfaces": ["lo"], "mechanism": "identity-mapped-user-network-namespace"} + path = state / "offline-net.pid" + path.write_text(str(proc_pid) + "\n") + path.chmod(0o444) + path = state / "network-access.json" + path.write_text(json.dumps(record, indent=2) + "\n") + path.chmod(0o644) + os.write(ready_w, b"R") + os.close(ready_w) + # The job container owns this keeper's lifetime. Supervisor/tool UIDs + # cannot accidentally include it in the research process shutdown. + while True: + signal.pause() + except BaseException: + import traceback + traceback.print_exc() + os._exit(1) + os.close(ready_w) + os.close(go_r) + try: + if not select.select([ready_r], [], [], 10)[0]: + raise RuntimeError("Could not create the offline user/network namespace") + message = os.read(ready_r, 64).decode() + if not message.startswith("U") or not message[1:].strip().isdigit(): + raise RuntimeError("Invalid offline namespace initialization") + proc_pid = int(message[1:].strip()) + Path(f"/proc/{proc_pid}/uid_map").write_text("0 0 65536\n") + Path(f"/proc/{proc_pid}/gid_map").write_text("0 0 65536\n") + os.write(go_w, b"M") + if not select.select([ready_r], [], [], 10)[0] or os.read(ready_r, 1) != b"R": + raise RuntimeError("Could not initialize the offline network namespace") + return json.loads((state / "network-access.json").read_text()) + except BaseException: + os.kill(pid, signal.SIGKILL) + os.waitpid(pid, 0) + raise + finally: + os.close(ready_r) + os.close(go_w) + + +def enter_if_needed(state, helper): + path = Path(state) / "network-access.json" + info = path.stat() + if info.st_uid != 0 or info.st_mode & 0o022: + raise RuntimeError("Untrusted network namespace policy") + record = json.loads(path.read_text()) + if os.stat("/proc/self/ns/net").st_ino != record["net_inode"]: + os.execv("/opt/speedrun/enter-offline", [ + "/opt/speedrun/enter-offline", sys.executable, "-I", str(helper), *sys.argv[1:]]) + if os.getuid() != 1000 or os.geteuid() != 1000: + raise RuntimeError("Research networking requires an unprivileged UID") + if socket.if_nameindex() != [(1, "lo")]: + raise RuntimeError("Offline namespace contains a non-loopback interface") + return record diff --git a/reproduction/files/96/96b688a84f60c1c7790f2f42e321645faa80979c86d261fdbe12c028e3157462/test_task.py b/reproduction/files/96/96b688a84f60c1c7790f2f42e321645faa80979c86d261fdbe12c028e3157462/test_task.py new file mode 100644 index 0000000000000000000000000000000000000000..13edc3fef4ac5a30b6308cb74828293ef36e137b --- /dev/null +++ b/reproduction/files/96/96b688a84f60c1c7790f2f42e321645faa80979c86d261fdbe12c028e3157462/test_task.py @@ -0,0 +1,139 @@ +"""Synthetic unit tests for the trusted metric and grading code.""" +import importlib.util +import json +import math +import sys +import tempfile +import unittest +from pathlib import Path + +import grader +import metrics + +DATA_SCRIPTS = Path(__file__).resolve().parents[1] / "environment" / "data" + + +def load_data_script(name): + spec = importlib.util.spec_from_file_location(name, DATA_SCRIPTS / f"{name}.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class PretrainSourcePinTests(unittest.TestCase): + def test_drifted_uniref50_fails_closed_unless_allowed(self): + builder = load_data_script("build_pretrain_subset") + with tempfile.TemporaryDirectory() as tmp: + source = Path(tmp) / "uniref50.fasta.gz" + source.write_bytes(b"not the pinned release") + with self.assertRaises(SystemExit) as raised: + builder.verify_pinned_source(source) + self.assertIn(builder.PINNED_RELEASE, str(raised.exception)) + self.assertIn("--allow-drift", str(raised.exception)) + drifted = builder.verify_pinned_source(source, allow_drift=True) + self.assertFalse(drifted["matches_pin"]) + self.assertEqual(drifted["size"], source.stat().st_size) + self.assertEqual(len(drifted["sha256"]), 64) + self.assertEqual(len(builder.PINNED_SHA256), 64) + self.assertGreater(builder.PINNED_SIZE, 8_000_000_000) + + +class MetricTests(unittest.TestCase): + def test_classification_perfect_and_uniform(self): + truth = {f"e{i}": i % 2 for i in range(10)} + perfect = {k: {"scores": [1.0 if c == v else 0.0 for c in range(2)]} for k, v in truth.items()} + result = metrics.score_task("solubility", truth, perfect) + self.assertEqual(result["reward"], 1.0) + uniform = {k: {"scores": [1, 1]} for k in truth} + result = metrics.score_task("solubility", truth, uniform) + self.assertLessEqual(result["reward"], 0.6) + + def test_spearman_reward_clamps_at_zero(self): + truth = {f"e{i}": float(i) for i in range(20)} + forward = {k: {"value": v * 2 + 1} for k, v in truth.items()} + self.assertAlmostEqual(metrics.score_task("fluorescence", truth, forward)["reward"], 1.0) + reverse = {k: {"value": -v} for k, v in truth.items()} + self.assertEqual(metrics.score_task("fluorescence", truth, reverse)["reward"], 0.0) + + def test_ppi_affinity_rmse_reward(self): + truth = {f"e{i}": float(i) for i in range(5)} + exact = {k: {"value": v} for k, v in truth.items()} + result = metrics.score_task("ppi_affinity", truth, exact, ppi_affinity_std=2.0) + self.assertAlmostEqual(result["reward"], 1.0) + off = {k: {"value": v + 2.0} for k, v in truth.items()} + result = metrics.score_task("ppi_affinity", truth, off, ppi_affinity_std=2.0) + self.assertAlmostEqual(result["reward"], math.exp(-1.0)) + + def test_ssp_masked_accuracy(self): + truth = {"a": {"ss3": [0, 1, 2, 1], "valid_mask": [1, 1, 0, 1]}} + prediction = {"a": {"ss3_scores": [[9, 0, 0], [0, 9, 0], [9, 0, 0], [9, 0, 0]]}} + result = metrics.score_task("secondary_structure", truth, prediction) + self.assertEqual(result["valid_residues"], 3) + self.assertAlmostEqual(result["accuracy"], 2 / 3) + + def test_malformed_predictions_raise(self): + truth = {"a": 0, "b": 1} + with self.assertRaises(ValueError): # missing prediction + metrics.score_task("solubility", truth, {"a": {"scores": [1, 0]}}) + with self.assertRaises(ValueError): # wrong score length + metrics.score_task("solubility", truth, {k: {"scores": [1, 0, 0]} for k in truth}) + with self.assertRaises(ValueError): # negative scores + metrics.score_task("solubility", truth, {k: {"scores": [-1, 2]} for k in truth}) + with self.assertRaises(ValueError): # non-finite regression + metrics.score_task("fluorescence", {"a": 1.0, "b": 2.0}, + {"a": {"value": float("nan")}, "b": {"value": 0.0}}) + with self.assertRaises(ValueError): # ss3 length mismatch + metrics.score_task("secondary_structure", + {"a": {"ss3": [0, 1], "valid_mask": [1, 1]}}, + {"a": {"ss3_scores": [[1, 0, 0]]}}) + + +class GraderTests(unittest.TestCase): + def write_jsonl(self, path, rows): + path.write_text("".join(json.dumps(r, separators=(",", ":")) + "\n" for r in rows)) + + def test_grade_task_zeroes_only_bad_task(self): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + self.write_jsonl(tmp / "labels.jsonl", + [{"example_id": "a", "label": 0}, {"example_id": "b", "label": 1}]) + self.write_jsonl(tmp / "good.jsonl", + [{"example_id": "a", "prediction": {"scores": [1, 0]}}, + {"example_id": "b", "prediction": {"scores": [0, 1]}}]) + good = grader.grade_task("solubility", tmp / "good.jsonl", tmp / "labels.jsonl", 1.0) + self.assertEqual(good["reward"], 1.0) + self.assertIsNone(good["invalid_reason"]) + # duplicate id fails loudly + self.write_jsonl(tmp / "dup.jsonl", + [{"example_id": "a", "prediction": {"scores": [1, 0]}}, + {"example_id": "a", "prediction": {"scores": [1, 0]}}]) + bad = grader.grade_task("solubility", tmp / "dup.jsonl", tmp / "labels.jsonl", 1.0) + self.assertEqual(bad["reward"], 0.0) + self.assertIsNotNone(bad["invalid_reason"]) + # unknown id fails loudly + self.write_jsonl(tmp / "unknown.jsonl", + [{"example_id": "z", "prediction": {"scores": [1, 0]}}]) + bad = grader.grade_task("solubility", tmp / "unknown.jsonl", tmp / "labels.jsonl", 1.0) + self.assertEqual(bad["reward"], 0.0) + # missing file fails loudly + bad = grader.grade_task("solubility", tmp / "absent.jsonl", tmp / "labels.jsonl", 1.0) + self.assertEqual(bad["reward"], 0.0) + + def test_flatten_metrics(self): + flat = {} + metrics.flatten_metrics("solubility", {"accuracy": 0.5, "invalid_reason": None, + "nested": {"x": 1.0}}, flat) + self.assertEqual(flat, {"solubility_accuracy": 0.5, "solubility_nested_x": 1.0}) + + def test_metrics_copies_match(self): + """Development self-scoring must use the same code as the grader.""" + here = Path(__file__).resolve().parent + sibling = here.parent / "environment" / "evaluation" / "metrics.py" + if not sibling.is_file(): + self.skipTest("running inside the verifier image; sibling copy absent") + self.assertEqual((here / "metrics.py").read_bytes(), sibling.read_bytes(), + "tests/metrics.py and environment/evaluation/metrics.py have diverged") + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/97/97feb1dc05df1dec4ab5fb0df922daee5f029e629b28643461803741ad014007/test_materialize.py b/reproduction/files/97/97feb1dc05df1dec4ab5fb0df922daee5f029e629b28643461803741ad014007/test_materialize.py new file mode 100644 index 0000000000000000000000000000000000000000..fb2163785837d50e3313ce8a61ae5bf0d6be9cf0 --- /dev/null +++ b/reproduction/files/97/97feb1dc05df1dec4ab5fb0df922daee5f029e629b28643461803741ad014007/test_materialize.py @@ -0,0 +1,127 @@ +import gzip +import hashlib +import json +from pathlib import Path +import shutil +import sys + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/data")) +import materialize as m + + +def item(source, content, **extra): + return dict( + bytes=source.stat().st_size, + sha256=m.sha256(source), + unpacked_bytes=len(content), + unpacked_sha256=hashlib.sha256(content).hexdigest(), + encoding="gzip", + **extra, + ) + + +def test_verified_unpack_is_repeatable_and_rejects_corruption(tmp_path): + content = b'{"frame":1}\n' + source = tmp_path / "data.gz" + source.write_bytes(gzip.compress(content)) + metadata = item(source, content) + destination = tmp_path / "out/data.jsonl" + m.unpack(source, destination, metadata) + m.unpack(source, destination, metadata) + assert destination.read_bytes() == content + destination.write_bytes(b"corrupt") + with pytest.raises(ValueError, match="checksum"): + m.unpack(source, destination, metadata) + destination.unlink() + source.write_bytes(source.read_bytes() + b"corrupt") + with pytest.raises(ValueError, match="checksum"): + m.unpack(source, destination, metadata) + assert not destination.exists() + + +def test_unpack_enforces_expansion_limit_without_partial_output(tmp_path): + source = tmp_path / "data.gz" + source.write_bytes(gzip.compress(b"x" * 100)) + metadata = item(source, b"x" * 100) + metadata["unpacked_bytes"] = 10 + destination = tmp_path / "out/data" + with pytest.raises(ValueError, match="declared size"): + m.unpack(source, destination, metadata) + assert list(destination.parent.iterdir()) == [] + + +def test_destinations_cannot_escape_through_traversal_or_symlinks(tmp_path): + root = tmp_path / "root" + root.mkdir() + (root / "escape").symlink_to(tmp_path, target_is_directory=True) + for name in ("../secret", "/absolute", "escape/secret"): + with pytest.raises(ValueError, match="path|Path"): + m.within(root, name) + + +def test_materialization_fetches_only_explicit_components(tmp_path, monkeypatch): + remote = tmp_path / "remote" + remote.mkdir() + files = [] + for group in m.GROUPS: + content = (group + "\n").encode() + source = remote / f"{group}.gz" + source.write_bytes(gzip.compress(content)) + files.append( + item( + source, + content, + path=source.name, + destination=f"{group}/data", + group=group, + ) + ) + manifest = remote / "manifest.json" + manifest.write_text(json.dumps({"files": files, "required_groups": ["licenses"]})) + pin = tmp_path / "release.json" + pin.write_text( + json.dumps( + dict( + repo_id="owner/data", + revision="a" * 40, + manifest_sha256=m.sha256(manifest), + ) + ) + ) + monkeypatch.setattr(m, "PIN", pin) + calls = [] + + def fetch(url, target, expected_sha, expected_bytes=None, token=None): + name = url.rsplit("/", 1)[1] + calls.append(name) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(remote / name, target) + m.checked(target, expected_bytes or target.stat().st_size, expected_sha) + return target + + monkeypatch.setattr(m, "fetch", fetch) + root = tmp_path / "data" + m.materialize(root, ["training", "protocol"]) + assert set(calls) == { + "manifest.json", "training.gz", "protocol.gz", "licenses.gz" + } + assert not (root / "records").exists() + assert not (root / "eval-test").exists() + assert not (root / "trained-models").exists() + m.materialize(root, ["records"]) + assert (root / "records/data").read_text() == "records\n" + m.materialize(root, ["initial-model", "eval-val"]) + assert (root / "initial-model/data").read_text() == "initial-model\n" + assert (root / "eval-val/data").read_text() == "eval-val\n" + assert not (root / "eval-test").exists() + m.materialize(root, ["eval-test"]) + assert (root / "eval-test/data").read_text() == "eval-test\n" + + manifest.write_text(json.dumps({"files": files, "required_groups": ["eval-test"]})) + pin_data = json.loads(pin.read_text()) + pin_data["manifest_sha256"] = m.sha256(manifest) + pin.write_text(json.dumps(pin_data)) + with pytest.raises(ValueError, match="implicit components"): + m.materialize(tmp_path / "fresh", ["training"]) diff --git a/reproduction/files/99/99691f9b32a2054ff83b0d65529d5b74d2e1e3b238a0ab72e8d5d38801a69a02/main_verifier.py b/reproduction/files/99/99691f9b32a2054ff83b0d65529d5b74d2e1e3b238a0ab72e8d5d38801a69a02/main_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..f36eff0d241d516871a87125f50f79b9566d6e3c --- /dev/null +++ b/reproduction/files/99/99691f9b32a2054ff83b0d65529d5b74d2e1e3b238a0ab72e8d5d38801a69a02/main_verifier.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Run the untrusted submission offline and seal only bounded design output. + +The submission generates backbones; it never sees the scoring pipeline. Sealing copies +the design index and the referenced structures into a read-only, hash-manifested +snapshot that the trusted grader consumes. +""" + +import argparse +import json +import os +from pathlib import Path +import pwd +import shutil +import signal +import stat +import subprocess +import time + +from common import (SNAPSHOT_SCHEMA, TRACKS, sha256, validate_harness, + validate_input, write_json) + +MAX_OUTPUT_BYTES = 2 * 1024 * 1024 * 1024 +MAX_STRUCTURES = 100_000 + + + +def invalid_submission(output, sealed, error): + """An invalid package, a failed inference or a timeout scores 0 (TASK_STANDARD.md); Harbor needs reward.json.""" + reason = f"{type(error).__name__}: {error}" + output.mkdir(parents=True, exist_ok=True) + (output / "report.json").write_text(json.dumps( + {"status": "invalid_submission", "error": reason[:4000], "reward": 0.0}, indent=2) + "\n") + (output / "reward.json").write_text(json.dumps({"reward": 0.0, "invalid_submission": 1.0}, indent=2) + "\n") + sealed.parent.mkdir(parents=True, exist_ok=True) + (sealed.parent / "INVALID").write_text(reason + "\n") + print(f"invalid submission: {reason}") + +def validate_submission(root): + root = root.resolve() + for required in ("infer.sh", "README.md", "harness.json"): + if not (root / required).is_file() or (root / required).is_symlink(): + raise FileNotFoundError(f"submission/{required} is required") + for path in root.rglob("*"): + if path.is_symlink() and not path.resolve().is_relative_to(root): + raise ValueError(f"submission symlink escapes package: {path.relative_to(root)}") + + +def check_grading_instruments(root, manifest): + """Record when a submission declares the models that grade it. + + Pretrained predictors are permitted - a `predictor_inversion` system is nothing but + a pretrained predictor - so this records rather than rejects. It matters because a + system optimising against the very models that score it inflates in-silico + designability, and a reviewer should see it. + + This is declaration-based. It matters MORE now than when AlphaFold 3 was the + predictor: AF3's parameters could not be redistributed, so the scorer was never in + the agent's image and inverting it needed the agent to bring its own copy. RF3's + parameters DO ship, so the scoring predictor is sitting in the image the agent runs + in, and optimising directly against it is correspondingly easier. The declaration + is still the only signal - this does not scan bytes. + """ + from pipeline import RF3_REVISION, LIGANDMPNN_COMMIT # noqa: F401 + instruments = ("ligandmpnn", "ligand_mpnn", "proteinmpnn", "protein_mpnn", + "rosettafold3", "rosettafold-3", "rf3", "foundry", + "alphafold3", "alphafold-3", "af3") + found = [] + for asset in manifest.get("pretrained_assets", []): + haystack = f"{asset.get('asset_id', '')} {asset.get('role', '')}".lower() + for name in instruments: + if name in haystack: + found.append({"asset": name, "declared_as": asset.get("asset_id")}) + break + return found + + +def kill_agent_processes(uid): + proc = Path("/proc") + if not proc.is_dir(): + return + for entry in proc.iterdir(): + if not entry.name.isdigit() or int(entry.name) == os.getpid(): + continue + try: + status = (entry / "status").read_text() + process_uid = int(next(line for line in status.splitlines() + if line.startswith("Uid:")).split()[1]) + if process_uid == uid: + os.kill(int(entry.name), signal.SIGKILL) + except (FileNotFoundError, ProcessLookupError, PermissionError, StopIteration): + pass + + +def run_submission(submission, input_root, work, timeout): + agent = pwd.getpwnam("agent") + output = work / "untrusted-output" + output.mkdir() + os.chown(output, agent.pw_uid, agent.pw_gid) + env = { + "PATH": "/opt/conda/bin:/usr/local/bin:/usr/bin:/bin", + "HOME": agent.pw_dir, "PYTHONUNBUFFERED": "1", "PIP_NO_INDEX": "1", + "HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1", + "CUDA_VISIBLE_DEVICES": os.environ.get("CUDA_VISIBLE_DEVICES", "0"), + } + + def demote(): + os.setgid(agent.pw_gid) + os.setuid(agent.pw_uid) + + process = None + try: + with (work / "inference.log").open("wb") as log: + process = subprocess.Popen( + ["bash", str(submission / "infer.sh"), str(input_root), str(output)], + cwd=submission, env=env, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, preexec_fn=demote, + ) + code = process.wait(timeout=timeout) + if code: + raise subprocess.CalledProcessError(code, process.args) + except subprocess.TimeoutExpired: + if process: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=5) + raise + finally: + if process: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if process.poll() is None: + process.wait(timeout=5) + kill_agent_processes(agent.pw_uid) + return output + + +def validate_output_tree(root): + total, count = 0, 0 + for directory, names, files in os.walk(root, followlinks=False): + for name in names + files: + info = (Path(directory) / name).lstat() + if stat.S_ISLNK(info.st_mode) or not (stat.S_ISDIR(info.st_mode) + or stat.S_ISREG(info.st_mode)): + raise ValueError("design output contains a symlink or special file") + if stat.S_ISREG(info.st_mode): + total += info.st_size + count += 1 + if total > MAX_OUTPUT_BYTES: + raise ValueError("design output exceeds 2 GiB") + if count > MAX_STRUCTURES + len(TRACKS): + raise ValueError("design output contains too many files") + + +def seal_designs(untrusted, sealed, input_manifest): + if sealed.exists(): + raise FileExistsError("sealed destination already exists") + validate_output_tree(untrusted) + predictions = untrusted / "predictions" + temporary = sealed.with_name(sealed.name + f".tmp-{os.getpid()}") + (temporary / "structures").mkdir(parents=True) + hashes, structures = {}, 0 + + for track in TRACKS: + source = predictions / f"{track}.jsonl" + if not source.is_file() or source.is_symlink(): + continue + if not source.resolve().is_relative_to(untrusted.resolve()): + raise ValueError("design index escapes the output root") + destination = temporary / f"{track}.jsonl" + shutil.copyfile(source, destination, follow_symlinks=False) + hashes[destination.name] = sha256(destination) + destination.chmod(0o444) + + source_structures = predictions / "structures" + if source_structures.is_dir() and not source_structures.is_symlink(): + for path in sorted(source_structures.rglob("*")): + if path.is_symlink() or not path.is_file(): + continue + if not path.resolve().is_relative_to(source_structures.resolve()): + raise ValueError("structure path escapes the output root") + relative = path.relative_to(source_structures) + target = temporary / "structures" / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, target, follow_symlinks=False) + target.chmod(0o444) + structures += 1 + + snapshot = {"schema": SNAPSHOT_SCHEMA, "input_manifest_sha256": sha256(input_manifest), + "files": hashes, "structures": structures} + write_json(temporary / "snapshot.json", snapshot) + (temporary / "snapshot.json").chmod(0o444) + os.replace(temporary, sealed) + (sealed.parent / "READY").write_text(sha256(sealed / "snapshot.json") + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--submission", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--input", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--pretrained", default="/pretrained", type=lambda x: Path(x).resolve()) + parser.add_argument("--sealed", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--output", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--timeout", type=int, default=43200) + # How long to wait for the trusted grader AFTER inference. Must match the grader's + # own patience (`grader.py --wait-seconds`) or a correct run is killed for being slow. + # The evaluation view is 51 targets x 20 designs = 1,020, and grading folds ~8,600 + # structures (the 100-design view took 9 h 33 min on 8x L40S). Together with --timeout this must stay + # within `task.toml [verifier] timeout_sec`. This was hard-coded to 3600 and aborted + # every honest full-path run at the one-hour mark with "trusted grader did not publish + # reward.json". + parser.add_argument("--grader-timeout", type=int, default=129600) + parser.add_argument("--no-wait", action="store_true") + arguments = parser.parse_args() + + arguments.output.mkdir(parents=True, exist_ok=True) + os.chmod(arguments.output, 0o777) + arguments.sealed.parent.mkdir(parents=True, exist_ok=True) + validate_input(arguments.input) + try: + validate_submission(arguments.submission) + manifest = validate_harness(arguments.submission, arguments.pretrained) + instruments = check_grading_instruments(arguments.submission, manifest) + work = arguments.output / "main" + work.mkdir() + write_json(arguments.output / "harness.json", { + "kind": manifest["kind"], + "declared_parameters": manifest["declared_parameters"], + "trained_in_session": [c["path"] for c in manifest["learned_components"] + if c["trained_in_session"]], + "pretrained_assets": [a["asset_id"] for a in manifest["pretrained_assets"]], + "grading_instruments_present": instruments, + }) + untrusted = run_submission(arguments.submission, arguments.input, work, arguments.timeout) + seal_designs(untrusted, arguments.sealed, arguments.input / "manifest.json") + except (FileNotFoundError, ValueError, subprocess.SubprocessError) as error: + invalid_submission(arguments.output, arguments.sealed, error) + return + + if not arguments.no_wait: + results = arguments.sealed.parent / "results" + deadline = time.monotonic() + arguments.grader_timeout + while not (results / "reward.json").is_file(): + if time.monotonic() >= deadline: + raise TimeoutError( + f"trusted grader did not publish reward.json within " + f"{arguments.grader_timeout}s") + time.sleep(1) + for name in ("report.json", "reward.json"): + shutil.copyfile(results / name, arguments.output / name) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/99/99cb7f28b327aaa41c67dcb7efb8266c555cbaa37196e8374c264e0507e47a8a/docker-compose.cpu-smoke.yaml b/reproduction/files/99/99cb7f28b327aaa41c67dcb7efb8266c555cbaa37196e8374c264e0507e47a8a/docker-compose.cpu-smoke.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6f73513e36d1edf2ab558012580fc27d41ba9d32 --- /dev/null +++ b/reproduction/files/99/99cb7f28b327aaa41c67dcb7efb8266c555cbaa37196e8374c264e0507e47a8a/docker-compose.cpu-smoke.yaml @@ -0,0 +1,8 @@ +# Synthetic CI plumbing only; production inference keeps its one-GPU request. +# !reset is a Docker Compose merge tag, not ordinary YAML. +services: + main: + deploy: + resources: + reservations: + devices: !reset [] diff --git a/reproduction/files/9b/9b491db7cd0975394dbc360b1941a90b1aa69be25a672fc954d46808cbc97efb/test_training.py b/reproduction/files/9b/9b491db7cd0975394dbc360b1941a90b1aa69be25a672fc954d46808cbc97efb/test_training.py new file mode 100644 index 0000000000000000000000000000000000000000..db75563ba691177d2fdd5bfacb7450e33fc84a47 --- /dev/null +++ b/reproduction/files/9b/9b491db7cd0975394dbc360b1941a90b1aa69be25a672fc954d46808cbc97efb/test_training.py @@ -0,0 +1,169 @@ +"""Small CPU exercises for fixed-data training, resume, and split isolation.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pytest +import stim +import tensorflow as tf + +from baselines.cache import prepare +from baselines.data import group_conditions +from baselines.train import ( + PackedSequence, + _load_allowed_hardware, + argument_parser, + checkpoint_state, + evaluate_validation, + load_populations, + run_training, + sha256, +) + + +def small_data(tmp_path: Path) -> tuple[Path, Path, str]: + root = tmp_path / "data" + root.mkdir() + for rounds in range(1, 26, 2): + condition = root / f"surface_code_bZ_d3_r{rounds:02d}_center_3_3" + condition.mkdir() + circuit = stim.Circuit.generated( + "surface_code:rotated_memory_z", distance=3, rounds=rounds, + after_clifford_depolarization=0.01, + before_measure_flip_probability=0.01, + after_reset_flip_probability=0.01, + ) + circuit.to_file(condition / "circuit_noisy.stim") + circuit.without_noise().to_file(condition / "circuit_ideal.stim") + group = "d3_bZ_center_3_3" + cache = prepare(root, tmp_path / "cache", group, seed=13, shots=312, validation_shots=8) + return root, cache, group + + +def test_sequence_covers_population_and_resumes_exact_cursor(tmp_path: Path) -> None: + root, cache, group = small_data(tmp_path) + training, _, _ = load_populations(root, cache, group, "pretrain") + sequence = PackedSequence(training, batch_size=8, seed=71, epoch=2) + resumed = PackedSequence(training, batch_size=8, seed=71, epoch=2, start_batch=2) + assert sum(sequence.batch_samples(i) for i in range(len(sequence))) == 312 + seen: dict[int, list[int]] = {index: [] for index in range(13)} + for group_index, start, end in sequence.batches: + seen[group_index].extend(sequence.shot_orders[group_index][start:end].tolist()) + assert all(sorted(indices) == list(range(24)) for indices in seen.values()) + for index in range(len(resumed)): + expected_inputs, expected_labels = sequence[index + 2] + inputs, labels = resumed[index] + for name in inputs: + np.testing.assert_array_equal(inputs[name], expected_inputs[name]) + for name in labels: + np.testing.assert_array_equal(labels[name], expected_labels[name]) + np.testing.assert_array_equal(labels["main_output"], labels["aux_output"]) + + +def test_fixed_cache_training_checkpoint_and_resume(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + root, cache, group = small_data(tmp_path) + output = tmp_path / "run" + args = argument_parser().parse_args([ + "--data-root", str(root), "--cache-dir", str(cache), "--group", group, + "--output", str(output), "--hours", "1", "--epochs", "3", + "--max-steps", "3", "--batch-size", "8", "--eval-seconds", "0.01", + "--workers", "1", "--allow-cpu", + ]) + tf.keras.backend.clear_session() + result = run_training(args) + assert result["stop_reason"] == "max_steps" + assert result["global_steps"] == result["optimizer_iterations"] == 3 + assert result["seen_samples"] == 24 + assert result["next_batch"] == 3 + assert checkpoint_state(output / "last.keras")["global_steps"] == 3 + assert (output / "best.keras").is_file() + history = [json.loads(line) for line in (output / "history.jsonl").read_text().splitlines()] + assert any(row["trigger"] == "interval" and row["global_steps"] < 3 for row in history) + assert all(row["complete"] and np.isfinite(row["loss"]) for row in history) + + args.max_steps = 5 + resumed = run_training(args) + assert resumed["global_steps"] == resumed["optimizer_iterations"] == 5 + assert resumed["seen_samples"] == 40 + assert resumed["next_batch"] == 5 + assert resumed["elapsed_seconds"] > result["elapsed_seconds"] + metadata = json.loads((output / "metadata.json").read_text()) + assert len(metadata["sessions"]) == 2 + assert metadata["sessions"][1]["resume_global_steps"] == 3 + assert metadata["identity"]["label_mode"] == "qrennd_global_data_parity" + assert metadata["source_sha256"]["train.py"] == sha256(Path("baselines/train.py")) + + # Manual validation must not reset or update the ongoing fit metric states. + training, validation, _ = load_populations(root, cache, group, "pretrain") + model = tf.keras.models.load_model(output / "last.keras") + assert any(np.any(variable.numpy()) for variable in model.optimizer.variables()[1:]) + inputs, labels = PackedSequence(training, 8, 0, 0)[0] + model.train_on_batch(inputs, labels) + metrics_before = [variable.numpy().copy() for metric in model.metrics for variable in metric.variables] + validation_result = evaluate_validation(model, validation, lambda: True, batch_size=8) + metrics_after = [variable.numpy() for metric in model.metrics for variable in metric.variables] + assert validation_result["complete"] + for before, after in zip(metrics_before, metrics_after): + np.testing.assert_array_equal(before, after) + + last_hash = sha256(output / "last.keras") + args.seed = 4 + with pytest.raises(ValueError, match="Resume settings/data differ"): + run_training(args) + assert sha256(output / "last.keras") == last_hash + + args.seed = 0 + with monkeypatch.context() as context: + def changed_transform_hash(path: Path) -> str: + return "0" * 64 if path.name == "observables.py" else sha256(path) + context.setattr("baselines.train.sha256", changed_transform_hash) + with pytest.raises(ValueError, match="Resume settings/data differ"): + run_training(args) + assert sha256(output / "last.keras") == last_hash + + # Cross an epoch boundary after restoring a partial epoch, without replaying + # already-seen batches. Also exercise the measured-throughput warmup window. + args.max_steps = 40 + args.eval_seconds = 60 + next_epoch = run_training(args) + assert next_epoch["global_steps"] == next_epoch["optimizer_iterations"] == 40 + assert next_epoch["seen_samples"] == 320 + assert next_epoch["epoch"] == 1 and next_epoch["next_batch"] == 1 + assert next_epoch["steady_steps"] == 25 + assert next_epoch["steady_samples_per_second"] > 0 + + +def test_hardware_training_does_not_parse_odd_test_labels(tmp_path: Path) -> None: + root, _, group = small_data(tmp_path) + condition = group_conditions(root)[group][0] + width = condition.rounds * (condition.distance**2 - 1) // 8 + np.zeros((50_000, width), dtype=np.uint8).tofile(condition.path / "detection_events.b8") + # Deliberately invalid odd rows fail if any full-file label parser is used. + (condition.path / "obs_flips_actual.01").write_bytes(b"0\nx\n" * 25_000) + train_dets, train_labels = _load_allowed_hardware(condition, "train") + val_dets, val_labels = _load_allowed_hardware(condition, "validation") + assert train_dets.shape == (19_880, width) + assert val_dets.shape == (5_120, width) + assert not train_labels.any() and not val_labels.any() + + +def test_corrupt_cache_and_nonempty_output_are_rejected(tmp_path: Path) -> None: + root, cache, group = small_data(tmp_path) + manifest = json.loads((cache / "manifest.json").read_text()) + corrupted = cache / manifest["conditions"][0]["files"]["train_labels"] + with corrupted.open("ab") as stream: + stream.write(b"corrupt") + with pytest.raises(ValueError, match="checksum mismatch"): + load_populations(root, cache, group, "pretrain") + output = tmp_path / "occupied" + output.mkdir() + (output / "do-not-overwrite.txt").write_text("existing results") + args = argument_parser().parse_args([ + "--data-root", str(root), "--cache-dir", str(cache), "--group", group, + "--output", str(output), "--hours", "1", "--allow-cpu", + ]) + with pytest.raises(ValueError, match="nonempty"): + run_training(args) diff --git a/reproduction/files/9b/9b5dd306ea7b19c77e368190a859eb21d6465eb1255b523023efa80b9e07bbf8/runtime.py b/reproduction/files/9b/9b5dd306ea7b19c77e368190a859eb21d6465eb1255b523023efa80b9e07bbf8/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..7bd3bc2c58c9d0efb13f119b0ff4914d2df27096 --- /dev/null +++ b/reproduction/files/9b/9b5dd306ea7b19c77e368190a859eb21d6465eb1255b523023efa80b9e07bbf8/runtime.py @@ -0,0 +1,811 @@ +"""Direct Beaker execution: persistent Codex research, then a separate verifier job. + +The agent image contains only the development workspace. The verifier image and +its Weka mount contain neither Codex credentials nor the development trajectory. +""" + +import argparse +from concurrent.futures import ThreadPoolExecutor +import ctypes +import errno +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from task_profiles import PROFILES, configure_data, gpu_count + +STATE = Path("/run-state") +WORKSPACE = Path("/workspace") +CODEX_VERSION = "0.163.0" +OFFLINE_HELPER = Path(__file__).with_name("network_sandbox.py") +HEARTBEAT_SECONDS = 10 +MAX_CAPACITY_RETRIES = 6 +TASK_ID = os.environ.get("SPEEDRUN_TASK", "tokamak-magnetic-control") +EARTH = "earth-observation-pretraining-transfer" +NDP = "natural-disease-progression" +CONTINUE = ( + "Continue the research. There is no end point: pick up from your research notes " + "and the latest results, run the next experiment, and keep the submission up to " + "date with the strongest replayable candidate." +) + + +def write_json(path, value): + path = Path(path) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(value, indent=2) + "\n") + tmp.replace(path) + + +def status(phase, **extra): + data = {"phase": phase, "updated_unix": time.time(), **extra} + write_json(STATE / "status.json", data) + print(json.dumps(data), flush=True) + + +def fingerprint(root): + """Hash content and modes; reject links escaping the portable package.""" + root = Path(root) + digest = hashlib.sha256() + for p in sorted(root.rglob("*")): + relative = str(p.relative_to(root)) + digest.update(relative.encode() + b"\0") + if p.is_symlink(): + p.resolve(strict=True).relative_to(root.resolve()) + digest.update(b"link:" + os.readlink(p).encode()) + elif p.is_file(): + digest.update(str(p.stat().st_mode & 0o777).encode()) + with p.open("rb") as f: + for chunk in iter(lambda: f.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def snapshot(start, previous): + src = WORKSPACE / "submission" + if not src.is_dir() or not any(src.iterdir()): + return previous + staging = STATE / "snapshots" / ".staging" + try: + before = fingerprint(src) + if before == previous: + return previous + shutil.rmtree(staging, ignore_errors=True) + staging.parent.mkdir(exist_ok=True) + shutil.copytree(src, staging, symlinks=True) + if fingerprint(src) != before or fingerprint(staging) != before: + shutil.rmtree(staging) + return previous + elapsed = int(time.monotonic() - start) + dst = staging.parent / f"{elapsed:06d}-{before[:12]}" + staging.rename(dst) + with (staging.parent / "index.jsonl").open("a") as f: + f.write(json.dumps({"seconds": elapsed, "sha256": before, "path": dst.name}) + "\n") + return before + except (OSError, ValueError) as error: + print(json.dumps({"snapshot_skipped": str(error)}), flush=True) + shutil.rmtree(staging, ignore_errors=True) + return previous + + +def researcher(): + os.setgroups([]) + os.setgid(1000) + os.setuid(1000) + + +def stop_research(): + # A dedicated UID inside this job includes background trainers which have + # detached from Codex's process group. The supervisor remains root. + for sig in (signal.SIGTERM, signal.SIGKILL): + for p in Path("/proc").iterdir(): + if not p.name.isdigit(): + continue + try: + if p.stat().st_uid == 1000: + os.kill(int(p.name), sig) + except (ProcessLookupError, PermissionError, FileNotFoundError): + pass + if sig == signal.SIGTERM: + time.sleep(3) + + +def check_atomic_exchange(parent): + """Exercise the exact syscall used by Earth's unchanged publisher.""" + with tempfile.TemporaryDirectory(prefix=".exchange-check-", dir=parent) as folder: + a, b = Path(folder) / "a", Path(folder) / "b" + a.mkdir() + b.mkdir() + (a / "marker").write_text("a") + (b / "marker").write_text("b") + libc = ctypes.CDLL(None, use_errno=True) + rename = libc.renameat2 + rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, + ctypes.c_char_p, ctypes.c_uint] + rename.restype = ctypes.c_int + if rename(-100, os.fsencode(a), -100, os.fsencode(b), 2): + error = ctypes.get_errno() + raise OSError(error, os.strerror(error)) + if (a / "marker").read_text() != "b" or (b / "marker").read_text() != "a": + raise RuntimeError("Atomic directory exchange did not exchange content") + return True + + +def latest_published_package(actual): + """Restore the latest completely committed snapshot after a container loss.""" + index = STATE / "snapshots/index.jsonl" + if index.exists(): + for line in reversed(index.read_text().splitlines()): + try: + entry = json.loads(line) + except json.JSONDecodeError: + continue # A killed append cannot invalidate earlier complete records. + name = entry["path"] + if Path(name).name != name: + raise RuntimeError("Invalid snapshot path") + package = index.parent / name + if fingerprint(package) != entry["sha256"]: + raise RuntimeError("Committed publication snapshot changed") + return package + return actual / "submission" + + +def configure_earth_workspace(actual): + # Keep the workspace parent and submission on the container's local filesystem. + # The original publisher stages beside submission and requires RENAME_EXCHANGE. + # Research, data, and task files still resolve to their persistent Weka paths. + if WORKSPACE.is_symlink(): + if WORKSPACE.resolve() != actual.resolve(): + raise RuntimeError("Unexpected workspace symlink") + WORKSPACE.unlink() + WORKSPACE.mkdir(exist_ok=True) + for child in actual.iterdir(): + if child.name == "submission": + continue + destination = WORKSPACE / child.name + if destination.is_symlink(): + if os.readlink(destination) != str(child): + raise RuntimeError("Unexpected Earth workspace link") + elif destination.exists(): + raise RuntimeError("Unexpected local Earth workspace file") + else: + destination.symlink_to(child, target_is_directory=child.is_dir()) + destination = WORKSPACE / "submission" + if destination.exists() or destination.is_symlink(): + raise RuntimeError("Refusing to replace an existing local publication") + package = latest_published_package(actual) + shutil.copytree(package, destination, symlinks=True) + if fingerprint(destination) != fingerprint(package): + raise RuntimeError("Restored publication differs from its durable package") + for p in [WORKSPACE, destination, *destination.rglob("*")]: + if not p.is_symlink(): + os.chown(p, 1000, 1000) + check_atomic_exchange(WORKSPACE) + write_json(STATE / "publication-storage.json", { + "layout": "local-workspace-parent-with-persistent-research", + "restored_from": str(package), "restored_sha256": fingerprint(destination), + "atomic_exchange_ok": True, + }) + + +def configure_workspace(resume=False): + actual = STATE / "workspace" + if actual.exists(): + if not resume: + raise RuntimeError("Refusing to overwrite an existing research workspace") + else: + if resume: + raise RuntimeError("Saved research state has no workspace") + shutil.copytree("/opt/task-workspace", actual) + for p in [actual, *actual.rglob("*")]: + if not p.is_symlink(): + os.chown(p, 1000, 1000) + if TASK_ID == EARTH or TASK_ID in PROFILES: + configure_earth_workspace(actual) + elif WORKSPACE.is_symlink(): + if WORKSPACE.resolve() != actual.resolve(): + raise RuntimeError("Unexpected workspace symlink") + else: + WORKSPACE.rmdir() + WORKSPACE.symlink_to(actual, target_is_directory=True) + if TASK_ID in PROFILES: + configure_data(TASK_ID, WORKSPACE) + elif TASK_ID == EARTH: + from earth_data import validate_development + validate_development(Path("/task-data")) + for name in ("19837", "eval"): + destination = WORKSPACE / "data" / name + target = Path("/task-data") / name + if destination.is_symlink(): + if destination.resolve() != target.resolve(): + raise RuntimeError("Unexpected task data symlink") + else: + destination.symlink_to(target, target_is_directory=True) + elif TASK_ID == NDP: + from ndp_data import validate_development, WORKSPACE_DATA + validate_development(Path("/task-data")) + for name in WORKSPACE_DATA: + destination = WORKSPACE / "data" / name + target = Path("/task-data") / name + if destination.is_symlink(): + if destination.resolve() != target.resolve(): + raise RuntimeError("Unexpected task data symlink") + else: + if destination.is_dir(): + destination.rmdir() # Only the image's empty mount points. + destination.symlink_to(target, target_is_directory=target.is_dir()) + home = STATE / "agent" + home.mkdir(mode=0o700, exist_ok=True) + os.chown(home, 1000, 1000) + auth = home / "auth.json" + if not auth.is_file(): + raise RuntimeError("Missing staged Codex auth.json") + os.chown(auth, 1000, 1000) + auth.chmod(0o600) + # Allow traversal into this run, but credentials and logs retain 0700/0600. + STATE.chmod(0o755) + if os.environ.get("SPEEDRUN_ENFORCE_ONE_GPU") == "1": + from gpu_access import configure + policy = configure(STATE, count=gpu_count(TASK_ID), + strict_allocation=os.environ.get("SPEEDRUN_SINGLE_SLOT") == "1") + else: + policy = None + env = {**os.environ, "HOME": "/home/researcher", "CODEX_HOME": str(home), + "TMPDIR": "/tmp", "PYTHONPATH": "/workspace" + ( + ":" + os.environ["PYTHONPATH"] if os.environ.get("PYTHONPATH") else ""), + "CUDA_VISIBLE_DEVICES": ",".join(policy["allowed_uuids"]) if policy else "0"} + # Authentication comes exclusively from the privately staged auth.json. + for name in ("OPENAI_API_KEY", "CODEX_API_KEY", "OPENAI_BASE_URL"): + env.pop(name, None) + if TASK_ID == "crystal-structure-generation": + env.update(CRYSTALGEN_LEMAT_GPU_WORKERS=str(gpu_count(TASK_ID)), + HF_HOME="/scorer-assets/huggingface", HF_HUB_CACHE="/scorer-assets/huggingface/hub", + HF_DATASETS_CACHE="/scorer-assets/huggingface/datasets", + XDG_CACHE_HOME="/scorer-assets/xdg-cache", TORCH_HOME="/scorer-assets/torch-cache") + env.pop("SPEEDRUN_OFFLINE_LOOPBACK", None) + if gpu_count(TASK_ID) > 1: + from offline_network import configure + configure(STATE) + env.update(SPEEDRUN_OFFLINE_LOOPBACK="1", NCCL_SOCKET_IFNAME="lo", + GLOO_SOCKET_IFNAME="lo", MASTER_ADDR="127.0.0.1") + return env + + +def codex_command(args, resume=False, ephemeral=False): + cmd = ["codex", "exec", "--ignore-user-config", "--skip-git-repo-check", + "-m", args.model, "-c", f'model_reasoning_effort="{args.reasoning}"', + "-c", 'service_tier="default"', "--disable", "fast_mode", + "-c", 'approval_policy="never"', "-c", 'default_permissions="job"', + "-c", 'permissions={job={filesystem={":root"="write"},network={enabled=false}}}', + "--enable", "use_legacy_landlock", + "-c", 'web_search="disabled"', "--json"] + if ephemeral: + cmd += ["--ephemeral"] + if resume: + cmd += ["resume", resume if isinstance(resume, str) else "--last"] + return cmd + ["-"] + + +def start_codex(command, env, out, err, *, process_setup=None): + """Install the offline helper before delivering any prompt to Codex. + + Codex 0.163 creates per-process helper aliases before reading stdin. There + is no CLI override for its sandbox executable. Replace this invocation's + alias with our root-owned helper, retaining the same declared permissions. + Fail closed if the pinned CLI no longer creates the expected alias. + """ + aliases = Path(env["CODEX_HOME"]) / "tmp/arg0-linux" + old = set(aliases.glob("*/codex-linux-sandbox")) + proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=out, stderr=err, + text=True, cwd=WORKSPACE, env=env, + user=1000, group=1000, extra_groups=[], start_new_session=True, + preexec_fn=process_setup) + try: + for _ in range(300): + candidates = set(aliases.glob("*/codex-linux-sandbox")) - old + if len(candidates) == 1: + alias = candidates.pop() + # 0.163 uses platform-specific aliases and no longer creates + # codex-execve-wrapper. Wait for the complete alias set. + markers = [alias.parent / name for name in ("apply_patch", "applypatch")] + if not all(p.is_symlink() for p in markers): + time.sleep(0.05) + continue + if not alias.is_symlink(): + raise RuntimeError("Unexpected Codex helper file") + binary = Path(shutil.which(command[0], path=env.get("PATH"))).resolve() + if any(p.resolve() != binary for p in [alias, *markers]): + raise RuntimeError("Unexpected Codex helper target") + staged = alias.with_name("offline-helper.tmp") + shutil.copyfile(OFFLINE_HELPER, staged) + staged.chmod(0o755) + staged.replace(alias) + return proc + if proc.poll() is not None: + raise RuntimeError(f"Codex exited before sandbox setup: {proc.returncode}") + time.sleep(0.05) + raise RuntimeError("Codex sandbox helper did not appear") + except BaseException: + proc.kill() + proc.wait() + raise + + +def preflight(args, env, check_resume=False): + status("preflight") + # Require the actual model to execute a tool in the same sandbox used by the + # trial, and prove that scientific code can use the GPU while network calls + # from tools are blocked. Model API traffic stays outside the tool sandbox. + probe = WORKSPACE / "research" / "codex-preflight.json" + probe.unlink(missing_ok=True) + prompt = ( + "Perform this environment check and then stop: execute " + "`python /opt/speedrun/probe.py` using your shell tool. Do not modify that " + "script or read credentials. It verifies CUDA, task imports, blocked tool " + "networking, and a workspace write. Reply PREFLIGHT_OK only if it succeeds." + ) + with (STATE / "preflight.jsonl").open("w") as out, (STATE / "preflight.stderr").open("w") as err: + completed = start_codex(codex_command(args, ephemeral=not check_resume), env, out, err) + try: + completed.communicate(prompt, timeout=420) + except BaseException: + stop_research() + completed.wait() + raise + if completed.returncode != 0 or not probe.is_file(): + raise RuntimeError("Codex preflight failed; inspect preflight logs") + data = json.loads(probe.read_text()) + if not all(data.get(k) is True for k in ("cuda_ok", "imports_ok", "network_blocked")): + raise RuntimeError(f"Preflight assertions failed: {data}") + write_json(STATE / "preflight-result.json", data) + if check_resume: + probe.unlink() + with (STATE / "resume-preflight.jsonl").open("w") as out, \ + (STATE / "resume-preflight.stderr").open("w") as err: + resumed = start_codex(codex_command(args, resume=True), env, out, err) + try: + resumed.communicate(prompt, timeout=420) + except BaseException: + stop_research() + resumed.wait() + raise + if resumed.returncode != 0 or not probe.is_file(): + raise RuntimeError("Codex resume preflight failed; inspect resume preflight logs") + resumed_data = json.loads(probe.read_text()) + if not all(resumed_data.get(k) is True for k in ("cuda_ok", "imports_ok", "network_blocked")): + raise RuntimeError(f"Resume preflight assertions failed: {resumed_data}") + def thread_id(path): + for line in path.read_text().splitlines(): + event = json.loads(line) + if event.get("type") == "thread.started": + return event["thread_id"] + raise RuntimeError(f"Missing thread.started event in {path.name}") + first_id = thread_id(STATE / "preflight.jsonl") + if thread_id(STATE / "resume-preflight.jsonl") != first_id: + raise RuntimeError("Resume started a different Codex session") + write_json(STATE / "resume-preflight-result.json", { + **resumed_data, "session_resume_ok": True, "thread_id": first_id, + }) + if TASK_ID in (EARTH, NDP) or TASK_ID in PROFILES: + if not data.get("development_data_ok") or not data.get("data_readonly"): + raise RuntimeError(f"{TASK_ID} data checks did not pass") + probe.unlink() + return + # Confirm a real nonlinear simulator reset/step before starting the clock. + code = """ +import json, numpy as np +from tokagym import TokamakMagneticEnv +env = TokamakMagneticEnv('mastu_diverted_hold', randomization='none', solver='nonlinear') +obs, info = env.reset(seed=0) +assert obs.shape == (585,) and np.isfinite(obs).all() +obs, reward, terminated, truncated, info = env.step(np.zeros(12)) +assert np.isfinite(obs).all() and np.isfinite(reward) +print(json.dumps({'reset_and_step_ok': True, 'observation_shape': list(obs.shape)})) +""" + with (STATE / "simulator-preflight.log").open("w") as log: + subprocess.run([sys.executable, "-c", code], cwd=WORKSPACE, env=env, + preexec_fn=researcher, stdout=log, stderr=subprocess.STDOUT, + timeout=300, check=True) + probe.unlink() + + +def checked_codex_version(): + version = subprocess.check_output(["codex", "--version"], text=True).strip() + if version != f"codex-cli {CODEX_VERSION}": + raise RuntimeError(f"The sandbox adapter requires Codex {CODEX_VERSION}, got {version}") + return version + + +def validate(args): + version = checked_codex_version() + env = configure_workspace() + try: + preflight(args, env, check_resume=True) + finally: + stop_research() + status("complete", validation_only=True, codex_version=version, + model=args.model, reasoning=args.reasoning, service_tier="default", session_resume_ok=True, + network_isolation=network_isolation()) + return 0 + + +def network_isolation(): + return ("loopback-only-user-network-namespace+gpu-landlock" if gpu_count(TASK_ID) > 1 + else "gpu-compatible-seccomp-helper") + + +def load_research_state(args, version): + expected = {"budget_seconds": args.seconds, "model": args.model, + "task": TASK_ID, "gpu_count": gpu_count(TASK_ID), + "single_slot": os.environ.get("SPEEDRUN_SINGLE_SLOT") == "1", + "reasoning": args.reasoning, "codex_version": version, + "service_tier": "default", "network_isolation": network_isolation()} + path = STATE / "research-state.json" + if not path.exists(): + return {"metadata": expected, "elapsed_seconds": 0, "turns": 0, + "quick_turns": 0, "last_hash": None, "attempt": 0, "phase": "initializing"} + saved = json.loads(path.read_text()) + for key, value in expected.items(): + observed = saved["metadata"].get(key, "tokamak-magnetic-control" if key == "task" else None) + if key == "gpu_count" and observed is None: + observed = 8 if TASK_ID in PROFILES else 1 + if key == "single_slot" and observed is None: + observed = False + if observed != value: + raise RuntimeError(f"Cannot resume with changed {key}") + if saved["phase"] == "failed": + raise RuntimeError("Research failed; inspect the saved error before retrying") + if saved["phase"] == "running": + # A hard kill can lose at most one heartbeat. Conservatively charge it + # so interrupted jobs never gain additional research budget. + saved["elapsed_seconds"] = min(args.seconds, saved["elapsed_seconds"] + HEARTBEAT_SECONDS) + return saved + + +def trajectory_events(path, offset=0): + if not path.exists(): + return + with path.open() as stream: + stream.seek(offset) + for line in stream: + try: + yield json.loads(line) + except json.JSONDecodeError: + continue # The current writer may have an incomplete last line. + + +def trajectory_thread(path, offset=0): + threads = {event["thread_id"] for event in trajectory_events(path, offset) + if event.get("type") == "thread.started"} + if len(threads) > 1: + raise RuntimeError("Research trajectory contains different Codex sessions") + return next(iter(threads), None) + + +def capacity_failure(path, offset=0): + """Only the terminal error from this invocation can authorize a retry.""" + terminal = None + for event in trajectory_events(path, offset): + if event.get("type") == "turn.started": + terminal = None + elif event.get("type") == "turn.failed": + terminal = event.get("error", {}).get("message", "") + if not terminal: + return None + allowed = ("selected model is at capacity", "currently experiencing high demand") + return terminal if any(value in terminal.lower() for value in allowed) else None + + +def capacity_delay(retries): + return min(300, 30 * 2 ** min(retries, 4)) + + +def checked_preflight(args, env): + for retry in range(MAX_CAPACITY_RETRIES + 1): + try: + preflight(args, env) + return + except Exception: + reason = capacity_failure(STATE / "preflight.jsonl") + if not reason or retry == MAX_CAPACITY_RETRIES: + raise + archive = STATE / "preflight-retries" / f"{time.time_ns()}" + archive.mkdir(parents=True) + for name in ("preflight.jsonl", "preflight.stderr"): + (STATE / name).replace(archive / name) + delay = capacity_delay(retry) + status("preflight-retrying", retry=retry + 1, delay_seconds=delay, reason=reason) + time.sleep(delay) + + +def submission_entrypoint(): + if TASK_ID in PROFILES: + return PROFILES[TASK_ID]["entrypoint"] + return "infer.py" if TASK_ID == EARTH else "infer.sh" + + +def agent(args): + with (STATE / "supervisor.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + return research(args) + + +def research(args): + saved = load_research_state(args, checked_codex_version()) + if saved["phase"] == "complete": + if fingerprint(STATE / "submission") != saved["last_hash"]: + raise RuntimeError("Completed submission changed") + return 0 + env = configure_workspace(resume=saved["attempt"] > 0) + saved["attempt"] += 1 + metadata = saved["metadata"] + saved["phase"] = "preflight" + write_json(STATE / "research-state.json", saved) + if saved["attempt"] > 1: + archive = STATE / "attempts" / f"{saved['attempt'] - 1:03d}" + archive.mkdir(parents=True, exist_ok=True) + for name in ("preflight.jsonl", "preflight.stderr", "preflight-result.json", "simulator-preflight.log"): + path = STATE / name + if path.exists(): + path.replace(archive / name) + checked_preflight(args, env) + metadata.setdefault("started_unix", time.time()) + write_json(STATE / "trial.json", metadata) + base_elapsed = saved["elapsed_seconds"] + start = time.monotonic() + deadline = start + max(0, args.seconds - base_elapsed) + turn = saved["turns"] + quick = saved["quick_turns"] + last_hash = saved["last_hash"] + trajectory = STATE / "trajectory.jsonl" + thread_id = saved.get("thread_id") or trajectory_thread(trajectory) + recovery_notice = STATE / "recovery-notice.txt" + notice = recovery_notice.read_text() if recovery_notice.exists() else "" + failure = None + charged_elapsed = None + retries = 0 + interrupted = [] + old_handlers = {sig: signal.signal(sig, lambda signum, frame: interrupted.append(signum)) + for sig in (signal.SIGTERM, signal.SIGINT)} + + def persist(phase): + elapsed = charged_elapsed if charged_elapsed is not None else min( + args.seconds, base_elapsed + time.monotonic() - start) + saved.update(phase=phase, elapsed_seconds=elapsed, thread_id=thread_id, + turns=turn, quick_turns=quick, last_hash=last_hash, error=failure) + write_json(STATE / "research-state.json", saved) + + # Copy/hash large packages off the deadline/heartbeat thread. In particular, + # vendored runtimes must not keep research processes alive beyond the budget. + snapshots = ThreadPoolExecutor(max_workers=1) + pending_snapshot = None + next_snapshot = next_heartbeat = next_status = 0 + + def maintain(): + nonlocal pending_snapshot, last_hash, next_snapshot, next_heartbeat, next_status + now = time.monotonic() + if pending_snapshot is not None and pending_snapshot.done(): + last_hash = pending_snapshot.result() + pending_snapshot = None + if now >= next_snapshot and pending_snapshot is None: + pending_snapshot = snapshots.submit(snapshot, start - base_elapsed, last_hash) + next_snapshot = now + 60 + if now >= next_heartbeat: + persist("running") + next_heartbeat = now + HEARTBEAT_SECONDS + if now >= next_status: + status("running", **metadata, elapsed_seconds=int(base_elapsed + now - start), + turn=turn, attempt=saved["attempt"], thread_id=thread_id, + capacity_retries=retries, latest_submission_sha256=last_hash) + next_status = now + 60 + + persist("running") + status("running", **metadata, attempt=saved["attempt"], elapsed_seconds=base_elapsed) + try: + with (STATE / "trajectory.jsonl").open("a", buffering=1) as out, \ + (STATE / "codex.stderr").open("a", buffering=1) as err: + while time.monotonic() < deadline and not interrupted: + turn_start = time.monotonic() + resume = thread_id or any((Path(env["CODEX_HOME"]) / "sessions").rglob("*.jsonl")) + offset = trajectory.stat().st_size + process = start_codex(codex_command(args, resume=resume), env, out, err) + prompt = CONTINUE if resume else (WORKSPACE / "instruction.md").read_text() + if not resume and TASK_ID in PROFILES and gpu_count(TASK_ID) == 1: + prompt += ("\n\nOperator resource override for this reduced-compute trial: " + "you have exactly ONE H100 GPU. " + "This overrides any eight-GPU research budget in the task documents. " + "All scientific rules, data restrictions, submission requirements, and " + "evaluation criteria still apply. Adapt your research to this allocation.") + if os.environ.get("SPEEDRUN_SINGLE_SLOT") == "1": + prompt += " CPU and RAM are also reduced to a request of 22 CPUs and 224 GiB RAM." + if notice: + prompt += "\n\n" + notice + notice = "" + process.stdin.write(prompt) + process.stdin.close() + turn += 1 + checked_thread = False + while process.poll() is None and time.monotonic() < deadline and not interrupted: + if not checked_thread: + observed = trajectory_thread(trajectory, offset) + if observed: + if thread_id and observed != thread_id: + raise RuntimeError("Codex resumed a different research session") + thread_id, checked_thread = observed, True + maintain() + time.sleep(min(2, max(0, deadline - time.monotonic()))) + if not checked_thread: + observed = trajectory_thread(trajectory, offset) + if observed: + if thread_id and observed != thread_id: + raise RuntimeError("Codex resumed a different research session") + thread_id = observed + if time.monotonic() >= deadline or interrupted: + break + if process.returncode != 0: + reason = capacity_failure(trajectory, offset) + if reason and retries < MAX_CAPACITY_RETRIES: + delay = capacity_delay(retries) + retries += 1 + with (STATE / "capacity-retries.jsonl").open("a") as log: + log.write(json.dumps({"unix": time.time(), "turn": turn, + "retry": retries, "delay_seconds": delay, "reason": reason}) + "\n") + until = min(deadline, time.monotonic() + delay) + while time.monotonic() < until and not interrupted: + maintain() + time.sleep(min(2, max(0, until - time.monotonic()))) + continue + failure = f"Codex exited with status {process.returncode}" + break + retries = 0 + quick = quick + 1 if time.monotonic() - turn_start < 120 else 0 + if quick >= 3: + failure = "Three consecutive short turns; stopping a stalled continuation loop" + break + except Exception as error: + failure = str(error) + finally: + stop_research() + # Research has stopped; final snapshot/collection time must not silently + # change the remaining research budget or disagree between status files. + charged_elapsed = min(args.seconds, base_elapsed + time.monotonic() - start) + if pending_snapshot is not None: + last_hash = pending_snapshot.result() + snapshots.shutdown(wait=True) + last_hash = snapshot(start - base_elapsed, last_hash) + persist("interrupted" if interrupted else "running") + for sig, handler in old_handlers.items(): + signal.signal(sig, handler) + if interrupted: + status("interrupted", **metadata, elapsed_seconds=saved["elapsed_seconds"], + attempt=saved["attempt"], turns=turn, submission_sha256=last_hash) + return 128 + interrupted[0] + elapsed = saved["elapsed_seconds"] + src = WORKSPACE / "submission" + if not (src / submission_entrypoint()).is_file(): + failure = failure or f"No runnable {submission_entrypoint()} was published" + elif last_hash: + dst = STATE / "submission" + if dst.exists(): + if fingerprint(dst) != last_hash: + raise RuntimeError("Frozen submission differs from the completed research") + else: + staging = STATE / ".submission-staging" + shutil.rmtree(staging, ignore_errors=True) + shutil.copytree(src, staging, symlinks=True) + if fingerprint(staging) != last_hash: + raise RuntimeError("Final submission snapshot changed") + staging.rename(dst) + if elapsed < args.seconds: + failure = failure or "Trial stopped before its full time budget" + persist("failed" if failure else "complete") + status(saved["phase"], **metadata, elapsed_seconds=elapsed, attempt=saved["attempt"], + turns=turn, submission_sha256=last_hash, error=failure) + return 1 if failure else 0 + + +def deny_network(): + """Irreversible seccomp ban on IPv4/IPv6 sockets, inherited by verifier children. + + AF_UNIX remains available to multiprocessing. This requires no privileged + network namespace or host firewall modifications. + """ + lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) + class Compare(ctypes.Structure): + _fields_ = [("arg", ctypes.c_uint), ("op", ctypes.c_int), + ("datum_a", ctypes.c_uint64), ("datum_b", ctypes.c_uint64)] + lib.seccomp_init.argtypes = [ctypes.c_uint32] + lib.seccomp_init.restype = ctypes.c_void_p + lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] + lib.seccomp_syscall_resolve_name.restype = ctypes.c_int + lib.seccomp_rule_add_array.argtypes = [ctypes.c_void_p, ctypes.c_uint32, + ctypes.c_int, ctypes.c_uint, ctypes.POINTER(Compare)] + lib.seccomp_load.argtypes = [ctypes.c_void_p] + lib.seccomp_release.argtypes = [ctypes.c_void_p] + ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW + if not ctx: + raise RuntimeError("seccomp_init failed") + try: + for domain in (2, 10): # AF_INET, AF_INET6 + cmp = Compare(0, 4, domain, 0) # SCMP_CMP_EQ + rc = lib.seccomp_rule_add_array(ctx, 0x00050000 | errno.EPERM, + lib.seccomp_syscall_resolve_name(b"socket"), 1, + ctypes.byref(cmp)) + if rc != 0: + raise RuntimeError(f"seccomp_rule_add failed: {rc}") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("seccomp_load failed") + finally: + lib.seccomp_release(ctx) + import socket + for family in (socket.AF_INET, socket.AF_INET6): + try: + sock = socket.socket(family) + except PermissionError: + continue + sock.close() + raise RuntimeError("Verifier network isolation check failed") + + +def verify(args): + if TASK_ID != "tokamak-magnetic-control": + raise RuntimeError("This verifier adapter only supports tokamak") + status("verifying") + src = STATE / "submission" + if not (src / "infer.sh").is_file(): + raise RuntimeError("Missing inference package") + package_hash = fingerprint(src) + shutil.copytree(src, WORKSPACE / "submission", dirs_exist_ok=True, symlinks=True) + deny_network() + write_json(STATE / "isolation.json", {"inet_sockets_blocked": True, "ipv6_sockets_blocked": True}) + env = {**os.environ, "TOKAGYM_WORKERS": str(args.workers)} + started = time.time() + with (STATE / "verifier.log").open("w") as log: + result = subprocess.run(["bash", "/tests/test.sh"], env=env, stdout=log, + stderr=subprocess.STDOUT, timeout=args.seconds) + shutil.copytree("/logs/verifier", STATE / "results", dirs_exist_ok=True) + score = STATE / "results/reward.json" + reward = json.loads(score.read_text()) if score.exists() else None + status("complete" if result.returncode == 0 and reward is not None else "failed", + returncode=result.returncode, reward=reward, elapsed_seconds=time.time() - started, + submission_sha256=package_hash) + return 0 if result.returncode == 0 and reward is not None else 1 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("mode", choices=["agent", "verify", "preflight"]) + parser.add_argument("--seconds", type=int, default=3600) + parser.add_argument("--model", default="gpt-6.1-sol") + parser.add_argument("--reasoning", default="medium") + parser.add_argument("--workers", type=int, default=35) + parser.add_argument("--gpus", type=int, choices=[1, 8]) + parser.add_argument("--single-slot", action="store_true") + args = parser.parse_args() + if args.single_slot: + if args.gpus not in (None, 1): + parser.error("--single-slot cannot use eight GPUs") + args.gpus = 1 + os.environ["SPEEDRUN_SINGLE_SLOT"] = "1" + if args.gpus is not None: + os.environ["SPEEDRUN_GPU_COUNT"] = str(args.gpus) + STATE.mkdir(exist_ok=True) + try: + return {"agent": agent, "verify": verify, "preflight": validate}[args.mode](args) + except Exception as error: + import traceback + traceback.print_exc() + status("failed", error=str(error)) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/reproduction/files/9d/9de4ee6ae2d15f252501d9fba630ea65d57e9862a066a16b93bf9c1e0dfa748c/native_verifier.py b/reproduction/files/9d/9de4ee6ae2d15f252501d9fba630ea65d57e9862a066a16b93bf9c1e0dfa748c/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..b755585f4b2e828589c4cfc6bfd157cbcedc2ec2 --- /dev/null +++ b/reproduction/files/9d/9de4ee6ae2d15f252501d9fba630ea65d57e9862a066a16b93bf9c1e0dfa748c/native_verifier.py @@ -0,0 +1,355 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import shutil +import signal +import socket +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def enter_offline_namespace(): + import offline_network + record = offline_network.configure(STATE) + libc = ctypes.CDLL(None, use_errno=True) + for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)): + fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC) + try: + if libc.setns(fd, flag): + raise OSError(ctypes.get_errno(), 'enter offline verifier namespace') + finally: + os.close(fd) + if socket.if_nameindex() != [(1, 'lo')]: + raise RuntimeError('Offline verifier namespace has external interfaces') + return record + + +def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')): + """End the native waiting supervisor only after its authenticated seal.""" + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + seconds + sealed_ready = False + try: + while process.poll() is None: + if (sealed_root / 'READY').is_file(): + marker = json.loads((sealed_root / 'READY').read_text()) + snapshot = sealed_root / 'run/snapshot.json' + if (hashlib.sha256(snapshot.read_bytes()).hexdigest() != marker['snapshot_sha256'] + or json.loads(snapshot.read_text())['run_id'] != marker['run_id']): + raise RuntimeError('Native seal marker is inconsistent') + sealed_ready = True + break + if time.monotonic() >= deadline: + raise TimeoutError('Verifier inference budget exhausted') + time.sleep(.1) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode) + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + adapted = cfg.get('adapted_permissions', False) + if adapted: + import adapted_boundary + adapted_boundary.no_new_privileges() + os.setgroups([]) + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + crystal_cache_receipt = None + if cfg.get('isolated_crystal_dataset_cache'): + if plan['task'] != 'crystal-structure-generation' or phase != 'score': + raise RuntimeError('Crystal cache isolation is for trusted grading only') + import crystal_cache + crystal_cache_receipt = crystal_cache.prepare( + '/scorer-assets/huggingface/datasets', os.environ['HF_DATASETS_CACHE']) + crystal_cache_receipt['asset_manifest_sha256'] = hashlib.sha256( + Path('/scorer-assets/READY.json').read_bytes()).hexdigest() + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus'], strict_allocation=adapted) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + if adapted: + adapted_boundary.exact_gpu_allocation(gpu_policy) + else: + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + if cfg.get('gpu_runtime', 'torch') == 'torch' and not adapted: + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if cfg.get('local_benchmark_copy'): + status('copying_benchmark', task=plan['task'], role=phase) + # Folding's upstream evaluator runs inference and grading together. + # Give its non-root process a local readable copy, never relax Weka ACLs. + shutil.copytree('/source-benchmark', '/benchmark', symlinks=False) + for path in [Path('/benchmark'), *Path('/benchmark').rglob('*')]: + path.chmod(0o555 if path.is_dir() else 0o444) + if phase == 'inference': + if adapted:status('copying_submission', task=plan['task'], role=phase) + if cfg.get('native_uid_isolation'): + # The original PDE verifier explicitly supports this UID fallback. + # The mount is below a local root-only parent, never chmod shared data. + Path('/private').chmod(0o700) + Path('/tests').chmod(0o700) + elif plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + try: + agent = pwd.getpwuid(10001) + except KeyError: + subprocess.run(['/usr/sbin/useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + # Some native images precreate this empty container-local mountpoint. + # rmdir fails closed if it contains anything; never remove existing logs. + if Path('/logs/verifier').is_dir() and not Path('/logs/verifier').is_symlink(): + Path('/logs/verifier').rmdir() + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + if adapted and cfg.get('network_policy') != 'policy-children-only': + adapted_boundary.restrict_network() + elif not offline and not adapted: + runtime.deny_network() + if not adapted: + writable_roots = ['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc', + *cfg.get('writable_runtime_paths', [])] + if crystal_cache_receipt: + # The native image links /scorer-assets beneath /workspace. A + # writable ancestor defeats a read-only Landlock child rule. + # Trusted grading needs its output and scratch directories only. + writable_roots.remove('/workspace') + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets', + *cfg.get('readonly_runtime_paths', [])], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=writable_roots) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + if adapted: + source_audit = adapted_boundary.audit_source_permissions( + ['/operator', '/submission-source', '/source-benchmark', '/benchmark', '/data', '/labels', '/private'], + untrusted_uids=tuple(range(10001, 10009))) + else: + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if crystal_cache_receipt: + try: + fd = os.open('/scorer-assets/READY.json', os.O_WRONLY | os.O_CLOEXEC) + except PermissionError: + crystal_cache_receipt['asset_write_denied'] = True + else: + os.close(fd) + raise RuntimeError('Prepared scorer assets remain writable') + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' and not adapted else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())); ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + if cfg.get('gpu_runtime') == 'jax': + probe = ('import jax; import jax.numpy as jnp; ' + f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in d.device_kind for d in jax.devices("gpu")); ' + 'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 ' + 'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + if adapted and plan['task'] == 'fluid-flow-control': + # native_runtime.sh loads a module-provided libpython. Preserve + # only these runtime settings, never credentials, in the probe. + for key in ('PATH', 'LD_LIBRARY_PATH', 'OMP_NUM_THREADS', + 'OPENBLAS_NUM_THREADS', 'XLA_PYTHON_CLIENT_PREALLOCATE'): + if key in os.environ: + probe_env[key] = os.environ[key] + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + def dependency_identity(): + os.setgroups([]); os.setgid(10001); os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + cache=Path('/tmp/verifier-cache');cache.mkdir(exist_ok=True) + os.chown(cache,10001,10001) + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True, + preexec_fn=dependency_identity if cfg.get('untrusted_whole_verifier') else None) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': ('seccomp in unprivileged policy children; trusted simulator retains MPI sockets' + if cfg.get('network_policy') == 'policy-children-only' else + 'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children'), + 'offline_namespace': offline, + 'source_mounts': f'POSIX permission audit ({source_audit} entries); non-root submission' if adapted else 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan.get('label_isolated', plan['task'] != 'protein-folding-prediction'), + 'adapted_execution': adapted, + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + if cfg.get('stop_after_sealed_ready'): + # The native supervisor has already killed all model processes and + # sealed/hashes its predictions before writing READY. End only its + # wait-for-grader loop; the unchanged grader runs in a separate job. + result = run_until_sealed(cfg['command'], log, remaining) + else: + def run_identity(): + os.setgroups([]) + os.setgid(10001) + os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + os.chown(STATE / 'results', 10001, 10001) + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True, + preexec_fn=run_identity if cfg.get('untrusted_whole_verifier') else None) + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + if cfg.get('verify_crystal_assets_after'): + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted before post-score asset validation') + with (STATE / 'asset-validation-after.log').open('w') as log: + subprocess.run([cfg['driver_python'], '-c', + 'import sys;sys.path.insert(0,"/tests");from pathlib import Path;' + 'from grader import validate_assets;validate_assets(Path("/scorer-assets"));' + 'print("ORIGINAL_SCORER_ASSET_DIGEST_OK")'], + stdout=log, stderr=subprocess.STDOUT, timeout=remaining, check=True) + if hashlib.sha256(Path('/scorer-assets/READY.json').read_bytes()).hexdigest() != crystal_cache_receipt['asset_manifest_sha256']: + raise RuntimeError('Scorer asset manifest changed during grading') + crystal_cache_receipt['original_asset_digest_after'] = 'passed' + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + elapsed = time.monotonic() - entered + reward_path = STATE / 'results/reward.json' + if phase == 'score': + score_root = Path('/sealed/results') + if cfg.get('results_by_run_id'): + score_root /= json.loads(Path('/sealed/READY').read_text())['run_id'] + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = score_root / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/9d/9df966825750e6addf6fc73330bf15fbd4d1d0a234e2c10932c79313870421f2/adapted_boundary.py b/reproduction/files/9d/9df966825750e6addf6fc73330bf15fbd4d1d0a234e2c10932c79313870421f2/adapted_boundary.py new file mode 100644 index 0000000000000000000000000000000000000000..d449cb0593a6d34ee4edaa13a0fc71e6dd9663a5 --- /dev/null +++ b/reproduction/files/9d/9df966825750e6addf6fc73330bf15fbd4d1d0a234e2c10932c79313870421f2/adapted_boundary.py @@ -0,0 +1,107 @@ +"""Explicit permission/seccomp fallback for namespace-incompatible Beaker hosts. + +This is an adapted execution boundary, not a claim of namespace equivalence. +Native numerical evaluation code and submitted packages remain unchanged. +""" +import ctypes +import errno +import os +from pathlib import Path +import socket + + +def restrict_network(*, contain_process_group=False): + lib = ctypes.CDLL('libseccomp.so.2', use_errno=True) + class Compare(ctypes.Structure): + _fields_ = [('arg', ctypes.c_uint), ('op', ctypes.c_int), + ('a', ctypes.c_uint64), ('b', ctypes.c_uint64)] + lib.seccomp_init.argtypes = [ctypes.c_uint32] + lib.seccomp_init.restype = ctypes.c_void_p + lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] + lib.seccomp_syscall_resolve_name.restype = ctypes.c_int + lib.seccomp_rule_add_array.argtypes = [ctypes.c_void_p, ctypes.c_uint32, + ctypes.c_int, ctypes.c_uint, ctypes.POINTER(Compare)] + lib.seccomp_load.argtypes = [ctypes.c_void_p] + lib.seccomp_release.argtypes = [ctypes.c_void_p] + ctx = lib.seccomp_init(0x7fff0000) + if not ctx: + raise RuntimeError('seccomp_init failed') + try: + rules = [(b'socket', Compare(0, 1, socket.AF_UNIX, 0)), + (b'socketpair', Compare(0, 1, socket.AF_UNIX, 0))] + # Prevent alternate network creation and cross-process memory access. + rules += [(name, None) for name in (b'io_uring_setup', b'ptrace', + b'process_vm_readv', b'process_vm_writev', b'pidfd_getfd')] + if contain_process_group: + # start_new_session happens before preexec_fn; descendants cannot + # escape the process group that the trusted parent always kills. + rules += [(name, None) for name in (b'setsid', b'setpgid', b'truncate')] + for name, comparison in rules: + number = lib.seccomp_syscall_resolve_name(name) + if number < 0: + raise RuntimeError(f'Unknown syscall {name!r}') + rc = lib.seccomp_rule_add_array(ctx, 0x50000 | errno.EPERM, number, + int(comparison is not None), ctypes.byref(comparison) if comparison is not None else None) + if rc: + raise RuntimeError(f'seccomp rule failed: {name!r}: {rc}') + if lib.seccomp_load(ctx): + raise RuntimeError('seccomp_load failed') + finally: + lib.seccomp_release(ctx) + network_probe() + + +def network_probe(): + for family in (socket.AF_INET, socket.AF_INET6, socket.AF_PACKET, socket.AF_NETLINK): + try: + sock = socket.socket(family, socket.SOCK_DGRAM) + except PermissionError: + continue + else: + sock.close() + raise RuntimeError(f'Non-local socket family {family} remains available') + a, b = socket.socketpair() + try: + a.sendall(b'ok') + assert b.recv(2) == b'ok' + finally: + a.close(); b.close() + + +def no_new_privileges(): + libc = ctypes.CDLL(None, use_errno=True) + if libc.prctl(38, 1, 0, 0, 0): + raise OSError(ctypes.get_errno(), 'PR_SET_NO_NEW_PRIVS') + + +def exact_gpu_allocation(policy): + if policy['allocated_count'] != policy['count']: + raise RuntimeError('Adapted verifier requires exactly its requested GPU allocation') + # Do not install ABI1 Landlock: it implicitly denies cross-directory rename. + # Every additional device node, if present, must already be denied by the + # container device policy. CUDA_VISIBLE_DEVICES alone is not sufficient. + for path in policy['denied_devices']: + try: + fd = os.open(path, os.O_RDWR | os.O_CLOEXEC) + except PermissionError: + continue + else: + os.close(fd) + raise RuntimeError(f'Extra GPU device is accessible: {path}') + + +def audit_source_permissions(roots, untrusted_uids=(10001,)): + """Read-only audit; never chmod shared Weka mounts.""" + count = 0 + for root in map(Path, roots): + if not root.exists(): + continue + for p in [root, *root.rglob('*')]: + if p.is_symlink(): + continue + info = p.stat() + if (info.st_uid in untrusted_uids or info.st_mode & 0o002 + or (info.st_gid in untrusted_uids and info.st_mode & 0o020)): + raise RuntimeError(f'Shared source writable by an inference identity: {p}') + count += 1 + return count diff --git a/reproduction/files/9e/9e6717ecbcd77161fb56e42265916e7a0ef110641dcba15c12e57691e0d1987f/run_unit_tests.sh b/reproduction/files/9e/9e6717ecbcd77161fb56e42265916e7a0ef110641dcba15c12e57691e0d1987f/run_unit_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..242184efa4f4b50b4ade52c6fcc476c478f0120f --- /dev/null +++ b/reproduction/files/9e/9e6717ecbcd77161fb56e42265916e7a0ef110641dcba15c12e57691e0d1987f/run_unit_tests.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# Interface and metric tests with synthetic fixtures. No weights, no downloads. +set -euo pipefail +cd "$(dirname "$0")" +exec python3 -m unittest discover -s . -p 'test_*.py' -v diff --git a/reproduction/files/9e/9e87503585e9da663f0297c14552fd74b6bac405b8f04aaea1e85bb24359cc20/test_lfmc_microbatch.py b/reproduction/files/9e/9e87503585e9da663f0297c14552fd74b6bac405b8f04aaea1e85bb24359cc20/test_lfmc_microbatch.py new file mode 100644 index 0000000000000000000000000000000000000000..3f026e6d89396397666ef15ceba0f6e4b0f88356 --- /dev/null +++ b/reproduction/files/9e/9e87503585e9da663f0297c14552fd74b6bac405b8f04aaea1e85bb24359cc20/test_lfmc_microbatch.py @@ -0,0 +1,92 @@ +"""Microbatch weighting equals official whole-batch masked MSE and gradients.""" + +import copy +import hashlib +import json +from pathlib import Path +import sys +import tempfile +import unittest +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/downstream")) +from lfmc_model import LFMCModel, backward_microbatches +from train_lfmc import evaluate +from olmoearth_pretrain.nn.flexi_vit import EncoderConfig + + +class TestMicrobatch(unittest.TestCase): + def test_unequal_masks_match_whole_batch(self): + torch.set_num_threads(2) + torch.manual_seed(21) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + config = EncoderConfig( + supported_modality_names=["sentinel2_l2a", "sentinel1"], + embedding_size=32, + num_heads=4, + depth=1, + drop_path=0, + ) + torch.save(config.build().state_dict(), root / "encoder.pt") + (root / "config.json").write_text(json.dumps(config.as_dict())) + with (root / "encoder.pt").open("rb") as f: + sha = hashlib.file_digest(f, "sha256").hexdigest() + (root / "provenance.json").write_text( + json.dumps( + {"origin": "own_from_scratch_training", "encoder_sha256": sha} + ) + ) + model = LFMCModel(str(root)) + other = copy.deepcopy(model) + batch = { + "ids": ["a", "b", "c"], + "pixels": { + "sentinel2_l2a": torch.randn(3, 8, 8, 2, 12), + "sentinel1": torch.randn(3, 8, 8, 2, 2), + }, + "valid": { + "sentinel2_l2a": torch.ones(3, 2, 3, dtype=torch.bool), + "sentinel1": torch.ones(3, 2, 1, dtype=torch.bool), + }, + "target": torch.randn(3, 8, 8), + "target_valid": torch.zeros(3, 8, 8, dtype=torch.bool), + } + batch["target_valid"][0, 4, 4] = True + batch["target_valid"][1, 2:4, 2:4] = True + result = model( + batch["pixels"], batch["valid"], batch["target"], batch["target_valid"] + ) + loss = result.loss_dict["regress"] + loss.backward() + micro, count = backward_microbatches( + other, batch, torch.device("cpu"), microbatch=1 + ) + self.assertEqual(count, 5) + self.assertAlmostEqual(float(loss.detach()), micro, places=5) + squared = 0.0 + denom = 0.0 + for a, b in zip(model.parameters(), other.parameters()): + self.assertEqual(a.grad is None, b.grad is None) + if a.grad is not None: + squared += float((a.grad - b.grad).double().square().sum()) + denom += float(a.grad.double().square().sum()) + self.assertLess((squared / denom) ** 0.5, 2e-5) + metrics = evaluate(other, [batch], torch.device("cpu"), microbatch=1) + self.assertEqual(metrics["windows"], 3) + self.assertEqual(metrics["valid_pixels"], 5) + self.assertAlmostEqual(metrics["mse"], micro, places=5) + other.zero_grad(set_to_none=True) + batch["target_valid"].zero_() + empty, count = backward_microbatches( + other, batch, torch.device("cpu"), microbatch=1 + ) + self.assertEqual(empty, 0) + self.assertEqual(count, 0) + self.assertTrue( + all(p.grad is None or not p.grad.any() for p in other.parameters()) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/9e/9eb3dbd50ed32b9547e03d69cf9d11df903802fed0517fd232943933d13572f0/test_risk_protocol.py b/reproduction/files/9e/9eb3dbd50ed32b9547e03d69cf9d11df903802fed0517fd232943933d13572f0/test_risk_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..46d014fe8ca49c0542de57ea754c3c252e0a43cd --- /dev/null +++ b/reproduction/files/9e/9eb3dbd50ed32b9547e03d69cf9d11df903802fed0517fd232943933d13572f0/test_risk_protocol.py @@ -0,0 +1,327 @@ +"""Risk-only v2 protocol, metric behavior, and leakage-boundary regressions.""" + +from __future__ import annotations + +import json +import subprocess +import sys +from datetime import date +from pathlib import Path + +import numpy as np +import pyarrow as pa +import pyarrow.parquet as pq +import pytest +import torch +from sklearn.metrics import average_precision_score, roc_auc_score + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "environment" / "data")) +sys.path.insert(0, str(ROOT / "environment" / "evaluation")) +sys.path.insert(0, str(ROOT / "environment" / "references" / "scaffold")) +sys.path.insert(0, str(ROOT / "docs" / "maintenance" / "legacy-neural")) + +from data import HORIZONS, write_predictions # noqa: E402 +from adapter import history_to_ids # noqa: E402 +from audit import run as audit_run # noqa: E402 +from baseline import Predictor, RiskNet # noqa: E402 +from label_rules import death_label, disease_label # noqa: E402 +from materialize import run as materialize_run # noqa: E402 +from protocol import split_subjects # noqa: E402 +from stage_runtime_data import stage as stage_runtime_data # noqa: E402 +from risk_scoring import (auc_and_average_precision, disease_time_brier, + disease_time_discrimination, + percentile_interval, + normalized_disease_time_brier, read_predictions, + score, weighted_auc) # noqa: E402 +from fixture_data import fixture_source # noqa: E402 + + +def test_split_is_reproducible_and_patient_disjoint(): + a = split_subjects(list(range(100))) + b = split_subjects(list(reversed(range(100)))) + assert a == b + assert [list(a.values()).count(x) for x in ("train", "validation", "test")] == [70, 15, 15] + + +def test_competing_death_and_censor_masks(): + row = {"risk_set": True, "ambiguous_prior": False, "event_days": None, + "cutoff": date(2150, 1, 1), "diagnosis_observation_end": date(2150, 1, 20), + "death_days": None, "death_observation_end": date(2150, 1, 20)} + assert disease_label(row, 30) == (0, False) + assert death_label(row, 30) == (0, False) + row["death_days"] = 10 + assert disease_label(row, 30) == (0, True) + assert death_label(row, 30) == (1, True) + row["event_days"] = 11 + assert disease_label(row, 30) == (0, True) + row["event_days"] = 8 + assert disease_label(row, 30) == (1, True) + row["risk_set"] = False + assert disease_label(row, 30) == (0, False) + row["risk_set"] = True + row["ambiguous_prior"] = True + assert disease_label(row, 30) == (0, False) + + +def test_future_changes_and_diagnosis_row_order_do_not_change_inputs_or_labels(tmp_path): + outputs = [] + for name, future_value, reverse in (("a", "8", False), ("b", "999", True)): + source, output = tmp_path / f"source-{name}", tmp_path / f"output-{name}" + fixture_source(source, future_value=future_value, reverse_diagnoses=reverse) + audit_run(source, output, ROOT / "environment" / "data" / "cms-2018-gem.zip") + materialize_run(source, output, 1) + outputs.append(output) + for split in ("validation", "test"): + for filename in ("samples.parquet", "events.parquet"): + left = pq.read_table(outputs[0] / "public" / split / filename) + right = pq.read_table(outputs[1] / "public" / split / filename) + order = [("sample_id", "ascending")] + if filename == "events.parquet": + order.extend([("available_time", "ascending"), + ("event_time", "ascending"), + ("event_type", "ascending"), ("code", "ascending")]) + assert left.sort_by(order).equals(right.sort_by(order)) + for split in ("validation", "test"): + assert pq.read_table(outputs[0] / "trusted" / split / "label_windows.parquet").equals( + pq.read_table(outputs[1] / "trusted" / split / "label_windows.parquet")) + + +def test_materialization_and_runtime_stage_keep_test_truth_private(tmp_path): + source, materialized = tmp_path / "source", tmp_path / "materialized" + fixture_source(source) + audit_run(source, materialized, ROOT / "environment" / "data" / "cms-2018-gem.zip") + materialize_run(source, materialized, 1) + for split in ("validation", "test"): + truth = materialized / "trusted" / split + assert {path.name for path in truth.iterdir()} == { + "labels.parquet", "label_windows.parquet", "sample_boundaries.parquet"} + boundaries = pq.read_table(truth / "sample_boundaries.parquet").to_pylist() + assert boundaries and {row["split"] for row in boundaries} == {split} + for legacy in ("labels.parquet", "label_windows.parquet", "sample_boundaries.parquet"): + assert not (materialized / "trusted" / legacy).exists() + development, private = stage_runtime_data(materialized, tmp_path / "runtime") + assert not (development / "public" / "test").exists() + assert not (development / "trusted" / "test").exists() + assert not (development / "working.duckdb").exists() + assert (development / "trusted" / "validation" / "label_windows.parquet").is_file() + assert (private / "trusted" / "test" / "label_windows.parquet").is_file() + assert (private / "public" / "test" / "samples.parquet").is_file() + + +def test_adapter_ignores_ids_and_future_metadata(): + adapter = {"vocab": {"gender:F": 1, "age_decade:50": 2, "diagnosis:A00": 3}, + "lab_bins": {}, "max_events": 10} + base = {"gender": "F", "approx_age": 55, + "events": [{"event_type": "diagnosis", "code": "A00"}]} + altered = {**base, "subject_id": 99, "sample_id": "future", "last_followup": 999, + "future_admission_count": 11, + "events": [{"event_type": "diagnosis", "code": "A00", + "hadm_id": 123, "future_status": "died later"}]} + assert history_to_ids(base, adapter) == history_to_ids(altered, adapter) + + +def test_prediction_contract_is_direct_13_point_and_monotone(tmp_path): + path = tmp_path / "predictions.parquet" + good = np.linspace(0.01, 0.2, len(HORIZONS)).tolist() + pq.write_table(pa.Table.from_pylist([{ + "sample_id": "s", "disease_risk": good, "death_risk": good}]), path) + disease, death = read_predictions(path, ["s"], 1) + assert disease.shape == (1, 1, 13) and death.shape == (1, 13) + bad = good.copy() + bad[5] = bad[4] - .01 + pq.write_table(pa.Table.from_pylist([{ + "sample_id": "s", "disease_risk": bad, "death_risk": good}]), path) + with pytest.raises(ValueError, match="decreases"): + read_predictions(path, ["s"], 1) + pq.write_table(pa.Table.from_pylist([{ + "sample_id": "s", "disease_risk": [.1] * 4, "death_risk": [.1] * 4}]), path) + with pytest.raises(ValueError, match="direct time grid"): + read_predictions(path, ["s"], 1) + + +def test_primary_brier_detects_timing_identity_and_miscalibration(): + # Four patients, two diseases. Disease A first appears by day 60 in two; + # disease B by day 180 in the other two. + labels = np.zeros((4, 2, len(HORIZONS)), dtype=np.uint8) + labels[:2, 0, np.asarray(HORIZONS) >= 60] = 1 + labels[2:, 1, np.asarray(HORIZONS) >= 180] = 1 + valid = np.ones_like(labels, dtype=bool) + exact = labels.astype(np.float32) + exact_score, _ = disease_time_brier(labels, exact, valid) + early = np.roll(exact, -1, axis=2) + early[:, :, -1] = exact[:, :, -1] + late = np.roll(exact, 1, axis=2) + late[:, :, 0] = 0 + swapped = exact[:, ::-1, :] + assert exact_score == 0 + assert disease_time_brier(labels, early, valid)[0] > exact_score + assert disease_time_brier(labels, late, valid)[0] > exact_score + assert disease_time_brier(labels, swapped, valid)[0] > exact_score + + calibrated = np.broadcast_to(labels.mean(axis=0), labels.shape).copy() + overconfident = np.where(calibrated > 0, .99, .01).astype(np.float32) + assert disease_time_brier(labels, overconfident, valid)[0] > disease_time_brier( + labels, calibrated, valid)[0] + + +def test_normalized_brier_uses_frozen_cell_denominators(): + labels = np.zeros((2, 2, 1), dtype=np.uint8) + valid = np.ones_like(labels, dtype=bool) + prediction = np.asarray([[[.01], [.1]], [[.01], [.1]]], dtype=np.float32) + denominators = np.asarray([[.001], [.01]]) + raw, _ = disease_time_brier(labels, prediction, valid) + normalized, details = normalized_disease_time_brier( + labels, prediction, valid, denominators) + assert raw == pytest.approx(.00505) + assert normalized == pytest.approx(.55) + assert details[0]["normalized_time_brier"] == pytest.approx(.1) + assert details[1]["normalized_time_brier"] == pytest.approx(1.0) + + +def test_primary_auc_is_disease_first_time_average_and_skips_single_class_cells(): + labels = np.asarray([ + [[0, 0], [0, 0]], + [[1, 0], [1, 0]], + [[0, 1], [1, 0]], + [[1, 1], [1, 0]], + ], dtype=np.uint8) + prediction = np.asarray([ + [[.1, .1], [.1, .1]], + [[.9, .2], [.6, .2]], + [[.8, .8], [.7, .3]], + [[.2, .9], [.8, .4]], + ], dtype=np.float32) + valid = np.ones_like(labels, dtype=bool) + summary, details = disease_time_discrimination(labels, prediction, valid) + # Disease 0 has AUCs .75 and 1; disease 1 contributes only its first cell. + expected = ((.75 + 1.0) / 2 + 1.0) / 2 + assert summary["macro_time_averaged_auroc"] == pytest.approx(expected) + assert summary["valid_diseases"] == 2 + assert summary["valid_disease_time_cells"] == 3 + assert details[1]["timepoints"][1]["auroc"] is None + assert details[1]["timepoints"][1]["reason"] == "single_class" + pooled = roc_auc_score(labels.reshape(-1), prediction.reshape(-1)) + assert summary["macro_time_averaged_auroc"] != pytest.approx(pooled) + + +def test_bootstrap_interval_reports_unavailable_metric(): + assert percentile_interval([None, None]) is None + + +def test_weighted_auc_matches_expanded_patient_bootstrap(): + y = np.asarray([0, 1, 0, 1], dtype=np.uint8) + p = np.asarray([.2, .8, .2, .4]) + weights = np.asarray([2, 1, 3, 2], dtype=np.float64) + expanded = np.repeat(np.arange(len(y)), weights.astype(int)) + assert weighted_auc(y, p, weights) == pytest.approx( + roc_auc_score(y[expanded], p[expanded])) + + +def test_combined_discrimination_matches_reference_with_ties(): + y = np.asarray([0, 1, 0, 1, 1], dtype=np.uint8) + p = np.asarray([.2, .8, .2, .4, .8]) + auc, ap = auc_and_average_precision(y, p) + assert auc == pytest.approx(roc_auc_score(y, p)) + assert ap == pytest.approx(average_precision_score(y, p)) + + +def _write_scoring_fixture(root: Path): + public, trusted = root / "public", root / "trusted" + public.mkdir(parents=True) + trusted.mkdir() + codes = ["A00", "B00"] + sample_rows = [ + {"sample_id": "s0", "gender": "F", "approx_age": 50, "cutoff": date(2150, 1, 1)}, + {"sample_id": "s1", "gender": "M", "approx_age": 70, "cutoff": date(2150, 1, 1)}, + {"sample_id": "s2", "gender": "F", "approx_age": 80, "cutoff": date(2150, 1, 1)}, + {"sample_id": "s3", "gender": "M", "approx_age": 40, "cutoff": date(2150, 1, 1)}, + ] + pq.write_table(pa.Table.from_pylist(sample_rows), public / "samples.parquet") + # The panel reward reads diagnosis history; one unrelated diagnosis is enough here. + pq.write_table(pa.Table.from_pylist([{"sample_id": "s0", "event_type": "diagnosis", + "code": "Z00"}]), public / "events.parquet") + (public / "manifest.json").write_text(json.dumps({ + "schema": "natural-disease-progression-input/v2", + "task": "first-recorded-disease-time-and-death-risk", + "horizons_days": list(HORIZONS), "scored_diseases": codes, "split": "validation"})) + label_rows = [] + event_day = {("s0", "A00"): 60, ("s0", "B00"): 60, ("s1", "A00"): 180} + for sample in sample_rows: + for code in codes: + row = {"sample_id": sample["sample_id"], "disease_code": code, + "risk_set": True, "ambiguous_prior": False, + "event_days": event_day.get((sample["sample_id"], code)), + "cutoff": date(2150, 1, 1), + "diagnosis_observation_end": date(2152, 1, 1), + "death_days": None, "death_observation_end": date(2152, 1, 1)} + for horizon in HORIZONS: + row[f"disease_label_{horizon}"], row[f"disease_valid_{horizon}"] = disease_label(row, horizon) + row[f"death_label_{horizon}"], row[f"death_valid_{horizon}"] = death_label(row, horizon) + label_rows.append(row) + pq.write_table(pa.Table.from_pylist(label_rows), trusted / "label_windows.parquet") + normalization_rows = [{"disease_code": code, "horizon_days": horizon, + "train_valid": 100, "train_positive": 10, + "train_negative": 90, "age_sex_oof_brier": 1.0, + "denominator_brier": 1.0, "normalization_weight": 1.0, + "floor_applied": False} + for code in codes for horizon in HORIZONS] + pq.write_table(pa.Table.from_pylist(normalization_rows), + trusted / "risk_normalization.parquet") + boundaries = [{"sample_id": row["sample_id"], "split": "validation", + "cutoff": date(2150, 1, 1), "death_date": None, "death_days": None, + "diagnosis_observation_end": date(2152, 1, 1), + "death_observation_end": date(2152, 1, 1), + "any_future_disease_record_365": row["sample_id"] in {"s0", "s1"}} + for row in sample_rows] + boundaries[-1]["diagnosis_observation_end"] = date(2150, 6, 1) + pq.write_table(pa.Table.from_pylist(boundaries), trusted / "sample_boundaries.parquet") + return public, trusted, sample_rows, codes, event_day + + +def test_end_to_end_scorer_has_only_risk_outputs(tmp_path): + public, trusted, samples, codes, event_day = _write_scoring_fixture(tmp_path) + prediction_rows = [] + for sample in samples: + disease = [] + for code in codes: + day = event_day.get((sample["sample_id"], code)) + disease.extend([float(day is not None and day <= h) for h in HORIZONS]) + prediction_rows.append({"sample_id": sample["sample_id"], + "disease_risk": disease, + "death_risk": [0.0] * len(HORIZONS)}) + path = tmp_path / "predictions.parquet" + pq.write_table(pa.Table.from_pylist(prediction_rows), path) + report = score(public, trusted, path, bootstrap=2) + assert report["schema"] == "natural-disease-progression-report/v3" + assert report["primary"]["macro_time_averaged_auroc"] == 1.0 + assert report["primary"]["valid_diseases"] == 2 + assert report["auxiliary"] == { + "raw_disease_time_brier_macro": 0.0, + "age_sex_normalized_disease_time_brier": 0.0, + } + assert report["cohort"] == {"all_samples": 4, "primary_complete_year": 3, + "partial_observation_outside_primary": 1} + assert set(report["horizons"]) == set(map(str, HORIZONS)) + assert report["horizons"]["365"]["frozen_diseases"] == 2 + assert "trajectories" not in pq.read_schema(path).names + assert report["strata"]["no_future_disease_record"]["n"] == 1 + assert report["strata"]["future_disease_record"]["n"] == 2 + + +def test_starter_writes_risk_only_predictions(tmp_path): + output_dir = tmp_path / "output" + disease = np.linspace(.01, .2, len(HORIZONS), dtype=np.float32).reshape(1, 1, -1) + death = np.linspace(.02, .1, len(HORIZONS), dtype=np.float32).reshape(1, -1) + write_predictions(output_dir, ["s"], disease, death, disease_count=1) + schema = pq.read_schema(output_dir / "predictions.parquet") + assert schema.names == ["sample_id", "disease_risk", "death_risk"] + with pytest.raises(ValueError, match="nondecreasing"): + write_predictions(tmp_path / "bad", ["s"], disease[:, :, ::-1], death, 1) + + +def test_obsolete_trajectory_protocol_modules_are_absent(): + for relative in ("environment/data/derive_trajectory.py", + "environment/evaluation/joint_scoring.py", + "environment/evaluation/trajectory.py"): + assert not (ROOT / relative).exists() diff --git a/reproduction/files/9e/9eb5943f537cc11091b6c1d1a040c332fb03f0076aee990dd25f82dcd7cbd39c/sealed_sandbox.py b/reproduction/files/9e/9eb5943f537cc11091b6c1d1a040c332fb03f0076aee990dd25f82dcd7cbd39c/sealed_sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..55999228f080948e6719d435dad74615cac044f0 --- /dev/null +++ b/reproduction/files/9e/9eb5943f537cc11091b6c1d1a040c332fb03f0076aee990dd25f82dcd7cbd39c/sealed_sandbox.py @@ -0,0 +1,231 @@ +"""Offline inference boundary for the Beaker-only sealed verifier adapter. + +Beaker provides the outer container. Landlock limits candidate filesystem access; +seccomp allows only local Unix sockets and prevents widening CPU affinity. UID +10001 has no capabilities. The default memory policy requires the benchmark +limit. An explicit operator option accepts Beaker's larger kernel-enforced +allocation and records that resource deviation. +""" +import ctypes +import errno +import json +import os +from pathlib import Path +import resource +import signal +import subprocess +import time + +UID = 10001 +MEMORY_POLICY = 'benchmark-limit' +SAMPLED_MEMORY_MAX = 0 + + +class ResourceExceeded(RuntimeError): + pass + + +def memory_peak(): + global SAMPLED_MEMORY_MAX + for path in (Path('/sys/fs/cgroup/memory.peak'), + Path('/sys/fs/cgroup/memory/memory.max_usage_in_bytes')): + if path.is_file(): + return int(path.read_text()) + if MEMORY_POLICY == 'beaker-allocation': + current = int(Path('/sys/fs/cgroup/memory.current').read_text()) + SAMPLED_MEMORY_MAX = max(SAMPLED_MEMORY_MAX, current) + return SAMPLED_MEMORY_MAX + raise RuntimeError('Kernel cgroup memory high-water accounting is required') + + +def allocated_memory_limit(): + for path in (Path('/sys/fs/cgroup/memory.max'), + Path('/sys/fs/cgroup/memory/memory.limit_in_bytes')): + if path.is_file(): + raw = path.read_text().strip() + if raw.isdigit(): + return int(raw) + raise RuntimeError('A finite Beaker kernel memory limit is required') + + +def effective_memory_limit(requested): + if MEMORY_POLICY == 'benchmark-limit': + return requested + if MEMORY_POLICY != 'beaker-allocation': + raise ValueError(f'Unknown memory policy: {MEMORY_POLICY}') + allocated = allocated_memory_limit() + if allocated < requested: + raise ResourceExceeded('Beaker allocated less memory than requested') + return allocated + + +def memory_receipt(requested): + kernel_peak = any(p.is_file() for p in ( + Path('/sys/fs/cgroup/memory.peak'), + Path('/sys/fs/cgroup/memory/memory.max_usage_in_bytes'))) + return {'memory_policy': MEMORY_POLICY, + 'benchmark_requested_memory_bytes': requested, + 'effective_memory_limit_bytes': effective_memory_limit(requested), + 'observed_memory_max_bytes': memory_peak(), + 'memory_measurement': 'kernel high-water' if kernel_peak else 'sampled memory.current; not a true peak', + 'benchmark_ram_cap_enforced': MEMORY_POLICY == 'benchmark-limit', + 'memory_enforcement': ('benchmark high-water acceptance gate' if MEMORY_POLICY == 'benchmark-limit' + else 'Beaker kernel allocation; larger RAM explicitly accepted')} + + +def seccomp(): + lib = ctypes.CDLL('libseccomp.so.2', use_errno=True) + class Compare(ctypes.Structure): + _fields_ = [('arg', ctypes.c_uint), ('op', ctypes.c_int), + ('a', ctypes.c_uint64), ('b', ctypes.c_uint64)] + lib.seccomp_init.argtypes = [ctypes.c_uint32] + lib.seccomp_init.restype = ctypes.c_void_p + lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] + lib.seccomp_syscall_resolve_name.restype = ctypes.c_int + lib.seccomp_rule_add_array.argtypes = [ctypes.c_void_p, ctypes.c_uint32, + ctypes.c_int, ctypes.c_uint, ctypes.POINTER(Compare)] + lib.seccomp_load.argtypes = [ctypes.c_void_p] + lib.seccomp_release.argtypes = [ctypes.c_void_p] + ctx = lib.seccomp_init(0x7fff0000) + if not ctx: + raise RuntimeError('seccomp_init failed') + try: + for syscall in (b'socket', b'socketpair'): + comparison = Compare(0, 1, 1, 0) # domain != AF_UNIX + rc = lib.seccomp_rule_add_array(ctx, 0x50000 | errno.EPERM, + lib.seccomp_syscall_resolve_name(syscall), 1, ctypes.byref(comparison)) + if rc: + raise RuntimeError(f'seccomp socket rule failed: {rc}') + for syscall in (b'sched_setaffinity', b'ptrace', b'process_vm_writev'): + rc = lib.seccomp_rule_add_array(ctx, 0x50000 | errno.EPERM, + lib.seccomp_syscall_resolve_name(syscall), 0, None) + if rc: + raise RuntimeError(f'seccomp rule failed: {rc}') + if lib.seccomp_load(ctx): + raise RuntimeError('seccomp_load failed') + finally: + lib.seccomp_release(ctx) + + +def filesystem(readonly, writable): + """Restrict this process and descendants, without changing any host mount.""" + libc = ctypes.CDLL(None, use_errno=True) + abi = libc.syscall(444, 0, 0, 1) + if abi < 1: + raise RuntimeError(f'Landlock is required, got ABI {abi}') + class Ruleset(ctypes.Structure): + _fields_ = [('handled_access_fs', ctypes.c_uint64)] + class Beneath(ctypes.Structure): + _pack_ = 1 + _fields_ = [('allowed_access', ctypes.c_uint64), ('parent_fd', ctypes.c_int)] + # Older Beaker kernels expose ABI1. Read-only model/input ownership and + # permissions also deny path-based truncate operations, which ABI1 does not + # mediate. Operator artifacts are root-owned and never writable by UID10001. + handled = (1 << (15 if abi >= 3 else 14 if abi >= 2 else 13)) - 1 + read = (1 << 0) | (1 << 2) | (1 << 3) + attr = Ruleset(handled) + rules = libc.syscall(444, ctypes.byref(attr), ctypes.sizeof(attr), 0) + if rules < 0: + raise OSError(ctypes.get_errno(), 'landlock_create_ruleset') + try: + for names, access in ((readonly, read), (writable, handled)): + for name in names: + path = Path(name) + if not path.exists(): + continue + fd = os.open(path, os.O_PATH | os.O_CLOEXEC) + try: + permitted = access if path.is_dir() else access & ((1 << 0) | (1 << 1) | (1 << 2) | (1 << 14)) + rule = Beneath(permitted, fd) + if libc.syscall(445, rules, 1, ctypes.byref(rule), 0): + raise OSError(ctypes.get_errno(), f'landlock_add_rule: {path}') + finally: + os.close(fd) + if libc.prctl(38, 1, 0, 0, 0) or libc.syscall(446, rules, 0): + raise OSError(ctypes.get_errno(), 'landlock_restrict_self') + finally: + os.close(rules) + + +def runtime_paths(): + # /opt/task-workspace, /operator, /run-state and /sealed are deliberately absent. + return [Path(p) for p in ('/usr', '/bin', '/sbin', '/lib', '/lib64', '/etc', + '/opt/conda', '/opt/olmoearth', '/proc', '/sys')] + + +def kill_uid(): + for path in Path('/proc').iterdir(): + if not path.name.isdigit(): + continue + try: + uid = int(next(line for line in (path / 'status').read_text().splitlines() + if line.startswith('Uid:')).split()[1]) + if uid == UID: + os.kill(int(path.name), signal.SIGKILL) + except (OSError, StopIteration): + pass + + +def run(argv, *, cwd, env, logfile, cpus, memory_bytes, seconds, + readonly=(), writable=(), untrusted=True, file_limit=None): + if seconds <= 0: + raise ResourceExceeded('Verifier time budget exhausted') + memory_limit = effective_memory_limit(memory_bytes) + if memory_peak() > memory_limit: + raise ResourceExceeded('Container memory peak already exceeds verifier budget') + affinity = sorted(os.sched_getaffinity(0))[:cpus] + if len(affinity) != cpus: + raise RuntimeError('Not enough allocated CPUs') + # Intel/LLVM OpenMP probes sched_setaffinity even with its default "none" + # setting and aborts when the syscall is denied. Placement is already fixed + # by this wrapper; disable only OpenMP's own affinity interface, retaining + # the requested thread count and the enforced process affinity. + env = {**env, 'KMP_AFFINITY': 'disabled', 'OMP_PROC_BIND': 'false'} + + def restrict(): + os.sched_setaffinity(0, affinity) + libc = ctypes.CDLL(None, use_errno=True) + if libc.prctl(38, 1, 0, 0, 0): + raise OSError(ctypes.get_errno(), 'NO_NEW_PRIVS') + if untrusted: + os.setgroups([]) + os.setgid(UID) + os.setuid(UID) + if file_limit: + resource.setrlimit(resource.RLIMIT_FSIZE, (file_limit, file_limit)) + # NVIDIA initialization needs writable procfs access. The outer + # container's procfs protections, UID boundary and denied ptrace / + # process_vm_writev still protect the root supervisor. + filesystem([*runtime_paths(), *readonly], [Path('/dev'), Path('/proc'), *writable]) + seccomp() + + started = time.monotonic() + process = None + try: + with Path(logfile).open('wb') as stream: + process = subprocess.Popen(argv, cwd=cwd, env=env, preexec_fn=restrict, + stdout=stream, stderr=subprocess.STDOUT, close_fds=True, start_new_session=True) + while process.poll() is None: + if memory_peak() > memory_limit: + raise ResourceExceeded('Verifier cgroup memory high-water exceeds budget') + if time.monotonic() - started >= seconds: + raise subprocess.TimeoutExpired(argv, seconds) + time.sleep(.1) + if memory_peak() > memory_limit: + raise ResourceExceeded('Verifier memory peak exceeded budget before exit') + if process.returncode: + raise subprocess.CalledProcessError(process.returncode, argv) + finally: + if process is not None: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + if untrusted: + kill_uid() + return {'elapsed_seconds': time.monotonic() - started, + 'cpus': affinity, **memory_receipt(memory_bytes), + 'openmp_affinity': 'disabled; CPU placement enforced by wrapper', + 'network': 'seccomp allows AF_UNIX only', + 'filesystem': 'Landlock and UID10001 with root-owned immutable inputs' if untrusted else 'trusted scorer'} diff --git a/reproduction/files/9f/9fae359cee0fd807321edd1ea971f6a3a7e7dc56be868cf3a9414977e963b4f7/case_spec.py b/reproduction/files/9f/9fae359cee0fd807321edd1ea971f6a3a7e7dc56be868cf3a9414977e963b4f7/case_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..7aeba96e25eea9caee6d341e52b6739a3e5bdbf6 --- /dev/null +++ b/reproduction/files/9f/9fae359cee0fd807321edd1ea971f6a3a7e7dc56be868cf3a9414977e963b4f7/case_spec.py @@ -0,0 +1,139 @@ +"""Executable native-replay profiles derived from the immutable Research v2 data. + +These are organizer profiles, not recovered paper protocols or score certification. +Both development replay and the Harbor verifier use these exact profiles. +""" +import hashlib +import json +import math +from pathlib import Path +import sys + +from protocol import InfrastructureError +from metrics import CASE_METRICS, VERSION as METRIC_VERSION, definition, registry_hash + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'data')) +from public_release import load_release, digest +from materialize import file_digest + +PROFILE_VERSION = 'hydrogym-native-replay/v1' +DATA = Path(__file__).resolve().parent.parent / 'data' + + +def specifications(): + release = load_release() + if {c['id'] for c in release['cases']} != set(CASE_METRICS): + raise InfrastructureError('Frozen data and physical metric coverage differ') + cases = [] + evidence = {c['case']: c for c in json.loads((DATA / 'cost-evidence-coverage-v1.json').read_text())['cases']} + for row in release['cases']: + profile = row['runtime_profile'] + name, backend = row['id'], row['backend'] + horizon = row['selection_review']['native_episode_controls_for_costing'] + observation_shape = profile.get('observation_shape', [128 if name.startswith('Channel') else 64]) + action_shape = profile.get('action_shape', [24 if name.startswith('Channel') else 4]) + case = dict(id=name, environment=name, family=row['family'], backend=backend, + observation_size=math.prod(observation_shape), action_size=math.prod(action_shape), + observation_shape=observation_shape, action_shape=action_shape, + horizon=horizon, seeds=[123], solver_processes=row['required_solver_gpus'], + timeout_sec=max(1800, math.ceil(900 + 2 * (evidence[name]['startup_seconds'] + + horizon * evidence[name]['seconds_per_control']))), + runtime_profile=profile, runtime_profile_sha256=digest(profile), + initialization='Native reset and supplied source initial states; seed 123. No independent-flow-sample claim.', + provenance='Organizer native replay profile adopted unchanged from the approved source/cost specification; not paper certification.', + episode_end='native', strict_horizon=True, primary_metric=definition(name)) + if backend == 'maia': + case['env_kwargs'] = {'probe_locations': profile['probe_locations'], + 'obs_normalization_strategy': 'none'} + # Verify these defaults at runtime; do not silently override source physics. + case['native_settings'] = {} + cases.append(case) + return {'profile_version': PROFILE_VERSION, 'status': 'executable-not-benchmark-certified', + 'metric_version': METRIC_VERSION, 'metrics_sha256': registry_hash(), + 'data_release_id': release['release_id'], 'data_release_sha256': digest(release), + 'source_revision': release['source']['revision'], 'cases': cases} + + +# The scored verifier suite: every 2D case, and one 3D case per family (cube included). Side by side on +# 8 H100s it takes about 2.3 h, set by Cube_3D_Re3700 (3.9 h when other jobs share the GPUs). Every family, dimension and solver +# backend stays scored; the dropped 3D instances repeat a family at 2.0-5.2 H100-hours each. The complete +# 39-case suite stays available for development replays (`--case all`). +VERIFIER_CASES = ( + 'Cylinder_2D_Re200', 'Cylinder_2D_Re1000', 'Cylinder_2D_Re3900', + 'Nozzle2D_coarse', 'Nozzle2D_fine', 'Kolmogorov_2D', + 'NACA0012_2D_Re100_AOA20', 'NACA0012_2D_Re100_AOA40', 'NACA0012_2D_Re1000_AOA20', 'NACA0012_2D_Re1000_AOA40', + 'NACA0012Gust_2D_Re100_AOA20', 'NACA0012Gust_2D_Re100_AOA40', + 'NACA0012Gust_2D_Re1000_AOA20', 'NACA0012Gust_2D_Re1000_AOA40', + 'Pinball_2D_Re30', 'Pinball_2D_Re75', 'Pinball_2D_Re100', 'Pinball_2D_Re150', + 'SquareCylinder_2D_Re200', 'SquareCylinder_2D_Re1000', + 'Channel_3D_Retau180', 'Pinball_3D_Re100', 'NACA0012Gust_3D_Re100_AOA20', 'NACA0012Gust_3D_Re1000_AOA20', + 'Sphere_3D_Re300', 'Cube_3D_Re3700', +) + + +def estimated_seconds(case_id): + """Single-replay cost from the frozen cost evidence (startup + controls x seconds per control).""" + evidence = {c['case']: c for c in json.loads((DATA / 'cost-evidence-coverage-v1.json').read_text())['cases']} + row = {c['id']: c for c in load_release()['cases']}[case_id] + horizon = row['selection_review']['native_episode_controls_for_costing'] + return evidence[case_id]['startup_seconds'] + horizon * evidence[case_id]['seconds_per_control'] + + +def select_cases(names): + spec = specifications() + indexed = {c['id']: c for c in spec['cases']} + if names == ['all']: + names = list(indexed) + elif names == ['verifier']: + if set(VERIFIER_CASES) - indexed.keys(): + raise InfrastructureError('Verifier suite names a case outside the frozen release') + names = [n for n in indexed if n in VERIFIER_CASES] + if not names or len(set(names)) != len(names) or set(names) - indexed.keys(): + raise InfrastructureError('Select unique frozen case IDs, or --case all') + return spec, [indexed[name] for name in names] + + +def verify_resources(data, cases): + data = data.resolve() + release = load_release() + if not data.is_dir() or json.loads((data / 'release.json').read_text()) != release: + raise InfrastructureError('Mounted resources differ from the frozen release') + receipt = json.loads((data / 'materialized.json').read_text()) + index = json.loads((DATA / 'source-files.json').read_text()) + names = {c['environment'] for c in cases} + if (receipt.get('data_release_id') != release['release_id'] or + receipt.get('data_release_sha256') != digest(release) or + receipt.get('source_index_sha256') != digest(index) or + receipt.get('revision') != release['source']['revision'] or + not names.issubset(receipt.get('verified_directories', []))): + raise InfrastructureError('Missing verified materialization identity or selected case') + # Large inputs were fully hashed by materialization and must be mounted read-only. + # Recheck all sizes and small configuration hashes on each independent replay. + for item in index['files']: + if item['rfilename'].split('/')[0] not in names: + continue + path = data / 'environments' / item['rfilename'] + if path.resolve() != path or not path.is_file() or path.stat().st_size != item['size']: + raise InfrastructureError(f'Missing/truncated/redirected resource: {path}') + if item['size'] <= 1024 * 1024: + lfs = item.get('lfs') + if file_digest(path, 'sha256' if lfs else 'sha1') != (lfs['sha256'] if lfs else item['blobId']): + raise InfrastructureError(f'Changed source configuration: {path}') + for case in cases: + if case['environment'] == 'Channel_3D_Retau180': + adapter = Path(__file__).with_name('native_channel.py') + if hashlib.sha256(adapter.read_bytes()).hexdigest() != case['runtime_profile']['adapter_sha256']: + raise InfrastructureError('Frozen Channel actuator-clock adapter changed') + + +def local_only(data, case, scratch): + import os + import hydrogym.data_manager as manager + manager.HF_AVAILABLE = False + expected = data / 'environments' / case['environment'] + for kind in ('maiagym', 'jaxfluidsgym'): + cached = Path.home() / '.cache' / kind / case['environment'] + if cached.exists() and cached.resolve() != expected.resolve(): + raise InfrastructureError(f'Legacy cache shadows pinned source: {cached}') + os.environ['HF_HUB_OFFLINE'] = '1' + os.environ['HF_HUB_CACHE'] = str(scratch / 'unused-hub-cache') diff --git a/reproduction/files/a0/a03fdc1c3d2d2dc6db2caecb388534f6689175436e381d688a5e81d56cfe8131/docker-compose.yaml b/reproduction/files/a0/a03fdc1c3d2d2dc6db2caecb388534f6689175436e381d688a5e81d56cfe8131/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..122e4f99197cf6ed1218daa74d0548b4f73e8a55 --- /dev/null +++ b/reproduction/files/a0/a03fdc1c3d2d2dc6db2caecb388534f6689175436e381d688a5e81d56cfe8131/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: .. + dockerfile: environment/Dockerfile + target: verifier + # The replayed policy needs no network; the verifier is offline end to end. + network_mode: none + shm_size: "32gb" + volumes: + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR to the prepared release} + target: /data + read_only: true + bind: + create_host_path: false + healthcheck: + test: ["CMD", "bash", "/opt/hydrogym-task/evaluation/evaluate_native.sh", "--data", "/data", "--case", "all", "--preflight"] + interval: 10s + timeout: 10s + retries: 1 diff --git a/reproduction/files/a1/a1640e03aa2b049e00063c0d360277f3f83d180a6f053c517b91e0bc770a9ec7/task_profiles.py b/reproduction/files/a1/a1640e03aa2b049e00063c0d360277f3f83d180a6f053c517b91e0bc770a9ec7/task_profiles.py new file mode 100644 index 0000000000000000000000000000000000000000..92ac674914c8c387d06eb2aaa865052d02db978b --- /dev/null +++ b/reproduction/files/a1/a1640e03aa2b049e00063c0d360277f3f83d180a6f053c517b91e0bc770a9ec7/task_profiles.py @@ -0,0 +1,224 @@ +"""Explicit development-only mounts and budgets for the added benchmark tasks.""" +from pathlib import Path +import importlib +import json +import os +import shutil + + +PROFILES = { + "crystal-structure-generation": { + "cpus": 64, "memory_gib": 512, "shm_gib": 32, + "entries": [(f"mp20/{p}", f"mp20/{p}") for p in ("train.csv", "val.csv", "manifest.json")] + + [("scorer-assets", "scorer-assets")], + "imports": ["numpy", "pymatgen.core", "omg"], + "python_bin": "/opt/conda/bin", "entrypoint": "generate.sh", + }, + "fluid-flow-control": { + "cpus": 64, "memory_gib": 1536, "shm_gib": 32, + "entries": [("release.json", "release/release.json"), + ("materialized.json", "release/materialized.json"), + ("environments", "release/environments")], + "imports": ["numpy", "hydrogym", "pyarrow"], + "python_bin": "/home/easybuild/venvs/hydrogym_gpu/bin", "entrypoint": "infer.sh", + }, + "molecular-pretraining-transfer": { + "cpus": 96, "memory_gib": 768, "shm_gib": 256, + "entries": [("public/pretrain", "pretrain"), ("public/downstream", "downstream")], + "imports": ["numpy", "rdkit", "lmdb", "unicore"], + "python_bin": "/opt/conda/bin", "entrypoint": "infer.sh", + }, + "pde-surrogate": { + "cpus": 64, "memory_gib": 512, "shm_gib": 16, + "entries": [(p, p) for p in ("ape2d-full", "pdearena-ns", "well-active_matter", + "well-turbulent_radiative_layer_2D", "release-receipt.json", "materialize-receipt.json")], + "imports": ["numpy", "h5py"], + "python_bin": "/usr/local/bin", "entrypoint": "infer.sh", + "check": ["python", "/opt/pde-surrogate/check_agent_mount.py", "/workspace/data", "/workspace/data/split.json"], + }, + "probabilistic-global-weather": { + "cpus": 64, "memory_gib": 512, "shm_gib": 64, "storage_gib": 2048, + "entries": [("training-2017-2020", "training"), + ("development-inputs-2021", "development/inputs"), + ("development-weather-2021", "development/weather"), + ("development-precipitation-2021", "development/precipitation")], + "imports": ["numpy", "jax", "xarray", "weathernext"], "gpu_runtime": "jax", + "python_bin": "/opt/weather-python/bin", "entrypoint": "infer.sh", + "check": ["bwrap", "--unshare-all", "--ro-bind", "/", "/", "--proc", "/proc", + "--dev", "/dev", "/bin/true"], + }, + "protein-design": { + "cpus": 64, "memory_gib": 512, "shm_gib": 16, + "entries": [("development/fit", "fit"), ("development/tune", "tune")], + "imports": ["numpy", "gemmi", "atomworks", "lightning"], + "python_bin": "/opt/conda/bin", "entrypoint": "infer.sh", + }, + "protein-sequence-modeling": { + "cpus": 64, "memory_gib": 512, "shm_gib": 16, + "entries": [(f"public/development/{p}", p) for p in + ("fit", "tune", "pretrain", "manifest.json", "stats.json")], + "imports": ["numpy"], + "python_bin": "/opt/conda/bin", "entrypoint": "infer.sh", + }, + "timeseries-forecasting": { + "cpus": 64, "memory_gib": 512, "shm_gib": 16, + "entries": [(p, p) for p in ("gifteval_pretrain", "valid", "materialize-receipt.json")], + "imports": ["numpy", "pyarrow"], + "python_bin": "/usr/local/bin", "entrypoint": "infer.sh", + }, + "surface-code-decoding": { + "cpus": 64, "memory_gib": 512, "shm_gib": 16, + "entries": [(f"development/{p}", p) for p in + ("release.json", "inventory.json", "train", "validation", "reference")], + "imports": ["numpy", "stim", "pymatching", "jax"], + "gpu_runtime": "jax", + "python_bin": "/opt/qec/.venv/bin", "entrypoint": "infer.sh", + "check": ["python", "/opt/qec/check_resources.py", "--data-root", "/workspace/data"], + }, + "fruit-fly-neuron-reconstruction": { + "cpus": 64, "memory_gib": 512, "shm_gib": 16, + "entries": [(p, p) for p in ("training", "validation", "runtime")], + "imports": ["numpy", "scipy", "h5py"], + "python_bin": "/usr/local/bin", "entrypoint": "package.json", + }, + "mass-spectrometry-molecule-retrieval": { + "cpus": 64, "memory_gib": 512, "shm_gib": 32, + "entries": [(f"development/{p}", p) for p in + ("manifest.json", "train.jsonl", "validation.jsonl", + "validation_candidate_pools.jsonl", "glacier", "synthetic_augmentation")], + "imports": ["numpy", "rdkit"], + "python_bin": "/opt/conda/bin", "entrypoint": "infer.sh", + "check": ["python", "/workspace/data/check_resources.py", "--data-root", "/workspace/data"], + }, + "atomistic-materials": { + "cpus": 128, "memory_gib": 768, "shm_gib": 64, + "entries": [(p, p) for p in ("pool", "val", "baselines/mp-standard")], + "imports": ["ase", "fairchem.core", "phonopy", "phono3py"], + "python_bin": "/opt/venv/bin", "entrypoint": "calculator.py", + }, + "protein-folding-prediction": { + "cpus": 64, "memory_gib": 512, "shm_gib": 32, + "entries": [("manifests", "manifests"), ("objects", "objects"), + ("features", "features"), ("foldbench-val", "foldbench"), ("models", "models")], + "imports": ["numpy", "biotite", "esm", "transformers"], + "python_bin": "/opt/conda/bin", "entrypoint": "infer.sh", + }, + "single-cell-perturbation-prediction": { + "cpus": 64, "memory_gib": 512, "shm_gib": 32, + "entries": [(f"dev/{p}", p) for p in + ("manifest.json", "splits.json", "gene_panel.csv", + "gene_panel_intersection.json", "train", "priors", "se600m", + "test/ctx_near/public", "test/ctx_mid/public", "test/ctx_far/public")], + "imports": ["numpy", "anndata", "h5py", "state"], + "python_bin": "/opt/conda/bin", "entrypoint": "infer.sh", + }, + "genome-sequence-to-function": { + "cpus": 128, "memory_gib": 768, "shm_gib": 64, + "entries": [(p, p) for p in + ("reference", "public/train.parquet", "public/valid.parquet", + "public/junction_tracks.parquet", "metadata/tracks.parquet", + "labels/train.parquet", "labels/valid.parquet", "scoring/train", + "scoring/valid", "targets/train", "targets/valid", "variant_evals/valid")], + "imports": ["numpy", "pyarrow", "pysam", "zarr"], + "python_bin": "/opt/conda/bin", "entrypoint": "infer.sh", + }, +} + + +def gpu_count(task): + """An explicit reduced-compute budget overrides the original task allocation.""" + value = int(os.environ.get("SPEEDRUN_GPU_COUNT", "8" if task in PROFILES else "1")) + if value not in (1, 8): + raise ValueError("SPEEDRUN_GPU_COUNT must be 1 or 8") + return value + + +def cpu_count(task): + return 22 if os.environ.get("SPEEDRUN_SINGLE_SLOT") == "1" else PROFILES.get(task, {}).get("cpus", 64) + + +def validate_sources(task, root): + """Validate only the reviewed allowlist; the operator installer checks payload hashes.""" + root = Path(root).resolve(strict=True) + entries = [] + for source, target in PROFILES[task]["entries"]: + path = root / source + path.resolve(strict=True).relative_to(root) + if path.is_symlink() or not (path.is_file() or path.is_dir()): + raise ValueError(f"Missing or linked development source: {path}") + for item in (path, *path.parents): + if item == root.parent: + break + info = item.stat() + if info.st_uid == 1000 or info.st_mode & 0o022: + raise ValueError(f"Researcher could alter development source: {item}") + entries.append({"source": source, "target": target, "kind": "directory" if path.is_dir() else "file"}) + return entries + + +def configure_data(task, workspace): + data_root = Path("/task-data") + for _, target in PROFILES[task]["entries"]: + source = data_root / target + if not source.exists(): + raise RuntimeError(f"Missing scoped development mount: {source}") + # Preserve the original image's data documentation/helper files beside the + # scoped mounts. Keep one real data root so upstream containment checks work. + image_data = Path("/opt/task-workspace/data") + for source in image_data.rglob("*"): + relative = source.relative_to(image_data) + destination = data_root / relative + if any(relative == Path(t) or Path(t) in relative.parents + for _, t in PROFILES[task]["entries"]): + continue + if source.is_dir(): + destination.mkdir(parents=True, exist_ok=True) + destination.chmod(0o755) + elif source.is_file() and not destination.exists(): + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + destination.chmod(0o444) + destination = workspace / "data" + if not destination.is_symlink(): + raise RuntimeError("Expected the persistent workspace data link") + destination.unlink() + destination.symlink_to(data_root, target_is_directory=True) + + +def probe_data(task): + profile = PROFILES[task] + for module in profile["imports"]: + importlib.import_module(module) + entries = [] + for _, target in profile["entries"]: + path = Path("/workspace/data") / target + assert path.resolve() == (Path("/task-data") / target).resolve() + assert not os.access(path, os.W_OK), f"Writable data mount: {path}" + sample = next((p for p in path.rglob("*") if p.is_file()), None) if path.is_dir() else path + if sample: + assert not os.access(sample, os.W_OK), f"Writable data file: {sample}" + with sample.open("rb") as stream: + stream.read(64) + entries.append(target) + # Explicitly reject evaluation roots that exist in the operator materialization. + forbidden = ("private", "verifier", "grader", "foldbench-test", "public/test.parquet", + "labels/test.parquet", "targets/test", "scoring/test", + "variant_evals/public", "variant_evals/labels") + if task != "single-cell-perturbation-prediction": + forbidden += ("test",) + else: + for context in ("ctx_near", "ctx_mid", "ctx_far"): + public = Path("/workspace/data/test") / context / "public" + assert len((public / "requests.jsonl").read_text().splitlines()) == 300 + assert not (public / "responses.h5ad").exists() + assert not (public.parent / "private").exists() + for name in forbidden: + assert not (Path("/workspace/data") / name).exists(), f"Evaluation role leaked: {name}" + if task == "crystal-structure-generation": + assert not Path("/workspace/data/mp20/test.csv").exists() + assert Path("/workspace/data/scorer-assets/READY.json").is_file() + if task == "protein-folding-prediction": + manifest = json.loads(Path("/workspace/data/foldbench/suite/suite_manifest.json").read_text()) + assert len(manifest["requests"]) == 74 + return {"development_data_ok": True, "data_readonly": True, + "development_mounts": entries, "evaluation_roles_absent": True} diff --git a/reproduction/files/a1/a1c918a16c6745943ba4d7b3b7caaed98dda39fedd3d01c103e9c28af5a7b16a/common.py b/reproduction/files/a1/a1c918a16c6745943ba4d7b3b7caaed98dda39fedd3d01c103e9c28af5a7b16a/common.py new file mode 100644 index 0000000000000000000000000000000000000000..6ff38b41cc1218e27fd1db0ff836b4b88536cbbc --- /dev/null +++ b/reproduction/files/a1/a1c918a16c6745943ba4d7b3b7caaed98dda39fedd3d01c103e9c28af5a7b16a/common.py @@ -0,0 +1,229 @@ +"""Shared constants, safe I/O, and input validation for the protein-design task.""" + +import hashlib +import json +from pathlib import Path + +TRACKS = ("unconditional", "sm_binder", "ppi_binder", "enzyme") +CONDITIONED_TRACKS = ("sm_binder", "ppi_binder", "enzyme") +# Only the enzyme track scaffolds a motif. An sm_binder target is a bare ligand: +# RFdiffusion3 designs a protein around it with no pocket template. +MOTIF_TRACKS = ("enzyme",) + +INPUT_SCHEMA = "protein-design-input/v1" +HARNESS_SCHEMA = "protein-design-harness/v1" +SNAPSHOT_SCHEMA = "protein-design-design-snapshot/v1" +REPORT_SCHEMA = "protein-design-report/v1" + +# Structures use the atom14 layout: [L, 14, 3] with an [L, 14] occupancy mask and +# backbone N/CA/C/O pinned to slots 0-3. See residues.py. +ATOM14_WIDTH = 14 +BACKBONE_ATOMS = ("N", "CA", "C", "O") + +# What a delivered design system may be. BoltzDesign-style inversion trains nothing, +# so "learned parameters trained in session" cannot be a universal requirement. +HARNESS_KINDS = ("trained_generator", "predictor_inversion", "hybrid") + +# Acceptance thresholds. These define the metric and must not drift silently. +# Per-track evaluation budget. See environment/data/targets/*/success.txt. +# FOUR sequences per backbone on every track, which is the task's own budget: the +# published criteria use 8 on enzyme and sm_binder and 4 on ppi_binder, and 4 +# everywhere trades a little statistical power for a uniform, affordable protocol. +# The criterion is "pass if ANY sequence passes", so fewer sequences can only LOWER +# a pass rate - these numbers are conservative against the published ones, never +# flattering, and they are not comparable with RFdiffusion3's own tables. +# enzyme additionally folds 5 predictor models per sequence; the other tracks fold 1. +SEQUENCES_PER_BACKBONE = {"unconditional": 4, "sm_binder": 4, + "ppi_binder": 4, "enzyme": 4} +MODELS_PER_SEQUENCE = {"unconditional": 1, "sm_binder": 1, + "ppi_binder": 1, "enzyme": 5} +SAMPLING_TEMPERATURE = 0.1 + +# RFdiffusion3's published success criteria (results/*/success.txt). +SC_RMSD_MAX = 1.5 # angstrom, backbone RMSD of the refolded design +PLDDT_MIN = 70.0 # refolded-model confidence, when no complex predictor is used +MOTIF_RMSD_MAX = 1.5 # angstrom, motif all-atom RMSD after motif-backbone alignment +NOVELTY_MAX_TM = 0.8 # a passing design's max TM-score to any fit-corpus chain must stay below this (novelty.py) +LIGAND_RMSD_MAX = 5.0 # angstrom, backbone-aligned ligand RMSD (sm_binder) +INTERFACE_PAE_MAX = 1.5 # predicted aligned error at the interface +IPTM_MIN = 0.8 # interface predicted TM-score +PPI_RMSD_MAX = 2.0 # angstrom, binder backbone RMSD (ppi_binder) +HOTSPOT_CONTACT_MAX = 5.0 # angstrom, binder-to-hotspot heavy-atom contact +LIGAND_CLASH_MIN = 1.5 # angstrom, non-motif backbone atom to nearest ligand atom +LIGAND_CONTACT_MAX = 5.0 # angstrom, design atom to ligand atom counted as contact +DIVERSITY_RMSD = 2.0 # angstrom, within-target structural clustering radius +CLASH_MIN = 2.0 # angstrom, inter-atom distance below which a fold is impossible + +# Of the thresholds above, only LIGAND_CLASH_MIN and DIVERSITY_RMSD are applied to a +# graded submission: the first is the published enzyme ligand-clash term, the second +# reports diversity beside the pass rate. The rest are the predictor's own criteria, or - +# CLASH_MIN, LIGAND_CONTACT_MAX, HOTSPOT_CONTACT_MAX - the test suite's stand-in for what +# a predictor would refuse to refold. +# +# CA_CA_DISTANCE, CA_CA_TOLERANCE, LIGAND_BURIAL_MIN and HOTSPOT_FRACTION_MIN were the +# task's own pre-fold gate, deleted 2026-09-26 along with it: designability is the only +# metric, and a threshold table should not advertise limits nothing enforces. See +# environment/evaluation/RESULTS.md for what that gate had been costing. +MIN_DESIGN_LENGTH = 20 +MAX_DESIGN_LENGTH = 600 +# RFdiffusion3's benchmark protocol is 100 backbones per target, and this task reports +# its designability numbers on exactly that. `validate_input` rejects anything larger, +# so raising the protocol means raising this too - they were 32 and 4 respectively, and +# the mismatch made 100 unrepresentable on every path that validates an input view. +MAX_DESIGNS_PER_TARGET = 100 + +INPUT_FIELDS = { + "example_id", "track", "design_length", "num_designs", + "context_path", "context_sha256", "motif_size", "hotspot_count", + "ligand_atom_count", +} +DESIGN_FIELDS = {"design_index", "ranking_score", "structure_path", "motif_map"} +HARNESS_FIELDS = {"schema", "kind", "entry_point", "learned_components", "pretrained_assets"} +LEARNED_FIELDS = {"path", "sha256", "parameters", "trained_in_session"} +ASSET_FIELDS = {"asset_id", "sha256", "license", "role"} + + +def sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest() + + +def write_json(path, value): + Path(path).write_text(json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n") + + +def contained(root, name): + """Resolve `name` under `root`, rejecting absolute paths, escapes, and symlinks.""" + root = Path(root).resolve() + if Path(name).is_absolute(): + raise ValueError(f"unsafe absolute path: {name}") + path = (root / name).resolve() + if not path.is_relative_to(root) or not path.is_file() or path.is_symlink(): + raise ValueError(f"unsafe path: {name}") + return path + + +def jsonl(path, max_bytes=512 * 1024 * 1024, max_line=1024 * 1024): + path = Path(path) + if not path.is_file() or path.is_symlink() or path.stat().st_size > max_bytes: + raise ValueError(f"unsafe JSONL: {path.name}") + with path.open() as stream: + for number, line in enumerate(stream, 1): + if len(line.encode()) > max_line: + raise ValueError(f"oversized line: {path.name}:{number}") + if not line.strip(): + continue + try: + yield json.loads(line) + except json.JSONDecodeError as error: + raise ValueError(f"invalid JSON: {path.name}:{number}") from error + + +def validate_input(root, views=("verifier",)): + """Validate an input view and return (manifest, requests-by-track). + + The verifier accepts only its own `verifier` view. Development scoring passes + `views=("verifier", "development")`, because materialize.py labels fit and tune + `development` and score.py must be able to read them - the documented + `score.py --input /data/tune` is the whole self-scoring workflow. + """ + root = Path(root).resolve() + manifest = json.loads((root / "manifest.json").read_text()) + names = {f"{track}.jsonl" for track in TRACKS} + if (set(manifest) != {"schema", "view", "files", "counts"} + or manifest["schema"] != INPUT_SCHEMA + or manifest["view"] not in views + or set(manifest["files"]) != names + or set(manifest["counts"]) != set(TRACKS)): + raise ValueError("invalid input manifest") + requests = {} + seen = set() + for track in TRACKS: + path = contained(root, f"{track}.jsonl") + if sha256(path) != manifest["files"][path.name]: + raise ValueError(f"input hash mismatch: {path.name}") + rows = {} + for row in jsonl(path): + if set(row) != INPUT_FIELDS or row["track"] != track: + raise ValueError(f"invalid request fields: {track}") + example_id = row["example_id"] + if not isinstance(example_id, str) or not example_id or example_id in seen: + raise ValueError(f"invalid or duplicate example_id: {track}") + length, count = row["design_length"], row["num_designs"] + if (type(length) is not int or not MIN_DESIGN_LENGTH <= length <= MAX_DESIGN_LENGTH + or type(count) is not int or not 1 <= count <= MAX_DESIGNS_PER_TARGET): + raise ValueError(f"invalid design length/count: {example_id}") + for field in ("motif_size", "hotspot_count", "ligand_atom_count"): + if type(row[field]) is not int or row[field] < 0: + raise ValueError(f"invalid {field}: {example_id}") + if track in MOTIF_TRACKS and row["motif_size"] < 1: + raise ValueError(f"{track} requires a motif: {example_id}") + if track == "ppi_binder" and row["hotspot_count"] < 1: + raise ValueError(f"ppi_binder requires hotspots: {example_id}") + if track == "unconditional" and (row["motif_size"] or row["hotspot_count"] + or row["ligand_atom_count"]): + raise ValueError(f"unconditional requests carry no conditioning: {example_id}") + if row["motif_size"] > length: + raise ValueError(f"motif larger than design: {example_id}") + context = contained(root, row["context_path"]) + if sha256(context) != row["context_sha256"]: + raise ValueError(f"context hash mismatch: {example_id}") + seen.add(example_id) + rows[example_id] = row + if len(rows) != manifest["counts"][track]: + raise ValueError(f"input count mismatch: {track}") + requests[track] = rows + return manifest, requests + + +def validate_harness(root, pretrained_root): + """Validate `harness.json` and every component it declares. + + The graded artifact is a design SYSTEM, which may be a trained generator, a + training-free inversion of a pretrained predictor, or a hybrid. What is enforced is + that the manifest matches reality: declared learned components exist inside the + package with the stated digest, and declared pretrained assets exist in the + operator-mounted store with the stated digest and a license. + """ + root = Path(root).resolve() + manifest_path = root / "harness.json" + if not manifest_path.is_file() or manifest_path.is_symlink(): + raise FileNotFoundError("submission/harness.json is required") + manifest = json.loads(manifest_path.read_text()) + if (set(manifest) != HARNESS_FIELDS + or manifest["schema"] != HARNESS_SCHEMA + or manifest["kind"] not in HARNESS_KINDS + or not isinstance(manifest["entry_point"], str) + or not isinstance(manifest["learned_components"], list) + or not isinstance(manifest["pretrained_assets"], list)): + raise ValueError("invalid harness manifest fields, schema, or kind") + + total_parameters = 0 + for component in manifest["learned_components"]: + if (set(component) != LEARNED_FIELDS + or type(component["parameters"]) is not int or component["parameters"] < 0 + or not isinstance(component["trained_in_session"], bool)): + raise ValueError("invalid learned component declaration") + path = contained(root, component["path"]) + if sha256(path) != component["sha256"]: + raise ValueError(f"learned component checksum mismatch: {component['path']}") + total_parameters += component["parameters"] + + for asset in manifest["pretrained_assets"]: + if set(asset) != ASSET_FIELDS or not asset["license"] or not asset["role"]: + raise ValueError("pretrained assets must declare a license and a role") + path = contained(pretrained_root, asset["asset_id"]) + if sha256(path) != asset["sha256"]: + raise ValueError(f"pretrained asset checksum mismatch: {asset['asset_id']}") + + kind = manifest["kind"] + trained = [c for c in manifest["learned_components"] if c["trained_in_session"]] + if kind in ("trained_generator", "hybrid") and not trained: + raise ValueError(f"kind '{kind}' requires at least one component trained in session") + if kind in ("predictor_inversion", "hybrid") and not manifest["pretrained_assets"]: + raise ValueError(f"kind '{kind}' requires at least one declared pretrained asset") + manifest["declared_parameters"] = total_parameters + return manifest diff --git a/reproduction/files/a6/a6f4a1229595f00d5a0fef9f31cd69991fc6abc4b04a52238c9977c61e52ecae/test_panel_scoring.py b/reproduction/files/a6/a6f4a1229595f00d5a0fef9f31cd69991fc6abc4b04a52238c9977c61e52ecae/test_panel_scoring.py new file mode 100644 index 0000000000000000000000000000000000000000..ea93ee4252ed7b175e38a63ac717bd19a778503d --- /dev/null +++ b/reproduction/files/a6/a6f4a1229595f00d5a0fef9f31cd69991fc6abc4b04a52238c9977c61e52ecae/test_panel_scoring.py @@ -0,0 +1,70 @@ +"""Primary reward: panel case detection at a fixed alert budget.""" + +import sys +from pathlib import Path + +import numpy as np +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment" / "evaluation")) +from panel_scoring import (MIN_POSITIVES, PANEL, PRIMARY, has_family_history, # noqa: E402 + history_code, panel_score, recall_at) + + +def test_recall_at_alert_budget_counts_cases_in_top_share(): + y = np.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0] * 10) + p = np.where(y == 1, 0.9, 0.1).astype(float) + p[0] = 0.05 # one case ranked last + recall, ppv = recall_at(y, p, 0.05) # top 5 of 100 + assert recall == pytest.approx(5 / 20) and ppv == 1.0 + + +def test_ties_score_their_expectation_so_constant_prediction_is_chance(): + rng = np.random.default_rng(0) + y = (rng.random(1000) < 0.1).astype(int) + recall, _ = recall_at(y, np.full(1000, 0.3), 0.05) + assert recall == pytest.approx(0.05) + # Row order cannot be exploited: putting all cases first does not change a tied score. + order = np.argsort(-y, kind="stable") + assert recall_at(y[order], np.full(1000, 0.3), 0.05)[0] == pytest.approx(0.05) + + +def test_family_history_exclusion_matches_icd10_exactly_and_icd9_by_prefix(): + family = PANEL["I50"][1] + assert has_family_history({"I11"}, family) + assert has_family_history({"ICD9:42831"}, family) + assert not has_family_history({"I10", "ICD9:4019"}, family) + assert history_code("I509") == "I50" and history_code("ICD9:42831") == "ICD9:42831" + + +def _panel_inputs(n=2000, seed=1): + codes = list(PANEL) + rng = np.random.default_rng(seed) + labels = (rng.random((n, len(codes))) < 0.03).astype(np.uint8) + valid = np.ones_like(labels, dtype=bool) + complete = np.ones(n, dtype=bool) + return codes, labels, valid, complete, [set() for _ in range(n)] + + +def test_perfect_ranking_scores_one_and_reward_set_ignores_predictions(): + codes, labels, valid, complete, history = _panel_inputs() + perfect = panel_score(labels, valid, labels.astype(float), complete, codes, history) + noisy = panel_score(labels, valid, np.random.default_rng(2).random(labels.shape), + complete, codes, history) + assert perfect[PRIMARY] == pytest.approx(1.0) + assert noisy[PRIMARY] < 0.2 + assert perfect["endpoints_in_reward"] == noisy["endpoints_in_reward"] + + +def test_rare_endpoints_and_ineligible_patients_stay_out_of_the_reward(): + codes, labels, valid, complete, history = _panel_inputs(n=400) + labels[:, codes.index("C67")] = 0 + labels[: MIN_POSITIVES - 1, codes.index("C67")] = 1 + complete[:50] = False + for h in history[50:100]: + h.add("I11") + report = panel_score(labels, valid, np.random.default_rng(3).random(labels.shape), + complete, codes, history) + assert "C67" not in report["endpoints_in_reward"] + hf = report["endpoints"]["I50"] + assert hf["eligible"] == 300 and hf["family_history_excluded"] == 50 diff --git a/reproduction/files/a7/a743a10f9ee026ea627969ff9d905a8f1c1cf0e0ad60c40352b37e8717076f5e/test_evaluation.py b/reproduction/files/a7/a743a10f9ee026ea627969ff9d905a8f1c1cf0e0ad60c40352b37e8717076f5e/test_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..297de41bd98dcae267c4c8e94cbd09f24f17a0af --- /dev/null +++ b/reproduction/files/a7/a743a10f9ee026ea627969ff9d905a8f1c1cf0e0ad60c40352b37e8717076f5e/test_evaluation.py @@ -0,0 +1,124 @@ +import copy + +import numpy as np +import pytest +from ase.build import bulk +from ase.calculators.emt import EMT +from ase import units + +from common import decode_atoms, encode_atoms +from physics import elasticity, make_phonon, phonons, relax +from score import corrected_formation, discovery_metrics, score_rows + + +def test_no_reference_labels_in_atoms(): + atoms = bulk("Cu") + atoms.info["energy"] = -9999 + atoms.set_initial_magnetic_moments([17]) + atoms.calc = EMT() + atoms.get_potential_energy() + restored = decode_atoms(encode_atoms(atoms)) + assert restored.info == {} + assert restored.calc is None + assert set(restored.arrays) == {"numbers", "positions"} + + +def sample_rows(): + targets = [ + { + "id": f"elasticity/{i}", + "suite": "elasticity", + "bulk_modulus_vrh": 100 + 50 * i, + "shear_modulus_vrh": 30 + 10 * i, + } + for i in range(2) + ] + predictions = [dict(row, status="ok") for row in targets] + predictions[0]["bulk_modulus_vrh"] += 10 + predictions[1]["bulk_modulus_vrh"] -= 20 + return targets, predictions + + +def test_scores_match_by_id_not_row_order(): + targets, predictions = sample_rows() + score = score_rows(targets, predictions) + assert score == score_rows(targets, predictions[::-1]) + assert score["elasticity"]["bulk_modulus_vrh"]["MAE"] == 15 + + +@pytest.mark.parametrize("mutation", ["duplicate", "unknown"]) +def test_malformed_prediction_sets_are_rejected(mutation): + targets, predictions = sample_rows() + if mutation == "duplicate": + predictions.append(copy.deepcopy(predictions[0])) + else: + predictions[0]["id"] = "elasticity/unknown" + with pytest.raises(ValueError): + score_rows(targets, predictions) + + +@pytest.mark.parametrize("mutation", ["missing", "nan", "failed", "suite"]) +def test_failed_cases_are_scored_and_cannot_improve_score(mutation): + targets, predictions = sample_rows() + clean = score_rows(targets, predictions)["elasticity"] + if mutation == "missing": + predictions.pop(0) + elif mutation == "nan": + predictions[0]["bulk_modulus_vrh"] = float("nan") + elif mutation == "failed": + predictions[0]["status"] = "failed" + else: + predictions[0]["suite"] = "phonons" + scored = score_rows(targets, predictions)["elasticity"] + assert scored["failed"] == 1 + for field in ("bulk_modulus_vrh", "shear_modulus_vrh"): + assert scored[field]["MAE"] >= clean[field]["MAE"] + + +def test_signed_hull_threshold_and_units(): + metrics = discovery_metrics([-0.1, 0, 0.2, 0.3], [-0.2, 0.01, -0.1, 0.3]) + assert (metrics["TP"], metrics["FN"], metrics["FP"], metrics["TN"]) == (1, 1, 1, 1) + assert metrics["F1"] == 0.5 + assert metrics["hull_MAE_meV_per_atom"] == pytest.approx(102.5) + + +def test_wrong_correction_runtime_is_rejected(): + with pytest.raises(ValueError, match="pymatgen 2023.5.10"): + corrected_formation({}, {}) + + +def test_elastic_bulk_matches_independent_energy_curvature(): + atoms = bulk("Cu") + calculator = EMT() + result = elasticity({"atoms": encode_atoms(atoms)}, calculator) + relax(atoms, calculator) + energies = [] + delta = 0.001 + for volume_scale in (1 - delta, 1, 1 + delta): + probe = atoms.copy() + probe.set_cell(atoms.cell * volume_scale ** (1 / 3), scale_atoms=True) + probe.calc = EMT() + energies.append(probe.get_potential_energy()) + curvature = (energies[0] - 2 * energies[1] + energies[2]) / ( + delta**2 * atoms.get_volume() + ) + assert result["bulk_modulus_vrh"] == pytest.approx(curvature / units.GPa, rel=0.02) + assert 20 < result["shear_modulus_vrh"] < 200 + + +def test_phonon_pipeline_has_no_force_constants_at_input(): + atoms = bulk("Cu") + case = { + "atoms": encode_atoms(atoms), + "phonon": { + "masses": atoms.get_masses().tolist(), + "supercell_matrix": [[2, 0, 0], [0, 2, 0], [0, 0, 2]], + "primitive_matrix": None, + }, + } + assert make_phonon(case).force_constants is None + result = phonons(case, EMT()) + assert 100 < result["max_freq"] < 600 + assert 0 < result["heat_capacity"] < 3 * 8.3145 + assert np.isfinite(result["free_energy"]) + assert result["diagnostics"]["supercell_atoms"] == 8 diff --git a/reproduction/files/aa/aa6d8b98d6ce8bd884167def4c9ebc3bf4e343bade45b91c233709a6160acd4e/test_package.py b/reproduction/files/aa/aa6d8b98d6ce8bd884167def4c9ebc3bf4e343bade45b91c233709a6160acd4e/test_package.py new file mode 100644 index 0000000000000000000000000000000000000000..586970891021d74fe7dfb714abbbf946a8d6b166 --- /dev/null +++ b/reproduction/files/aa/aa6d8b98d6ce8bd884167def4c9ebc3bf4e343bade45b91c233709a6160acd4e/test_package.py @@ -0,0 +1,205 @@ +"""Frozen checkpoint identity, tamper rejection, and relocated Keras replay.""" +from __future__ import annotations + +import fcntl +import hashlib +import io +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any +import zipfile + +import numpy as np +import pytest +import stim + +PROJECT = Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" if (Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit").is_dir() else Path(__file__).resolve().parents[1] # the baseline project: environment/baseline/alphaqubit here, /opt/task in the verifier image +sys.path.insert(0, str(PROJECT)) +from baselines.package import ( # noqa: E402 + CHECKPOINT_STATE, EXPECTED_GROUPS, TASK_ROOT, freeze_package, verify_package, +) + + +GROUP = "d3_bX_center_3_5" + + +def identity_hash(identity: dict[str, Any]) -> str: + return hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() + + +def write_archive(path: Path, state: dict[str, Any], keras_bytes: bytes | None = None) -> None: + with zipfile.ZipFile(path, "w") as output: + if keras_bytes is None: + for name, value in (("config.json", b"{}"), ("metadata.json", b"{}"), ("model.weights.h5", b"fixture")): + output.writestr(name, value) + else: + with zipfile.ZipFile(io.BytesIO(keras_bytes)) as source: + for name in source.namelist(): + if name != CHECKPOINT_STATE: + output.writestr(name, source.read(name)) + output.writestr(CHECKPOINT_STATE, json.dumps(state)) + + +def make_stage(models_root: Path, group: str = GROUP, keras_bytes: bytes | None = None) -> tuple[Path, dict[str, Any], dict[str, Any]]: + folder = models_root / group / "pretrain" + folder.mkdir(parents=True) + source_hashes = {name: hashlib.sha256((TASK_ROOT / "baselines" / name).read_bytes()).hexdigest() + for name in ("train.py", "neural.py", "cache.py", "data.py", "observables.py")} + identity = { + "stage": "pretrain", "group": group, "distance": int(group[1]), "seed": 0, + "label_mode": "qrennd_global_data_parity", "native_repository": "https://github.com/Hossein-D/qrennd", + "native_commit": "c2ed73e3ec6ee843293c8839bf059c63b2960e61", + "data": {"manifest_sha256": "a" * 64, "cache_directory": str(models_root / "historical-cache")}, + "semantic_source_sha256": {name: source_hashes[name] for name in ("data.py", "neural.py", "observables.py")}, + } + identity_sha = identity_hash(identity) + metadata = { + "identity": identity, "identity_sha256": identity_sha, "stage": "pretrain", "group": group, + "distance": int(group[1]), "label_mode": "qrennd_global_data_parity", "source_sha256": source_hashes, + "sessions": [{"started_at": "2026-09-19T01:00:00Z", "ended_at": "2026-09-19T02:00:00Z", "stop_reason": "max_steps"}], + "protocol": {"selection": "main BCE + 0.5 auxiliary BCE", "adaptations": ["bounded fixture"]}, + "limitations": ["synthetic fixture; not scientific evidence"], + } + state = { + "identity_sha256": identity_sha, "global_steps": 10, "best_step": 10, "last_validation_step": 10, + "best_validation_loss": 0.2, "convergence_established": False, + "latest_validation": {"complete": True, "selected_best": True, "global_steps": 10, "loss": 0.2}, + } + (folder / "metadata.json").write_text(json.dumps(metadata), encoding="utf-8") + (folder / "progress.json").write_text(json.dumps({**state, "status": "stopped", "global_steps": 20}), encoding="utf-8") + (folder / ".training.lock").touch() + write_archive(folder / "best.keras", state, keras_bytes) + return folder, metadata, state + + +def test_exact_ten_groups_required_by_default(tmp_path: Path) -> None: + models = tmp_path / "models" + make_stage(models) + with pytest.raises(ValueError, match="exactly 10"): + freeze_package(models, "pretrain", tmp_path / "package") + for group in EXPECTED_GROUPS: + if group != GROUP: + make_stage(models, group) + result = freeze_package(models, "pretrain", tmp_path / "package") + assert result["groups"] == list(EXPECTED_GROUPS) + assert len(result["models"]) == 10 + + +@pytest.mark.parametrize("invalid", ["identity", "embedded_identity", "best_step", "stage", "group", "label_mode", "unfinished", "progress", "semantic_source", "validation"]) +def test_reject_inconsistent_or_active_stage(tmp_path: Path, invalid: str) -> None: + models = tmp_path / "models" + folder, metadata, state = make_stage(models) + if invalid == "identity": + metadata["identity"]["seed"] = 1 + elif invalid == "embedded_identity": + state["identity_sha256"] = "f" * 64 + elif invalid == "best_step": + state["best_step"] = 11 + elif invalid in {"stage", "group", "label_mode"}: + metadata[invalid] = "wrong" + elif invalid == "unfinished": + del metadata["sessions"][-1]["ended_at"] + elif invalid == "progress": + progress = json.loads((folder / "progress.json").read_text()) + progress["status"] = "training" + (folder / "progress.json").write_text(json.dumps(progress), encoding="utf-8") + elif invalid == "semantic_source": + metadata["identity"]["semantic_source_sha256"]["data.py"] = "f" * 64 + metadata["identity_sha256"] = identity_hash(metadata["identity"]) + state["identity_sha256"] = metadata["identity_sha256"] + elif invalid == "validation": + state["latest_validation"]["complete"] = False + (folder / "metadata.json").write_text(json.dumps(metadata), encoding="utf-8") + write_archive(folder / "best.keras", state) + with pytest.raises(ValueError): + freeze_package(models, "pretrain", tmp_path / "package", GROUP) + assert not (tmp_path / "package").exists() + assert not list(tmp_path.glob(".package.staging-*")) + + +def test_live_training_lock_prevents_freeze(tmp_path: Path) -> None: + models = tmp_path / "models" + folder, _, _ = make_stage(models) + with (folder / ".training.lock").open("r") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + with pytest.raises(ValueError, match="training is still active"): + freeze_package(models, "pretrain", tmp_path / "package", GROUP) + + +def test_idempotence_and_payload_tamper_rejection(tmp_path: Path) -> None: + models, output = tmp_path / "models", tmp_path / "package" + make_stage(models) + original = freeze_package(models, "pretrain", output, GROUP) + assert freeze_package(models, "pretrain", output, GROUP) == original + assert verify_package(output) == original + sidecar = json.loads((output / "models" / GROUP / "metadata.json").read_text()) + assert sidecar["checkpoint_sha256"] == original["models"][GROUP]["checkpoint_sha256"] + assert set(path.name for path in (output / "baselines").iterdir()) == {"predict.py", "data.py", "observables.py"} + assert (output / "UPSTREAM_LICENSE").read_bytes() == (TASK_ROOT / "baselines" / "reference" / "LICENSE").read_bytes() + assert "UPSTREAM_LICENSE" in original["files"] + readme = (output / "README.md").read_text() + assert "Boris M. Varbanov" in readme and original["native_source"]["commit"] in readme + (output / "baselines" / "predict.py").write_text("tampered", encoding="utf-8") + with pytest.raises(ValueError, match="hash/size mismatch"): + verify_package(output) + with pytest.raises(ValueError, match="hash/size mismatch"): + freeze_package(models, "pretrain", output, GROUP) + + +def test_refuse_different_verified_package_and_unknown_payload(tmp_path: Path) -> None: + models, output = tmp_path / "models", tmp_path / "package" + folder, metadata, _ = make_stage(models) + freeze_package(models, "pretrain", output, GROUP) + original_manifest = (output / "manifest.json").read_bytes() + metadata["limitations"].append("a new provenance record") + (folder / "metadata.json").write_text(json.dumps(metadata), encoding="utf-8") + with pytest.raises(ValueError, match="not identical"): + freeze_package(models, "pretrain", output, GROUP) + assert (output / "manifest.json").read_bytes() == original_manifest + (output / "unrecorded.py").write_text("# unexpected", encoding="utf-8") + with pytest.raises(ValueError, match="coverage mismatch"): + verify_package(output) + + +def test_relocated_standard_keras_checkpoint_replays_without_training_tree(tmp_path: Path, monkeypatch: Any) -> None: + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "") + monkeypatch.setenv("TF_NUM_INTRAOP_THREADS", "1") + monkeypatch.setenv("TF_NUM_INTEROP_THREADS", "1") + tf = pytest.importorskip("tensorflow") + recurrent = tf.keras.Input((None, 8), name="rec_input") + evaluation = tf.keras.Input((4,), name="eval_input") + hidden = tf.keras.layers.Concatenate()([tf.keras.layers.GlobalAveragePooling1D()(recurrent), evaluation]) + outputs = [tf.keras.layers.Dense(1, activation="sigmoid", name=name, kernel_initializer="zeros", bias_initializer="zeros")(hidden) + for name in ("main_output", "aux_output")] + model = tf.keras.Model([recurrent, evaluation], outputs) + keras_path = tmp_path / "fixture.keras" + model.save(keras_path) + models = tmp_path / "training-tree" + make_stage(models, keras_bytes=keras_path.read_bytes()) + output = tmp_path / "frozen" + freeze_package(models, "pretrain", output, GROUP) + relocated = tmp_path / "relocated" + shutil.move(output, relocated) + shutil.rmtree(models) + keras_path.unlink() + data_root = tmp_path / "synthetic-detectors" + for rounds in range(1, 26, 2): + folder = data_root / f"surface_code_bX_d3_r{rounds:02d}_center_3_5" + folder.mkdir(parents=True) + circuit = stim.Circuit.generated("surface_code:rotated_memory_x", distance=3, rounds=rounds) + circuit.to_file(folder / "circuit_ideal.stim") + np.zeros((50_000, (circuit.num_detectors + 7) // 8), dtype=np.uint8).tofile(folder / "detection_events.b8") + environment = {key: value for key, value in os.environ.items() if key != "PYTHONPATH"} + result = subprocess.run( + [sys.executable, "-m", "baselines.predict", "--model", f"models/{GROUP}/model.keras", + "--data-root", str(data_root), "--group", GROUP, "--split", "validation", "--output", str(tmp_path / "predictions")], + cwd=relocated, env=environment, capture_output=True, text=True, timeout=60, + ) + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout.splitlines()[-1])["status"] == "complete" + assert len(list((tmp_path / "predictions").glob("*.npz"))) == 13 + assert verify_package(relocated)["groups"] == [GROUP] diff --git a/reproduction/files/ab/abe4b85f9c39d9c193a4233fd1ad007c8ea342d13266e493e9ceb261ed66c87c/runtime.py b/reproduction/files/ab/abe4b85f9c39d9c193a4233fd1ad007c8ea342d13266e493e9ceb261ed66c87c/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..235a118088790863828be67aeea054ac84d00d3f --- /dev/null +++ b/reproduction/files/ab/abe4b85f9c39d9c193a4233fd1ad007c8ea342d13266e493e9ceb261ed66c87c/runtime.py @@ -0,0 +1,810 @@ +"""Direct Beaker execution: persistent Codex research, then a separate verifier job. + +The agent image contains only the development workspace. The verifier image and +its Weka mount contain neither Codex credentials nor the development trajectory. +""" + +import argparse +from concurrent.futures import ThreadPoolExecutor +import ctypes +import errno +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from task_profiles import PROFILES, configure_data, gpu_count + +STATE = Path("/run-state") +WORKSPACE = Path("/workspace") +CODEX_VERSION = "0.163.0" +OFFLINE_HELPER = Path(__file__).with_name("network_sandbox.py") +HEARTBEAT_SECONDS = 10 +MAX_CAPACITY_RETRIES = 6 +TASK_ID = os.environ.get("SPEEDRUN_TASK", "tokamak-magnetic-control") +EARTH = "earth-observation-pretraining-transfer" +NDP = "natural-disease-progression" +CONTINUE = ( + "Continue the research. There is no end point: pick up from your research notes " + "and the latest results, run the next experiment, and keep the submission up to " + "date with the strongest replayable candidate." +) + + +def write_json(path, value): + path = Path(path) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(value, indent=2) + "\n") + tmp.replace(path) + + +def status(phase, **extra): + data = {"phase": phase, "updated_unix": time.time(), **extra} + write_json(STATE / "status.json", data) + print(json.dumps(data), flush=True) + + +def fingerprint(root): + """Hash content and modes; reject links escaping the portable package.""" + root = Path(root) + digest = hashlib.sha256() + for p in sorted(root.rglob("*")): + relative = str(p.relative_to(root)) + digest.update(relative.encode() + b"\0") + if p.is_symlink(): + p.resolve(strict=True).relative_to(root.resolve()) + digest.update(b"link:" + os.readlink(p).encode()) + elif p.is_file(): + digest.update(str(p.stat().st_mode & 0o777).encode()) + with p.open("rb") as f: + for chunk in iter(lambda: f.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def snapshot(start, previous): + src = WORKSPACE / "submission" + if not src.is_dir() or not any(src.iterdir()): + return previous + staging = STATE / "snapshots" / ".staging" + try: + before = fingerprint(src) + if before == previous: + return previous + shutil.rmtree(staging, ignore_errors=True) + staging.parent.mkdir(exist_ok=True) + shutil.copytree(src, staging, symlinks=True) + if fingerprint(src) != before or fingerprint(staging) != before: + shutil.rmtree(staging) + return previous + elapsed = int(time.monotonic() - start) + dst = staging.parent / f"{elapsed:06d}-{before[:12]}" + staging.rename(dst) + with (staging.parent / "index.jsonl").open("a") as f: + f.write(json.dumps({"seconds": elapsed, "sha256": before, "path": dst.name}) + "\n") + return before + except (OSError, ValueError) as error: + print(json.dumps({"snapshot_skipped": str(error)}), flush=True) + shutil.rmtree(staging, ignore_errors=True) + return previous + + +def researcher(): + os.setgroups([]) + os.setgid(1000) + os.setuid(1000) + + +def stop_research(): + # A dedicated UID inside this job includes background trainers which have + # detached from Codex's process group. The supervisor remains root. + for sig in (signal.SIGTERM, signal.SIGKILL): + for p in Path("/proc").iterdir(): + if not p.name.isdigit(): + continue + try: + if p.stat().st_uid == 1000: + os.kill(int(p.name), sig) + except (ProcessLookupError, PermissionError, FileNotFoundError): + pass + if sig == signal.SIGTERM: + time.sleep(3) + + +def check_atomic_exchange(parent): + """Exercise the exact syscall used by Earth's unchanged publisher.""" + with tempfile.TemporaryDirectory(prefix=".exchange-check-", dir=parent) as folder: + a, b = Path(folder) / "a", Path(folder) / "b" + a.mkdir() + b.mkdir() + (a / "marker").write_text("a") + (b / "marker").write_text("b") + libc = ctypes.CDLL(None, use_errno=True) + rename = libc.renameat2 + rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, + ctypes.c_char_p, ctypes.c_uint] + rename.restype = ctypes.c_int + if rename(-100, os.fsencode(a), -100, os.fsencode(b), 2): + error = ctypes.get_errno() + raise OSError(error, os.strerror(error)) + if (a / "marker").read_text() != "b" or (b / "marker").read_text() != "a": + raise RuntimeError("Atomic directory exchange did not exchange content") + return True + + +def latest_published_package(actual): + """Restore the latest completely committed snapshot after a container loss.""" + index = STATE / "snapshots/index.jsonl" + if index.exists(): + for line in reversed(index.read_text().splitlines()): + try: + entry = json.loads(line) + except json.JSONDecodeError: + continue # A killed append cannot invalidate earlier complete records. + name = entry["path"] + if Path(name).name != name: + raise RuntimeError("Invalid snapshot path") + package = index.parent / name + if fingerprint(package) != entry["sha256"]: + raise RuntimeError("Committed publication snapshot changed") + return package + return actual / "submission" + + +def configure_earth_workspace(actual): + # Keep the workspace parent and submission on the container's local filesystem. + # The original publisher stages beside submission and requires RENAME_EXCHANGE. + # Research, data, and task files still resolve to their persistent Weka paths. + if WORKSPACE.is_symlink(): + if WORKSPACE.resolve() != actual.resolve(): + raise RuntimeError("Unexpected workspace symlink") + WORKSPACE.unlink() + WORKSPACE.mkdir(exist_ok=True) + for child in actual.iterdir(): + if child.name == "submission": + continue + destination = WORKSPACE / child.name + if destination.is_symlink(): + if os.readlink(destination) != str(child): + raise RuntimeError("Unexpected Earth workspace link") + elif destination.exists(): + raise RuntimeError("Unexpected local Earth workspace file") + else: + destination.symlink_to(child, target_is_directory=child.is_dir()) + destination = WORKSPACE / "submission" + if destination.exists() or destination.is_symlink(): + raise RuntimeError("Refusing to replace an existing local publication") + package = latest_published_package(actual) + shutil.copytree(package, destination, symlinks=True) + if fingerprint(destination) != fingerprint(package): + raise RuntimeError("Restored publication differs from its durable package") + for p in [WORKSPACE, destination, *destination.rglob("*")]: + if not p.is_symlink(): + os.chown(p, 1000, 1000) + check_atomic_exchange(WORKSPACE) + write_json(STATE / "publication-storage.json", { + "layout": "local-workspace-parent-with-persistent-research", + "restored_from": str(package), "restored_sha256": fingerprint(destination), + "atomic_exchange_ok": True, + }) + + +def configure_workspace(resume=False): + actual = STATE / "workspace" + if actual.exists(): + if not resume: + raise RuntimeError("Refusing to overwrite an existing research workspace") + else: + if resume: + raise RuntimeError("Saved research state has no workspace") + shutil.copytree("/opt/task-workspace", actual) + for p in [actual, *actual.rglob("*")]: + if not p.is_symlink(): + os.chown(p, 1000, 1000) + if TASK_ID == EARTH or TASK_ID in PROFILES: + configure_earth_workspace(actual) + elif WORKSPACE.is_symlink(): + if WORKSPACE.resolve() != actual.resolve(): + raise RuntimeError("Unexpected workspace symlink") + else: + WORKSPACE.rmdir() + WORKSPACE.symlink_to(actual, target_is_directory=True) + if TASK_ID in PROFILES: + configure_data(TASK_ID, WORKSPACE) + elif TASK_ID == EARTH: + from earth_data import validate_development + validate_development(Path("/task-data")) + for name in ("19837", "eval"): + destination = WORKSPACE / "data" / name + target = Path("/task-data") / name + if destination.is_symlink(): + if destination.resolve() != target.resolve(): + raise RuntimeError("Unexpected task data symlink") + else: + destination.symlink_to(target, target_is_directory=True) + elif TASK_ID == NDP: + from ndp_data import validate_development, WORKSPACE_DATA + validate_development(Path("/task-data")) + for name in WORKSPACE_DATA: + destination = WORKSPACE / "data" / name + target = Path("/task-data") / name + if destination.is_symlink(): + if destination.resolve() != target.resolve(): + raise RuntimeError("Unexpected task data symlink") + else: + if destination.is_dir(): + destination.rmdir() # Only the image's empty mount points. + destination.symlink_to(target, target_is_directory=target.is_dir()) + home = STATE / "agent" + home.mkdir(mode=0o700, exist_ok=True) + os.chown(home, 1000, 1000) + auth = home / "auth.json" + if not auth.is_file(): + raise RuntimeError("Missing staged Codex auth.json") + os.chown(auth, 1000, 1000) + auth.chmod(0o600) + # Allow traversal into this run, but credentials and logs retain 0700/0600. + STATE.chmod(0o755) + if os.environ.get("SPEEDRUN_ENFORCE_ONE_GPU") == "1": + from gpu_access import configure + policy = configure(STATE, count=gpu_count(TASK_ID), + strict_allocation=os.environ.get("SPEEDRUN_SINGLE_SLOT") == "1") + else: + policy = None + env = {**os.environ, "HOME": "/home/researcher", "CODEX_HOME": str(home), + "TMPDIR": "/tmp", "PYTHONPATH": "/workspace" + ( + ":" + os.environ["PYTHONPATH"] if os.environ.get("PYTHONPATH") else ""), + "CUDA_VISIBLE_DEVICES": ",".join(policy["allowed_uuids"]) if policy else "0"} + # Authentication comes exclusively from the privately staged auth.json. + for name in ("OPENAI_API_KEY", "CODEX_API_KEY", "OPENAI_BASE_URL"): + env.pop(name, None) + if TASK_ID == "crystal-structure-generation": + env.update(CRYSTALGEN_LEMAT_GPU_WORKERS=str(gpu_count(TASK_ID)), + HF_HOME="/scorer-assets/huggingface", HF_HUB_CACHE="/scorer-assets/huggingface/hub", + HF_DATASETS_CACHE="/scorer-assets/huggingface/datasets", + XDG_CACHE_HOME="/scorer-assets/xdg-cache", TORCH_HOME="/scorer-assets/torch-cache") + env.pop("SPEEDRUN_OFFLINE_LOOPBACK", None) + if gpu_count(TASK_ID) > 1: + from offline_network import configure + configure(STATE) + env.update(SPEEDRUN_OFFLINE_LOOPBACK="1", NCCL_SOCKET_IFNAME="lo", + GLOO_SOCKET_IFNAME="lo", MASTER_ADDR="127.0.0.1") + return env + + +def codex_command(args, resume=False, ephemeral=False): + cmd = ["codex", "exec", "--ignore-user-config", "--skip-git-repo-check", + "-m", args.model, "-c", f'model_reasoning_effort="{args.reasoning}"', + "-c", 'service_tier="default"', "--disable", "fast_mode", + "-c", 'approval_policy="never"', "-c", 'default_permissions="job"', + "-c", 'permissions={job={filesystem={":root"="write"},network={enabled=false}}}', + "--enable", "use_legacy_landlock", + "-c", 'web_search="disabled"', "--json"] + if ephemeral: + cmd += ["--ephemeral"] + if resume: + cmd += ["resume", resume if isinstance(resume, str) else "--last"] + return cmd + ["-"] + + +def start_codex(command, env, out, err): + """Install the offline helper before delivering any prompt to Codex. + + Codex 0.163 creates per-process helper aliases before reading stdin. There + is no CLI override for its sandbox executable. Replace this invocation's + alias with our root-owned helper, retaining the same declared permissions. + Fail closed if the pinned CLI no longer creates the expected alias. + """ + aliases = Path(env["CODEX_HOME"]) / "tmp/arg0-linux" + old = set(aliases.glob("*/codex-linux-sandbox")) + proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=out, stderr=err, + text=True, cwd=WORKSPACE, env=env, + user=1000, group=1000, extra_groups=[], start_new_session=True) + try: + for _ in range(300): + candidates = set(aliases.glob("*/codex-linux-sandbox")) - old + if len(candidates) == 1: + alias = candidates.pop() + # 0.163 uses platform-specific aliases and no longer creates + # codex-execve-wrapper. Wait for the complete alias set. + markers = [alias.parent / name for name in ("apply_patch", "applypatch")] + if not all(p.is_symlink() for p in markers): + time.sleep(0.05) + continue + if not alias.is_symlink(): + raise RuntimeError("Unexpected Codex helper file") + binary = Path(shutil.which(command[0], path=env.get("PATH"))).resolve() + if any(p.resolve() != binary for p in [alias, *markers]): + raise RuntimeError("Unexpected Codex helper target") + staged = alias.with_name("offline-helper.tmp") + shutil.copyfile(OFFLINE_HELPER, staged) + staged.chmod(0o755) + staged.replace(alias) + return proc + if proc.poll() is not None: + raise RuntimeError(f"Codex exited before sandbox setup: {proc.returncode}") + time.sleep(0.05) + raise RuntimeError("Codex sandbox helper did not appear") + except BaseException: + proc.kill() + proc.wait() + raise + + +def preflight(args, env, check_resume=False): + status("preflight") + # Require the actual model to execute a tool in the same sandbox used by the + # trial, and prove that scientific code can use the GPU while network calls + # from tools are blocked. Model API traffic stays outside the tool sandbox. + probe = WORKSPACE / "research" / "codex-preflight.json" + probe.unlink(missing_ok=True) + prompt = ( + "Perform this environment check and then stop: execute " + "`python /opt/speedrun/probe.py` using your shell tool. Do not modify that " + "script or read credentials. It verifies CUDA, task imports, blocked tool " + "networking, and a workspace write. Reply PREFLIGHT_OK only if it succeeds." + ) + with (STATE / "preflight.jsonl").open("w") as out, (STATE / "preflight.stderr").open("w") as err: + completed = start_codex(codex_command(args, ephemeral=not check_resume), env, out, err) + try: + completed.communicate(prompt, timeout=420) + except BaseException: + stop_research() + completed.wait() + raise + if completed.returncode != 0 or not probe.is_file(): + raise RuntimeError("Codex preflight failed; inspect preflight logs") + data = json.loads(probe.read_text()) + if not all(data.get(k) is True for k in ("cuda_ok", "imports_ok", "network_blocked")): + raise RuntimeError(f"Preflight assertions failed: {data}") + write_json(STATE / "preflight-result.json", data) + if check_resume: + probe.unlink() + with (STATE / "resume-preflight.jsonl").open("w") as out, \ + (STATE / "resume-preflight.stderr").open("w") as err: + resumed = start_codex(codex_command(args, resume=True), env, out, err) + try: + resumed.communicate(prompt, timeout=420) + except BaseException: + stop_research() + resumed.wait() + raise + if resumed.returncode != 0 or not probe.is_file(): + raise RuntimeError("Codex resume preflight failed; inspect resume preflight logs") + resumed_data = json.loads(probe.read_text()) + if not all(resumed_data.get(k) is True for k in ("cuda_ok", "imports_ok", "network_blocked")): + raise RuntimeError(f"Resume preflight assertions failed: {resumed_data}") + def thread_id(path): + for line in path.read_text().splitlines(): + event = json.loads(line) + if event.get("type") == "thread.started": + return event["thread_id"] + raise RuntimeError(f"Missing thread.started event in {path.name}") + first_id = thread_id(STATE / "preflight.jsonl") + if thread_id(STATE / "resume-preflight.jsonl") != first_id: + raise RuntimeError("Resume started a different Codex session") + write_json(STATE / "resume-preflight-result.json", { + **resumed_data, "session_resume_ok": True, "thread_id": first_id, + }) + if TASK_ID in (EARTH, NDP) or TASK_ID in PROFILES: + if not data.get("development_data_ok") or not data.get("data_readonly"): + raise RuntimeError(f"{TASK_ID} data checks did not pass") + probe.unlink() + return + # Confirm a real nonlinear simulator reset/step before starting the clock. + code = """ +import json, numpy as np +from tokagym import TokamakMagneticEnv +env = TokamakMagneticEnv('mastu_diverted_hold', randomization='none', solver='nonlinear') +obs, info = env.reset(seed=0) +assert obs.shape == (585,) and np.isfinite(obs).all() +obs, reward, terminated, truncated, info = env.step(np.zeros(12)) +assert np.isfinite(obs).all() and np.isfinite(reward) +print(json.dumps({'reset_and_step_ok': True, 'observation_shape': list(obs.shape)})) +""" + with (STATE / "simulator-preflight.log").open("w") as log: + subprocess.run([sys.executable, "-c", code], cwd=WORKSPACE, env=env, + preexec_fn=researcher, stdout=log, stderr=subprocess.STDOUT, + timeout=300, check=True) + probe.unlink() + + +def checked_codex_version(): + version = subprocess.check_output(["codex", "--version"], text=True).strip() + if version != f"codex-cli {CODEX_VERSION}": + raise RuntimeError(f"The sandbox adapter requires Codex {CODEX_VERSION}, got {version}") + return version + + +def validate(args): + version = checked_codex_version() + env = configure_workspace() + try: + preflight(args, env, check_resume=True) + finally: + stop_research() + status("complete", validation_only=True, codex_version=version, + model=args.model, reasoning=args.reasoning, service_tier="default", session_resume_ok=True, + network_isolation=network_isolation()) + return 0 + + +def network_isolation(): + return ("loopback-only-user-network-namespace+gpu-landlock" if gpu_count(TASK_ID) > 1 + else "gpu-compatible-seccomp-helper") + + +def load_research_state(args, version): + expected = {"budget_seconds": args.seconds, "model": args.model, + "task": TASK_ID, "gpu_count": gpu_count(TASK_ID), + "single_slot": os.environ.get("SPEEDRUN_SINGLE_SLOT") == "1", + "reasoning": args.reasoning, "codex_version": version, + "service_tier": "default", "network_isolation": network_isolation()} + path = STATE / "research-state.json" + if not path.exists(): + return {"metadata": expected, "elapsed_seconds": 0, "turns": 0, + "quick_turns": 0, "last_hash": None, "attempt": 0, "phase": "initializing"} + saved = json.loads(path.read_text()) + for key, value in expected.items(): + observed = saved["metadata"].get(key, "tokamak-magnetic-control" if key == "task" else None) + if key == "gpu_count" and observed is None: + observed = 8 if TASK_ID in PROFILES else 1 + if key == "single_slot" and observed is None: + observed = False + if observed != value: + raise RuntimeError(f"Cannot resume with changed {key}") + if saved["phase"] == "failed": + raise RuntimeError("Research failed; inspect the saved error before retrying") + if saved["phase"] == "running": + # A hard kill can lose at most one heartbeat. Conservatively charge it + # so interrupted jobs never gain additional research budget. + saved["elapsed_seconds"] = min(args.seconds, saved["elapsed_seconds"] + HEARTBEAT_SECONDS) + return saved + + +def trajectory_events(path, offset=0): + if not path.exists(): + return + with path.open() as stream: + stream.seek(offset) + for line in stream: + try: + yield json.loads(line) + except json.JSONDecodeError: + continue # The current writer may have an incomplete last line. + + +def trajectory_thread(path, offset=0): + threads = {event["thread_id"] for event in trajectory_events(path, offset) + if event.get("type") == "thread.started"} + if len(threads) > 1: + raise RuntimeError("Research trajectory contains different Codex sessions") + return next(iter(threads), None) + + +def capacity_failure(path, offset=0): + """Only the terminal error from this invocation can authorize a retry.""" + terminal = None + for event in trajectory_events(path, offset): + if event.get("type") == "turn.started": + terminal = None + elif event.get("type") == "turn.failed": + terminal = event.get("error", {}).get("message", "") + if not terminal: + return None + allowed = ("selected model is at capacity", "currently experiencing high demand") + return terminal if any(value in terminal.lower() for value in allowed) else None + + +def capacity_delay(retries): + return min(300, 30 * 2 ** min(retries, 4)) + + +def checked_preflight(args, env): + for retry in range(MAX_CAPACITY_RETRIES + 1): + try: + preflight(args, env) + return + except Exception: + reason = capacity_failure(STATE / "preflight.jsonl") + if not reason or retry == MAX_CAPACITY_RETRIES: + raise + archive = STATE / "preflight-retries" / f"{time.time_ns()}" + archive.mkdir(parents=True) + for name in ("preflight.jsonl", "preflight.stderr"): + (STATE / name).replace(archive / name) + delay = capacity_delay(retry) + status("preflight-retrying", retry=retry + 1, delay_seconds=delay, reason=reason) + time.sleep(delay) + + +def submission_entrypoint(): + if TASK_ID in PROFILES: + return PROFILES[TASK_ID]["entrypoint"] + return "infer.py" if TASK_ID == EARTH else "infer.sh" + + +def agent(args): + with (STATE / "supervisor.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + return research(args) + + +def research(args): + saved = load_research_state(args, checked_codex_version()) + if saved["phase"] == "complete": + if fingerprint(STATE / "submission") != saved["last_hash"]: + raise RuntimeError("Completed submission changed") + return 0 + env = configure_workspace(resume=saved["attempt"] > 0) + saved["attempt"] += 1 + metadata = saved["metadata"] + saved["phase"] = "preflight" + write_json(STATE / "research-state.json", saved) + if saved["attempt"] > 1: + archive = STATE / "attempts" / f"{saved['attempt'] - 1:03d}" + archive.mkdir(parents=True, exist_ok=True) + for name in ("preflight.jsonl", "preflight.stderr", "preflight-result.json", "simulator-preflight.log"): + path = STATE / name + if path.exists(): + path.replace(archive / name) + checked_preflight(args, env) + metadata.setdefault("started_unix", time.time()) + write_json(STATE / "trial.json", metadata) + base_elapsed = saved["elapsed_seconds"] + start = time.monotonic() + deadline = start + max(0, args.seconds - base_elapsed) + turn = saved["turns"] + quick = saved["quick_turns"] + last_hash = saved["last_hash"] + trajectory = STATE / "trajectory.jsonl" + thread_id = saved.get("thread_id") or trajectory_thread(trajectory) + recovery_notice = STATE / "recovery-notice.txt" + notice = recovery_notice.read_text() if recovery_notice.exists() else "" + failure = None + charged_elapsed = None + retries = 0 + interrupted = [] + old_handlers = {sig: signal.signal(sig, lambda signum, frame: interrupted.append(signum)) + for sig in (signal.SIGTERM, signal.SIGINT)} + + def persist(phase): + elapsed = charged_elapsed if charged_elapsed is not None else min( + args.seconds, base_elapsed + time.monotonic() - start) + saved.update(phase=phase, elapsed_seconds=elapsed, thread_id=thread_id, + turns=turn, quick_turns=quick, last_hash=last_hash, error=failure) + write_json(STATE / "research-state.json", saved) + + # Copy/hash large packages off the deadline/heartbeat thread. In particular, + # vendored runtimes must not keep research processes alive beyond the budget. + snapshots = ThreadPoolExecutor(max_workers=1) + pending_snapshot = None + next_snapshot = next_heartbeat = next_status = 0 + + def maintain(): + nonlocal pending_snapshot, last_hash, next_snapshot, next_heartbeat, next_status + now = time.monotonic() + if pending_snapshot is not None and pending_snapshot.done(): + last_hash = pending_snapshot.result() + pending_snapshot = None + if now >= next_snapshot and pending_snapshot is None: + pending_snapshot = snapshots.submit(snapshot, start - base_elapsed, last_hash) + next_snapshot = now + 60 + if now >= next_heartbeat: + persist("running") + next_heartbeat = now + HEARTBEAT_SECONDS + if now >= next_status: + status("running", **metadata, elapsed_seconds=int(base_elapsed + now - start), + turn=turn, attempt=saved["attempt"], thread_id=thread_id, + capacity_retries=retries, latest_submission_sha256=last_hash) + next_status = now + 60 + + persist("running") + status("running", **metadata, attempt=saved["attempt"], elapsed_seconds=base_elapsed) + try: + with (STATE / "trajectory.jsonl").open("a", buffering=1) as out, \ + (STATE / "codex.stderr").open("a", buffering=1) as err: + while time.monotonic() < deadline and not interrupted: + turn_start = time.monotonic() + resume = thread_id or any((Path(env["CODEX_HOME"]) / "sessions").rglob("*.jsonl")) + offset = trajectory.stat().st_size + process = start_codex(codex_command(args, resume=resume), env, out, err) + prompt = CONTINUE if resume else (WORKSPACE / "instruction.md").read_text() + if not resume and TASK_ID in PROFILES and gpu_count(TASK_ID) == 1: + prompt += ("\n\nOperator resource override for this reduced-compute trial: " + "you have exactly ONE H100 GPU. " + "This overrides any eight-GPU research budget in the task documents. " + "All scientific rules, data restrictions, submission requirements, and " + "evaluation criteria still apply. Adapt your research to this allocation.") + if os.environ.get("SPEEDRUN_SINGLE_SLOT") == "1": + prompt += " CPU and RAM are also reduced to a request of 22 CPUs and 224 GiB RAM." + if notice: + prompt += "\n\n" + notice + notice = "" + process.stdin.write(prompt) + process.stdin.close() + turn += 1 + checked_thread = False + while process.poll() is None and time.monotonic() < deadline and not interrupted: + if not checked_thread: + observed = trajectory_thread(trajectory, offset) + if observed: + if thread_id and observed != thread_id: + raise RuntimeError("Codex resumed a different research session") + thread_id, checked_thread = observed, True + maintain() + time.sleep(min(2, max(0, deadline - time.monotonic()))) + if not checked_thread: + observed = trajectory_thread(trajectory, offset) + if observed: + if thread_id and observed != thread_id: + raise RuntimeError("Codex resumed a different research session") + thread_id = observed + if time.monotonic() >= deadline or interrupted: + break + if process.returncode != 0: + reason = capacity_failure(trajectory, offset) + if reason and retries < MAX_CAPACITY_RETRIES: + delay = capacity_delay(retries) + retries += 1 + with (STATE / "capacity-retries.jsonl").open("a") as log: + log.write(json.dumps({"unix": time.time(), "turn": turn, + "retry": retries, "delay_seconds": delay, "reason": reason}) + "\n") + until = min(deadline, time.monotonic() + delay) + while time.monotonic() < until and not interrupted: + maintain() + time.sleep(min(2, max(0, until - time.monotonic()))) + continue + failure = f"Codex exited with status {process.returncode}" + break + retries = 0 + quick = quick + 1 if time.monotonic() - turn_start < 120 else 0 + if quick >= 3: + failure = "Three consecutive short turns; stopping a stalled continuation loop" + break + except Exception as error: + failure = str(error) + finally: + stop_research() + # Research has stopped; final snapshot/collection time must not silently + # change the remaining research budget or disagree between status files. + charged_elapsed = min(args.seconds, base_elapsed + time.monotonic() - start) + if pending_snapshot is not None: + last_hash = pending_snapshot.result() + snapshots.shutdown(wait=True) + last_hash = snapshot(start - base_elapsed, last_hash) + persist("interrupted" if interrupted else "running") + for sig, handler in old_handlers.items(): + signal.signal(sig, handler) + if interrupted: + status("interrupted", **metadata, elapsed_seconds=saved["elapsed_seconds"], + attempt=saved["attempt"], turns=turn, submission_sha256=last_hash) + return 128 + interrupted[0] + elapsed = saved["elapsed_seconds"] + src = WORKSPACE / "submission" + if not (src / submission_entrypoint()).is_file(): + failure = failure or f"No runnable {submission_entrypoint()} was published" + elif last_hash: + dst = STATE / "submission" + if dst.exists(): + if fingerprint(dst) != last_hash: + raise RuntimeError("Frozen submission differs from the completed research") + else: + staging = STATE / ".submission-staging" + shutil.rmtree(staging, ignore_errors=True) + shutil.copytree(src, staging, symlinks=True) + if fingerprint(staging) != last_hash: + raise RuntimeError("Final submission snapshot changed") + staging.rename(dst) + if elapsed < args.seconds: + failure = failure or "Trial stopped before its full time budget" + persist("failed" if failure else "complete") + status(saved["phase"], **metadata, elapsed_seconds=elapsed, attempt=saved["attempt"], + turns=turn, submission_sha256=last_hash, error=failure) + return 1 if failure else 0 + + +def deny_network(): + """Irreversible seccomp ban on IPv4/IPv6 sockets, inherited by verifier children. + + AF_UNIX remains available to multiprocessing. This requires no privileged + network namespace or host firewall modifications. + """ + lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) + class Compare(ctypes.Structure): + _fields_ = [("arg", ctypes.c_uint), ("op", ctypes.c_int), + ("datum_a", ctypes.c_uint64), ("datum_b", ctypes.c_uint64)] + lib.seccomp_init.argtypes = [ctypes.c_uint32] + lib.seccomp_init.restype = ctypes.c_void_p + lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] + lib.seccomp_syscall_resolve_name.restype = ctypes.c_int + lib.seccomp_rule_add_array.argtypes = [ctypes.c_void_p, ctypes.c_uint32, + ctypes.c_int, ctypes.c_uint, ctypes.POINTER(Compare)] + lib.seccomp_load.argtypes = [ctypes.c_void_p] + lib.seccomp_release.argtypes = [ctypes.c_void_p] + ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW + if not ctx: + raise RuntimeError("seccomp_init failed") + try: + for domain in (2, 10): # AF_INET, AF_INET6 + cmp = Compare(0, 4, domain, 0) # SCMP_CMP_EQ + rc = lib.seccomp_rule_add_array(ctx, 0x00050000 | errno.EPERM, + lib.seccomp_syscall_resolve_name(b"socket"), 1, + ctypes.byref(cmp)) + if rc != 0: + raise RuntimeError(f"seccomp_rule_add failed: {rc}") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("seccomp_load failed") + finally: + lib.seccomp_release(ctx) + import socket + for family in (socket.AF_INET, socket.AF_INET6): + try: + sock = socket.socket(family) + except PermissionError: + continue + sock.close() + raise RuntimeError("Verifier network isolation check failed") + + +def verify(args): + if TASK_ID != "tokamak-magnetic-control": + raise RuntimeError("This verifier adapter only supports tokamak") + status("verifying") + src = STATE / "submission" + if not (src / "infer.sh").is_file(): + raise RuntimeError("Missing inference package") + package_hash = fingerprint(src) + shutil.copytree(src, WORKSPACE / "submission", dirs_exist_ok=True, symlinks=True) + deny_network() + write_json(STATE / "isolation.json", {"inet_sockets_blocked": True, "ipv6_sockets_blocked": True}) + env = {**os.environ, "TOKAGYM_WORKERS": str(args.workers)} + started = time.time() + with (STATE / "verifier.log").open("w") as log: + result = subprocess.run(["bash", "/tests/test.sh"], env=env, stdout=log, + stderr=subprocess.STDOUT, timeout=args.seconds) + shutil.copytree("/logs/verifier", STATE / "results", dirs_exist_ok=True) + score = STATE / "results/reward.json" + reward = json.loads(score.read_text()) if score.exists() else None + status("complete" if result.returncode == 0 and reward is not None else "failed", + returncode=result.returncode, reward=reward, elapsed_seconds=time.time() - started, + submission_sha256=package_hash) + return 0 if result.returncode == 0 and reward is not None else 1 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("mode", choices=["agent", "verify", "preflight"]) + parser.add_argument("--seconds", type=int, default=3600) + parser.add_argument("--model", default="gpt-6.1-sol") + parser.add_argument("--reasoning", default="medium") + parser.add_argument("--workers", type=int, default=35) + parser.add_argument("--gpus", type=int, choices=[1, 8]) + parser.add_argument("--single-slot", action="store_true") + args = parser.parse_args() + if args.single_slot: + if args.gpus not in (None, 1): + parser.error("--single-slot cannot use eight GPUs") + args.gpus = 1 + os.environ["SPEEDRUN_SINGLE_SLOT"] = "1" + if args.gpus is not None: + os.environ["SPEEDRUN_GPU_COUNT"] = str(args.gpus) + STATE.mkdir(exist_ok=True) + try: + return {"agent": agent, "verify": verify, "preflight": validate}[args.mode](args) + except Exception as error: + import traceback + traceback.print_exc() + status("failed", error=str(error)) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/reproduction/files/ad/adae1277e85debfd8acccedefcb17519acd54ab834dc2eacd98c145ade83920e/native_runtime.sh b/reproduction/files/ad/adae1277e85debfd8acccedefcb17519acd54ab834dc2eacd98c145ade83920e/native_runtime.sh new file mode 100644 index 0000000000000000000000000000000000000000..09c3909d664b2c03549c0aba34c95b5006b03f08 --- /dev/null +++ b/reproduction/files/ad/adae1277e85debfd8acccedefcb17519acd54ab834dc2eacd98c145ade83920e/native_runtime.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +set -eo pipefail +backend="$1" +shift +source /etc/profile +module purge +case "$backend" in + maia) module load MAIA/1.0-NVHPC-26.1 ;; + jax|jax-fluids) unset LD_LIBRARY_PATH; module load Python/3.12.3-GCCcore-13.3.0 ;; + *) echo "Unsupported native backend: $backend" >&2; exit 2 ;; +esac +source /home/easybuild/venvs/hydrogym_gpu/bin/activate +set -u +export OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 +export PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 +export XLA_PYTHON_CLIENT_PREALLOCATE=false +exec "$@" diff --git a/reproduction/files/ae/ae3d94807c0301dd4d85712db0b8d25c8c4d0d669f4a79a0a084661acd66bc67/analyze_subgroups.py b/reproduction/files/ae/ae3d94807c0301dd4d85712db0b8d25c8c4d0d669f4a79a0a084661acd66bc67/analyze_subgroups.py new file mode 100644 index 0000000000000000000000000000000000000000..1cb1d6c77541503e633b498ba660a79a7ed53658 --- /dev/null +++ b/reproduction/files/ae/ae3d94807c0301dd4d85712db0b8d25c8c4d0d669f4a79a0a084661acd66bc67/analyze_subgroups.py @@ -0,0 +1,132 @@ +"""Compare fixed predictions by disease frequency, horizon, and history span.""" + +from __future__ import annotations + +import argparse +import json +from datetime import timedelta +from pathlib import Path + +import duckdb +import numpy as np +import pyarrow.parquet as pq + +from risk_scoring import HORIZONS, disease_time_discrimination, read_predictions + + +def primary(labels: np.ndarray, prediction: np.ndarray, valid: np.ndarray) -> dict: + summary, _ = disease_time_discrimination(labels, prediction, valid) + return summary + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--trusted", type=Path, required=True) + parser.add_argument("--normalization", type=Path, + help="accepted for backwards-compatible commands; unused by AUROC") + parser.add_argument("--prediction", action="append", required=True, help="name=parquet") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + + manifest = json.loads((args.input / "manifest.json").read_text()) + diseases = manifest["scored_diseases"] + samples = pq.read_table(args.input / "samples.parquet").to_pylist() + sample_ids = [row["sample_id"] for row in samples] + sample_index = {sample_id: i for i, sample_id in enumerate(sample_ids)} + disease_index = {code: i for i, code in enumerate(diseases)} + shape = (len(sample_ids), len(diseases), len(HORIZONS)) + labels = np.zeros(shape, np.uint8) + valid = np.zeros(shape, bool) + columns = ["sample_id", "disease_code"] + [ + f"{prefix}_{horizon}" for horizon in HORIZONS + for prefix in ("disease_label", "disease_valid") + ] + seen = set() + for batch in pq.ParquetFile(args.trusted / "label_windows.parquet").iter_batches( + batch_size=65536, columns=columns): + values = batch.to_pydict() + for row in range(batch.num_rows): + key = (values["sample_id"][row], values["disease_code"][row]) + if key in seen: + raise ValueError(f"duplicate label key: {key}") + seen.add(key) + i, j = sample_index[key[0]], disease_index[key[1]] + for k, horizon in enumerate(HORIZONS): + labels[i, j, k] = values[f"disease_label_{horizon}"][row] + valid[i, j, k] = values[f"disease_valid_{horizon}"][row] + if len(seen) != len(sample_ids) * len(diseases): + raise ValueError("label key coverage is incomplete") + + boundaries = { + row["sample_id"]: row + for row in pq.read_table(args.trusted / "sample_boundaries.parquet").to_pylist() + } + year = timedelta(days=365) + def as_date(value): + return value.date() if hasattr(value, "date") else value + primary_cohort = np.asarray([ + as_date(row["cutoff"]) + year <= boundaries[row["sample_id"]]["diagnosis_observation_end"] + and as_date(row["cutoff"]) + year <= boundaries[row["sample_id"]]["death_observation_end"] + for row in samples + ]) + valid &= primary_cohort[:, None, None] + + db = duckdb.connect() + span_rows = db.execute(""" + SELECT s.sample_id, + date_diff('day', min(e.event_time), s.cutoff) AS history_days + FROM read_parquet(?) s + JOIN read_parquet(?) e USING (sample_id) + GROUP BY s.sample_id, s.cutoff + """, [str(args.input / "samples.parquet"), str(args.input / "events.parquet")]).fetchall() + db.close() + spans = dict(span_rows) + history_days = np.asarray([spans[sample_id] for sample_id in sample_ids], dtype=np.float64) + history_quartiles = np.quantile(history_days, [.25, .5, .75]) + + normalization = pq.read_table(args.trusted.parent / "risk_normalization.parquet").to_pandas() + frequency = (normalization[normalization.horizon_days == 365] + .set_index("disease_code").loc[diseases, "train_positive"].to_numpy()) + frequency_quartiles = np.quantile(frequency, [.25, .5, .75]) + history_groups = [ + history_days <= history_quartiles[0], + (history_days > history_quartiles[0]) & (history_days <= history_quartiles[1]), + (history_days > history_quartiles[1]) & (history_days <= history_quartiles[2]), + history_days > history_quartiles[2], + ] + frequency_groups = [ + frequency <= frequency_quartiles[0], + (frequency > frequency_quartiles[0]) & (frequency <= frequency_quartiles[1]), + (frequency > frequency_quartiles[1]) & (frequency <= frequency_quartiles[2]), + frequency > frequency_quartiles[2], + ] + + result = { + "schema": "ndp-auroc-subgroup-comparison/v2", + "history_days_quartiles": history_quartiles.tolist(), + "train_365d_positive_quartiles": frequency_quartiles.tolist(), + "models": {}, + } + for item in args.prediction: + name, path = item.split("=", 1) + prediction, _ = read_predictions(Path(path), sample_ids, len(diseases)) + model = {"overall": primary(labels, prediction, valid), + "by_horizon": {}, "by_history": {}, "by_frequency": {}} + for k, horizon in enumerate(HORIZONS): + model["by_horizon"][str(horizon)] = primary( + labels[:, :, k:k + 1], prediction[:, :, k:k + 1], valid[:, :, k:k + 1]) + for i, group in enumerate(history_groups): + model["by_history"][f"q{i + 1}"] = primary( + labels[group], prediction[group], valid[group]) + for i, group in enumerate(frequency_groups): + model["by_frequency"][f"q{i + 1}"] = primary( + labels[:, group], prediction[:, group], valid[:, group]) + result["models"][name] = model + + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/ae/aef2321cce2e82f6c36a3fbd1a2db5cc0bd6eee8802e1af97df1a3fb7fcf30bb/test_lfmc_batch.py b/reproduction/files/ae/aef2321cce2e82f6c36a3fbd1a2db5cc0bd6eee8802e1af97df1a3fb7fcf30bb/test_lfmc_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa50054f8014448e5954fb4dcafe1eeed2075e1 --- /dev/null +++ b/reproduction/files/ae/aef2321cce2e82f6c36a3fbd1a2db5cc0bd6eee8802e1af97df1a3fb7fcf30bb/test_lfmc_batch.py @@ -0,0 +1,35 @@ +"""Paired crop streams are independent of dataset traversal and worker RNG.""" + +from pathlib import Path +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/downstream")) +from lfmc_batch import LFMCWindows + + +class TestBatch(unittest.TestCase): + def test_paired_epoch_and_window_rng(self): + rows = [{"id": n, "split": "train", "path": n} for n in ["b", "a"]] + a = LFMCWindows(rows, "train", 123) + b = LFMCWindows(list(reversed(rows)), "train", 123) + + def read(path, *, rng=None, center_on_label=False): + return {"id": path, "split": "train", "crop": rng.getrandbits(64)} + + with patch("lfmc_batch.read_window", side_effect=read): + initial = a[0] + self.assertEqual(initial, b[0]) + self.assertEqual(a[1], b[1]) + self.assertEqual(initial, a[0]) + a.set_epoch(1) + b.set_epoch(1) + self.assertEqual(a[0], b[0]) + self.assertNotEqual(initial["crop"], a[0]["crop"]) + with self.assertRaises(ValueError): + LFMCWindows(rows, "test") + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/b0/b056c497d7d6864cec8aacfdd2988d56b26149330e39d14c0e54119416878f2b/labels.py b/reproduction/files/b0/b056c497d7d6864cec8aacfdd2988d56b26149330e39d14c0e54119416878f2b/labels.py new file mode 100644 index 0000000000000000000000000000000000000000..892785d91ac664a678e7d558c6fd1b104134d23d --- /dev/null +++ b/reproduction/files/b0/b056c497d7d6864cec8aacfdd2988d56b26149330e39d14c0e54119416878f2b/labels.py @@ -0,0 +1,7 @@ +"""Import the public label rules into the trusted scoring package.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "data")) +from label_rules import death_label, disease_label # noqa: E402,F401 diff --git a/reproduction/files/b0/b0c3514c9036697ee4a93daec45cae7c0b0b54f92fbc51780000a8f9ad0c3513/common.py b/reproduction/files/b0/b0c3514c9036697ee4a93daec45cae7c0b0b54f92fbc51780000a8f9ad0c3513/common.py new file mode 100644 index 0000000000000000000000000000000000000000..b5f9f2780ead5138d59ea02d14be8ad199020ffe --- /dev/null +++ b/reproduction/files/b0/b0c3514c9036697ee4a93daec45cae7c0b0b54f92fbc51780000a8f9ad0c3513/common.py @@ -0,0 +1,17 @@ +"""Shared sealed-output helpers for the independent verifier phases.""" + +import hashlib +import json +from pathlib import Path + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_json(path: Path, value) -> None: + path.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") diff --git a/reproduction/files/b3/b3f1276be2a884273408f84a5e6f6d43f165c77c93d4d837944c623e96dbb65f/native_verifier.py b/reproduction/files/b3/b3f1276be2a884273408f84a5e6f6d43f165c77c93d4d837944c623e96dbb65f/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..d5bba3b8e7cce144f6a948a2c0c5ffec58120047 --- /dev/null +++ b/reproduction/files/b3/b3f1276be2a884273408f84a5e6f6d43f165c77c93d4d837944c623e96dbb65f/native_verifier.py @@ -0,0 +1,292 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import shutil +import signal +import socket +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def enter_offline_namespace(): + import offline_network + record = offline_network.configure(STATE) + libc = ctypes.CDLL(None, use_errno=True) + for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)): + fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC) + try: + if libc.setns(fd, flag): + raise OSError(ctypes.get_errno(), 'enter offline verifier namespace') + finally: + os.close(fd) + if socket.if_nameindex() != [(1, 'lo')]: + raise RuntimeError('Offline verifier namespace has external interfaces') + return record + + +def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')): + """End the native waiting supervisor only after its authenticated seal.""" + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + seconds + sealed_ready = False + try: + while process.poll() is None: + if (sealed_root / 'READY').is_file(): + marker = json.loads((sealed_root / 'READY').read_text()) + snapshot = sealed_root / 'run/snapshot.json' + if (hashlib.sha256(snapshot.read_bytes()).hexdigest() != marker['snapshot_sha256'] + or json.loads(snapshot.read_text())['run_id'] != marker['run_id']): + raise RuntimeError('Native seal marker is inconsistent') + sealed_ready = True + break + if time.monotonic() >= deadline: + raise TimeoutError('Verifier inference budget exhausted') + time.sleep(.1) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode) + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + adapted = cfg.get('adapted_permissions', False) + if adapted: + import adapted_boundary + adapted_boundary.no_new_privileges() + os.setgroups([]) + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus'], strict_allocation=adapted) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + if adapted: + adapted_boundary.exact_gpu_allocation(gpu_policy) + else: + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + if cfg.get('gpu_runtime', 'torch') == 'torch': + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if cfg.get('local_benchmark_copy'): + # Folding's upstream evaluator runs inference and grading together. + # Give its non-root process a local readable copy, never relax Weka ACLs. + shutil.copytree('/source-benchmark', '/benchmark', symlinks=False) + for path in [Path('/benchmark'), *Path('/benchmark').rglob('*')]: + path.chmod(0o555 if path.is_dir() else 0o444) + if phase == 'inference': + if cfg.get('native_uid_isolation'): + # The original PDE verifier explicitly supports this UID fallback. + # The mount is below a local root-only parent, never chmod shared data. + Path('/private').chmod(0o700) + Path('/tests').chmod(0o700) + elif plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + subprocess.run(['/usr/sbin/useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + if adapted and cfg.get('network_policy') != 'policy-children-only': + adapted_boundary.restrict_network() + elif not offline and not adapted: + runtime.deny_network() + if not adapted: + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets'], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc', + *cfg.get('writable_runtime_paths', [])]) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + if adapted: + source_audit = adapted_boundary.audit_source_permissions( + ['/operator', '/submission-source', '/source-benchmark', '/benchmark', '/data', '/labels', '/private'], + untrusted_uids=tuple(range(10001, 10009))) + else: + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' and not adapted else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + if cfg.get('gpu_runtime') == 'jax': + probe = ('import jax; import jax.numpy as jnp; ' + f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in d.device_kind for d in jax.devices("gpu")); ' + 'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 ' + 'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': ('seccomp in unprivileged policy children; trusted simulator retains MPI sockets' + if cfg.get('network_policy') == 'policy-children-only' else + 'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children'), + 'offline_namespace': offline, + 'source_mounts': f'POSIX permission audit ({source_audit} entries); non-root submission' if adapted else 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan.get('label_isolated', plan['task'] != 'protein-folding-prediction'), + 'adapted_execution': adapted, + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + if cfg.get('stop_after_sealed_ready'): + # The native supervisor has already killed all model processes and + # sealed/hashes its predictions before writing READY. End only its + # wait-for-grader loop; the unchanged grader runs in a separate job. + result = run_until_sealed(cfg['command'], log, remaining) + else: + def run_identity(): + os.setgroups([]) + os.setgid(10001) + os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + os.chown(STATE / 'results', 10001, 10001) + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True, + preexec_fn=run_identity if cfg.get('untrusted_whole_verifier') else None) + elapsed = time.monotonic() - entered + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + reward_path = STATE / 'results/reward.json' + if phase == 'score': + score_root = Path('/sealed/results') + if cfg.get('results_by_run_id'): + score_root /= json.loads(Path('/sealed/READY').read_text())['run_id'] + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = score_root / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/b5/b5606b0c450cdb95e8b1e5bb7407a353a32f63c49a276d8e4e4cec1696ac31d7/test_frozen_coverage.py b/reproduction/files/b5/b5606b0c450cdb95e8b1e5bb7407a353a32f63c49a276d8e4e4cec1696ac31d7/test_frozen_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9d0a887e467406442b91946020e3c28bd09bb6 --- /dev/null +++ b/reproduction/files/b5/b5606b0c450cdb95e8b1e5bb7407a353a32f63c49a276d8e4e4cec1696ac31d7/test_frozen_coverage.py @@ -0,0 +1,51 @@ +"""Actual frozen release integration; short-loop evidence is not a policy score.""" +import json +from pathlib import Path +import sys +import unittest + +DATA=Path(__file__).resolve().parents[1]/'environment/data' +sys.path.insert(0,str(DATA)) +import coverage_release +import public_release + + +@unittest.skipUnless((DATA/'selection-coverage-v1.json').exists(), 'Coverage decision not frozen yet') +class FrozenCoverageTests(unittest.TestCase): + def test_current_manifest_is_exact_reviewed_build(self): + archive=DATA/'release-coverage-v1.json' + release=public_release.load_release(archive) if archive.exists() else public_release.load_release() + self.assertEqual(release,coverage_release.build_current()) + self.assertLessEqual(release['files']['bytes'],500_000_000_000) + self.assertGreater(release['case_count'],28) + self.assertEqual(release['training']['case_ids'],release['test']['case_ids']) + self.assertTrue(release['test']['one_shared_checkpoint']) + self.assertFalse(release['test']['parameter_updates']) + self.assertFalse(release['test']['normalizer_updates']) + self.assertEqual(release['status'],'data-release-not-cfd-certified') + for case in release['cases']: + record=case['cost_screening'] + self.assertGreaterEqual(len(record['timing_samples_seconds']),2) + self.assertEqual(record['container_exit_code'],0) + self.assertEqual(case['execution_status'],'short_loop_passed_full_evaluation_pending') + + def test_previous_release_identities_are_preserved(self): + for filename,expected in [ + ('release-speed-v1.json','23c53782f87b91c9be8babee3cab5e7cd16730c9dc79eb46d1b19c796be82890'), + ('release-500gb-v1.json','226b7059b4b6b34bb4a8f169374f2a6bc74bc4f780b22ccbc3171c06b34778f3')]: + with self.subTest(filename=filename): + release=public_release.load_release(DATA/filename) + self.assertEqual(public_release.digest(release),expected) + + def test_all_complete_candidates_have_one_decision(self): + selection=json.loads((DATA/'selection-coverage-v1.json').read_text()) + included={r['case'] for r in selection['included']} + excluded={r['case'] for r in selection['excluded_complete_resources']} + self.assertFalse(included & excluded) + self.assertEqual(len(included | excluded),62) + self.assertTrue(selection['policy']['unknown_is_not_slow']) + self.assertIsNone(selection['policy']['global_seconds_per_control_cutoff']) + + +if __name__=='__main__': + unittest.main() diff --git a/reproduction/files/b6/b6438b1d094cf4807a5e64d8f3198b72a201b2002751c68ede575b1ddb65556b/test_native_resource_bindings.py b/reproduction/files/b6/b6438b1d094cf4807a5e64d8f3198b72a201b2002751c68ede575b1ddb65556b/test_native_resource_bindings.py new file mode 100644 index 0000000000000000000000000000000000000000..820f0a9726ef5aeaff2bcfe7f48e6ad8e3986595 --- /dev/null +++ b/reproduction/files/b6/b6438b1d094cf4807a5e64d8f3198b72a201b2002751c68ede575b1ddb65556b/test_native_resource_bindings.py @@ -0,0 +1,30 @@ +"""Unit tests of explicit loader correction, not CFD performance evidence.""" +import copy +from pathlib import Path +import sys +import unittest + +sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'environment/data')) +from native_resource_bindings import bind_nozzle_restart + + +class NativeResourceBindingsTests(unittest.TestCase): + def test_only_missing_restart_switch_added_without_source_mutation(self): + original={'domain':{'x':{'cells':500}},'initial_condition':{'levelset':'placeholder'}, + 'boundary_conditions':{'unchanged':True}} + before=copy.deepcopy(original) + for name in ['Nozzle2D_fine','Nozzle3D_coarse']: + result=bind_nozzle_restart(name,original,'/data/'+name+'/restart.h5') + self.assertEqual(result.pop('restart'),{'is_restart':True,'file_path':'/data/'+name+'/restart.h5'}) + self.assertEqual(result,original) + self.assertEqual(original,before) + + def test_existing_choice_and_unreviewed_cases_are_rejected(self): + for case,setup in [('Nozzle2D_coarse',{}),('Nozzle3D_fine',{}), + ('Nozzle2D_fine',{'restart':{'is_restart':False}})]: + with self.subTest(case=case),self.assertRaises(ValueError): + bind_nozzle_restart(case,setup,'/data/restart.h5') + + +if __name__=='__main__': + unittest.main() diff --git a/reproduction/files/b6/b6a176aa46cf4b974f82e8899160b41f035d28b22fa632265ea2c3a11637158a/predict.py b/reproduction/files/b6/b6a176aa46cf4b974f82e8899160b41f035d28b22fa632265ea2c3a11637158a/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd544d181cf041eafbf0036a8fd562b94b128e4 --- /dev/null +++ b/reproduction/files/b6/b6a176aa46cf4b974f82e8899160b41f035d28b22fa632265ea2c3a11637158a/predict.py @@ -0,0 +1,142 @@ +"""Run fixed physical calculations against a model's ASE calculator. + +This is a development evaluator, not yet a sandbox for untrusted submissions. +""" + +from __future__ import annotations + +import argparse +import importlib +import importlib.metadata +import importlib.util +import json +from pathlib import Path +import platform +import time + +from common import PROTOCOL, digest, indexed, read_rows, with_oom_retry, write_json +from physics import CALCULATIONS + + +def load_calculator(factory: str, artifact: Path | None, device: str): + if factory == "uma": + if artifact is None or not artifact.is_file(): + raise ValueError("UMA requires --artifact pointing to a local checkpoint") + from fairchem.core import FAIRChemCalculator + from fairchem.core.calculate.pretrained_mlip import load_predict_unit + + unit = load_predict_unit( + str(artifact), + device=device, + inference_settings="default", + ) + return FAIRChemCalculator(unit, task_name="omat") + if factory == "submission": + # Contract: ARTIFACT is the submission directory; calculator.py defines + # make_calculator(submission_dir, device) returning an ASE calculator (E/F/S). + spec = importlib.util.spec_from_file_location("submission_calculator", Path(artifact) / "calculator.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module.make_calculator(Path(artifact), device) + if factory == "emt": + from ase.calculators.emt import EMT + + return EMT() # plumbing-only baseline; not a universal materials model + module, function = factory.split(":", 1) + return getattr(importlib.import_module(module), function)(artifact, device) + + +def run( + inputs: Path, + output: Path, + factory, + artifact=None, + device="cpu", + energy_audit=None, + calculator=None, + verbose=True, +): + cases = read_rows(inputs) + indexed(cases) + if output.exists(): + raise FileExistsError(f"Refusing to mix/overwrite predictions: {output}") + output.mkdir(parents=True) + versions = {} + for package in ("numpy", "ase", "pymatgen", "phonopy", "fairchem-core", "torch"): + try: + versions[package] = importlib.metadata.version(package) + except importlib.metadata.PackageNotFoundError: + pass + metadata = { + "protocol": PROTOCOL, + "inputs_sha256": digest(inputs), + "factory": factory, + "checkpoint_sha256": digest(artifact) if artifact and artifact.exists() else None, + "device": device, + "platform": platform.platform(), + "versions": versions, + "cases": len(cases), + "complete": False, + } + if energy_audit is not None: + audit = json.loads(Path(energy_audit).read_text()) + if audit.get("checkpoint_sha256") != metadata["checkpoint_sha256"]: + raise ValueError("Energy-convention audit belongs to another checkpoint") + metadata["energy_audit"] = audit + metadata["energy_audit_sha256"] = digest(Path(energy_audit)) + write_json(output / "run.json", metadata) + if calculator is None: + calculator = load_calculator(factory, artifact, device) + with (output / "predictions.jsonl").open("w") as stream: + for case in cases: + started = time.monotonic() + record = {"id": case["id"], "suite": case["suite"]} + try: + def calculate(): + calculator.reset() + return CALCULATIONS[case["suite"]](case, calculator) + record.update(with_oom_retry(calculate)) + record["status"] = "ok" + json.dumps(record, allow_nan=False) + except Exception as error: + # Preserve the failure as a record. Scoring rejects incomplete runs. + record = { + "id": case["id"], + "suite": case["suite"], + "status": "failed", + "error": f"{type(error).__name__}: {error}", + } + record["seconds"] = time.monotonic() - started + stream.write(json.dumps(record, allow_nan=False) + "\n") + stream.flush() + if verbose: + print( + f"{case['id']}: {record['status']} ({record['seconds']:.1f}s)", + flush=True, + ) + metadata["complete"] = True + metadata["predictions_sha256"] = digest(output / "predictions.jsonl") + write_json(output / "run.json", metadata) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--inputs", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--factory", default="uma", help="uma, emt, or module:function") + parser.add_argument("--artifact", type=Path) + parser.add_argument("--device", choices=["cpu", "cuda"], default="cuda") + parser.add_argument( + "--energy-audit", + type=Path, + help="Operator-reviewed training provenance for MP-compatible raw energies", + ) + args = parser.parse_args() + run( + args.inputs, + args.output, + args.factory, + args.artifact, + args.device, + args.energy_audit, + ) diff --git a/reproduction/files/b8/b8cd81c4d80b355bdbebf39fe8092def1a543646af1b580f6da75dd61af336fb/docker-compose.yaml b/reproduction/files/b8/b8cd81c4d80b355bdbebf39fe8092def1a543646af1b580f6da75dd61af336fb/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..75ae560ce1e811e38ddad77f065bdd16d0bdff59 --- /dev/null +++ b/reproduction/files/b8/b8cd81c4d80b355bdbebf39fe8092def1a543646af1b580f6da75dd61af336fb/docker-compose.yaml @@ -0,0 +1,19 @@ +services: + main: + build: + context: .. + dockerfile: environment/Dockerfile + target: verifier + # Outer-container settings for the bwrap prediction namespace (verify_single.py), as in the + # weather and earth-observation verifiers: bwrap's user namespace needs seccomp/AppArmor relaxed + # and an unmasked /proc; tests/test.sh detaches the NVIDIA runtime's /proc/driver/nvidia mounts. + security_opt: + - seccomp:unconfined + - apparmor:unconfined + - systempaths=unconfined + cap_add: [SYS_ADMIN] + volumes: + - ${TASK_PRIVATE_DIR:?Set materialized private resources}/image:/benchmark/image:ro + - ${TASK_PRIVATE_DIR:?Set materialized private resources}/suite:/benchmark/suite:ro + - ${TASK_DATA_DIR:?Set materialized development resources}/runtime:/benchmark/runtime:ro + - ${TASK_VERIFIER_SCRATCH:?Set a fresh empty verifier scratch directory}:/workspace/research diff --git a/reproduction/files/b8/b8cd8cbc049638df1f77722e25585e10bbcde8d74cc0abba77c4279a099eba6e/test.sh b/reproduction/files/b8/b8cd8cbc049638df1f77722e25585e10bbcde8d74cc0abba77c4279a099eba6e/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d282fe549375fee2550fb55544c70b9c1c36d534 --- /dev/null +++ b/reproduction/files/b8/b8cd8cbc049638df1f77722e25585e10bbcde8d74cc0abba77c4279a099eba6e/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +exec python3 /tests/main_verifier.py --timeout "${NDP_INFERENCE_TIMEOUT_SECONDS:-42000}" diff --git a/reproduction/files/b9/b97b14b644a63c62c3695b114ba2bc24bb707e2b6cade8929a0520475c63b44e/test_external_lfmc_resolved.py b/reproduction/files/b9/b97b14b644a63c62c3695b114ba2bc24bb707e2b6cade8929a0520475c63b44e/test_external_lfmc_resolved.py new file mode 100644 index 0000000000000000000000000000000000000000..270b9c96ecf4023ccda5a6908b78c90dc6976671 --- /dev/null +++ b/reproduction/files/b9/b97b14b644a63c62c3695b114ba2bc24bb707e2b6cade8929a0520475c63b44e/test_external_lfmc_resolved.py @@ -0,0 +1,109 @@ +"""Recovery must preserve fixed coverage and immutable failure history.""" + +import copy +import json +import shutil +import unittest + +import test_external_lfmc_reconcile as fixture +from test_external_lfmc_reconcile import write +from reconcile_external_lfmc_cohort import digest +from reconcile_external_lfmc_resolved import reconcile_resolved + + +class ResolvedTests(unittest.TestCase): + def setUp(self): + fixture.CohortGateTests.setUp(self) + launch = json.loads(self.launch.read_text()) + launch["output_root"] = str(self.cohort) + write(self.launch, launch) + self.ledger_path = self.root / "ledger.json" + self.ledger = { + "manifest_sha256": digest(self.manifest), + "tasks": 1, + "sites": 1, + "launches": { + "original": { + "path": str(self.launch), + "sha256": digest(self.launch), + "indices": [0], + } + }, + "rows": [{"index": 0, "attempts": [{"launch": "original"}]}], + } + + def resolved(self): + write(self.ledger_path, self.ledger) + return reconcile_resolved(self.manifest, self.ledger_path) + + def retry(self): + retry_root = self.root / "retry" + shutil.copytree(self.directory, retry_root / "0000") + (self.directory / "completion.json").unlink() + failure = self.directory / "failure.json" + write(failure, {"exit_code": 1}) + launch = json.loads(self.launch.read_text()) + launch.update(output_root=str(retry_root), indices=[0]) + retry_launch = self.root / "retry-launch.json" + write(retry_launch, launch) + self.ledger["launches"]["retry"] = { + "path": str(retry_launch), + "sha256": digest(retry_launch), + "indices": [0], + } + self.ledger["rows"][0]["attempts"] = [ + {"launch": "original", "failure_sha256": digest(failure)}, + {"launch": "retry"}, + ] + return retry_root + + def test_resolved_original(self): + self.assertTrue(self.resolved()["all_inputs_verified"]) + + def test_recovery_retains_failure(self): + self.retry() + report = self.resolved() + self.assertTrue(report["all_inputs_verified"]) + self.assertEqual( + report["rows"][0]["attempts"][0]["status"], "preserved_failure" + ) + + def test_missing_fixed_row(self): + self.ledger["rows"] = [] + with self.assertRaisesRegex(ValueError, "every fixed row"): + self.resolved() + + def test_duplicate_fixed_row(self): + self.ledger["rows"].append(copy.deepcopy(self.ledger["rows"][0])) + with self.assertRaisesRegex(ValueError, "every fixed row"): + self.resolved() + + def test_changed_failure(self): + self.retry() + write(self.directory / "failure.json", {"exit_code": 2}) + self.assertEqual(self.resolved()["counts"]["invalid"], 1) + + def test_completed_original_cannot_be_replaced(self): + root = self.retry() + shutil.copyfile( + root / "0000/completion.json", self.directory / "completion.json" + ) + self.assertEqual(self.resolved()["counts"]["invalid"], 1) + + def test_unlisted_attempt(self): + root = self.retry() + (root / "0001").mkdir() + self.assertFalse(self.resolved()["all_inputs_verified"]) + + def test_corrupt_recovered_input(self): + root = self.retry() + with (root / "0000/input/input.npz").open("ab") as handle: + handle.write(b"corruption") + self.assertEqual(self.resolved()["counts"]["invalid"], 1) + + def test_no_fallback_to_earlier_attempt(self): + root = self.retry() + (root / "0000/completion.json").unlink() + result = self.resolved() + self.assertEqual(result["counts"]["incomplete"], 1) + self.assertEqual(len(result["rows"]), 1) diff --git a/reproduction/files/bb/bb4a136ec03099b66e8ce268f7ff4a5ad04ff560e826115cfa75a2aa8be384a1/test_lfmc_window.py b/reproduction/files/bb/bb4a136ec03099b66e8ce268f7ff4a5ad04ff560e826115cfa75a2aa8be384a1/test_lfmc_window.py new file mode 100644 index 0000000000000000000000000000000000000000..afcb90fa53aaa4a6f2990aa0f34510eadf57740b --- /dev/null +++ b/reproduction/files/bb/bb4a136ec03099b66e8ce268f7ff4a5ad04ff560e826115cfa75a2aa8be384a1/test_lfmc_window.py @@ -0,0 +1,77 @@ +"""Original-window reader preserves off-center labels and sparse time/band groups.""" + +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch +import numpy as np +import rasterio +from rasterio.transform import from_origin + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/downstream")) +from lfmc_window import read_window + + +class TestWindow(unittest.TestCase): + def test_sparse_groups_centering_and_heldout_guard(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + meta = { + "name": "fixture", + "bounds": [0, -63, 63, 0], + "projection": { + "crs": "EPSG:32611", + "x_resolution": 10, + "y_resolution": -10, + }, + "options": {"split": "train"}, + } + (root / "metadata.json").write_text(json.dumps(meta)) + + def write(relative, values): + p = root / relative + p.parent.mkdir(parents=True, exist_ok=True) + with rasterio.open( + p, + "w", + driver="GTiff", + height=63, + width=63, + count=len(values), + dtype=str(values.dtype), + crs="EPSG:32611", + transform=from_origin(0, 630, 10, 10), + ) as d: + d.write(values) + + target = np.full((1, 63, 63), -1, dtype=np.float32) + target[0, 30, 31] = 50 + write("layers/labels/value/geotiff.tif", target) + write( + "layers/sentinel2.3/B02_B03_B04_B08/geotiff.tif", + np.full((4, 63, 63), 2000, dtype=np.uint16), + ) + a = read_window(root, center_on_label=True) + self.assertEqual(a["bounds"], (15, -49, 47, -17)) + self.assertEqual(a["target"][16, 16], 50) + self.assertEqual(a["target_valid"].sum(), 1) + self.assertEqual(a["valid"]["sentinel2_l2a"].sum(), 1) + self.assertTrue(a["valid"]["sentinel2_l2a"][3, 0]) + self.assertFalse(a["valid"]["sentinel1"].any()) + self.assertEqual(a["pixels"]["sentinel2_l2a"].shape, (32, 32, 12, 12)) + empty = read_window(root, bounds=(0, -32, 32, 0)) + self.assertFalse(empty["target_valid"].any()) + meta["options"]["split"] = "test" + (root / "metadata.json").write_text(json.dumps(meta)) + with patch( + "lfmc_window.GeotiffRasterFormat.decode_raster", + side_effect=AssertionError("Test payload read"), + ): + with self.assertRaisesRegex(ValueError, "heldout"): + read_window(root, center_on_label=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/bc/bcd8f778e892786296ec7c39599aaeef7e737cd0fc2cafc3eeb5aa58c3843998/test_full_recomputation.py b/reproduction/files/bc/bcd8f778e892786296ec7c39599aaeef7e737cd0fc2cafc3eeb5aa58c3843998/test_full_recomputation.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8405b7c803c034de13162387efb010180876ce --- /dev/null +++ b/reproduction/files/bc/bcd8f778e892786296ec7c39599aaeef7e737cd0fc2cafc3eeb5aa58c3843998/test_full_recomputation.py @@ -0,0 +1,232 @@ +"""Compare official Large loss and every gradient on a real masked small batch.""" + +import argparse +import gc +import hashlib +import json +import os +from pathlib import Path +import sys +import tempfile + +import torch + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--upstream", type=Path, required=True) + p.add_argument("--data", type=Path, required=True) + p.add_argument("--output", type=Path, required=True) + p.add_argument("--diagnostic", action="store_true") + p.add_argument("--math-sdp", action="store_true") + p.add_argument("--fp32", action="store_true") + p.add_argument("--microbatches", type=int, default=1) + a = p.parse_args() + if a.microbatches < 1: + p.error("microbatches must be positive") + if ( + os.environ.get("EARTH_SLURM_PARTITION") + and os.environ.get("SLURM_JOB_PARTITION") != os.environ["EARTH_SLURM_PARTITION"] + ): + raise RuntimeError("CUDA regression requires configured-gpu-partition") + torch.set_num_threads(4) + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + torch.cuda.set_device(int(os.environ.get("LOCAL_RANK", "0"))) + if a.math_sdp: + torch.backends.cuda.enable_flash_sdp(False) + torch.backends.cuda.enable_mem_efficient_sdp(False) + torch.backends.cuda.enable_math_sdp(True) + with tempfile.TemporaryDirectory() as tmp: + if world_size > 1: + torch.distributed.init_process_group("nccl", init_method="env://") + else: + torch.distributed.init_process_group( + "nccl", init_method=f"file://{tmp}/init", rank=0, world_size=1 + ) + sys.path.insert(0, str(a.upstream / "scripts/official/v1")) + sys.path.insert( + 0, str(Path(__file__).resolve().parents[1] / "environment/baseline/starter") + ) + import large + import script + from recomputation import wrap_block + + common = script.build_common_components( + str(a.upstream / "scripts/official/v1/large.py"), + "dry_run", + "regression", + "local", + [], + ) + config = large.build_model_config(common) + dataset_config = script.build_dataset_config(common) + dataset_config.h5py_dir = str(a.data) + dataset = dataset_config.build() + loader_config = script.build_dataloader_config(common) + loader_config.work_dir = tmp + loader_config.global_batch_size = 2 * world_size + loader_config.num_workers = 0 + loader_config.prefetch_factor = None + loader_config.min_patch_size = loader_config.max_patch_size = 4 + loader_config.sampled_hw_p_list = [2] + loader_config.max_timesteps = 2 + loader_config.token_budget = 512 + loader = loader_config.build(dataset) + # Per-rank temporary directories are intentionally separate. Keep the + # deterministic global index array in memory instead of a shared cache. + loader.reshuffle(epoch=1, in_memory=True) + patch_size, view_a, view_b = next(iter(loader)) + views = [ + view_a.to_device(torch.device("cuda")), + view_b.to_device(torch.device("cuda")), + ] + module_config = script.build_train_module_config(common) + base_loss = module_config.loss_config.build() + contrastive_loss = module_config.contrastive_config.build() + reference_gradients = {} + losses = [] + comparisons = {} + initialization_hashes = [] + for mode, recompute in [ + ("native", False), + ("native_repeat", False), + ("recomputed", True), + ]: + torch.manual_seed(12536) + model = config.build() + initial_hash = hashlib.sha256() + for parameter in model.parameters(): + initial_hash.update(parameter.detach().numpy().tobytes()) + initialization_hashes.append(initial_hash.hexdigest()) + if recompute: + for part in [model.encoder, model.decoder]: + for i, block in enumerate(part.blocks): + part.blocks[i] = wrap_block(block) + model.cuda().train() + model.apply_fsdp( + param_dtype=torch.float32 if a.fp32 else torch.bfloat16, + reduce_dtype=torch.float32, + ) + torch.manual_seed(777 + rank) + total_loss = 0.0 + for micro in range(a.microbatches): + # Match the official train module FSDP microbatch context. + model.set_is_last_backward(micro == a.microbatches - 1) + per_view, pooled = [], [] + for original_view in views: + view = type(original_view)( + *[ + value.clone() if isinstance(value, torch.Tensor) else value + for value in original_view + ] + ) + output = model(view, patch_size=patch_size) + with torch.no_grad(): + target = model.target_encoder( + view.unmask(), + patch_size=patch_size, + token_exit_cfg=module_config.token_exit_cfg, + )["tokens_and_masks"] + per_view.append(base_loss.compute(output[1], target)) + pooled.append(output[2]) + loss = sum(per_view) / 2 + contrastive_loss.compute(*pooled) + loss = loss / a.microbatches + loss.backward() + total_loss += float(loss.detach().cpu()) + losses.append(total_loss) + print(mode, "loss", losses[-1], flush=True) + names = set() + differences = [] + diff_squared = reference_squared = 0.0 + gradient_max_abs = 0.0 + for name, param in model.named_parameters(): + name = name.replace("._checkpoint_wrapped_module", "") + names.add(name) + grad = ( + None + if param.grad is None + else param.grad.full_tensor().detach().cpu() + ) + if mode == "native": + reference_gradients[name] = grad + else: + reference = reference_gradients[name] + if (reference is None) != (grad is None): + raise AssertionError(f"Gradient participation differs: {name}") + if grad is not None: + diff = float((grad - reference).abs().max()) + gradient_max_abs = max(gradient_max_abs, diff) + delta = grad - reference + diff_squared += float(delta.double().square().sum()) + reference_squared += float(reference.double().square().sum()) + if not torch.equal(grad, reference): + differences.append( + { + "name": name, + "max_abs": diff, + "reference_max_abs": float(reference.abs().max()), + } + ) + assert names == set(reference_gradients) + if mode != "native": + comparisons[mode] = { + "gradient_max_abs": gradient_max_abs, + "gradient_relative_l2": ( + diff_squared / max(reference_squared, 1e-300) + ) + ** 0.5, + "nonidentical_parameters": len(differences), + "largest_differences": sorted( + differences, key=lambda v: v["max_abs"], reverse=True + )[:20], + } + del model, loss, output, target, per_view, pooled, param, grad + gc.collect() + torch.cuda.empty_cache() + exact = len(set(losses)) == 1 and all( + c["nonidentical_parameters"] == 0 for c in comparisons.values() + ) + assert len(set(initialization_hashes)) == 1, "Initializations differ" + report = { + "model": "official v1 Large, encoder and predictor", + "real_source": str(a.data), + "batch": 2 * world_size, + "rank_microbatch": 2, + "accumulation_microbatches": a.microbatches, + "same_real_microbatch_reused": True, + "patch_size": patch_size, + "sampled_hw_p": 2, + "max_timesteps": 2, + "fsdp_world_size": world_size, + "parameter_dtype": "float32" if a.fp32 else "bfloat16", + "math_sdp": a.math_sdp, + "initialization_hashes": initialization_hashes, + "losses": losses, + "comparisons": comparisons, + "all_parameter_gradients_identical": exact, + "limitation": "Small real masked batch; does not prove long-run learning quality.", + } + rank_reports = [None] * world_size + torch.distributed.all_gather_object( + rank_reports, + { + "rank": rank, + "losses": losses, + "comparisons": comparisons, + "all_parameter_gradients_identical": exact, + }, + ) + exact = all(row["all_parameter_gradients_identical"] for row in rank_reports) + report["all_parameter_gradients_identical"] = exact + report["rank_reports"] = rank_reports + if rank == 0: + a.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2), flush=True) + torch.distributed.destroy_process_group() + if not a.diagnostic and not exact: + raise AssertionError("Full model gradients differ; inspect written report") + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/bd/bd198510ac8becdb304e8e887f3ffdee4b9a6c0f469260c454a278ab709c408f/docker-compose.local.yaml b/reproduction/files/bd/bd198510ac8becdb304e8e887f3ffdee4b9a6c0f469260c454a278ab709c408f/docker-compose.local.yaml new file mode 100644 index 0000000000000000000000000000000000000000..484412fdd0b7471ed6fd49f36654517185d93b32 --- /dev/null +++ b/reproduction/files/bd/bd198510ac8becdb304e8e887f3ffdee4b9a6c0f469260c454a278ab709c408f/docker-compose.local.yaml @@ -0,0 +1,19 @@ +services: + main: + command: ["sleep", "infinity"] + cpus: 16 + mem_limit: "64g" + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: 1 + capabilities: [gpu] + volumes: + - type: bind + source: ${MASSSPECGYM_SUBMISSION_DIR:?Set MASSSPECGYM_SUBMISSION_DIR} + target: /workspace/submission + read_only: true + bind: + create_host_path: false diff --git a/reproduction/files/bd/bd31ec6ef75f65f779c43140aebbe1305f077343fa00f4e5393357431bd5aedf/test_splits.py b/reproduction/files/bd/bd31ec6ef75f65f779c43140aebbe1305f077343fa00f4e5393357431bd5aedf/test_splits.py new file mode 100644 index 0000000000000000000000000000000000000000..d64e3b759a1ec43b1f995a04960f86e43705d145 --- /dev/null +++ b/reproduction/files/bd/bd31ec6ef75f65f779c43140aebbe1305f077343fa00f4e5393357431bd5aedf/test_splits.py @@ -0,0 +1,88 @@ +"""Scientific split invariants, including cross-suite and historical leakage.""" + +import copy +from collections import Counter + +import pytest + +from splits import assign, composition_key, load_split, validate_assignment + + +def row(suite, material_id, formula, n_sites=2): + return { + "id": f"{suite}/{material_id}", + "suite": suite, + "material_id": material_id, + "composition": composition_key(formula), + "n_sites": n_sites, + } + + +def test_canonical_composition_handles_polymorphs_supercells_and_dimers(): + assert composition_key("Fe2O3") == composition_key("Fe4 O6") + assert composition_key("O") == composition_key("O2") + assert composition_key("LiFePO4") != composition_key("LiFePO3") + + +def test_group_assignment_is_order_independent_and_protects_shared_ids(): + rows = [ + row("phonons", "mp-1", "Fe2O3"), + row("elasticity", "mp-1", "FeO"), + row("discovery", "wbm-1", "Fe4O6"), + row("discovery", "wbm-2", "SiO2"), + ] + exposure = {"compositions": [composition_key("FeO")], "material_ids": []} + result, _ = assign(rows, exposure) + reversed_result, _ = assign(rows[::-1], exposure) + assert result == reversed_result + assert all(r["split"] == "val" for r in result if r["material_id"] != "wbm-2") + validate_assignment(result, exposure) + + +def test_overlap_and_prior_exposure_are_rejected(): + exposure = {"compositions": [composition_key("FeO")], "material_ids": []} + rows, _ = assign( + [row("phonons", "mp-1", "FeO"), row("elasticity", "mp-1", "FeO")], exposure + ) + corrupted = copy.deepcopy(rows) + corrupted[0]["split"] = "test" + with pytest.raises(ValueError, match="overlap"): + validate_assignment(corrupted, exposure) + for record in corrupted: + record["split"] = "test" + with pytest.raises(ValueError, match="exposed"): + validate_assignment(corrupted, exposure) + + +def test_frozen_release_covers_every_case_and_is_reproducible(): + import json + from splits import DEFAULT_SPLITS + + if not (DEFAULT_SPLITS / "manifest.json").exists(): + pytest.skip("Materialize --components protocol for frozen-release checks") + rows, manifest = load_split() + assert Counter(r["suite"] for r in rows) == { + "discovery": 256963, + "phonons": 9958, + "elasticity": 12122, + } + exposure = json.loads((DEFAULT_SPLITS / "exposure.json").read_text()) + inputs = [{k: v for k, v in r.items() if k not in ("group", "split")} for r in rows] + rebuilt, _ = assign( + inputs, exposure, manifest["target_validation_fraction"], manifest["seed"] + ) + assert rebuilt == rows + + +def test_manifest_tampering_is_rejected(tmp_path): + import shutil + from splits import DEFAULT_SPLITS + + if not (DEFAULT_SPLITS / "manifest.json").exists(): + pytest.skip("Materialize --components protocol for frozen-release checks") + directory = tmp_path / "split" + shutil.copytree(DEFAULT_SPLITS, directory) + with (directory / "assignments.jsonl.gz").open("ab") as stream: + stream.write(b"changed") + with pytest.raises(ValueError, match="checksum"): + load_split(directory) diff --git a/reproduction/files/be/be721464782e0604dbe30c5ee0f9d5229c4e0b87fc8a36ec5815608d0a30c16c/test_alphaqubit_report.py b/reproduction/files/be/be721464782e0604dbe30c5ee0f9d5229c4e0b87fc8a36ec5815608d0a30c16c/test_alphaqubit_report.py new file mode 100644 index 0000000000000000000000000000000000000000..99c5f53c84eadf2e18867b4f252aaf3b20c95c7a --- /dev/null +++ b/reproduction/files/be/be721464782e0604dbe30c5ee0f9d5229c4e0b87fc8a36ec5815608d0a30c16c/test_alphaqubit_report.py @@ -0,0 +1,113 @@ +"""Rendering checks for incomplete progress, resource scope, and safe values.""" +from __future__ import annotations + +import json +from pathlib import Path + +from baselines.alphaqubit_report import render_report, write_report + + +def save(root: Path, name: str, value: dict) -> None: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value)) + + +def test_partial_report_keeps_sunk_cost_and_diagnostics_separate_from_quality(tmp_path: Path) -> None: + save(tmp_path, "alphaqubit-v1/pilot/runtime.json", { + "group": "d5_X", "config": {"dtype": "bfloat16"}, "batch_size": 256, + "rounds": 25, "samples_per_second": 1500., "gradient_norm": 1., + "master_dtype": "float32", "first_update_compile_seconds": 76., + }) + save(tmp_path, "alphaqubit-v1/overfit.json", {"overfit_passed": True, + "latest_metrics": {"main_loss": 0.05, "main_error": 0.01}}) + html = render_report(tmp_path) + assert "145.90194 GPU-hours" in html + assert "Missing usage is not zero" in html + assert "finite update / throughput recorded" in html + assert "fixed-batch overfit passed" in html + assert html.count("held-out evaluation pending") == 2 + assert "full odd-test coverage recorded" not in html + assert "not official Google code" in html + + +def test_accounting_and_stage_validation_render_without_implying_convergence(tmp_path: Path) -> None: + save(tmp_path, "accounting.json", { + "updated_utc": "2026-09-20T03:00:00Z", "actual_allocated_gpu_hours": 150., + "remaining_actual_gpu_hours": 234., "records": [{"job_id": "old_lstm", "state": "CANCELLED", "gpu_hours": 145.90194}], + }) + save(tmp_path, "alphaqubit-v1/models/d5_X/pretrain/progress.json", { + "status": "stopped", "stop_reason": "budget", "global_steps": 1234, + "seen_samples": 315904, "updated_at": "2026-09-20T03:01:00Z", + "latest_validation": {"complete": True, "main_loss": .24, + "fit": {"accepted": False, "logical_error_per_round": -.02, + "rejection_reasons": ["unphysical_ler"]}}, + }) + html = render_report(tmp_path) + assert "150.00000" in html and "234.00000" in html + assert "not added a second time" in html + assert "CANCELLED" in html + assert "stopped; convergence not established" in html + assert "315,904" in html and "1,234" in html + assert "rejected validation fit" in html and "unphysical_ler" in html + assert html.count("held-out evaluation pending") == 2 + + +def test_final_scores_escape_markup_reject_nonfinite_display_and_write_atomically(tmp_path: Path) -> None: + attack = "" + save(tmp_path, "alphaqubit-v1/scores-finetune.json", { + "split": "test", "conditions": 130, "total_shots": 3250000, + "summary": {"macro": {"d3": {"logical_error_per_round": .03, "ci95": [.029, .031]}}, + "per_group": {attack: {"logical_error_per_round": float("nan"), "zero_round_fidelity": float("inf")}}}, + "calibration": {"macro": {"d3": {"negative_log_likelihood": .12, "brier_score": .04}}}, + "paired_comparisons": {"pymatching_correlated_selected": {"comparisons": {"d3": { + "logical_error_per_round_a_minus_b": -.003, "ci95": [-.004, -.002]}}}}, + }) + path = write_report(tmp_path) + html = path.read_text() + assert path == tmp_path / "alphaqubit-v1/report.html" + assert "full odd-test coverage recorded" in html + assert "3.000" in html and "[2.900, 3.100]" in html + assert "-0.300" in html and "[-0.400, -0.200]" in html + assert "0.12000" in html and "0.04000" in html + assert attack not in html and "<script>" in html + assert "invalid" in html and ">nan<" not in html and ">inf<" not in html + assert sorted(item.name for item in path.parent.iterdir()) == ["report.html", "scores-finetune.json"] + + +def test_expansion_gate_displays_allocation_evidence_without_promoting_test_claim(tmp_path: Path) -> None: + save(tmp_path, "alphaqubit-v1/expansion-gate.json", { + "passed": True, "decision": "expand", "evaluated_at": "2026-09-20T05:00:00Z", + "interpretation": "Representative learning evidence supports further allocation.", + "thresholds": {"minimum_seen_samples": 1000000}, + "groups": {"d5_X": {"passed": True, "status": "eligible", "rejection_reasons": [], + "measurements": {"seen_samples": 2000000, "complete_validations": 4, + "selected_LER": .035, "matching_LER": .03, "model_to_matching_LER_ratio": 7 / 6, + "first_main_BCE": .5, "candidate_main_BCE": .3, "bce_relative_improvement": .4, + "selected_errors": 500, "no_correction_errors": 1000, "total_shots": 10000, + "shot_error_relative_improvement": .5}}}, + }) + html = render_report(tmp_path) + assert "Expansion allowed by the recorded gate" in html + assert "2,000,000" in html and "1.167" in html + assert "40.00" in html and "50.00" in html + assert "Synthetic MWPM LER" in html and "not a scientific success/failure verdict" in html + assert html.count("held-out evaluation pending") == 2 + assert "full odd-test coverage recorded" not in html + + +def test_closed_expansion_gate_preserves_diagnosis_reasons_and_escapes_values(tmp_path: Path) -> None: + attack = "" + save(tmp_path, "alphaqubit-v1/expansion-gate.json", { + "passed": False, "decision": "no_expansion", "groups": { + "d3_X": {"status": "insufficient_evidence", "rejection_reasons": ["stage_not_finalized"]}, + "d5_X": {"status": "needs_diagnosis", "rejection_reasons": [attack], + "measurements": {"selected_LER": float("nan")}}, + }, + }) + html = render_report(tmp_path) + assert "No expansion: inspect missing evidence or diagnosis reasons" in html + assert "stage_not_finalized" in html and "needs_diagnosis" in html + assert attack not in html and "<img" in html + assert "invalid" in html + assert "Expansion allowed by the recorded gate" not in html diff --git a/reproduction/files/c2/c2b5ff3fcd00367b27bdd5b7a69d20e48cfa6e61df9da95221c1beb81fff7eda/common.py b/reproduction/files/c2/c2b5ff3fcd00367b27bdd5b7a69d20e48cfa6e61df9da95221c1beb81fff7eda/common.py new file mode 100644 index 0000000000000000000000000000000000000000..a0d507b358b049c5cb6e79b0a0aa5125c464467a --- /dev/null +++ b/reproduction/files/c2/c2b5ff3fcd00367b27bdd5b7a69d20e48cfa6e61df9da95221c1beb81fff7eda/common.py @@ -0,0 +1,147 @@ +"""Trusted validation helpers shared by replay and grading.""" + +import hashlib +import json +import math +import os +from pathlib import Path +import tempfile + + +QUERY_FIELDS = { + "query_id", "mzs", "intensities", "precursor_mz", "adduct", + "instrument_type", "collision_energy", "candidate_pool_id", +} + + +def compact_json(value): + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + + +def write_json(path: Path, value): + # The other verifier service polls for these files. Existence must mean + # complete JSON, including on shared volumes. + with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, + prefix=f".{path.name}.", delete=False) as stream: + temporary = Path(stream.name) + try: + stream.write(compact_json(value) + "\n") + stream.flush() + # A host-side runner may read bind-mounted verifier logs as a + # different UID. The containing directory controls write access. + os.fchmod(stream.fileno(), 0o644) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def contained(root: Path, relative: str) -> Path: + if not isinstance(relative, str) or not relative: + raise ValueError("path must be a nonempty string") + path = (root / relative).resolve() + if not path.is_relative_to(root.resolve()): + raise ValueError("path escapes its declared root") + if not path.is_file(): + raise FileNotFoundError(path) + return path + + +def jsonl(path: Path): + values = [] + with path.open(encoding="utf-8") as stream: + for line_number, line in enumerate(stream, 1): + if not line.strip(): + continue + try: + value = json.loads(line) + except json.JSONDecodeError as error: + raise ValueError(f"invalid JSON at {path}:{line_number}") from error + if not isinstance(value, dict): + raise ValueError(f"non-object JSONL row at {path}:{line_number}") + values.append(value) + return values + + +def candidate_id(smiles: str) -> str: + return hashlib.sha256(smiles.encode("utf-8")).hexdigest() + + +def numeric(value, *, positive=False, nullable=False): + if nullable and value is None: + return + if type(value) not in (int, float) or not math.isfinite(value): + raise ValueError("expected a finite JSON number") + if positive and value <= 0: + raise ValueError("expected a positive number") + + +def validate_input(root: Path): + root = root.resolve() + manifest_path = root / "manifest.json" + manifest = json.loads(manifest_path.read_text()) + if manifest.get("schema") != "massspecgym-retrieval-input/v1": + raise ValueError("invalid input manifest schema") + for name in ("queries.jsonl", "candidate_pools.jsonl"): + if manifest.get("files", {}).get(name) != sha256(root / name): + raise ValueError(f"input hash mismatch: {name}") + + pools = {} + for row in jsonl(root / "candidate_pools.jsonl"): + if set(row) != {"candidate_pool_id", "candidates"}: + raise ValueError("invalid candidate pool fields") + pool_id = row["candidate_pool_id"] + if not isinstance(pool_id, str) or not pool_id or pool_id in pools: + raise ValueError("missing or duplicate candidate pool ID") + candidates = row["candidates"] + if not isinstance(candidates, list) or not 1 <= len(candidates) <= 256: + raise ValueError("invalid candidate pool length") + by_id = {} + for candidate in candidates: + if set(candidate) != {"candidate_id", "smiles"}: + raise ValueError("invalid candidate fields") + identifier, smiles = candidate["candidate_id"], candidate["smiles"] + if not isinstance(smiles, str) or identifier != candidate_id(smiles): + raise ValueError("candidate ID/SMILES mismatch") + if identifier in by_id: + raise ValueError("duplicate candidate ID") + by_id[identifier] = smiles + pools[pool_id] = by_id + + queries = {} + for row in jsonl(root / "queries.jsonl"): + if set(row) != QUERY_FIELDS: + raise ValueError("invalid query fields") + query_id = row["query_id"] + if not isinstance(query_id, str) or not query_id or query_id in queries: + raise ValueError("missing or duplicate query ID") + if row["candidate_pool_id"] not in pools: + raise ValueError("query references unknown candidate pool") + mzs, intensities = row["mzs"], row["intensities"] + if not isinstance(mzs, list) or not mzs or len(mzs) != len(intensities): + raise ValueError("invalid peak arrays") + for mz in mzs: + numeric(mz, positive=True) + for intensity in intensities: + numeric(intensity) + if intensity < 0: + raise ValueError("negative intensity") + if max(intensities) <= 0 or mzs != sorted(mzs): + raise ValueError("invalid peak ordering or normalization") + numeric(row["precursor_mz"], positive=True) + numeric(row["collision_energy"], nullable=True) + if not isinstance(row["adduct"], str) or not isinstance(row["instrument_type"], str): + raise ValueError("invalid metadata strings") + queries[query_id] = row + + counts = manifest.get("counts", {}) + if counts.get("queries") != len(queries) or counts.get("candidate_pools") != len(pools): + raise ValueError("input manifest count mismatch") + return manifest, queries, pools diff --git a/reproduction/files/c3/c34ddf9d347824c36f40f38d8c690c81732cf18947ebc9b4efacf894818d4914/native_verifier.py b/reproduction/files/c3/c34ddf9d347824c36f40f38d8c690c81732cf18947ebc9b4efacf894818d4914/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..2c1919bb45e77b9d7b1c0ac0f20323ff5be85015 --- /dev/null +++ b/reproduction/files/c3/c34ddf9d347824c36f40f38d8c690c81732cf18947ebc9b4efacf894818d4914/native_verifier.py @@ -0,0 +1,373 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import re +import shutil +import signal +import socket +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def enter_offline_namespace(): + import offline_network + record = offline_network.configure(STATE) + libc = ctypes.CDLL(None, use_errno=True) + for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)): + fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC) + try: + if libc.setns(fd, flag): + raise OSError(ctypes.get_errno(), 'enter offline verifier namespace') + finally: + os.close(fd) + if socket.if_nameindex() != [(1, 'lo')]: + raise RuntimeError('Offline verifier namespace has external interfaces') + return record + + +def validate_ready_marker(sealed_root): + """Accept either upstream seal format, always checking the exact snapshot. + +Surface-code uses JSON with a run ID. Molecular, Genome and Protein-sequence +use a plain SHA-256 line. The original scientific grader rechecks the seal. +""" + root = Path(sealed_root) + raw = (root/'READY').read_text().strip() + snapshot = root/'run/snapshot.json' + observed = hashlib.sha256(snapshot.read_bytes()).hexdigest() + if re.fullmatch('[0-9a-f]{64}', raw): + if raw != observed: + raise RuntimeError('Native seal marker is inconsistent') + return + marker = json.loads(raw) + if (not isinstance(marker, dict) or marker.get('snapshot_sha256') != observed + or not isinstance(marker.get('run_id'), str) + or json.loads(snapshot.read_text()).get('run_id') != marker['run_id']): + raise RuntimeError('Native seal marker is inconsistent') + + +def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')): + """End the native waiting supervisor only after its authenticated seal.""" + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + seconds + sealed_ready = False + try: + while process.poll() is None: + if (sealed_root / 'READY').is_file(): + validate_ready_marker(sealed_root) + sealed_ready = True + break + if time.monotonic() >= deadline: + raise TimeoutError('Verifier inference budget exhausted') + time.sleep(.1) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode) + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + adapted = cfg.get('adapted_permissions', False) + if adapted: + import adapted_boundary + adapted_boundary.no_new_privileges() + os.setgroups([]) + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + crystal_cache_receipt = None + if cfg.get('isolated_crystal_dataset_cache'): + if plan['task'] != 'crystal-structure-generation' or phase != 'score': + raise RuntimeError('Crystal cache isolation is for trusted grading only') + import crystal_cache + crystal_cache_receipt = crystal_cache.prepare( + '/scorer-assets/huggingface/datasets', os.environ['HF_DATASETS_CACHE']) + crystal_cache_receipt['asset_manifest_sha256'] = hashlib.sha256( + Path('/scorer-assets/READY.json').read_bytes()).hexdigest() + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus'], strict_allocation=adapted) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + if adapted: + adapted_boundary.exact_gpu_allocation(gpu_policy) + else: + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + if cfg.get('gpu_runtime', 'torch') == 'torch' and not adapted: + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if cfg.get('local_benchmark_copy'): + status('copying_benchmark', task=plan['task'], role=phase) + # Folding's upstream evaluator runs inference and grading together. + # Give its non-root process a local readable copy, never relax Weka ACLs. + shutil.copytree('/source-benchmark', '/benchmark', symlinks=False) + for path in [Path('/benchmark'), *Path('/benchmark').rglob('*')]: + path.chmod(0o555 if path.is_dir() else 0o444) + if phase == 'inference': + if adapted:status('copying_submission', task=plan['task'], role=phase) + if cfg.get('native_uid_isolation'): + # The original PDE verifier explicitly supports this UID fallback. + # The mount is below a local root-only parent, never chmod shared data. + Path('/private').chmod(0o700) + Path('/tests').chmod(0o700) + elif plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + try: + agent = pwd.getpwuid(10001) + except KeyError: + subprocess.run(['/usr/sbin/useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + # Some native images precreate this empty container-local mountpoint. + # rmdir fails closed if it contains anything; never remove existing logs. + if Path('/logs/verifier').is_dir() and not Path('/logs/verifier').is_symlink(): + Path('/logs/verifier').rmdir() + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + if adapted and cfg.get('network_policy') != 'policy-children-only': + adapted_boundary.restrict_network() + elif not offline and not adapted: + runtime.deny_network() + if not adapted: + writable_roots = ['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc', + *cfg.get('writable_runtime_paths', [])] + if crystal_cache_receipt: + # The native image links /scorer-assets beneath /workspace. A + # writable ancestor defeats a read-only Landlock child rule. + # Trusted grading needs its output and scratch directories only. + writable_roots.remove('/workspace') + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets', + *cfg.get('readonly_runtime_paths', [])], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=writable_roots) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + if adapted: + source_audit = adapted_boundary.audit_source_permissions( + ['/operator', '/submission-source', '/source-benchmark', '/benchmark', '/data', '/labels', '/private'], + untrusted_uids=tuple(range(10001, 10009))) + else: + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if crystal_cache_receipt: + try: + fd = os.open('/scorer-assets/READY.json', os.O_WRONLY | os.O_CLOEXEC) + except PermissionError: + crystal_cache_receipt['asset_write_denied'] = True + else: + os.close(fd) + raise RuntimeError('Prepared scorer assets remain writable') + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' and not adapted else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())); ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + if cfg.get('gpu_runtime') == 'jax': + probe = ('import jax; import jax.numpy as jnp; ' + f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in d.device_kind for d in jax.devices("gpu")); ' + 'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 ' + 'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + if adapted and plan['task'] == 'fluid-flow-control': + # native_runtime.sh loads a module-provided libpython. Preserve + # only these runtime settings, never credentials, in the probe. + for key in ('PATH', 'LD_LIBRARY_PATH', 'OMP_NUM_THREADS', + 'OPENBLAS_NUM_THREADS', 'XLA_PYTHON_CLIENT_PREALLOCATE'): + if key in os.environ: + probe_env[key] = os.environ[key] + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + def dependency_identity(): + os.setgroups([]); os.setgid(10001); os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + cache=Path('/tmp/verifier-cache');cache.mkdir(exist_ok=True) + os.chown(cache,10001,10001) + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True, + preexec_fn=dependency_identity if cfg.get('untrusted_whole_verifier') else None) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': ('seccomp in unprivileged policy children; trusted simulator retains MPI sockets' + if cfg.get('network_policy') == 'policy-children-only' else + 'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children'), + 'offline_namespace': offline, + 'source_mounts': f'POSIX permission audit ({source_audit} entries); non-root submission' if adapted else 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan.get('label_isolated', plan['task'] != 'protein-folding-prediction'), + 'adapted_execution': adapted, + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + if cfg.get('stop_after_sealed_ready'): + # The native supervisor has already killed all model processes and + # sealed/hashes its predictions before writing READY. End only its + # wait-for-grader loop; the unchanged grader runs in a separate job. + result = run_until_sealed(cfg['command'], log, remaining) + else: + def run_identity(): + os.setgroups([]) + os.setgid(10001) + os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + os.chown(STATE / 'results', 10001, 10001) + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True, + preexec_fn=run_identity if cfg.get('untrusted_whole_verifier') else None) + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + if cfg.get('verify_crystal_assets_after'): + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted before post-score asset validation') + with (STATE / 'asset-validation-after.log').open('w') as log: + subprocess.run([cfg['driver_python'], '-c', + 'import sys;sys.path.insert(0,"/tests");from pathlib import Path;' + 'from grader import validate_assets;validate_assets(Path("/scorer-assets"));' + 'print("ORIGINAL_SCORER_ASSET_DIGEST_OK")'], + stdout=log, stderr=subprocess.STDOUT, timeout=remaining, check=True) + if hashlib.sha256(Path('/scorer-assets/READY.json').read_bytes()).hexdigest() != crystal_cache_receipt['asset_manifest_sha256']: + raise RuntimeError('Scorer asset manifest changed during grading') + crystal_cache_receipt['original_asset_digest_after'] = 'passed' + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + elapsed = time.monotonic() - entered + reward_path = STATE / 'results/reward.json' + if phase == 'score': + score_root = Path('/sealed/results') + if cfg.get('results_by_run_id'): + score_root /= json.loads(Path('/sealed/READY').read_text())['run_id'] + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = score_root / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/c3/c39fe81f53fc6920fe82d5dd15c7853667b53be20c793941edb9a03846beac4c/main_verifier.py b/reproduction/files/c3/c39fe81f53fc6920fe82d5dd15c7853667b53be20c793941edb9a03846beac4c/main_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..266825b287ae91511e7063c77b0a518878c86fc0 --- /dev/null +++ b/reproduction/files/c3/c39fe81f53fc6920fe82d5dd15c7853667b53be20c793941edb9a03846beac4c/main_verifier.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +"""Label-free inference supervisor; trusted scoring runs in the grader service.""" + +from __future__ import annotations + +import argparse +import ctypes +import json +import os +from pathlib import Path +import pwd +import resource +import shutil +import signal +import socket +import stat +import subprocess +import time +import uuid + +from common import sha256, write_json + + +def invalid(output: Path, status: str, error: Exception) -> None: + write_json(output / "report.json", { + "schema": "natural-disease-progression-report/v3", + "status": status, + "model_quality_measured": False, + "error": f"{type(error).__name__}: {error}", + }) + write_json(output / "reward.json", {"reward": 0.0}) + + +def kill_uid_processes(uid: int) -> None: + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + status = (entry / "status").read_text() + owner = int(next(row for row in status.splitlines() + if row.startswith("Uid:")).split()[1]) + if owner == uid: + os.kill(int(entry.name), signal.SIGKILL) + except (OSError, StopIteration): + pass + + +def validate_submission(root: Path) -> Path: + if root.is_symlink() or not root.is_dir(): + raise ValueError("Submission must be an ordinary directory") + total = 0 + for path in root.rglob("*"): + info = path.lstat() + if stat.S_ISLNK(info.st_mode) or not (stat.S_ISREG(info.st_mode) + or stat.S_ISDIR(info.st_mode)): + raise ValueError("Submission may contain only ordinary files and directories") + if stat.S_ISREG(info.st_mode): + # Hard links are accepted: the verifier reads its own copy of the package, so a second + # name for a file cannot change what is scored (atomic publishers often use `cp -al`). + total += info.st_size + if total > 50 * 1024**3: + raise ValueError("Submission exceeds 50 GiB") + inference = root / "infer.sh" + if not inference.is_file(): + raise FileNotFoundError("submission/infer.sh is required") + if not (root / "README.md").is_file(): + raise FileNotFoundError("submission/README.md is required for architecture review") + # Model/training/configuration/weight filenames are intentionally not guessed + # here. Shallow extension checks cannot establish that infer.sh actually uses + # a jointly trained neural model; reviewers inspect the frozen package path. + return inference + + +def run_submission(submission: Path, input_dir: Path, work: Path, + timeout: int) -> Path: + agent = pwd.getpwnam("agent") + frozen = work / "submission" + shutil.copytree(submission, frozen) + for path in frozen.rglob("*"): + os.chown(path, 0, 0) + path.chmod(0o555 if path.is_dir() or path.stat().st_mode & 0o111 else 0o444) + frozen.chmod(0o555) + output = work / "output" + output.mkdir() + os.chown(output, agent.pw_uid, agent.pw_gid) + environment = { + "PATH": "/opt/conda/bin:/usr/local/bin:/usr/bin:/bin", + "HOME": agent.pw_dir, + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONUNBUFFERED": "1", + "PIP_NO_INDEX": "1", + "HF_HUB_OFFLINE": "1", + "CUDA_VISIBLE_DEVICES": os.environ.get("CUDA_VISIBLE_DEVICES", "0"), + } + + def demote() -> None: + os.setgroups([]) + os.setgid(agent.pw_gid) + os.setuid(agent.pw_uid) + resource.setrlimit(resource.RLIMIT_FSIZE, (8 * 1024**3, 8 * 1024**3)) + libc = ctypes.CDLL(None, use_errno=True) + if libc.prctl(38, 1, 0, 0, 0) != 0: + raise OSError(ctypes.get_errno(), "PR_SET_NO_NEW_PRIVS failed") + + process = None + try: + with (work / "inference.log").open("wb") as stream: + process = subprocess.Popen( + ["bash", str(frozen / "infer.sh"), str(input_dir), str(output)], + cwd=frozen, env=environment, stdout=stream, + stderr=subprocess.STDOUT, preexec_fn=demote, + start_new_session=True) + code = process.wait(timeout=timeout) + if code: + raise subprocess.CalledProcessError(code, process.args) + finally: + if process: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + kill_uid_processes(agent.pw_uid) + return output + + +def seal_prediction(source_dir: Path, sealed: Path, input_dir: Path, + run_id: str) -> None: + source = source_dir / "predictions.parquet" + if not source.exists() and not source.is_symlink(): + raise ValueError("Missing predictions.parquet") + info = source.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size > 8 * 1024**3: + raise ValueError("predictions.parquet must be a regular file no larger than 8 GiB") + temporary = sealed.parent / f".snapshot-{run_id}" + temporary.mkdir(mode=0o700) + destination = temporary / "predictions.parquet" + with os.fdopen(os.open(source, os.O_RDONLY | os.O_NOFOLLOW), "rb") as reader: + with destination.open("xb") as writer: + shutil.copyfileobj(reader, writer) + destination.chmod(0o444) + write_json(temporary / "snapshot.json", { + "schema": "natural-disease-progression-prediction-snapshot/v1", + "run_id": run_id, + "input_manifest_sha256": sha256(input_dir / "manifest.json"), + "predictions_sha256": sha256(destination), + }) + (temporary / "snapshot.json").chmod(0o444) + temporary.chmod(0o555) + os.replace(temporary, sealed) + write_json(sealed.parent / "READY", { + "run_id": run_id, + "snapshot_sha256": sha256(sealed / "snapshot.json"), + }) + + +def evaluate(args: argparse.Namespace) -> None: + args.output.mkdir(parents=True, exist_ok=True) + args.sealed.parent.mkdir(parents=True, exist_ok=True) + args.sealed.parent.chmod(0o700) + for name in ("reward.json", "report.json"): + (args.output / name).unlink(missing_ok=True) + if any(name != "lo" for _, name in socket.if_nameindex()): + raise RuntimeError("Verifier inference requires a network_mode:none namespace") + if args.sealed.exists() or (args.sealed.parent / "READY").exists(): + raise RuntimeError("Stale sealed output; use a fresh verifier volume") + manifest_path = args.input / "manifest.json" + if not manifest_path.is_file() or not (args.input / "events.parquet").is_file(): + raise FileNotFoundError("Public test input is incomplete") + manifest = json.loads(manifest_path.read_text()) + if manifest.get("split") != "test": + raise ValueError("Verifier main accepts only the public test split") + try: + validate_submission(args.submission) + except (OSError, ValueError) as error: + invalid(args.output, "invalid_submission", error) + return + run_id = uuid.uuid4().hex + work = args.output / f"inference-{run_id}" + work.mkdir() + try: + untrusted = run_submission(args.submission, args.input, work, args.timeout) + except subprocess.TimeoutExpired as error: + invalid(args.output, "inference_timeout", error) + return + except subprocess.CalledProcessError as error: + invalid(args.output, "inference_failed", error) + return + try: + seal_prediction(untrusted, args.sealed, args.input, run_id) + except ValueError as error: + invalid(args.output, "invalid_prediction", error) + return + result_root = args.sealed.parent / "results" / run_id + deadline = time.monotonic() + args.grader_timeout + while not (result_root / "DONE").is_file(): + if time.monotonic() >= deadline: + raise TimeoutError("Trusted grader did not publish a result") + time.sleep(0.25) + report = json.loads((result_root / "report.json").read_text()) + if report.get("run_id") != run_id or report.get("status") == "infrastructure_error": + raise RuntimeError(f"Trusted grader infrastructure error: {report}") + for name in ("report.json", "reward.json"): + shutil.copyfile(result_root / name, args.output / name) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--input", type=Path, default=Path("/input")) + parser.add_argument("--submission", type=Path, default=Path("/workspace/submission")) + parser.add_argument("--sealed", type=Path, default=Path("/sealed/run")) + parser.add_argument("--output", type=Path, default=Path("/logs/verifier")) + parser.add_argument("--timeout", type=int, default=42000) + parser.add_argument("--grader-timeout", type=int, default=600) + args = parser.parse_args() + if os.geteuid() != 0: + parser.error("Inference supervisor must run as root before dropping to uid 10001") + try: + evaluate(args) + except Exception as error: + args.output.mkdir(parents=True, exist_ok=True) + (args.output / "reward.json").unlink(missing_ok=True) + write_json(args.output / "report.json", { + "schema": "natural-disease-progression-report/v3", + "status": "infrastructure_error", + "model_quality_measured": False, + "error": f"{type(error).__name__}: {error}", + }) + raise + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/c4/c4cf3b9d06125570467061555f17f50505a43d2bc41c6edab5f837b0bfb42049/replay_local.py b/reproduction/files/c4/c4cf3b9d06125570467061555f17f50505a43d2bc41c6edab5f837b0bfb42049/replay_local.py new file mode 100644 index 0000000000000000000000000000000000000000..e41632d81e87aaa49fa877ded4a2a5435200c8c0 --- /dev/null +++ b/reproduction/files/c4/c4cf3b9d06125570467061555f17f50505a43d2bc41c6edab5f837b0bfb42049/replay_local.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Operator-side input-only replay on a Linux host without a Docker daemon. + +Uses a fresh rootless user/PID/network/mount namespace. This validates package +isolation and portability, but does not certify the production Docker image or +the H100 runtime limit. Private labels, training files and host home are absent. +""" + +import argparse +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import time + +from common import validate_input, write_json +from main_verifier import seal_output, validate_submission + + +def replay(args): + validate_input(args.input) + manifest = validate_submission(args.submission) + args.output.mkdir(parents=True, exist_ok=False) + output = args.output / 'untrusted-output' + output.mkdir() + # Only the chosen venv and its actual CPython installation are visible. + # In particular, never bind /usr: a cluster may store private data below it. + python = args.runtime / 'bin/python' + base = Path(subprocess.check_output([str(python), '-c', 'import sys; print(sys.base_prefix)'], text=True).strip()).resolve() + command = ['bwrap', '--unshare-all', '--die-with-parent', '--new-session', + '--uid', '0', '--gid', '0', '--cap-drop', 'ALL', '--clearenv'] + for path in ['/usr/bin', '/usr/lib', '/usr/lib64', '/usr/share', '/bin', '/lib', '/lib64']: + if Path(path).exists(): + command += ['--ro-bind', path, path] + for path in ['/etc/ld.so.cache', '/etc/ld.so.conf', '/etc/ld.so.conf.d']: + if Path(path).exists(): + command += ['--ro-bind', path, path] + command += ['--ro-bind', str(base), str(base), + '--ro-bind', str(args.runtime), str(args.runtime), + '--ro-bind', str(args.submission), '/submission', + '--ro-bind', str(args.input), '/input', + '--bind', str(output), '/output', '--tmpfs', '/tmp', + '--dir', '/home/agent', '--proc', '/proc', '--dev', '/dev'] + if args.gpu: + if Path('/sys').exists(): + command += ['--ro-bind', '/sys', '/sys'] + for path in sorted(Path('/dev').glob('nvidia*')): + command += ['--dev-bind', str(path), str(path)] + for key, value in { + 'PATH': f'{args.runtime}/bin:/usr/bin:/bin', 'HOME': '/home/agent', + 'MASSSPECGYM_GLACIER_PYTHON': str(python), 'OMP_NUM_THREADS': str(args.cpus), + 'PYTHONUNBUFFERED': '1', 'PYTHONDONTWRITEBYTECODE': '1', + 'PIP_NO_INDEX': '1', 'HF_HUB_OFFLINE': '1', 'TRANSFORMERS_OFFLINE': '1', + 'CUDA_VISIBLE_DEVICES': os.environ.get('CUDA_VISIBLE_DEVICES', '0') if args.gpu else '', + }.items(): + command += ['--setenv', key, value] + command += ['--chdir', '/submission', '/bin/bash', '/submission/infer.sh', '/input', '/output'] + started = time.monotonic() + with (args.output / 'inference.log').open('wb') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + try: + code = process.wait(timeout=args.timeout) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + raise + if code: + raise subprocess.CalledProcessError(code, command) + seal_output(output, args.output / 'sealed/run', args.input / 'manifest.json') + report = {'isolation': 'rootless user/PID/network/mount namespaces; all capabilities dropped', + 'host_uid': os.getuid(), 'namespace_uid': 0, 'elapsed_seconds': time.monotonic() - started, + 'checkpoint_sha256': manifest['checkpoint']['sha256'], 'gpu_enabled': args.gpu, + 'production_docker_acceptance': False, 'h100_budget_acceptance': False} + write_json(args.output / 'replay.json', report) + return report + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + for name in ['submission', 'input', 'output', 'runtime']: + parser.add_argument('--' + name, type=lambda p: Path(p).resolve(), required=True) + parser.add_argument('--timeout', type=int, default=18000) + parser.add_argument('--cpus', type=int, default=4) + parser.add_argument('--gpu', action='store_true') + args = parser.parse_args() + if not shutil.which('bwrap') or args.timeout < 1 or args.cpus < 1: + parser.error('bwrap and positive limits are required') + print(json.dumps(replay(args), indent=2)) diff --git a/reproduction/files/c4/c4f8af4a34b581dca33c5b26d819cd89aef68281a5f144676551a2f23dc548f1/package_contract.py b/reproduction/files/c4/c4f8af4a34b581dca33c5b26d819cd89aef68281a5f144676551a2f23dc548f1/package_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..1df153ea8a3ee0ed291307348b1532e70ff22591 --- /dev/null +++ b/reproduction/files/c4/c4f8af4a34b581dca33c5b26d819cd89aef68281a5f144676551a2f23dc548f1/package_contract.py @@ -0,0 +1,53 @@ +"""Structural submission checks; dataset/runtime failures remain infrastructure errors.""" +import json +from pathlib import Path +import zipfile + +import h5py +import numpy as np + + +class InvalidSubmission(ValueError): + pass + + +def validate_package(model): + model = Path(model) + for name in ('encoder.pt', 'config.json', 'infer.py', 'provenance.json', 'LICENSE-OlmoEarth'): + path = model / name + if path.is_symlink() or not path.is_file() or path.stat().st_size == 0: + raise InvalidSubmission(f'Missing nonempty regular package file: {name}') + for name in ('config.json', 'provenance.json'): + try: + value = json.loads((model / name).read_text()) + except (ValueError, UnicodeError) as error: + raise InvalidSubmission(f'Invalid {name}') from error + if not isinstance(value, dict): + raise InvalidSubmission(f'{name} must contain an object') + if name == 'provenance.json': + if value.get('training_validity') == 'invalid': + raise InvalidSubmission('Known invalid training implementation') + if value.get('origin') == 'official_public_pretrained_reference': + raise InvalidSubmission('Public pretrained reference is ineligible') + + +def validate_features(path, inputs): + # Read trusted input outside the candidate-error handler. + with h5py.File(inputs, 'r') as source: + expected = source['ids'].asstr()[:].tolist() + path = Path(path) + if path.is_symlink() or not path.is_file(): + raise InvalidSubmission('Missing regular prediction file') + try: + with np.load(path, allow_pickle=False) as data: + ids, features = data['ids'], data['features'] + if (ids.ndim != 1 or ids.dtype.kind not in 'US' + or len(ids) != len(expected) or len(set(ids.tolist())) != len(ids) + or set(ids.tolist()) != set(expected)): + raise InvalidSubmission('IDs missing, duplicate or extra') + if (features.ndim != 2 or features.shape[0] != len(expected) + or features.shape[1] == 0 or features.dtype != np.float32 + or not np.isfinite(features).all()): + raise InvalidSubmission('Expected finite float32 features [N,D]') + except (ValueError, TypeError, KeyError, EOFError, zipfile.BadZipFile) as error: + raise InvalidSubmission(str(error)) from error diff --git a/reproduction/files/c7/c788150358fc319eb0f7f9711be9bccc5cf9b0eed35b43ab8cb5c113e674a08b/main_verifier.py b/reproduction/files/c7/c788150358fc319eb0f7f9711be9bccc5cf9b0eed35b43ab8cb5c113e674a08b/main_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..51cdc90dac6f4c3aa83893b96f44e57640a6a770 --- /dev/null +++ b/reproduction/files/c7/c788150358fc319eb0f7f9711be9bccc5cf9b0eed35b43ab8cb5c113e674a08b/main_verifier.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +"""Trusted label-free inference supervisor; labels exist only in grader service.""" +from __future__ import annotations +import argparse +import ctypes +import json +import os +from pathlib import Path +import pwd +import resource +import shutil +import signal +import socket +import stat +import subprocess +import sys +import time +import uuid +from typing import Any + +PROJECT = Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" if (Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit").is_dir() else Path(__file__).resolve().parents[1] # the baseline project: environment/baseline/alphaqubit here, /opt/task in the verifier image +sys.path.insert(0, str(PROJECT)) +from qecbench.data import contained, load_manifest, sha256, write_json + + +def validate_submission(root: Path) -> dict[str, Any]: + if root.is_symlink() or not root.is_dir(): + raise ValueError("Submission must be a directory") + size = 0 + for path in root.rglob("*"): + if path.is_symlink() or not (path.is_file() or path.is_dir()): + raise ValueError("Submission must contain ordinary files/directories only") + if path.is_file(): + # Hard links are accepted: the verifier scores an immutable relocated copy of the package. + size += path.stat().st_size + if size > 50 * 1024 ** 3: + raise ValueError("Submission exceeds 50 GiB") + for name in ("infer.sh", "README.md", "model_manifest.json", "requirements.lock"): + contained(root, name) + manifest = json.loads((root / "model_manifest.json").read_text()) + if not isinstance(manifest, dict) or manifest.get("schema") != "surface-code-decoding-model/v1": + raise ValueError("Unsupported submission manifest") + records = manifest.get("checkpoints") + if not isinstance(records, list) or not records or len(records) > 1000: + raise ValueError("Submit a trained model/checkpoint or serialized decoder state") + paths = set() + for record in records: + path = contained(root, record["path"]) + if record["path"] in paths or path.stat().st_size == 0 or sha256(path) != record["sha256"]: + raise ValueError("Duplicate/empty/corrupt checkpoint") + paths.add(record["path"]) + for field in ("model_config", "training_provenance"): + if not isinstance(json.loads(contained(root, manifest[field]).read_text()), dict): + raise ValueError(f"{field} must be a JSON object") + return manifest + + +def kill_uid_processes(uid: int) -> None: + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + status = (entry / "status").read_text() + owner = int(next(row for row in status.splitlines() if row.startswith("Uid:")).split()[1]) + if owner == uid: + os.kill(int(entry.name), signal.SIGKILL) + except (OSError, StopIteration): + pass + + +def run_submission(submission: Path, inputs: Path, work: Path, timeout: int) -> Path: + identity = pwd.getpwnam("agent") + frozen = work / "submission" + shutil.copytree(submission, frozen) + for path in frozen.rglob("*"): + os.chown(path, 0, 0) + path.chmod(0o555 if path.is_dir() or (path.stat().st_mode & 0o111) else 0o444) + frozen.chmod(0o555) + output = work / "output" + output.mkdir() + os.chown(output, identity.pw_uid, identity.pw_gid) + environment = {"PATH": "/opt/qec/.venv/bin:/usr/local/bin:/usr/bin:/bin", "HOME": "/tmp/agent-home", + "PYTHONUNBUFFERED": "1", "PYTHONDONTWRITEBYTECODE": "1", "HF_HUB_OFFLINE": "1", + "PIP_NO_INDEX": "1", "XLA_PYTHON_CLIENT_PREALLOCATE": "false", + "CUDA_VISIBLE_DEVICES": os.environ.get("CUDA_VISIBLE_DEVICES", "0")} + + def demote() -> None: + os.setgroups([]) + os.setgid(identity.pw_gid) + os.setuid(identity.pw_uid) + resource.setrlimit(resource.RLIMIT_FSIZE, (1024 ** 3, 1024 ** 3)) + libc = ctypes.CDLL(None, use_errno=True) + if libc.prctl(38, 1, 0, 0, 0) != 0: + raise OSError(ctypes.get_errno(), "PR_SET_NO_NEW_PRIVS failed") + + process = None + try: + with (work / "inference.log").open("wb") as log: + process = subprocess.Popen(["bash", str(frozen / "infer.sh"), str(inputs), str(output)], cwd=frozen, + env=environment, stdout=log, stderr=subprocess.STDOUT, start_new_session=True, preexec_fn=demote) + code = process.wait(timeout=timeout) + if code: + raise subprocess.CalledProcessError(code, process.args) + finally: + if process: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + kill_uid_processes(identity.pw_uid) + return output + + +def seal_output(output: Path, sealed: Path, inputs: Path, manifest: dict[str, Any], run_id: str) -> None: + temporary = sealed.parent / f".snapshot-{run_id}" + temporary.mkdir(mode=0o700) + files = {} + for row in manifest["conditions"]: + name = f"{row['name']}.npz" + path = output / name + # Missing output is sealed as missing and classified by the grader. + if not path.exists() and not path.is_symlink(): + continue + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size > row["shots"] * 12 + 65536: + raise ValueError(f"Invalid prediction file: {name}") + destination = temporary / name + with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW), "rb") as source: + with destination.open("xb") as target: + shutil.copyfileobj(source, target) + destination.chmod(0o444) + files[name] = sha256(destination) + write_json(temporary / "snapshot.json", {"schema": "surface-code-decoding-snapshot/v1", "run_id": run_id, + "input_manifest_sha256": sha256(inputs / "manifest.json"), "files": files}) + (temporary / "snapshot.json").chmod(0o444) + temporary.chmod(0o555) + os.replace(temporary, sealed) + write_json(sealed.parent / "READY", {"run_id": run_id, "snapshot_sha256": sha256(sealed / "snapshot.json")}) + + +def invalid(output: Path, status: str, error: Exception) -> None: + write_json(output / "report.json", {"schema": "surface-code-decoding-report/v1", "status": status, + "model_quality_measured": False, "score": 0.0, "score_unclipped": None, "performance": None, + "error": f"{type(error).__name__}: {error}"}) + write_json(output / "reward.json", {"reward": 0.0}) + + +def evaluate(args: argparse.Namespace) -> None: + for path, mode in ((args.output, 0o755), (args.sealed.parent, 0o700)): + path.mkdir(parents=True, exist_ok=True) + os.chown(path, 0, 0) + path.chmod(mode) + for name in ("reward.json", "reward.txt", "report.json"): + (args.output / name).unlink(missing_ok=True) + # Operator-approved adapted execution: test enforced socket denial, not interface names. + from adapted_boundary import network_probe + network_probe() + if args.sealed.exists(): + raise RuntimeError("Stale sealed output; create a fresh verifier volume") + manifest = load_manifest(args.input) + try: + validate_submission(args.submission) + except (OSError, ValueError, KeyError, TypeError) as error: + invalid(args.output, "invalid_submission", error) + return + work = args.output / "inference" + work.mkdir() + try: + output = run_submission(args.submission, args.input, work, args.timeout) + except subprocess.TimeoutExpired as error: + invalid(args.output, "inference_timeout", error) + return + except subprocess.CalledProcessError as error: + invalid(args.output, "inference_failed", error) + return + run_id = uuid.uuid4().hex + try: + seal_output(output, args.sealed, args.input, manifest, run_id) + except ValueError as error: + invalid(args.output, "invalid_prediction", error) + return + deadline = time.monotonic() + 300 + result_root = args.sealed.parent / "results" / run_id + while not (result_root / "DONE").exists(): + if time.monotonic() > deadline: + raise TimeoutError("Trusted grader did not publish a result") + time.sleep(0.25) + result = json.loads((result_root / "report.json").read_text()) + if result.get("run_id") != run_id or result.get("status") == "infrastructure_error": + raise RuntimeError(f"Trusted grader infrastructure error: {result}") + for name in ("report.json", "reward.json"): + shutil.copyfile(result_root / name, args.output / name) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--submission", type=Path, default=Path("/workspace/submission")) + parser.add_argument("--input", type=Path, default=Path("/benchmark")) + parser.add_argument("--sealed", type=Path, default=Path("/sealed/run")) + parser.add_argument("--output", type=Path, default=Path("/logs/verifier")) + parser.add_argument("--timeout", type=int, default=3600) + args = parser.parse_args() + if os.geteuid() != 0: + parser.error("Trusted supervisor requires root to isolate inference UID 10001") + if not 1 <= args.timeout <= 3600: + parser.error("timeout must be in 1..3600") + try: + evaluate(args) + except Exception as error: + args.output.mkdir(parents=True, exist_ok=True) + for name in ("reward.json", "reward.txt"): + (args.output / name).unlink(missing_ok=True) + write_json(args.output / "report.json", {"schema": "surface-code-decoding-report/v1", + "status": "infrastructure_error", "model_quality_measured": False, + "error": f"{type(error).__name__}: {error}"}) + raise + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/ca/ca06e43ca7662f4f3c023c0e68bfdcdde52a6759790e512fbb0f87c691f84b68/test_release_and_score.py b/reproduction/files/ca/ca06e43ca7662f4f3c023c0e68bfdcdde52a6759790e512fbb0f87c691f84b68/test_release_and_score.py new file mode 100644 index 0000000000000000000000000000000000000000..3ccc9f8208da68f0ae94cd345bd1e51068944b35 --- /dev/null +++ b/reproduction/files/ca/ca06e43ca7662f4f3c023c0e68bfdcdde52a6759790e512fbb0f87c691f84b68/test_release_and_score.py @@ -0,0 +1,153 @@ +"""Pinned prepared releases and normalization must preserve evaluation semantics.""" +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path +import shutil +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "environment/data")) +sys.path.insert(0, str(ROOT / "environment/evaluation")) +import benchmark_score +import materialize_hf +import release_manifest + + +class ScoreTests(unittest.TestCase): + def test_reference_anchors_and_saturation_preserve_raw_performance(self): + lower, upper = benchmark_score.BOUNDS["lower"], benchmark_score.BOUNDS["upper"] + for raw, expected in [(lower, 0), ((lower + upper) / 2, 0.5), (upper, 1), (0, 0), (1, 1)]: + with self.subTest(raw=raw): + value = benchmark_score.normalize(raw) + self.assertAlmostEqual(value["score"], expected) + self.assertEqual(value["raw_performance"], raw) + above = benchmark_score.normalize(0.7) + self.assertGreater(above["unclipped_score"], 1) + self.assertEqual(above["saturation"], "upper") + self.assertEqual(benchmark_score.normalize(0)["saturation"], "lower") + self.assertIsNone(benchmark_score.normalize(upper)["saturation"]) + + def test_invalid_performance_is_not_a_valid_reward(self): + for value in (float("nan"), float("inf"), -0.1, 1.1, True): + with self.subTest(value=value), self.assertRaises(ValueError): + benchmark_score.normalize(value) + + def test_anchor_evidence_matches_frozen_results(self): + formal = json.loads((ROOT / "docs" / "baseline_score.json").read_text()) + self.assertEqual(formal["metrics"]["hit_rate_at_1"], benchmark_score.BOUNDS["upper"]) + self.assertEqual(formal["reward"], 1) + evidence = json.loads((ROOT / "docs" / "release_validation.json").read_text()) + self.assertIn(str(benchmark_score.BOUNDS["lower"]), json.dumps(evidence)) + + +class ReleaseTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.source = self.root / "source" + self.source.mkdir() + labels = self.source / "labels.jsonl" + labels.write_text('{"query_id":"q","correct_candidate_id":"a","true_smiles":"C"}\n') + (self.source / "manifest.json").write_text(json.dumps({ + "files": {"labels.jsonl": release_manifest.sha256(labels)}, "queries": 17556, + })) + self.manifest = release_manifest.build(self.source, "private") + manifest_path = self.source / "release-manifest.json" + manifest_path.write_text(json.dumps(self.manifest)) + self.pin = {"repo_id": "Corning/fixture", "revision": "a" * 40, + "manifest_sha256": release_manifest.sha256(manifest_path)} + self.calls = [] + + def download(self, *, filename: str, cache_dir: Path, **kwargs: str) -> str: + self.calls.append(filename) + output = cache_dir / filename + output.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(self.source / filename, output) + return str(output) + + def test_fresh_download_and_verified_offline_reuse(self): + destination = self.root / "downloaded" + result = materialize_hf.fetch_release(self.pin, destination, "private", self.download) + self.assertTrue(result["verified"]) + self.assertEqual(len(self.calls), 3) + self.assertEqual((destination / "labels.jsonl").stat().st_mode & 0o077, 0) + with mock.patch.object(materialize_hf, "verify", wraps=release_manifest.verify) as verify: + materialize_hf.fetch_release(self.pin, destination, "private", lambda **kwargs: self.fail("download on reuse")) + verify.assert_called_once() + (destination / "labels.jsonl").write_text("tampered") + with self.assertRaisesRegex(ValueError, "corrupt"): + materialize_hf.fetch_release(self.pin, destination, "private", self.download) + + def test_hf_metadata_stays_outside_clean_payload_and_is_not_deleted(self): + destination = self.root / "downloaded" + def with_cache_metadata(**kwargs): + cache = kwargs["cache_dir"] + metadata = cache / ".cache/huggingface/download/held-open.metadata" + metadata.parent.mkdir(parents=True, exist_ok=True) + metadata.write_text("simulated NFS-held HF metadata") + return self.download(**kwargs) + result = materialize_hf.fetch_release(self.pin, destination, "private", with_cache_metadata) + self.assertTrue(result["verified"]) + self.assertFalse((destination / ".cache").exists()) + external = self.root / ".massspecgym-hf-cache" + self.assertTrue((external / ".cache/huggingface/download/held-open.metadata").is_file()) + self.assertEqual(external.stat().st_mode & 0o077, 0) + self.assertEqual({p.name for p in destination.iterdir()}, {"manifest.json", "labels.jsonl", "release-manifest.json"}) + self.assertEqual((destination / "labels.jsonl").stat().st_ino, (external / "labels.jsonl").stat().st_ino) + + def test_undeclared_files_cannot_enter_a_reused_release(self): + destination = self.root / "downloaded" + materialize_hf.fetch_release(self.pin, destination, "private", self.download) + (destination / "accidental-secret.txt").write_text("fixture") + with self.assertRaisesRegex(ValueError, "undeclared"): + materialize_hf.fetch_release(self.pin, destination, "private", self.download) + + def test_corrupt_payload_never_publishes_destination(self): + (self.source / "labels.jsonl").write_text("corrupt") + destination = self.root / "invalid" + with self.assertRaisesRegex(ValueError, "corrupt"): + materialize_hf.fetch_release(self.pin, destination, "private", self.download) + self.assertFalse(destination.exists()) + self.assertFalse(list(self.root.glob(".massspecgym-private-*"))) + + def test_pin_manifest_path_and_existing_destination_fail_closed(self): + destination = self.root / "existing" + destination.mkdir() + with self.assertRaises(FileExistsError): + materialize_hf.fetch_release(self.pin, destination, "private", self.download) + for pin in [{**self.pin, "revision": "main"}, {**self.pin, "manifest_sha256": "bad"}]: + with self.assertRaises(ValueError): + materialize_hf.fetch_release(pin, self.root / "new", "private", self.download) + for unsafe in ("../outside", "/tmp/outside", "nested/../../outside", "x\\y", "x//y"): + with self.assertRaises(ValueError): + release_manifest.safe_path(self.root, unsafe) + link = self.root / "link" + link.symlink_to(self.source, target_is_directory=True) + with self.assertRaises(ValueError): + materialize_hf.fetch_release(self.pin, link, "private", self.download) + with self.assertRaisesRegex(ValueError, "complete, exact"): + release_manifest.validate_manifest({**self.manifest, "files": {"../labels.jsonl": {}}}, "private") + + def test_wrong_manifest_is_rejected_before_payload_download(self): + pin = {**self.pin, "manifest_sha256": "b" * 64} + with self.assertRaisesRegex(ValueError, "pinned manifest"): + materialize_hf.fetch_release(pin, self.root / "wrong", "private", self.download) + self.assertEqual(self.calls, ["release-manifest.json"]) + + def test_source_rebuild_selects_both_exact_upstream_files(self): + source = (ROOT / "environment/data/materialize.sh").read_text() + self.assertIn('MASSSPECGYM_MATERIALIZE_MODE:-prepared', source) + self.assertIn('data/MassSpecGym1.5.tsv', source) + self.assertIn('data/molecules/MassSpecGym1.5_retrieval_candidates_mass.json', source) + self.assertNotIn('--include', source) + self.assertLess(source.index('"$massspec_script_dir/materialize.py"'), source.index('/starter/glacier/prepare.py')) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/ca/ca555a4fe1d66717da0169917d2b303277e4759ff1b911ff83756f04ebc48220/docker-compose.yaml b/reproduction/files/ca/ca555a4fe1d66717da0169917d2b303277e4759ff1b911ff83756f04ebc48220/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2f857a63313555627af4193dcbdde05f7d20813b --- /dev/null +++ b/reproduction/files/ca/ca555a4fe1d66717da0169917d2b303277e4759ff1b911ff83756f04ebc48220/docker-compose.yaml @@ -0,0 +1,56 @@ +# Isolated replay: `main` runs the submission's infer.sh on the public test inputs and seals the +# predictions into a shared volume; `grader` scores them against the private responses. The +# private directory is never mounted into `main`, and no container has network access. +# TASK_DATA_DIR = the release's dev/ tree, TASK_PRIVATE_DIR = its private/ tree (TASK_STANDARD.md). +volumes: + sealed: + verifier_logs: + +services: + main: + build: . + network_mode: none + shm_size: "16gb" + volumes: + - type: bind + source: "${TASK_DATA_DIR:?Set TASK_DATA_DIR to the release's dev/ tree}/test" + target: /benchmark + read_only: true + bind: + create_host_path: false + - type: bind + source: "${TASK_DATA_DIR:?Set TASK_DATA_DIR to the release's dev/ tree}/se600m" + target: /opt/se600m + read_only: true + bind: + create_host_path: false + - sealed:/sealed + - verifier_logs:/logs/verifier + environment: + SE600M_DIR: /opt/se600m + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: 1 + capabilities: [gpu] + + grader: + build: . + network_mode: none + command: ["python", "/tests/grader.py", "--sealed", "/sealed/run", "--benchmark", "/benchmark", "--private", "/private", "--output", "/sealed/results"] + volumes: + - type: bind + source: "${TASK_DATA_DIR:?Set TASK_DATA_DIR to the release's dev/ tree}/test" + target: /benchmark + read_only: true + bind: + create_host_path: false + - type: bind + source: "${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the release's private/ tree}" + target: /private + read_only: true + bind: + create_host_path: false + - sealed:/sealed diff --git a/reproduction/files/cc/cc925339150dee9491e9d8073e3eddf049e6fcfc0ffd6363401855497fdd5594/common.py b/reproduction/files/cc/cc925339150dee9491e9d8073e3eddf049e6fcfc0ffd6363401855497fdd5594/common.py new file mode 100644 index 0000000000000000000000000000000000000000..81ae8cd644459d38290091cc69db272cdf7a4f0c --- /dev/null +++ b/reproduction/files/cc/cc925339150dee9491e9d8073e3eddf049e6fcfc0ffd6363401855497fdd5594/common.py @@ -0,0 +1,74 @@ +"""Shared verifier helpers for protein-sequence-modeling.""" +import hashlib +import json +from pathlib import Path + +from metrics import TASKS + +SCHEMA = "peer-protein-input/v1" +PRIVATE_SCHEMA = "peer-protein-private-labels/v1" +SNAPSHOT_SCHEMA = "peer-protein-prediction-snapshot/v1" +PUBLIC_FIELDS = {"example_id", "task", "features"} + + +def sha256(path): + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest() + + +def write_json(path, value): + path.write_text(json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n") + + +def contained(root, name): + resolved = (root.resolve() / name).resolve() + if (Path(name).is_absolute() or not resolved.is_relative_to(root.resolve()) + or not resolved.is_file() or resolved.is_symlink()): + raise ValueError("unsafe path") + return resolved + + +def jsonl(path, max_bytes=512 * 1024 * 1024, max_line=2 * 1024 * 1024): + if not path.is_file() or path.is_symlink() or path.stat().st_size > max_bytes: + raise ValueError(f"unsafe JSONL: {path.name}") + with path.open() as handle: + for number, line in enumerate(handle, 1): + if len(line.encode()) > max_line: + raise ValueError(f"oversized line: {path.name}:{number}") + try: + yield json.loads(line) + except json.JSONDecodeError as error: + raise ValueError(f"invalid JSON: {path.name}:{number}") from error + + +def validate_input(root): + manifest = json.loads((root / "manifest.json").read_text()) + names = {f"{task}.jsonl" for task in TASKS} + if (set(manifest) != {"schema", "view", "files", "counts"} or manifest["schema"] != SCHEMA + or manifest["view"] != "verifier" or set(manifest["files"]) != names + or set(manifest["counts"]) != set(TASKS)): + raise ValueError("invalid input manifest") + all_ids = set() + expected = {} + for task in TASKS: + path = contained(root, f"{task}.jsonl") + if sha256(path) != manifest["files"][path.name]: + raise ValueError("input hash mismatch") + ids = set() + count = 0 + for row in jsonl(path, 2 * 1024 ** 3): + count += 1 + if (set(row) != PUBLIC_FIELDS or row.get("task") != task + or not isinstance(row.get("example_id"), str) + or not isinstance(row.get("features"), dict) + or row["example_id"] in all_ids): + raise ValueError(f"invalid row: {task}") + ids.add(row["example_id"]) + all_ids.add(row["example_id"]) + if count != manifest["counts"][task]: + raise ValueError("input count mismatch") + expected[task] = ids + return manifest, expected diff --git a/reproduction/files/cd/cd2c23d32009d3af1773228a8af12cfa36c469a6d8c7228e52c60db8c307cf14/test_reference_policy.py b/reproduction/files/cd/cd2c23d32009d3af1773228a8af12cfa36c469a6d8c7228e52c60db8c307cf14/test_reference_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..4d26432379ab1abbcdf96f106f60da254c2547b3 --- /dev/null +++ b/reproduction/files/cd/cd2c23d32009d3af1773228a8af12cfa36c469a6d8c7228e52c60db8c307cf14/test_reference_policy.py @@ -0,0 +1,57 @@ +"""Contract regression tests for standalone exported reference actors.""" + +import hashlib +import importlib.util +import json +from pathlib import Path +import shutil +import sys +import tempfile +import unittest + +TASK = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(TASK / "environment/evaluation")) + + +@unittest.skipUnless(importlib.util.find_spec("torch"), "Requires declared PyTorch runtime") +class ReferencePolicyTests(unittest.TestCase): + def test_relocated_observation_conditioned_reference(self): + import torch + from protocol import Policy, PolicyError + + torch.set_num_threads(1) + torch.manual_seed(900) + model = torch.nn.Sequential(torch.nn.Linear(5, 3), torch.nn.Tanh()).eval() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + package = root / "original" + package.mkdir() + torch.jit.trace(model, torch.zeros(1, 5)).save(str(package / "model.pt")) + cfg = {"observation_size": 5, "action_size": 3, + "model_sha256": hashlib.sha256((package / "model.pt").read_bytes()).hexdigest()} + (package / "config.json").write_text(json.dumps(cfg)) + shutil.copyfile(TASK / "environment/baseline/starter/reference_predict.py", package / "predict.py") + (package / "infer.sh").write_text('#!/bin/sh\nexec python "$(dirname "$0")/predict.py"\n') + relocated = root / "relocated" + shutil.move(package, relocated) + policy = Policy(relocated, root / "stderr", timeout=20) + try: + for name in ("arbitrary-new-name", "different-order-and-name"): + policy.reset({"environment": name}, [5], [3], [-1.] * 3, [1.] * 3) + for obs in ([0.] * 5, [1., -.3, .5, -.1, 2.]): + actual = policy.act(obs) + expected = model(torch.tensor(obs).unsqueeze(0))[0].detach() + torch.testing.assert_close(torch.tensor(actual), expected) + policy.close() + finally: + policy.abort() + wrong = Policy(relocated, root / "wrong-stderr", timeout=20) + try: + with self.assertRaises(PolicyError): + wrong.reset({"environment": "same-name"}, [6], [3], [-1.] * 3, [1.] * 3) + finally: + wrong.abort() + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/cd/cd36ae0fe3d19e955374686b3e040a3c4b072d51cf758394972b4e2c41148356/test.sh b/reproduction/files/cd/cd36ae0fe3d19e955374686b3e040a3c4b072d51cf758394972b4e2c41148356/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..dea64eb5e0db1cfdcd6007817b09c4c01b575c10 --- /dev/null +++ b/reproduction/files/cd/cd36ae0fe3d19e955374686b3e040a3c4b072d51cf758394972b4e2c41148356/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail +# Fresh inference and scoring; infrastructure failures never create reward.json. +# The NVIDIA container runtime bind-mounts entries under /proc/driver/nvidia; the kernel then refuses +# the fresh procfs of the prediction's user namespace ("Can't mount proc"). Detach them first, as the +# weather verifier does; the GPUs stay usable through /dev/nvidia*. +for mount in $(awk '$5 ~ /^\/proc\/driver\/nvidia/ {print $5}' /proc/self/mountinfo | sort -r); do + umount "${mount}" 2>/dev/null || echo "warning: could not detach ${mount}; the sandbox may fail" >&2 +done +exec python3 -B /opt/pathfinder/upstream/pathfinder/verify_single.py \ + --submission /workspace/submission \ + --image /benchmark/image --suite /benchmark/suite --runtime /benchmark/runtime \ + --limits /opt/pathfinder/limits.json --root /workspace/research/run \ + --logs /logs/verifier --seconds 41400 diff --git a/reproduction/files/cd/cd86433d24b9e5b5db9dc7b4e23532615ec155490cd38ba74953cb7b37925874/test_alphaqubit_gate.py b/reproduction/files/cd/cd86433d24b9e5b5db9dc7b4e23532615ec155490cd38ba74953cb7b37925874/test_alphaqubit_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..01cd77744a9ee2c207d663062780ed03e8d86d36 --- /dev/null +++ b/reproduction/files/cd/cd86433d24b9e5b5db9dc7b4e23532615ec155490cd38ba74953cb7b37925874/test_alphaqubit_gate.py @@ -0,0 +1,99 @@ +"""Independent expansion policy tests; no model training or test-fold reads.""" +from __future__ import annotations + +import json +import copy +import math +from pathlib import Path + +import pytest + +from baselines.alphaqubit_gate import GROUPS, _validation_evidence, checked_fit, policy_decision, run_gate + + +def evidence(**changes): + return {"global_steps": 15000, "seen_samples": 5_000_000, "complete_validations": 5, + "accepted_best_fit": True, "first_main_BCE": 0.65, "candidate_main_BCE": 0.50, + "selected_LER": 0.034, "matching_LER": 0.02, + "selected_errors": 18000, "no_correction_errors": 24000, + "total_shots": 66560, **changes} + + +def test_learning_and_already_strong_are_independent_positive_routes() -> None: + learning = policy_decision(evidence()) + assert learning["passed"] and not learning["measurements"]["already_strong"] + strong = policy_decision(evidence(candidate_main_BCE=0.64, selected_LER=0.024)) + assert strong["passed"] and strong["measurements"]["already_strong"] + assert strong["measurements"]["bce_relative_improvement"] < 0.10 + + +@pytest.mark.parametrize("changes,reason", [ + ({"global_steps": 9999}, "fewer_than_10000_optimizer_steps"), + ({"seen_samples": 3_999_999}, "fewer_than_4M_training_examples"), + ({"complete_validations": 2}, "fewer_than_three_complete_validations"), + ({"accepted_best_fit": False}, "no_accepted_best_validation_fit"), + ({"selected_LER": 0.0401}, "selected_LER_exceeds_twice_matching_or_fit_unavailable"), + ({"candidate_main_BCE": 0.64}, "insufficient_BCE_improvement_and_not_already_strong"), + ({"selected_errors": 21601}, "less_than_10_percent_shot_error_improvement_over_no_correction"), + ({"matching_LER": None}, "selected_LER_exceeds_twice_matching_or_fit_unavailable"), +]) +def test_each_required_gate_rejects_independently(changes, reason) -> None: + result = policy_decision(evidence(**changes)) + assert not result["passed"] and reason in result["rejection_reasons"] + + +def test_zero_matching_does_not_create_an_infinite_or_spurious_pass() -> None: + result = policy_decision(evidence(matching_LER=0.0)) + assert not result["passed"] and result["measurements"]["model_to_matching_LER_ratio"] is None + assert policy_decision(evidence(matching_LER=0.0, selected_LER=0.0))["passed"] + + +def test_missing_artifacts_always_write_non_scientific_no_expansion(tmp_path: Path) -> None: + output = tmp_path / "nested" / "gate.json" + result = run_gate(tmp_path, output) + assert json.loads(output.read_text()) == result + assert not result["passed"] and result["decision"] == "no_expansion" + assert set(result["groups"]) == set(GROUPS) + assert all(record["status"] == "insufficient_evidence" for record in result["groups"].values()) + assert "not a negative scientific result" in result["interpretation"] + + +def fit_snapshot(step: int, bce: float) -> dict: + rows = [] + for rounds in range(1, 26, 2): + errors = round((1 - math.exp(0.003 + rounds * math.log(0.96))) * 5120 / 2) + rows.append({"condition": f"surface_code_bX_d3_r{rounds:02d}_center_3_5", "rounds": rounds, + "shots": 5120, "errors": errors, "main_error": errors / 5120, + "main_loss": bce, "aux_loss": 0.2, "loss": bce + 0.004}) + fit = checked_fit(rows) + assert fit["accepted"] + return {"complete": True, "global_steps": step, "seen_samples": step * 256, + "shots": 66560, "per_condition": rows, "fit": fit, + "main_error": sum(row["errors"] for row in rows) / 66560, + "main_loss": bce, "aux_loss": 0.2, "loss": bce + 0.004} + + +def test_validation_evidence_recomputes_fit_and_rejects_count_drift() -> None: + history = [fit_snapshot(4000, 0.65), fit_snapshot(9000, 0.5), fit_snapshot(16000, 0.55)] + progress = {"global_steps": 16000, "latest_validation": history[-1]} + best = {"validation": history[1]} + complete, candidate = _validation_evidence(history, best, progress) + assert len(complete) == 3 and candidate["global_steps"] == 9000 + modified = copy.deepcopy(history) + modified[0]["per_condition"][0]["errors"] += 1 + with pytest.raises(ValueError, match="raw counts"): + _validation_evidence(modified, best, progress) + modified = copy.deepcopy(history) + modified[1]["fit"]["logical_error_per_round"] *= 0.5 + with pytest.raises(ValueError, match="does not reproduce"): + _validation_evidence(modified, best, progress) + with pytest.raises(ValueError, match="duplicated"): + _validation_evidence([history[0], *history], best, progress) + modified = copy.deepcopy(history) + modified[0]["main_loss"] += 0.1 + with pytest.raises(ValueError, match="aggregate"): + _validation_evidence(modified, best, progress) + with pytest.raises(ValueError, match="absent"): + _validation_evidence(history, {"validation": fit_snapshot(8000, 0.5)}, progress) + with pytest.raises(ValueError, match="absent"): + _validation_evidence(history, best, {**progress, "latest_validation": history[0]}) diff --git a/reproduction/files/ce/ceb41d1d7c4037397e4a6233a02056a17f07d78232c38d23fa30c3ccedaed123/risk_scoring.py b/reproduction/files/ce/ceb41d1d7c4037397e4a6233a02056a17f07d78232c38d23fa30c3ccedaed123/risk_scoring.py new file mode 100644 index 0000000000000000000000000000000000000000..9a2f19e4a4fdf5f67fd9d7e006fb615b18ea8fe4 --- /dev/null +++ b/reproduction/files/ce/ceb41d1d7c4037397e4a6233a02056a17f07d78232c38d23fa30c3ccedaed123/risk_scoring.py @@ -0,0 +1,477 @@ +"""Trusted scorer for first-recorded disease time and mortality risk.""" + +from __future__ import annotations + +import json +from datetime import timedelta +from pathlib import Path + +import numpy as np +import duckdb +import pyarrow as pa +import pyarrow.parquet as pq + +from labels import death_label +from panel_scoring import PRIMARY as PANEL_PRIMARY, history_code, panel_score + +HORIZONS = tuple(range(30, 361, 30)) + (365,) +MAX_NORMALIZATION_WEIGHT = 1000.0 + + +def mean_or_none(values) -> float | None: + values = [v for v in values if v is not None] + return float(np.mean(values)) if values else None + + +def percentile_interval(values) -> list[float] | None: + available = [x for x in values if x is not None] + return np.quantile(available, [.025, .975]).tolist() if available else None + + +def weighted_auc(y: np.ndarray, p: np.ndarray, weight: np.ndarray) -> float | None: + """Exact tie-aware weighted AUROC via prediction-value groups.""" + positive = float(weight[y == 1].sum()) + negative = float(weight[y == 0].sum()) + if not positive or not negative: + return None + _, group = np.unique(p, return_inverse=True) + positive_weight = np.bincount(group, weights=weight * (y == 1)) + negative_weight = np.bincount(group, weights=weight * (y == 0)) + lower_negative = np.cumsum(negative_weight) - negative_weight + concordance = np.sum(positive_weight * (lower_negative + .5 * negative_weight)) + return float(concordance / (positive * negative)) + + +def auc_and_average_precision(y: np.ndarray, p: np.ndarray) -> tuple[float, float]: + """Tie-aware AUROC and AP from one stable prediction sort.""" + order = np.argsort(p, kind="stable") + y_sorted, p_sorted = y[order], p[order] + starts = np.r_[0, np.flatnonzero(p_sorted[1:] != p_sorted[:-1]) + 1] + positive_group = np.add.reduceat(y_sorted, starts).astype(np.float64) + group_size = np.diff(np.r_[starts, len(y)]).astype(np.float64) + negative_group = group_size - positive_group + positive, negative = float(positive_group.sum()), float(negative_group.sum()) + lower_negative = np.cumsum(negative_group) - negative_group + auc = float(np.sum(positive_group * (lower_negative + .5 * negative_group)) + / (positive * negative)) + descending_positive = positive_group[::-1] + descending_size = group_size[::-1] + cumulative_positive = np.cumsum(descending_positive) + precision = cumulative_positive / np.cumsum(descending_size) + ap = float(np.sum(precision * descending_positive) / positive) + return auc, ap + + +def calibration(y: np.ndarray, p: np.ndarray, bins: int = 10) -> dict | None: + if not len(y): + return None + edges = np.linspace(0.0, 1.0, bins + 1) + bucket = np.clip(np.searchsorted(edges, p, side="right") - 1, 0, bins - 1) + ece, nonempty = 0.0, 0 + for k in range(bins): + use = bucket == k + if use.any(): + nonempty += 1 + ece += float(use.mean()) * abs(float(p[use].mean()) - float(y[use].mean())) + observed, predicted = float(y.mean()), float(p.mean()) + return {"observed_rate": observed, "mean_prediction": predicted, + "calibration_in_the_large": predicted - observed, + "expected_calibration_error_10bin": ece, "nonempty_bins": nonempty} + + +def metrics(y: np.ndarray, p: np.ndarray, valid: np.ndarray) -> dict: + y, p = y[valid].astype(np.uint8), p[valid].astype(np.float64) + n, positives = len(y), int(y.sum()) + result = {"valid": n, "positives": positives, "negatives": n - positives, + "auroc": None, "auprc": None, "brier": None, + "calibration": calibration(y, p), "reason": None} + if not n: + result["reason"] = "no_valid_labels" + return result + result["brier"] = float(np.mean((p - y) ** 2)) + if not positives or positives == n: + result["reason"] = "single_class" + return result + result["auroc"], result["auprc"] = auc_and_average_precision(y, p) + return result + + +def read_predictions(path: Path, sample_ids: list[str], disease_count: int, + horizons: tuple[int, ...] = HORIZONS) -> tuple[np.ndarray, np.ndarray]: + table = pq.read_table(path, columns=["sample_id", "disease_risk", "death_risk"]) + if table.num_rows != len(sample_ids): + raise ValueError("Prediction row count differs from public sample count") + by_id = {sid: i for i, sid in enumerate(sample_ids)} + disease = np.empty((len(sample_ids), disease_count, len(horizons)), dtype=np.float32) + death = np.empty((len(sample_ids), len(horizons)), dtype=np.float32) + seen = set() + for row in table.to_pylist(): + sid = row["sample_id"] + if sid not in by_id or sid in seen: + raise ValueError("Unknown or repeated sample_id") + seen.add(sid) + dr = np.asarray(row["disease_risk"], dtype=np.float32) + mr = np.asarray(row["death_risk"], dtype=np.float32) + if dr.size != disease_count * len(horizons) or mr.size != len(horizons): + raise ValueError("Prediction dimensions do not match frozen diseases and direct time grid") + disease[by_id[sid]] = dr.reshape(disease_count, len(horizons)) + death[by_id[sid]] = mr + if seen != set(sample_ids): + raise ValueError("Missing prediction sample_id") + if not np.isfinite(disease).all() or not np.isfinite(death).all(): + raise ValueError("Non-finite probability") + if (disease < 0).any() or (disease > 1).any() or (death < 0).any() or (death > 1).any(): + raise ValueError("Probability outside [0,1]") + if (np.diff(disease, axis=2) < -1e-6).any() or (np.diff(death, axis=1) < -1e-6).any(): + raise ValueError("Cumulative risk decreases across horizons") + return disease, death + + +def disease_time_brier(labels: np.ndarray, prediction: np.ndarray, + valid: np.ndarray) -> tuple[float | None, list[dict]]: + """Equal-weight time average per disease, then macro average diseases.""" + per_disease = [] + for j in range(labels.shape[1]): + by_time = [] + for k in range(labels.shape[2]): + use = valid[:, j, k] + by_time.append(float(np.mean((prediction[use, j, k] - labels[use, j, k]) ** 2)) + if use.any() else None) + available = [x for x in by_time if x is not None] + per_disease.append({"time_brier": float(np.mean(available)) if available else None, + "timepoint_brier": by_time, + "reason": None if available else "no_valid_labels"}) + return mean_or_none([x["time_brier"] for x in per_disease]), per_disease + + +def disease_time_discrimination(labels: np.ndarray, prediction: np.ndarray, + valid: np.ndarray) -> tuple[dict, list[dict]]: + """Disease-first, time-averaged discrimination on the frozen valid cells. + + A disease/time cell with no positive or no negative label is unavailable. It + is deliberately not assigned a neutral value: available time points are + averaged within each disease, then available diseases are averaged equally. + """ + per_disease = [] + for j in range(labels.shape[1]): + by_time = [] + for k in range(labels.shape[2]): + value = metrics(labels[:, j, k], prediction[:, j, k], valid[:, j, k]) + by_time.append(value) + available_auc = [cell["auroc"] for cell in by_time if cell["auroc"] is not None] + available_auprc = [cell["auprc"] for cell in by_time if cell["auprc"] is not None] + per_disease.append({ + "time_averaged_auroc": mean_or_none(available_auc), + "time_averaged_auprc": mean_or_none(available_auprc), + "valid_timepoint_cells": len(available_auc), + "timepoints": by_time, + "reason": None if available_auc else "no_two_class_timepoint", + }) + available = [item for item in per_disease if item["time_averaged_auroc"] is not None] + scorable_cells = [cell for item in available for cell in item["timepoints"] + if cell["auroc"] is not None] + summary = { + "macro_time_averaged_auroc": mean_or_none( + [item["time_averaged_auroc"] for item in available]), + "macro_time_averaged_auprc": mean_or_none( + [item["time_averaged_auprc"] for item in available]), + "valid_diseases": len(available), + "frozen_diseases": labels.shape[1], + "valid_disease_time_cells": len(scorable_cells), + "frozen_disease_time_cells": labels.shape[1] * labels.shape[2], + "positive_support": int(sum(cell["positives"] for cell in scorable_cells)), + "negative_support": int(sum(cell["negatives"] for cell in scorable_cells)), + } + return summary, per_disease + + +def weighted_macro_time_auroc(labels: np.ndarray, prediction: np.ndarray, + valid: np.ndarray, weight: np.ndarray) -> float | None: + """Recompute the primary metric for a patient-bootstrap frequency vector.""" + disease_auc = [] + present = weight > 0 + for j in range(labels.shape[1]): + time_auc = [] + for k in range(labels.shape[2]): + use = valid[:, j, k] & present + value = weighted_auc(labels[use, j, k], prediction[use, j, k], weight[use]) + if value is not None: + time_auc.append(value) + if time_auc: + disease_auc.append(float(np.mean(time_auc))) + return mean_or_none(disease_auc) + + +def normalized_disease_time_brier(labels: np.ndarray, prediction: np.ndarray, + valid: np.ndarray, + denominators: np.ndarray) -> tuple[float | None, list[dict]]: + """Divide each disease/time Brier by its frozen train-only reference.""" + if denominators.shape != labels.shape[1:] or not np.isfinite(denominators).all(): + raise ValueError("Normalization denominator dimensions or values are invalid") + if (denominators <= 0).any(): + raise ValueError("Normalization denominators must be positive") + _, raw = disease_time_brier(labels, prediction, valid) + per_disease = [] + for j, detail in enumerate(raw): + by_time = [None if value is None else value / float(denominators[j, k]) + for k, value in enumerate(detail["timepoint_brier"])] + available = [value for value in by_time if value is not None] + per_disease.append({ + "normalized_time_brier": float(np.mean(available)) if available else None, + "normalized_timepoint_brier": by_time, + "raw_time_brier": detail["time_brier"], + "raw_timepoint_brier": detail["timepoint_brier"], + "reason": None if available else "no_valid_labels", + }) + return mean_or_none([x["normalized_time_brier"] for x in per_disease]), per_disease + + +def read_normalization(path: Path, disease_codes: list[str]) -> tuple[np.ndarray, dict]: + table = pq.read_table(path) + required = {"disease_code", "horizon_days", "age_sex_oof_brier", + "denominator_brier", "normalization_weight", "floor_applied"} + if not required.issubset(table.schema.names): + raise ValueError("Train-only normalization artifact has missing fields") + index = {code: j for j, code in enumerate(disease_codes)} + denominators = np.full((len(disease_codes), len(HORIZONS)), np.nan, dtype=np.float64) + raw_reference = np.full_like(denominators, np.nan) + horizon_index = {h: k for k, h in enumerate(HORIZONS)} + floor_applied = np.zeros_like(denominators, dtype=np.bool_) + for row in table.to_pylist(): + if row["disease_code"] not in index or row["horizon_days"] not in horizon_index: + raise ValueError("Normalization artifact contains an unknown disease or horizon") + j, k = index[row["disease_code"]], horizon_index[row["horizon_days"]] + if np.isfinite(denominators[j, k]): + raise ValueError("Duplicate disease/time normalization cell") + denominators[j, k] = row["denominator_brier"] + raw_reference[j, k] = row["age_sex_oof_brier"] + floor_applied[j, k] = row["floor_applied"] + if not np.isclose(row["normalization_weight"], 1.0 / denominators[j, k]): + raise ValueError("Normalization weight and denominator disagree") + if not np.isfinite(denominators).all() or (denominators <= 0).any(): + raise ValueError("Normalization artifact does not cover the frozen score grid") + if (1.0 / denominators).max() > MAX_NORMALIZATION_WEIGHT + 1e-9: + raise ValueError("Normalization artifact exceeds the frozen weight cap") + metadata = {"cells": int(denominators.size), + "floor_applied_cells": int(floor_applied.sum()), + "minimum_denominator": float(denominators.min()), + "maximum_weight": float((1.0 / denominators).max()), + "mean_train_reference_ratio": float(np.mean(raw_reference / denominators))} + return denominators, metadata + + +def _date(value): + return value.date() if hasattr(value, "time") else value + + +def _full_year(row: dict) -> bool: + cutoff = _date(row["cutoff"]) + return (cutoff + timedelta(days=365) <= _date(row["diagnosis_observation_end"]) + and cutoff + timedelta(days=365) <= _date(row["death_observation_end"])) + + +def score(input_dir: Path, trusted_dir: Path, prediction_file: Path, + bootstrap: int = 0, normalization_file: Path | None = None) -> dict: + manifest = json.loads((input_dir / "manifest.json").read_text()) + if manifest.get("horizons_days") != list(HORIZONS): + raise ValueError("Submission must predict every frozen time point directly") + disease_codes = manifest["scored_diseases"] + denominators, normalization_metadata = read_normalization( + normalization_file or trusted_dir / "risk_normalization.parquet", disease_codes) + public_samples = pq.read_table(input_dir / "samples.parquet").to_pylist() + sample_ids = [r["sample_id"] for r in public_samples] + sample_index = {sid: i for i, sid in enumerate(sample_ids)} + disease_index = {code: i for i, code in enumerate(disease_codes)} + if len(sample_index) != len(sample_ids): + raise ValueError("Duplicate public sample ID") + prediction, death_prediction = read_predictions( + prediction_file, sample_ids, len(disease_codes)) + db = duckdb.connect() + db.register("sample_order", pa.table({"sample_id": sample_ids, + "i": np.arange(len(sample_ids), dtype=np.int32)})) + db.register("disease_order", pa.table({"disease_code": disease_codes, + "j": np.arange(len(disease_codes), dtype=np.int16)})) + label_path = str(trusted_dir / "label_windows.parquet") + total, unique = db.execute("""SELECT count(*),count(DISTINCT (sample_id,disease_code)) + FROM read_parquet(?)""", [label_path]).fetchone() + expected = len(sample_ids) * len(disease_codes) + if total != expected or unique != expected: + db.close() + raise ValueError("Trusted label keys are duplicated or do not cover the public grid") + fields = [f"l.{field}_{horizon}" for horizon in HORIZONS + for field in ("disease_label", "disease_valid")] + aligned = db.execute(f"""SELECT {','.join(fields)} FROM sample_order s + CROSS JOIN disease_order d JOIN read_parquet(?) l USING(sample_id,disease_code) + ORDER BY s.i,d.j""", [label_path]).fetchnumpy() + db.close() + labels = np.stack([aligned[f"disease_label_{h}"] for h in HORIZONS], axis=1) + valid = np.stack([aligned[f"disease_valid_{h}"] for h in HORIZONS], axis=1) + labels = labels.reshape(prediction.shape).astype(np.uint8) + valid = valid.reshape(prediction.shape).astype(bool) + + boundaries = {r["sample_id"]: r for r in pq.read_table( + trusted_dir / "sample_boundaries.parquet").to_pylist() + if r["sample_id"] in sample_index} + if len(boundaries) != len(sample_ids): + raise ValueError("Missing trusted observation boundary") + death_y = np.zeros((len(sample_ids), len(HORIZONS)), dtype=np.uint8) + death_valid = np.zeros_like(death_y, dtype=np.bool_) + primary_patients = np.zeros(len(sample_ids), dtype=np.bool_) + for sid, i in sample_index.items(): + row = boundaries[sid] + primary_patients[i] = _full_year(row) + for k, horizon in enumerate(HORIZONS): + death_y[i, k], death_valid[i, k] = death_label(row, horizon) + + primary_valid = valid & primary_patients[:, None, None] + history = [set() for _ in sample_ids] + for sid, code in duckdb.connect().execute("""SELECT DISTINCT sample_id, code + FROM read_parquet(?) WHERE event_type='diagnosis'""", + [str(input_dir / "events.parquet")]).fetchall(): + if sid in sample_index: + history[sample_index[sid]].add(history_code(code)) + k365 = HORIZONS.index(365) + panel = panel_score(labels[:, :, k365], valid[:, :, k365], prediction[:, :, k365], + primary_patients, disease_codes, history) + discrimination, discrimination_by_disease = disease_time_discrimination( + labels, prediction, primary_valid) + primary_score = discrimination["macro_time_averaged_auroc"] + raw_primary_score, _ = disease_time_brier(labels, prediction, primary_valid) + normalized_brier, brier_by_disease = normalized_disease_time_brier( + labels, prediction, primary_valid, denominators) + death_primary = [metrics(death_y[:, k], death_prediction[:, k], + death_valid[:, k] & primary_patients) + for k in range(len(HORIZONS))] + death_time_brier = mean_or_none([x["brier"] for x in death_primary]) + + by_horizon, per_disease = {}, {"time_brier": {}, "discrimination": {}} + for k, horizon in enumerate(HORIZONS): + one = {} + for j, code in enumerate(disease_codes): + horizon_valid = valid[:, j, k] & primary_patients + value = discrimination_by_disease[j]["timepoints"][k] + value["coverage_in_primary_cohort"] = float( + horizon_valid.sum() / max(primary_patients.sum(), 1)) + one[code] = value + auc = [x for x in one.values() if x["auroc"] is not None] + calibrated = [x["calibration"] for x in one.values() if x["calibration"] is not None] + by_horizon[str(horizon)] = { + "macro_auroc": mean_or_none([x["auroc"] for x in auc]), + "macro_auprc": mean_or_none([x["auprc"] for x in auc]), + "macro_brier": mean_or_none([x["brier"] for x in one.values()]), + "macro_normalized_brier": mean_or_none([ + value["brier"] / denominators[disease_index[code], k] + for code, value in one.items() if value["brier"] is not None]), + "macro_expected_calibration_error_10bin": mean_or_none( + [x["expected_calibration_error_10bin"] for x in calibrated]), + "valid_pairs": int(primary_valid[:, :, k].sum()), + "positive_pairs": int((labels[:, :, k] & primary_valid[:, :, k]).sum()), + "valid_patients": int(primary_valid[:, :, k].any(axis=1).sum()), + "scorable_auroc_diseases": len(auc), "frozen_diseases": len(disease_codes), + "disease_without_auc": {code: value["reason"] for code, value in one.items() + if value["auroc"] is None}, + "death": metrics(death_y[:, k], death_prediction[:, k], + death_valid[:, k] & primary_patients), + } + per_disease[str(horizon)] = one + for j, code in enumerate(disease_codes): + brier_by_disease[j]["horizons_days"] = list(HORIZONS) + brier_by_disease[j]["normalization_denominator"] = denominators[j].tolist() + per_disease["time_brier"][code] = brier_by_disease[j] + per_disease["discrimination"][code] = discrimination_by_disease[j] + + ages = np.asarray([r["approx_age"] for r in public_samples]) + sexes = np.asarray([r["gender"] for r in public_samples]) + any_event = np.asarray([bool(boundaries[sid]["any_future_disease_record_365"]) + for sid in sample_ids]) + subsets = {"age_18_64": ages < 65, "age_65_plus": ages >= 65, + "sex_F": sexes == "F", "sex_M": sexes == "M", + "no_future_disease_record": primary_patients & ~any_event, + "future_disease_record": primary_patients & any_event} + strata = {} + for name, subset in subsets.items(): + fixed = subset & primary_patients + raw_score_value, _ = disease_time_brier( + labels, prediction, valid & fixed[:, None, None]) + score_value, _ = normalized_disease_time_brier( + labels, prediction, valid & fixed[:, None, None], denominators) + parts = [metrics(labels[:, j, -1], prediction[:, j, -1], + valid[:, j, -1] & fixed) for j in range(len(disease_codes))] + auc = [x for x in parts if x["auroc"] is not None] + strata[name] = {"n": int(fixed.sum()), + "age_sex_normalized_disease_time_brier": score_value, + "raw_disease_time_brier_macro": raw_score_value, + "macro_auroc_365d": mean_or_none([x["auroc"] for x in auc]), + "macro_auprc_365d": mean_or_none([x["auprc"] for x in auc]), + "macro_brier_365d": mean_or_none([x["brier"] for x in parts]), + "scorable_auroc_diseases": len(auc), + "death_time_brier": mean_or_none([metrics( + death_y[:, k], death_prediction[:, k], death_valid[:, k] & fixed)["brier"] + for k in range(len(HORIZONS))])} + + confidence = None + if bootstrap > 0: + rng = np.random.default_rng(20260924) + primary_rows = np.flatnonzero(primary_patients) + boot_labels = labels[primary_rows] + boot_prediction = prediction[primary_rows] + boot_valid = valid[primary_rows] + squared_error = (boot_prediction - boot_labels) ** 2 + boot_death_y = death_y[primary_rows] + boot_death_prediction = death_prediction[primary_rows] + boot_death_valid = death_valid[primary_rows] + death_squared_error = (boot_death_prediction - boot_death_y) ** 2 + disease_values, death_values, auc365_values, primary_auc_values = [], [], [], [] + for _ in range(bootstrap): + sampled = rng.integers(0, len(primary_rows), len(primary_rows)) + weights = np.bincount(sampled, minlength=len(primary_rows)).astype(np.float64) + disease_denominator = np.tensordot(weights, boot_valid, axes=(0, 0)) + disease_numerator = np.tensordot( + weights, squared_error * boot_valid, axes=(0, 0)) + with np.errstate(invalid="ignore", divide="ignore"): + time_brier = np.divide(disease_numerator, disease_denominator, + out=np.full_like(disease_numerator, np.nan), + where=disease_denominator > 0) + disease_values.append(float(np.nanmean( + np.nanmean(time_brier / denominators, axis=1)))) + death_denominator = np.tensordot(weights, boot_death_valid, axes=(0, 0)) + death_numerator = np.tensordot( + weights, death_squared_error * boot_death_valid, axes=(0, 0)) + with np.errstate(invalid="ignore", divide="ignore"): + death_brier = np.divide(death_numerator, death_denominator, + out=np.full_like(death_numerator, np.nan), + where=death_denominator > 0) + death_values.append(float(np.nanmean(death_brier))) + auc_parts = [] + for j in range(len(disease_codes)): + use = boot_valid[:, j, -1] & (weights > 0) + value = weighted_auc(boot_labels[use, j, -1], + boot_prediction[use, j, -1], weights[use]) + if value is not None: + auc_parts.append(value) + auc365_values.append(mean_or_none(auc_parts)) + primary_auc_values.append(weighted_macro_time_auroc( + boot_labels, boot_prediction, boot_valid, weights)) + confidence = {"bootstrap_patients": bootstrap, + "macro_time_averaged_auroc_95pct": percentile_interval(primary_auc_values), + "age_sex_normalized_disease_time_brier_95pct": percentile_interval(disease_values), + "death_time_brier_95pct": percentile_interval(death_values), + "macro_auroc_365d_95pct": percentile_interval(auc365_values)} + + return {"schema": "natural-disease-progression-report/v3", + # The reward. "primary" keeps the earlier disease-first AUROC as a reported metric. + "reward_metric": PANEL_PRIMARY, + "panel": panel, + "primary": discrimination, + "auxiliary": { + "raw_disease_time_brier_macro": raw_primary_score, + "age_sex_normalized_disease_time_brier": normalized_brier, + }, + "normalization": normalization_metadata, + "mortality": {"death_time_brier": death_time_brier, + "by_time": dict(zip(map(str, HORIZONS), death_primary))}, + "cohort": {"all_samples": len(sample_ids), + "primary_complete_year": int(primary_patients.sum()), + "partial_observation_outside_primary": int((~primary_patients).sum())}, + "horizons": by_horizon, "per_disease": per_disease, + "strata": strata, "confidence_intervals": confidence} diff --git a/reproduction/files/ce/ced338ca379f16966407adbdd11203fdc96761117fa9ba0f4117692c7050d721/test_public_release.py b/reproduction/files/ce/ced338ca379f16966407adbdd11203fdc96761117fa9ba0f4117692c7050d721/test_public_release.py new file mode 100644 index 0000000000000000000000000000000000000000..d82bc9aad8a31e077fe612ff53a6a3895c8fefb5 --- /dev/null +++ b/reproduction/files/ce/ced338ca379f16966407adbdd11203fdc96761117fa9ba0f4117692c7050d721/test_public_release.py @@ -0,0 +1,270 @@ +"""Frozen public train/test membership and materialization, never fake CFD proof.""" + +import copy +from contextlib import redirect_stdout +import hashlib +import io +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + + +DATA = Path(__file__).resolve().parents[1] / "environment/data" +sys.path.insert(0, str(DATA)) +import public_release as public +import materialize + + +class PublicReleaseTests(unittest.TestCase): + def setUp(self): + self.release = public.load_release(DATA / "release-500gb-v1.json") + self.index = json.loads((DATA / "source-files.json").read_text()) + + def test_selection_is_reproducible_and_not_cfd_certification(self): + actual = public.build(json.loads((DATA / "resource-audit.json").read_text()), + self.index, json.loads((DATA / "native-configs.json").read_text())) + self.assertEqual(actual, self.release) + self.assertEqual(actual["case_count"], 47) + self.assertEqual(actual["status"], "data-release-not-cfd-certified") + self.assertEqual(actual["training"]["case_ids"], actual["test"]["case_ids"]) + self.assertEqual(actual["files"]["count"], 730) + self.assertEqual(actual["files"]["bytes"], 488770756805) + self.assertEqual(actual["data_budget"]["max_bytes"], 500000000000) + self.assertIsNone(actual["training"]["fixed_transition_count"]) + self.assertEqual(sum(c["dimension"] == 2 for c in actual["cases"]), 30) + self.assertEqual(sum(c["dimension"] == 3 for c in actual["cases"]), 17) + self.assertTrue(all(c["execution_status"] != "validated" for c in actual["cases"])) + + def test_selected_backends_and_scientific_pairs_are_kept(self): + self.assertEqual(self.release["backend_counts"], { + "maia": 31, "maia-structured": 1, "firedrake": 9, + "jax": 2, "jax-fluids": 3, "nek5000-v19": 1}) + ids = set(self.release["test"]["case_ids"]) + for re in (10000, 50000): + for objective in ("NACA0012", "NACA0012Gust"): + self.assertIn(f"{objective}_3D_Re{re}_AOA12", ids) + for re in (30, 75, 100, 150): + self.assertIn(f"Pinball_3D_Re{re}", ids) + self.assertTrue({"Cylinder_3D_Re200", "Cylinder_3D_Re3900", + "Sphere_3D_Re300", "Sphere_3D_Re3700", "Cube_3D_Re3700", + "DRA2303Jet_3D_Re400000_Ma02", "Nozzle3D_coarse", + "Channel_3D_Retau180", "TCFmini_3D_Re180"}.issubset(ids)) + + def test_budget_exclusions_are_not_missing_data(self): + excluded = [e for e in self.release["exclusions"] if e["reason"] == "not_selected_500gb_scope"] + self.assertEqual(len(excluded), 15) + self.assertEqual(sum(e["bytes"] for e in excluded), 1093326110913 - 488770756805) + self.assertTrue(all(e["resource_status"] == "required_payloads_present" for e in excluded)) + self.assertTrue({"Nozzle3D_fine", "NACA0012_3D_Re200000_AOA0"}.issubset( + {e["environment"] for e in excluded})) + self.assertTrue(set(e["environment"] for e in excluded).isdisjoint(self.release["test"]["case_ids"])) + + def test_missing_selected_asset_cannot_silently_shrink_release(self): + index = copy.deepcopy(self.index) + index["files"] = [f for f in index["files"] if f["rfilename"] != + "DRA2303Jet_3D_Re400000_Ma02/restart_.hdf5"] + with self.assertRaisesRegex(ValueError, "Selected cases lack complete resources"): + public.build(json.loads((DATA / "resource-audit.json").read_text()), + index, json.loads((DATA / "native-configs.json").read_text())) + + def test_oversize_source_assets_are_rejected(self): + index = copy.deepcopy(self.index) + item = next(f for f in index["files"] if f["rfilename"].startswith("Cube_3D_Re3700/")) + item["size"] += 500000000000 + with self.assertRaisesRegex(ValueError, "exceed.*500 GB"): + public.build(json.loads((DATA / "resource-audit.json").read_text()), + index, json.loads((DATA / "native-configs.json").read_text())) + + def test_real_exclusions_are_explicit_not_score_based(self): + excluded = self.release["exclusions"] + self.assertEqual(sum(e["reason"] == "missing_payload" for e in excluded), 9) + self.assertEqual(sum(e["reason"] == "parameter_mismatch" for e in excluded), 1) + self.assertTrue(any(e.get("environment") == "SquareCylinder_2D_Re3900" + and e["missing"] == ["restart_.Netcdf"] for e in excluded)) + self.assertTrue(all("score" not in e["reason"] for e in excluded)) + + def test_partition_variants_and_analytic_initialization_are_not_missing(self): + configs = {c["name"]: c["config"] for c in json.loads((DATA / "native-configs.json").read_text())["configs"]} + for name in ["Kolmogorov_2D", "Nozzle3D_fine", "NACA0012_3D_Re200000_AOA0"]: + files = [f for f in self.index["files"] if f["rfilename"].startswith(name + "/")] + self.assertEqual(public.resource_inputs(name, files, configs[name])[1], []) + files = [f for f in self.index["files"] if f["rfilename"].startswith("Nozzle3D_fine/") + and not f["rfilename"].endswith("restart_proc2.h5")] + missing = public.resource_inputs("Nozzle3D_fine", files, configs["Nozzle3D_fine"])[1] + self.assertIn("restart_proc2.h5", missing) + + def test_no_unvalidated_physics_reconstruction(self): + reconstructed = [c for c in self.release["cases"] if c["configuration_identity_reconstructed"]] + self.assertEqual(len(reconstructed), 9) + self.assertTrue(all(c["backend"] == "firedrake" for c in reconstructed)) + self.assertNotIn("Cavity_2D_Re4200", self.release["test"]["case_ids"]) + self.assertNotIn("Cavity_2D_Re4140", self.release["test"]["case_ids"]) + + def test_exact_suite_binding_not_a_subset(self): + suite = {"data_release_id": self.release["release_id"], + "data_release_sha256": public.digest(self.release), + "cases": [{"id": c["id"], "environment": c["environment"], "backend": c["backend"]} + for c in self.release["cases"]]} + public.validate_suite_binding(self.release, suite) + bad = copy.deepcopy(suite) + bad["cases"].pop() + with self.assertRaisesRegex(ValueError, "exact frozen"): + public.validate_suite_binding(self.release, bad) + bad = copy.deepcopy(suite) + bad["cases"][0]["environment"] = "another-Re" + with self.assertRaisesRegex(ValueError, "replaced"): + public.validate_suite_binding(self.release, bad) + bad = copy.deepcopy(suite) + bad["cases"][0]["backend"] = "fake" + with self.assertRaisesRegex(ValueError, "backend"): + public.validate_suite_binding(self.release, bad) + bad = copy.deepcopy(suite) + bad["data_release_sha256"] = "different" + with self.assertRaisesRegex(ValueError, "not bound"): + public.validate_suite_binding(self.release, bad) + + def test_no_source_path_or_hash_ambiguity(self): + for field, value in [("rfilename", "../outside"), ("blobId", "invalid"), ("size", -1)]: + bad = copy.deepcopy(self.index) + bad["files"][0] = {"rfilename": "file", "size": 0, "blobId": "a" * 40, field: value} + with self.assertRaises(ValueError): + public.validate_index(bad) + bad = copy.deepcopy(self.index) + bad["files"].append(bad["files"][0]) + with self.assertRaisesRegex(ValueError, "duplicate"): + public.validate_index(bad) + + def test_train_test_drift_is_rejected(self): + release = copy.deepcopy(self.release) + release["test"]["case_ids"] = release["test"]["case_ids"][:-1] + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / "release.json" + path.write_text(json.dumps(release)) + with self.assertRaisesRegex(ValueError, "drift"): + public.load_release(path) + + def test_mutated_membership_budget_and_totals_are_rejected(self): + for mutation in ("membership", "budget", "totals", "old-version"): + release = copy.deepcopy(self.release) + if mutation == "membership": + release["cases"].pop() + release["case_count"] -= 1 + release["training"]["case_ids"] = [c["id"] for c in release["cases"]] + release["test"]["case_ids"] = list(release["training"]["case_ids"]) + elif mutation == "budget": + release["data_budget"]["max_bytes"] *= 2 + elif mutation == "totals": + release["files"]["bytes"] += 1 + else: + release["release_id"] = "hydrogym-public-resources-v1" + with self.subTest(mutation=mutation), tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / "release.json" + path.write_text(json.dumps(release)) + with self.assertRaises(ValueError): + public.load_release(path) + + def test_default_plan_is_only_the_frozen_resource_set(self): + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / "not-created" + result = subprocess.run([sys.executable, str(DATA / "materialize.py"), str(path), + "--release", str(DATA / "release-500gb-v1.json")], + check=True, capture_output=True, text=True) + plan = json.loads(result.stdout) + self.assertEqual(plan["directories"], self.release["training"]["case_ids"]) + self.assertEqual(plan["bytes"], 488770756805) + self.assertTrue(plan["complete_release_selection"]) + self.assertFalse(path.exists()) + diagnostic = subprocess.run([sys.executable, str(DATA / "materialize.py"), str(path), + "--release", str(DATA / "release-500gb-v1.json"), + "--case", "Cylinder_2D_Re200"], check=True, capture_output=True, text=True) + self.assertFalse(json.loads(diagnostic.stdout)["complete_release_selection"]) + + def materialization_fixture(self, root): + source = root / "archive" + source.mkdir() + payload = b"synthetic source bytes, not CFD" + file = source / "environments/fixture/input" + file.parent.mkdir(parents=True) + file.write_bytes(payload) + (source / "environments/excluded").mkdir() + (source / "environments/excluded/private-research").write_text("not part of the release") + index = {"repo_id": "dynamicslab/HydroGym-environments", "revision": public.REVISION, + "files": [{"rfilename": "fixture/input", "size": len(payload), + "blobId": hashlib.sha1(f"blob {len(payload)}\0".encode() + payload).hexdigest()}]} + catalog = {"repo_id": index["repo_id"], "revision": public.REVISION, + "directories": [{"name": "fixture", "bytes": len(payload)}]} + config = root / "config" + config.mkdir() + (config / "catalog.json").write_text(json.dumps(catalog)) + (config / "source-files.json").write_text(json.dumps(index)) + release = {"release_id": public.RELEASE_ID, "source_index_sha256": public.digest(index), + "training": {"case_ids": ["fixture"]}} + return source, config / "catalog.json", release + + def test_local_reuse_is_selected_portable_and_hash_verified(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + source, catalog, release = self.materialization_fixture(root) + target = root / "release" + argv = ["materialize", str(target), "--from-local", str(source)] + with patch.object(materialize, "CATALOG", catalog), patch.object(public, "load_release", return_value=release), \ + patch.object(sys, "argv", argv), patch.object(materialize.subprocess, "run", side_effect=AssertionError("No download")), \ + redirect_stdout(io.StringIO()): + materialize.main() + file = target / "environments/fixture/input" + self.assertFalse(file.is_symlink()) + self.assertTrue(file.samefile(source / "environments/fixture/input")) + self.assertFalse((target / "environments/excluded").exists()) + receipt = json.loads((target / "materialized.json").read_text()) + self.assertEqual(receipt["data_release_sha256"], public.digest(release)) + self.assertFalse(receipt["benchmark_validated"]) + self.assertFalse((target / "suite.json").exists()) + + def test_corrupt_local_input_cannot_publish_a_receipt(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + source, catalog, release = self.materialization_fixture(root) + file = source / "environments/fixture/input" + file.write_bytes(b"x" * file.stat().st_size) + target = root / "release" + with patch.object(materialize, "CATALOG", catalog), patch.object(public, "load_release", return_value=release), \ + patch.object(sys, "argv", ["materialize", str(target), "--from-local", str(source)]), \ + redirect_stdout(io.StringIO()), self.assertRaisesRegex(ValueError, "checksum"): + materialize.main() + self.assertFalse((target / "release.json").exists()) + self.assertFalse((target / "materialized.json").exists()) + + def test_old_release_root_cannot_be_relabelled(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + source, catalog, release = self.materialization_fixture(root) + prior = json.dumps({"release_id": "hydrogym-public-resources-v1"}) + (source / "release.json").write_text(prior) + old_receipt = json.dumps({"data_release_id": "hydrogym-public-resources-v1"}) + (source / "materialized.json").write_text(old_receipt) + with patch.object(materialize, "CATALOG", catalog), patch.object(public, "load_release", return_value=release), \ + patch.object(sys, "argv", ["materialize", str(source), "--verify-only"]), \ + redirect_stdout(io.StringIO()), self.assertRaisesRegex(ValueError, "another release"): + materialize.main() + self.assertEqual((source / "release.json").read_text(), prior) + self.assertEqual((source / "materialized.json").read_text(), old_receipt) + + def test_verification_preserves_unrelated_verified_archive_entries(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + source, catalog, release = self.materialization_fixture(root) + (source / "materialized.json").write_text(json.dumps({"revision": public.REVISION, + "verified_directories": ["prior-entry"]})) + with patch.object(materialize, "CATALOG", catalog), patch.object(public, "load_release", return_value=release), \ + patch.object(sys, "argv", ["materialize", str(source), "--verify-only"]), redirect_stdout(io.StringIO()): + materialize.main() + receipt = json.loads((source / "materialized.json").read_text()) + self.assertEqual(receipt["verified_directories"], ["fixture", "prior-entry"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/cf/cf8397a94ad2a13f1c2de01fbd12b7dfe31bff95c9c56dc9a68cf9ac7eab85df/test_alphaqubit_model.py b/reproduction/files/cf/cf8397a94ad2a13f1c2de01fbd12b7dfe31bff95c9c56dc9a68cf9ac7eab85df/test_alphaqubit_model.py new file mode 100644 index 0000000000000000000000000000000000000000..0e3e9543cc3001d8e6fa61e61b99c51697adbe7d --- /dev/null +++ b/reproduction/files/cf/cf8397a94ad2a13f1c2de01fbd12b7dfe31bff95c9c56dc9a68cf9ac7eab85df/test_alphaqubit_model.py @@ -0,0 +1,189 @@ +"""Small CPU checks of AlphaQubit's mathematical and temporal contracts. + +Run with JAX_PLATFORMS=cpu and a bounded CPU affinity. These validate the +independent implementation, not equivalence to unavailable official weights. +""" +from __future__ import annotations + +from dataclasses import replace +from pathlib import Path + +import haiku as hk +import jax +import jax.numpy as jnp +import numpy as np +import pytest + +from baselines.alphaqubit_model import ( + AlphaQubitConfig, + SyndromeTransformer, + event_indicators, + loss_terms, + perpendicular_pool, + scatter_grid, + transformed_model, +) + + +POSITIONS = np.array([[0, 1], [1, 1], [1, 2], [1, 3], + [2, 0], [2, 1], [2, 2], [3, 2]]) +GEOMETRY = {"stabilizer_positions": POSITIONS, + "stabilizer_types": np.sum(POSITIONS, axis=1) % 2, + "logical_axis": 0, "logical_index": 0} + + +def small_config(dtype: str = "float32") -> AlphaQubitConfig: + return AlphaQubitConfig(3, width=4, heads=1, key_size=2, value_size=2, + layers=1, conv_width=2, widening=2, + feature_layers=1, bias_width=2, bias_layers=1, + readout_width=2, readout_layers=1, dtype=dtype) + + +def sample_features(rounds: int = 3) -> dict[str, jax.Array]: + random = np.random.default_rng(73) + values = random.integers(0, 2, size=(2, rounds + 1, 8)).astype(np.float32) + previous_measurements = np.concatenate((np.zeros_like(values[:, :1]), values[:, :-1]), axis=1) + events = np.abs(values - previous_measurements) + previous_events = np.concatenate((np.zeros_like(events[:, :1]), events[:, :-1]), axis=1) + valid = np.ones((rounds + 1, 8), dtype=bool) + valid[-1, ::2] = False + final = np.zeros(rounds + 1, dtype=bool) + final[-1] = True + return {key: jnp.asarray(value) for key, value in { + "measurements": values, "events": events, + "previous_events": previous_events, + "valid_mask": valid, "is_final": final, + }.items()} + + +def test_spatial_scatter_and_perpendicular_pool_keep_coordinate_convention() -> None: + values = jnp.arange(2 * 3 * 8 * 2).reshape(2, 3, 8, 2) + grid = scatter_grid(values, POSITIONS, 3) + np.testing.assert_array_equal(grid[..., POSITIONS[:, 0], POSITIONS[:, 1], :], values) + assert grid.shape == (2, 3, 4, 4, 2) + np.testing.assert_array_equal(grid[..., 0, 0, :], 0) + # A horizontal logical row has fixed axis 0. Perpendicular pooling averages + # rows; retaining rows would instead pool along the observable. + data = jnp.array([[0., 1., 2.], [10., 11., 12.], [20., 21., 22.]])[None, ..., None] + np.testing.assert_array_equal(perpendicular_pool(data, 0)[0, :, 0], [10., 11., 12.]) + np.testing.assert_array_equal(perpendicular_pool(data, 1)[0, :, 0], [1., 11., 21.]) + + +def test_indicator_features_preserve_directed_time_space_pairs() -> None: + current = jnp.array([[1., 0., 1.]]) + previous = jnp.array([[0., 1., 1.]]) + result = np.asarray(event_indicators(current, previous))[0] + np.testing.assert_array_equal(result[0, 1], [0, 1, 0, 0, 0, 0, 0]) + np.testing.assert_array_equal(result[1, 0], [0, 0, 1, 0, 0, 0, 0]) + np.testing.assert_array_equal(result[2, 2], np.ones(7)) + np.testing.assert_array_equal(result[0, 0], [1, 0, 0, 0, 1, 0, 0]) + + +def test_attention_matches_supplement_scaled_bias_formula() -> None: + config = replace(small_config(), width=8, heads=2, key_size=3, value_size=2, + conv_width=4, bias_width=4) + random = np.random.default_rng(912) + x = random.normal(size=(2, 8, 8)).astype(np.float32) + fixed = random.normal(size=(8, 8, 4)).astype(np.float32) + dynamic = random.normal(size=(2, 8, 8, 7)).astype(np.float32) + model = hk.without_apply_rng(hk.transform( + lambda value, bias, events: SyndromeTransformer(config, POSITIONS, "block")(value, bias, events))) + params = hk.data_structures.to_mutable_dict(model.init(jax.random.PRNGKey(12), x, fixed, dynamic)) + # Remove later residual contributions to observe exactly attention + input. + for module in params: + if module == "block/dense_down" or module.startswith("block/conv_project_"): + params[module] = {name: jnp.zeros_like(value) for name, value in params[module].items()} + # This formula check compares against NumPy FP32 products. GPU defaults + # may use TF32, whose reduced input precision can exceed these tolerances. + with jax.default_matmul_precision("highest"): + actual = np.asarray(model.apply(params, x, fixed, dynamic)) + p = {module: {name: np.asarray(value) for name, value in fields.items()} + for module, fields in params.items()} + normalized = (x - x.mean(-1, keepdims=True)) / np.sqrt(x.var(-1, keepdims=True) + config.layer_norm_epsilon) + normalized = normalized * p["block/attention_norm"]["scale"] + p["block/attention_norm"]["offset"] + + def linear(value: np.ndarray, name: str) -> np.ndarray: + fields = p[f"block/{name}"] + return value @ fields["w"] + fields.get("b", 0.) + + query = linear(normalized, "query").reshape(2, 8, 2, 3) + key = linear(normalized, "key").reshape(2, 8, 2, 3) + value = linear(normalized, "value").reshape(2, 8, 2, 2) + projected_bias = linear(fixed, "fixed_bias_projection")[None] + linear(dynamic, "event_bias_projection") + scores = (np.einsum("bihk,bjhk->bhij", query, key) + np.moveaxis(projected_bias, -1, 1)) / np.sqrt(3.) + weights = np.exp(scores - scores.max(-1, keepdims=True)) + weights /= weights.sum(-1, keepdims=True) + expected = x + linear(np.einsum("bhij,bjhv->bihv", weights, value).reshape(2, 8, 4), "attention_output") + np.testing.assert_allclose(actual, expected, rtol=3e-5, atol=3e-6) + + +def test_next_stabilizer_predictions_are_causal_and_terminal_values_are_masked() -> None: + features = sample_features() + model = transformed_model(small_config(), GEOMETRY) + params = model.init(jax.random.PRNGKey(5), features) + original = model.apply(params, features) + changed = dict(features) + for name in ("measurements", "events", "previous_events"): + changed[name] = features[name].at[:, 2:, :].set(1 - features[name][:, 2:, :]) + future_changed = model.apply(params, changed) + np.testing.assert_array_equal(original["next_stabilizer_logits"][:, :2], + future_changed["next_stabilizer_logits"][:, :2]) + # Running just the bulk prefix must use the same recurrent parameters and + # state update, regardless of a later terminal readout branch. + prefix = {key: value[:2] if key in ("valid_mask", "is_final") else value[:, :2] + for key, value in features.items()} + prefix_output = model.apply(params, prefix) + np.testing.assert_allclose(original["next_stabilizer_logits"][:, :2], + prefix_output["next_stabilizer_logits"], rtol=1e-6, atol=1e-6) + # Off-basis final measurement values are undefined. Their arbitrary storage + # content must never influence the output through the feature embedding. + masked = dict(features) + masked["measurements"] = features["measurements"].at[:, -1, ::2].set(99.) + masked_output = model.apply(params, masked) + np.testing.assert_array_equal(original["logits"], masked_output["logits"]) + + +@pytest.mark.parametrize("dtype", ["float32", "bfloat16"]) +def test_finite_training_gradients_float32_master_parameters_and_leaf_replay(dtype: str, tmp_path: Path) -> None: + features = sample_features(rounds=2) + model = transformed_model(small_config(dtype), GEOMETRY) + params = model.init(jax.random.PRNGKey(10), features) + leaves, structure = jax.tree_util.tree_flatten(params) + assert {value.dtype for value in leaves} == {jnp.dtype("float32")} + labels = jnp.array([0., 1.]) + objective = lambda candidate: loss_terms(model.apply(candidate, features), features, labels)[0] + loss, gradients = jax.jit(jax.value_and_grad(objective))(params) + assert np.isfinite(loss) + grad_leaves = jax.tree_util.tree_leaves(gradients) + assert all(np.isfinite(value).all() for value in grad_leaves) + assert sum(float(jnp.sum(value * value)) for value in grad_leaves) > 0 + # Real float32 master updates survive even when compute activations use + # bf16. The file below is a trusted test artifact, not the campaign format. + updated = jax.tree_util.tree_map(lambda weight, grad: weight - 1e-4 * grad, params, gradients) + updated_leaves = jax.tree_util.tree_leaves(updated) + assert any(not np.array_equal(before, after) for before, after in zip(leaves, updated_leaves)) + checkpoint = tmp_path / "parameters.npz" + np.savez(checkpoint, **{str(i): np.asarray(value) for i, value in enumerate(updated_leaves)}) + with np.load(checkpoint, allow_pickle=False) as saved: + restored = jax.tree_util.tree_unflatten(structure, [jnp.asarray(saved[str(i)]) for i in range(len(leaves))]) + for name, expected in model.apply(updated, features).items(): + actual = model.apply(restored, features)[name] + assert np.isfinite(actual).all() + np.testing.assert_array_equal(actual, expected) + + +def test_auxiliary_loss_uses_only_next_bulk_measurements() -> None: + features = sample_features(rounds=2) + output = {"logits": jnp.zeros(2), "next_stabilizer_logits": jnp.zeros((2, 3, 8))} + labels = jnp.array([0., 1.]) + _, metrics = loss_terms(output, features, labels) + assert float(metrics["aux_loss"]) == pytest.approx(np.log(2.)) + changed = dict(features) + changed["measurements"] = features["measurements"].at[:, -1].set(99.) + _, changed_metrics = loss_terms(output, changed, labels) + assert float(changed_metrics["aux_loss"]) == float(metrics["aux_loss"]) + one_round = sample_features(rounds=1) + output["next_stabilizer_logits"] = jnp.zeros((2, 2, 8)) + total, metrics = loss_terms(output, one_round, labels) + assert np.isfinite(total) + assert float(metrics["aux_loss"]) == 0. diff --git a/reproduction/files/d0/d013383382b7f6be72a0f19f3bf40c288d0392ded98b61a816cbd94de46fd85a/test_task.py b/reproduction/files/d0/d013383382b7f6be72a0f19f3bf40c288d0392ded98b61a816cbd94de46fd85a/test_task.py new file mode 100644 index 0000000000000000000000000000000000000000..d627549bfb55287614a3d981a3f397e1d98b615f --- /dev/null +++ b/reproduction/files/d0/d013383382b7f6be72a0f19f3bf40c288d0392ded98b61a816cbd94de46fd85a/test_task.py @@ -0,0 +1,745 @@ +"""Interface and metric tests for the protein-design task. + +These use synthetic all-atom structures and a stubbed designability scorer. They +validate the contract, the harness manifest, the geometry and conditioning gates, and +the per-track pass-rate accounting. They do NOT establish a benchmark result and do not +exercise real LigandMPNN or RoseTTAFold3 weights. +""" + +import json +import shutil +import tempfile +import threading +import unittest +import zlib +from pathlib import Path + +import numpy as np + +import grader +from common import (CLASH_MIN, HARNESS_SCHEMA, HOTSPOT_CONTACT_MAX, LIGAND_CLASH_MIN, + LIGAND_CONTACT_MAX, MOTIF_RMSD_MAX, TRACKS, sha256, + validate_harness, validate_input, write_json) +from pipeline import ScorerUnavailable +from geometry import (backbone_aligned_motif_rmsd, minimum_distance, present_atoms, + write_allatom_pdb) +from residues import ATOM14, ATOM14_WIDTH + +MOTIF_RESIDUES = ["SER", "HIS", "ASP"] +# A catalytic triad is scattered along the sequence, not consecutive. Using adjacent +# residues would make the motif trivially reproducible: any three consecutive residues +# of an ideal helix superimpose on any other three. +MOTIF_POSITIONS = (3, 15, 27) + + +def stable_seed(text, offset=0): + """Deterministic across processes; Python's str hash is salted per interpreter.""" + return zlib.crc32(text.encode()) % 9973 + offset + + +def build_structure(trace, restypes=None): + """Turn a CA trace into atom14 coords + mask with plausible sidechain placement. + + CB comes from the standard tetrahedral construction on N, CA, C, which is always + well defined; remaining sidechain atoms sit on a small circle around CB. Projecting + "outward from the chain centroid" instead degenerates near the chain ends, where + that direction is nearly parallel to the chain, and folds sidechains into the + backbone. + """ + length = trace.shape[0] + restypes = list(restypes) if restypes else ["GLY"] * length + coordinates = np.zeros((length, ATOM14_WIDTH, 3)) + mask = np.zeros((length, ATOM14_WIDTH), dtype=bool) + for index in range(length): + alpha = trace[index] + forward = trace[min(index + 1, length - 1)] - trace[max(index - 1, 0)] + forward = forward / (np.linalg.norm(forward) + 1e-9) + helper = np.array([0.0, 0.0, 1.0]) + if abs(forward @ helper) > 0.9: + helper = np.array([1.0, 0.0, 0.0]) + side = np.cross(forward, helper) + side /= np.linalg.norm(side) + 1e-9 + nitrogen = alpha - 1.20 * forward + 0.50 * side + carbon = alpha + 1.20 * forward + 0.50 * side + coordinates[index, 0] = nitrogen + coordinates[index, 1] = alpha + coordinates[index, 2] = carbon + coordinates[index, 3] = carbon + 0.30 * forward + 1.05 * side + mask[index, :4] = True + + atoms = ATOM14[restypes[index]] + if len(atoms) <= 4: + continue + b = alpha - nitrogen + c = carbon - alpha + a = np.cross(b, c) + beta = -0.58273431 * a + 0.56802827 * b - 0.54067466 * c + alpha + coordinates[index, 4] = beta + mask[index, 4] = True + outward = beta - alpha + outward /= np.linalg.norm(outward) + 1e-9 + perpendicular = np.cross(outward, forward) + perpendicular /= np.linalg.norm(perpendicular) + 1e-9 + second = np.cross(outward, perpendicular) + for slot in range(5, len(atoms)): + angle = 2 * np.pi * (slot - 5) / max(1, len(atoms) - 5) + coordinates[index, slot] = (beta + 0.9 * outward + + 1.1 * (np.cos(angle) * perpendicular + + np.sin(angle) * second)) + mask[index, slot] = True + return coordinates, mask, restypes + + +def helix(length, origin=(0.0, 0.0, 0.0), seed=0): + """CA trace of an ideal alpha helix with exact 3.80 A spacing.""" + trace = np.zeros((length, 3)) + for index in range(length): + angle = index * 100.0 * np.pi / 180.0 + trace[index] = [2.3 * np.cos(angle), 2.3 * np.sin(angle), index * 1.5] + trace *= 3.80 / np.linalg.norm(trace[1] - trace[0]) + rotation, _ = np.linalg.qr(np.random.default_rng(seed).normal(size=(3, 3))) + if np.linalg.det(rotation) < 0: + rotation[:, 0] *= -1 + return trace @ rotation.T + np.asarray(origin) + + +def random_compact_chain(length, seed=0): + """Self-avoiding chain at exact 3.80 A spacing; distinct seeds give distinct folds.""" + rng = np.random.default_rng(seed) + trace = [np.zeros(3), np.array([3.80, 0.0, 0.0])] + while len(trace) < length: + current = trace[-1] + inward = -current / (np.linalg.norm(current) + 1e-9) + previous = current - trace[-2] + previous /= np.linalg.norm(previous) + 1e-9 + for _ in range(400): + step = rng.normal(size=3) + step /= np.linalg.norm(step) + step = 0.45 * previous + 0.35 * inward + 0.60 * step + step /= np.linalg.norm(step) + candidate = current + 3.80 * step + # 6.5 A between non-adjacent CA keeps their backbone O atoms, which sit + # roughly 1.9 A off the CA, clear of the 2.0 A all-atom clash threshold. + if all(np.linalg.norm(candidate - point) >= 6.5 for point in trace[:-2]): + trace.append(candidate) + break + else: + return random_compact_chain(length, seed + 1000) + return np.asarray(trace) + + +def bridge_designs(length, scale=1.5, seed=3): + """Three structures whose greedy cluster count depends on the order they are seen in. + + B and C are opposite displacements of the same chain, so each is within + DIVERSITY_RMSD of A while being about twice that far from each other. Seeing A first + absorbs both (1 cluster); seeing B first makes C a second centre and then absorbs A + (2 clusters). Returned A-first so a caller cycling through them exercises both. + """ + base = random_compact_chain(length, seed=seed) + offset = np.random.default_rng(seed + 100).normal(size=base.shape) + offset /= np.sqrt((offset ** 2).sum(axis=1).mean()) # unit mean-square displacement + return [build_structure(trace) for trace in + (base, base + scale * offset, base - scale * offset)] + + +def dock_near_hotspots(structure, target, target_mask, hotspots): + """Translate a binder so it contacts hotspots without clashing into the target.""" + coordinates, mask, restypes = structure + target_atoms = target[target_mask] + centre_hot = target[list(hotspots)][target_mask[list(hotspots)]].mean(axis=0) + primary = centre_hot - target_atoms.mean(axis=0) + primary /= np.linalg.norm(primary) + 1e-9 + rng = np.random.default_rng(0) + centre = coordinates[:, 1].mean(axis=0) + for direction in [primary] + [primary + 0.55 * rng.normal(size=3) for _ in range(24)]: + direction = direction / (np.linalg.norm(direction) + 1e-9) + for distance in np.arange(5.0, 34.0, 0.25): + moved = coordinates - centre + centre_hot + direction * distance + atoms = moved[mask] + if minimum_distance(atoms, target_atoms) < 2.4: + continue + touched = sum(minimum_distance(atoms, target[i][target_mask[i]]) <= 5.0 + for i in hotspots) + if touched / len(hotspots) >= 0.5: + return (moved, mask, restypes) + raise AssertionError("fixture could not dock a binder against the hotspots") + + +class StubScorer: + """Deterministic stand-in for LigandMPNN + RoseTTAFold3. + + Passing `passed=` pins the verdict, for tests about pass-rate accounting rather than + about the criterion. + + The default models what the PREDICTOR would say, geometrically. Every published + criterion is a statement about a refolded complex - motif recapitulation, + backbone-aligned ligand RMSD, ipTM, interface min PAE - and they share one + consequence: a design that cannot fold to itself, or that does not engage the + conditioning it was given, cannot satisfy them. `grader.score_track` deliberately + adds no gate of its own, so these belong here, standing in for the predictor. A stub + that returned `passed` unconditionally would report every degenerate submission as + designable, and the anti-degeneracy tests below would prove nothing about the task. + """ + + # Non-adjacent CA atoms do not come this close in a real fold, so a design that + # violates it would never be refolded into itself. Stands in for sc_RMSD. Chosen + # below the ~5.0 A i/i+3 spacing of an ideal helix so the fixtures remain valid. + MIN_CA_SEPARATION = 4.0 + + def __init__(self, passed=None, sc_rmsd=1.0, iptm=0.9, interface_pae=1.0, + ligand_rmsd=2.0, motif_rmsd=0.8, devices=(None,)): + # `devices` is how many designs grader.fold_designs scores at once, mirroring + # DesignabilityScorer.devices. + self.devices = list(devices) + self._lock = threading.Lock() + self.pinned = passed + self.verdict = {"passed": True, "sc_rmsd": sc_rmsd, "iptm": iptm, + "interface_pae": interface_pae, "ligand_rmsd": ligand_rmsd, + "motif_rmsd": motif_rmsd, "sequences_tried": 1, "reason": None} + self.calls = 0 + + def evaluate(self, track, structure, context, motif_map=None): + with self._lock: + self.calls += 1 + verdict = dict(self.verdict) + if self.pinned is not None: + verdict["passed"] = self.pinned + verdict["reason"] = None if self.pinned else "stubbed failure" + return verdict + reason = self._would_refold(structure) or self._engages( + track, structure, context, motif_map, verdict) + verdict["passed"] = reason is None + verdict["reason"] = reason + return verdict + + def _would_refold(self, structure): + """sc_RMSD stand-in: self-intersecting or non-globular chains do not refold.""" + alpha = structure[0][:, 1] + length = alpha.shape[0] + separations = np.linalg.norm(alpha[:, None, :] - alpha[None, :, :], axis=-1) + indices = np.arange(length) + far = np.abs(indices[:, None] - indices[None, :]) > 2 + if far.any() and separations[far].min() < self.MIN_CA_SEPARATION: + return f"sc_RMSD: chain self-intersects at {separations[far].min():.2f} A" + radius = float(np.sqrt(((alpha - alpha.mean(axis=0)) ** 2).sum(axis=1).mean())) + if radius > 3.0 * (2.2 * length ** 0.38): + return f"sc_RMSD: radius of gyration {radius:.1f} A is not globular" + return None + + def _engages(self, track, structure, context, motif_map, verdict): + """The conditioning half: motif recapitulation, ligand RMSD, ipTM and PAE.""" + coordinates, mask, restypes = structure + atoms = present_atoms(coordinates, mask) + if track == "enzyme": + motif_mask = context["motif_mask"].astype(bool) + verdict["motif_rmsd"] = backbone_aligned_motif_rmsd( + coordinates[list(motif_map)], mask[list(motif_map)], + context["motif_coords"], motif_mask, + [str(name) for name in context["motif_restypes"]]) + if verdict["motif_rmsd"] > MOTIF_RMSD_MAX: + return f"motif recapitulation {verdict['motif_rmsd']:.2f} A" + if track in ("enzyme", "sm_binder"): + ligand = context["ligand_coords"] + separation = minimum_distance(atoms, ligand) + if separation < LIGAND_CLASH_MIN: + return f"ligand RMSD: design overlaps the ligand at {separation:.2f} A" + if separation > LIGAND_CONTACT_MAX: + return f"ipTM: nearest ligand atom is {separation:.2f} A away" + if track == "ppi_binder": + target_mask = context["target_mask"].astype(bool) + target = context["target_coords"] + separation = minimum_distance(atoms, target[target_mask]) + if separation < CLASH_MIN: + return f"interface PAE: binder overlaps the target at {separation:.2f} A" + contacted = sum( + minimum_distance(atoms, target[index][target_mask[index]]) + <= HOTSPOT_CONTACT_MAX + for index in (int(v) for v in context["hotspot_indices"].ravel())) + if not contacted: + return "interface PAE: binder contacts no hotspot" + return None + + +class Fixture: + """Builds a tiny four-track evaluation view plus a matching submission.""" + + LENGTH = 32 + DESIGNS = 4 + MOTIF = len(MOTIF_RESIDUES) + + def __init__(self, root): + self.root = Path(root) + self.input = self.root / "input" + self.snapshot = self.root / "snapshot" + (self.input / "contexts").mkdir(parents=True) + (self.snapshot / "structures").mkdir(parents=True) + self.reference = build_structure(helix(self.LENGTH, seed=1), + self.residue_types()) + self._write_input() + + @classmethod + def residue_types(cls, positions=MOTIF_POSITIONS): + types = ["GLY"] * cls.LENGTH + for slot, position in enumerate(positions): + types[position] = MOTIF_RESIDUES[slot] + return types + + def _context(self, track, example_id): + path = self.input / "contexts" / f"{track}_{example_id}.npz" + coordinates, mask, restypes = self.reference + arrays = {"design_length": np.array([self.LENGTH])} + # Seat the ligand against the reference surface: close enough to be engaged, + # far enough not to clash. A ligand parked outside the bounding sphere would + # fail the burial gate, which is exactly what that gate exists to catch. + atoms = coordinates[mask] + centre = atoms.mean(axis=0) + middle = coordinates[self.LENGTH // 2, 1] + outward = middle - centre + outward = outward / (np.linalg.norm(outward) + 1e-9) + seat = middle + outward * 4.2 + ligand = np.stack([seat, seat + outward * 0.9, seat + np.roll(outward, 1) * 0.9]) + if track == "enzyme": + # An enzyme target is a catalytic motif plus its ligand. + selection = list(MOTIF_POSITIONS) + arrays["motif_coords"] = coordinates[selection] + arrays["motif_mask"] = mask[selection] + arrays["motif_restypes"] = np.array([restypes[i] for i in selection], dtype=" 0 if comparable else None, + } + + +def _mces(pair): + truth, prediction = pair + if truth == prediction: + return 0.0 + import pulp + from myopic_mces.myopic_mces import MCES + if not pulp.PULP_CBC_CMD(msg=False).available(): + raise RuntimeError("Pulp's bundled CBC solver is not available") + return float(MCES( + s1=truth, + s2=prediction, + ind=0, + threshold=15, + always_stronger_bound=True, + solver="PULP_CBC_CMD", + solver_options={"msg": 0}, + )[1]) + + +def load_labels(path: Path, expected_queries: set[str]): + labels = {} + for row in jsonl(path): + if set(row) != {"query_id", "correct_candidate_id", "true_smiles"}: + raise ValueError("invalid private label fields") + query_id = row["query_id"] + if query_id not in expected_queries or query_id in labels: + raise ValueError("unknown or duplicate private label") + if not isinstance(row["correct_candidate_id"], str) or not isinstance(row["true_smiles"], str): + raise ValueError("invalid private label types") + labels[query_id] = row + if set(labels) != expected_queries: + raise ValueError("private labels do not cover all input queries") + return labels + + +def load_rankings(path: Path, queries: dict, pools: dict): + rankings, global_error = {}, None + try: + for row in jsonl(path): + if set(row) != {"query_id", "ranking"}: + raise ValueError("invalid ranking fields") + query_id = row["query_id"] + if not isinstance(query_id, str) or query_id not in queries or query_id in rankings: + raise ValueError("unknown or duplicate query ranking") + expected = set(pools[queries[query_id]["candidate_pool_id"]]) + ranking = row["ranking"] + if ( + not isinstance(ranking, list) + or any(not isinstance(value, str) for value in ranking) + or len(ranking) != len(expected) + or set(ranking) != expected + ): + raise ValueError("ranking is not an exact candidate permutation") + rankings[query_id] = ranking + except (OSError, ValueError, json.JSONDecodeError) as error: + rankings, global_error = {}, str(error) + return rankings, global_error + + +def score(rankings, queries, pools, labels, compute_mces=True, workers=None): + count = len(queries) + metrics = { + f"hit_rate_at_{k}": sum( + query_id in rankings + and labels[query_id]["correct_candidate_id"] in rankings[query_id][:k] + for query_id in queries + ) / count + for k in (1, 5, 20) + } + mces_values = [] + if compute_mces: + pair_indexes = {} + for query_id, query in queries.items(): + if query_id not in rankings: + mces_values.append(100.0) + continue + predicted_id = rankings[query_id][0] + predicted_smiles = pools[query["candidate_pool_id"]][predicted_id] + pair = (labels[query_id]["true_smiles"], predicted_smiles) + pair_indexes.setdefault(pair, []).append(len(mces_values)) + mces_values.append(None) + worker_count = workers or min(16, os.cpu_count() or 1) + if pair_indexes: + with ProcessPoolExecutor(max_workers=worker_count) as executor: + values = executor.map(_mces, pair_indexes, chunksize=16) + for indexes, value in zip(pair_indexes.values(), values): + for index in indexes: + mces_values[index] = value + metrics["mces_at_1"] = sum(mces_values) / count + return metrics + + +def run(args, compute_mces=True): + ready = args.sealed.parent / "READY" + deadline = time.monotonic() + args.wait_seconds + while not ready.is_file(): + if time.monotonic() >= deadline: + raise TimeoutError("ranking snapshot was not published") + time.sleep(1) + snapshot_path = args.sealed / "snapshot.json" + if ready.read_text().strip() != sha256(snapshot_path): + raise ValueError("snapshot ready hash mismatch") + snapshot = json.loads(snapshot_path.read_text()) + if snapshot.get("schema") != "massspecgym-retrieval-ranking-snapshot/v1": + raise ValueError("invalid snapshot schema") + if snapshot.get("input_manifest_sha256") != sha256(args.input / "manifest.json"): + raise ValueError("snapshot/input mismatch") + for name, expected_hash in snapshot.get("files", {}).items(): + path = args.sealed / name + if not path.is_file() or path.is_symlink() or sha256(path) != expected_hash: + raise ValueError(f"sealed output hash mismatch: {name}") + + input_manifest, queries, pools = validate_input(args.input) + private_manifest = json.loads((args.labels / "manifest.json").read_text()) + if private_manifest.get("schema") != "massspecgym-retrieval-private-labels/v1": + raise ValueError("invalid private manifest schema") + if private_manifest.get("files", {}).get("labels.jsonl") != sha256(args.labels / "labels.jsonl"): + raise ValueError("private label hash mismatch") + labels = load_labels(args.labels / "labels.jsonl", set(queries)) + ranking_path = args.sealed / "rankings.jsonl" + rankings, global_error = load_rankings(ranking_path, queries, pools) + if not ranking_path.is_file(): + global_error = "rankings.jsonl is missing" + metrics = score( + rankings, queries, pools, labels, + compute_mces=compute_mces, + workers=args.mces_workers, + ) + args.output.mkdir(parents=True, exist_ok=True) + report = { + "schema": "massspecgym-retrieval-report/v1", + "evaluation_mode": "isolated_model_replay", + "status": ("invalid_output" if global_error else + "complete" if len(rankings) == len(queries) else "missing_predictions"), + "model_quality_measured": global_error is None, + "queries": len(queries), + "valid_rankings": len(rankings), + "invalid_or_missing_rankings": len(queries) - len(rankings), + "global_error": global_error, + "metric_directions": { + "hit_rate_at_1": "maximize", + "hit_rate_at_5": "maximize", + "hit_rate_at_20": "maximize", + "mces_at_1": "minimize", + }, + "reference_comparison": reference_comparison(metrics, input_manifest), + "metrics": metrics, + "benchmark_score": normalize(metrics["hit_rate_at_1"]), + } + write_json(args.output / "report.json", report) + write_json(args.output / "reward.json", {"reward": metrics["hit_rate_at_1"]}) + return report + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--sealed", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--input", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--labels", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--output", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--wait-seconds", type=int, default=21600) + parser.add_argument("--mces-workers", type=int, default=16) + args = parser.parse_args() + try: + run(args) + except Exception as error: + args.output.mkdir(parents=True, exist_ok=True) + (args.output / "reward.json").unlink(missing_ok=True) + write_json(args.output / "error.json", { + "status": "infrastructure_error", + "error": f"{type(error).__name__}: {error}", + }) + raise + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/d2/d202745d1d08e62257b643d0e62beb958cc13e08bafdc2b18e66d0ff36945f1f/check_local_isolation.py b/reproduction/files/d2/d202745d1d08e62257b643d0e62beb958cc13e08bafdc2b18e66d0ff36945f1f/check_local_isolation.py new file mode 100644 index 0000000000000000000000000000000000000000..483b7d151d7699ffec679f8f41ccbcf937b11499 --- /dev/null +++ b/reproduction/files/d2/d202745d1d08e62257b643d0e62beb958cc13e08bafdc2b18e66d0ff36945f1f/check_local_isolation.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Exercise absent private paths, offline sockets and read-only replay mounts.""" + +import argparse +import hashlib +import json +from pathlib import Path +import subprocess +import sys + +from common import write_json + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--runtime', type=Path, required=True) + parser.add_argument('--input', type=Path, required=True, help='Small public validation view') + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + args.output = args.output.resolve() + args.output.mkdir(parents=True, exist_ok=False) + secret = args.output / 'organizer-private-canary' + secret.write_text('not visible to the submission\n') + package = args.output / 'submission' + package.mkdir() + (package / 'weights.pt').write_bytes(b'isolation probe only') + (package / 'config.json').write_text('{}') + (package / 'README.md').write_text('Kernel boundary probe, not a trained benchmark model.\n') + write_json(package / 'model_manifest.json', { + 'schema': 'massspecgym-retrieval-model/v1', + 'checkpoint': {'path': 'weights.pt', 'sha256': hashlib.sha256((package / 'weights.pt').read_bytes()).hexdigest(), 'format': 'pytorch'}, + 'model_config': 'config.json', 'training_provenance': {'data': 'isolation probe', 'pretrained_assets': []}, + }) + (package / 'infer.sh').write_text('#!/bin/bash\nexec python3 /submission/probe.py "$@"\n') + probe = '''import json, os, pathlib, socket, sys +input_root, output_root = map(pathlib.Path, sys.argv[1:]) +assert not pathlib.Path(PRIVATE_CANARY).exists(), 'private path exposed' +assert not pathlib.Path('/workspace/data/train.jsonl').exists(), 'training data exposed' +assert not pathlib.Path('/private').exists(), 'private mount exposed' +assert not pathlib.Path('/run').exists(), 'host runtime sockets exposed' +for root in [pathlib.Path('/submission'), input_root]: + try: + (root / 'write-probe').write_text('bad') + except OSError: + pass + else: + raise AssertionError('read-only mount is writable') +sock = socket.socket() +sock.settimeout(0.5) +try: + sock.connect(('198.51.100.1', 443)) +except OSError: + pass +else: + raise AssertionError('external network route available') +finally: + sock.close() +assert os.getuid() == 0 # mapped root only, with all capabilities dropped +status = pathlib.Path('/proc/self/status').read_text() +assert 'CapEff:\\t0000000000000000' in status +pools = {r['candidate_pool_id']: [c['candidate_id'] for c in r['candidates']] for r in map(json.loads, (input_root/'candidate_pools.jsonl').read_text().splitlines())} +with (output_root/'rankings.jsonl').open('w') as f: + for row in map(json.loads, (input_root/'queries.jsonl').read_text().splitlines()): + f.write(json.dumps({'query_id': row['query_id'], 'ranking': pools[row['candidate_pool_id']]})+'\\n') +print('private paths absent; mounts read-only; external route unavailable; effective capabilities empty') +''' + (package / 'probe.py').write_text('PRIVATE_CANARY = ' + repr(str(secret)) + '\n' + probe) + subprocess.run([sys.executable, str(Path(__file__).with_name('replay_local.py')), + '--runtime', str(args.runtime), '--input', str(args.input), + '--submission', str(package), '--output', str(args.output / 'replay'), '--timeout', '30'], check=True) + print((args.output / 'replay/inference.log').read_text()) + + +if __name__ == '__main__': + main() diff --git a/reproduction/files/d3/d3d200238c6fc401b2b09eaaf04c01620bf31dba17c15baa824c8b42a48e88fb/test_speed_release.py b/reproduction/files/d3/d3d200238c6fc401b2b09eaaf04c01620bf31dba17c15baa824c8b42a48e88fb/test_speed_release.py new file mode 100644 index 0000000000000000000000000000000000000000..255cb8849d216ec131b3d95b82446f8be20fccfe --- /dev/null +++ b/reproduction/files/d3/d3d200238c6fc401b2b09eaaf04c01620bf31dba17c15baa824c8b42a48e88fb/test_speed_release.py @@ -0,0 +1,119 @@ +"""Cost-aware membership tests; not native CFD/evaluator certification.""" +import copy +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import tomllib +import unittest + +DATA=Path(__file__).resolve().parents[1]/'environment/data' +sys.path.insert(0,str(DATA)) +import public_release as public +import speed_release as speed + + +class SpeedReleaseTests(unittest.TestCase): + def setUp(self): + self.selection=speed.read('selection-speed-v1.json') + self.evidence=speed.read('cost-evidence-speed-v1.json') + archive=DATA/'release-speed-v1.json' + self.release=public.load_release(archive) if archive.exists() else public.load_release() + + def test_reproducible_current_release_with_3d_and_exact_train_test(self): + self.assertEqual(self.release,speed.build(self.selection,self.evidence)) + self.assertEqual(self.release['release_id'],speed.RELEASE_ID) + ids=[c['id'] for c in self.release['cases']] + self.assertEqual(ids,self.release['training']['case_ids']) + self.assertEqual(ids,self.release['test']['case_ids']) + self.assertTrue({'Channel_3D_Retau180','Pinball_3D_Re150','Sphere_3D_Re300'}.issubset(ids)) + self.assertGreaterEqual(sum(c['dimension']==3 for c in self.release['cases']),6) + self.assertLessEqual(self.release['files']['bytes'],500_000_000_000) + self.assertTrue(self.release['test']['one_shared_checkpoint']) + self.assertFalse(self.release['test']['parameter_updates']) + self.assertFalse(self.release['test']['normalizer_updates']) + self.assertEqual(self.release['status'],'data-release-not-cfd-certified') + + def test_no_missing_slow_or_unmeasured_case_can_enter_silently(self): + for name in ['Sphere_3D_Re3700','DRA2303Jet_3D_Re400000_Ma02','not-a-resource']: + selection=copy.deepcopy(self.selection) + selection['case_ids']=sorted(set(selection['case_ids'])|{name}) + with self.subTest(name=name),self.assertRaises(ValueError): + speed.build(selection,self.evidence) + + def test_cost_source_and_budget_tampering_are_rejected(self): + evidence=copy.deepcopy(self.evidence) + evidence['cases'][0]['seconds_per_control']=0 + with self.assertRaisesRegex(ValueError,'evidence has changed'): + speed.build(self.selection,evidence) + selection=copy.deepcopy(self.selection) + selection['max_source_bytes']=1_000_000_000_000 + with self.assertRaisesRegex(ValueError,'budget'): + speed.build(selection,self.evidence) + + def test_incomplete_reset_and_sample_summary_are_rejected(self): + name=self.selection['case_ids'][0] + for field,value in [('reset_seconds',None),('container_exit_code',137), + ('timing_samples_seconds',[1])]: + evidence=copy.deepcopy(self.evidence) + next(r for r in evidence['cases'] if r['case']==name)[field]=value + selection=copy.deepcopy(self.selection) + selection['cost_evidence_sha256']=public.digest(evidence) + with self.subTest(field=field),self.assertRaises(ValueError): + speed.build(selection,evidence) + + def test_task_metadata_and_prompt_use_current_release(self): + task=DATA.parents[1] + config=tomllib.loads((task/'task.toml').read_text()) + current=public.load_release() + self.assertEqual(config['metadata']['data_release'],current['release_id']) + self.assertEqual(config['metadata']['data_budget_bytes'],500_000_000_000) + self.assertIn(current['release_id'],(task/'instruction.md').read_text()) + + def test_partial_suite_and_mutated_manifest_are_rejected(self): + suite={'data_release_id':self.release['release_id'], + 'data_release_sha256':public.digest(self.release), + 'cases':[{k:c[k] for k in ['id','environment','backend']} for c in self.release['cases']]} + public.validate_suite_binding(self.release,suite) + suite['cases'].pop() + with self.assertRaisesRegex(ValueError,'exact frozen'): + public.validate_suite_binding(self.release,suite) + with tempfile.TemporaryDirectory() as temporary: + changed=copy.deepcopy(self.release) + changed['test']['case_ids'].pop() + path=Path(temporary)/'release.json' + path.write_text(json.dumps(changed)) + with self.assertRaisesRegex(ValueError,'exact frozen'): + public.load_release(path) + + def test_default_materializer_plans_new_selection_and_legacy_remains_loadable(self): + with tempfile.TemporaryDirectory() as temporary: + destination=Path(temporary)/'not-created' + result=subprocess.run([sys.executable,str(DATA/'materialize.py'),str(destination)], + capture_output=True,text=True,check=True) + plan=json.loads(result.stdout) + current=public.load_release() + self.assertEqual(plan['directories'],current['test']['case_ids']) + self.assertEqual(plan['bytes'],current['files']['bytes']) + self.assertTrue(plan['complete_release_selection']) + self.assertFalse(destination.exists()) + old=public.load_release(DATA/'release-500gb-v1.json') + self.assertEqual(old['case_count'],47) + self.assertEqual(old['files']['bytes'],488770756805) + + def test_verifier_does_not_accept_old_release_as_new_benchmark(self): + sys.path.insert(0,str(DATA.parent/'evaluation')) + import evaluate + from protocol import InfrastructureError + with tempfile.TemporaryDirectory() as temporary: + root=Path(temporary) + old=public.load_release(DATA/'release-500gb-v1.json') + (root/'release.json').write_text(json.dumps(old)) + (root/'suite.json').write_text(json.dumps({'data_release_id':old['release_id']})) + with self.assertRaisesRegex(InfrastructureError,'verifier.*frozen selection'): + evaluate.preflight(root,require_reference=False) + + +if __name__=='__main__': + unittest.main() diff --git a/reproduction/files/d5/d5ff131205d3c351f4c9e9ab411235f84fa2426a5346adc3220051ee0d761dd0/sealed_adapter.py b/reproduction/files/d5/d5ff131205d3c351f4c9e9ab411235f84fa2426a5346adc3220051ee0d761dd0/sealed_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..e3f028baca8593d25a49be3c96b37dd84fae738a --- /dev/null +++ b/reproduction/files/d5/d5ff131205d3c351f4c9e9ab411235f84fa2426a5346adc3220051ee0d761dd0/sealed_adapter.py @@ -0,0 +1,259 @@ +"""Beaker orchestration for unchanged Disease/Earth numeric scorers. + +This is an adapted verifier, not the native Docker/Bubblewrap launcher. Scientific +task files are imported from a frozen source tree. Inference jobs contain no +trusted labels; scoring jobs execute only trusted code after inference exits. +""" +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import shutil +import stat +import subprocess +import sys +import time +import uuid + +import sealed_sandbox as sandbox + + +def write(path, value): + path = Path(path) + temporary = path.with_name(path.name + '.tmp') + temporary.write_text(json.dumps(value, indent=2) + '\n') + temporary.replace(path) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as stream: + for block in iter(lambda: stream.read(4 * 1024**2), b''): + h.update(block) + return h.hexdigest() + + +def freeze(source, target): + source, target = Path(source), Path(target) + for path in [source, *source.rglob('*')]: + info = path.lstat() + if not (stat.S_ISREG(info.st_mode) or stat.S_ISDIR(info.st_mode)): + raise ValueError(f'Nonordinary frozen input: {path}') + shutil.copytree(source, target) + for path in [target, *target.rglob('*')]: + os.chown(path, 0, 0) + path.chmod(0o555 if path.is_dir() or path.stat().st_mode & 0o111 else 0o444) + return target + + +def child_directory(path): + path.mkdir(mode=0o700) + os.chown(path, sandbox.UID, sandbox.UID) + return path + + +def ndp_infer(package, inputs, results, sealed, seconds, memory_bytes=22 * 1024**3): + from main_verifier import validate_submission, seal_prediction, invalid + results.mkdir(parents=True) + results.chmod(0o755) + sealed.parent.mkdir(parents=True, exist_ok=True) + sealed.parent.chmod(0o700) + if sealed.exists() or (sealed.parent / 'READY').exists(): + raise RuntimeError('Fresh sealed output required') + manifest = json.loads((inputs / 'manifest.json').read_text()) + if manifest.get('split') != 'test' or not (inputs / 'events.parquet').is_file(): + raise RuntimeError('Complete public test split required') + try: + validate_submission(package) + except (ValueError, OSError) as error: + invalid(results, 'invalid_submission', error) + return {'status': 'invalid_submission'} + run_id = uuid.uuid4().hex + work = results / f'inference-{run_id}' + work.mkdir(mode=0o755) + work.chmod(0o755) + model = freeze(package, work / 'submission') + output = child_directory(work / 'output') + scratch = child_directory(work / 'scratch') + env = dict(PATH='/opt/conda/bin:/usr/local/bin:/usr/bin:/bin', HOME=str(scratch), + TMPDIR=str(scratch), PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + PIP_NO_INDEX='1', HF_HUB_OFFLINE='1', CUDA_VISIBLE_DEVICES='0') + try: + resources = sandbox.run(['bash', str(model / 'infer.sh'), str(inputs), str(output)], + cwd=model, env=env, logfile=work / 'inference.log', cpus=10, + memory_bytes=memory_bytes, seconds=min(42000, seconds), + readonly=[model, inputs], writable=[output, scratch], file_limit=8 * 1024**3) + except subprocess.TimeoutExpired as error: + invalid(results, 'inference_timeout', error) + return {'status': 'inference_timeout'} + except subprocess.CalledProcessError as error: + invalid(results, 'inference_failed', error) + return {'status': 'inference_failed'} + try: + seal_prediction(output, sealed, inputs, run_id) + except ValueError as error: + invalid(results, 'invalid_prediction', error) + return {'status': 'invalid_prediction'} + return {'status': 'inference_complete', 'run_id': run_id, 'resources': resources} + + +def earth_infer(package, data, output, seconds, memory_bytes=32 * 1024**3): + import grade + from package_contract import InvalidSubmission, validate_package, validate_features + from namespace import direct + validate_package(package) + output.mkdir(parents=True) + output.chmod(0o755) + started = time.monotonic() + receipts = {} + for task in ('awf', 'lfmc'): + if {path.name for path in (data / task).iterdir()} != {'inputs.h5'}: + raise RuntimeError('Earth inference requires an inputs-only directory; labels must not be mounted') + task_output = output / task + task_output.mkdir(mode=0o755) + task_output.chmod(0o755) + work = task_output / 'replay' + work.mkdir(mode=0o755) + work.chmod(0o755) + target = child_directory(work / 'output') + scratch = child_directory(work / 'scratch') + argv, env = direct(package, data / task, target) + env.update(HOME=str(scratch), TMPDIR=str(scratch), HF_HUB_OFFLINE='1') + receipts[task] = sandbox.run(argv, cwd=package, env=env, + logfile=task_output / 'inference.log', cpus=4, memory_bytes=memory_bytes, + seconds=seconds - (time.monotonic() - started), + readonly=[package, data / task], writable=[target, scratch]) + candidate = target / 'features.npz' + validate_features(candidate, data / task / 'inputs.h5') + # Child processes are dead before ownership and hash validation. Copy to + # a root-owned file: subsequent scoring never trusts a candidate-owned inode. + final = task_output / 'features.npz' + with candidate.open('rb') as source, final.open('xb') as destination: + shutil.copyfileobj(source, destination) + final.chmod(0o444) + validate_features(final, data / task / 'inputs.h5') + shutil.rmtree(work) + task_output.chmod(0o700) + output.chmod(0o700) + manifest = {'schema_version': 1, 'phase': 'inference', + 'recorded_utc': datetime.now(timezone.utc).isoformat(), + 'slurm_job_id': None, 'slurm_partition': None, 'python_hash_seed': '0', + 'fingerprints': grade.fingerprints(package, data, output, Path('/evaluation/probes.py')), + 'labels_read': False, 'adapted_isolation': 'Beaker container + UID + Landlock + seccomp', + 'adapter_sha256': digest(__file__), 'sandbox_sha256': digest(sandbox.__file__)} + write(output / 'inference-manifest.json', manifest) + return {'status': 'inference_complete', 'resources': receipts} + + +def native_score(task, *, package, data, sealed, output, seconds, memory_bytes): + if task == 'ndp': + ready = json.loads((sealed.parent / 'READY').read_text()) + command = [sys.executable, '/tests/grader.py', '--input', str(data), + '--trusted', '/trusted/test', '--normalization', '/trusted/risk_normalization.parquet', + '--sealed', str(sealed), '--output', str(output), '--wait-seconds', '1'] + final = output / ready['run_id'] + else: + command = [sys.executable, '/tests/grade.py', '--model', str(package), + '--data', str(data), '--output', str(output), '--probes', '/evaluation/probes.py', + '--score-existing'] + final = output + env = {'PATH': os.environ['PATH'], 'HOME': '/tmp', 'PYTHONDONTWRITEBYTECODE': '1', + 'PYTHONUNBUFFERED': '1', 'CUDA_VISIBLE_DEVICES': '', 'HF_HUB_OFFLINE': '1', + 'PIP_NO_INDEX': '1', 'OMP_NUM_THREADS': '10' if task == 'ndp' else '4', + 'OPENBLAS_NUM_THREADS': '10' if task == 'ndp' else '4', 'PYTHONHASHSEED': '0'} + receipt = sandbox.run(command, cwd='/tmp', env=env, logfile=output.parent / 'scorer.log', + cpus=10 if task == 'ndp' else 4, memory_bytes=memory_bytes, seconds=seconds, + untrusted=False) + report = json.loads((final / 'report.json').read_text()) + if report.get('status') == 'infrastructure_error': + raise RuntimeError(f'Native scorer infrastructure error: {report}') + if not (final / 'reward.json').is_file(): + raise RuntimeError('Native scorer did not produce a reward') + return {'status': report['status'], 'resources': receipt, + 'reward': json.loads((final / 'reward.json').read_text()), 'result_dir': str(final)} + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('task', choices=['ndp', 'earth']) + p.add_argument('phase', choices=['inference', 'score']) + p.add_argument('--accept-allocated-memory', action='store_true', + help='Accept Beaker RAM above the benchmark request and record this deviation') + args = p.parse_args() + if args.accept_allocated_memory: + sandbox.MEMORY_POLICY = 'beaker-allocation' + os.umask(0o022) + state = Path('/run-state') + state.chmod(0o755 if args.phase == 'inference' else 0o700) + sys.path[:0] = ['/tests', '/evaluation'] + for key in list(os.environ): + if any(word in key.upper() for word in ('TOKEN', 'SECRET', 'API_KEY')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', OLMO_INFERENCE_HASHSEED='0', + PYTHONHASHSEED='0', CUDA_VISIBLE_DEVICES='0') + started = time.monotonic() + budget = 43200 if args.task == 'ndp' else 14400 + allowance = budget + memory = (22 if args.task == 'ndp' else 32) * 1024**3 + output = state / 'results' + write(state / 'status.json', {'phase': 'initializing', 'task': args.task, 'role': args.phase, + 'memory_policy': sandbox.MEMORY_POLICY}) + try: + if args.phase == 'inference': + import torch + if not torch.cuda.is_available() or torch.cuda.device_count() != 1 or 'H100' not in torch.cuda.get_device_name(0): + raise RuntimeError('Exactly one H100 is required') + devices = subprocess.check_output(['nvidia-smi', '--query-gpu=uuid', '--format=csv,noheader'], text=True).splitlines() + if len(devices) != 1: + raise RuntimeError('Beaker must allocate exactly one GPU') + if args.task == 'ndp': + inputs = freeze(Path('/input-source'), Path('/input')) + result = ndp_infer(Path('/submission-source'), inputs, output, + Path('/sealed/run'), budget - (time.monotonic() - started), memory) + else: + package = freeze(Path('/submission-source'), Path('/model')) + from package_contract import InvalidSubmission + try: + result = earth_infer(package, Path('/input-source'), output, + budget - (time.monotonic() - started), memory) + except InvalidSubmission as error: + output.mkdir(parents=True, exist_ok=True) + write(output / 'report.json', {'reward': 0.0, + 'status': 'invalid_submission', 'reason': str(error)}) + write(output / 'reward.json', {'reward': 0.0, 'invalid_submission': 1}) + result = {'status': 'invalid_submission'} + else: + prior = json.loads(Path('/prior/receipt.json').read_text()) + if prior['status'] != 'inference_complete': + raise RuntimeError('Only completed, accepted inference can be scored') + if prior.get('memory_policy') != sandbox.MEMORY_POLICY: + raise RuntimeError('Inference and scoring memory policies differ') + remaining = budget - prior['elapsed_seconds'] + allowance = min(600, remaining) if args.task == 'ndp' else remaining + if args.task == 'earth': + shutil.copytree('/prior/results', output) + result = native_score(args.task, package=Path('/submission-source'), + data=Path('/input-source'), sealed=Path('/sealed/run'), output=output, + seconds=allowance - (time.monotonic() - started), memory_bytes=memory) + elapsed = time.monotonic() - started + if sandbox.memory_peak() > sandbox.effective_memory_limit(memory) or elapsed > allowance: + raise sandbox.ResourceExceeded('Verifier resource acceptance gate failed') + result.update(elapsed_seconds=elapsed, **sandbox.memory_receipt(memory), + task=args.task, role=args.phase, adapter_sha256=digest(__file__), + sandbox_sha256=digest(sandbox.__file__), job_id=os.environ.get('BEAKER_JOB_ID')) + write(state / 'receipt.json', result) + write(state / 'status.json', {'phase': result['status'], **result}) + print(json.dumps(result), flush=True) + except Exception as error: + # Never publish a model-quality zero for a wrapper/infrastructure error. + for path in output.rglob('reward.json') if output.exists() else []: + path.unlink() + write(state / 'status.json', {'phase': 'infrastructure_error', + 'model_quality_measured': False, 'error': f'{type(error).__name__}: {error}'}) + raise + + +if __name__ == '__main__': + main() diff --git a/reproduction/files/d7/d736cbfc4c7d7ffa29644342c51126c704ce49d297418dadb30b2a17227371d1/native_verifier.py b/reproduction/files/d7/d736cbfc4c7d7ffa29644342c51126c704ce49d297418dadb30b2a17227371d1/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4266b946e3a4bfb0315c9ddb715ea687713cd8 --- /dev/null +++ b/reproduction/files/d7/d736cbfc4c7d7ffa29644342c51126c704ce49d297418dadb30b2a17227371d1/native_verifier.py @@ -0,0 +1,182 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import hashlib +import json +import os +from pathlib import Path +import pwd +import shutil +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + STATE.chmod(0o755) + status('preflight', task=plan['task'], role=phase) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus']) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if phase == 'inference': + if plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + subprocess.run(['useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + runtime.deny_network() + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run'], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc']) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg['command'][0], '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + subprocess.run([cfg['command'][0], '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': 'IPv4/IPv6 socket creation denied; inherited by children', + 'source_mounts': 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan['task'] != 'protein-folding-prediction', + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True) + elapsed = time.monotonic() - entered + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + reward_path = STATE / 'results/reward.json' + if phase == 'score': + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = Path('/sealed/results') / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/d9/d9d67e424ff9fd66980b53646eeb148e2f80aab59d7b811f0ec1d79c3a2e8087/test_large_launcher.py b/reproduction/files/d9/d9d67e424ff9fd66980b53646eeb148e2f80aab59d7b811f0ec1d79c3a2e8087/test_large_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..3cd9ce8c861e5fff3e02ebcc9639d857334b9a42 --- /dev/null +++ b/reproduction/files/d9/d9d67e424ff9fd66980b53646eeb148e2f80aab59d7b811f0ec1d79c3a2e8087/test_large_launcher.py @@ -0,0 +1,187 @@ +"""Verify job dependencies, explicit Large settings and duplicate submission guard.""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +class LargeLauncherTest(unittest.TestCase): + def test_submission_graph_without_slurm(self): + launcher = Path(__file__).resolve().parents[1] / "docs/slurm/launch_large.py" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + data = root / "data with spaces" + (data / "9923").mkdir(parents=True) + runtime = root / "upstream" + (runtime / ".venv/bin").mkdir(parents=True) + (runtime / ".venv/bin/python").touch() + fake = root / "sbatch" + fake.write_text( + f"#!{sys.executable}\n" + "import json,os,sys\n" + "from pathlib import Path\n" + "p=Path(os.environ['FAKE_SLURM_LOG'])\n" + "calls=json.loads(p.read_text()) if p.exists() else []\n" + "calls.append({'argv':sys.argv[1:], 'settings':{k:v for k,v in os.environ.items() if k.startswith('OLMO_')}})\n" + "p.write_text(json.dumps(calls))\n" + "print(1000+len(calls))\n" + ) + fake.chmod(0o755) + log = root / "submitted.json" + env = dict( + os.environ, PATH=f"{root}:{os.environ['PATH']}", FAKE_SLURM_LOG=str(log) + ) + command = [ + sys.executable, + str(launcher), + "--data", + str(data), + "--upstream", + str(runtime), + "--name", + "confirmation", + "--seed", + "12537", + "--data-seed", + "3623", + ] + result = subprocess.run(command, env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + calls = json.loads(log.read_text()) + self.assertEqual(len(calls), 2) + self.assertIn("--dependency=afterok:1001", calls[1]["argv"]) + for call in calls: + self.assertIn("--partition=" + os.environ.get("EARTH_SLURM_PARTITION", "gpu"), call["argv"]) + self.assertIn("--gres=gpu:rtx_pro_6000:1", call["argv"]) + self.assertEqual(call["settings"]["OLMO_VARIANT"], "large") + self.assertEqual(call["settings"]["OLMO_SEED"], "12537") + self.assertEqual(call["settings"]["OLMO_DATA_SEED"], "3623") + self.assertEqual(call["settings"]["OLMO_DATA"], str(data)) + receipt = json.loads((data / "launches/confirmation.json").read_text()) + self.assertEqual(receipt["validation_job"], 1002) + repeated = subprocess.run(command, env=env, capture_output=True, text=True) + self.assertNotEqual(repeated.returncode, 0) + self.assertEqual(len(json.loads(log.read_text())), 2) + two_gpu = command.copy() + two_gpu[two_gpu.index("--name") + 1] = "two-gpu" + two_gpu += ["--gpus", "2"] + result = subprocess.run(two_gpu, env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + calls = json.loads(log.read_text()) + self.assertIn("--gres=gpu:rtx_pro_6000:2", calls[2]["argv"]) + self.assertIn("--gres=gpu:rtx_pro_6000:1", calls[3]["argv"]) + self.assertIn("--dependency=afterok:1003", calls[3]["argv"]) + receipt = json.loads((data / "launches/two-gpu.json").read_text()) + self.assertEqual(receipt["settings"]["NCCL_P2P_DISABLE"], "1") + self.assertEqual(receipt["settings"]["OLMO_BATCH"], "64") + self.assertEqual(receipt["settings"]["OLMO_MICROBATCH"], "32") + early = two_gpu.copy() + early[early.index("--name") + 1] = "early-checkpoint" + early += ["--evaluate-step", "500"] + result = subprocess.run(early, env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + receipt = json.loads((data / "launches/early-checkpoint.json").read_text()) + settings = receipt["settings"] + self.assertEqual(settings["OLMO_STEPS"], "2000") + self.assertEqual(settings["OLMO_NAME"], "early-checkpoint-step500") + self.assertEqual(settings["OLMO_FIXED_CHECKPOINT_STEP"], "500") + self.assertGreaterEqual(int(settings["OLMO_KEEP_CHECKPOINTS"]), 4) + self.assertTrue( + settings["OLMO_CHECKPOINT"].endswith("/step500/model_and_optim") + ) + early[-1] = "375" + result = subprocess.run(early, env=env, capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(len(json.loads(log.read_text())), 6) + (data / "19837").mkdir() + expanded = two_gpu.copy() + expanded[expanded.index("--name") + 1] = "two-shards" + expanded += ["--pretrain-source", "two-shards"] + result = subprocess.run(expanded, env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + receipt = json.loads((data / "launches/two-shards.json").read_text()) + self.assertEqual( + receipt["settings"]["OLMO_PRETRAIN_DATA"], str(data / "19837") + ) + native = two_gpu.copy() + native[native.index("--name") + 1] = "native-batch" + native += [ + "--global-batch", + "512", + "--steps", + "750", + "--warmup", + "38", + "--lr", + "0.0001", + ] + result = subprocess.run(native, env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + receipt = json.loads((data / "launches/native-batch.json").read_text()) + settings = receipt["settings"] + self.assertEqual(settings["OLMO_BATCH"], "512") + self.assertEqual(settings["OLMO_STEPS"], "750") + self.assertEqual(settings["OLMO_EPHEMERAL_INTERVAL"], "250") + evaluation = root / "a5000 evaluation" + (evaluation / "eval").mkdir(parents=True) + (evaluation / "packages").mkdir() + alternate = two_gpu.copy() + alternate[alternate.index("--name") + 1] = "alternate-evaluator" + alternate += [ + "--evaluation-gpu", + "a5000", + "--evaluation-root", + str(evaluation), + ] + result = subprocess.run(alternate, env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + receipt = json.loads( + (data / "launches/alternate-evaluator.json").read_text() + ) + self.assertIn("--gres=gpu:rtx_pro_6000:2", receipt["training"]) + self.assertIn("--gres=gpu:a5000:1", receipt["validation"]) + self.assertEqual(receipt["settings"]["OLMO_ROOT"], str(evaluation)) + self.assertEqual(receipt["settings"]["OLMO_DATA"], str(data)) + sharded = alternate.copy() + sharded[sharded.index("--name") + 1] = "parallel-evaluator" + shards = root / "shards" + shards.mkdir() + (shards / "part000.h5").touch() + (shards / "manifest.json").write_text( + json.dumps( + { + "full_release": True, + "start": 0, + "stop": 16, + "source_rows": 16, + "batch_size": 16, + "source": str(evaluation / "eval/lfmc/inputs.h5"), + "shards": [{"file": "part000.h5"}], + } + ) + ) + (evaluation / "execution-context.json").write_text("{}") + rejected = subprocess.run(sharded, env=env, capture_output=True, text=True) + self.assertNotEqual(rejected.returncode, 0) + sharded += ["--shard-inputs", str(shards)] + result = subprocess.run(sharded, env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + receipt = json.loads( + (data / "launches/parallel-evaluator.json").read_text() + ) + self.assertIn("dispatch_job", receipt) + self.assertNotIn("validation_job", receipt) + self.assertFalse(any(a.startswith("--gres") for a in receipt["validation"])) + self.assertTrue( + receipt["validation"][-1].endswith("dispatch_sharded_eval.sbatch") + ) + self.assertEqual(receipt["settings"]["OLMO_SHARD_INPUTS"], str(shards)) + self.assertNotIn("OLMO_INFERENCE_HASHSEED", receipt["settings"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/da/da2b14ccb4e4477bf13a87b54c70e97577051ad9c41e37ac127a665987b1514a/prepare.py b/reproduction/files/da/da2b14ccb4e4477bf13a87b54c70e97577051ad9c41e37ac127a665987b1514a/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..ed9519708c72eaef8068aea2ff80176f2a48c0f9 --- /dev/null +++ b/reproduction/files/da/da2b14ccb4e4477bf13a87b54c70e97577051ad9c41e37ac127a665987b1514a/prepare.py @@ -0,0 +1,396 @@ +"""Materialize public references and label-free inputs (no GPU or credentials).""" + +from __future__ import annotations + +import argparse +from concurrent.futures import ProcessPoolExecutor +import csv +import gzip +import hashlib +import json +from pathlib import Path + +import phonopy +import requests +from ase import Atoms +from pymatgen.core import Structure +from pymatgen.entries.computed_entries import ComputedEntry + +from common import ( + ELASTIC_FIELDS, + PHONON_FIELDS, + PROTOCOL, + digest, + encode_atoms, + indexed, + write_json, + write_rows, +) + +CATALOG = Path(__file__).with_name("sources.json") +MDR_ROOT = "https://alexandria.icams.rub.de/data/phonon_benchmark/" + + +def download(url: str, path: Path, expected=None) -> Path: + if path.exists() and path.stat().st_size > 0: + if expected and digest(path) != expected: + raise ValueError(f"Cached source checksum mismatch: {path}") + return path + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".partial") + with requests.get(url, stream=True, timeout=(30, 180)) as response: + response.raise_for_status() + with temporary.open("wb") as stream: + for chunk in response.iter_content(1 << 20): + stream.write(chunk) + if temporary.stat().st_size == 0: + raise ValueError(f"Empty download: {url}") + if expected and digest(temporary) != expected: + raise ValueError(f"Downloaded source checksum mismatch: {url}") + temporary.replace(path) + return path + + +def select_ids(rows, id_key, size, preset, limit): + if preset == "pilot": + # Label-blind size strata broaden the smoke while bounding GPU cost. + # This deliberately differs from the full population's size distribution. + selected = [] + for lower, upper in ((0, 4), (4, 8), (8, 16), (16, 32)): + bucket = [r[id_key] for r in rows if lower < size(r) <= upper] + bucket.sort( + key=lambda value: hashlib.sha256( + f"pilot-v1:{value}".encode() + ).hexdigest() + ) + if len(bucket) < limit // 4: + raise ValueError("Insufficient cases in pilot size stratum") + selected.extend(bucket[: limit // 4]) + return selected + eligible = rows if preset == "full" else [r for r in rows if size(r) <= 4] + # Geometry-size cap is for smoke cost only; it is not an accuracy test panel. + ids = [r[id_key] for r in eligible] + if len(ids) != len(set(ids)): + raise ValueError("Source contains duplicate material IDs") + ids.sort(key=lambda value: hashlib.sha256(f"smoke-v1:{value}".encode()).hexdigest()) + return ids if preset == "full" else ids[:limit] + + +def structure_atoms(data): + return encode_atoms(Structure.from_dict(data).to_ase_atoms()) + + +def phonon_input(path): + phonon = phonopy.load(path, produce_fc=False) + cell = phonon.unitcell + return { + "atoms": encode_atoms( + Atoms( + numbers=cell.numbers, + positions=cell.positions, + cell=cell.cell, + pbc=True, + ) + ), + "phonon": { + "masses": cell.masses.tolist(), + "supercell_matrix": phonon.supercell_matrix.tolist(), + "primitive_matrix": ( + phonon.primitive_matrix.tolist() + if phonon.primitive_matrix is not None + else None + ), + }, + } + + +def prepare_phonon_row(job): + """Independent CPU preparation; geometry is kept separate from targets.""" + row, cache = job + name = f"{row['mp_id']}.yaml.bz2" + url = MDR_ROOT + "pbe/" + name + file = download(url, cache / "mdr" / name) + return ( + {"id": f"phonons/{row['mp_id']}", "suite": "phonons", **phonon_input(file)}, + { + "id": f"phonons/{row['mp_id']}", + "suite": "phonons", + **{key: float(row[key]) for key in PHONON_FIELDS}, + }, + f"mdr/{name}", + {"url": url, "sha256": digest(file), "bytes": file.stat().st_size}, + ) + + +def prepare( + cache: Path, + output: Path, + suite="all", + preset="smoke", + limit=None, + split_dir=None, + workers=1, + panel=None, +): + if output.exists(): + raise FileExistsError(f"Refusing to mix/overwrite a prepared panel: {output}") + catalog = json.loads(CATALOG.read_text()) + provenance, inputs, targets, counts = {}, [], [], {} + split_rows, split_manifest = None, None + panel_manifest = None + if panel is not None: + if preset not in ("val", "test") or limit is not None: + raise ValueError("Frozen panel requires val/test preset and no limit") + panel_manifest = json.loads(Path(panel).read_text()) + if preset in ("val", "test"): + from splits import DEFAULT_SPLITS, load_split + + split_dir = split_dir or DEFAULT_SPLITS + split_rows, split_manifest = load_split(split_dir) + if panel_manifest and panel_manifest["parent_split_manifest_sha256"] != digest(split_dir / "manifest.json"): + raise ValueError("Panel belongs to another split") + # Reject materialization from sources other than the frozen split's sources. + for name in ("summary.csv.gz", "mdr.csv", "elastic.json.gz"): + if catalog[name]["sha256"] != split_manifest["sources"][name]["sha256"]: + raise ValueError(f"Split/source version mismatch: {name}") + + def choose(rows, name, id_key, size, default_limit): + if split_rows is None: + return select_ids(rows, id_key, size, preset, limit or default_limit) + if len(rows) != split_manifest["summary"][name]["all"]["cases"]: + raise ValueError(f"Split/source population mismatch: {name}") + wanted = [ + r["material_id"] + for r in split_rows + if r["suite"] == name and r["split"] == preset + ] + if not set(wanted) <= {r[id_key] for r in rows}: + raise ValueError(f"Split IDs absent from source: {name}") + if panel_manifest: + ids = panel_manifest["panels"][preset][name]["ids"] + available = {f"{name}/{key}":key for key in wanted} + if len(ids) != len(set(ids)) or not set(ids) <= available.keys(): + raise ValueError("Panel IDs escape their frozen partition") + return [available[key] for key in ids] + # A bounded development run samples across all atom sizes, without using + # target labels. Full val/test membership is fixed in the split manifest. + wanted.sort( + key=lambda key: hashlib.sha256( + f"eval-subset-v1:{name}/{key}".encode() + ).hexdigest() + ) + return wanted[:limit] if limit else wanted + + def source(name): + item = catalog[name] + file = download(item["url"], cache / name, item["sha256"]) + provenance[name] = {**item, "bytes": file.stat().st_size} + return file + + if suite in ("all", "discovery"): + with gzip.open(source("summary.csv.gz"), "rt") as stream: + summary = list(csv.DictReader(stream)) + counts["discovery"] = len(summary) + ids = choose( + summary, + "discovery", + "material_id", + lambda r: int(float(r["n_sites"])), + 128 if preset == "pilot" else 8, + ) + id_set = set(ids) + selected = {r["material_id"]: r for r in summary if r["material_id"] in id_set} + entries, structures = {}, {} + for file, key, result in ( + (source("initial.jsonl.gz"), "initial_structure", structures), + (source("cse.jsonl.gz"), "computed_structure_entry", entries), + ): + with gzip.open(file, "rt") as stream: + for line in stream: + row = json.loads(line) + if row["material_id"] in selected: + result[row["material_id"]] = row[key] + with gzip.open(source("elements.json.gz"), "rt") as stream: + refs = { + el: ComputedEntry.from_dict(entry).energy_per_atom + for el, entry in json.load(stream).items() + } + for material_id in ids: + row = selected[material_id] + inputs.append( + { + "id": f"discovery/{material_id}", + "suite": "discovery", + "atoms": structure_atoms(structures[material_id]), + } + ) + targets.append( + { + "id": f"discovery/{material_id}", + "suite": "discovery", + "entry": entries[material_id], + "elemental_refs": refs, + "e_form": float(row["e_form_per_atom_mp2020_corrected"]), + "e_hull": float(row["e_above_hull_mp2020_corrected_ppd_mp"]), + "unique_prototype": row["unique_prototype"].lower() == "true", + } + ) + + if suite in ("all", "phonons"): + with source("mdr.csv").open() as stream: + rows = list(csv.DictReader(stream)) + counts["phonons"] = len(rows) + ids = set( + choose( + rows, + "phonons", + "mp_id", + lambda r: int(r["nsites"]), + 16 if preset == "pilot" else 2, + ) + ) + jobs = [(r, cache) for r in rows if r["mp_id"] in ids] + pool = ProcessPoolExecutor(max_workers=workers) if workers > 1 else None + try: + results = ( + pool.map(prepare_phonon_row, jobs) + if pool + else map(prepare_phonon_row, jobs) + ) + for i, (case, target, name, entry) in enumerate(results, 1): + inputs.append(case) + targets.append(target) + provenance[name] = entry + if i % 100 == 0 or i == len(jobs): + print(f"Prepared phonons: {i}/{len(jobs)}", flush=True) + finally: + if pool: + pool.shutdown(cancel_futures=True) + + if suite in ("all", "elasticity"): + with gzip.open(source("elastic.json.gz"), "rt") as stream: + rows = json.load(stream) + counts["elasticity"] = len(rows) + ids = set( + choose( + rows, + "elasticity", + "mp_id", + lambda r: len(r["structure"]["sites"]), + 16 if preset == "pilot" else 2, + ) + ) + for row in rows: + if row["mp_id"] in ids: + inputs.append( + { + "id": f"elasticity/{row['mp_id']}", + "suite": "elasticity", + "atoms": structure_atoms(row["structure"]), + } + ) + targets.append( + { + "id": f"elasticity/{row['mp_id']}", + "suite": "elasticity", + **{key: float(row[key]) for key in ELASTIC_FIELDS}, + } + ) + + inputs.sort(key=lambda row: row["id"]) + targets.sort(key=lambda row: row["id"]) + if set(indexed(inputs)) != set(indexed(targets)): + raise ValueError("Input/target ID mismatch") + if split_rows is not None: + from splits import atoms_key + + split_index = {r["id"]: r for r in split_rows} + for row in inputs: + expected = split_index[row["id"]] + if ( + expected["split"] != preset + or atoms_key(row["atoms"]) != expected["composition"] + ): + raise ValueError(f"Frozen split/geometry mismatch: {row['id']}") + write_rows(output / "inputs" / "cases.jsonl", inputs) + write_rows(output / "references" / "targets.jsonl", targets) + manifest = { + "protocol": PROTOCOL, + "preset": preset, + "source_population_counts": counts, + "case_ids": [r["id"] for r in inputs], + "sources": provenance, + "inputs_sha256": digest(output / "inputs" / "cases.jsonl"), + "targets_sha256": digest(output / "references" / "targets.jsonl"), + "leaderboard_comparable": False, + "selection": "Equal counts in 1–4, 5–8, 9–16, 17–32 atom strata; SHA256 pilot-v1 order; no target labels" + if preset == "pilot" + else preset, + "note": "Public-data evaluator.", + } + if split_manifest is not None: + manifest["split"] = { + "version": split_manifest["version"], + "partition": preset, + "manifest_sha256": digest(split_dir / "manifest.json"), + "assignments_sha256": split_manifest["files"]["assignments.jsonl.gz"], + "limit_per_suite": limit, + "complete_partition": limit is None and panel_manifest is None, + } + manifest["selection"] = split_manifest["assignment"] + if panel_manifest: + manifest["panel"] = {"version":panel_manifest["version"], "manifest_sha256":digest(Path(panel))} + manifest["selection"] = panel_manifest["selection"] + write_json(output / "references" / "manifest.json", manifest) + print( + json.dumps( + {"cases": len(inputs), "population_counts": counts, "preset": preset} + ) + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cache", type=Path, default=Path(".data/sources")) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument( + "--panel", type=Path, help="Frozen compact panel manifest (val/test only)" + ) + parser.add_argument( + "--suite", choices=["all", "discovery", "phonons", "elasticity"], default="all" + ) + parser.add_argument( + "--preset", choices=["smoke", "pilot", "full", "val", "test"], default="smoke" + ) + parser.add_argument( + "--split-dir", type=Path, help="Frozen split directory; defaults to HF-materialized .data/splits/v1" + ) + parser.add_argument( + "--limit", + type=int, + help="Bound each suite in smoke/val/test; omitted val/test means entire partition", + ) + parser.add_argument( + "--workers", type=int, default=1, help="CPU processes for phonon preparation" + ) + args = parser.parse_args() + if args.limit is not None and ( + args.limit <= 0 or args.preset not in ("smoke", "val", "test") + ): + parser.error( + "--limit must be positive and is only valid with --preset smoke/val/test" + ) + if args.split_dir and args.preset not in ("val", "test"): + parser.error("--split-dir requires --preset val/test") + if not 1 <= args.workers <= 16: + parser.error("--workers must be between 1 and 16") + prepare( + args.cache, + args.output, + args.suite, + args.preset, + args.limit, + args.split_dir, + args.workers, + args.panel, + ) diff --git a/reproduction/files/da/da2e6a275d6cb5660c191c136ed3d9c49d8a135c7d2d0d276fd8d4864a498a05/test_starter.py b/reproduction/files/da/da2e6a275d6cb5660c191c136ed3d9c49d8a135c7d2d0d276fd8d4864a498a05/test_starter.py new file mode 100644 index 0000000000000000000000000000000000000000..28ed45477c0f76a992ad348e171e7fe14d903058 --- /dev/null +++ b/reproduction/files/da/da2e6a275d6cb5660c191c136ed3d9c49d8a135c7d2d0d276fd8d4864a498a05/test_starter.py @@ -0,0 +1,220 @@ +"""Optional CPU ML smoke: synthetic dynamics, not a HydroGym baseline result.""" + +import importlib.util +import io +import json +from pathlib import Path +import shutil +import sys +import tempfile +import unittest +import zipfile + + +TASK = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(TASK / "environment/baseline/starter"), str(TASK / "environment/evaluation")] +ML_AVAILABLE = all(importlib.util.find_spec(p) is not None for p in ("torch", "numpy", "gymnasium", "stable_baselines3")) + + +@unittest.skipUnless(ML_AVAILABLE, "PyTorch/Gymnasium/SB3 runtime not installed; use the documented CPU container smoke") +class StarterTests(unittest.TestCase): + def test_random_package_is_untrained_reproducible_and_relocatable(self): + import torch + import numpy as np + from init_random import initialize + from protocol import Policy + + def state(package): + with zipfile.ZipFile(package / 'policy.pyz') as archive: + return (json.loads(archive.read('config.json')), + torch.load(io.BytesIO(archive.read('checkpoint.pt')), weights_only=True)) + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + a, b, c = [root / name for name in ('a', 'b', 'c')] + record = initialize(a, 0) + self.assertEqual((a / 'policy.pyz').stat().st_mode & 0o777, 0o644) + initialize(b, 0) + initialize(c, 1) + config, weights = state(a) + _, same = state(b) + _, other = state(c) + self.assertEqual(record['training_steps'], 0) + self.assertEqual(record['case_capacity'], 39) + self.assertEqual(config['initialization']['optimizer_updates'], 0) + self.assertFalse(config['initialization']['pretrained_weights']) + self.assertTrue(all(torch.equal(weights[k], same[k]) for k in weights)) + self.assertTrue(any(not torch.equal(weights[k], other[k]) for k in weights)) + self.assertTrue(any(torch.count_nonzero(v) for k, v in weights.items() if k.endswith('weight'))) + with self.assertRaisesRegex(ValueError, 'empty'): + initialize(a, 0) + relocated = root / 'relocated' + shutil.move(a, relocated) + policy = Policy(relocated, root / 'policy.log', timeout=20) + try: + # Exercise every published shape, plus an unseen environment ID. + from case_spec import specifications + for case in specifications()['cases']: + n, m = case['observation_size'], case['action_size'] + low = [0.] * m if case['backend'] == 'jax-fluids' else [-1.] * m + policy.reset({'environment': case['environment']}, [n], [m], low, [1.] * m) + action = policy.act([.1] * n) + self.assertEqual(len(action), m) + self.assertTrue(np.isfinite(action).all()) + self.assertTrue(all(lo <= v <= 1. for lo, v in zip(low, action))) + policy.reset({'environment': 'future-unseen-case'}, [128], [24], [-1.] * 24, [1.] * 24) + positive = policy.act([.2] * 128) + negative = policy.act([-.2] * 128) + self.assertEqual(len(positive), 24) + self.assertFalse(np.allclose(positive, negative)) + policy.close() + finally: + policy.abort() + _, after = state(relocated) + self.assertTrue(all(torch.equal(weights[k], after[k]) for k in weights)) + + def test_same_training_and_replay_time_limit(self): + import gymnasium as gym + import numpy as np + from native_settings import apply_settings, with_episode_limit + from shared import SharedEnv, dimensions + from protocol import InfrastructureError + + class Native(gym.Env): + observation_space = gym.spaces.Box(-1, 1, (2,), dtype=np.float32) + action_space = gym.spaces.Box(-1, 1, (1,), dtype=np.float32) + max_episode_steps, num_substeps_per_iteration = 200, 170 + MAX_CONTROL, omega = .25, 1. + + def reset(self, **kwargs): + self.count = 0 + return np.zeros(2, dtype=np.float32), {} + + def step(self, action): + self.count += 1 + done = self.count > self.max_episode_steps + return np.zeros(2, dtype=np.float32), -1., done, done, {} + + case = {"id": "case", "environment": "synthetic", "observation_size": 2, + "action_size": 1, "horizon": 200, "episode_end": "time_limit", + "native_settings": {"max_episode_steps": 200}} + raw = Native() + raw.reviewed_protocol = apply_settings(raw, case) + replay = with_episode_limit(raw, case) + train = SharedEnv(replay, case, dimensions({"cases": [case]})) + try: + with self.assertRaisesRegex(InfrastructureError, "Reset"): + train.step(np.zeros(1, dtype=np.float32)) + for environment in (replay, train): + environment.reset() + for count in range(1, 201): + _, reward, terminated, truncated, _ = environment.step(np.zeros(1, dtype=np.float32)) + self.assertEqual(reward, -1.) + self.assertFalse(terminated) + self.assertEqual(truncated, count == 200) + with self.assertRaisesRegex(InfrastructureError, "Reset"): + environment.step(np.zeros(1, dtype=np.float32)) + # Exercise SB3's actual timeout bootstrap, not merely our flags. + import torch + from stable_baselines3 import PPO + torch.set_num_threads(1) + model = PPO("MlpPolicy", train, n_steps=200, batch_size=40, n_epochs=1, + gamma=.99, learning_rate=0., policy_kwargs={"net_arch": [8]}) + with torch.no_grad(): + model.policy.value_net.weight.zero_() + model.policy.value_net.bias.fill_(5.) + model.learn(total_timesteps=200) + np.testing.assert_allclose(model.rollout_buffer.rewards[:-1], -1., atol=1e-6) + np.testing.assert_allclose(model.rollout_buffer.rewards[-1], -1. + .99 * 5., atol=1e-6) + replay.reset() + raw.max_episode_steps = 0 + with self.assertRaisesRegex(InfrastructureError, "preceded"): + replay.step(np.zeros(1, dtype=np.float32)) + finally: + train.close() + + def test_resume_rejects_changed_episode_semantics(self): + import gymnasium as gym + from train import train + from shared import dimensions + case = {"id": "case", "environment": "synthetic", "observation_size": 2, "action_size": 1} + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + resume = root / "model.zip" + resume.write_bytes(b'Never load this legacy placeholder') + resume.with_suffix('.json').write_text(json.dumps(dimensions({"cases": [case]}))) + corrected = dict(case, episode_end="time_limit") + with self.assertRaisesRegex(ValueError, "incompatible"): + train(gym.Env(), {"cases": [corrected]}, corrected, 200, resume, root / "submission") + + def test_shared_training_publication_and_relocated_policy(self): + import gymnasium as gym + import numpy as np + import torch + from train import train + from protocol import Policy + from shared import build_policy, encode, native_action + + torch.set_num_threads(1) + + class Toy(gym.Env): + def __init__(self, size): + self.observation_space = gym.spaces.Box(-2, 2, shape=(size,), dtype=np.float32) + self.action_space = gym.spaces.Box(-0.03, 0.03, shape=(1,), dtype=np.float32) + + def reset(self, seed=None, options=None): + super().reset(seed=seed) + self.steps = 0 + self.state = np.full(self.observation_space.shape, 0.1, dtype=np.float32) + return self.state.copy(), {} + + def step(self, action): + self.steps += 1 + self.state = np.clip(self.state + float(action[0]), -2, 2) + return self.state.copy(), -float(np.square(self.state).mean()), False, self.steps >= 20, {} + + cases = [{"environment": f"synthetic-{n}", "observation_size": n, "action_size": 1} for n in (2, 3)] + suite = {"cases": cases} + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + resume, package = root / "resume.zip", root / "submission" + train(Toy(2), suite, cases[0], 200, resume, package) + first = (package / "policy.pyz").read_bytes() + train(Toy(3), suite, cases[1], 200, resume, package) + self.assertNotEqual(first, (package / "policy.pyz").read_bytes()) + with zipfile.ZipFile(package / "policy.pyz") as archive: + config = json.loads(archive.read("config.json")) + self.assertEqual(config["training_steps"], 400) + self.assertEqual(sum(n.endswith(".pt") for n in archive.namelist()), 1) + state = torch.load(io.BytesIO(archive.read("checkpoint.pt")), weights_only=True) + with zipfile.ZipFile(io.BytesIO(first)) as archive: + earlier = torch.load(io.BytesIO(archive.read("checkpoint.pt")), weights_only=True) + self.assertTrue(any(not torch.equal(state[k], earlier[k]) for k in state)) + expected_policy = build_policy(config) + expected_policy.load_state_dict(state) + expected_policy.eval() + self.assertEqual({p.name for p in package.iterdir()}, {"infer.sh", "README.md", "policy.pyz"}) + relocated = root / "relocated" + shutil.copytree(package, relocated) + # Remove original model/optimizer locations: replay must not depend on them. + shutil.rmtree(package) + resume.unlink() + process = Policy(relocated, root / "policy.log", timeout=20) + try: + for n in (3, 2): + process.reset({"environment": "new-request-name"}, [n], [1], [-0.03], [0.03]) + action = process.act([0.2] * n) + self.assertEqual(len(action), 1) + self.assertTrue(-0.03 <= action[0] <= 0.03) + vector = encode([0.2] * n, "new-request-name", config) + with torch.inference_mode(): + expected, _, _ = expected_policy(torch.as_tensor(vector).unsqueeze(0), deterministic=True) + expected = native_action(expected[0].numpy(), [-0.03], [0.03]) + np.testing.assert_allclose(action, expected, atol=1e-7) + process.close() + finally: + process.abort() + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/da/da419675f9ec395d31788841ee646f61244c6c84ae2b35e691a8193fdd413e3c/fixture_data.py b/reproduction/files/da/da419675f9ec395d31788841ee646f61244c6c84ae2b35e691a8193fdd413e3c/fixture_data.py new file mode 100644 index 0000000000000000000000000000000000000000..9062e51f1dc6a588227680ee2709a7a8bdf9f68f --- /dev/null +++ b/reproduction/files/da/da419675f9ec395d31788841ee646f61244c6c84ae2b35e691a8193fdd413e3c/fixture_data.py @@ -0,0 +1,67 @@ +"""Small MIMIC-shaped source used only by the two-phase verifier smoke test.""" + +from __future__ import annotations + +import csv +import gzip +from pathlib import Path + + +def _write(path: Path, header: list[str], rows: list[list]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with gzip.open(path, "wt", newline="") as stream: + writer = csv.writer(stream) + writer.writerow(header) + writer.writerows(rows) + + +def fixture_source(root: Path, *, future_value: str = "8", + reverse_diagnoses: bool = False) -> None: + root.mkdir(parents=True, exist_ok=True) + (root / "CHANGELOG.txt").write_text("MIMIC-IV v3.1\n") + hosp = root / "hosp" + subjects = range(10000001, 10000013) + _write(hosp / "patients.csv.gz", + ["subject_id", "gender", "anchor_age", "anchor_year", "anchor_year_group", "dod"], + [[s, "F" if s % 2 else "M", 50, 2150, "2011 - 2013", ""] for s in subjects]) + admissions, diagnoses, labs, prescriptions, pharmacy, emar = [], [], [], [], [], [] + for subject in subjects: + first = subject + 10000000 + admissions.append([subject, first, "2150-01-01 00:00:00", + "2150-01-03 12:00:00", "", 0]) + diagnoses.extend([[subject, first, 2, "A001", 10], + [subject, first, 1, "A002", 10]]) + labs.append([subject, first, subject * 10, 50000, + "2150-01-02 08:00:00", "2150-01-02 10:00:00", "2", "2", "mg/dL"]) + prescriptions.append([subject, first, first, "2150-01-02 12:00:00", + "2150-01-05 00:00:00", "00000000001", "1", "mg"]) + pharmacy.append([subject, first, first, "2150-01-02 11:00:00"]) + emar.append([subject, first, first, first, "2150-01-02 13:00:00", + "2150-01-02 14:00:00", "Administered"]) + if subject != 10000001: + second = first + 100 + admissions.append([subject, second, "2150-03-01 00:00:00", + "2150-03-03 10:00:00", "", 0]) + diagnoses.extend([[subject, second, 1, "B001", 10], + [subject, second, 2, "B002", 10]]) + labs.append([subject, second, subject * 10 + 1, 50000, + "2150-03-02 08:00:00", "2150-03-02 10:00:00", + future_value, future_value, "mg/dL"]) + _write(hosp / "admissions.csv.gz", + ["subject_id", "hadm_id", "admittime", "dischtime", "deathtime", "hospital_expire_flag"], admissions) + _write(hosp / "diagnoses_icd.csv.gz", + ["subject_id", "hadm_id", "seq_num", "icd_code", "icd_version"], + list(reversed(diagnoses)) if reverse_diagnoses else diagnoses) + _write(hosp / "d_icd_diagnoses.csv.gz", ["icd_code", "icd_version", "long_title"], + [[code, 10, "synthetic category"] for code in ("A001", "A002", "B001", "B002")]) + _write(hosp / "labevents.csv.gz", + ["subject_id", "hadm_id", "labevent_id", "itemid", "charttime", "storetime", + "value", "valuenum", "valueuom"], labs) + _write(hosp / "prescriptions.csv.gz", + ["subject_id", "hadm_id", "pharmacy_id", "starttime", "stoptime", "ndc", + "dose_val_rx", "dose_unit_rx"], prescriptions) + _write(hosp / "pharmacy.csv.gz", + ["subject_id", "hadm_id", "pharmacy_id", "entertime"], pharmacy) + _write(hosp / "emar.csv.gz", + ["subject_id", "hadm_id", "emar_id", "pharmacy_id", "charttime", "storetime", + "event_txt"], emar) diff --git a/reproduction/files/db/db02dd7c709c27becb3b92c50cad36d57c3f5b7429ada53f7055c28eda4439df/conftest.py b/reproduction/files/db/db02dd7c709c27becb3b92c50cad36d57c3f5b7429ada53f7055c28eda4439df/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..2a9c2b42d6da188da2b3c9bed86691842d3f0663 --- /dev/null +++ b/reproduction/files/db/db02dd7c709c27becb3b92c50cad36d57c3f5b7429ada53f7055c28eda4439df/conftest.py @@ -0,0 +1,7 @@ +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +# Evaluation code first: tests import its common/distributed/predict modules by name. +for path in (ROOT / "tests", ROOT / "environment" / "data", ROOT / "environment" / "evaluation"): + sys.path.insert(0, str(path)) diff --git a/reproduction/files/db/db2488f698ffe405344dbefb189b1383c143d1d9f4cee01f741b70652a9fbe07/test_physical_metrics.py b/reproduction/files/db/db2488f698ffe405344dbefb189b1383c143d1d9f4cee01f741b70652a9fbe07/test_physical_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..4e401276d0e4c9340b9fe968d2bf7339e6f620de --- /dev/null +++ b/reproduction/files/db/db2488f698ffe405344dbefb189b1383c143d1d9f4cee01f741b70652a9fbe07/test_physical_metrics.py @@ -0,0 +1,159 @@ +"""CPU physical extraction/aggregation tests, not full CFD acceptance.""" +import json +import math +from pathlib import Path +import sys +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import Mock + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'environment/evaluation')) +import metrics +from case_spec import select_cases +from native_envs import ReplayAdapter +from protocol import InfrastructureError, replay_episode + + +class MetricTests(unittest.TestCase): + def test_maia_empty_step_info_captures_existing_reward_objective_once(self): + class Env: + observation_space = action_space = SimpleNamespace(shape=(1,), dtype=np.float32) + def reset(self, seed): + self.calls = 0 + return np.zeros(1), {} + def get_reward(self): + self.calls += 1 + return -12., {'forces': [[2., 3.]]} + def step(self, action): + reward, discarded = self.get_reward() + return np.zeros(1), reward, True, True, {} + case = dict(id='Pinball_2D_Re100', environment='Pinball_2D_Re100', backend='maia', + horizon=1, primary_metric=metrics.definition('Pinball_2D_Re100')) + with tempfile.TemporaryDirectory() as directory: + native = Env() + env = ReplayAdapter(native, case, Path(directory)) + env.reset(123) + _, reward, _, _, info = env.step([0.]) + self.assertEqual(native.calls, 1) + self.assertEqual(reward, -12.) + self.assertEqual(info['CD'], 2.) + self.assertEqual(env.evaluation_metrics()['value'], 2.) + + def test_exact_39_coverage_and_targets(self): + spec, cases = select_cases(['all']) + self.assertEqual(set(metrics.registry()), {c['id'] for c in cases}) + self.assertEqual(len(cases), 39) + self.assertEqual(spec['metric_version'], metrics.VERSION) + self.assertEqual(spec['metrics_sha256'], metrics.registry_hash()) + self.assertEqual(len(metrics.GROUPS['drag_cd'].split()), 19) + for case in cases: + self.assertEqual(case['primary_metric'], metrics.definition(case['id'])) + with self.assertRaises(InfrastructureError): + metrics.definition('Cavity_2D_Re4200') # Not in this frozen release. + + def test_fixed_window_including_odd_horizon(self): + m = metrics.definition('Cylinder_2D_Re200') + for values, expected, first in [([10., 10., 2., 4.], 3., 3), ([10., 2., 4.], 3., 2)]: + result = metrics.summarize(m, [dict(CD=v) for v in values], len(values)) + self.assertEqual(result['value'], expected) + self.assertEqual(result['first_control'], first) + with self.assertRaises(InfrastructureError): + metrics.summarize(m, [dict(CD=1.)], 2) + + def test_maia_force_units_and_sphere_projection(self): + converter = Mock(side_effect=lambda **kw: np.asarray(kw['forces']) / 2) + env = SimpleNamespace(Ma=math.sqrt(3), referenceLength=2., dX=.5, zLength=3., + compute_nondim_coefficients=converter) + for name, expected_cd in [('Cylinder_2D_Re200', 3.), ('SquareCylinder_2D_Re200', 3.), + ('Cube_3D_Re300', 3.), ('Sphere_3D_Re300', 3.), ('Pinball_2D_Re100', 6.)]: + converter.reset_mock() + s = metrics.sample(env, {'environment': name}, {'forces': [[2., 1., 0.], [4., 3., 0.]]}, -99.) + self.assertEqual(s['CD'], expected_cd) + if name.startswith('Pinball'): + converter.assert_not_called() + else: + expected_area = math.pi * 4 if name.startswith('Sphere') else 24. + self.assertAlmostEqual(converter.call_args.kwargs['projectionLength'], expected_area) + + def test_gust_full_episode_error_and_frozen_target(self): + name = 'NACA0012Gust_2D_Re100_AOA20' + m = metrics.definition(name) + t = m['target'] + env = SimpleNamespace(Ma=1., referenceLength=1., dX=1., zLength=1., + unperturbed_avg_lift=t['CL'], unperturbed_avg_drag=t['CD'], omega=t['omega'], + compute_nondim_coefficients=lambda **kw: np.asarray(kw['forces'])) + s = metrics.sample(env, {'environment': name, 'primary_metric': m}, + {'forces': [t['CD'] + .4, t['CL'] + .2]}, -999.) + self.assertAlmostEqual(s['gust_load_error'], .3) + result = metrics.summarize(m, [s, dict(gust_load_error=0.)], 2) + self.assertAlmostEqual(result['value'], .15) + env.omega = 1 + with self.assertRaises(InfrastructureError): + metrics.sample(env, {'environment': name}, {'forces': [1., 1.]}, 0.) + + def test_lift_drag_is_mean_of_ratios_not_ratio_of_means(self): + m = metrics.definition('NACA0012_2D_Re100_AOA20') + rows = [dict(lift_drag=50., lift_drag_valid=1.), dict(lift_drag=50., lift_drag_valid=1.), + dict(lift_drag=2., lift_drag_valid=1.), dict(lift_drag=4., lift_drag_valid=1.)] + self.assertEqual(metrics.summarize(m, rows, 4)['value'], 3.) + rows[-1]['lift_drag_valid'] = 0. + invalid = metrics.summarize(m, rows, 4) + self.assertIsNone(invalid['value']) + self.assertEqual(invalid['status'], 'invalid_operating_regime') + + def test_nozzle_radians_to_degrees_full_window(self): + name = 'Nozzle2D_coarse' + s = metrics.sample(None, {'environment': name}, dict(target_angle=math.pi/6, thrust_angle=0.), -99.) + self.assertAlmostEqual(s['angle_error_deg'], 30.) + m = metrics.definition(name) + result = metrics.summarize(m, [s, dict(angle_error_deg=0.)], 2) + self.assertAlmostEqual(result['value'], 15.) + + def test_energy_not_action_penalized_reward_and_channel_exact_identity(self): + s = metrics.sample(None, {'environment': 'Kolmogorov_2D'}, {'mean_tke': .2}, -999.) + self.assertEqual(s, dict(TKE=.2)) + s = metrics.sample(None, {'environment': 'Channel_3D_Retau180'}, {}, -.4) + self.assertEqual(s, dict(wall_shear=.4)) + + def test_missing_nonfinite_or_reward_only_is_not_a_primary_metric(self): + m = metrics.definition('Cylinder_2D_Re200') + for episodes in ([{'return': 10.}], [{'primary_metric': dict(m, status='ok', value=float('nan'))}], + [{'primary_metric': dict(m, status='ok', value=1., window='full_episode')}]): + with self.assertRaises(InfrastructureError): + metrics.aggregate(m, episodes) + with self.assertRaises(InfrastructureError): + metrics.summarize(m, [dict(CD=float('nan'))], 1) + + def test_aggregate_equal_weight_episodes(self): + m = metrics.definition('Cylinder_2D_Re200') + es = [dict(primary_metric=dict(m, status='ok', value=x)) for x in (1., 3.)] + self.assertEqual(metrics.aggregate(m, es)['value'], 2.) + + def test_policy_replay_reports_physical_mean_not_return_or_terminal_value(self): + class Env: + observation_space = action_space = SimpleNamespace(shape=(1,), dtype=np.float32, + low=np.array([-1.]), high=np.array([1.])) + def reset(self, seed): + self.i = 0 + return np.zeros(1), {} + def step(self, action): + self.i += 1 + cd = [9., 9., 2., 4.][self.i-1] + return np.zeros(1), -100., self.i == 4, False, {'forces': [[cd, 0.]]} + case = dict(id='Pinball_2D_Re100', environment='Pinball_2D_Re100', family='pinball', + horizon=4, primary_metric=metrics.definition('Pinball_2D_Re100')) + policy = Mock() + policy.act.return_value = [0.] + with tempfile.TemporaryDirectory() as directory: + env = ReplayAdapter(Env(), case, Path(directory)) + result = replay_episode(env, policy, case, 123) + self.assertEqual(result['return'], -400.) + self.assertEqual(result['primary_metric']['value'], 3.) + self.assertEqual(result['diagnostics']['CD'], 4.) + + +if __name__ == '__main__': + unittest.main() diff --git a/reproduction/files/db/dbd0de1be1edff50b25cfac1b898ccdc70d3b0d2e1f89996154663ac4ca91ec4/grader.py b/reproduction/files/db/dbd0de1be1edff50b25cfac1b898ccdc70d3b0d2e1f89996154663ac4ca91ec4/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..428bb45737b49eab61002bb5b2719d83422e7030 --- /dev/null +++ b/reproduction/files/db/dbd0de1be1edff50b25cfac1b898ccdc70d3b0d2e1f89996154663ac4ca91ec4/grader.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Trusted prediction-only grader; never imports a submission.""" +import argparse +import json +import time +from pathlib import Path + +from common import PRIVATE_SCHEMA, SNAPSHOT_SCHEMA, jsonl, sha256, write_json +from metrics import TASKS, flatten_metrics, score_task + + +def harbor_reward(values): + """Harbor parses reward.json as a flat object of finite numbers; strings, None and nested details + belong in report.json / status.json.""" + import math as _math + return {k: v for k, v in values.items() if isinstance(v, (int, float)) and _math.isfinite(v)} + + +def grade_task(task, prediction_path, label_path, ppi_affinity_std): + try: + truth = {row["example_id"]: row["label"] for row in jsonl(label_path)} + found = {} + for row in jsonl(prediction_path): + if (set(row) != {"example_id", "prediction"} or row["example_id"] not in truth + or row["example_id"] in found or not isinstance(row["prediction"], dict)): + raise ValueError("malformed/unknown/duplicate prediction") + found[row["example_id"]] = row["prediction"] + return score_task(task, truth, found, ppi_affinity_std) | {"invalid_reason": None} + except (OSError, ValueError, TypeError, KeyError, OverflowError, json.JSONDecodeError) as error: + return {"reward": 0.0, "invalid_reason": str(error)} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--sealed", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--labels", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--output", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--wait-seconds", type=int, default=43200) + args = parser.parse_args() + ready = args.sealed.parent / "READY" + deadline = time.monotonic() + args.wait_seconds + while not ready.is_file(): + if time.monotonic() > deadline: + raise TimeoutError("snapshot not published") + time.sleep(1) + snapshot = json.loads((args.sealed / "snapshot.json").read_text()) + private = json.loads((args.labels / "manifest.json").read_text()) + names = {f"{task}.jsonl" for task in TASKS} + if (ready.read_text().strip() != sha256(args.sealed / "snapshot.json") + or snapshot.get("schema") != SNAPSHOT_SCHEMA + or private.get("schema") != PRIVATE_SCHEMA + or private.get("public_input_manifest_sha256") != snapshot.get("input_manifest_sha256")): + raise ValueError("snapshot/private mismatch") + if set(snapshot) != {"schema", "input_manifest_sha256", "files"} or not set(snapshot["files"]) <= names: + raise ValueError("invalid snapshot files") + for name, digest in snapshot["files"].items(): + if sha256(args.sealed / name) != digest: + raise ValueError("sealed prediction hash mismatch") + for name, digest in private["files"].items(): + if name not in names or sha256(args.labels / name) != digest: + raise ValueError("private label hash mismatch") + std = private["fit_standard_deviation"]["ppi_affinity"] + details = {task: grade_task(task, args.sealed / f"{task}.jsonl", args.labels / f"{task}.jsonl", std) + for task in TASKS} + reward = sum(value["reward"] for value in details.values()) / len(TASKS) + args.output.mkdir(parents=True, exist_ok=True) + write_json(args.output / "report.json", + {"schema": "peer-protein-report/v1", "tasks": details, "reward": reward}) + flat = {"reward": reward} + for task, result in details.items(): + flatten_metrics(task, result, flat) + write_json(args.output / "reward.json", harbor_reward(flat)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/db/dbdc5f86407baa57bc7e97c5729954b5da93de1f8c04ccacd726bddbe7c42a3b/native_verifier.py b/reproduction/files/db/dbdc5f86407baa57bc7e97c5729954b5da93de1f8c04ccacd726bddbe7c42a3b/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a9a97c6d717ca5567e70e973a59af03504cb1b --- /dev/null +++ b/reproduction/files/db/dbdc5f86407baa57bc7e97c5729954b5da93de1f8c04ccacd726bddbe7c42a3b/native_verifier.py @@ -0,0 +1,354 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import shutil +import signal +import socket +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def enter_offline_namespace(): + import offline_network + record = offline_network.configure(STATE) + libc = ctypes.CDLL(None, use_errno=True) + for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)): + fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC) + try: + if libc.setns(fd, flag): + raise OSError(ctypes.get_errno(), 'enter offline verifier namespace') + finally: + os.close(fd) + if socket.if_nameindex() != [(1, 'lo')]: + raise RuntimeError('Offline verifier namespace has external interfaces') + return record + + +def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')): + """End the native waiting supervisor only after its authenticated seal.""" + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + seconds + sealed_ready = False + try: + while process.poll() is None: + if (sealed_root / 'READY').is_file(): + marker = json.loads((sealed_root / 'READY').read_text()) + snapshot = sealed_root / 'run/snapshot.json' + if (hashlib.sha256(snapshot.read_bytes()).hexdigest() != marker['snapshot_sha256'] + or json.loads(snapshot.read_text())['run_id'] != marker['run_id']): + raise RuntimeError('Native seal marker is inconsistent') + sealed_ready = True + break + if time.monotonic() >= deadline: + raise TimeoutError('Verifier inference budget exhausted') + time.sleep(.1) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode) + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + adapted = cfg.get('adapted_permissions', False) + if adapted: + import adapted_boundary + adapted_boundary.no_new_privileges() + os.setgroups([]) + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + crystal_cache_receipt = None + if cfg.get('isolated_crystal_dataset_cache'): + if plan['task'] != 'crystal-structure-generation' or phase != 'score': + raise RuntimeError('Crystal cache isolation is for trusted grading only') + import crystal_cache + crystal_cache_receipt = crystal_cache.prepare( + '/scorer-assets/huggingface/datasets', os.environ['HF_DATASETS_CACHE']) + crystal_cache_receipt['asset_manifest_sha256'] = hashlib.sha256( + Path('/scorer-assets/READY.json').read_bytes()).hexdigest() + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus'], strict_allocation=adapted) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + if adapted: + adapted_boundary.exact_gpu_allocation(gpu_policy) + else: + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + if cfg.get('gpu_runtime', 'torch') == 'torch' and not adapted: + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if cfg.get('local_benchmark_copy'): + status('copying_benchmark', task=plan['task'], role=phase) + # Folding's upstream evaluator runs inference and grading together. + # Give its non-root process a local readable copy, never relax Weka ACLs. + shutil.copytree('/source-benchmark', '/benchmark', symlinks=False) + for path in [Path('/benchmark'), *Path('/benchmark').rglob('*')]: + path.chmod(0o555 if path.is_dir() else 0o444) + if phase == 'inference': + if adapted:status('copying_submission', task=plan['task'], role=phase) + if cfg.get('native_uid_isolation'): + # The original PDE verifier explicitly supports this UID fallback. + # The mount is below a local root-only parent, never chmod shared data. + Path('/private').chmod(0o700) + Path('/tests').chmod(0o700) + elif plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + try: + agent = pwd.getpwuid(10001) + except KeyError: + subprocess.run(['/usr/sbin/useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + # Some native images precreate this empty container-local mountpoint. + # rmdir fails closed if it contains anything; never remove existing logs. + if Path('/logs/verifier').is_dir() and not Path('/logs/verifier').is_symlink(): + Path('/logs/verifier').rmdir() + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + if adapted and cfg.get('network_policy') != 'policy-children-only': + adapted_boundary.restrict_network() + elif not offline and not adapted: + runtime.deny_network() + if not adapted: + writable_roots = ['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc', + *cfg.get('writable_runtime_paths', [])] + if crystal_cache_receipt: + # The native image links /scorer-assets beneath /workspace. A + # writable ancestor defeats a read-only Landlock child rule. + # Trusted grading needs its output and scratch directories only. + writable_roots.remove('/workspace') + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets'], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=writable_roots) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + if adapted: + source_audit = adapted_boundary.audit_source_permissions( + ['/operator', '/submission-source', '/source-benchmark', '/benchmark', '/data', '/labels', '/private'], + untrusted_uids=tuple(range(10001, 10009))) + else: + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if crystal_cache_receipt: + try: + fd = os.open('/scorer-assets/READY.json', os.O_WRONLY | os.O_CLOEXEC) + except PermissionError: + crystal_cache_receipt['asset_write_denied'] = True + else: + os.close(fd) + raise RuntimeError('Prepared scorer assets remain writable') + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' and not adapted else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())); ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + if cfg.get('gpu_runtime') == 'jax': + probe = ('import jax; import jax.numpy as jnp; ' + f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in d.device_kind for d in jax.devices("gpu")); ' + 'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 ' + 'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + if adapted and plan['task'] == 'fluid-flow-control': + # native_runtime.sh loads a module-provided libpython. Preserve + # only these runtime settings, never credentials, in the probe. + for key in ('PATH', 'LD_LIBRARY_PATH', 'OMP_NUM_THREADS', + 'OPENBLAS_NUM_THREADS', 'XLA_PYTHON_CLIENT_PREALLOCATE'): + if key in os.environ: + probe_env[key] = os.environ[key] + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + def dependency_identity(): + os.setgroups([]); os.setgid(10001); os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + cache=Path('/tmp/verifier-cache');cache.mkdir(exist_ok=True) + os.chown(cache,10001,10001) + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True, + preexec_fn=dependency_identity if cfg.get('untrusted_whole_verifier') else None) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': ('seccomp in unprivileged policy children; trusted simulator retains MPI sockets' + if cfg.get('network_policy') == 'policy-children-only' else + 'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children'), + 'offline_namespace': offline, + 'source_mounts': f'POSIX permission audit ({source_audit} entries); non-root submission' if adapted else 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan.get('label_isolated', plan['task'] != 'protein-folding-prediction'), + 'adapted_execution': adapted, + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + if cfg.get('stop_after_sealed_ready'): + # The native supervisor has already killed all model processes and + # sealed/hashes its predictions before writing READY. End only its + # wait-for-grader loop; the unchanged grader runs in a separate job. + result = run_until_sealed(cfg['command'], log, remaining) + else: + def run_identity(): + os.setgroups([]) + os.setgid(10001) + os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + os.chown(STATE / 'results', 10001, 10001) + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True, + preexec_fn=run_identity if cfg.get('untrusted_whole_verifier') else None) + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + if cfg.get('verify_crystal_assets_after'): + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted before post-score asset validation') + with (STATE / 'asset-validation-after.log').open('w') as log: + subprocess.run([cfg['driver_python'], '-c', + 'import sys;sys.path.insert(0,"/tests");from pathlib import Path;' + 'from grader import validate_assets;validate_assets(Path("/scorer-assets"));' + 'print("ORIGINAL_SCORER_ASSET_DIGEST_OK")'], + stdout=log, stderr=subprocess.STDOUT, timeout=remaining, check=True) + if hashlib.sha256(Path('/scorer-assets/READY.json').read_bytes()).hexdigest() != crystal_cache_receipt['asset_manifest_sha256']: + raise RuntimeError('Scorer asset manifest changed during grading') + crystal_cache_receipt['original_asset_digest_after'] = 'passed' + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + elapsed = time.monotonic() - entered + reward_path = STATE / 'results/reward.json' + if phase == 'score': + score_root = Path('/sealed/results') + if cfg.get('results_by_run_id'): + score_root /= json.loads(Path('/sealed/READY').read_text())['run_id'] + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = score_root / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/dc/dcbb09034cd26d31a03a8d9c494b88b8f1837ceb7d8172659baa99fbbba6af58/test_downstream_encoder.py b/reproduction/files/dc/dcbb09034cd26d31a03a8d9c494b88b8f1837ceb7d8172659baa99fbbba6af58/test_downstream_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..3ba57f1cc1bc1a6541834416c73080ac523191a7 --- /dev/null +++ b/reproduction/files/dc/dcbb09034cd26d31a03a8d9c494b88b8f1837ceb7d8172659baa99fbbba6af58/test_downstream_encoder.py @@ -0,0 +1,68 @@ +"""Portable wrapper preserves weights/features and enables encoder gradients.""" + +import hashlib +import json +from pathlib import Path +import sys +import tempfile +import unittest +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/downstream")) +from portable_encoder import PortableAWFEncoder +from olmoearth_pretrain.nn.flexi_vit import EncoderConfig +from olmoearth_pretrain.nn.pooling import pool_unmasked_tokens, PoolingType +from rslearn.train.model_context import ModelContext, RasterImage + + +class TestAdapter(unittest.TestCase): + def test_exact_features_gradients_and_provenance(self): + torch.set_num_threads(2) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + config = EncoderConfig( + supported_modality_names=["sentinel2_l2a"], + embedding_size=32, + num_heads=4, + depth=1, + drop_path=0.0, + ) + model = config.build() + torch.save(model.state_dict(), root / "encoder.pt") + (root / "config.json").write_text(json.dumps(config.as_dict())) + with (root / "encoder.pt").open("rb") as f: + sha = hashlib.file_digest(f, "sha256").hexdigest() + provenance = {"origin": "own_from_scratch_training", "encoder_sha256": sha} + (root / "provenance.json").write_text(json.dumps(provenance)) + adapter = PortableAWFEncoder(str(root)).eval() + for key, value in model.state_dict().items(): + self.assertTrue(torch.equal(value, adapter.model.state_dict()[key])) + context = ModelContext( + inputs=[{"sentinel2_l2a": RasterImage(torch.randn(12, 1, 8, 8))}], + metadatas=[], + ) + sample, _, _ = adapter._prepare_modality_inputs_legacy(context) + model.eval() + expected = pool_unmasked_tokens( + model(sample, patch_size=4, fast_pass=True)["tokens_and_masks"], + PoolingType.MEAN, + spatial_pooling=True, + ).permute(0, 3, 1, 2) + actual = adapter(context).feature_maps[0] + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + adapter.train() + adapter(context).feature_maps[0].square().mean().backward() + self.assertTrue( + any( + p.grad is not None and torch.any(p.grad != 0) + for p in adapter.model.parameters() + ) + ) + provenance["origin"] = "official_public_pretrained_reference" + (root / "provenance.json").write_text(json.dumps(provenance)) + with self.assertRaisesRegex(ValueError, "Ineligible"): + PortableAWFEncoder(str(root)) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/dd/dd789172f4b9d4d775c43628a9b326e95c86ce4fb53f625f74a8b1432a8c1db2/raw_features.py b/reproduction/files/dd/dd789172f4b9d4d775c43628a9b326e95c86ce4fb53f625f74a8b1432a8c1db2/raw_features.py new file mode 100644 index 0000000000000000000000000000000000000000..bd04fb7eeaab3022b1381244f5054ff699f16ddb --- /dev/null +++ b/reproduction/files/dd/dd789172f4b9d4d775c43628a9b326e95c86ce4fb53f625f74a8b1432a8c1db2/raw_features.py @@ -0,0 +1,52 @@ +"""Seasonal band means/stds: no learned representation, no labels.""" + +import argparse +from pathlib import Path +import sys +import h5py +import numpy as np + +for _starter in ("baseline/starter", "starter"): # repository / workspace layout + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / _starter)) +from infer import normalized_pixels, Modality + +p = argparse.ArgumentParser() +p.add_argument("--input", type=Path, required=True) +p.add_argument("--output", type=Path, required=True) +a = p.parse_args() +features = [] +with h5py.File(a.input, "r") as h: + ids = h["ids"].asstr()[:] + for i in range(0, len(ids), 64): + pixels = normalized_pixels(h, i, i + 64) + pieces = [] + for name, arr in pixels.items(): + if name + "_valid" in h: + valid = h[name + "_valid"][i : i + 64].astype(bool) + if valid.ndim == 2: + valid = np.repeat( + valid[:, :, None], Modality.get(name).num_band_sets, axis=2 + ) + for j in range(len(arr)): + for g, bandset in enumerate(Modality.get(name).band_sets): + bands = [ + Modality.get(name).band_order.index(b) + for b in bandset.bands + ] + good = np.flatnonzero(valid[j, :, g]) + for t in np.flatnonzero(~valid[j, :, g]): + for band in bands: + arr[j, :, :, t, band] = ( + arr[j, :, :, good[np.argmin(abs(good - t))], band] + if len(good) + else 0 + ) + pieces.extend( + [ + arr.mean(axis=(1, 2)).reshape(len(arr), -1), + arr.std(axis=(1, 2)).reshape(len(arr), -1), + ] + ) + features.append(np.concatenate(pieces, axis=1)) +a.output.parent.mkdir(parents=True, exist_ok=True) +np.savez(a.output, ids=np.asarray(ids, dtype=str), features=np.concatenate(features)) diff --git a/reproduction/files/dd/dda0feb126c718b34652024429d6c03cc00737be6fa4e886499fee396394ec07/test_metrics.py b/reproduction/files/dd/dda0feb126c718b34652024429d6c03cc00737be6fa4e886499fee396394ec07/test_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..21005e6181f6f7b33e0076e4958e0c58217f4e5c --- /dev/null +++ b/reproduction/files/dd/dda0feb126c718b34652024429d6c03cc00737be6fa4e886499fee396394ec07/test_metrics.py @@ -0,0 +1,116 @@ +"""Scientific invariants for the surface-code scoring and split contract.""" +from __future__ import annotations + +from pathlib import Path +import sys +import tempfile +import unittest + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" / "baselines")) +from classical import discover_conditions, expected_conditions, split_indices +from metrics import FIT_ROUNDS, compare_paired_conditions, summarize_conditions, wilson_interval + + +def synthetic_counts( + *, distance: int = 3, basis: str = "X", center: tuple[int, int] = (3, 5), + epsilon: float = 0.03, intercept: float = -0.08, total: int = 1_000_000, +) -> dict[str, dict[str, int]]: + return { + f"surface_code_b{basis}_d{distance}_r{rounds:02d}_center_{center[0]}_{center[1]}": { + "errors": round(total * (1 - np.exp(intercept) * (1 - 2 * epsilon)**rounds) / 2), + "total": total, + } + for rounds in (1, *FIT_ROUNDS) + } + + +class MetricsTests(unittest.TestCase): + def test_free_intercept_recovers_round_error_and_round_one_is_excluded(self) -> None: + counts = synthetic_counts() + counts["surface_code_bX_d3_r01_center_3_5"]["errors"] = 900_000 + summary = summarize_conditions(counts, bootstrap_samples=256, seed=17) + fit = summary["per_group"]["d3_bX_center_3_5"] + self.assertAlmostEqual(fit["logical_error_per_round"], 0.03, places=6) + self.assertAlmostEqual(fit["intercept"], -0.08, places=5) + self.assertAlmostEqual(fit["zero_round_fidelity"], float(np.exp(-0.08)), places=5) + self.assertGreater(fit["weighted_log_fidelity_r_squared"], 0.999999) + self.assertGreater(fit["unweighted_log_fidelity_r_squared"], 0.999999) + self.assertEqual(fit["diagnostic_flags"], []) + lower, upper = fit["logical_error_per_round_ci95"] + self.assertLess(lower, 0.03) + self.assertGreater(upper, 0.03) + self.assertEqual(fit["degrees_of_freedom"], 10) + + def test_macro_is_mean_of_separate_fits_and_suppression_is_ratio(self) -> None: + counts = synthetic_counts(epsilon=0.02, intercept=-0.1) + counts.update(synthetic_counts(basis="Z", epsilon=0.06, intercept=-0.7)) + counts.update(synthetic_counts(distance=5, center=(5, 5), epsilon=0.02)) + summary = summarize_conditions(counts, bootstrap_samples=0) + self.assertAlmostEqual(summary["macro"]["d3"]["logical_error_per_round"], 0.04, places=6) + self.assertAlmostEqual(summary["macro"]["error_suppression_d3_over_d5"]["value"], 2.0, places=4) + + def test_missing_round_and_invalid_fidelity_raise(self) -> None: + counts = synthetic_counts() + counts.pop("surface_code_bX_d3_r05_center_3_5") + with self.assertRaisesRegex(ValueError, "expected each fit round"): + summarize_conditions(counts) + counts = synthetic_counts() + counts["surface_code_bX_d3_r05_center_3_5"]["errors"] = 500_000 + with self.assertRaisesRegex(ValueError, "P_fail < 0.5"): + summarize_conditions(counts) + + def test_low_intercept_and_unphysical_rate_are_reported_without_clipping(self) -> None: + counts = synthetic_counts(epsilon=-0.002, intercept=-3.0) + summary = summarize_conditions(counts, bootstrap_samples=0) + fit = summary["per_group"]["d3_bX_center_3_5"] + self.assertLess(fit["logical_error_per_round"], 0) + self.assertAlmostEqual(fit["zero_round_fidelity"], float(np.exp(-3)), places=4) + self.assertIn("unphysical_negative_logical_error_per_round", fit["diagnostic_flags"]) + self.assertIn("extrapolated_zero_round_fidelity_below_0.1", fit["diagnostic_flags"]) + self.assertEqual(len(summary["per_condition"]), 13) + + def test_flat_fidelity_has_undefined_r_squared_and_no_false_perfect_fit(self) -> None: + counts = synthetic_counts(epsilon=0, intercept=-1) + summary = summarize_conditions(counts, bootstrap_samples=0) + fit = summary["per_group"]["d3_bX_center_3_5"] + self.assertIsNone(fit["weighted_log_fidelity_r_squared"]) + self.assertIsNone(fit["unweighted_log_fidelity_r_squared"]) + self.assertIn("constant_log_fidelity_r_squared_undefined", fit["diagnostic_flags"]) + + def test_paired_identical_decoders_have_exact_zero_difference_interval(self) -> None: + counts = synthetic_counts(total=10_000) + errors = { + name: np.arange(record["total"]) < record["errors"] for name, record in counts.items() + } + comparison = compare_paired_conditions(errors, errors, bootstrap_samples=128, seed=42) + for result in comparison["comparisons"].values(): + self.assertEqual(result["logical_error_per_round_a_minus_b"], 0) + self.assertEqual(result["ci95"], [0, 0]) + with self.assertRaisesRegex(ValueError, "identical conditions"): + compare_paired_conditions(errors, {}) + + def test_wilson_zero_errors_retains_nonzero_upper_uncertainty(self) -> None: + lower, upper = wilson_interval(0, 100) + self.assertAlmostEqual(lower, 0) + self.assertGreater(upper, 0.03) + self.assertLess(upper, 0.04) + + def test_train_validation_and_test_are_disjoint_and_cover_all_shots(self) -> None: + train, validation, test = [split_indices(split) for split in ("train", "validation", "test")] + self.assertEqual(tuple(map(len, (train, validation, test))), (19880, 5120, 25000)) + all_indices = np.concatenate((train, validation, test)) + np.testing.assert_array_equal(np.sort(all_indices), np.arange(50000)) + self.assertTrue(np.all(validation % 2 == 0)) + self.assertTrue(np.all(test % 2 == 1)) + + def test_full_suite_missing_condition_is_fatal(self) -> None: + self.assertEqual(len(expected_conditions()), 130) + with tempfile.TemporaryDirectory() as temporary: + with self.assertRaisesRegex(ValueError, "Expected all 130"): + discover_conditions(Path(temporary)) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/df/df9261979dccc2e709b4e6cdafb2fe18df1d139799b5dbcefb1581689eed6763/gpu_access.py b/reproduction/files/df/df9261979dccc2e709b4e6cdafb2fe18df1d139799b5dbcefb1581689eed6763/gpu_access.py new file mode 100644 index 0000000000000000000000000000000000000000..851abae655a55ed2d47149885256eff5c58a7784 --- /dev/null +++ b/reproduction/files/df/df9261979dccc2e709b4e6cdafb2fe18df1d139799b5dbcefb1581689eed6763/gpu_access.py @@ -0,0 +1,108 @@ +"""Enforce the task's NVIDIA device count, independent of CUDA environment overrides.""" +import ctypes +import errno +import json +import os +from pathlib import Path +import re +import subprocess +import xml.etree.ElementTree as ET + +READ_WRITE = (1 << 1) | (1 << 2) + + +def configure(state, count=1, strict_allocation=False): + # Device minor numbers are in the XML inventory; they are not supported as + # --query-gpu fields by all deployed NVIDIA driver versions. + devices = ET.fromstring(subprocess.check_output( + ["nvidia-smi", "-q", "-x"], text=True)).findall("gpu") + if not isinstance(count, int) or count < 1 or len(devices) < count: + raise RuntimeError(f"Need {count} allocated GPUs; found {len(devices)}") + if strict_allocation and len(devices) != count: + raise RuntimeError(f"Refusing research: expected exactly {count} allocated GPUs, found {len(devices)}") + allowed, uuids = [], [] + for device in devices[:count]: + minor, uuid = device.findtext("minor_number", ""), device.findtext("uuid", "") + if not minor.isdigit() or not uuid.startswith("GPU-"): + raise RuntimeError("Unexpected NVIDIA device inventory") + path = Path("/dev") / f"nvidia{minor}" + if not path.is_char_device(): + raise RuntimeError("Selected GPU device node is missing") + allowed.append(path) + uuids.append(uuid) + if len(set(allowed)) != count or len(set(uuids)) != count: + raise RuntimeError("Duplicate GPU device inventory") + denied = sorted(str(p) for p in Path("/dev").iterdir() + if re.fullmatch(r"nvidia\d+", p.name) and p not in allowed) + record = {"allowed_device": str(allowed[0]), "uuid": uuids[0], "denied_devices": denied, + "allowed_devices": [str(p) for p in allowed], "allowed_uuids": uuids, + "count": count, + "strict_allocation": strict_allocation, "allocated_count": len(devices), + "other_allocated_uuids": [d.findtext("uuid") for d in devices[count:]], + "mechanism": "landlock-read-write-device-access"} + path = state / "gpu-access.json" + path.write_text(json.dumps(record, indent=2) + "\n") + path.chmod(0o644) + if path.stat().st_uid != 0: + raise RuntimeError("GPU access policy must be root-owned") + return record + + +def restrict_device_access(denied): + """Allow the existing container filesystem except reads/writes of denied nodes. + + Landlock attaches restrictions to this tool process and descendants. It does + not chmod, bind-mount over, or otherwise modify shared host device nodes. + """ + libc = ctypes.CDLL(None, use_errno=True) + if libc.syscall(444, 0, 0, 1) < 1: + raise RuntimeError("Landlock device isolation is unavailable") + class Ruleset(ctypes.Structure): + _fields_ = [("handled_access_fs", ctypes.c_uint64)] + class Beneath(ctypes.Structure): + _pack_ = 1 + _fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int)] + attr = Ruleset(READ_WRITE) + fd = libc.syscall(444, ctypes.byref(attr), ctypes.sizeof(attr), 0) + if fd < 0: + raise OSError(ctypes.get_errno(), "landlock_create_ruleset") + try: + # Grant every root child except /dev, then /dev children individually. + # READ_DIR/EXECUTE and other access kinds are not restricted here. + paths = [p for p in Path("/").iterdir() if p.name != "dev"] + paths += [p for p in Path("/dev").iterdir() if str(p) not in set(denied)] + for path in paths: + try: + parent = os.open(path, os.O_PATH | os.O_CLOEXEC) + except FileNotFoundError: + continue # Optional dangling system symlinks are not grants. + try: + rule = Beneath(READ_WRITE, parent) + if libc.syscall(445, fd, 1, ctypes.byref(rule), 0): + if ctypes.get_errno() == errno.EBADFD: + continue # E.g. /dev/stdout resolves to an existing pipe. + raise OSError(ctypes.get_errno(), f"landlock_add_rule: {path}") + finally: + os.close(parent) + if libc.prctl(38, 1, 0, 0, 0) or libc.syscall(446, fd, 0): + raise OSError(ctypes.get_errno(), "landlock_restrict_self") + finally: + os.close(fd) + + +def enforce(state): + policy = state / "gpu-access.json" + stat = policy.stat() + if stat.st_uid != 0 or stat.st_mode & 0o022: + raise RuntimeError("Untrusted GPU access policy") + record = json.loads(policy.read_text()) + restrict_device_access(record["denied_devices"]) + for name in record["denied_devices"]: + try: + fd = os.open(name, os.O_RDWR) + except PermissionError: + continue + else: + os.close(fd) + raise RuntimeError("An extra GPU device remains accessible") + return record diff --git a/reproduction/files/df/dfc0501a02e86463acf9c5aef06fbb649715c830242e1853f47301e7c6175fe8/metrics.py b/reproduction/files/df/dfc0501a02e86463acf9c5aef06fbb649715c830242e1853f47301e7c6175fe8/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..33a64166b89d56d1f58e969697f7978be24ecd26 --- /dev/null +++ b/reproduction/files/df/dfc0501a02e86463acf9c5aef06fbb649715c830242e1853f47301e7c6175fe8/metrics.py @@ -0,0 +1,158 @@ +"""Frozen per-case physical reporting metrics; never read candidate scores. + +Native rewards remain available to learners/diagnostic logs. This specification +does not define a cross-case aggregate or change any source physics. +""" +import hashlib +import json +import math +from pathlib import Path + +from protocol import InfrastructureError + +VERSION = 'hydrogym-physical-metrics/v1' +DEFINITIONS = { + 'drag_cd': dict(name='平均阻力系数 CD', units='dimensionless', direction='lower_is_better', + window='last_half', quantity='CD', reduction='mean'), + 'lift_drag': dict(name='平均升阻比 L/D', units='dimensionless', direction='higher_is_better', + window='last_half', quantity='lift_drag', reduction='mean'), + 'gust_load_error': dict(name='平均加权载荷偏差', units='coefficient', direction='lower_is_better', + window='full_episode', quantity='gust_load_error', reduction='mean'), + 'nozzle_angle_mae': dict(name='推力方向平均绝对误差', units='degree', direction='lower_is_better', + window='full_episode', quantity='angle_error_deg', reduction='mean'), + 'tke': dict(name='平均扰动动能 TKE', units='native_nondimensional', direction='lower_is_better', + window='last_half', quantity='TKE', reduction='mean'), + 'wall_shear': dict(name='平均壁面剪切应力', units='native_nondimensional', direction='lower_is_better', + window='last_half', quantity='wall_shear', reduction='mean'), +} +GROUPS = { + 'drag_cd': '''Cube_3D_Re300 Cube_3D_Re3700 + Cylinder_2D_Re1000 Cylinder_2D_Re200 Cylinder_2D_Re3900 + Cylinder_3D_Re200 Cylinder_3D_Re3900 + Pinball_2D_Re100 Pinball_2D_Re150 Pinball_2D_Re30 Pinball_2D_Re75 + Pinball_3D_Re100 Pinball_3D_Re150 Pinball_3D_Re30 Pinball_3D_Re75 + Sphere_3D_Re300 SquareCylinder_2D_Re1000 SquareCylinder_2D_Re200 SquareCylinder_3D_Re200''', + 'lift_drag': '''NACA0012_2D_Re1000_AOA20 NACA0012_2D_Re1000_AOA40 + NACA0012_2D_Re100_AOA20 NACA0012_2D_Re100_AOA40 + NACA0012_3D_Re1000_AOA20 NACA0012_3D_Re100_AOA20 NACA0012_3D_Re100_AOA40''', + 'gust_load_error': '''NACA0012Gust_2D_Re1000_AOA20 NACA0012Gust_2D_Re1000_AOA40 + NACA0012Gust_2D_Re100_AOA20 NACA0012Gust_2D_Re100_AOA40 + NACA0012Gust_3D_Re1000_AOA20 NACA0012Gust_3D_Re1000_AOA40 + NACA0012Gust_3D_Re100_AOA20 NACA0012Gust_3D_Re100_AOA40 NACA0012Gust_3D_Re50000_AOA12''', + 'nozzle_angle_mae': 'Nozzle2D_coarse Nozzle2D_fine', + 'tke': 'Kolmogorov_2D', + 'wall_shear': 'Channel_3D_Retau180', +} +CASE_METRICS = {name: key for key, names in GROUPS.items() for name in names.split()} + + +def definition(name): + try: + key = CASE_METRICS[name] + except KeyError as error: + raise InfrastructureError(f'No frozen primary metric for {name}') from error + result = dict(version=VERSION, id=key, **DEFINITIONS[key]) + if key == 'gust_load_error': + configs = json.loads((Path(__file__).resolve().parent.parent / 'data/native-configs.json').read_text()) + config = next(c['config']['maia'] for c in configs['configs'] if c['name'] == name) + result['target'] = dict(CL=config['unperturbed_avg_lift'], + CD=config['unperturbed_avg_drag'], omega=config['omega']) + return result + + +def registry(): + return {name: definition(name) for name in sorted(CASE_METRICS)} + + +def registry_hash(): + return hashlib.sha256(json.dumps(registry(), sort_keys=True, separators=(',', ':')).encode()).hexdigest() + + +def sample(env, case, info, reward): + """Read physical outputs after one unchanged native step (no second CFD step). + + Pinball already exposes nondimensional coefficients; other MAIA classes + expose raw lattice forces. Sphere uses pi*D^2/4, not the prism area. + Channel's pinned reward is exactly -wss, with no action penalty; this one + identity preserves its existing, hash-frozen actuator-clock adapter. + """ + import numpy as np + name = case['environment'] + metric = case.get('primary_metric') or definition(name) + key = metric['id'] + base = getattr(env, 'unwrapped', env) + if key in ('drag_cd', 'lift_drag', 'gust_load_error'): + forces = np.asarray(info['forces'], dtype=np.float64) + if forces.ndim == 1: + forces = forces[None, :] + if forces.ndim != 2 or forces.shape[0] == 0 or forces.shape[1] < 2 or not np.isfinite(forces).all(): + raise InfrastructureError('Missing/invalid per-body force measurements') + if not name.startswith('Pinball_'): + area = (math.pi / 4 * (base.referenceLength / base.dX) ** 2 + if name.startswith('Sphere_') else base.referenceLength / base.dX * base.zLength / base.dX) + forces = np.asarray(base.compute_nondim_coefficients(forces=forces, density=1.0, + referenceVelocity=base.Ma / math.sqrt(3), projectionLength=area)) + values = dict(CD=float(forces[:, 0].sum()), CL=float(forces[:, 1].sum())) + if forces.shape[1] > 2: + values['CS'] = float(forces[:, 2].sum()) + if key == 'lift_drag': + # Keep the source's admissible lift/drag domain; do not replace an + # inadmissible physical ratio by its artificial -100 training penalty. + valid = values['CD'] >= 1e-6 and values['CL'] >= 0 + values['lift_drag_valid'] = float(valid) + values['lift_drag'] = values['CL'] / values['CD'] if valid else 0.0 + elif key == 'gust_load_error': + target = metric['target'] + actual = dict(CL=float(base.unperturbed_avg_lift), CD=float(base.unperturbed_avg_drag), omega=float(base.omega)) + if actual != target: + raise InfrastructureError('Gust target/weight changed from frozen source') + values['lift_error'] = abs(values['CL'] - target['CL']) + values['drag_error'] = abs(values['CD'] - target['CD']) + values['gust_load_error'] = values['lift_error'] + target['omega'] * values['drag_error'] + elif key == 'nozzle_angle_mae': + values = dict(angle_error_deg=float(abs(np.asarray(info['target_angle']).item() + - np.asarray(info['thrust_angle']).item()) * 180 / math.pi)) + elif key == 'tke': + values = dict(TKE=float(info['mean_tke'])) + elif key == 'wall_shear': + values = dict(wall_shear=-float(reward)) + else: + raise InfrastructureError('Unimplemented primary metric') + if not all(math.isfinite(v) for v in values.values()): + raise InfrastructureError('Nonfinite physical measurement') + return values + + +def summarize(metric, rows, horizon): + if len(rows) != horizon or horizon <= 0: + raise InfrastructureError('Primary metric requires a complete episode') + start = horizon // 2 if metric['window'] == 'last_half' else 0 + selected = rows[start:] + result = dict(metric, samples=len(selected), first_control=start + 1, last_control=horizon) + if metric['id'] == 'lift_drag' and any(r['lift_drag_valid'] != 1 for r in selected): + return dict(result, status='invalid_operating_regime', value=None, + reason='L/D requires CD >= 1e-6 and CL >= 0 at every scored sample') + values = [r[metric['quantity']] for r in selected] + if any(type(v) not in (float, int) or not math.isfinite(v) for v in values): + raise InfrastructureError('Missing/nonfinite primary metric samples') + value = math.fsum(values) / len(values) + if not math.isfinite(value): + raise InfrastructureError('Nonfinite primary metric mean') + return dict(result, status='ok', value=value) + + +def aggregate(metric, episodes): + """Equal-weight complete episode metrics, never reward or terminal info.""" + measured = [e.get('primary_metric', {}) for e in episodes] + if not measured or any(any(m.get(k) != v for k, v in metric.items()) for m in measured): + raise InfrastructureError('Missing/mismatched physical metric definition') + for m in measured: + if m.get('status') == 'invalid_operating_regime': + if metric['id'] != 'lift_drag' or m.get('value') is not None: + raise InfrastructureError('Invalid operating-regime outcome') + elif m.get('status') != 'ok' or type(m.get('value')) not in (int, float) or not math.isfinite(m['value']): + raise InfrastructureError('Invalid physical metric episode value') + if any(m.get('status') == 'invalid_operating_regime' for m in measured): + return dict(metric, status='invalid_operating_regime', value=None, episodes=len(measured)) + values = [m['value'] for m in measured] + return dict(metric, status='ok', value=math.fsum(values) / len(values), episodes=len(values)) diff --git a/reproduction/files/e3/e3a184f88b91ab69aa32a0d131317ca865ba0d8e35640b2595d9e6b32854069e/grader.py b/reproduction/files/e3/e3a184f88b91ab69aa32a0d131317ca865ba0d8e35640b2595d9e6b32854069e/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..0d9862591731c2276a0f0094812883fd1d8263bc --- /dev/null +++ b/reproduction/files/e3/e3a184f88b91ab69aa32a0d131317ca865ba0d8e35640b2595d9e6b32854069e/grader.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Trusted grader: check the sealed snapshot, then score every suite against the test references. + +It never imports submission code. Physical suites use environment/evaluation/score.py in the +pinned MP2020 scoring runtime (/opt/scoring-venv); the other suites use score_extra.py. +All 15 raw metrics remain available; reward.json also includes the fixed eight-suite +Crystal Potential Score v2 (0–100) and reward = score / 100. +""" +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +import time +from pathlib import Path + +from verifier_common import sha256, tree_sha256, write_json + +EVALUATION = Path("/evaluation") if Path("/evaluation").is_dir() else Path(__file__).resolve().parents[1] / "environment/evaluation" +sys.path.insert(0, str(EVALUATION)) +from score_extra import SCORERS, score as score_extra # noqa: E402 +from aggregate import expanded_score # noqa: E402 + +SCHEMA = "atomistic-materials-prediction-snapshot/v2" +SCORING_PYTHON = "/opt/scoring-venv/bin/python" +# Lower is better for every reward key except F1. +REWARD_KEYS = { + ("physical", "discovery", "F1"): "discovery_F1", + ("physical", "discovery", "hull_MAE_meV_per_atom"): "discovery_hull_MAE_meV_per_atom", + ("physical", "phonons", "max_freq"): "phonon_max_freq_MAE_K", + ("physical", "phonons", "avg_freq"): "phonon_avg_freq_MAE_K", + ("physical", "phonons", "entropy"): "phonon_entropy_MAE", + ("physical", "phonons", "heat_capacity"): "phonon_heat_capacity_MAE", + ("physical", "phonons", "free_energy"): "phonon_free_energy_MAE", + ("physical", "elasticity", "bulk_modulus_vrh"): "bulk_modulus_MAE_GPa", + ("physical", "elasticity", "shear_modulus_vrh"): "shear_modulus_MAE_GPa", + ("kappa", "kappa_SRME"): "kappa_SRME", + ("mof", "bulk_modulus_MAPE_pct"): "mof_bulk_modulus_MAPE_pct", + ("amorphous", "energy_RelRMSE_pct_mean"): "amorphous_energy_RelRMSE_pct", + ("amorphous", "force_RelRMSE_pct_mean"): "amorphous_force_RelRMSE_pct", + ("cleavage", "cleavage_relMAE_pct"): "cleavage_relMAE_pct", + ("neb", "barrier_MAE_eV"): "neb_barrier_MAE_eV", +} + + +def harbor_reward(values): + """Harbor parses reward.json as a flat object of finite numbers; strings, None and nested details + belong in report.json / status.json.""" + import math as _math + return {k: v for k, v in values.items() if isinstance(v, (int, float)) and _math.isfinite(v)} + + +def score_physical(predictions: Path, references: Path, output: Path) -> dict: + proc = subprocess.run([SCORING_PYTHON, str(EVALUATION / "score.py"), "--references", str(references), + "--predictions", str(predictions), "--output", str(output)], + capture_output=True, text=True) + if output.is_file(): + return json.loads(output.read_text()) + return {"valid": False, "error": (proc.stderr or proc.stdout)[-2000:]} + + +def flatten(report: dict) -> dict: + reward = {} + for path, name in REWARD_KEYS.items(): + value = report.get(path[0], {}) + value = value.get("metrics", value) if path[0] == "physical" else value + for key in path[1:]: + value = value.get(key, {}) if isinstance(value, dict) else {} + if isinstance(value, dict): + value = value.get("MAE") + reward[name] = value if isinstance(value, (int, float)) else None + return reward + + +def main(): + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--sealed", type=Path, required=True) + p.add_argument("--labels", type=Path, required=True, help="test//{inputs,references}") + p.add_argument("--output", type=Path, required=True) + p.add_argument("--wait-seconds", type=int, default=172800) + a = p.parse_args() + ready = a.sealed.parent / "READY" + deadline = time.monotonic() + a.wait_seconds + while not ready.is_file(): + if time.monotonic() >= deadline: + raise TimeoutError("prediction snapshot was not published") + time.sleep(2) + snapshot = json.loads((a.sealed / "snapshot.json").read_text()) + if ready.read_text().strip() != sha256(a.sealed / "snapshot.json") or snapshot.get("schema") != SCHEMA: + raise ValueError("invalid sealed snapshot") + a.output.mkdir(parents=True, exist_ok=True) + report = {"schema": "atomistic-materials-report/v2", "split": "test", "runs": snapshot["runs"]} + for suite, digest in snapshot["predictions"].items(): + pred = a.sealed / suite + inputs, refs = a.labels / suite / "inputs", a.labels / suite / "references" + try: + if tree_sha256(pred) != digest: + raise ValueError("sealed prediction hash mismatch") + if tree_sha256(inputs) != snapshot["inputs"][suite]: + raise ValueError("sealed predictions were made on other inputs") + if suite == "physical": + report[suite] = score_physical(pred, refs, a.output / "physical-score.json") + elif (pred / "run.json").is_file(): + report[suite] = score_extra(suite, pred, inputs, refs) + else: # the run died before writing anything: every case is a failure + report[suite] = {"suite": suite, **SCORERS[suite]({}, refs), "complete": False} + except (ValueError, KeyError, OSError, SystemExit) as error: + report[suite] = {"valid": False, "error": f"{type(error).__name__}: {error}"[:2000]} + reward = flatten(report) + report["aggregate"] = expanded_score( + reward, valid=not any(r.get("valid") is False for r in report.values() if isinstance(r, dict)) + ) + reward["crystal_potential_score"] = report["aggregate"]["score"] + reward["reward"] = report["aggregate"]["score"] / 100 + write_json(a.output / "report.json", report) + write_json(a.output / "reward.json", harbor_reward(reward)) + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/e4/e44a845532d20a8900f8013065530db70a2abaea07519b94f0b0413721c393d8/docker-compose.yaml b/reproduction/files/e4/e44a845532d20a8900f8013065530db70a2abaea07519b94f0b0413721c393d8/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..567502e6e988cbf841de9a1ba004f57ba5af2139 --- /dev/null +++ b/reproduction/files/e4/e44a845532d20a8900f8013065530db70a2abaea07519b94f0b0413721c393d8/docker-compose.yaml @@ -0,0 +1,36 @@ +volumes: + sealed: + verifier_logs: + +services: + main: + build: . + network_mode: none + shm_size: "16gb" + volumes: + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the materialized data root}/public/verifier + target: /benchmark + read_only: true + bind: + create_host_path: false + - sealed:/sealed + - verifier_logs:/logs/verifier + healthcheck: + test: ["CMD-SHELL", "test -s /benchmark/manifest.json && test -s /benchmark/fluorescence.jsonl"] + interval: 5s + timeout: 5s + retries: 3 + + grader: + build: . + network_mode: none + command: ["python3", "/tests/grader.py", "--sealed", "/sealed/run", "--labels", "/private", "--output", "/sealed/results"] + volumes: + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR to the materialized data root}/private + target: /private + read_only: true + bind: + create_host_path: false + - sealed:/sealed diff --git a/reproduction/files/e7/e72d5da9a0ce8dbb1b489836d793e1b6fc290d6ea7f134bc5ba4a46c1f1a3d38/verifier_common.py b/reproduction/files/e7/e72d5da9a0ce8dbb1b489836d793e1b6fc290d6ea7f134bc5ba4a46c1f1a3d38/verifier_common.py new file mode 100644 index 0000000000000000000000000000000000000000..cb6b4f260f65a3115cb0088f76233be92156287e --- /dev/null +++ b/reproduction/files/e7/e72d5da9a0ce8dbb1b489836d793e1b6fc290d6ea7f134bc5ba4a46c1f1a3d38/verifier_common.py @@ -0,0 +1,23 @@ +"""Hashing and atomic-write helpers shared by the inference supervisor and the grader. + +The physical drivers and scorers live in environment/evaluation (copied to /evaluation), so the +agent's validation runs and the grader use the same code. +""" +from __future__ import annotations +import hashlib, json +from pathlib import Path + +def sha256(path:Path)->str: + digest=hashlib.sha256() + with path.open("rb") as stream: + while chunk:=stream.read(8*1024*1024): digest.update(chunk) + return digest.hexdigest() + +def tree_sha256(path:Path)->str: + digest=hashlib.sha256() + for item in sorted(x for x in path.rglob("*") if x.is_file()): + digest.update(str(item.relative_to(path)).encode()); digest.update(bytes.fromhex(sha256(item))) + return digest.hexdigest() + +def write_json(path:Path,value:object)->None: + temporary=path.with_name(path.name+".tmp"); temporary.write_text(json.dumps(value,indent=2,sort_keys=True)+"\n"); temporary.replace(path) diff --git a/reproduction/files/e8/e810f013249155d331377c7e3c78ef313997a34b2c0011a54b90d877d3ec75e5/test_masked_spatial.py b/reproduction/files/e8/e810f013249155d331377c7e3c78ef313997a34b2c0011a54b90d877d3ec75e5/test_masked_spatial.py new file mode 100644 index 0000000000000000000000000000000000000000..46ab1d88a33a6bbebaa9237fd27f4828ceb79132 --- /dev/null +++ b/reproduction/files/e8/e810f013249155d331377c7e3c78ef313997a34b2c0011a54b90d877d3ec75e5/test_masked_spatial.py @@ -0,0 +1,69 @@ +"""Missing-observation spatial features preserve batch independence and gradients.""" + +from pathlib import Path +import sys +import unittest +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/downstream")) +from masked_spatial import spatial_features +from olmoearth_pretrain.nn.flexi_vit import EncoderConfig + + +class TestSpatial(unittest.TestCase): + def test_missing_batches_and_gradients(self): + torch.set_num_threads(2) + torch.manual_seed(7) + model = ( + EncoderConfig( + supported_modality_names=["sentinel2_l2a", "sentinel1"], + embedding_size=32, + num_heads=4, + depth=1, + drop_path=0, + ) + .build() + .eval() + ) + pixels = { + "sentinel2_l2a": torch.randn(3, 8, 8, 2, 12), + "sentinel1": torch.randn(3, 8, 8, 2, 2), + } + valid = { + "sentinel2_l2a": torch.ones(3, 2, 3, dtype=torch.bool), + "sentinel1": torch.ones(3, 2, 1, dtype=torch.bool), + } + valid["sentinel2_l2a"][0, 1] = False + valid["sentinel1"][1] = False + for v in valid.values(): + v[2] = False + features = spatial_features(model, pixels, valid) + self.assertEqual(tuple(features.shape), (3, 32, 2, 2)) + self.assertTrue(torch.equal(features[2], torch.zeros_like(features[2]))) + for i in range(3): + alone = spatial_features( + model, + {k: v[i : i + 1] for k, v in pixels.items()}, + {k: v[i : i + 1] for k, v in valid.items()}, + ) + torch.testing.assert_close(features[i : i + 1], alone, atol=2e-6, rtol=2e-6) + changed = {k: v.clone() for k, v in pixels.items()} + changed["sentinel2_l2a"][0, :, :, 1, :] = 999 + changed["sentinel1"][1] = 999 + torch.testing.assert_close( + features, spatial_features(model, changed, valid), atol=0, rtol=0 + ) + model.train() + spatial_features(model, pixels, valid).square().mean().backward() + grads = [p.grad for p in model.parameters() if p.grad is not None] + self.assertTrue( + grads + and all(torch.isfinite(g).all() for g in grads) + and any(torch.any(g != 0) for g in grads) + ) + with self.assertRaises(ValueError): + spatial_features(model, pixels, {"sentinel1": valid["sentinel1"]}) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/e8/e84b10ca30f9380d5b0472300c79182f07135b2bef17e2faf46b8ed7956bd7f4/native_verifier.py b/reproduction/files/e8/e84b10ca30f9380d5b0472300c79182f07135b2bef17e2faf46b8ed7956bd7f4/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..4c594b5f16dd696c32c13edc63b226d63c063d2f --- /dev/null +++ b/reproduction/files/e8/e84b10ca30f9380d5b0472300c79182f07135b2bef17e2faf46b8ed7956bd7f4/native_verifier.py @@ -0,0 +1,375 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import re +import shutil +import signal +import socket +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def enter_offline_namespace(): + import offline_network + record = offline_network.configure(STATE) + libc = ctypes.CDLL(None, use_errno=True) + for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)): + fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC) + try: + if libc.setns(fd, flag): + raise OSError(ctypes.get_errno(), 'enter offline verifier namespace') + finally: + os.close(fd) + if socket.if_nameindex() != [(1, 'lo')]: + raise RuntimeError('Offline verifier namespace has external interfaces') + return record + + +def validate_ready_marker(sealed_root): + """Accept either upstream seal format, always checking the exact snapshot. + +Surface-code uses JSON with a run ID. Molecular, Genome and Protein-sequence +use a plain SHA-256 line. The original scientific grader rechecks the seal. +""" + root = Path(sealed_root) + raw = (root/'READY').read_text().strip() + snapshot = root/'run/snapshot.json' + observed = hashlib.sha256(snapshot.read_bytes()).hexdigest() + if re.fullmatch('[0-9a-f]{64}', raw): + if raw != observed: + raise RuntimeError('Native seal marker is inconsistent') + return + marker = json.loads(raw) + if (not isinstance(marker, dict) or marker.get('snapshot_sha256') != observed + or not isinstance(marker.get('run_id'), str) + or json.loads(snapshot.read_text()).get('run_id') != marker['run_id']): + raise RuntimeError('Native seal marker is inconsistent') + + +def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')): + """End the native waiting supervisor only after its authenticated seal.""" + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + seconds + sealed_ready = False + try: + while process.poll() is None: + if (sealed_root / 'READY').is_file(): + validate_ready_marker(sealed_root) + sealed_ready = True + break + if time.monotonic() >= deadline: + raise TimeoutError('Verifier inference budget exhausted') + time.sleep(.1) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode) + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + adapted = cfg.get('adapted_permissions', False) + if adapted: + import adapted_boundary + adapted_boundary.no_new_privileges() + os.setgroups([]) + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + crystal_cache_receipt = None + if cfg.get('isolated_crystal_dataset_cache'): + if plan['task'] != 'crystal-structure-generation' or phase != 'score': + raise RuntimeError('Crystal cache isolation is for trusted grading only') + import crystal_cache + crystal_cache_receipt = crystal_cache.prepare( + '/scorer-assets/huggingface/datasets', os.environ['HF_DATASETS_CACHE']) + crystal_cache_receipt['asset_manifest_sha256'] = hashlib.sha256( + Path('/scorer-assets/READY.json').read_bytes()).hexdigest() + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus'], strict_allocation=adapted) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + if adapted: + adapted_boundary.exact_gpu_allocation(gpu_policy) + else: + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + if cfg.get('gpu_runtime', 'torch') == 'torch' and not adapted: + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if cfg.get('local_benchmark_copy'): + status('copying_benchmark', task=plan['task'], role=phase) + # Folding's upstream evaluator runs inference and grading together. + # Give its non-root process a local readable copy, never relax Weka ACLs. + shutil.copytree('/source-benchmark', '/benchmark', symlinks=False) + for path in [Path('/benchmark'), *Path('/benchmark').rglob('*')]: + path.chmod(0o555 if path.is_dir() else 0o444) + if phase == 'inference': + status('copying_submission', task=plan['task'], role=phase) + if cfg.get('native_uid_isolation'): + # The original PDE verifier explicitly supports this UID fallback. + # The mount is below a local root-only parent, never chmod shared data. + Path('/private').chmod(0o700) + Path('/tests').chmod(0o700) + elif plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + status('checking_submission', task=plan['task'], role=phase) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + try: + agent = pwd.getpwuid(10001) + except KeyError: + subprocess.run(['/usr/sbin/useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + status('setting_submission_permissions', task=plan['task'], role=phase) + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + # Some native images precreate this empty container-local mountpoint. + # rmdir fails closed if it contains anything; never remove existing logs. + if Path('/logs/verifier').is_dir() and not Path('/logs/verifier').is_symlink(): + Path('/logs/verifier').rmdir() + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + if adapted and cfg.get('network_policy') != 'policy-children-only': + adapted_boundary.restrict_network() + elif not offline and not adapted: + runtime.deny_network() + if not adapted: + writable_roots = ['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc', + *cfg.get('writable_runtime_paths', [])] + if crystal_cache_receipt: + # The native image links /scorer-assets beneath /workspace. A + # writable ancestor defeats a read-only Landlock child rule. + # Trusted grading needs its output and scratch directories only. + writable_roots.remove('/workspace') + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets', + *cfg.get('readonly_runtime_paths', [])], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=writable_roots) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + if adapted: + source_audit = adapted_boundary.audit_source_permissions( + ['/operator', '/submission-source', '/source-benchmark', '/benchmark', '/data', '/labels', '/private'], + untrusted_uids=tuple(range(10001, 10009))) + else: + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if crystal_cache_receipt: + try: + fd = os.open('/scorer-assets/READY.json', os.O_WRONLY | os.O_CLOEXEC) + except PermissionError: + crystal_cache_receipt['asset_write_denied'] = True + else: + os.close(fd) + raise RuntimeError('Prepared scorer assets remain writable') + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' and not adapted else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())); ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + if cfg.get('gpu_runtime') == 'jax': + probe = ('import jax; import jax.numpy as jnp; ' + f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in d.device_kind for d in jax.devices("gpu")); ' + 'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 ' + 'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + if adapted and plan['task'] == 'fluid-flow-control': + # native_runtime.sh loads a module-provided libpython. Preserve + # only these runtime settings, never credentials, in the probe. + for key in ('PATH', 'LD_LIBRARY_PATH', 'OMP_NUM_THREADS', + 'OPENBLAS_NUM_THREADS', 'XLA_PYTHON_CLIENT_PREALLOCATE'): + if key in os.environ: + probe_env[key] = os.environ[key] + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + def dependency_identity(): + os.setgroups([]); os.setgid(10001); os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + cache=Path('/tmp/verifier-cache');cache.mkdir(exist_ok=True) + os.chown(cache,10001,10001) + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True, + preexec_fn=dependency_identity if cfg.get('untrusted_whole_verifier') else None) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': ('seccomp in unprivileged policy children; trusted simulator retains MPI sockets' + if cfg.get('network_policy') == 'policy-children-only' else + 'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children'), + 'offline_namespace': offline, + 'source_mounts': f'POSIX permission audit ({source_audit} entries); non-root submission' if adapted else 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan.get('label_isolated', plan['task'] != 'protein-folding-prediction'), + 'adapted_execution': adapted, + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + if cfg.get('stop_after_sealed_ready'): + # The native supervisor has already killed all model processes and + # sealed/hashes its predictions before writing READY. End only its + # wait-for-grader loop; the unchanged grader runs in a separate job. + result = run_until_sealed(cfg['command'], log, remaining) + else: + def run_identity(): + os.setgroups([]) + os.setgid(10001) + os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + os.chown(STATE / 'results', 10001, 10001) + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True, + preexec_fn=run_identity if cfg.get('untrusted_whole_verifier') else None) + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + if cfg.get('verify_crystal_assets_after'): + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted before post-score asset validation') + with (STATE / 'asset-validation-after.log').open('w') as log: + subprocess.run([cfg['driver_python'], '-c', + 'import sys;sys.path.insert(0,"/tests");from pathlib import Path;' + 'from grader import validate_assets;validate_assets(Path("/scorer-assets"));' + 'print("ORIGINAL_SCORER_ASSET_DIGEST_OK")'], + stdout=log, stderr=subprocess.STDOUT, timeout=remaining, check=True) + if hashlib.sha256(Path('/scorer-assets/READY.json').read_bytes()).hexdigest() != crystal_cache_receipt['asset_manifest_sha256']: + raise RuntimeError('Scorer asset manifest changed during grading') + crystal_cache_receipt['original_asset_digest_after'] = 'passed' + runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt) + elapsed = time.monotonic() - entered + reward_path = STATE / 'results/reward.json' + if phase == 'score': + score_root = Path('/sealed/results') + if cfg.get('results_by_run_id'): + score_root /= json.loads(Path('/sealed/READY').read_text())['run_id'] + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = score_root / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/e9/e957f38971356883aa8b1fb2975a9e0250d5285f0a4b3c571db7d780296b8dac/test_resume_lfmc_extraction.py b/reproduction/files/e9/e957f38971356883aa8b1fb2975a9e0250d5285f0a4b3c571db7d780296b8dac/test_resume_lfmc_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..5d9c9041498fe42a43fb6c724b09f4a2c05d9a32 --- /dev/null +++ b/reproduction/files/e9/e957f38971356883aa8b1fb2975a9e0250d5285f0a4b3c571db7d780296b8dac/test_resume_lfmc_extraction.py @@ -0,0 +1,93 @@ +"""Resume must retain completed files, preserve a bad tail, and exclude heldout data.""" + +import io +import json +from pathlib import Path +import sys +import tarfile +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/downstream")) +import resume_lfmc_extraction as resume + + +class ResumeTests(unittest.TestCase): + def test_closed_file_milestone(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "log" + path.write_text( + str({"files": 100000, "windows": resume.EXPECTED}) + + "\nerror: TIMEOUT\n" + ) + self.assertEqual(resume.logged_prefix(path), 100000) + + def test_resume_suffix_and_preserve_bad_file(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "data.tar" + out = root / "output" + out.mkdir() + (out / "config.json").write_bytes(b"{}") + before = (out / "config.json").stat().st_mtime_ns + expected = {"train": 1, "val": 0, "test": 1} + entries = { + "data/config.json": b"{}", + "data/windows/spatial_split/train/metadata.json": json.dumps( + {"options": {"split": "train"}} + ).encode(), + "data/windows/spatial_split/train/payload.bin": b"complete train data", + "data/windows/spatial_split/test/metadata.json": json.dumps( + {"options": {"split": "test"}} + ).encode(), + "data/windows/spatial_split/test/payload.bin": b"heldout payload", + } + target = out / "windows/spatial_split/train/payload.bin" + target.parent.mkdir(parents=True) + target.write_bytes(b"partial") + with tarfile.open(archive, "w") as tar: + for name, value in entries.items(): + member = tarfile.TarInfo(name) + member.size = len(value) + tar.addfile(member, io.BytesIO(value)) + log = root / "log" + log.write_text("preserved log") + argv = [ + "resume", + "--previous-job", + "123", + "--previous-log", + str(log), + "--archive", + str(archive), + "--output", + str(out), + "--quarantine", + str(root / "quarantine"), + ] + with ( + patch.object(sys, "argv", argv), + patch.object(resume, "EXPECTED", expected), + patch.object(resume, "logged_prefix", return_value=1), + patch.object( + resume.subprocess, "check_output", return_value="123|TIMEOUT\n" + ), + ): + resume.main() + self.assertEqual(target.read_bytes(), b"complete train data") + self.assertEqual( + ( + root / "quarantine/windows/spatial_split/train/payload.bin" + ).read_bytes(), + b"partial", + ) + self.assertEqual((out / "config.json").stat().st_mtime_ns, before) + self.assertFalse((out / "windows/spatial_split/test").exists()) + report = json.loads((out / "extraction.json").read_text()) + self.assertEqual(report["files"], 3) + self.assertEqual(report["quarantined_incomplete_files"], 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/eb/eb1ff7b3952c7ec412e6a4a0dd8939358a4a724f2ecb39309855a561ec86b53b/native_verifier.py b/reproduction/files/eb/eb1ff7b3952c7ec412e6a4a0dd8939358a4a724f2ecb39309855a561ec86b53b/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..a501cf3b849f7098863ecddaaad72a7c0e791946 --- /dev/null +++ b/reproduction/files/eb/eb1ff7b3952c7ec412e6a4a0dd8939358a4a724f2ecb39309855a561ec86b53b/native_verifier.py @@ -0,0 +1,315 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import ctypes +import hashlib +import json +import os +from pathlib import Path +import pwd +import platform +import shutil +import signal +import socket +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def enter_offline_namespace(): + import offline_network + record = offline_network.configure(STATE) + libc = ctypes.CDLL(None, use_errno=True) + for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)): + fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC) + try: + if libc.setns(fd, flag): + raise OSError(ctypes.get_errno(), 'enter offline verifier namespace') + finally: + os.close(fd) + if socket.if_nameindex() != [(1, 'lo')]: + raise RuntimeError('Offline verifier namespace has external interfaces') + return record + + +def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')): + """End the native waiting supervisor only after its authenticated seal.""" + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + seconds + sealed_ready = False + try: + while process.poll() is None: + if (sealed_root / 'READY').is_file(): + marker = json.loads((sealed_root / 'READY').read_text()) + snapshot = sealed_root / 'run/snapshot.json' + if (hashlib.sha256(snapshot.read_bytes()).hexdigest() != marker['snapshot_sha256'] + or json.loads(snapshot.read_text())['run_id'] != marker['run_id']): + raise RuntimeError('Native seal marker is inconsistent') + sealed_ready = True + break + if time.monotonic() >= deadline: + raise TimeoutError('Verifier inference budget exhausted') + time.sleep(.1) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode) + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + adapted = cfg.get('adapted_permissions', False) + if adapted: + import adapted_boundary + adapted_boundary.no_new_privileges() + os.setgroups([]) + STATE.chmod(0o755) + kernel_features = {'kernel': platform.release(), + 'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)} + runtime.write_json(STATE / 'kernel-features.json', kernel_features) + status('preflight', task=plan['task'], role=phase, **kernel_features) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/verifier-cache', + NUMBA_CACHE_DIR='/tmp/verifier-cache/numba', + TRITON_CACHE_DIR='/tmp/verifier-cache/triton', + TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions', + CUDA_CACHE_PATH='/tmp/verifier-cache/cuda') + os.environ.update(cfg.get('environment', {})) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus'], strict_allocation=adapted) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + if adapted: + adapted_boundary.exact_gpu_allocation(gpu_policy) + else: + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + if cfg.get('gpu_runtime', 'torch') == 'torch' and not adapted: + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if cfg.get('local_benchmark_copy'): + status('copying_benchmark', task=plan['task'], role=phase) + # Folding's upstream evaluator runs inference and grading together. + # Give its non-root process a local readable copy, never relax Weka ACLs. + shutil.copytree('/source-benchmark', '/benchmark', symlinks=False) + for path in [Path('/benchmark'), *Path('/benchmark').rglob('*')]: + path.chmod(0o555 if path.is_dir() else 0o444) + if phase == 'inference': + if adapted:status('copying_submission', task=plan['task'], role=phase) + if cfg.get('native_uid_isolation'): + # The original PDE verifier explicitly supports this UID fallback. + # The mount is below a local root-only parent, never chmod shared data. + Path('/private').chmod(0o700) + Path('/tests').chmod(0o700) + elif plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + try: + agent = pwd.getpwuid(10001) + except KeyError: + subprocess.run(['/usr/sbin/useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + # Some native images precreate this empty container-local mountpoint. + # rmdir fails closed if it contains anything; never remove existing logs. + if Path('/logs/verifier').is_dir() and not Path('/logs/verifier').is_symlink(): + Path('/logs/verifier').rmdir() + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + if adapted and cfg.get('network_policy') != 'policy-children-only': + adapted_boundary.restrict_network() + elif not offline and not adapted: + runtime.deny_network() + if not adapted: + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets'], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc', + *cfg.get('writable_runtime_paths', [])]) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + if adapted: + source_audit = adapted_boundary.audit_source_permissions( + ['/operator', '/submission-source', '/source-benchmark', '/benchmark', '/data', '/labels', '/private'], + untrusted_uids=tuple(range(10001, 10009))) + else: + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' and not adapted else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())); ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + if cfg.get('gpu_runtime') == 'jax': + probe = ('import jax; import jax.numpy as jnp; ' + f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; ' + 'assert all("H100" in d.device_kind for d in jax.devices("gpu")); ' + 'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 ' + 'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + if adapted and plan['task'] == 'fluid-flow-control': + # native_runtime.sh loads a module-provided libpython. Preserve + # only these runtime settings, never credentials, in the probe. + for key in ('PATH', 'LD_LIBRARY_PATH', 'OMP_NUM_THREADS', + 'OPENBLAS_NUM_THREADS', 'XLA_PYTHON_CLIENT_PREALLOCATE'): + if key in os.environ: + probe_env[key] = os.environ[key] + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + if cfg.get('dependency_probe'): + # Exercise the original runtime imports under the final restrictions + # before spending time loading test data. Cache files belong in /tmp, + # while installed libraries and frozen source mounts remain read-only. + with (STATE / 'dependency-probe.log').open('w') as log: + def dependency_identity(): + os.setgroups([]); os.setgid(10001); os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + cache=Path('/tmp/verifier-cache');cache.mkdir(exist_ok=True) + os.chown(cache,10001,10001) + subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']], + stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True, + preexec_fn=dependency_identity if cfg.get('untrusted_whole_verifier') else None) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'kernel_features': kernel_features, + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': ('seccomp in unprivileged policy children; trusted simulator retains MPI sockets' + if cfg.get('network_policy') == 'policy-children-only' else + 'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children'), + 'offline_namespace': offline, + 'source_mounts': f'POSIX permission audit ({source_audit} entries); non-root submission' if adapted else 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested', + 'cache_environment': {key: os.environ[key] for key in ( + 'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR', + 'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')}, + 'label_isolated': plan.get('label_isolated', plan['task'] != 'protein-folding-prediction'), + 'adapted_execution': adapted, + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + if cfg.get('stop_after_sealed_ready'): + # The native supervisor has already killed all model processes and + # sealed/hashes its predictions before writing READY. End only its + # wait-for-grader loop; the unchanged grader runs in a separate job. + result = run_until_sealed(cfg['command'], log, remaining) + else: + def run_identity(): + os.setgroups([]) + os.setgid(10001) + os.setuid(10001) + if cfg.get('untrusted_whole_verifier'): + os.chown(STATE / 'results', 10001, 10001) + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True, + preexec_fn=run_identity if cfg.get('untrusted_whole_verifier') else None) + elapsed = time.monotonic() - entered + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + reward_path = STATE / 'results/reward.json' + if phase == 'score': + score_root = Path('/sealed/results') + if cfg.get('results_by_run_id'): + score_root /= json.loads(Path('/sealed/READY').read_text())['run_id'] + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = score_root / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/eb/eb7ea7e0428a206cfb15b1cd2fbd89afea460fe52351e8181f4803256dc1df79/evaluate_native.py b/reproduction/files/eb/eb7ea7e0428a206cfb15b1cd2fbd89afea460fe52351e8181f4803256dc1df79/evaluate_native.py new file mode 100644 index 0000000000000000000000000000000000000000..cf92b2a67e568c6dc58dfa3437cade856e014994 --- /dev/null +++ b/reproduction/files/eb/eb7ea7e0428a206cfb15b1cd2fbd89afea460fe52351e8181f4803256dc1df79/evaluate_native.py @@ -0,0 +1,247 @@ +"""Replay one submission on selected real native cases, without score anchors. + +Uses frozen organizer execution profiles. The Harbor entrypoint exports the same +per-case physical metrics; there is no mixed-unit aggregate or paper-score anchor. +""" +import argparse +import hashlib +import json +import math +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import time +from concurrent.futures import ThreadPoolExecutor + +from case_spec import digest, estimated_seconds, select_cases, verify_resources +from evaluate import package_hash, write_json +from protocol import InfrastructureError, PolicyError +from metrics import aggregate as aggregate_physical + + +def implementation_hash(): + here = Path(__file__).resolve().parent + files = [p for folder in (here, here.parent / 'data') for p in folder.iterdir() + if p.suffix in ('.py', '.sh')] + return digest({str(p.relative_to(here.parent)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in files}) + + +def stop_policy(output): + """Clean up the separate policy session if its MPI parent was forcibly killed.""" + receipt = output / 'policy-process.json' + if not receipt.exists(): + return + record = json.loads(receipt.read_text()) + pid = record['pid'] + try: + ticks = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[19] + # Do not signal a reused PID, or a group other than this policy's session. + if ticks == record['start_ticks'] and os.getpgid(pid) == pid: + os.killpg(pid, signal.SIGKILL) + except (FileNotFoundError, ProcessLookupError): + pass + + +def run_case(case, data, package, output, env=None): + output.mkdir() + here = Path(__file__).resolve().parent + command = ['bash', str(here / 'native_runtime.sh'), case['backend'], 'python', + str(here / 'run_native.py'), '--case', case['id'], '--data', str(data), + '--submission', str(package), '--output', str(output)] + start = time.monotonic() + with (output / 'native.log').open('wb') as log: + process = subprocess.Popen(command, cwd=output, stdout=log, stderr=subprocess.STDOUT, start_new_session=True, + env=env) + try: + sys.path.insert(0, "/operator") + from fluid_cleanup import wait_native + code = wait_native(process, case=case, output=output, submission_sha256=package_hash(package), started=start) + except subprocess.TimeoutExpired as error: + raise InfrastructureError(f'Native case timed out: {case["id"]}') from error + finally: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + stop_policy(output) + if code or not (output / 'result.json').is_file(): + detail = f'exit code {code}' + for filename in ('worker-error.json', 'launcher-error.json'): + path = output / filename + if path.exists(): + detail = json.loads(path.read_text()).get('error', detail) + break + raise InfrastructureError(f'Native execution failed for {case["id"]}: {detail}; see {output / "native.log"}') + result = json.loads((output / 'result.json').read_text()) + result['wall_seconds'] = time.monotonic() - start + return result + + +def visible_gpus(): + """CUDA device UUIDs this process may use (enumerated in a fresh child, as run_native.py does).""" + helper = Path(__file__).with_name('maia_gpu_rank.py') + try: + return json.loads(subprocess.check_output([sys.executable, str(helper), '--list-gpus'], text=True)) + except (OSError, subprocess.CalledProcessError, ValueError): + return [] + + +# One policy account per case that can run at once (created in environment/Dockerfile). +POLICY_UIDS = tuple(range(10001, 10017)) +# Cases replayed side by side share the host's CPUs and memory bandwidth: on 8xH100 they ran +# 1.1-2.2x slower than alone, so a per-case limit sized for a solo run (about 2.5x its estimate) +# would turn a slow but healthy simulation into an infrastructure error that voids the reward. +SIDE_BY_SIDE_TIMEOUT_FACTOR = 2 + + +def replay_cases(cases, replay, devices): + """Run cases side by side, each on its own `solver_processes` GPUs, longest first. + + Each running case also gets its own policy account (HYDROGYM_POLICY_UID): closing a policy kills + every process of its account, which must not reach another case's policy. + With fewer GPUs than a case needs (or none visible) the cases run one at a time, as before.""" + if not devices or len(devices) < max(c['solver_processes'] for c in cases): + return {case['id']: replay(case, None) for case in cases} + free, lock = list(devices), threading.Condition() + uids = list(POLICY_UIDS[:len(devices)]) + + def run(case): + need = case['solver_processes'] + with lock: + lock.wait_for(lambda: len(free) >= need and uids) + mine = [free.pop(0) for _ in range(need)] + uid = uids.pop(0) + try: + slow = dict(case, timeout_sec=case['timeout_sec'] * SIDE_BY_SIDE_TIMEOUT_FACTOR) + return case['id'], replay(slow, dict(os.environ, CUDA_VISIBLE_DEVICES=','.join(mine), + HYDROGYM_POLICY_UID=str(uid))) + finally: + with lock: + free.extend(mine) + uids.append(uid) + lock.notify_all() + + order = sorted(cases, key=lambda c: -estimated_seconds(c['id']) * c['solver_processes']) + with ThreadPoolExecutor(max_workers=len(devices)) as pool: + return dict(pool.map(run, order)) + + +def evaluate_native(data, submission, output, names, runner=run_case): + data, submission, output = (Path(p).resolve() for p in (data, submission, output)) + if (output.is_relative_to(data) or data.is_relative_to(output) or + output.is_relative_to(submission) or submission.is_relative_to(output)): + raise InfrastructureError('Output must be separate from both source data and submission') + if output.exists() and any(output.iterdir()): + raise InfrastructureError('Evaluation output must be empty') + output.mkdir(parents=True, exist_ok=True) + try: + spec, cases = select_cases(names) + verify_resources(data, cases) + identity = {'evaluation_mode': 'native-profile-replay', 'benchmark_validated': False, + 'metric_version': spec['metric_version'], 'metrics_sha256': spec['metrics_sha256'], + 'evaluator_sha256': implementation_hash(), + 'data_release_id': spec['data_release_id'], 'data_release_sha256': spec['data_release_sha256'], + 'profile_version': spec['profile_version'], 'profiles_sha256': digest(spec), + 'selected_case_ids': [c['id'] for c in cases], + 'all_frozen_cases_selected': len(cases) == len(spec['cases'])} + write_json(output / 'profiles.json', spec) + results = {} + try: + model_hash = package_hash(submission) + except PolicyError as error: + model_hash = None + results = {c['id']: {'status': 'policy_error', 'error': str(error)} for c in cases} + if model_hash is not None: + with tempfile.TemporaryDirectory(prefix='.native-snapshot-', dir=output) as tmp: + package = Path(tmp) / 'submission' + shutil.copytree(submission, package, symlinks=True) + # Readable (never writable) by the unprivileged policy account. + os.chmod(tmp, 0o755) + for path in [package, *package.rglob('*')]: + if not path.is_symlink(): + path.chmod(0o555 if path.is_dir() or os.access(path, os.X_OK) else 0o444) + if package_hash(package) != model_hash or package_hash(submission) != model_hash: + raise InfrastructureError('Submission changed while snapshotting') + write_json(output / 'identity.json', dict(identity, submission_sha256=model_hash)) + progress = threading.Lock() + + def replay(case, env): + try: + row = (runner(case, data, package, output / case['id'], env) if env is not None + else runner(case, data, package, output / case['id'])) + if row.get('submission_sha256') != model_hash: + raise InfrastructureError('Native worker replayed a different model package') + if row.get('status') == 'ok': + episodes = row.get('episodes', []) + if [e.get('seed') for e in episodes] != case['seeds'] or any( + e.get('steps') != case['horizon'] or + not (e.get('terminated') is True or e.get('truncated') is True) + for e in episodes): + raise InfrastructureError('Wrong/missing complete native episode') + returns = [e.get('return') for e in episodes] + if not all(type(v) in (float, int) and math.isfinite(v) for v in returns): + raise InfrastructureError('Nonfinite/missing native returns') + row['mean_return'] = sum(returns) / len(returns) + if not math.isfinite(row['mean_return']): + raise InfrastructureError('Nonfinite mean native return') + row['primary_metric'] = aggregate_physical(case['primary_metric'], episodes) + elif row.get('status') != 'policy_error': + raise InfrastructureError('Native worker did not return an explicit outcome') + except Exception as error: + row = {'status': 'infrastructure_error', 'error': str(error)} + with progress: + results[case['id']] = row + write_json(output / 'partial-results.json', dict(identity, submission_sha256=model_hash, cases=results)) + return row + + replay_cases(cases, replay, visible_gpus()) + results = {c['id']: results[c['id']] for c in cases if c['id'] in results} + if package_hash(package) != model_hash: + raise InfrastructureError('Submission snapshot mutated during evaluation') + verify_resources(data, cases) + if digest(select_cases(names)[0]) != identity['profiles_sha256']: + raise InfrastructureError('Executable profiles changed during replay') + if implementation_hash() != identity['evaluator_sha256']: + raise InfrastructureError('Evaluator implementation changed during replay') + ok = sum(row['status'] == 'ok' for row in results.values()) + result = dict(identity, submission_sha256=model_hash, + status='ok' if ok == len(cases) else 'completed_with_errors', + successful_cases=ok, requested_cases=len(cases), cases=results) + write_json(output / 'results.json', result) + return result + except Exception as error: + write_json(output / 'error.json', {'status': 'infrastructure_error', 'error': str(error)}) + raise + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--data', type=Path, default=Path('/data')) + p.add_argument('--submission', type=Path, default=Path('/workspace/submission')) + p.add_argument('--output', type=Path) + p.add_argument('--case', action='append', required=True, help='Frozen case ID; repeat, or use all') + p.add_argument('--preflight', action='store_true', help='Check source/profile bindings without running CFD') + args = p.parse_args() + if args.preflight: + spec, cases = select_cases(args.case) + verify_resources(args.data.resolve(), cases) + print(json.dumps({'status': 'source-profile-preflight-passed', 'benchmark_validated': False, + 'profiles_sha256': digest(spec), 'cases': cases}, indent=2)) + return + if args.output is None: + p.error('--output is required for replay') + result = evaluate_native(args.data, args.submission, args.output, args.case) + print(json.dumps({k: v for k, v in result.items() if k != 'cases'}, indent=2)) + if result['status'] != 'ok': + raise SystemExit(2) + + +if __name__ == '__main__': + main() diff --git a/reproduction/files/eb/eba2ac81bc01a9bf264d025fd3c72c2c98d31b05dbfefc6a3eb4f9908e92cb5a/main_verifier.py b/reproduction/files/eb/eba2ac81bc01a9bf264d025fd3c72c2c98d31b05dbfefc6a3eb4f9908e92cb5a/main_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..beb0617e65660f705ceb7a6384749cfbfcd05991 --- /dev/null +++ b/reproduction/files/eb/eba2ac81bc01a9bf264d025fd3c72c2c98d31b05dbfefc6a3eb4f9908e92cb5a/main_verifier.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +"""Replay an untrusted model on input-only data and seal its ranking output.""" + +import argparse +import ctypes +import json +import os +from pathlib import Path +import pwd +import shutil +import signal +import subprocess +import time +import sys + +# In the verifier image these shared files are copied beside this module. +# In a checkout import the same source used by development validation. +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/evaluation")) +from benchmark_score import normalize + +from common import contained, sha256, validate_input, write_json + + +def validate_submission(root: Path): + root = root.resolve() + for required in ("infer.sh", "model_manifest.json", "README.md"): + path = root / required + if not path.is_file() or path.is_symlink(): + raise FileNotFoundError( + f"submission/{required} is required and must not be a symlink" + ) + for path in root.rglob("*"): + if path.is_symlink() and not path.resolve().is_relative_to(root): + raise ValueError(f"submission symlink escapes package: {path.relative_to(root)}") + manifest = json.loads((root / "model_manifest.json").read_text()) + if set(manifest) != {"schema", "checkpoint", "model_config", "training_provenance"}: + raise ValueError("invalid model manifest fields") + if manifest["schema"] != "massspecgym-retrieval-model/v1": + raise ValueError("invalid model manifest schema") + checkpoint = manifest["checkpoint"] + if ( + set(checkpoint) != {"path", "sha256", "format"} + or checkpoint["format"] not in {"pytorch", "safetensors"} + or not isinstance(checkpoint["sha256"], str) + or len(checkpoint["sha256"]) != 64 + or any(character not in "0123456789abcdef" for character in checkpoint["sha256"]) + ): + raise ValueError("invalid checkpoint declaration") + checkpoint_path = contained(root, checkpoint["path"]) + if sha256(checkpoint_path) != checkpoint["sha256"]: + raise ValueError("checkpoint checksum mismatch") + config = contained(root, manifest["model_config"]) + if not isinstance(json.loads(config.read_text()), dict): + raise ValueError("model config must contain a JSON object") + provenance = manifest["training_provenance"] + if ( + not isinstance(provenance, dict) + or set(provenance) != {"data", "pretrained_assets"} + or not isinstance(provenance["data"], str) + or not isinstance(provenance["pretrained_assets"], list) + ): + raise ValueError("invalid training provenance") + if provenance['pretrained_assets']: + raise ValueError('this task release supplies no authorized pretrained assets') + return manifest + + +def kill_uid_processes(uid: int): + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit() or int(entry.name) == os.getpid(): + continue + try: + status = (entry / "status").read_text() + process_uid = int( + next(line for line in status.splitlines() if line.startswith("Uid:")).split()[1] + ) + if process_uid == uid: + os.kill(int(entry.name), signal.SIGKILL) + except (FileNotFoundError, ProcessLookupError, PermissionError, StopIteration): + pass + + +def run_submission(submission: Path, input_root: Path, work: Path, timeout: int): + agent = pwd.getpwnam("agent") + output = work / "untrusted-output" + output.mkdir() + os.chown(output, agent.pw_uid, agent.pw_gid) + log = work / "inference.log" + environment = { + "PATH": "/opt/conda/bin:/usr/local/bin:/usr/bin:/bin", + "HOME": agent.pw_dir, + "PYTHONUNBUFFERED": "1", + "PIP_NO_INDEX": "1", + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + "CUDA_VISIBLE_DEVICES": os.environ.get("CUDA_VISIBLE_DEVICES", "0"), + } + + def demote(): + os.setgroups([]) + os.setgid(agent.pw_gid) + os.setuid(agent.pw_uid) + # Prevent setuid binaries or file capabilities from recovering privilege. + libc = ctypes.CDLL(None, use_errno=True) + if libc.prctl(38, 1, 0, 0, 0) != 0: # PR_SET_NO_NEW_PRIVS + raise OSError(ctypes.get_errno(), 'PR_SET_NO_NEW_PRIVS failed') + + process = None + try: + with log.open("wb") as stream: + process = subprocess.Popen( + ["bash", str(submission / "infer.sh"), str(input_root), str(output)], + cwd=submission, + env=environment, + stdout=stream, + stderr=subprocess.STDOUT, + start_new_session=True, + preexec_fn=demote, + ) + code = process.wait(timeout=timeout) + if code: + raise subprocess.CalledProcessError(code, process.args) + except subprocess.TimeoutExpired: + if process: + os.killpg(process.pid, signal.SIGKILL) + raise + finally: + if process: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + kill_uid_processes(agent.pw_uid) + return output + + +def seal_output(untrusted: Path, sealed: Path, input_manifest: Path): + if sealed.exists(): + raise FileExistsError(sealed) + temporary = sealed.with_name(sealed.name + ".tmp") + temporary.mkdir(parents=True) + files = {} + source = untrusted / "rankings.jsonl" + if source.is_file() and not source.is_symlink(): + if source.stat().st_size > 512 * 1024 * 1024: + raise ValueError("ranking output exceeds 512 MiB") + if not source.resolve().is_relative_to(untrusted.resolve()): + raise ValueError("ranking output escapes output root") + destination = temporary / "rankings.jsonl" + shutil.copyfile(source, destination, follow_symlinks=False) + destination.chmod(0o444) + files["rankings.jsonl"] = sha256(destination) + snapshot = { + "schema": "massspecgym-retrieval-ranking-snapshot/v1", + "input_manifest_sha256": sha256(input_manifest), + "files": files, + } + write_json(temporary / "snapshot.json", snapshot) + (temporary / "snapshot.json").chmod(0o444) + temporary.chmod(0o555) + os.replace(temporary, sealed) + ready = sealed.parent / "READY.tmp" + ready.write_text(sha256(sealed / "snapshot.json") + "\n") + os.replace(ready, sealed.parent / "READY") + + +def prepare_trusted_directories(output: Path, sealed: Path): + for path, mode in ((output, 0o755), (sealed.parent, 0o700)): + path.mkdir(parents=True, exist_ok=True) + os.chown(path, os.geteuid(), os.getegid()) + path.chmod(mode) + # Harbor also accepts reward.txt, even if test.sh returns nonzero. Neither + # stale results nor files written by the inference UID may become rewards. + for name in ("reward.json", "reward.txt", "report.json"): + (output / name).unlink(missing_ok=True) + + +def failed_submission(output: Path, queries: int, status: str, error: Exception): + metrics = {"hit_rate_at_1": 0.0, "hit_rate_at_5": 0.0, + "hit_rate_at_20": 0.0, "mces_at_1": 100.0} + write_json(output / "report.json", { + "schema": "massspecgym-retrieval-report/v1", "status": status, + "model_quality_measured": False, "queries": queries, + "valid_rankings": 0, "invalid_or_missing_rankings": queries, + "global_error": str(error), "metrics": metrics, + "benchmark_score": normalize(metrics["hit_rate_at_1"]), + "metric_directions": {name: "minimize" if name == "mces_at_1" else "maximize" + for name in metrics}, + }) + write_json(output / "reward.json", {"reward": metrics["hit_rate_at_1"]}) + + +def evaluate(args): + started = time.monotonic() + prepare_trusted_directories(args.output, args.sealed) + _, queries, _ = validate_input(args.input) + try: + validate_submission(args.submission) + except (OSError, ValueError, TypeError, KeyError) as error: + failed_submission(args.output, len(queries), "invalid_submission", error) + return + work = args.output / "main" + work.mkdir() + try: + untrusted = run_submission(args.submission, args.input, work, args.timeout) + except subprocess.TimeoutExpired as error: + failed_submission(args.output, len(queries), "inference_timeout", error) + return + except subprocess.CalledProcessError as error: + failed_submission(args.output, len(queries), "inference_failed", error) + return + try: + seal_output(untrusted, args.sealed, args.input / "manifest.json") + except ValueError as error: + failed_submission(args.output, len(queries), "invalid_output", error) + return + if not args.no_wait: + results = args.sealed.parent / "results" + deadline = min(time.monotonic() + 3600, started + 21600) + while not (results / "reward.json").is_file(): + if (results / "error.json").is_file(): + raise RuntimeError(f"trusted grader failed: {(results / 'error.json').read_text()}") + if time.monotonic() >= deadline: + raise TimeoutError("trusted grader did not publish reward.json") + time.sleep(1) + for name in ("report.json", "reward.json"): + shutil.copyfile(results / name, args.output / name) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--submission", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--input", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--sealed", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--output", required=True, type=lambda x: Path(x).resolve()) + parser.add_argument("--timeout", type=int, default=18000) + parser.add_argument("--no-wait", action="store_true") + args = parser.parse_args() + if os.geteuid() != 0: + parser.error("the trusted verifier must run as root to isolate inference UID 10001") + if not 0 < args.timeout <= 18000: + parser.error("inference timeout must be in 1..18000 seconds") + try: + evaluate(args) + except Exception as error: + args.output.mkdir(parents=True, exist_ok=True) + for name in ("reward.json", "reward.txt"): + (args.output / name).unlink(missing_ok=True) + write_json(args.output / "report.json", { + "schema": "massspecgym-retrieval-report/v1", + "status": "infrastructure_error", "model_quality_measured": False, + "global_error": f"{type(error).__name__}: {error}", + }) + raise + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/ec/ec22408d51ff09693be835db56a0fee19276c749066eaf6d958f783f6e9f5fd4/test_selection.py b/reproduction/files/ec/ec22408d51ff09693be835db56a0fee19276c749066eaf6d958f783f6e9f5fd4/test_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..42438f995fc8b68bc26eae64c8328d1ab269851f --- /dev/null +++ b/reproduction/files/ec/ec22408d51ff09693be835db56a0fee19276c749066eaf6d958f783f6e9f5fd4/test_selection.py @@ -0,0 +1,88 @@ +"""Check declared task ranking, context isolation, and immutable selection records.""" + +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +class SelectionTest(unittest.TestCase): + def test_task_policy_and_guards(self): + script = Path(__file__).resolve().parents[1] / "docs/analysis/select_checkpoint.py" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "results").mkdir() + context = {"gpu_type": "a5000", "python_hash_seed": 0} + (root / "execution-context.json").write_text(json.dumps(context)) + names = ["better-awf-step500", "better-lfmc-step1000"] + for name, acc, mae in zip(names, [0.9, 0.5], [23, 21]): + package = root / "packages" / name + package.mkdir(parents=True) + (package / "encoder.pt").write_bytes(name.encode()) + (package / "provenance.json").write_text( + json.dumps( + { + "origin": "own_from_scratch_training", + "checkpoint": "own-checkpoint", + "encoder_sha256": hashlib.sha256(name.encode()).hexdigest(), + } + ) + ) + for task in ["awf", "lfmc"]: + report = { + "features": str( + root / "features" / f"{name}-{task}" / "features.npz" + ), + "validation_predictions": str( + root / "results" / f"{name}-{task}-predictions.npz" + ), + "probe": { + "validation": {"accuracy": acc} + if task == "awf" + else {"mae": mae} + }, + "constant_val": {"mae": 30}, + } + (root / "results" / f"{name}-{task}.json").write_text( + json.dumps(report) + ) + policy = {"candidates": names, "execution_context": context} + policy_path = root / "policy.json" + output = root / "selection.json" + cmd = [ + sys.executable, + str(script), + "--data-root", + str(root), + "--policy", + str(policy_path), + "--output", + str(output), + ] + for primary, expected in [("joint", names[0]), ("lfmc", names[1])]: + policy["primary_task"] = primary + policy_path.write_text(json.dumps(policy)) + run = subprocess.run(cmd, capture_output=True, text=True) + self.assertEqual(run.returncode, 0, run.stderr) + selected = json.loads(output.read_text()) + self.assertEqual(selected["selected"], expected) + self.assertTrue(selected["ranking_only"]) + repeated = subprocess.run(cmd, capture_output=True, text=True) + self.assertNotEqual(repeated.returncode, 0) + self.assertEqual(json.loads(output.read_text()), selected) + output.unlink() + metric_path = root / "results" / f"{names[1]}-lfmc.json" + metric = json.loads(metric_path.read_text()) + metric["features"] = "/different-context/features.npz" + metric_path.write_text(json.dumps(metric)) + rejected = subprocess.run(cmd, capture_output=True, text=True) + self.assertNotEqual(rejected.returncode, 0) + self.assertIn("execution contexts", rejected.stderr) + self.assertFalse(output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/f0/f0bcb5c57abceb69f373243501e0ecdb03b3a33904473cfeae53a390e962320c/docker-compose.yaml b/reproduction/files/f0/f0bcb5c57abceb69f373243501e0ecdb03b3a33904473cfeae53a390e962320c/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f52976079690430ec96c63a0ccffbfa2148f638f --- /dev/null +++ b/reproduction/files/f0/f0bcb5c57abceb69f373243501e0ecdb03b3a33904473cfeae53a390e962320c/docker-compose.yaml @@ -0,0 +1,49 @@ +volumes: + sealed: + verifier_logs: + +services: + main: + build: + context: .. + dockerfile: tests/Dockerfile + network_mode: none + # Main resources come from task.toml or the explicit evaluation profile. + shm_size: "16gb" + volumes: + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR}/verifier + target: /benchmark + read_only: true + bind: + create_host_path: false + - sealed:/sealed + - verifier_logs:/logs/verifier + healthcheck: + test: ["CMD-SHELL", "test -s /benchmark/manifest.json && test -s /benchmark/queries.jsonl && test -s /benchmark/candidate_pools.jsonl"] + interval: 5s + timeout: 5s + retries: 3 + + grader: + build: + context: .. + dockerfile: tests/Dockerfile + network_mode: none + cpus: 16 + mem_limit: "16g" + command: ["python", "/tests/grader.py", "--sealed", "/sealed/run", "--input", "/benchmark", "--labels", "/private", "--output", "/sealed/results"] + volumes: + - type: bind + source: ${TASK_DATA_DIR:?Set TASK_DATA_DIR}/verifier + target: /benchmark + read_only: true + bind: + create_host_path: false + - type: bind + source: ${TASK_PRIVATE_DIR:?Set TASK_PRIVATE_DIR} + target: /private + read_only: true + bind: + create_host_path: false + - sealed:/sealed diff --git a/reproduction/files/f1/f10aeef8a09d98c98e3a1337ec07b7059beb743ab8190a041315cf958b17b049/test_preparation.py b/reproduction/files/f1/f10aeef8a09d98c98e3a1337ec07b7059beb743ab8190a041315cf958b17b049/test_preparation.py new file mode 100644 index 0000000000000000000000000000000000000000..698e48f114fa1e2a5d11ba22fe976244095020fb --- /dev/null +++ b/reproduction/files/f1/f10aeef8a09d98c98e3a1337ec07b7059beb743ab8190a041315cf958b17b049/test_preparation.py @@ -0,0 +1,220 @@ +import sys +from pathlib import Path + +import numpy as np +import pytest +from ase.build import bulk + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/data")) +sys.path.insert( + 0, str(Path(__file__).resolve().parents[1] / "environment/baseline/uma-s-pretrain") +) +from prepare_training import prepare, _AppendOnlyIDs, fit_element_references + + +def test_training_schedule_rejects_ambiguous_duration(tmp_path): + with pytest.raises(ValueError, match="exactly one"): + prepare(tmp_path, tmp_path / "output", steps=500, epochs=1) + with pytest.raises(ValueError, match="exactly one"): + prepare(tmp_path, tmp_path / "output", steps=None, epochs=None) + + +def test_bulk_lmdb_id_index_preserves_order_labels_and_metadata(tmp_path): + pytest.importorskip("ase_db_backends") + from ase.db import connect + from ase.calculators.singlepoint import SinglePointCalculator + + path = tmp_path / "frames.aselmdb" + with connect(path) as db: + db.ids = _AppendOnlyIDs(db.ids) + for i in range(40): + atoms = bulk("Cu").repeat((1 + i % 3, 1, 1)) + atoms.calc = SinglePointCalculator( + atoms, + energy=float(i), + forces=np.full((len(atoms), 3), i / 10), + stress=np.eye(3) * i / 100, + ) + assert db.write(atoms, data={"sid": f"frame-{i}"}) == i + 1 + assert list(db.ids) == list(range(1, 41)) + with connect(path, readonly=True) as db: + assert len(db) == 40 + for i, row in enumerate(db.select()): + assert row.id == i + 1 + assert row.data.sid == f"frame-{i}" + assert row.energy == float(i) + assert np.allclose(row.forces, i / 10) + assert np.allclose( + row.toatoms().get_cell(), bulk("Cu").repeat((1 + i % 3, 1, 1)).cell + ) + assert np.allclose( + row.toatoms().get_stress(voigt=False), + np.eye(3) * i / 100, + ) + + +def test_scratch_recipe_uses_only_training_statistics_and_no_checkpoint(tmp_path): + import json + import yaml + from common import digest, encode_atoms, write_rows + + data = tmp_path / "data" + data.mkdir() + row = dict( + id="mptrj/frame", + parent="mp-1", + source="mptrj", + atoms=encode_atoms(bulk("Cu")), + energy=-1.0, + forces=[[0.1, 0.2, 0.3]], + stress=np.eye(3).tolist(), + ) + for split in ("train", "val"): + write_rows(data / f"{split}.jsonl", [row]) + (data / "element-references.yaml").write_text("mpa_elem_refs: {29: -1.0}\n") + (data / "manifest.json").write_text( + json.dumps( + dict( + energy_convention="mp-pbe-raw-total", + corrections_applied=False, + files={ + f"{s}.jsonl": digest(data / f"{s}.jsonl") for s in ("train", "val") + }, + element_reference_resource={ + "sha256": digest(data / "element-references.yaml") + }, + ) + ) + ) + config_path = prepare( + data, + tmp_path / "output", + steps=None, + epochs=3, + world_size=8, + batch_size=4, + evaluate_every=1000, + ) + config = yaml.safe_load(config_path.read_text()) + assert config["epochs"] == 3 and config["steps"] is None + assert config["batch_size"] == 4 + assert config["job"]["scheduler"]["ranks_per_node"] == 8 + assert config["checkpoint_every_n_steps"] == 5000 + assert config["runner"]["train_eval_unit"]["ema_decay"] is None + assert ( + config["runner"]["callbacks"][-1]["_target_"] + == "learning_curves.LearningCurveAudit" + ) + assert any( + c.get("max_saved_checkpoints") == 12 for c in config["runner"]["callbacks"] + ) + model = config["runner"]["train_eval_unit"]["model"] + assert model["_target_"] == "fairchem.core.models.base.HydraModel" + assert "checkpoint_location" not in model and "finetune_config" not in model + assert model["backbone"]["num_experts"] == 32 + assert model["backbone"]["direct_forces"] is False + before = json.loads((config_path.parent / "preparation.json").read_text()) + assert before["initial_checkpoint_sha256"] is None + assert before["element_reference_values_eV"][29] == pytest.approx(-1.0) + assert before["force_rms"] == pytest.approx(np.sqrt(0.14 / 3)) + + # Neither development labels nor an external fitted-reference file may + # influence the learned offsets / normalizers in a from-scratch track. + row.update(energy=-999.0, forces=[[10.0, 20.0, 30.0]]) + write_rows(data / "val.jsonl", [row]) + manifest = json.loads((data / "manifest.json").read_text()) + manifest["files"]["val.jsonl"] = digest(data / "val.jsonl") + (data / "manifest.json").write_text(json.dumps(manifest)) + (data / "element-references.yaml").unlink() + path = prepare(data, tmp_path / "changed-dev", steps=2) + after = json.loads((path.parent / "preparation.json").read_text()) + for key in ["force_rms", "element_reference_values_eV", "statistics_train_sha256"]: + assert after[key] == before[key] + + from export_model import export + + # Reject a mismatched or warm-start receipt before opening checkpoint weights. + for key, value in [ + ("initial_checkpoint_sha256", "pretrained-sha"), + ("pretrained_weights_allowed", True), + ("training_manifest_sha256", "another-dataset"), + ("statistics_train_sha256", "another-training-split"), + ]: + bad = {**after, key: value} + receipt = tmp_path / "bad-preparation.json" + receipt.write_text(json.dumps(bad)) + with pytest.raises(ValueError, match="pretraining provenance"): + export( + tmp_path / "absent-model", + data, + tmp_path / "artifact", + preparation=receipt, + ) + + +def test_element_offsets_recover_known_mixture_and_ignore_absent_elements(): + compositions = np.array([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.5, 0.5]]) + refs, present, rank = fit_element_references( + compositions, np.array([-2.0, -4.0, -3.0]) + ) + assert refs == pytest.approx([0.0, -2.0, -4.0]) + assert present == [1, 2] and rank == 2 + refs, _, rank = fit_element_references(compositions[2:], np.array([-3.0])) + assert refs == pytest.approx([0.0, -3.0, -3.0]) + assert rank == 1 + + +def test_export_package_has_verifier_entrypoint(tmp_path): + import json + from types import SimpleNamespace + + torch = pytest.importorskip("torch") + from common import digest, encode_atoms, write_rows + from export_model import export + + data = tmp_path / "data" + data.mkdir() + row = dict( + id="mptrj/one", + parent="mp-1", + source="mptrj", + atoms=encode_atoms(bulk("Cu")), + energy=-1.0, + forces=[[0.1, 0.2, 0.3]], + stress=np.eye(3).tolist(), + ) + for split in ("train", "val"): + write_rows(data / f"{split}.jsonl", [row]) + (data / "manifest.json").write_text( + json.dumps( + dict( + energy_convention="mp-pbe-raw-total", + corrections_applied=False, + files={ + f"{s}.jsonl": digest(data / f"{s}.jsonl") for s in ("train", "val") + }, + ) + ) + ) + config = prepare(data, tmp_path / "prepared", steps=2) + checkpoint = tmp_path / "checkpoint.pt" + torch.save( + SimpleNamespace(model_state_dict={"weight": torch.tensor([1.0])}), checkpoint + ) + package = export( + checkpoint, + data, + tmp_path / "package", + preparation=config.parent / "preparation.json", + ) + for filename in [ + "calculator.py", + "README.md", + "model.pt", + "preparation.json", + "training-manifest.json", + ]: + assert (package / filename).is_file() + exported = torch.load(package / "model.pt", weights_only=False) + assert exported.ema_state_dict["module.weight"].item() == 1.0 + assert exported.ema_state_dict["n_averaged"].item() == 1 diff --git a/reproduction/files/f5/f53eed63bc26828f7089588fb90fc7f00b1afce5c67598a8942d9bca99b69a43/geometry.py b/reproduction/files/f5/f53eed63bc26828f7089588fb90fc7f00b1afce5c67598a8942d9bca99b69a43/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5fbff1f632370d7352f80757793b7b56cf5d66 --- /dev/null +++ b/reproduction/files/f5/f53eed63bc26828f7089588fb90fc7f00b1afce5c67598a8942d9bca99b69a43/geometry.py @@ -0,0 +1,240 @@ +"""All-atom backbone parsing, superposition, and geometric validity checks. + +Structures use the atom14 layout (see residues.py): [L, 14, 3] coordinates with an +[L, 14] occupancy mask, backbone N/CA/C/O always in slots 0-3. + +Every function here consumes output produced by an untrusted design system, so parsing +is strict and allocation is bounded before any array is built. +""" + +import numpy as np + +from residues import (ATOM14, ATOM14_WIDTH, IGNORED_ATOMS, SYMMETRIC_SWAPS, + atom_slot) + +CA_SLOT = 1 +MAX_PDB_BYTES = 32 * 1024 * 1024 +MAX_DESIGN_LENGTH = 600 + +# Bond-length and clash thresholds lived here for `validate_geometry`, the task's own +# pre-fold sanity gate. That gate was deleted on 2026-09-26 - designability is the only +# metric now - and the thresholds went with it rather than sitting here advertising limits +# nothing enforces. See environment/evaluation/RESULTS.md for what the gate had cost. +DIVERSITY_RMSD = 2.0 + + +def parse_allatom_pdb(path, expected_length): + """Parse a single-chain all-atom PDB into (coords [L,14,3], mask [L,14], restypes).""" + size = path.stat().st_size + if path.is_symlink() or not path.is_file() or size == 0 or size > MAX_PDB_BYTES: + raise ValueError("missing, empty, oversized, or symlinked structure") + if not 0 < expected_length <= MAX_DESIGN_LENGTH: + raise ValueError("unsupported design length") + + residues, order, chains = {}, [], set() + with path.open("r", errors="strict") as stream: + for line in stream: + if not line.startswith("ATOM"): + continue + if len(line) < 54: + raise ValueError("truncated ATOM record") + atom = line[12:16].strip() + if atom in IGNORED_ATOMS or atom.startswith("H") or line[76:78].strip() == "H": + continue + if line[16] not in (" ", "A"): + continue + residue_name = line[17:20].strip() + if residue_name not in ATOM14: + raise ValueError(f"non-standard residue: {residue_name}") + chains.add(line[21]) + if len(chains) > 1: + raise ValueError("design must contain exactly one chain") + try: + number = int(line[22:26]) + coordinate = (float(line[30:38]), float(line[38:46]), float(line[46:54])) + except ValueError as error: + raise ValueError("unparsable residue number or coordinate") from error + slot = atom_slot(residue_name, atom) + if slot is None: + raise ValueError(f"atom {atom} is not valid for residue {residue_name}") + if number not in residues: + if len(residues) >= MAX_DESIGN_LENGTH: + raise ValueError("design exceeds the maximum supported length") + residues[number] = (residue_name, {}) + order.append(number) + stored_name, atoms = residues[number] + if stored_name != residue_name: + raise ValueError(f"residue {number} has conflicting identities") + if slot in atoms: + raise ValueError(f"duplicate {atom} in residue {number}") + atoms[slot] = coordinate + + if len(residues) != expected_length: + raise ValueError(f"expected {expected_length} residues, found {len(residues)}") + + coordinates = np.zeros((expected_length, ATOM14_WIDTH, 3), dtype=np.float64) + mask = np.zeros((expected_length, ATOM14_WIDTH), dtype=bool) + restypes = [] + for index, number in enumerate(sorted(order)): + residue_name, atoms = residues[number] + restypes.append(residue_name) + if not set((0, 1, 2, 3)) <= set(atoms): + raise ValueError(f"residue {number} is missing backbone atoms") + for slot, coordinate in atoms.items(): + coordinates[index, slot] = coordinate + mask[index, slot] = True + if not np.all(np.isfinite(coordinates)): + raise ValueError("non-finite coordinate") + if np.abs(coordinates[mask]).max(initial=0.0) > 1e4: + raise ValueError("coordinate outside a plausible envelope") + return coordinates, mask, restypes + + +def write_allatom_pdb(path, coordinates, mask, restypes, chain="A"): + """Write an atom14 structure in canonical PDB columns.""" + lines, serial = [], 1 + for index, residue_name in enumerate(restypes): + for slot, atom in enumerate(ATOM14[residue_name]): + if not mask[index, slot]: + continue + x, y, z = coordinates[index, slot] + # Four-character atom field: one-character elements start at column 14. + field = f" {atom:<3s}" if len(atom) < 4 else atom + lines.append( + f"ATOM {serial:>5d} {field} {residue_name:<3s} {chain}{index + 1:>4d} " + f"{x:>8.3f}{y:>8.3f}{z:>8.3f} 1.00 0.00" + " " * 10 + f"{atom[0]:>2s}") + serial += 1 + path.write_text("\n".join(lines + ["TER", "END"]) + "\n") + + +def present_atoms(coordinates, mask): + """Flatten to the [K, 3] set of atoms that actually exist.""" + return coordinates[mask] + + +def kabsch_rotation(mobile, target): + correlation = mobile.T @ target + u, _, vt = np.linalg.svd(correlation) + reflection = np.sign(np.linalg.det(vt.T @ u.T)) + return vt.T @ np.diag([1.0, 1.0, reflection]) @ u.T + + +def superposed_rmsd(mobile, target): + """RMSD after optimal rigid superposition of two equal-length point sets. + + Fewer than three points do not define a rigid frame, so superposition is not + meaningful. One real benchmark target constrains only two motif atoms, so this is + reached in practice: fall back to the centroid-aligned RMSD, which is the tightest + well-defined answer, rather than raising. + """ + if mobile.shape != target.shape or mobile.ndim != 2 or mobile.shape[1] != 3: + raise ValueError("superposition needs matching [N, 3] point sets") + if mobile.shape[0] == 0: + raise ValueError("superposition needs at least one point") + if mobile.shape[0] < 3: + centred_mobile = mobile - mobile.mean(axis=0) + centred_target = target - target.mean(axis=0) + return float(np.sqrt(np.mean(np.sum( + (centred_mobile - centred_target) ** 2, axis=1)))) + left = mobile - mobile.mean(axis=0) + right = target - target.mean(axis=0) + rotated = left @ kabsch_rotation(left, right).T + return float(np.sqrt(np.mean(np.sum((rotated - right) ** 2, axis=1)))) + + +def backbone_aligned_motif_rmsd(design, design_mask, reference, reference_mask, restypes): + """RFdiffusion3's motif criterion: superimpose on motif N/CA/C, score all atoms. + + Aligning on every motif atom (including sidechains) lets a design trade sidechain + error against backbone error and flatters a scaffold that placed the backbone + badly. RFdiffusion3 aligns on the motif backbone only, then measures all-atom RMSD, + which is what actually has to be right for catalysis. + """ + shared = design_mask & reference_mask + backbone = shared.copy() + backbone[:, 4:] = False # slots 0-3 are N, CA, C, O + backbone[:, 3] = False # align on N, CA, C as RFdiffusion3 does + if backbone.sum() < 3: + # Too few backbone atoms to define a frame; fall back to all shared atoms. + backbone = shared + if shared.sum() == 0: + raise ValueError("motif has no shared atoms to compare") + + best = None + for variant in _symmetry_variants(reference, shared, restypes): + mobile = design[backbone] + target = variant[backbone] + offset_mobile = mobile.mean(axis=0) + offset_target = target.mean(axis=0) + rotation = kabsch_rotation(mobile - offset_mobile, target - offset_target) + moved = (design[shared] - offset_mobile) @ rotation.T + offset_target + value = float(np.sqrt(np.mean(np.sum((moved - variant[shared]) ** 2, axis=1)))) + best = value if best is None else min(best, value) + return best + + +def _symmetry_variants(reference, shared, restypes): + """Reference motif under every indistinguishable sidechain relabeling.""" + variants = [reference] + for index, residue_name in enumerate(restypes): + for left_name, right_name in SYMMETRIC_SWAPS.get(residue_name, ()): + left = atom_slot(residue_name, left_name) + right = atom_slot(residue_name, right_name) + if left is None or right is None: + continue + if not (shared[index, left] and shared[index, right]): + continue + swapped = [] + for variant in variants: + copy = variant.copy() + copy[index, [left, right]] = copy[index, [right, left]] + swapped.append(copy) + variants = variants + swapped + if len(variants) > 64: + variants = variants[:64] + return variants + + +def symmetric_motif_rmsd(design, design_mask, reference, reference_mask, restypes): + """Motif RMSD over shared atoms, minimised across symmetric sidechain relabelings. + + ASP OD1/OD2, GLU OE1/OE2, ARG NH1/NH2 and the PHE/TYR ring pairs are physically + indistinguishable, so a naive atom-by-atom RMSD penalises a correct design purely + for the order the atoms were written in. + """ + shared = design_mask & reference_mask + if shared.sum() < 3: + raise ValueError("motif has too few shared atoms to superimpose") + + variants = [reference] + for index, residue_name in enumerate(restypes): + for left_name, right_name in SYMMETRIC_SWAPS.get(residue_name, ()): + left, right = atom_slot(residue_name, left_name), atom_slot(residue_name, right_name) + if left is None or right is None: + continue + if not (shared[index, left] and shared[index, right]): + continue + swapped = [] + for variant in variants: + copy = variant.copy() + copy[index, [left, right]] = copy[index, [right, left]] + swapped.append(copy) + variants = variants + swapped + if len(variants) > 64: # bound the combinatorics on large motifs + variants = variants[:64] + return min(superposed_rmsd(design[shared], variant[shared]) for variant in variants) + + +def minimum_distance(left, right): + if left.size == 0 or right.size == 0: + return float("inf") + return float(np.sqrt(((left[:, None, :] - right[None, :, :]) ** 2).sum(-1)).min()) + + +def cluster_designs(traces): + """Greedy within-target clustering by superposed CA-RMSD; returns the cluster count.""" + centers = [] + for alpha in traces: + if not any(superposed_rmsd(alpha, other) < DIVERSITY_RMSD for other in centers): + centers.append(alpha) + return len(centers) diff --git a/reproduction/files/f5/f5801213b989eea6212c565d8176189b57e3dd011a82f7221fd33c47b498a50f/ensemble_predictions.py b/reproduction/files/f5/f5801213b989eea6212c565d8176189b57e3dd011a82f7221fd33c47b498a50f/ensemble_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..8fa76cc2f7957d247d7b5f2a13d895f24580f151 --- /dev/null +++ b/reproduction/files/f5/f5801213b989eea6212c565d8176189b57e3dd011a82f7221fd33c47b498a50f/ensemble_predictions.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Average compatible prediction files by key, never by implicit row order.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import numpy as np +import pyarrow as pa +import pyarrow.parquet as pq + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--input", type=Path, action="append", required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if len(args.input) < 2: + parser.error("at least two --input files are required") + + frames = [] + expected_ids = None + for path in args.input: + table = pq.read_table(path, columns=["sample_id", "disease_risk", "death_risk"]) + ids = table["sample_id"].to_pylist() + if len(ids) != len(set(ids)): + raise ValueError(f"duplicate sample_id in {path}") + by_id = {sample_id: i for i, sample_id in enumerate(ids)} + if expected_ids is None: + expected_ids = sorted(ids) + elif set(ids) != set(expected_ids): + raise ValueError(f"sample_id coverage differs in {path}") + order = np.asarray([by_id[sample_id] for sample_id in expected_ids]) + disease = np.asarray(table["disease_risk"].to_pylist(), dtype=np.float32)[order] + death = np.asarray(table["death_risk"].to_pylist(), dtype=np.float32)[order] + frames.append((disease, death)) + + disease = np.mean([frame[0] for frame in frames], axis=0, dtype=np.float64).astype(np.float32) + death = np.mean([frame[1] for frame in frames], axis=0, dtype=np.float64).astype(np.float32) + schema = pa.schema([ + pa.field("sample_id", pa.string()), + pa.field("disease_risk", pa.list_(pa.float32(), disease.shape[1])), + pa.field("death_risk", pa.list_(pa.float32(), death.shape[1])), + ]) + rows = [ + {"sample_id": sample_id, "disease_risk": disease[i].tolist(), "death_risk": death[i].tolist()} + for i, sample_id in enumerate(expected_ids) + ] + args.output.parent.mkdir(parents=True, exist_ok=True) + pq.write_table(pa.Table.from_pylist(rows, schema=schema), args.output, compression="zstd") + print(f"wrote {len(rows)} keyed predictions averaged across {len(frames)} inputs") + + +if __name__ == "__main__": + main() diff --git a/reproduction/files/f9/f9cba73943c246ec85d07cb3030906113ad5e5a11bad1fcb4d1df7ab05dca8a5/panels.py b/reproduction/files/f9/f9cba73943c246ec85d07cb3030906113ad5e5a11bad1fcb4d1df7ab05dca8a5/panels.py new file mode 100644 index 0000000000000000000000000000000000000000..cb18929529c7192bdc2e429a328826aa28c05844 --- /dev/null +++ b/reproduction/files/f9/f9cba73943c246ec85d07cb3030906113ad5e5a11bad1fcb4d1df7ab05dca8a5/panels.py @@ -0,0 +1,151 @@ +"""Small frozen, label-blind physical evaluation panels inside split v1.""" + +import argparse +from collections import Counter, defaultdict +import hashlib +import json +from pathlib import Path + +from common import digest, write_json +from splits import DEFAULT_SPLITS, load_split + +VERSION = "atomistic-physical-panels-v1" +DEFAULT_PANELS = Path(__file__).resolve().parents[2] / ".data/panels/v1/manifest.json" +COUNTS = { + "val": {"discovery": 1000, "phonons": 100, "elasticity": 100}, + "test": {"discovery": 5000, "phonons": 500, "elasticity": 500}, +} + + +def order(key): + return hashlib.sha256(f"{VERSION}:{key}".encode()).hexdigest() + + +def stratum(row): + size = next((n for n in [4, 8, 16, 32, 64, 128] if row["n_sites"] <= n), 99999) + elements = min(4, len(row["composition"].split("|"))) + return f"sites<={size}:elements={elements}" + + +def select(rows, count): + buckets = defaultdict(list) + for row in rows: + buckets[stratum(row)].append(row) + if count < len(buckets) or count > len(rows): + raise ValueError("Panel cannot cover occupied geometry strata") + allocations = {key: 1 for key in buckets} + # Largest proportional deficit allocation, with one per occupied stratum. + while sum(allocations.values()) < count: + key = max( + (k for k in buckets if allocations[k] < len(buckets[k])), + key=lambda k: ( + count * len(buckets[k]) / len(rows) - allocations[k], + order(k), + ), + ) + allocations[key] += 1 + selected, groups = [], Counter() + for key in sorted(buckets): + candidates = sorted(buckets[key], key=lambda r: order(r["id"])) + chosen = [] + # Prefer distinct composition groups, but never change split membership. + for cap in (1, 2, count): + for row in candidates: + if row["id"] in chosen or groups[row["group"]] >= cap: + continue + chosen.append(row["id"]) + groups[row["group"]] += 1 + if len(chosen) == allocations[key]: + break + if len(chosen) == allocations[key]: + break + selected.extend(chosen) + if len(set(selected)) != count: + raise ValueError("Panel lost/duplicated IDs") + return { + "ids": sorted(selected), + "cases": count, + "composition_groups": len(groups), + "strata": { + k: {"population": len(buckets[k]), "selected": allocations[k]} + for k in sorted(buckets) + }, + } + + +def freeze(output, regression_predictions=None): + if output.exists(): + raise FileExistsError(output) + rows, _ = load_split() + result = { + "version": VERSION, + "parent_split_manifest_sha256": digest(DEFAULT_SPLITS / "manifest.json"), + "selection": "Geometry size and chemical-complexity strata; proportional allocation with one per occupied stratum; SHA256 ordering; prefer distinct composition groups; no target/model labels", + "leaderboard_comparable": False, + "panels": {}, + } + for split, counts in COUNTS.items(): + result["panels"][split] = { + suite: select( + [r for r in rows if r["split"] == split and r["suite"] == suite], n + ) + for suite, n in counts.items() + } + if regression_predictions: + failed = [ + json.loads(line) + for line in regression_predictions.open() + if json.loads(line)["status"] == "failed" + ] + lookup = {r["id"]: r for r in rows} + if any(lookup[r["id"]]["split"] != "val" for r in failed): + raise ValueError("Regression cases must remain validation-only") + result["regression"] = { + "ids": sorted(r["id"] for r in failed), + "selection": "Known pilot failures; diagnostic only, excluded from representative aggregate", + "source_predictions_sha256": digest(regression_predictions), + } + write_json(output, result) + return result + + +V2_VALIDATION = {"phonons": 300, "elasticity": 300} + + +def enlarge(v1, output): + """Panels v2: v1 test panels and v1 discovery validation unchanged; larger phonon and + elasticity validation panels drawn by the same label-blind stratified rule.""" + if output.exists(): + raise FileExistsError(output) + result = json.loads(v1.read_text()) + rows, _ = load_split() + if result["parent_split_manifest_sha256"] != digest(DEFAULT_SPLITS / "manifest.json"): + raise ValueError("v1 panels belong to another split") + for suite, n in V2_VALIDATION.items(): + result["panels"]["val"][suite] = select( + [r for r in rows if r["split"] == "val" and r["suite"] == suite], n + ) + result.update(version="atomistic-physical-panels-v2", derived_from_v1_sha256=digest(v1)) + write_json(output, result) + return result + + +if __name__ == "__main__": + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--output", type=Path, default=DEFAULT_PANELS) + p.add_argument("--regression-predictions", type=Path) + p.add_argument("--enlarge-v1", type=Path, help="v1 manifest; write panels v2 instead") + args = p.parse_args() + if args.enlarge_v1: + r = enlarge(args.enlarge_v1, args.output) + else: + r = freeze(args.output, args.regression_predictions) + print( + json.dumps( + { + s: {k: v["cases"] for k, v in suites.items()} + for s, suites in r["panels"].items() + }, + indent=2, + ) + ) diff --git a/reproduction/files/fa/fa1ba1ab2276d0ca2066696025a421d789f5a4fc33a2ea94fab19b4a45ad40c4/test_download_mirror.py b/reproduction/files/fa/fa1ba1ab2276d0ca2066696025a421d789f5a4fc33a2ea94fab19b4a45ad40c4/test_download_mirror.py new file mode 100644 index 0000000000000000000000000000000000000000..84ba6b723d8569d8b770c0aae74f41c51d87af8d --- /dev/null +++ b/reproduction/files/fa/fa1ba1ab2276d0ca2066696025a421d789f5a4fc33a2ea94fab19b4a45ad40c4/test_download_mirror.py @@ -0,0 +1,94 @@ +"""No-network tests for delivering identical frozen data from our Hub mirror.""" +import contextlib +import copy +import hashlib +import io +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'environment/data')) +import materialize +import public_release as public + + +class DownloadMirrorTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.catalog = {'repo_id':'authors/source', 'revision':'a'*40, + 'directories':[{'name':'fixture','bytes':3}]} + self.release = {'release_id':'fixture-v1','training':{'case_ids':['fixture']}} + self.mirror = {'repo_id':'organizer/data','revision':'b'*40, + 'path_prefix':'environments','data_release_id':'fixture-v1', + 'data_release_sha256':public.digest(self.release)} + self.patch = patch.object(materialize, 'CATALOG', self.root/'catalog.json') + self.patch.start() + self.addCleanup(self.patch.stop) + + def write_mirror(self, value=None): + (self.root/'download-source.json').write_text(json.dumps(value or self.mirror)) + + def test_current_release_uses_pinned_data_repo(self): + self.write_mirror() + result=materialize.download_source(self.catalog,self.release,['fixture']) + self.assertEqual(result, {k:self.mirror[k] for k in ('repo_id','revision','path_prefix')}) + + def test_missing_mirror_preserves_legacy_source(self): + self.assertEqual(materialize.download_source(self.catalog,self.release,['fixture']), + {'repo_id':'authors/source','revision':'a'*40,'path_prefix':''}) + + def test_archive_and_extra_inventory_use_original_source(self): + self.write_mirror() + older=copy.deepcopy(self.release);older['release_id']='older' + for release,names in [(older,['fixture']),(self.release,['fixture','excluded'])]: + self.assertEqual(materialize.download_source(self.catalog,release,names)['repo_id'],'authors/source') + + def test_release_hash_must_match(self): + self.write_mirror(dict(self.mirror,data_release_sha256='wrong')) + with self.assertRaisesRegex(ValueError,'another frozen release'): + materialize.download_source(self.catalog,self.release,['fixture']) + + def test_unpinned_revision_and_unsafe_locations_rejected(self): + for field,value in [('revision','main'),('revision',None),('repo_id','https://host/path'), + ('repo_id',None),('path_prefix','../escape')]: + with self.subTest(field=field,value=value): + self.write_mirror(dict(self.mirror,**{field:value})) + with self.assertRaises(ValueError): + materialize.download_source(self.catalog,self.release,['fixture']) + + def test_download_layout_checksums_and_receipt_keep_source_identity(self): + index={'files':[{'rfilename':'fixture/input','size':3, + 'blobId':hashlib.sha1(b'blob 3\0abc').hexdigest()}]} + self.release['source_index_sha256']=public.digest(index) + self.mirror['data_release_sha256']=public.digest(self.release) + self.write_mirror() + (self.root/'source-files.json').write_text(json.dumps(index)) + (self.root/'catalog.json').write_text(json.dumps(self.catalog)) + target=self.root/'prepared' + def download(command, **kwargs): + self.assertEqual(command[2],'organizer/data') + self.assertEqual(command[command.index('--local-dir')+1],str(target)) + self.assertEqual(command[command.index('--include')+1],'environments/fixture/*') + payload=target/'environments/fixture/input' + payload.parent.mkdir(parents=True);payload.write_bytes(b'abc') + with patch.object(public,'load_release',return_value=self.release), \ + patch.object(public,'validate_index'), \ + patch.object(sys,'argv',['materialize',str(target),'--download']), \ + patch.object(materialize.subprocess,'run',side_effect=download), \ + contextlib.redirect_stdout(io.StringIO()): + materialize.main() + receipt=json.loads((target/'materialized.json').read_text()) + self.assertEqual(receipt['repo_id'],'authors/source') + self.assertEqual(receipt['revision'],'a'*40) + self.assertEqual(receipt['download_source']['repo_id'],'organizer/data') + self.assertEqual(receipt['download_source']['revision'],'b'*40) + self.assertEqual(receipt['data_release_sha256'],public.digest(self.release)) + self.assertEqual(receipt['verified_files'],1) + + +if __name__=='__main__':unittest.main() diff --git a/reproduction/files/fb/fb6694ac824865c7007fdac6e8296c82ce9db9596bccc3e5608cf8b472ff55a3/test_data.py b/reproduction/files/fb/fb6694ac824865c7007fdac6e8296c82ce9db9596bccc3e5608cf8b472ff55a3/test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..0f585714fa9b5fce834fffb59d5b3b82a6a76b06 --- /dev/null +++ b/reproduction/files/fb/fb6694ac824865c7007fdac6e8296c82ce9db9596bccc3e5608cf8b472ff55a3/test_data.py @@ -0,0 +1,199 @@ +"""Detector geometry, split isolation and experimental reference-bit checks. + +Set QEC_DATA_ROOT to the extracted Zenodo release to enable the integration +checks. The small generated-circuit checks always run without downloaded data. +""" + +from __future__ import annotations + +import os +from pathlib import Path +import sys + +import numpy as np +import pytest +import stim + +PROJECT = Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" if (Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit").is_dir() else Path(__file__).resolve().parents[1] # the baseline project: environment/baseline/alphaqubit here, /opt/task in the verifier image +sys.path.insert(0, str(PROJECT)) +from baselines.data import ( # noqa: E402 + CircuitSampler, + Condition, + DetectorLayout, + discover_conditions, + group_conditions, + hardware_split_indices, + load_hardware, + load_hardware_packed, +) + + +def make_condition(tmp_path: Path, distance: int, basis: str, rounds: int) -> Condition: + name = f"surface_code_b{basis}_d{distance}_r{rounds:02d}_center_5_5" + path = tmp_path / name + path.mkdir() + generator = f"surface_code:rotated_memory_{basis.lower()}" + ideal = stim.Circuit.generated(generator, distance=distance, rounds=rounds) + noisy = stim.Circuit.generated( + generator, distance=distance, rounds=rounds, + after_clifford_depolarization=0.01, + before_measure_flip_probability=0.02, + after_reset_flip_probability=0.01, + ) + ideal.to_file(path / "circuit_ideal.stim") + noisy.to_file(path / "circuit_noisy.stim") + noisy.detector_error_model(decompose_errors=True).to_file(path / "circuit_detector_error_model.dem") + return Condition(path, name, distance, basis, rounds, f"d{distance}_b{basis}_center_5_5") + + +@pytest.fixture(scope="module") +def hardware_root() -> Path: + value = os.environ.get("QEC_DATA_ROOT") or os.environ.get("SYCAMORE_DATA_ROOT") + if value is None: + pytest.skip("Set QEC_DATA_ROOT to run the downloaded Sycamore integration checks") + root = Path(value) + if not root.is_dir(): + pytest.fail(f"Configured Sycamore directory does not exist: {root}") + return root + + +def check_geometry(condition: Condition) -> None: + layout = DetectorLayout.from_condition(condition) + m = condition.distance**2 - 1 + circuit = stim.Circuit.from_file(condition.path / "circuit_ideal.stim") + # Each detector fires alone once, detecting omitted, duplicated, shifted or + # permuted detector mappings without relying on stochastic samples. + features = layout.decode_features(np.eye(circuit.num_detectors, dtype=np.bool_)) + recurrent, evaluation = features["rec_input"], features["eval_input"] + assert recurrent.shape == (m * condition.rounds, condition.rounds, m) + assert evaluation.shape == (m * condition.rounds, m // 2) + assert recurrent.dtype == evaluation.dtype == np.float32 + np.testing.assert_array_equal(recurrent.sum(axis=(1, 2)) + evaluation.sum(axis=1), 1.0) + for detector, (x, y, time) in circuit.get_detector_coordinates().items(): + if int(time) == condition.rounds: + assert evaluation[detector, layout.eval_coords.index((x, y))] == 1.0 + else: + assert recurrent[detector, int(time), layout.stabilizer_coords.index((x, y))] == 1.0 + off_basis = [i for i, coord in enumerate(layout.stabilizer_coords) if coord not in layout.eval_coords] + assert len(off_basis) == m // 2 + assert np.all(recurrent[:, 0, off_basis] == 0) + + +@pytest.mark.parametrize("distance", [3, 5]) +@pytest.mark.parametrize("basis", ["X", "Z"]) +@pytest.mark.parametrize("rounds", [1, 3, 25]) +def test_generated_geometry(tmp_path: Path, distance: int, basis: str, rounds: int) -> None: + check_geometry(make_condition(tmp_path, distance, basis, rounds)) + + +def test_discovery_numeric_order_and_grouping(tmp_path: Path) -> None: + make_condition(tmp_path, 3, "X", 11) + make_condition(tmp_path, 3, "X", 3) + make_condition(tmp_path, 5, "Z", 1) + (tmp_path / "repetition_code_bZ_d25_r50_center_5_5").mkdir() + (tmp_path / "README").write_text("Not a condition", encoding="utf-8") + groups = group_conditions(tmp_path) + assert list(groups) == ["d3_bX_center_5_5", "d5_bZ_center_5_5"] + assert [item.rounds for item in groups["d3_bX_center_5_5"]] == [3, 11] + assert len(discover_conditions(tmp_path)) == 3 + + +def test_hardware_splits_are_disjoint_and_exhaustive() -> None: + train = hardware_split_indices("train") + validation = hardware_split_indices("validation") + test = hardware_split_indices("test") + assert (len(train), len(validation), len(test)) == (19_880, 5_120, 25_000) + assert (train[0], train[-1]) == (0, 39_758) + assert (validation[0], validation[-1]) == (39_760, 49_998) + assert (test[0], test[-1]) == (1, 49_999) + assert np.all(train % 2 == 0) and np.all(validation % 2 == 0) + assert np.all(test % 2 == 1) + np.testing.assert_array_equal( + np.sort(np.concatenate([train, validation, test])), + hardware_split_indices("all"), + ) + with pytest.raises(ValueError, match="50,000 shots"): + hardware_split_indices("train", 1_000) + with pytest.raises(ValueError, match="Unknown hardware split"): + hardware_split_indices("invalid") # type: ignore[arg-type] + + +@pytest.mark.parametrize("noise_source", ["circuit", "dem"]) +@pytest.mark.parametrize("distance", [3, 5]) +def test_sampler_labels_shapes_and_reproducibility(tmp_path: Path, noise_source: str, distance: int) -> None: + condition = make_condition(tmp_path, distance, "Z", 3) + sampler_a = CircuitSampler(condition, seed=23, noise_source=noise_source) + sampler_b = CircuitSampler(condition, seed=23, noise_source=noise_source) + for shots in (1_024, 33): + packed, labels = sampler_a.sample_packed(shots) + other_packed, other_labels = sampler_b.sample_packed(shots) + np.testing.assert_array_equal(packed, other_packed) + np.testing.assert_array_equal(labels, other_labels) + assert packed.shape == (shots, (sampler_a.num_detectors + 7) // 8) + assert packed.dtype == labels.dtype == np.uint8 + assert labels.shape == (shots, 1) + assert np.all((labels == 0) | (labels == 1)) + assert np.count_nonzero(packed) > 0 + features = sampler_a.layout.decode_packed_features(packed) + unpacked = np.unpackbits(packed, axis=1, count=sampler_a.num_detectors, bitorder="little") + direct = sampler_a.layout.decode_features(unpacked) + assert set(features) == {"rec_input", "eval_input"} + for key in features: + assert features[key].dtype == np.float32 + assert np.isfinite(features[key]).all() + np.testing.assert_array_equal(features[key], direct[key]) + features, y = sampler_a.sample(8) + assert features["rec_input"].shape == (8, 3, distance**2 - 1) + assert features["eval_input"].shape == (8, (distance**2 - 1) // 2) + assert y.shape == (8, 1) and y.dtype == np.float32 + + +def test_hardware_all_layouts_and_round_one_order(hardware_root: Path) -> None: + groups = group_conditions(hardware_root) + assert len(groups) == 10 + assert sum(map(len, groups.values())) == 130 + for conditions in groups.values(): + assert [condition.rounds for condition in conditions] == list(range(1, 26, 2)) + layouts = [DetectorLayout.from_condition(condition) for condition in conditions] + assert all(layout.stabilizer_coords == layouts[0].stabilizer_coords for layout in layouts) + assert all(layout.eval_coords == layouts[0].eval_coords for layout in layouts) + for condition in conditions: + check_geometry(condition) + + +@pytest.mark.parametrize("distance,basis", [(3, "Z"), (5, "X")]) +def test_hardware_reference_conversion_and_split_loading( + hardware_root: Path, distance: int, basis: str +) -> None: + condition = next( + item for item in discover_conditions(hardware_root) + if item.distance == distance and item.basis == basis and item.rounds == 3 + ) + circuit = stim.Circuit.from_file(condition.path / "circuit_ideal.stim") + measurements = stim.read_shot_data_file( + path=str(condition.path / "measurements.b8"), format="b8", + num_measurements=circuit.num_measurements, + ) + sweeps = stim.read_shot_data_file( + path=str(condition.path / "sweep.b8"), format="b8", + num_measurements=circuit.num_sweep_bits, + ) + computed_dets, computed_obs = circuit.compile_m2d_converter().convert( + measurements=measurements, sweep_bits=sweeps, separate_observables=True, + ) + packed, labels = load_hardware_packed(condition, "all") + official_dets = np.unpackbits(packed, axis=1, count=circuit.num_detectors, bitorder="little") + assert len(labels) == 50_000 + np.testing.assert_array_equal(computed_dets, official_dets) + np.testing.assert_array_equal(computed_obs, labels) + # A raw-data-parity target is a different observable and would be a silent + # protocol bug even when its tensor dimensions look correct. + raw_parity = np.logical_xor.reduce(measurements[:, -(distance**2):], axis=1) + assert np.count_nonzero(raw_parity != labels[:, 0]) > 1_000 + all_features = DetectorLayout.from_condition(condition).decode_features(official_dets) + for split in ("train", "validation", "test"): + indices = hardware_split_indices(split) + features, y = load_hardware(condition, split) + np.testing.assert_array_equal(y, labels[indices].astype(np.float32)) + for key in all_features: + np.testing.assert_array_equal(features[key], all_features[key][indices]) diff --git a/reproduction/files/fc/fc15353447c19ae663aa77839f924350d4927f3548f143452b1db2dfd8fbe329/test_external_lfmc_metadata.py b/reproduction/files/fc/fc15353447c19ae663aa77839f924350d4927f3548f143452b1db2dfd8fbe329/test_external_lfmc_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..7bfd55c189ee9c119a403054c95a5f0b5902b812 --- /dev/null +++ b/reproduction/files/fc/fc15353447c19ae663aa77839f924350d4927f3548f143452b1db2dfd8fbe329/test_external_lfmc_metadata.py @@ -0,0 +1,111 @@ +"""Candidate site/date selection must not depend on heldout target values.""" + +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +import numpy as np +from openpyxl import Workbook + + +class TestMetadata(unittest.TestCase): + def test_targets_cannot_change_selection(self): + script = ( + Path(__file__).resolve().parents[1] + / "docs/downstream/external_lfmc_metadata.py" + ) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + coords = root / "coords.npy" + np.save(coords, np.array([[0.0, 0.0]])) + policy = { + "file_md5": "", + "woody_functional_types": ["tree"], + "coordinate_bounds": { + "min_lon": -20, + "max_lon": 180, + "min_lat": -60, + "max_lat": 75, + }, + "eligible_dates": ["2018-01-01", "2023-12-31"], + "minimum_distinct_dates_per_site": 3, + "maximum_sites": 200, + "maximum_dates_per_site": 12, + } + outputs = [] + for variant in range(2): + book = Workbook() + sheet = book.active + sheet.title = "LFMC data" + sheet.append( + [ + "Latitude (WGS84, EPSG:4326)", + "Longitude (WGS84, EPSG:4326)", + "Sampling date (YYYYMMDD)", + "Species functional type", + "Country", + "LFMC value (%)", + ] + ) + for day in [20180101, 20180201, 20180301]: + sheet.append( + [ + -30, + 150, + day, + "tree", + "Australia", + 50 if variant == 0 else -99999, + ] + ) + sheet.append( + [ + 0, + 0, + day, + "tree", + "Excluded location", + 50 if variant == 0 else 99999, + ] + ) + path = root / f"data{variant}.xlsx" + book.save(path) + with path.open("rb") as f: + policy["file_md5"] = hashlib.file_digest(f, "md5").hexdigest() + policy_path = root / "policy.json" + policy_path.write_text(json.dumps(policy)) + output = root / f"output{variant}.json" + result = subprocess.run( + [ + sys.executable, + str(script), + "--workbook", + str(path), + "--policy", + str(policy_path), + "--pretrain-coordinates", + str(coords), + "--output", + str(output), + ], + env=os.environ, + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + outputs.append(json.loads(output.read_text())) + self.assertEqual(outputs[0]["sites"], outputs[1]["sites"]) + self.assertEqual(outputs[0]["selected_sites"], 1) + self.assertEqual(outputs[0]["selected_site_dates"], 3) + self.assertFalse(outputs[0]["target_column_selected"]) + self.assertEqual( + outputs[0]["source_counters"]["pretraining_buffer_excluded_rows"], 3 + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/fc/fc3df6723f3a24a00c4cb2ba9e1b3c3c5f79e8244122b1f11d918382ba99b4b4/test_staged_verifier.py b/reproduction/files/fc/fc3df6723f3a24a00c4cb2ba9e1b3c3c5f79e8244122b1f11d918382ba99b4b4/test_staged_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..7682226a5eda7ea5a49fa8e24261f27d3f1b0d0a --- /dev/null +++ b/reproduction/files/fc/fc3df6723f3a24a00c4cb2ba9e1b3c3c5f79e8244122b1f11d918382ba99b4b4/test_staged_verifier.py @@ -0,0 +1,181 @@ +"""Deferred scoring must use the exact label-free independent replay.""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +import numpy as np +import grade + + +class StagedVerifierTest(unittest.TestCase): + def test_label_free_replay_tamper_rejection_and_real_cpu_scoring(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + model, data, output = (root / n for n in ["model", "data", "output"]) + model.mkdir() + for name in ["encoder.pt", "config.json", "infer.py", "LICENSE-OlmoEarth"]: + (model / name).write_text("fixture") + (model / "provenance.json").write_text( + json.dumps({"origin": "own_from_scratch_training"}) + ) + (model / "config.json").write_text("{}") + probes = root / "probes.py" + shutil.copyfile( + Path(__file__).resolve().parents[1] + / "environment/evaluation/probes.py", + probes, + ) + for task in ["awf", "lfmc"]: + (data / task).mkdir(parents=True) + (data / task / "inputs.h5").write_bytes(b"unlabeled-input-fixture") + rng = np.random.default_rng(17) + x = rng.normal(size=(110, 8)).astype(np.float32) + ids = np.array([f"id-{i}" for i in range(len(x))]) + command = [ + "grade.py", + "--model", + str(model), + "--data", + str(data), + "--output", + str(output), + "--probes", + str(probes), + ] + + def fake_replay(cmd, **kwargs): + self.assertTrue( + cmd[1].endswith("replay.py"), "Inference-only attempted scoring" + ) + target = Path(cmd[cmd.index("--output") + 1]) + np.savez(target / "features.npz", ids=ids, features=x) + return subprocess.CompletedProcess(cmd, 0) + + with ( + patch.object(sys, "argv", command + ["--inference-only"]), + patch.object(grade.subprocess, "run", side_effect=fake_replay), + ): + grade.main() + manifest = json.loads((output / "inference-manifest.json").read_text()) + self.assertFalse(manifest["labels_read"]) + self.assertFalse((output / "reward.json").exists()) + self.assertFalse(any(data.glob("*/labels.json"))) + for path in [ + model / "encoder.pt", + model / "infer.py", + data / "lfmc/inputs.h5", + output / "lfmc/features.npz", + probes, + ]: + original = path.read_bytes() + path.write_bytes(original + b"tampered") + with self.assertRaisesRegex( + ValueError, "artifacts or verifier code changed" + ): + grade.validate_manifest(manifest, model, data, output, probes) + path.write_bytes(original) + for task in ["awf", "lfmc"]: + rows = [ + { + "id": id_, + "label": int(x[i, 0] > 0) + if task == "awf" + else float(4 * x[i, 0] + 2 * x[i, 1]), + "split": "train" + if i < 70 + else "val" + if task == "awf" or i < 90 + else "test", + } + for i, id_ in enumerate(ids) + ] + (data / task / "labels.json").write_text(json.dumps(rows)) + real_run = subprocess.run + + def score_only(cmd, **kwargs): + self.assertEqual( + Path(cmd[1]), probes, "Deferred scoring attempted inference" + ) + return real_run(cmd, **kwargs, capture_output=True, text=True) + + with ( + patch.object(sys, "argv", command + ["--score-existing"]), + patch.object(grade.subprocess, "run", side_effect=score_only), + patch.dict( + os.environ, + { + "CUDA_VISIBLE_DEVICES": "", + "OMP_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + }, + ), + ): + grade.main() + result = json.loads((output / "reward.json").read_text()) + self.assertTrue(all(isinstance(v, (int, float)) for v in result.values())) + self.assertEqual( + json.loads((output / "report.json").read_text())["inference_manifest_sha256"], + grade.digest(output / "inference-manifest.json"), + ) + self.assertEqual( + result["reward"], + 0.5 + * (result["awf_validation_accuracy"] + result["lfmc_test_mae_skill"]), + ) + with patch.object(sys, "argv", command + ["--score-existing"]): + with self.assertRaisesRegex(ValueError, "Scoring already completed"): + grade.main() + full_output = root / "full-output" + full_command = command.copy() + full_command[full_command.index("--output") + 1] = str(full_output) + + def full_run(cmd, **kwargs): + if cmd[1].endswith("replay.py"): + return fake_replay(cmd, **kwargs) + return score_only(cmd, **kwargs) + + with ( + patch.object(sys, "argv", full_command), + patch.object(grade.subprocess, "run", side_effect=full_run), + patch.dict( + os.environ, + { + "CUDA_VISIBLE_DEVICES": "", + "OMP_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + }, + ), + ): + grade.main() + full_result = json.loads((full_output / "reward.json").read_text()) + for key in [ + "reward", + "awf_validation_accuracy", + "lfmc_test_mae", + "lfmc_test_mae_skill", + ]: + self.assertAlmostEqual(result[key], full_result[key], places=12) + for provenance, message in [ + ({"training_validity": "invalid"}, "invalid training"), + ({"origin": "official_public_pretrained_reference"}, "ineligible"), + ]: + (model / "provenance.json").write_text(json.dumps(provenance)) + invalid_command = command.copy() + invalid_output = root / ("invalid-" + str(len(message))) + invalid_command[invalid_command.index("--output") + 1] = str(invalid_output) + with patch.object(sys, "argv", invalid_command + ["--inference-only"]): + grade.main() + invalid = json.loads((invalid_output / "reward.json").read_text()) + self.assertEqual(invalid["reward"], 0) + self.assertIn(message, json.loads((invalid_output / "report.json").read_text())["reason"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/fc/fc4d7fe1616abab93006f69bc5e8f891cf9868025f2d279f617b8eaf180d4b3a/test_paper_evidence.py b/reproduction/files/fc/fc4d7fe1616abab93006f69bc5e8f891cf9868025f2d279f617b8eaf180d4b3a/test_paper_evidence.py new file mode 100644 index 0000000000000000000000000000000000000000..fd6d0485ab79c340758acfa895b0752cf05511e4 --- /dev/null +++ b/reproduction/files/fc/fc4d7fe1616abab93006f69bc5e8f891cf9868025f2d279f617b8eaf180d4b3a/test_paper_evidence.py @@ -0,0 +1,103 @@ +"""Evidence catalog integrity, not CFD execution or paper-performance proof.""" + +import hashlib +import json +from pathlib import Path +import unittest + + +TASK = Path(__file__).resolve().parents[1] + + +class PaperEvidenceTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.audit = json.loads((TASK / "environment/references/specialists/paper-targets.json").read_text()) + # These immutable paper targets describe the original 47-case release, + # not a regenerated set of claimed scores for the new speed selection. + cls.release = json.loads((TASK / "environment/data/release-500gb-v1.json").read_text()) + cls.cases = {case["id"]: case for case in cls.audit["cases"]} + + def test_exact_frozen_coverage_and_source_identity(self): + canonical = json.dumps(self.release, sort_keys=True, separators=(",", ":"), + allow_nan=False).encode() + self.assertEqual(self.audit["data_release_sha256"], hashlib.sha256(canonical).hexdigest()) + self.assertEqual(self.audit["data_release_id"], self.release["release_id"]) + self.assertEqual(self.audit["sources"]["data"]["revision"], self.release["source"]["revision"]) + self.assertEqual(self.audit["sources"]["platform"]["revision"], self.release["source"]["code_revision"]) + self.assertEqual(len(self.cases), 47) + self.assertEqual(len(self.audit["cases"]), 47) + self.assertEqual(list(self.cases), self.release["test"]["case_ids"]) + self.assertEqual(self.audit["benchmark_primary_metric"], self.release["test"]["primary_metric"]) + + def test_every_row_has_resolved_references_and_unchanged_public_values(self): + for source in self.release["cases"]: + with self.subTest(case=source["id"]): + row = self.cases[source["id"]] + self.assertIn(row["metric_profile"], self.audit["metric_profiles"]) + for ref in row["curve_refs"]: + self.assertIn(ref, self.audit["curve_evidence"]) + for ref in row["issue_refs"] + self.audit["global_unresolved"]: + self.assertIn(ref, self.audit["issues"]) + config = source["native_configuration"] + native = config.get("maia", config.get("jax", config.get("jaxfluids", {}))) + self.assertEqual(row["public_config_values"], { + "episode_limit": config.get("env", {}).get("max_episode_steps", + config.get("runner", {}).get("nb_interactions")), + "cfd_substeps": native.get("num_sim_substeps_per_actuation", native.get("steps_per_action")), + "action_inputs": native.get("num_action_inputs", native.get("num_actuators")), + "omega": native.get("omega"), + }) + + def test_curve_estimates_do_not_become_acceptance_scores(self): + self.assertEqual(self.audit["status"], "evidence-audit-not-executable-protocol") + counts = {} + for row in self.cases.values(): + status = row["learned_result_status"] + counts[status] = counts.get(status, 0) + 1 + self.assertEqual(row["paper_acceptance"], { + "metric": None, "target": None, "tolerance": None, "ready": False}) + self.assertEqual(counts, { + "case_plot_located_setup_unresolved": 5, + "family_plot_located_case_unresolved": 1, + "not_located_for_exact_variant": 41, + }) + for curve in self.audit["curve_evidence"].values(): + self.assertEqual(curve["readout_kind"], "coarse_visual_estimate_not_acceptance_target") + self.assertIsNone(curve["test_scalar_target"]) + for bounds in curve["approximate_training_endpoint_ranges"].values(): + self.assertEqual(len(bounds), 2) + self.assertLess(bounds[0], bounds[1]) + self.assertEqual(self.audit["curve_evidence"]["fig3b"]["training_seeds_reported"], 1) + self.assertEqual(self.audit["curve_evidence"]["ed2a"]["training_seeds_reported"], 3) + + def test_no_transfer_across_case_solver_or_actuation_identity(self): + self.assertEqual(self.cases["SquareCylinder_2D_Re200"]["curve_refs"], ["ed3c"]) + for source in self.release["cases"]: + row = self.cases[source["id"]] + if (source["backend"] == "firedrake" or source["id"].startswith("NACA0012") + or source["id"] in {"Cylinder_3D_Re200", "Cylinder_3D_Re3900", + "Cavity_2D_Re7500", "TCFmini_3D_Re180"}): + self.assertEqual(row["curve_refs"], [], source["id"]) + if source["backend"] == "firedrake": + self.assertIsNone(row["paper_training_defaults"]["cfd_steps_per_control_action"]) + self.assertIsNone(row["physics_validation"]) + + def test_physics_validation_is_separate_and_conflicts_remain_visible(self): + checks = [c["physics_validation"] for c in self.cases.values() if c["physics_validation"]] + self.assertEqual(len(checks), 15) + for check in checks: + self.assertEqual(check["kind"], "uncontrolled_flow_validation_not_learned_policy") + self.assertIsNone(check["averaging_window"]) + self.assertIsNone(check["acceptance_tolerance"]) + pinball = self.cases["Pinball_3D_Re150"] + self.assertEqual(pinball["physics_validation"]["values"]["mean_total_CD"], 2.949) + self.assertEqual(pinball["public_config_values"]["omega"], 0) + self.assertEqual(self.audit["metric_profiles"]["pinball"]["paper_parameters"]["omega"], 1) + self.assertIn("pinball_omega", pinball["issue_refs"]) + self.assertIn("cavity_reward", self.cases["Cavity_2D_Re7500"]["issue_refs"]) + self.assertIn("kolmogorov_objective", self.cases["Kolmogorov_2D"]["issue_refs"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/reproduction/files/fd/fd4fd42ae7269eee99efe48e4dc7eedb358271e703f495523790f4722e368d10/native_verifier.py b/reproduction/files/fd/fd4fd42ae7269eee99efe48e4dc7eedb358271e703f495523790f4722e368d10/native_verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..29bb4ac8cb67e61d26942fa73e738afd132b985a --- /dev/null +++ b/reproduction/files/fd/fd4fd42ae7269eee99efe48e4dc7eedb358271e703f495523790f4722e368d10/native_verifier.py @@ -0,0 +1,166 @@ +"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs. + +Prediction and trusted grading use separate jobs and mounts. Folding retains its +upstream single-process replay and is explicitly NOT called label-isolated. +No scientific verifier functions are replaced or monkey-patched. +""" +import hashlib +import json +import os +from pathlib import Path +import pwd +import shutil +import subprocess +import sys +import time + +import gpu_access +import runtime +import sealed_sandbox + +STATE = Path('/phase-state') + + +def status(phase, **details): + runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details}) + print(json.dumps({'phase': phase, **details}), flush=True) + + +def main(phase): + entered = time.monotonic() + plan = json.loads(Path('/operator/plan.json').read_text()) + cfg = plan['phases'][phase] + STATE.chmod(0o755) + status('preflight', task=plan['task'], role=phase) + for key in list(os.environ): + if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')): + os.environ.pop(key, None) + os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1', + HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1', + HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib') + os.environ.update(cfg.get('environment', {})) + for rel, expected in plan['verifier_source_sha256'].items(): + if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected: + raise RuntimeError(f'Frozen verifier source changed: {rel}') + cpus = cfg['cpu_count'] + affinity = sorted(os.sched_getaffinity(0)) + if len(affinity) < cpus: + raise RuntimeError('Insufficient allocated CPUs') + os.sched_setaffinity(0, affinity[:cpus]) + gpu_policy = None + if cfg['accessible_gpus']: + gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus']) + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids']) + gpu_access.restrict_device_access(gpu_policy['denied_devices']) + import torch + if torch.cuda.device_count() != cfg['accessible_gpus'] or not all( + 'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())): + raise RuntimeError('Verifier did not receive the required H100 devices') + else: + os.environ['CUDA_VISIBLE_DEVICES'] = '' + memory = sealed_sandbox.allocated_memory_limit() + if memory < cfg['memory_gib'] * 1024**3: + raise RuntimeError('Insufficient allocated RAM') + if phase == 'inference': + if plan['task'] != 'protein-folding-prediction': + for path in ('/private', '/labels'): + if Path(path).is_dir() and any(Path(path).iterdir()): + raise RuntimeError('Private labels unexpectedly mounted into inference') + package = Path('/workspace/submission') + if package.exists(): + raise RuntimeError('Expected a fresh local submission directory') + shutil.copytree('/submission-source', package, symlinks=True) + if runtime.fingerprint(package) != plan['submission_sha256']: + raise RuntimeError('Frozen submission fingerprint mismatch') + try: + agent = pwd.getpwnam('agent') + except KeyError: + subprocess.run(['useradd', '--create-home', '--uid', '10001', 'agent'], check=True) + agent = pwd.getpwnam('agent') + if agent.pw_uid != 10001: + raise RuntimeError('Unexpected inference user identity') + for path in [package, *package.rglob('*')]: + os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False) + Path('/logs').mkdir(exist_ok=True) + Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True) + (STATE / 'results').mkdir() + runtime.deny_network() + sealed_sandbox.filesystem( + readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels', + '/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64', + '/opt', '/etc', '/sys', '/run'], + # NVIDIA initialization requires writable procfs, as in the existing + # sealed adapter. Beaker's procfs protections and the upstream UID + # boundary still apply. Weka inputs and operator files stay read-only. + writable=['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc']) + # Root also inherits the write restriction; this protects Weka source mounts + # even for the upstream folding evaluator, which does not drop privileges. + try: + Path('/operator/.write-probe').write_text('must be denied') + except PermissionError: + pass + else: + raise RuntimeError('Operator source mount is writable') + if cfg['accessible_gpus']: + # Test a fresh CUDA process AFTER all restrictions, with the same UID + # used by the native verifier. A parent probe before Landlock can pass + # while the actual inference child cannot initialize CUDA. + uid = 0 if plan['task'] == 'protein-folding-prediction' else 10001 + def demote_probe(): + if uid: + os.setgid(uid) + os.setuid(uid) + probe = ( + 'import torch; ' + f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; ' + 'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 ' + 'for i in range(torch.cuda.device_count())); ' + 'print("CUDA_AFTER_SANDBOX_OK")') + probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', + 'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir, + 'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'], + 'PYTHONDONTWRITEBYTECODE': '1'} + with (STATE / 'gpu-child-probe.log').open('w') as log: + subprocess.run([cfg['command'][0], '-c', probe], env=probe_env, + preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT, + timeout=120, check=True) + receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'], + 'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False, + 'network': 'IPv4/IPv6 socket creation denied; inherited by children', + 'source_mounts': 'Landlock read-only', + 'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable', + 'label_isolated': plan['task'] != 'protein-folding-prediction', + 'scientific_scorer_modified': False} + runtime.write_json(STATE / 'preflight.json', receipt) + status('verifying', task=plan['task'], role=phase) + start = time.monotonic() + with (STATE / 'verifier.log').open('w') as log: + remaining = cfg['timeout_seconds'] - (time.monotonic() - entered) + if remaining <= 0: + raise TimeoutError('Verifier budget exhausted during initialization') + result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT, + timeout=remaining, start_new_session=True) + elapsed = time.monotonic() - entered + if result.returncode: + raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log') + reward_path = STATE / 'results/reward.json' + if phase == 'score': + for name in ('reward.json', 'report.json', 'agent_feedback.json'): + source = Path('/sealed/results') / name + if source.exists(): + shutil.copy2(source, STATE / 'results' / name) + reward = json.loads(reward_path.read_text()) if reward_path.exists() else None + ready = Path('/sealed/READY').is_file() + if reward is None and not (phase == 'inference' and ready): + raise RuntimeError('Verifier produced neither a reward nor sealed predictions') + status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed, + reward=reward, sealed_ready=ready) + + +if __name__ == '__main__': + try: + main(sys.argv[1]) + except Exception as error: + status('failed', error=f'{type(error).__name__}: {error}') + raise diff --git a/reproduction/files/ff/ff99dd71159323aab63b9ca61e7989dd94a087e07a3cda02a13f93a318722a64/test_prediction_contract.py b/reproduction/files/ff/ff99dd71159323aab63b9ca61e7989dd94a087e07a3cda02a13f93a318722a64/test_prediction_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..6024aaf7eda9aae1eb2a05b2654cb25ba189c6f1 --- /dev/null +++ b/reproduction/files/ff/ff99dd71159323aab63b9ca61e7989dd94a087e07a3cda02a13f93a318722a64/test_prediction_contract.py @@ -0,0 +1,303 @@ +"""Prediction integrity and label-free inference, using synthetic fixtures only.""" +from __future__ import annotations + +from pathlib import Path +import json +import sys +from typing import Any + +import numpy as np +import pytest +import stim + +PROJECT = Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit" if (Path(__file__).resolve().parents[1] / "environment" / "baseline" / "alphaqubit").is_dir() else Path(__file__).resolve().parents[1] # the baseline project: environment/baseline/alphaqubit here, /opt/task in the verifier image +sys.path.insert(0, str(PROJECT)) +from baselines.data import Condition, discover_conditions, hardware_split_indices # noqa: E402 +from baselines.predict import ( # noqa: E402 + atomic_prediction, predict_condition, run_prediction, sha256_file, + validate_model_metadata, +) +from baselines.score_neural import ( # noqa: E402 + CLASSICAL_METHODS, calibration_record, discover_predictions, expected_condition_names, + safe_summary, score_predictions, validate_inference_metadata, validate_prediction, +) + + +GROUP = "d3_bX_center_3_5" + + +def write_prediction(path: Path, indices: Any = None, probabilities: Any = None) -> None: + if indices is None: + indices = hardware_split_indices("validation").astype(np.uint64) + if probabilities is None: + probabilities = np.full(len(indices), 0.25, dtype=np.float32) + np.savez(path, shot_indices=indices, probabilities=probabilities) + + +@pytest.mark.parametrize("mode", ["missing_row", "duplicate_id", "wrong_id", "reordered", "nan", "infinite", "negative", "above_one", "column_vector", "float_ids"]) +def test_reject_malformed_prediction(tmp_path: Path, mode: str) -> None: + indices = hardware_split_indices("validation").astype(np.uint64) + probabilities = np.full(len(indices), 0.25, dtype=np.float32) + if mode == "missing_row": + indices, probabilities = indices[:-1], probabilities[:-1] + elif mode == "duplicate_id": + indices[1] = indices[0] + elif mode == "wrong_id": + indices[0] += np.uint64(1) + elif mode == "reordered": + indices = indices[::-1] + elif mode in {"nan", "infinite", "negative", "above_one"}: + probabilities[0] = {"nan": np.nan, "infinite": np.inf, "negative": -0.1, "above_one": 1.1}[mode] + elif mode == "column_vector": + probabilities = probabilities[:, None] + elif mode == "float_ids": + indices = indices.astype(np.float64) + path = tmp_path / "prediction.npz" + write_prediction(path, indices, probabilities) + with pytest.raises(ValueError): + validate_prediction(path) + + +@pytest.mark.parametrize("split", ["validation", "test"]) +def test_atomic_roundtrip_validates_original_order(tmp_path: Path, split: str) -> None: + path = tmp_path / "prediction.npz" + indices = hardware_split_indices(split) + probabilities = np.linspace(0, 1, len(indices), dtype=np.float32) + atomic_prediction(path, indices, probabilities) + actual_split, actual_indices, actual_probabilities = validate_prediction(path) + assert actual_split == split + np.testing.assert_array_equal(actual_indices, indices) + np.testing.assert_array_equal(actual_probabilities, probabilities) + assert list(tmp_path.iterdir()) == [path] + + +def test_condition_coverage_rejects_missing_and_duplicate(tmp_path: Path) -> None: + expected = expected_condition_names(GROUP) + first = sorted(expected)[0] + write_prediction(tmp_path / f"{first}.npz") + with pytest.raises(ValueError, match="coverage mismatch"): + discover_predictions(tmp_path, expected) + duplicate = tmp_path / "duplicate" + duplicate.mkdir() + write_prediction(duplicate / f"{first}.npz") + with pytest.raises(ValueError, match="Duplicate prediction"): + discover_predictions(tmp_path, {first}) + + +def test_unfit_ler_retains_all_counts_and_marks_null() -> None: + counts = {name: {"errors": 51, "total": 100} for name in expected_condition_names(GROUP)} + result = safe_summary(counts, bootstrap_samples=10, seed=1) + assert result["status"] == "unfit" + assert "P_fail < 0.5" in result["reason"] + assert len(result["per_condition"]) == 13 + assert sum(record["total"] for record in result["per_condition"].values()) == 1300 + assert result["per_group"][GROUP]["logical_error_per_round"] is None + assert result["macro"]["d3"]["logical_error_per_round"] is None + + +def test_calibration_uses_probabilities_and_preserves_endpoint_penalty() -> None: + result = calibration_record(np.array([0.0, 0.2, 1.0]), np.array([0, 1, 0])) + assert result["brier_score"] == pytest.approx((0.0 + 0.8**2 + 1.0) / 3) + assert result["negative_log_likelihood"] == pytest.approx((-np.log(1 - 1e-7) - np.log(0.2) - np.log(1e-7)) / 3) + + +def test_complete_synthetic_scoring_reports_unfit_and_calibration(tmp_path: Path) -> None: + data_root, predictions = tmp_path / "data", tmp_path / "predictions" + data_root.mkdir() + predictions.mkdir() + for name in expected_condition_names(GROUP): + folder = data_root / name + folder.mkdir() + (folder / "obs_flips_actual.01").write_text("0\n" * 50_000, encoding="ascii") + write_prediction(predictions / f"{name}.npz", probabilities=np.full(5120, 0.5, dtype=np.float32)) + result = score_predictions(predictions, data_root, group=GROUP, bootstrap_samples=10) + assert result["split"] == "validation" + assert result["total_shots"] == 13 * 5120 + assert result["summary"]["status"] == "unfit" + assert all(record["errors"] == 5120 for record in result["summary"]["per_condition"].values()) + assert result["calibration"]["macro"]["all"]["brier_score"] == 0.25 + + +def test_synthetic_paired_comparison_and_alignment_rejection(tmp_path: Path) -> None: + data_root, predictions, classical = tmp_path / "data", tmp_path / "predictions", tmp_path / "classical" + data_root.mkdir() + predictions.mkdir() + paired_directory = classical / "paired_errors" + paired_directory.mkdir(parents=True) + indices = hardware_split_indices("test") + for name in expected_condition_names(GROUP): + rounds = int(name.split("_r")[1].split("_")[0]) + folder = data_root / name + folder.mkdir() + (folder / "obs_flips_actual.01").write_text("0\n" * 50_000, encoding="ascii") + errors = np.arange(25_000) < int(25_000 * 0.005 * rounds) + probabilities = np.where(errors, 0.9, 0.1).astype(np.float32) + write_prediction(predictions / f"{name}.npz", indices.astype(np.uint64), probabilities) + np.savez(paired_directory / f"{name}.npz", shot_indices=indices, + actual=np.zeros(25_000, dtype=np.bool_), + **{f"errors__{method}": errors for method in CLASSICAL_METHODS}) + result = score_predictions(predictions, data_root, group=GROUP, classical_root=classical, bootstrap_samples=20) + assert result["summary"]["status"] == "ok" + assert result["summary"]["macro"]["d3"]["logical_error_per_round"] > 0 + for comparison in result["paired_comparisons"].values(): + assert comparison["status"] == "ok" + assert comparison["comparisons"][GROUP]["logical_error_per_round_a_minus_b"] == 0 + assert comparison["comparisons"][GROUP]["ci95"] == [0.0, 0.0] + first = paired_directory / f"{sorted(expected_condition_names(GROUP))[0]}.npz" + with np.load(first, allow_pickle=False) as record: + changed = {key: record[key] for key in record.files} + changed["shot_indices"] = changed["shot_indices"][::-1] + np.savez(first, **changed) + with pytest.raises(ValueError, match="shot IDs or actual labels disagree"): + score_predictions(predictions, data_root, group=GROUP, classical_root=classical, bootstrap_samples=20) + + +def test_predict_condition_uses_only_detectors_and_named_main_head(tmp_path: Path, monkeypatch: Any) -> None: + """No observable-label, sweep or measurement file exists in this fixture.""" + name = "surface_code_bX_d3_r03_center_3_5" + folder = tmp_path / name + folder.mkdir() + circuit = stim.Circuit.generated("surface_code:rotated_memory_x", distance=3, rounds=3) + circuit.to_file(folder / "circuit_ideal.stim") + width = (circuit.num_detectors + 7) // 8 + packed = np.zeros((50_000, width), dtype=np.uint8) + packed[39_760::4, 0] = 1 + packed.tofile(folder / "detection_events.b8") + condition = Condition(folder, name, 3, "X", 3, GROUP) + + class FakeModel: + input_names = ["eval_input", "rec_input"] + # Deliberately put the auxiliary head first; positional selection of + # output zero would silently produce the wrong prediction. + output_names = ["aux_output", "main_output"] + + def __call__(self, features: dict[str, Any], training: bool) -> list[Any]: + assert training is False + n = len(features["eval_input"]) + main = 0.1 + 0.7 * features["rec_input"].sum(axis=(1, 2))[:, None] + return [np.full((n, 1), 0.99), main] + + def forbid_labels(*args: Any, **kwargs: Any) -> Any: + raise AssertionError("Inference attempted to read a shot-data label file") + + monkeypatch.setattr(stim, "read_shot_data_file", forbid_labels) + indices, probabilities = predict_condition(FakeModel(), condition, "validation", batch_size=79) + np.testing.assert_array_equal(indices, hardware_split_indices("validation")) + # Account for the exact global-to-path transform rather than assuming its + # mask is empty for the generated circuit. + from baselines.observables import ObservableTransform + transform = ObservableTransform.from_condition(condition) + global_probabilities = np.tile(np.array([0.8, 0.1], dtype=np.float32), 2560)[:, None] + expected = transform.global_to_path_probabilities_packed(packed[indices], global_probabilities)[:, 0] + np.testing.assert_allclose(probabilities, expected, atol=1e-7) + + +@pytest.mark.parametrize("invalid", ["label_mode", "group", "distance", "model_sha256"]) +def test_checkpoint_metadata_rejects_incompatible_model(tmp_path: Path, invalid: str) -> None: + model_path = tmp_path / "best.keras" + model_path.write_bytes(b"fixture checkpoint") + record = {"label_mode": "qrennd_global_data_parity", "group": GROUP, "distance": 3, + "model_sha256": sha256_file(model_path)} + record[invalid] = "incompatible" + path = tmp_path / "metadata.json" + path.write_text(json.dumps(record), encoding="utf-8") + with pytest.raises(ValueError): + validate_model_metadata(path, model_path, GROUP, 3) + + +@pytest.mark.parametrize("invalid", ["status", "split", "prediction_hash", "detector_hash", "circuit_hash", "model_label", "group", "checkpoint_hash", "shots", "missing_condition"]) +def test_inference_metadata_rejects_incomplete_or_tampered_artifacts(tmp_path: Path, invalid: str) -> None: + name = sorted(expected_condition_names(GROUP))[0] + folder = tmp_path / "data" / name + folder.mkdir(parents=True) + (folder / "circuit_ideal.stim").write_bytes(b"circuit fixture") + (folder / "detection_events.b8").write_bytes(b"detector fixture") + prediction_root = tmp_path / "predictions" + prediction_root.mkdir() + prediction = prediction_root / f"{name}.npz" + write_prediction(prediction) + conditions = {name: Condition(folder, name, 3, "X", 1, GROUP)} + counts = {name: {"total": 5120, "errors": 0}} + hashes = {name: sha256_file(prediction)} + metadata = { + "status": "complete", "split": "validation", "group": GROUP, + "prediction_label_mode": "official_path_observable_flip", "model_label_mode": "qrennd_global_data_parity", + "model_sha256": "0" * 64, + "checkpoint_metadata": {"label_mode": "qrennd_global_data_parity", "group": GROUP, "model_sha256": "0" * 64}, + "conditions": {name: {"shots": 5120, "prediction_sha256": hashes[name], + "detectors_sha256": sha256_file(folder / "detection_events.b8"), + "circuit_sha256": sha256_file(folder / "circuit_ideal.stim")}}, + } + metadata_path = prediction_root / "metadata.json" + metadata_path.write_text(json.dumps(metadata), encoding="utf-8") + assert len(validate_inference_metadata(prediction_root, "validation", conditions, hashes, counts)) == 1 + if invalid == "status": + metadata["status"] = "running" + elif invalid == "split": + metadata["split"] = "test" + elif invalid == "prediction_hash": + metadata["conditions"][name]["prediction_sha256"] = "f" * 64 + elif invalid in {"detector_hash", "circuit_hash"}: + filename = "detection_events.b8" if invalid == "detector_hash" else "circuit_ideal.stim" + (folder / filename).write_bytes(b"different input fixture") + elif invalid == "model_label": + metadata["model_label_mode"] = "official_path_observable_flip" + elif invalid == "group": + metadata["group"] = "d3_bZ_center_3_5" + elif invalid == "checkpoint_hash": + metadata["checkpoint_metadata"]["model_sha256"] = "f" * 64 + elif invalid == "shots": + metadata["conditions"][name]["shots"] = 5119 + elif invalid == "missing_condition": + metadata["conditions"] = {} + metadata_path.write_text(json.dumps(metadata), encoding="utf-8") + with pytest.raises(ValueError): + validate_inference_metadata(prediction_root, "validation", conditions, hashes, counts) + + +def test_portable_standard_keras_replay_without_labels(tmp_path: Path, monkeypatch: Any) -> None: + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "") + monkeypatch.setenv("TF_NUM_INTRAOP_THREADS", "1") + monkeypatch.setenv("TF_NUM_INTEROP_THREADS", "1") + tf = pytest.importorskip("tensorflow") + data_root = tmp_path / "data" + data_root.mkdir() + for name in expected_condition_names(GROUP): + rounds = int(name.split("_r")[1].split("_")[0]) + folder = data_root / name + folder.mkdir() + circuit = stim.Circuit.generated("surface_code:rotated_memory_x", distance=3, rounds=rounds) + circuit.to_file(folder / "circuit_ideal.stim") + np.zeros((50_000, (circuit.num_detectors + 7) // 8), dtype=np.uint8).tofile(folder / "detection_events.b8") + recurrent = tf.keras.Input(shape=(None, 8), name="rec_input") + evaluation = tf.keras.Input(shape=(4,), name="eval_input") + hidden = tf.keras.layers.Concatenate()([tf.keras.layers.GlobalAveragePooling1D()(recurrent), evaluation]) + main = tf.keras.layers.Dense(1, activation="sigmoid", name="main_output", kernel_initializer="zeros", bias_initializer="zeros")(hidden) + auxiliary = tf.keras.layers.Dense(1, activation="sigmoid", name="aux_output")(hidden) + model = tf.keras.Model([recurrent, evaluation], [auxiliary, main]) + model_path = tmp_path / "best.keras" + model.save(model_path) + (tmp_path / "metadata.json").write_text(json.dumps({ + "label_mode": "qrennd_global_data_parity", "group": GROUP, "distance": 3, + "model_sha256": sha256_file(model_path), + }), encoding="utf-8") + + def forbid_labels(*args: Any, **kwargs: Any) -> Any: + raise AssertionError("Inference attempted to read labels") + + monkeypatch.setattr(stim, "read_shot_data_file", forbid_labels) + result = run_prediction(model_path, data_root, GROUP, "validation", tmp_path / "predictions") + assert result["status"] == "complete" + assert result["model_sha256"] == sha256_file(model_path) + assert result["model_label_mode"] == "qrennd_global_data_parity" + assert result["prediction_label_mode"] == "official_path_observable_flip" + assert len(result["conditions"]) == 13 + for path in (tmp_path / "predictions").glob("*.npz"): + split, _, probabilities = validate_prediction(path) + assert split == "validation" + np.testing.assert_array_equal(probabilities, np.full(5120, 0.5, dtype=np.float32)) + conditions = {item.name: item for item in discover_conditions(data_root)} + hashes = {name: sha256_file(tmp_path / "predictions" / f"{name}.npz") for name in conditions} + counts = {name: {"total": 5120, "errors": 0} for name in conditions} + metadata = validate_inference_metadata(tmp_path / "predictions", "validation", conditions, hashes, counts) + assert len(metadata) == 1 diff --git a/restore_submission.py b/restore_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..16e6425a827c3e18308e2783ac8df9c862807e8e --- /dev/null +++ b/restore_submission.py @@ -0,0 +1,79 @@ +"""Restore the recorded export's files/modes without executing submitted code. + +For explicitly marked inference subsets, the export fingerprint differs from the +original full directory fingerprint; both are recorded in the package index. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path + + +def contained(root, relative): + p = root / relative + p.resolve().relative_to(root.resolve()) + return p + + +def restore(index_path, candidate, destination, repo_id=None, revision=None): + index_path, destination = Path(index_path).resolve(), Path(destination) + # tasks///index.json + repo = index_path.parents[3] + index = json.loads(index_path.read_text()) + package = index['finalization']['package'] if candidate == 'GRACE_FINAL' else index['packages'][candidate] + destination.mkdir(parents=True, exist_ok=False) + for entry in package['entries']: + p = contained(destination, entry['name']) + if entry['kind'] == 'directory': + p.mkdir(parents=True, exist_ok=True) + elif entry['kind'] == 'file': + src = contained(repo, entry['stored']['path']) + if not src.is_file() and repo_id: + from huggingface_hub import hf_hub_download + src = Path(hf_hub_download(repo_id, entry['stored']['path'], + repo_type='dataset', revision=revision)) + p.parent.mkdir(parents=True, exist_ok=True) + sha = hashlib.sha256() + with src.open('rb') as stream, p.open('wb') as out: + for chunk in iter(lambda: stream.read(8 << 20), b''): + sha.update(chunk) + out.write(chunk) + if sha.hexdigest() != entry['stored']['sha256']: + raise ValueError('File checksum mismatch: ' + entry['name']) + os.chmod(p, entry['mode']) + elif entry['kind'] == 'symlink': + p.parent.mkdir(parents=True, exist_ok=True) + contained(destination, str(Path(entry['name']).parent / entry['target'])) + p.symlink_to(entry['target']) + else: + raise ValueError('Unsupported entry kind') + for entry in reversed(package['entries']): + if entry['kind'] == 'directory': + os.chmod(contained(destination, entry['name']), entry['mode']) + digest = hashlib.sha256() + for p in sorted(destination.rglob('*')): + rel = str(p.relative_to(destination)) + digest.update(rel.encode() + b'\0') + if p.is_symlink(): + p.resolve(strict=True).relative_to(destination.resolve()) + digest.update(b'link:' + os.readlink(p).encode()) + elif p.is_file(): + digest.update(str(p.stat().st_mode & 0o777).encode()) + with p.open('rb') as f: + for chunk in iter(lambda: f.read(8 << 20), b''): + digest.update(chunk) + if digest.hexdigest() != package['fingerprint']: + raise ValueError('Reconstructed package fingerprint mismatch') + print(json.dumps({'verified': True, 'candidate': candidate, 'fingerprint': digest.hexdigest()})) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('index', type=Path) + parser.add_argument('candidate') + parser.add_argument('destination', type=Path) + parser.add_argument('--repo', help='Optionally download only missing files from this Hugging Face dataset') + parser.add_argument('--revision', help='Optional pinned Hugging Face commit') + a = parser.parse_args() + restore(a.index, a.candidate, a.destination, a.repo, a.revision) diff --git a/shared/package-files/00/00045245f8b241ad05bba8c205d871f37c893977425ad7ecd2ad1877c98cc708/blob b/shared/package-files/00/00045245f8b241ad05bba8c205d871f37c893977425ad7ecd2ad1877c98cc708/blob new file mode 100644 index 0000000000000000000000000000000000000000..535efee51937473071c9490330eb68364769d5aa --- /dev/null +++ b/shared/package-files/00/00045245f8b241ad05bba8c205d871f37c893977425ad7ecd2ad1877c98cc708/blob @@ -0,0 +1,13 @@ +from pandas.core.arrays import IntervalArray + + +def test_repr(): + # GH#25022 + arr = IntervalArray.from_tuples([(0, 1), (1, 2)]) + result = repr(arr) + expected = ( + "\n" + "[(0, 1], (1, 2]]\n" + "Length: 2, dtype: interval[int64, right]" + ) + assert result == expected diff --git a/shared/package-files/00/0007b59dd4462717573a7145e8565e375adbc80a753102e28186e1ad46031cc1/blob b/shared/package-files/00/0007b59dd4462717573a7145e8565e375adbc80a753102e28186e1ad46031cc1/blob new file mode 100644 index 0000000000000000000000000000000000000000..4f283c7ac8b7f15010b48ad60a6a0749cfc30baf --- /dev/null +++ b/shared/package-files/00/0007b59dd4462717573a7145e8565e375adbc80a753102e28186e1ad46031cc1/blob @@ -0,0 +1,30 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor div(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & div_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & div_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & div_(at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor div(const at::Tensor & self, const at::Tensor & other, c10::optional rounding_mode); +TORCH_API at::Tensor & div_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other, c10::optional rounding_mode); +TORCH_API at::Tensor & div_outf(const at::Tensor & self, const at::Tensor & other, c10::optional rounding_mode, at::Tensor & out); +TORCH_API at::Tensor & div_(at::Tensor & self, const at::Tensor & other, c10::optional rounding_mode); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/00/0008e8c8ac10d3a9b65e2825152e8287f71d836a78fb0900ec66a4188fde5f51/blob b/shared/package-files/00/0008e8c8ac10d3a9b65e2825152e8287f71d836a78fb0900ec66a4188fde5f51/blob new file mode 100644 index 0000000000000000000000000000000000000000..e2b911fafdbbc2ec95d0de4233b6bbb663ffa44e --- /dev/null +++ b/shared/package-files/00/0008e8c8ac10d3a9b65e2825152e8287f71d836a78fb0900ec66a4188fde5f51/blob @@ -0,0 +1,157 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/io/interfaces.h" +#include "arrow/util/type_fwd.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace io { + +struct ARROW_EXPORT CacheOptions { + static constexpr double kDefaultIdealBandwidthUtilizationFrac = 0.9; + static constexpr int64_t kDefaultMaxIdealRequestSizeMib = 64; + + /// \brief The maximum distance in bytes between two consecutive + /// ranges; beyond this value, ranges are not combined + int64_t hole_size_limit; + /// \brief The maximum size in bytes of a combined range; if + /// combining two consecutive ranges would produce a range of a + /// size greater than this, they are not combined + int64_t range_size_limit; + /// \brief A lazy cache does not perform any I/O until requested. + /// lazy = false: request all byte ranges when PreBuffer or WillNeed is called. + /// lazy = True, prefetch_limit = 0: request merged byte ranges only after the reader + /// needs them. + /// lazy = True, prefetch_limit = k: prefetch up to k merged byte ranges ahead of the + /// range that is currently being read. + bool lazy; + /// \brief The maximum number of ranges to be prefetched. This is only used + /// for lazy cache to asynchronously read some ranges after reading the target range. + int64_t prefetch_limit = 0; + + bool operator==(const CacheOptions& other) const { + return hole_size_limit == other.hole_size_limit && + range_size_limit == other.range_size_limit && lazy == other.lazy && + prefetch_limit == other.prefetch_limit; + } + + /// \brief Construct CacheOptions from network storage metrics (e.g. S3). + /// + /// \param[in] time_to_first_byte_millis Seek-time or Time-To-First-Byte (TTFB) in + /// milliseconds, also called call setup latency of a new read request. + /// The value is a positive integer. + /// \param[in] transfer_bandwidth_mib_per_sec Data transfer Bandwidth (BW) in MiB/sec + /// (per connection). + /// The value is a positive integer. + /// \param[in] ideal_bandwidth_utilization_frac Transfer bandwidth utilization fraction + /// (per connection) to maximize the net data load. + /// The value is a positive double precision number less than 1. + /// \param[in] max_ideal_request_size_mib The maximum single data request size (in MiB) + /// to maximize the net data load. + /// The value is a positive integer. + /// \return A new instance of CacheOptions. + static CacheOptions MakeFromNetworkMetrics( + int64_t time_to_first_byte_millis, int64_t transfer_bandwidth_mib_per_sec, + double ideal_bandwidth_utilization_frac = kDefaultIdealBandwidthUtilizationFrac, + int64_t max_ideal_request_size_mib = kDefaultMaxIdealRequestSizeMib); + + static CacheOptions Defaults(); + static CacheOptions LazyDefaults(); +}; + +namespace internal { + +/// \brief A read cache designed to hide IO latencies when reading. +/// +/// This class takes multiple byte ranges that an application expects to read, and +/// coalesces them into fewer, larger read requests, which benefits performance on some +/// filesystems, particularly remote ones like Amazon S3. By default, it also issues +/// these read requests in parallel up front. +/// +/// To use: +/// 1. Cache() the ranges you expect to read in the future. Ideally, these ranges have +/// the exact offset and length that will later be read. The cache will combine those +/// ranges according to parameters (see constructor). +/// +/// By default, the cache will also start fetching the combined ranges in parallel in +/// the background, unless CacheOptions.lazy is set. +/// +/// 2. Call WaitFor() to be notified when the given ranges have been read. If +/// CacheOptions.lazy is set, I/O will be triggered in the background here instead. +/// This can be done in parallel (e.g. if parsing a file, call WaitFor() for each +/// chunk of the file that can be parsed in parallel). +/// +/// 3. Call Read() to retrieve the actual data for the given ranges. +/// A synchronous application may skip WaitFor() and just call Read() - it will still +/// benefit from coalescing and parallel fetching. +class ARROW_EXPORT ReadRangeCache { + public: + static constexpr int64_t kDefaultHoleSizeLimit = 8192; + static constexpr int64_t kDefaultRangeSizeLimit = 32 * 1024 * 1024; + + /// Construct a read cache with default + explicit ReadRangeCache(std::shared_ptr file, IOContext ctx) + : ReadRangeCache(file, file.get(), std::move(ctx), CacheOptions::Defaults()) {} + + /// Construct a read cache with given options + explicit ReadRangeCache(std::shared_ptr file, IOContext ctx, + CacheOptions options) + : ReadRangeCache(file, file.get(), std::move(ctx), options) {} + + /// Construct a read cache with an unowned file + ReadRangeCache(RandomAccessFile* file, IOContext ctx, CacheOptions options) + : ReadRangeCache(NULLPTR, file, std::move(ctx), options) {} + + ~ReadRangeCache(); + + /// \brief Cache the given ranges in the background. + /// + /// The caller must ensure that the ranges do not overlap with each other, + /// nor with previously cached ranges. Otherwise, behaviour will be undefined. + Status Cache(std::vector ranges); + + /// \brief Read a range previously given to Cache(). + Result> Read(ReadRange range); + + /// \brief Wait until all ranges added so far have been cached. + Future<> Wait(); + + /// \brief Wait until all given ranges have been cached. + Future<> WaitFor(std::vector ranges); + + protected: + struct Impl; + struct LazyImpl; + + ReadRangeCache(std::shared_ptr owned_file, RandomAccessFile* file, + IOContext ctx, CacheOptions options); + + std::unique_ptr impl_; +}; + +} // namespace internal +} // namespace io +} // namespace arrow diff --git a/shared/package-files/00/000c00bad31d126b054c6ec7f3e02b27c0f9a4d579f987d3c4f879cee1bacb81/blob b/shared/package-files/00/000c00bad31d126b054c6ec7f3e02b27c0f9a4d579f987d3c4f879cee1bacb81/blob new file mode 100644 index 0000000000000000000000000000000000000000..7746ea2601024ceb7e750472753fcfc80fa2bd01 --- /dev/null +++ b/shared/package-files/00/000c00bad31d126b054c6ec7f3e02b27c0f9a4d579f987d3c4f879cee1bacb81/blob @@ -0,0 +1,11 @@ + +try: + from _decimal import * + from _decimal import __doc__ + from _decimal import __version__ + from _decimal import __libmpdec_version__ +except ImportError: + from _pydecimal import * + from _pydecimal import __doc__ + from _pydecimal import __version__ + from _pydecimal import __libmpdec_version__ diff --git a/shared/package-files/00/000e5dc946825256d2293b2c92b4393177dedfbe526495d22aadd95e734c2e29/blob b/shared/package-files/00/000e5dc946825256d2293b2c92b4393177dedfbe526495d22aadd95e734c2e29/blob new file mode 100644 index 0000000000000000000000000000000000000000..e8489e4ad8161ba8b53f2f16918fa0a992babe3f --- /dev/null +++ b/shared/package-files/00/000e5dc946825256d2293b2c92b4393177dedfbe526495d22aadd95e734c2e29/blob @@ -0,0 +1,120 @@ +""" +Tests for CategoricalIndex.__repr__ and related methods. +""" +import pytest + +from pandas._config import using_string_dtype +import pandas._config.config as cf + +from pandas import CategoricalIndex +import pandas._testing as tm + + +class TestCategoricalIndexRepr: + def test_format_different_scalar_lengths(self): + # GH#35439 + idx = CategoricalIndex(["aaaaaaaaa", "b"]) + expected = ["aaaaaaaaa", "b"] + msg = r"CategoricalIndex\.format is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert idx.format() == expected + + @pytest.mark.xfail(using_string_dtype(), reason="repr different") + def test_string_categorical_index_repr(self): + # short + idx = CategoricalIndex(["a", "bb", "ccc"]) + expected = """CategoricalIndex(['a', 'bb', 'ccc'], categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" # noqa: E501 + assert repr(idx) == expected + + # multiple lines + idx = CategoricalIndex(["a", "bb", "ccc"] * 10) + expected = """CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', + 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', + 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'], + categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" # noqa: E501 + + assert repr(idx) == expected + + # truncated + idx = CategoricalIndex(["a", "bb", "ccc"] * 100) + expected = """CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', + ... + 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'], + categories=['a', 'bb', 'ccc'], ordered=False, dtype='category', length=300)""" # noqa: E501 + + assert repr(idx) == expected + + # larger categories + idx = CategoricalIndex(list("abcdefghijklmmo")) + expected = """CategoricalIndex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', + 'm', 'm', 'o'], + categories=['a', 'b', 'c', 'd', ..., 'k', 'l', 'm', 'o'], ordered=False, dtype='category')""" # noqa: E501 + + assert repr(idx) == expected + + # short + idx = CategoricalIndex(["あ", "いい", "ううう"]) + expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501 + assert repr(idx) == expected + + # multiple lines + idx = CategoricalIndex(["あ", "いい", "ううう"] * 10) + expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', + 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'], + categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501 + + assert repr(idx) == expected + + # truncated + idx = CategoricalIndex(["あ", "いい", "ううう"] * 100) + expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', + ... + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'], + categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)""" # noqa: E501 + + assert repr(idx) == expected + + # larger categories + idx = CategoricalIndex(list("あいうえおかきくけこさしすせそ")) + expected = """CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', 'さ', 'し', + 'す', 'せ', 'そ'], + categories=['あ', 'い', 'う', 'え', ..., 'し', 'す', 'せ', 'そ'], ordered=False, dtype='category')""" # noqa: E501 + + assert repr(idx) == expected + + # Enable Unicode option ----------------------------------------- + with cf.option_context("display.unicode.east_asian_width", True): + # short + idx = CategoricalIndex(["あ", "いい", "ううう"]) + expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501 + assert repr(idx) == expected + + # multiple lines + idx = CategoricalIndex(["あ", "いい", "ううう"] * 10) + expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', + 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'], + categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501 + + assert repr(idx) == expected + + # truncated + idx = CategoricalIndex(["あ", "いい", "ううう"] * 100) + expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', + 'ううう', 'あ', + ... + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', + 'あ', 'いい', 'ううう'], + categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)""" # noqa: E501 + + assert repr(idx) == expected + + # larger categories + idx = CategoricalIndex(list("あいうえおかきくけこさしすせそ")) + expected = """CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', + 'さ', 'し', 'す', 'せ', 'そ'], + categories=['あ', 'い', 'う', 'え', ..., 'し', 'す', 'せ', 'そ'], ordered=False, dtype='category')""" # noqa: E501 + + assert repr(idx) == expected diff --git a/shared/package-files/00/00134f5868c683a2db9fdc2ba78c6faea9255e30ac1e214833ee9a9f1d0b2efb/blob b/shared/package-files/00/00134f5868c683a2db9fdc2ba78c6faea9255e30ac1e214833ee9a9f1d0b2efb/blob new file mode 100644 index 0000000000000000000000000000000000000000..93fa2890a363346ec5d30d73cf4f4c66d15e4176 --- /dev/null +++ b/shared/package-files/00/00134f5868c683a2db9fdc2ba78c6faea9255e30ac1e214833ee9a9f1d0b2efb/blob @@ -0,0 +1,25 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor _sparse_log_softmax(const at::Tensor & self, int64_t dim, c10::optional dtype=c10::nullopt); +TORCH_API at::Tensor _sparse_log_softmax(const at::Tensor & self, at::Dimname dim, c10::optional dtype=c10::nullopt); +TORCH_API at::Tensor & _sparse_log_softmax_out(const at::Tensor & self, int64_t dim, bool half_to_float, at::Tensor & out); +TORCH_API at::Tensor log_softmax_sparse_cpu(const at::Tensor & self, int64_t dim, bool half_to_float); +TORCH_API at::Tensor log_softmax_sparse_cuda(const at::Tensor & self, int64_t dim, bool half_to_float); +} // namespace native +} // namespace at diff --git a/shared/package-files/00/00167e2f2c3e8a02b0045a0b177418b4599fbadc192e201d59ca5131b71a7065/blob b/shared/package-files/00/00167e2f2c3e8a02b0045a0b177418b4599fbadc192e201d59ca5131b71a7065/blob new file mode 100644 index 0000000000000000000000000000000000000000..e7053bac12fdb7b2cc50448f88318cd93f62cc0e --- /dev/null +++ b/shared/package-files/00/00167e2f2c3e8a02b0045a0b177418b4599fbadc192e201d59ca5131b71a7065/blob @@ -0,0 +1,20 @@ +import functools + + +# from jaraco.functools 3.5 +def pass_none(func): + """ + Wrap func so it's not called if its first param is None + + >>> print_text = pass_none(print) + >>> print_text('text') + text + >>> print_text(None) + """ + + @functools.wraps(func) + def wrapper(param, *args, **kwargs): + if param is not None: + return func(param, *args, **kwargs) + + return wrapper diff --git a/shared/package-files/00/001782ae33bc852e41fbcdcc16852ff207792282cc0e56da2b52dc5b0a92e8ca/blob b/shared/package-files/00/001782ae33bc852e41fbcdcc16852ff207792282cc0e56da2b52dc5b0a92e8ca/blob new file mode 100644 index 0000000000000000000000000000000000000000..a4b3f74db3a2930a21db7da4c9e23469d63e4ca5 --- /dev/null +++ b/shared/package-files/00/001782ae33bc852e41fbcdcc16852ff207792282cc0e56da2b52dc5b0a92e8ca/blob @@ -0,0 +1,36 @@ +# DO NOT EDIT! This file was generated by jschema_to_python version 0.0.1.dev29, +# with extension for dataclasses and type annotation. + +from __future__ import annotations + +import dataclasses +from typing import List, Optional + +from torch.onnx._internal.diagnostics.infra.sarif import ( + _location, + _message, + _node, + _property_bag, +) + + +@dataclasses.dataclass +class Node(object): + """Represents a node in a graph.""" + + id: str = dataclasses.field(metadata={"schema_property_name": "id"}) + children: Optional[List[_node.Node]] = dataclasses.field( + default=None, metadata={"schema_property_name": "children"} + ) + label: Optional[_message.Message] = dataclasses.field( + default=None, metadata={"schema_property_name": "label"} + ) + location: Optional[_location.Location] = dataclasses.field( + default=None, metadata={"schema_property_name": "location"} + ) + properties: Optional[_property_bag.PropertyBag] = dataclasses.field( + default=None, metadata={"schema_property_name": "properties"} + ) + + +# flake8: noqa