Publish 11 evaluated Astra histories with reproducible checkpoint artifacts
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- README.md +102 -0
- plots/all-task-progression.pdf +3 -0
- plots/baseline-references.csv +7 -0
- plots/evaluated-metrics.csv +0 -0
- plots/fluid-flow-control-progression-1.png +3 -0
- plots/fluid-flow-control-progression-1.svg +0 -0
- plots/fluid-flow-control-progression-2.png +3 -0
- plots/fluid-flow-control-progression-2.svg +0 -0
- plots/fluid-flow-control-progression-3.png +3 -0
- plots/fluid-flow-control-progression-3.svg +0 -0
- plots/protein-design-progression.png +3 -0
- plots/protein-design-progression.svg +1320 -0
- plots/scalar-task-progression.png +3 -0
- plots/scalar-task-progression.svg +0 -0
- reproduction/files/01/01450c9a5cfd39fb453742feae95510f9d15c90347f44cb55a09d59558d7d234/test.sh +17 -0
- reproduction/files/03/036c86f2674d84b404ff67c98bff5adf186dc51edffdbb4dbaa7843a845f61dd/run_unit_tests.sh +4 -0
- reproduction/files/03/03f3570a69ab4dabe59424d684b93b298f68b7ab981a1fc9148a08c34cc8d4e5/test_task.py +403 -0
- reproduction/files/04/0429ac4b74abdd4ed14c76efd89f119299132ba6d4fa03e1eb242e4a16df3616/container_smoke.py +282 -0
- reproduction/files/05/0554f498d0368ecd36ac232c40d7bcd0b9dc20ed1a901d72e300b13d501ae4d5/test_inference.py +69 -0
- reproduction/files/05/05735f6057ba486e9a82f09c0748bf41c8c736b775acd454c0343ff826bded8a/crystal_cache.py +29 -0
- reproduction/files/06/06574a519731708f2dbb71ebeb491fbdf3114f4d7af8b9eb121da35fd30c1b62/test_sharding.py +100 -0
- reproduction/files/07/07c28629ae97a2a93f1730061d27d8d096731bcd7a9e579e00c7980e0d6afc24/test_native_replay.py +246 -0
- reproduction/files/08/08431c3d888f0a102552f1facf1ea72135d88e504584f2531dea1a5c0c979e2f/score_extra.py +201 -0
- reproduction/files/08/08b0e3ae8a6e54b006cf60ffe74c63de172d0fa89714ff77df4f93866b1d63c1/grader.py +105 -0
- reproduction/files/0b/0b18d04b2b1f948d7d230ff451c93a205521037a985a856a979ba38d3c3d47ad/common.py +106 -0
- reproduction/files/0c/0c445f2319b2c3aca9fa1587339f781fbc5000c4c27ee1b478e72b9d9a27538c/validate_fly_verifier.py +41 -0
- reproduction/files/0d/0d0cbb759d4e8333988e9bdfdff8a8bccce42cff7b73d1d7ed3b23e0e2d584b5/test_release_contract.py +382 -0
- reproduction/files/0e/0e6e92803a5e581475f687f0ee03bfcab81c170775957d28668fd632a14c3e1b/benchmark_score.py +27 -0
- reproduction/files/0e/0e79954672aa8606568a564fd0e1f8ceb76bfbdac6fda2eadea7650396b6de06/test_policy_isolation.py +101 -0
- reproduction/files/11/110a51b699d57fd0239157173866513fab41f5d1ceeb6208bc2466bfa942486f/test_prepare_hf.py +211 -0
- reproduction/files/12/12033212bd52ab4a3c31643ee1434fdf4b84489b59feb62322cba2c56c127ff2/replay.py +56 -0
- reproduction/files/13/13b471d6183aced98dc4c168348cdfe26bd35c28f03f2e06f9da94345dfc7d12/run_local.py +92 -0
- reproduction/files/15/154b329ae33e35d2e254590344f029ae4b85350111b0a9a00f0e95019db0ff25/test_scaffold.py +96 -0
- reproduction/files/15/1553aceb037cf137db93f3156f0bb339ca179b773e58552a6400ad51b1699538/main_verifier.py +292 -0
- reproduction/files/15/15779511279917cfb9d960cb391c0edf6e60b35d2b247738ad7fc93a38a399a5/runtime.sh +12 -0
- reproduction/files/16/1649bbc73b03f29924a080b6fd4830d1efa5ced52914253d1f54ab0ef86a27f2/test_resource_audit.py +74 -0
- reproduction/files/17/1756e9907b650c8ec13b6d0b30c3c09297586db754ebdf7f18cf6c6566514c4c/fetch_baseline.py +35 -0
- reproduction/files/17/1788a1f2895aae12e5639dbf83cccffcb00b5ef9b850b60ed7bf2f37057fe140/pipeline.py +550 -0
- reproduction/files/18/18303172092c875b81bbb92d12d0c42e94404f0ee430741b1941645320036c5f/physics.py +139 -0
- reproduction/files/18/18f409937d30e1f78dd33ca4ac2fc24db941a319443551146fb09ad505dfb472/native_settings.py +86 -0
- reproduction/files/1a/1a17e381a1e20dff632e5a127d68deafe4786c27271e64de619787dff4f841c2/native_verifier.py +400 -0
- reproduction/files/1c/1c96f70bde6addcf83179c92f5e5a0a4b2aeb5c8bed1c5bfea6a5a167ff575b1/grader.py +76 -0
- reproduction/files/1d/1d5ba0e3f6977b88e95f7c60f3e009a37ea398b47c5488deb44875335aff74e5/test_research_tools.py +325 -0
- reproduction/files/1f/1f6f9a2579d1877217e9aba9c6c9eabcd30cac45975eee58c07e7a7bf00dd1ea/novelty.py +61 -0
- reproduction/files/1f/1fb4ffce095d7d563544d2826539a9113032c80c3907c9e746c93e0dcbe677ff/make_zero_predictions.py +12 -0
- reproduction/files/1f/1fff1846a4ec5dcc7e2beb2eda5dbb97f35494d686a33e4a62974d482a8e583b/evaluate_native.sh +6 -0
- reproduction/files/22/224957d662239021e18f16650cebeefedd5515b8b94454d64fc3064e98bb1a43/test_contract.py +86 -0
- reproduction/files/24/24cdd224ba6133de77df91462bb66d12b3432ee2b21cd85e24379c7813b44561/check_training_recovery.py +50 -0
- reproduction/files/25/25821b034a3b87b31eb7bd03c266decee1a2de037c3680796119f04c0740c63d/test_heldout_confirmation.py +220 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
plots/all-task-progression.pdf filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
pretty_name: Science Speedrun Astra research artifacts
|
| 3 |
+
tags:
|
| 4 |
+
- scientific-research
|
| 5 |
+
- agent-evaluation
|
| 6 |
+
- research-artifacts
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
# Science Speedrun: 11 completed Astra task histories
|
| 10 |
+
|
| 11 |
+
Reproducible submitted solutions, native evaluation reports, and screened Codex logs from
|
| 12 |
+
GPT-6 Astra with xhigh reasoning. These are file artifacts, not a tabular training dataset.
|
| 13 |
+
The eleven histories contain 194 inference-distinct candidates; each has a completed
|
| 14 |
+
sealed evaluation. Existing additional measurements of duplicate packages are retained.
|
| 15 |
+
|
| 16 |
+
| Task | Distinct candidates | Artifacts |
|
| 17 |
+
|---|---:|---|
|
| 18 |
+
| atomistic-materials | 3 | [Files](tasks/atomistic-materials/atomistic-materials-astra-xhigh-1h100-48h-20261020b) |
|
| 19 |
+
| earth-observation-pretraining-transfer | 11 | [Files](tasks/earth-observation-pretraining-transfer/earth-astra-xhigh-48h-20261020a) |
|
| 20 |
+
| fluid-flow-control | 11 | [Files](tasks/fluid-flow-control/fluid-flow-control-astra-xhigh-1h100-48h-20261022a) |
|
| 21 |
+
| fruit-fly-neuron-reconstruction | 7 | [Files](tasks/fruit-fly-neuron-reconstruction/fruit-fly-neuron-reconstruction-astra-xhigh-1h100-48h-20261022a) |
|
| 22 |
+
| natural-disease-progression | 13 | [Files](tasks/natural-disease-progression/ndp-astra-xhigh-48h-20261020a) |
|
| 23 |
+
| protein-design | 1 | [Files](tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a) |
|
| 24 |
+
| protein-sequence-modeling | 58 | [Files](tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a) |
|
| 25 |
+
| single-cell-perturbation-prediction | 17 | [Files](tasks/single-cell-perturbation-prediction/single-cell-perturbation-prediction-astra-xhigh-1h100-48h-20261020b) |
|
| 26 |
+
| surface-code-decoding | 45 | [Files](tasks/surface-code-decoding/surface-code-decoding-astra-xhigh-1h100-48h-20261020b) |
|
| 27 |
+
| tokamak-magnetic-control | 7 | [Files](tasks/tokamak-magnetic-control/tokamak-astra-xhigh-48h-20261020a) |
|
| 28 |
+
| mass-spectrometry-molecule-retrieval | 21 | [Files](tasks/mass-spectrometry-molecule-retrieval/mass-spectrometry-molecule-retrieval-astra-xhigh-1h100-48h-20261020b) |
|
| 29 |
+
|
| 30 |
+
## Layout
|
| 31 |
+
|
| 32 |
+
`tasks/<task>/<run-id>/` contains `submissions/`, `evaluations/`, `logs/`,
|
| 33 |
+
`finalization/`, and one `index.json`. The index maps every original snapshot and
|
| 34 |
+
research timestamp to its canonical package and actual evaluation, and records file
|
| 35 |
+
hashes, executable permissions, source commit, images, resources, and deviations.
|
| 36 |
+
`plots/` contains the complete-history figures and their metric/reference CSV files.
|
| 37 |
+
`reproduction/files/` preserves the frozen verifier/adapter source files referenced
|
| 38 |
+
by each evaluation. Scientific native reports are retained without rewriting scores.
|
| 39 |
+
|
| 40 |
+
Disease submissions include their required Python/CUDA runtime. Identical large
|
| 41 |
+
weights and bundled dependencies are shared under `shared/package-files/`, as plain
|
| 42 |
+
files, so repeated checkpoint contents need only be downloaded once. Small entry-point
|
| 43 |
+
files remain browsable in each submission folder. Indexes map stored files back to
|
| 44 |
+
their original paths and executable permissions. Reconstruct a package before execution.
|
| 45 |
+
From a complete downloaded repository:
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
python restore_submission.py tasks/<task>/<run-id>/index.json S001 /path/to/new/submission
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
To fetch just one candidate, download its `index.json` and the helper first (keeping
|
| 52 |
+
the directory layout), then add `--repo s42chen/sci-run` to the command above. With
|
| 53 |
+
`huggingface_hub` installed, the helper downloads only that candidate's missing files.
|
| 54 |
+
Use `--revision <dataset-commit>` to pin the download to a specific dataset version.
|
| 55 |
+
|
| 56 |
+
Use `GRACE_FINAL` for the separate post-budget package. The helper copies files into
|
| 57 |
+
a new directory, restores permissions, and checks the exported names/modes/content
|
| 58 |
+
fingerprint. It never executes the submitted code. Do not execute submissions merely
|
| 59 |
+
to inspect this archive; use the benchmark's isolated evaluation environment.
|
| 60 |
+
|
| 61 |
+
## Interpretation and limitations
|
| 62 |
+
|
| 63 |
+
All runs used one accessible H100 and 48 hours of charged research time. Eight of
|
| 64 |
+
these eleven tasks were run with reduced CPU/RAM/GPU allocations relative to their
|
| 65 |
+
pinned eight-GPU task configurations. Tokamak, Disease, and Earth match the original
|
| 66 |
+
one-GPU research requests at their recorded source commits. Runs were interrupted
|
| 67 |
+
and resumed; preserving the clock does not reproduce uninterrupted computation.
|
| 68 |
+
Beaker execution uses documented isolation/resource adaptations and may grant more
|
| 69 |
+
RAM than requested. Published baseline lines are reference measurements, not equal-
|
| 70 |
+
budget human trials. Missing or incompatible baselines are explicitly omitted.
|
| 71 |
+
|
| 72 |
+
Protein Design retained one early submission. Its requested pretrained inference
|
| 73 |
+
assets were not mounted, preventing publication of a promising development hybrid.
|
| 74 |
+
Its result is included with that setup limitation, not presented as an unrestricted
|
| 75 |
+
comparison. `finalization/` is an additional submission-only window of at most five
|
| 76 |
+
minutes; it is not backdated into the 48-hour curves. Purple markers denote those
|
| 77 |
+
reviewed post-budget results; orange marks denote reused scores for duplicate snapshots.
|
| 78 |
+
|
| 79 |
+
## Provenance and excluded material
|
| 80 |
+
|
| 81 |
+
Submissions were produced by the evaluated agent; reports by the native scientific
|
| 82 |
+
scorers under the recorded adapters; logs by Codex and the harness. Organization,
|
| 83 |
+
indexes, plots, and the reconstruction helper were created by the operator.
|
| 84 |
+
Logs are screened for credentials, with redaction counts and original/exported hashes
|
| 85 |
+
recorded in the indexes. Authentication stores, private test inputs/labels, raw research
|
| 86 |
+
workspaces and unsubmitted checkpoints are excluded. Dataset inputs and separately
|
| 87 |
+
distributed pretrained dependencies remain at their upstream locations. Existing source
|
| 88 |
+
and dependency licenses continue to apply; no blanket relicensing is asserted here.
|
| 89 |
+
|
| 90 |
+
Benchmark source: https://github.com/sunnweiwei/science-speedrun
|
| 91 |
+
|
| 92 |
+
## Lean export
|
| 93 |
+
|
| 94 |
+
Mass Spectrometry packages omit unused research backups and unselected generations.
|
| 95 |
+
The selection follows the same reviewed inference footprint used to deduplicate
|
| 96 |
+
evaluations. Every retained inference file, mode, and relevant verifier metadata was
|
| 97 |
+
checked against the recorded evaluated identity; required notes and adjacent licenses
|
| 98 |
+
are also retained. No model code, weights, paths, or scores were rewritten. These
|
| 99 |
+
trimmed packages have their own export fingerprint, with the original full-package
|
| 100 |
+
fingerprint and evaluated inference identity recorded separately in each index.
|
| 101 |
+
Other tasks retain their exact submitted package contents, with identical files shared.
|
| 102 |
+
Original full run artifacts remain preserved on the operator's storage.
|
plots/all-task-progression.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1fca25907e2b06b3266d5ecd11edffdfd126115fd1d9e97d4634ddb0a4717738
|
| 3 |
+
size 109557
|
plots/baseline-references.csv
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
task,metric,value,label,source
|
| 2 |
+
tokamak,reward,0.4857142857142857,Shape VC,/weka/oe-adapt-default/stevenc/science-speedrun/tasks/tokamak-magnetic-control/environment/baseline/shape_vc/RESULTS.md
|
| 3 |
+
ndp,reward,0.236256716,Temporal GRU,/weka/oe-adapt-default/stevenc/science-speedrun/tasks/natural-disease-progression/environment/baseline/temporal-gru/RESULTS.md
|
| 4 |
+
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
|
| 5 |
+
surface-code-decoding,reward,0.75569,AlphaQubit reproduction,/weka/oe-adapt-default/stevenc/science-speedrun/tasks/surface-code-decoding/environment/baseline/alphaqubit/RESULTS.md
|
| 6 |
+
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
|
| 7 |
+
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
|
plots/evaluated-metrics.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
plots/fluid-flow-control-progression-1.png
ADDED
|
Git LFS Details
|
plots/fluid-flow-control-progression-1.svg
ADDED
|
|
plots/fluid-flow-control-progression-2.png
ADDED
|
Git LFS Details
|
plots/fluid-flow-control-progression-2.svg
ADDED
|
|
plots/fluid-flow-control-progression-3.png
ADDED
|
Git LFS Details
|
plots/fluid-flow-control-progression-3.svg
ADDED
|
|
plots/protein-design-progression.png
ADDED
|
Git LFS Details
|
plots/protein-design-progression.svg
ADDED
|
|
plots/scalar-task-progression.png
ADDED
|
Git LFS Details
|
plots/scalar-task-progression.svg
ADDED
|
|
reproduction/files/01/01450c9a5cfd39fb453742feae95510f9d15c90347f44cb55a09d59558d7d234/test.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
OLMO_TEST_DIR=$(cd "$(dirname "$0")" && pwd)
|
| 4 |
+
# As in the weather verifier: the NVIDIA container runtime bind-mounts entries under
|
| 5 |
+
# /proc/driver/nvidia, and the kernel then refuses the fresh procfs of the model's user namespace
|
| 6 |
+
# ("Can't mount proc on /newroot/proc"). Detach them; the GPUs stay usable through /dev/nvidia*.
|
| 7 |
+
for mount in $(awk '$5 ~ /^\/proc\/driver\/nvidia/ {print $5}' /proc/self/mountinfo | sort -r); do
|
| 8 |
+
umount "${mount}" 2>/dev/null || echo "warning: could not detach ${mount}; the sandbox may fail" >&2
|
| 9 |
+
done
|
| 10 |
+
# Docker exposes the allocated GPUs without setting CUDA_VISIBLE_DEVICES; name them explicitly.
|
| 11 |
+
if [[ -z ${CUDA_VISIBLE_DEVICES:-} ]] && command -v nvidia-smi >/dev/null; then
|
| 12 |
+
CUDA_VISIBLE_DEVICES=$(nvidia-smi --query-gpu=uuid --format=csv,noheader | paste -sd,)
|
| 13 |
+
export CUDA_VISIBLE_DEVICES
|
| 14 |
+
fi
|
| 15 |
+
OLMO_PROBES=${OLMO_PROBES:-$OLMO_TEST_DIR/../environment/evaluation/probes.py}
|
| 16 |
+
[[ -f "$OLMO_PROBES" ]] || OLMO_PROBES=/evaluation/probes.py
|
| 17 |
+
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"
|
reproduction/files/03/036c86f2674d84b404ff67c98bff5adf186dc51edffdbb4dbaa7843a845f61dd/run_unit_tests.sh
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
cd "$(dirname "$0")"
|
| 4 |
+
exec python3 -m unittest -v test_task
|
reproduction/files/03/03f3570a69ab4dabe59424d684b93b298f68b7ab981a1fc9148a08c34cc8d4e5/test_task.py
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU-only interface tests. Fake dynamics below are NOT HydroGym benchmark cases."""
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import hashlib
|
| 5 |
+
import importlib.util
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import tempfile
|
| 11 |
+
import textwrap
|
| 12 |
+
import unittest
|
| 13 |
+
from unittest.mock import patch
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
TASK = Path(__file__).resolve().parents[1]
|
| 17 |
+
sys.path.insert(0, str(TASK / "environment/evaluation"))
|
| 18 |
+
import evaluate
|
| 19 |
+
import run_maia
|
| 20 |
+
from protocol import InfrastructureError, Policy, PolicyError, replay_episode
|
| 21 |
+
|
| 22 |
+
spec = importlib.util.spec_from_file_location("hydro_materialize", TASK / "environment/data/materialize.py")
|
| 23 |
+
materialize = importlib.util.module_from_spec(spec)
|
| 24 |
+
spec.loader.exec_module(materialize)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def fixture_suite():
|
| 28 |
+
suite = json.loads((TASK / "environment/data/suite.example.json").read_text())
|
| 29 |
+
# A test-only protocol fixture, never written to production data.
|
| 30 |
+
suite.update(status="validated", release_id="synthetic-interface-test-only")
|
| 31 |
+
suite["coverage"]["status"] = "complete"
|
| 32 |
+
suite["cases"][0].update(id="fixture-a", environment="fixture-a", horizon=3,
|
| 33 |
+
observation_size=1, action_size=1)
|
| 34 |
+
suite["cases"][0]["baseline"] = {"algorithm": "PPO", "anchor_description": "Synthetic zero action", "anchor_return": -3.0, "reference_return": 0.0}
|
| 35 |
+
second = copy.deepcopy(suite["cases"][0])
|
| 36 |
+
second.update(id="fixture-b", environment="fixture-b")
|
| 37 |
+
suite["cases"].append(second)
|
| 38 |
+
return suite
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class FakeEnv:
|
| 42 |
+
"""Toy scalar feedback problem used only to check who computes the reward."""
|
| 43 |
+
class Space:
|
| 44 |
+
shape = (1,)
|
| 45 |
+
low = [-1.0]
|
| 46 |
+
high = [1.0]
|
| 47 |
+
observation_space = action_space = Space()
|
| 48 |
+
|
| 49 |
+
def reset(self, seed=None):
|
| 50 |
+
self.state = 1.0
|
| 51 |
+
self.steps = 0
|
| 52 |
+
return [self.state], {}
|
| 53 |
+
|
| 54 |
+
def step(self, action):
|
| 55 |
+
self.steps += 1
|
| 56 |
+
self.state += action[0]
|
| 57 |
+
return [self.state], -abs(self.state), False, self.steps >= 3, {"state": self.state}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class TaskTests(unittest.TestCase):
|
| 61 |
+
def setUp(self):
|
| 62 |
+
self.temporary = tempfile.TemporaryDirectory()
|
| 63 |
+
self.addCleanup(self.temporary.cleanup)
|
| 64 |
+
self.root = Path(self.temporary.name)
|
| 65 |
+
|
| 66 |
+
def package(self, action="[-request['observation'][0]]", altered=""):
|
| 67 |
+
package = self.root / "package"
|
| 68 |
+
package.mkdir(exist_ok=True)
|
| 69 |
+
(package / "README.md").write_text("Synthetic protocol fixture, not a CFD controller.\n")
|
| 70 |
+
(package / "infer.sh").write_text(
|
| 71 |
+
f'#!/bin/sh\nexec "{sys.executable}" "$(dirname "$0")/policy.py"\n')
|
| 72 |
+
(package / "policy.py").write_text(textwrap.dedent(f"""
|
| 73 |
+
import json,sys,time
|
| 74 |
+
for line in sys.stdin:
|
| 75 |
+
request=json.loads(line)
|
| 76 |
+
reply={{'request_id':request['request_id']}}
|
| 77 |
+
if request['op']=='reset': reply['ready']=True
|
| 78 |
+
elif request['op']=='act':
|
| 79 |
+
{altered or 'pass'}
|
| 80 |
+
reply['action']={action}
|
| 81 |
+
else:
|
| 82 |
+
reply['closed']=True
|
| 83 |
+
print(json.dumps(reply),flush=True)
|
| 84 |
+
break
|
| 85 |
+
print(json.dumps(reply),flush=True)
|
| 86 |
+
"""))
|
| 87 |
+
return package
|
| 88 |
+
|
| 89 |
+
def data(self, suite=None):
|
| 90 |
+
suite = suite or fixture_suite()
|
| 91 |
+
root = self.root / "data"
|
| 92 |
+
root.mkdir()
|
| 93 |
+
release = {"release_id": "synthetic-interface-test-only",
|
| 94 |
+
"cases": fixture_suite()["cases"],
|
| 95 |
+
"test": {"case_ids": ["fixture-a", "fixture-b"]}}
|
| 96 |
+
# Replace only the verifier-owned fixture identity in these synthetic
|
| 97 |
+
# protocol tests. Real 47-case selection/binding is tested separately.
|
| 98 |
+
def fixture_release(path=None):
|
| 99 |
+
return json.loads(Path(path).read_text()) if path is not None else release
|
| 100 |
+
mocked = patch.object(evaluate, "load_release", side_effect=fixture_release)
|
| 101 |
+
mocked.start()
|
| 102 |
+
self.addCleanup(mocked.stop)
|
| 103 |
+
suite.update(data_release_id=release["release_id"],
|
| 104 |
+
data_release_sha256=evaluate.data_release_hash(release))
|
| 105 |
+
(root / "release.json").write_text(json.dumps(release))
|
| 106 |
+
(root / "suite.json").write_text(json.dumps(suite))
|
| 107 |
+
directories = []
|
| 108 |
+
for case in suite["cases"]:
|
| 109 |
+
folder = root / "environments" / case["environment"]
|
| 110 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 111 |
+
(folder / "environment_config.yaml").write_text("test-only: true\n")
|
| 112 |
+
directories.append(case["environment"])
|
| 113 |
+
(root / "materialized.json").write_text(json.dumps({
|
| 114 |
+
"revision": evaluate.SOURCE_REVISION, "verified_directories": directories,
|
| 115 |
+
"data_release_id": release["release_id"],
|
| 116 |
+
"data_release_sha256": evaluate.data_release_hash(release)}))
|
| 117 |
+
return root
|
| 118 |
+
|
| 119 |
+
def test_missing_manifest_and_binding_cannot_enable_legacy_subset(self):
|
| 120 |
+
data = self.data()
|
| 121 |
+
(data / "release.json").unlink()
|
| 122 |
+
suite = json.loads((data / "suite.json").read_text())
|
| 123 |
+
suite.pop("data_release_id")
|
| 124 |
+
suite.pop("data_release_sha256")
|
| 125 |
+
(data / "suite.json").write_text(json.dumps(suite))
|
| 126 |
+
with self.assertRaisesRegex(InfrastructureError, "Incomplete evaluation release"):
|
| 127 |
+
evaluate.preflight(data, require_reference=False)
|
| 128 |
+
|
| 129 |
+
def test_receipt_must_match_current_data_release(self):
|
| 130 |
+
data = self.data()
|
| 131 |
+
receipt = json.loads((data / "materialized.json").read_text())
|
| 132 |
+
receipt["data_release_id"] = "an-old-data-release"
|
| 133 |
+
(data / "materialized.json").write_text(json.dumps(receipt))
|
| 134 |
+
with self.assertRaisesRegex(InfrastructureError, "not been materialized"):
|
| 135 |
+
evaluate.preflight(data, require_reference=False)
|
| 136 |
+
|
| 137 |
+
def policy(self, package, timeout=2):
|
| 138 |
+
policy = Policy(package, self.root / "policy.log", timeout=timeout)
|
| 139 |
+
self.addCleanup(policy.abort)
|
| 140 |
+
policy.reset({"environment": "unseen-id"}, [1], [1], [-1.0], [1.0])
|
| 141 |
+
return policy
|
| 142 |
+
|
| 143 |
+
def test_feedback_and_episode_reset(self):
|
| 144 |
+
policy = self.policy(self.package())
|
| 145 |
+
case = fixture_suite()["cases"][0]
|
| 146 |
+
for seed in (83, 12):
|
| 147 |
+
result = replay_episode(FakeEnv(), policy, case, seed)
|
| 148 |
+
self.assertEqual(result["return"], 0.0)
|
| 149 |
+
self.assertEqual(result["steps"], 3)
|
| 150 |
+
policy.close()
|
| 151 |
+
|
| 152 |
+
def test_bad_actions(self):
|
| 153 |
+
for value in ("[]", "[True]", "[float('nan')]", "[2.0]", "['0']"):
|
| 154 |
+
with self.subTest(value=value):
|
| 155 |
+
policy = self.policy(self.package(action=value))
|
| 156 |
+
with self.assertRaises(PolicyError):
|
| 157 |
+
policy.act([1.0])
|
| 158 |
+
policy.abort()
|
| 159 |
+
|
| 160 |
+
def test_wrong_id(self):
|
| 161 |
+
policy = self.policy(self.package(altered="reply['request_id']='wrong'"))
|
| 162 |
+
with self.assertRaises(PolicyError):
|
| 163 |
+
policy.act([1.0])
|
| 164 |
+
|
| 165 |
+
def test_timeout(self):
|
| 166 |
+
policy = self.policy(self.package(altered="time.sleep(2)"), timeout=0.2)
|
| 167 |
+
with self.assertRaisesRegex(PolicyError, "timeout"):
|
| 168 |
+
policy.act([1.0])
|
| 169 |
+
|
| 170 |
+
def test_invalid_observation_is_infrastructure(self):
|
| 171 |
+
policy = self.policy(self.package())
|
| 172 |
+
for observation in ([float("nan")], [], [1.0, 2.0]):
|
| 173 |
+
with self.assertRaises(InfrastructureError):
|
| 174 |
+
policy.act(observation)
|
| 175 |
+
|
| 176 |
+
def test_default_example_cannot_be_graded(self):
|
| 177 |
+
example = json.loads((TASK / "environment/data/suite.example.json").read_text())
|
| 178 |
+
with self.assertRaises(InfrastructureError):
|
| 179 |
+
evaluate.validate_suite(example)
|
| 180 |
+
|
| 181 |
+
def test_legacy_cache_cannot_shadow_release(self):
|
| 182 |
+
case = fixture_suite()["cases"][0]
|
| 183 |
+
data = self.data()
|
| 184 |
+
fake_home = self.root / "legacy-home"
|
| 185 |
+
with patch.object(run_maia.Path, "home", return_value=fake_home):
|
| 186 |
+
run_maia.check_native_cache(case, data)
|
| 187 |
+
cached = fake_home / ".cache" / "maiagym" / case["environment"]
|
| 188 |
+
cached.mkdir(parents=True)
|
| 189 |
+
with self.assertRaisesRegex(InfrastructureError, "shadow"):
|
| 190 |
+
run_maia.check_native_cache(case, data)
|
| 191 |
+
|
| 192 |
+
def test_native_reward_and_horizon_errors(self):
|
| 193 |
+
case = fixture_suite()["cases"][0]
|
| 194 |
+
policy = self.policy(self.package())
|
| 195 |
+
class BrokenReward(FakeEnv):
|
| 196 |
+
def step(self, action):
|
| 197 |
+
return [0.0], float("nan"), False, True, {}
|
| 198 |
+
# A nonfinite reward after the policy acted is a diverged simulation: the case fails.
|
| 199 |
+
with self.assertRaisesRegex(PolicyError, "diverged.*finite scalar"):
|
| 200 |
+
replay_episode(BrokenReward(), policy, case, 1)
|
| 201 |
+
with self.assertRaisesRegex(InfrastructureError, "horizon"):
|
| 202 |
+
replay_episode(FakeEnv(), policy, dict(case, horizon=2), 1)
|
| 203 |
+
|
| 204 |
+
def test_reject_bad_suite(self):
|
| 205 |
+
transforms = [
|
| 206 |
+
lambda s: s.update(cases=[]),
|
| 207 |
+
lambda s: s["cases"].append(copy.deepcopy(s["cases"][0])),
|
| 208 |
+
lambda s: s["cases"][0].update(backend="nek"),
|
| 209 |
+
lambda s: s["cases"][0].update(id="../escape"),
|
| 210 |
+
lambda s: s["cases"][0].update(horizon=0),
|
| 211 |
+
lambda s: s["cases"][0].update(seeds=[1, 1]),
|
| 212 |
+
lambda s: s["cases"][0]["baseline"].update(reference_return=None),
|
| 213 |
+
lambda s: s["cases"][0]["baseline"].update(reference_return=-4.0),
|
| 214 |
+
lambda s: s["cases"][0]["env_kwargs"].update(configuration_file="/tmp/changed"),
|
| 215 |
+
lambda s: s["cases"][0]["env_kwargs"].update(obs_normalization_strategy="probewise_mean_std"),
|
| 216 |
+
lambda s: s["cases"][0]["env_kwargs"].update(obs_normalization_strategy="customized", obs_loc=[0.0], obs_scale=[0.0]),
|
| 217 |
+
]
|
| 218 |
+
for change in transforms:
|
| 219 |
+
suite = fixture_suite()
|
| 220 |
+
change(suite)
|
| 221 |
+
with self.assertRaises(InfrastructureError):
|
| 222 |
+
evaluate.validate_suite(suite)
|
| 223 |
+
|
| 224 |
+
def test_incomplete_release_does_not_score_missing_submission(self):
|
| 225 |
+
output = self.root / "out"
|
| 226 |
+
with self.assertRaises(InfrastructureError):
|
| 227 |
+
evaluate.evaluate(self.root / "missing-data", self.root / "missing-model", output)
|
| 228 |
+
self.assertFalse((output / "reward.json").exists())
|
| 229 |
+
self.assertTrue((output / "error.json").exists())
|
| 230 |
+
|
| 231 |
+
def test_missing_submission_scores_zero_only_after_preflight(self):
|
| 232 |
+
output = self.root / "out"
|
| 233 |
+
evaluate.evaluate(self.data(), self.root / "missing-model", output)
|
| 234 |
+
self.assertEqual(json.loads((output / "reward.json").read_text())["score"], 0)
|
| 235 |
+
|
| 236 |
+
def test_relocation_and_scoring(self):
|
| 237 |
+
package = self.package()
|
| 238 |
+
def runner(case, suite, data, relocated, output):
|
| 239 |
+
self.assertNotEqual(relocated, package)
|
| 240 |
+
policy = Policy(relocated, output.with_suffix(".policy.log"), timeout=2)
|
| 241 |
+
try:
|
| 242 |
+
episodes = [replay_episode(FakeEnv(), policy, case, seed) for seed in case["seeds"]]
|
| 243 |
+
policy.close()
|
| 244 |
+
finally:
|
| 245 |
+
policy.abort()
|
| 246 |
+
return {"status": "ok", "episodes": episodes}
|
| 247 |
+
output = self.root / "out"
|
| 248 |
+
evaluate.evaluate(self.data(), package, output, runner=runner)
|
| 249 |
+
self.assertEqual(json.loads((output / "reward.json").read_text()), {"score": 1.0, "case_coverage": 1.0})
|
| 250 |
+
|
| 251 |
+
def test_policy_failures_remain_in_denominator(self):
|
| 252 |
+
suite = fixture_suite()
|
| 253 |
+
results = {"fixture-a": {"status": "policy_error"}, "fixture-b": {
|
| 254 |
+
"status": "ok", "episodes": [{"seed": seed, "return": 0.0} for seed in suite["cases"][1]["seeds"]]}}
|
| 255 |
+
self.assertEqual(evaluate.aggregate(suite, results), {"score": 0.5, "case_coverage": 0.5})
|
| 256 |
+
del results["fixture-a"]
|
| 257 |
+
with self.assertRaises(InfrastructureError):
|
| 258 |
+
evaluate.aggregate(suite, results)
|
| 259 |
+
|
| 260 |
+
def test_raw_replay_all_cases_without_reference_scores(self):
|
| 261 |
+
suite = fixture_suite()
|
| 262 |
+
for case in suite["cases"]:
|
| 263 |
+
case.pop("baseline")
|
| 264 |
+
with self.assertRaises(InfrastructureError):
|
| 265 |
+
evaluate.validate_suite(suite)
|
| 266 |
+
evaluate.validate_suite(suite, require_reference=False)
|
| 267 |
+
seen = []
|
| 268 |
+
package = self.package()
|
| 269 |
+
package_digests = []
|
| 270 |
+
def runner(case, release, data, relocated, output):
|
| 271 |
+
seen.append(case["id"])
|
| 272 |
+
self.assertNotEqual(relocated, package)
|
| 273 |
+
package_digests.append(evaluate.package_hash(relocated))
|
| 274 |
+
policy = Policy(relocated, output.with_suffix(".policy.log"), timeout=2)
|
| 275 |
+
try:
|
| 276 |
+
episodes = [replay_episode(FakeEnv(), policy, case, seed) for seed in case["seeds"]]
|
| 277 |
+
policy.close()
|
| 278 |
+
finally:
|
| 279 |
+
policy.abort()
|
| 280 |
+
return {"status": "ok", "episodes": episodes}
|
| 281 |
+
output = self.root / "raw"
|
| 282 |
+
evaluate.evaluate(self.data(suite), package, output, runner=runner, raw_only=True)
|
| 283 |
+
result = json.loads((output / "results.json").read_text())
|
| 284 |
+
self.assertEqual(seen, ["fixture-a", "fixture-b"])
|
| 285 |
+
self.assertEqual(len(set(package_digests)), 1)
|
| 286 |
+
self.assertEqual(result["suite_sha256"], evaluate.suite_hash(suite))
|
| 287 |
+
self.assertEqual(result["evaluation_mode"], "native-returns")
|
| 288 |
+
self.assertEqual(result["case_coverage"], 1.0)
|
| 289 |
+
self.assertTrue(all(c["mean_return"] == 0.0 for c in result["cases"].values()))
|
| 290 |
+
self.assertTrue(all("score" not in c for c in result["cases"].values()))
|
| 291 |
+
self.assertFalse((output / "reward.json").exists())
|
| 292 |
+
|
| 293 |
+
def test_raw_mode_does_not_bypass_physics_or_coverage(self):
|
| 294 |
+
for change in (lambda s: s.update(status="draft"),
|
| 295 |
+
lambda s: s["coverage"].update(status="pending"),
|
| 296 |
+
lambda s: s["cases"][0].update(backend="jax"),
|
| 297 |
+
lambda s: s["cases"][0].update(horizon=0),
|
| 298 |
+
lambda s: s["cases"][0]["env_kwargs"].update(
|
| 299 |
+
obs_normalization_strategy="probewise_mean_std")):
|
| 300 |
+
suite = fixture_suite()
|
| 301 |
+
change(suite)
|
| 302 |
+
with self.assertRaises(InfrastructureError):
|
| 303 |
+
evaluate.validate_suite(suite, require_reference=False)
|
| 304 |
+
with self.assertRaisesRegex(InfrastructureError, "coverage"):
|
| 305 |
+
evaluate.aggregate(fixture_suite(), {}, normalize=False)
|
| 306 |
+
|
| 307 |
+
def test_raw_missing_model_does_not_fabricate_a_return(self):
|
| 308 |
+
output = self.root / "raw-missing"
|
| 309 |
+
evaluate.evaluate(self.data(), self.root / "missing", output, raw_only=True)
|
| 310 |
+
result = json.loads((output / "results.json").read_text())
|
| 311 |
+
self.assertEqual(set(result["cases"]), {"fixture-a", "fixture-b"})
|
| 312 |
+
self.assertTrue(all("return" not in c for c in result["cases"].values()))
|
| 313 |
+
self.assertFalse((output / "reward.json").exists())
|
| 314 |
+
|
| 315 |
+
def test_raw_policy_error_is_not_silently_omitted(self):
|
| 316 |
+
suite = fixture_suite()
|
| 317 |
+
results = {"fixture-a": {"status": "policy_error"}, "fixture-b": {
|
| 318 |
+
"status": "ok", "episodes": [{"seed": seed, "return": -2.0}
|
| 319 |
+
for seed in suite["cases"][1]["seeds"]]}}
|
| 320 |
+
self.assertEqual(evaluate.aggregate(suite, results, normalize=False), {"case_coverage": 0.5})
|
| 321 |
+
self.assertIsNone(results["fixture-a"]["mean_return"])
|
| 322 |
+
self.assertEqual(results["fixture-b"]["mean_return"], -2.0)
|
| 323 |
+
|
| 324 |
+
def test_release_mutation_during_replay_is_not_a_score(self):
|
| 325 |
+
data = self.data()
|
| 326 |
+
def runner(case, suite, data, relocated, output):
|
| 327 |
+
changed = json.loads((data / "suite.json").read_text())
|
| 328 |
+
changed["policy_timeout_sec"] += 1
|
| 329 |
+
(data / "suite.json").write_text(json.dumps(changed))
|
| 330 |
+
return {"status": "policy_error"}
|
| 331 |
+
output = self.root / "changed-release"
|
| 332 |
+
with self.assertRaisesRegex(InfrastructureError, "release changed"):
|
| 333 |
+
evaluate.evaluate(data, self.package(), output, runner=runner)
|
| 334 |
+
self.assertFalse((output / "reward.json").exists())
|
| 335 |
+
|
| 336 |
+
def test_negative_gains_remain_visible(self):
|
| 337 |
+
suite = fixture_suite()
|
| 338 |
+
results = {c["id"]: {"status": "ok", "episodes": [{"seed": seed, "return": -6.0} for seed in c["seeds"]]}
|
| 339 |
+
for c in suite["cases"]}
|
| 340 |
+
self.assertEqual(evaluate.aggregate(suite, results)["score"], 0)
|
| 341 |
+
self.assertEqual(results["fixture-a"]["normalized_gain"], -1)
|
| 342 |
+
|
| 343 |
+
def test_mutation_and_solver_error_are_not_scores(self):
|
| 344 |
+
for mode in ("mutation", "solver"):
|
| 345 |
+
with self.subTest(mode=mode):
|
| 346 |
+
def runner(case, suite, data, package, output):
|
| 347 |
+
if mode == "solver":
|
| 348 |
+
raise InfrastructureError("solver failed")
|
| 349 |
+
(package / "README.md").write_text("mutated")
|
| 350 |
+
return {"status": "policy_error"}
|
| 351 |
+
data = self.root / "data"
|
| 352 |
+
if not data.exists():
|
| 353 |
+
data = self.data()
|
| 354 |
+
output = self.root / mode
|
| 355 |
+
with self.assertRaises(InfrastructureError):
|
| 356 |
+
evaluate.evaluate(data, self.package(), output, runner=runner)
|
| 357 |
+
self.assertFalse((output / "reward.json").exists())
|
| 358 |
+
|
| 359 |
+
def test_escaping_package_symlink(self):
|
| 360 |
+
package = self.package()
|
| 361 |
+
(package / "escape").symlink_to(self.root)
|
| 362 |
+
with self.assertRaises(PolicyError):
|
| 363 |
+
evaluate.package_hash(package)
|
| 364 |
+
|
| 365 |
+
def test_stale_output_rejected(self):
|
| 366 |
+
output = self.root / "out"
|
| 367 |
+
output.mkdir()
|
| 368 |
+
(output / "reward.json").write_text('{"score":123}')
|
| 369 |
+
with self.assertRaises(InfrastructureError):
|
| 370 |
+
evaluate.evaluate(self.data(), self.package(), output)
|
| 371 |
+
|
| 372 |
+
def test_materialize_plan_downloads_nothing(self):
|
| 373 |
+
destination = self.root / "do-not-create"
|
| 374 |
+
result = subprocess.run([sys.executable, str(materialize.CATALOG.with_name("materialize.py")),
|
| 375 |
+
str(destination), "--case", "Cylinder_2D_Re200"], capture_output=True, text=True, check=True)
|
| 376 |
+
plan = json.loads(result.stdout)
|
| 377 |
+
self.assertEqual(plan["mode"], "plan")
|
| 378 |
+
self.assertEqual(len(plan["download_commands"]), 1)
|
| 379 |
+
self.assertFalse(destination.exists())
|
| 380 |
+
|
| 381 |
+
def test_resource_checksums_and_truncation(self):
|
| 382 |
+
path = self.root / "asset"
|
| 383 |
+
path.write_bytes(b"verified")
|
| 384 |
+
item = {"rfilename": "asset", "size": 8,
|
| 385 |
+
"lfs": {"sha256": hashlib.sha256(b"verified").hexdigest()}}
|
| 386 |
+
materialize.verify_files(self.root, [item])
|
| 387 |
+
path.write_bytes(b"modified")
|
| 388 |
+
with self.assertRaises(ValueError):
|
| 389 |
+
materialize.verify_files(self.root, [item])
|
| 390 |
+
path.write_bytes(b"v")
|
| 391 |
+
with self.assertRaises(ValueError):
|
| 392 |
+
materialize.verify_files(self.root, [item])
|
| 393 |
+
|
| 394 |
+
def test_catalog_pins_and_inventory_is_not_suite(self):
|
| 395 |
+
catalog = json.loads(materialize.CATALOG.read_text())
|
| 396 |
+
self.assertEqual(catalog["revision"], evaluate.SOURCE_REVISION)
|
| 397 |
+
self.assertEqual(len(catalog["directories"]), 89)
|
| 398 |
+
self.assertEqual(sum(c["has_environment_config"] for c in catalog["directories"]), 66)
|
| 399 |
+
self.assertNotIn("cases", catalog)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
if __name__ == "__main__":
|
| 403 |
+
unittest.main()
|
reproduction/files/04/0429ac4b74abdd4ed14c76efd89f119299132ba6d4fa03e1eb242e4a16df3616/container_smoke.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Exercise actual Docker role separation with tiny synthetic inputs, not accuracy.
|
| 3 |
+
|
| 4 |
+
Host orchestration uses only Python's standard library. Fixture generation runs
|
| 5 |
+
inside the already-built verifier image, whose pinned runtime supplies NumPy.
|
| 6 |
+
All three cases use the real supervisor, grader, and Compose topology.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
import os
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import shutil
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
import tempfile
|
| 20 |
+
import time
|
| 21 |
+
import uuid
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
TASK = Path(__file__).resolve().parents[1]
|
| 25 |
+
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]
|
| 26 |
+
|
| 27 |
+
# An executable without a .sh suffix also tests frozen-artifact execute bits.
|
| 28 |
+
DECODER = '''#!/opt/qec/.venv/bin/python
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
import errno
|
| 31 |
+
import json
|
| 32 |
+
import os
|
| 33 |
+
import socket
|
| 34 |
+
import sys
|
| 35 |
+
import numpy as np
|
| 36 |
+
|
| 37 |
+
assert os.getuid() == os.geteuid() == 10001, "inference must run as isolated UID"
|
| 38 |
+
assert os.getgid() == os.getegid() == 10001
|
| 39 |
+
assert {name for _, name in socket.if_nameindex()} == {"lo"}, "network namespace is not offline"
|
| 40 |
+
assert not Path("/private").exists(), "grader labels leaked into inference container"
|
| 41 |
+
try:
|
| 42 |
+
list(Path("/sealed").iterdir())
|
| 43 |
+
except PermissionError:
|
| 44 |
+
pass
|
| 45 |
+
else:
|
| 46 |
+
raise AssertionError("inference can read the trusted sealed volume")
|
| 47 |
+
status = Path("/proc/self/status").read_text()
|
| 48 |
+
assert any(line.split() == ["NoNewPrivs:", "1"] for line in status.splitlines())
|
| 49 |
+
root = Path(__file__).resolve().parents[1]
|
| 50 |
+
assert root != Path("/workspace/submission"), "artifact was not relocated"
|
| 51 |
+
for target in [root / "model_config.json", Path("/opt/task/qecbench/scoring.py"),
|
| 52 |
+
Path("/benchmark/manifest.json"), Path("/logs/verifier/forged-reward.json"),
|
| 53 |
+
Path("/workspace/submission/forged-file")]:
|
| 54 |
+
try:
|
| 55 |
+
with target.open("ab"):
|
| 56 |
+
pass
|
| 57 |
+
except OSError as error:
|
| 58 |
+
assert error.errno in (errno.EACCES, errno.EPERM, errno.EROFS), (target, error)
|
| 59 |
+
else:
|
| 60 |
+
raise AssertionError(f"inference can modify protected path: {target}")
|
| 61 |
+
inputs, output = map(Path, sys.argv[1:])
|
| 62 |
+
manifest = json.loads((inputs / "manifest.json").read_text())
|
| 63 |
+
probability = json.loads((root / "weights/constant.json").read_text())["probability"]
|
| 64 |
+
assert probability == 0.1
|
| 65 |
+
for condition in manifest["conditions"]:
|
| 66 |
+
with np.load(inputs / condition["arrays"], allow_pickle=False) as source:
|
| 67 |
+
assert set(source.files) == {"sample_ids", "detectors"}, "labels leaked into inference input"
|
| 68 |
+
ids = source["sample_ids"][::-1]
|
| 69 |
+
np.savez(output / (condition["name"] + ".npz"), sample_ids=ids,
|
| 70 |
+
probabilities=np.full(len(ids), probability, dtype=np.float32))
|
| 71 |
+
print(json.dumps({"container_security_probe": "passed", "uid": os.getuid(),
|
| 72 |
+
"conditions": len(manifest["conditions"]), "probability": probability,
|
| 73 |
+
"network_interfaces": [name for _, name in socket.if_nameindex()],
|
| 74 |
+
"private_labels_absent": True, "sealed_volume_inaccessible": True,
|
| 75 |
+
"protected_paths_not_writable": True, "artifact_relocated": True,
|
| 76 |
+
"extensionless_executable_ran": True}), flush=True)
|
| 77 |
+
'''
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def sha256(path: Path) -> str:
|
| 81 |
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def write_json(path: Path, value: Any) -> None:
|
| 85 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 86 |
+
path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def prepare(root: Path) -> None:
|
| 90 |
+
"""Create unmistakably synthetic public inputs and separately held labels."""
|
| 91 |
+
import numpy as np
|
| 92 |
+
|
| 93 |
+
sys.path.insert(0, str(PROJECT))
|
| 94 |
+
from baselines.alphaqubit_artifact import EXPECTED_GROUPS
|
| 95 |
+
from qecbench.data import SCHEMA
|
| 96 |
+
|
| 97 |
+
inputs, labels = root / "data/verifier", root / "labels"
|
| 98 |
+
rows, target_rows = [], []
|
| 99 |
+
for group in EXPECTED_GROUPS:
|
| 100 |
+
distance, basis = int(group[1]), group[4]
|
| 101 |
+
center = group.split("center_")[1]
|
| 102 |
+
for rounds in range(1, 26, 2):
|
| 103 |
+
name = f"surface_code_b{basis}_d{distance}_r{rounds:02}_center_{center}"
|
| 104 |
+
folder = inputs / "conditions" / name
|
| 105 |
+
folder.mkdir(parents=True)
|
| 106 |
+
ids = np.array([1017, 5, 991, 70], dtype=np.uint64) + np.uint64(len(rows) * 10000)
|
| 107 |
+
packed = np.zeros((4, (rounds * (distance ** 2 - 1) + 7) // 8), dtype=np.uint8)
|
| 108 |
+
np.savez(folder / "arrays.npz", sample_ids=ids, detectors=packed)
|
| 109 |
+
# The constant decoder does not parse circuits; still provide a valid
|
| 110 |
+
# Stim detector-count fixture, never an actual experimental circuit.
|
| 111 |
+
(folder / "circuit_ideal.stim").write_text(
|
| 112 |
+
"# Synthetic container plumbing fixture, not a physical experiment\nR 0\nM 0\n"
|
| 113 |
+
+ "DETECTOR rec[-1]\n" * (rounds * (distance ** 2 - 1))
|
| 114 |
+
+ "OBSERVABLE_INCLUDE(0) rec[-1]\n"
|
| 115 |
+
)
|
| 116 |
+
label_path = labels / "conditions" / f"{name}.npz"
|
| 117 |
+
label_path.parent.mkdir(parents=True, exist_ok=True)
|
| 118 |
+
np.savez(label_path, sample_ids=ids, labels=np.array([0, 0, 0, 1], dtype=np.uint8))
|
| 119 |
+
rows.append({"name": name, "group": group, "distance": distance, "basis": basis,
|
| 120 |
+
"rounds": rounds, "shots": 4, "num_detectors": rounds * (distance ** 2 - 1),
|
| 121 |
+
"arrays": f"conditions/{name}/arrays.npz", "arrays_sha256": sha256(folder / "arrays.npz"),
|
| 122 |
+
"circuit": f"conditions/{name}/circuit_ideal.stim", "circuit_sha256": sha256(folder / "circuit_ideal.stim")})
|
| 123 |
+
target_rows.append({"name": name, "shots": 4, "arrays": f"conditions/{name}.npz", "arrays_sha256": sha256(label_path)})
|
| 124 |
+
write_json(inputs / "manifest.json", {"schema": SCHEMA, "split": "test", "synthetic_smoke_only": True,
|
| 125 |
+
"shots": 520, "conditions": list(reversed(rows))})
|
| 126 |
+
write_json(labels / "manifest.json", {"schema": "surface-code-decoding-labels/v1",
|
| 127 |
+
"synthetic_smoke_only": True, "input_manifest_sha256": sha256(inputs / "manifest.json"), "conditions": target_rows})
|
| 128 |
+
submission = root / "submission-valid"
|
| 129 |
+
(submission / "bin").mkdir(parents=True)
|
| 130 |
+
(submission / "bin/decoder").write_text(DECODER)
|
| 131 |
+
(submission / "bin/decoder").chmod(0o755)
|
| 132 |
+
(submission / "infer.sh").write_text('#!/usr/bin/env bash\nset -euo pipefail\nROOT="$(cd -- "$(dirname -- "$0")" && pwd)"\nexec "$ROOT/bin/decoder" "$1" "$2"\n')
|
| 133 |
+
(submission / "infer.sh").chmod(0o755)
|
| 134 |
+
(submission / "README.md").write_text("Synthetic constant-decoder container smoke. This artifact is not a scientific reference.\n")
|
| 135 |
+
(submission / "requirements.lock").write_text("Uses the verifier image's pinned NumPy runtime; no additional packages.\n")
|
| 136 |
+
write_json(submission / "weights/constant.json", {"probability": 0.1})
|
| 137 |
+
write_json(submission / "model_config.json", {"model": "constant Bernoulli probability", "weights": "weights/constant.json"})
|
| 138 |
+
write_json(submission / "training_provenance.json", {"purpose": "synthetic container security smoke only",
|
| 139 |
+
"fit": "Maximum likelihood on nine synthetic negative and one synthetic positive observation", "scientific_accuracy_evidence": False})
|
| 140 |
+
write_json(submission / "model_manifest.json", {"schema": "surface-code-decoding-model/v1",
|
| 141 |
+
"checkpoints": [{"path": "weights/constant.json", "sha256": sha256(submission / "weights/constant.json")}],
|
| 142 |
+
"model_config": "model_config.json", "training_provenance": "training_provenance.json"})
|
| 143 |
+
shutil.copytree(submission, root / "submission-invalid")
|
| 144 |
+
(root / "submission-invalid/model_manifest.json").write_text("[]\n")
|
| 145 |
+
(root / "missing-labels").mkdir()
|
| 146 |
+
write_json(root / "fixture.json", {"synthetic_smoke_only": True, "conditions": 130, "shots": 520,
|
| 147 |
+
"expected_valid_performance": 0.75, "source": "deterministic synthetic fixture; no downloaded scientific data"})
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def command(args: list[str], *, cwd: Path | None = None, env: dict[str, str] | None = None,
|
| 151 |
+
timeout: int = 600, check: bool = True) -> subprocess.CompletedProcess[str]:
|
| 152 |
+
print("+ " + " ".join(args), flush=True)
|
| 153 |
+
result = subprocess.run(args, cwd=cwd, env=env, text=True, stdout=subprocess.PIPE,
|
| 154 |
+
stderr=subprocess.STDOUT, timeout=timeout)
|
| 155 |
+
if result.stdout:
|
| 156 |
+
print(result.stdout, end="", flush=True)
|
| 157 |
+
if check and result.returncode:
|
| 158 |
+
raise subprocess.CalledProcessError(result.returncode, args, output=result.stdout)
|
| 159 |
+
return result
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def collect_reports(container: str, destination: Path) -> None:
|
| 163 |
+
"""Copy individual evidence files without exporting the protected artifact.
|
| 164 |
+
|
| 165 |
+
Recursively copying /logs/verifier also exports the frozen 0555 submission
|
| 166 |
+
tree. Docker then cannot create its children as the unprivileged host user.
|
| 167 |
+
Keep those security permissions intact and request only reviewable files.
|
| 168 |
+
"""
|
| 169 |
+
for relative in ("report.json", "reward.json", "inference/inference.log"):
|
| 170 |
+
target = destination / relative
|
| 171 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 172 |
+
result = command(["docker", "cp", f"{container}:/logs/verifier/{relative}", str(target)], check=False)
|
| 173 |
+
if result.returncode:
|
| 174 |
+
# An infrastructure failure must have no reward; an invalid
|
| 175 |
+
# manifest has no inference log. Other copy errors remain errors.
|
| 176 |
+
missing = "Could not find the file" in result.stdout
|
| 177 |
+
if relative != "report.json" and missing:
|
| 178 |
+
continue
|
| 179 |
+
raise RuntimeError(f"Cannot collect {relative} from {container}: {result.stdout.strip()}")
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def case_run(case: str, fixture: Path, output: Path, image: str) -> dict[str, Any]:
|
| 183 |
+
"""Run a fresh main/grader pair and private sealed volume per scenario."""
|
| 184 |
+
project = "qec-smoke-" + uuid.uuid4().hex[:12]
|
| 185 |
+
container = project + "-inference"
|
| 186 |
+
case_output = output / case
|
| 187 |
+
case_output.mkdir(parents=True)
|
| 188 |
+
submission = fixture / ("submission-invalid" if case == "invalid-submission" else "submission-valid")
|
| 189 |
+
labels = fixture / ("missing-labels" if case == "missing-labels" else "labels")
|
| 190 |
+
override = fixture / f"override-{case}.json"
|
| 191 |
+
write_json(override, {"services": {
|
| 192 |
+
"main": {"image": image, "cpus": 2, "mem_limit": "4g", "shm_size": "256m",
|
| 193 |
+
"volumes": [{"type": "bind", "source": str(submission), "target": "/workspace/submission",
|
| 194 |
+
"read_only": True, "bind": {"create_host_path": False}}]},
|
| 195 |
+
"grader": {"image": image, "cpus": 2, "mem_limit": "4g",
|
| 196 |
+
"command": ["python", "/opt/task/tests/grader.py", "--wait-seconds", "180"]}}})
|
| 197 |
+
env = dict(os.environ, TASK_DATA_DIR=str(fixture / "data"), TASK_PRIVATE_DIR=str(labels))
|
| 198 |
+
compose = ["docker", "compose", "--project-name", project, "-f", str(TASK / "tests/docker-compose.yaml"),
|
| 199 |
+
"-f", str(TASK / "tests/docker-compose.cpu-smoke.yaml"), "-f", str(override)]
|
| 200 |
+
# Check the actual Compose merge: CI must not silently request a GPU.
|
| 201 |
+
resolved = json.loads(command(compose + ["config", "--format", "json"], env=env).stdout)
|
| 202 |
+
for service in resolved["services"].values():
|
| 203 |
+
assert not service.get("deploy", {}).get("resources", {}).get("reservations", {}).get("devices")
|
| 204 |
+
assert service["network_mode"] == "none"
|
| 205 |
+
run: subprocess.CompletedProcess[str] | None = None
|
| 206 |
+
try:
|
| 207 |
+
command(compose + ["up", "-d", "--no-build", "grader"], env=env)
|
| 208 |
+
run = command(compose + ["run", "--no-deps", "--name", container, "-e", "QEC_INFERENCE_TIMEOUT_SECONDS=60",
|
| 209 |
+
"main", "/opt/task/tests/test.sh"], env=env, timeout=420, check=False)
|
| 210 |
+
(case_output / "supervisor.log").write_text(run.stdout)
|
| 211 |
+
collect_reports(container, case_output)
|
| 212 |
+
grader_logs = command(compose + ["logs", "--no-color", "grader"], env=env, check=False)
|
| 213 |
+
(case_output / "grader.log").write_text(grader_logs.stdout)
|
| 214 |
+
report_path = case_output / "report.json"
|
| 215 |
+
if not report_path.is_file():
|
| 216 |
+
raise AssertionError(f"{case}: supervisor did not publish a report; see {case_output}")
|
| 217 |
+
report = json.loads(report_path.read_text())
|
| 218 |
+
reward_path = case_output / "reward.json"
|
| 219 |
+
config = json.loads((PROJECT / "score_config.json").read_text())
|
| 220 |
+
if case == "valid":
|
| 221 |
+
assert run.returncode == 0, run.stdout
|
| 222 |
+
assert report["status"] == "valid" and report["model_quality_measured"] is True
|
| 223 |
+
assert report["shots"] == 520 and report["conditions"] == 130
|
| 224 |
+
assert report["performance"] == 0.75 and report["balanced_logical_failure"] == 0.25
|
| 225 |
+
expected = max(0.0, (0.75 - config["lower_bound"]) / (config["upper_bound"] - config["lower_bound"]))
|
| 226 |
+
assert math.isclose(report["score"], expected, rel_tol=0, abs_tol=1e-12)
|
| 227 |
+
assert json.loads(reward_path.read_text())["reward"] == report["performance"]
|
| 228 |
+
inference_log = (case_output / "inference/inference.log").read_text()
|
| 229 |
+
probes = [json.loads(line) for line in inference_log.splitlines() if line.startswith('{"container_security_probe"')]
|
| 230 |
+
assert len(probes) == 1 and probes[0]["container_security_probe"] == "passed"
|
| 231 |
+
elif case == "invalid-submission":
|
| 232 |
+
assert run.returncode == 0 and report["status"] == "invalid_submission"
|
| 233 |
+
assert report["model_quality_measured"] is False and report["performance"] is None
|
| 234 |
+
assert json.loads(reward_path.read_text()) == {"reward": 0.0}
|
| 235 |
+
else:
|
| 236 |
+
assert run.returncode != 0 and report["status"] == "infrastructure_error"
|
| 237 |
+
assert report["model_quality_measured"] is False and not reward_path.exists()
|
| 238 |
+
return {"case": case, "status": "passed", "verifier_status": report["status"],
|
| 239 |
+
"supervisor_exit_code": run.returncode, "score": report.get("score"),
|
| 240 |
+
"scientific_accuracy_evidence": False}
|
| 241 |
+
finally:
|
| 242 |
+
command(["docker", "rm", "-f", container], check=False)
|
| 243 |
+
command(compose + ["down", "--volumes", "--remove-orphans"], env=env, check=False)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def orchestrate(args: argparse.Namespace) -> None:
|
| 247 |
+
started = time.monotonic()
|
| 248 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 249 |
+
command(["docker", "version"])
|
| 250 |
+
command(["docker", "compose", "version"])
|
| 251 |
+
if args.build:
|
| 252 |
+
command(["docker", "build", "-t", args.image, "-f", str(TASK / "tests/Dockerfile"), str(TASK)], timeout=2400)
|
| 253 |
+
with tempfile.TemporaryDirectory(prefix="qec-container-smoke-") as temporary:
|
| 254 |
+
fixture = Path(temporary)
|
| 255 |
+
command(["docker", "run", "--rm", "--network", "none", "--user", f"{os.getuid()}:{os.getgid()}",
|
| 256 |
+
"--mount", f"type=bind,src={fixture},dst=/fixture", args.image,
|
| 257 |
+
"python", "/opt/task/tests/container_smoke.py", "--prepare", "/fixture"])
|
| 258 |
+
results = [case_run(case, fixture, args.output, args.image)
|
| 259 |
+
for case in ("valid", "invalid-submission", "missing-labels")]
|
| 260 |
+
write_json(args.output / "container-smoke.json", {"schema": "surface-code-container-smoke/v1",
|
| 261 |
+
"status": "passed", "scientific_accuracy_evidence": False,
|
| 262 |
+
"scope": "Actual native Docker CPU supervisor/grader role separation and error classification on synthetic data",
|
| 263 |
+
"cases": results, "wall_seconds": time.monotonic() - started})
|
| 264 |
+
print(f"Container smoke passed; evidence: {args.output / 'container-smoke.json'}")
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def main() -> None:
|
| 268 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 269 |
+
parser.add_argument("--prepare", type=Path, help="Internal: generate synthetic fixtures using the image's NumPy")
|
| 270 |
+
parser.add_argument("--image", default="surface-code-verifier:smoke")
|
| 271 |
+
parser.add_argument("--build", action="store_true", help="Build the pinned verifier image before the smoke")
|
| 272 |
+
parser.add_argument("--output", type=Path, default=Path("container-smoke-results"))
|
| 273 |
+
args = parser.parse_args()
|
| 274 |
+
if args.prepare:
|
| 275 |
+
prepare(args.prepare)
|
| 276 |
+
else:
|
| 277 |
+
args.output = args.output.resolve()
|
| 278 |
+
orchestrate(args)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
if __name__ == "__main__":
|
| 282 |
+
main()
|
reproduction/files/05/0554f498d0368ecd36ac232c40d7bcd0b9dc20ed1a901d72e300b13d501ae4d5/test_inference.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU regression checks for missing observations and batch independence."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import sys
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
p = argparse.ArgumentParser()
|
| 11 |
+
p.add_argument("--model", type=Path, required=True)
|
| 12 |
+
p.add_argument("--output", type=Path, required=True)
|
| 13 |
+
a = p.parse_args()
|
| 14 |
+
sys.path.insert(0, str(a.model.resolve()))
|
| 15 |
+
from infer import EncoderConfig, Modality, configure_inference, embed
|
| 16 |
+
|
| 17 |
+
model = EncoderConfig.from_dict(
|
| 18 |
+
json.loads((a.model / "config.json").read_text())
|
| 19 |
+
).build()
|
| 20 |
+
model.load_state_dict(
|
| 21 |
+
torch.load(a.model / "encoder.pt", map_location="cpu", weights_only=True)
|
| 22 |
+
)
|
| 23 |
+
configure_inference(model)
|
| 24 |
+
rng = np.random.default_rng(42)
|
| 25 |
+
pixels = {
|
| 26 |
+
"sentinel2_l2a": rng.normal(size=(3, 8, 8, 3, 12)).astype(np.float32),
|
| 27 |
+
"sentinel1": rng.normal(size=(3, 8, 8, 3, 2)).astype(np.float32),
|
| 28 |
+
}
|
| 29 |
+
valid = {
|
| 30 |
+
"sentinel2_l2a": np.ones((3, 3, 3), dtype=bool),
|
| 31 |
+
"sentinel1": np.ones((3, 3, 1), dtype=bool),
|
| 32 |
+
}
|
| 33 |
+
valid["sentinel1"][0] = False
|
| 34 |
+
valid["sentinel2_l2a"][1, 1, 1] = False
|
| 35 |
+
for mask in valid.values():
|
| 36 |
+
mask[2] = False
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def run(x, masks):
|
| 40 |
+
return embed(model, x, torch.device("cpu"), center=True, valid=masks)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
joint = run(pixels, valid)
|
| 44 |
+
alone = np.concatenate(
|
| 45 |
+
[
|
| 46 |
+
run(
|
| 47 |
+
{k: v[i : i + 1] for k, v in pixels.items()},
|
| 48 |
+
{k: v[i : i + 1] for k, v in valid.items()},
|
| 49 |
+
)
|
| 50 |
+
for i in range(3)
|
| 51 |
+
]
|
| 52 |
+
)
|
| 53 |
+
altered = {k: v.copy() for k, v in pixels.items()}
|
| 54 |
+
for name in altered:
|
| 55 |
+
spec = Modality.get(name)
|
| 56 |
+
for row, time, group in np.argwhere(~valid[name]):
|
| 57 |
+
for band in spec.band_sets[group].bands:
|
| 58 |
+
altered[name][row, :, :, time, spec.band_order.index(band)] = 100000
|
| 59 |
+
perturbed = run(altered, valid)
|
| 60 |
+
report = {
|
| 61 |
+
"single_vs_batch_max_abs": float(np.max(abs(joint - alone))),
|
| 62 |
+
"masked_pixel_perturbation_max_abs": float(np.max(abs(joint - perturbed))),
|
| 63 |
+
"unobserved_row_is_zero": bool(np.all(joint[2] == 0)),
|
| 64 |
+
}
|
| 65 |
+
assert report["single_vs_batch_max_abs"] < 1e-5, report
|
| 66 |
+
assert report["masked_pixel_perturbation_max_abs"] < 1e-5, report
|
| 67 |
+
assert report["unobserved_row_is_zero"], report
|
| 68 |
+
a.output.write_text(json.dumps(report, indent=2))
|
| 69 |
+
print(json.dumps(report, indent=2))
|
reproduction/files/05/05735f6057ba486e9a82f09c0748bf41c8c736b775acd454c0343ff826bded8a/crystal_cache.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-grading-job writable HF lock directory over frozen dataset tables.
|
| 2 |
+
|
| 3 |
+
This is the same directory-link layout used by the task's native
|
| 4 |
+
writable_datasets_cache helper, applied explicitly by the Beaker launcher.
|
| 5 |
+
No scorer functions or dataset bytes are changed.
|
| 6 |
+
"""
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def prepare(source, destination):
|
| 11 |
+
source = Path(source).resolve(strict=True)
|
| 12 |
+
destination = Path(destination)
|
| 13 |
+
if not source.is_dir():
|
| 14 |
+
raise ValueError('Prepared dataset cache is not a directory')
|
| 15 |
+
if destination.resolve().is_relative_to(source):
|
| 16 |
+
raise ValueError('Writable cache must be outside prepared assets')
|
| 17 |
+
destination.mkdir(parents=True, exist_ok=False)
|
| 18 |
+
linked = []
|
| 19 |
+
for entry in sorted(source.iterdir()):
|
| 20 |
+
if entry.is_dir():
|
| 21 |
+
target = entry.resolve(strict=True)
|
| 22 |
+
if not target.is_relative_to(source):
|
| 23 |
+
raise ValueError('Prepared dataset directory escapes asset cache')
|
| 24 |
+
(destination / entry.name).symlink_to(target, target_is_directory=True)
|
| 25 |
+
linked.append(entry.name)
|
| 26 |
+
if not linked:
|
| 27 |
+
raise ValueError('No prepared dataset tables found')
|
| 28 |
+
return {'source': str(source), 'writable_cache': str(destination),
|
| 29 |
+
'linked_datasets': linked, 'table_bytes_copied': False}
|
reproduction/files/06/06574a519731708f2dbb71ebeb491fbdf3114f4d7af8b9eb121da35fd30c1b62/test_sharding.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Check lossless input shards, complete batch boundaries and merge rejection."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
import unittest
|
| 9 |
+
|
| 10 |
+
import h5py
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
TRACK = Path(__file__).resolve().parents[1]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ShardingTest(unittest.TestCase):
|
| 17 |
+
def test_coverage_and_rejection(self):
|
| 18 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 19 |
+
root = Path(tmp)
|
| 20 |
+
source = root / "input.h5"
|
| 21 |
+
pixels = np.arange(102, dtype=np.uint16).reshape(51, 2)
|
| 22 |
+
with h5py.File(source, "w") as h:
|
| 23 |
+
h.attrs["task"] = "lfmc"
|
| 24 |
+
h.create_dataset(
|
| 25 |
+
"ids", data=[str(i) for i in range(51)], dtype=h5py.string_dtype()
|
| 26 |
+
)
|
| 27 |
+
h.create_dataset("sentinel2_l2a", data=pixels)
|
| 28 |
+
command = [
|
| 29 |
+
sys.executable,
|
| 30 |
+
str(TRACK / "environment/data/shard_inputs.py"),
|
| 31 |
+
"--input",
|
| 32 |
+
str(source),
|
| 33 |
+
"--output",
|
| 34 |
+
str(root / "shards"),
|
| 35 |
+
"--shards",
|
| 36 |
+
"3",
|
| 37 |
+
]
|
| 38 |
+
result = subprocess.run(command, capture_output=True, text=True)
|
| 39 |
+
self.assertEqual(result.returncode, 0, result.stderr)
|
| 40 |
+
manifest_path = root / "shards/manifest.json"
|
| 41 |
+
manifest = json.loads(manifest_path.read_text())
|
| 42 |
+
self.assertEqual([s["start"] for s in manifest["shards"]], [0, 16, 32])
|
| 43 |
+
collected = []
|
| 44 |
+
for index, shard in enumerate(manifest["shards"]):
|
| 45 |
+
with h5py.File(root / "shards" / shard["file"]) as h:
|
| 46 |
+
collected.append(h["sentinel2_l2a"][:])
|
| 47 |
+
ids = h["ids"].asstr()[:].astype(str)
|
| 48 |
+
features = np.repeat(
|
| 49 |
+
np.arange(shard["start"], shard["stop"], dtype=np.float32)[
|
| 50 |
+
:, None
|
| 51 |
+
],
|
| 52 |
+
3,
|
| 53 |
+
axis=1,
|
| 54 |
+
)
|
| 55 |
+
part = root / f"features/part{index:03d}"
|
| 56 |
+
part.mkdir(parents=True)
|
| 57 |
+
np.savez(part / "features.npz", ids=ids, features=features)
|
| 58 |
+
np.testing.assert_array_equal(np.concatenate(collected), pixels)
|
| 59 |
+
output = root / "merged.npz"
|
| 60 |
+
merge = [
|
| 61 |
+
sys.executable,
|
| 62 |
+
str(TRACK / "docs/analysis/merge_features.py"),
|
| 63 |
+
"--manifest",
|
| 64 |
+
str(manifest_path),
|
| 65 |
+
"--features",
|
| 66 |
+
str(root / "features"),
|
| 67 |
+
"--output",
|
| 68 |
+
str(output),
|
| 69 |
+
]
|
| 70 |
+
result = subprocess.run(merge, capture_output=True, text=True)
|
| 71 |
+
self.assertEqual(result.returncode, 0, result.stderr)
|
| 72 |
+
with np.load(output, allow_pickle=False) as merged:
|
| 73 |
+
np.testing.assert_array_equal(merged["ids"], np.arange(51).astype(str))
|
| 74 |
+
np.testing.assert_array_equal(merged["features"][:, 0], np.arange(51))
|
| 75 |
+
result = subprocess.run(merge, capture_output=True, text=True)
|
| 76 |
+
self.assertNotEqual(
|
| 77 |
+
result.returncode, 0, "must not overwrite existing features"
|
| 78 |
+
)
|
| 79 |
+
output.unlink()
|
| 80 |
+
original = manifest_path.read_text()
|
| 81 |
+
manifest["start"] = 16
|
| 82 |
+
manifest["full_release"] = False
|
| 83 |
+
manifest_path.write_text(json.dumps(manifest))
|
| 84 |
+
result = subprocess.run(merge, capture_output=True, text=True)
|
| 85 |
+
self.assertNotEqual(result.returncode, 0)
|
| 86 |
+
self.assertIn("complete release", result.stderr)
|
| 87 |
+
manifest_path.write_text(original)
|
| 88 |
+
path = root / "features/part001/features.npz"
|
| 89 |
+
with np.load(path, allow_pickle=False) as good:
|
| 90 |
+
ids, features = good["ids"].copy(), good["features"].copy()
|
| 91 |
+
ids[0] = ids[1]
|
| 92 |
+
np.savez(path, ids=ids, features=features)
|
| 93 |
+
result = subprocess.run(merge, capture_output=True, text=True)
|
| 94 |
+
self.assertNotEqual(result.returncode, 0)
|
| 95 |
+
self.assertIn("IDs do not match", result.stderr)
|
| 96 |
+
self.assertFalse(output.exists())
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
if __name__ == "__main__":
|
| 100 |
+
unittest.main()
|
reproduction/files/07/07c28629ae97a2a93f1730061d27d8d096731bcd7a9e579e00c7980e0d6afc24/test_native_replay.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic bookkeeping/adapter tests, never substitutes for native CFD runs."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
import subprocess
|
| 6 |
+
import tempfile
|
| 7 |
+
import unittest
|
| 8 |
+
from unittest.mock import Mock, patch
|
| 9 |
+
|
| 10 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'environment/evaluation'))
|
| 11 |
+
import case_spec
|
| 12 |
+
import evaluate_native as replay
|
| 13 |
+
from evaluate import package_hash
|
| 14 |
+
from protocol import InfrastructureError, PolicyError
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class NativeProfilesTests(unittest.TestCase):
|
| 18 |
+
def test_exact_frozen_coverage_and_semantics(self):
|
| 19 |
+
spec, cases = case_spec.select_cases(['all'])
|
| 20 |
+
release = case_spec.load_release()
|
| 21 |
+
self.assertEqual([c['id'] for c in cases], [c['id'] for c in release['cases']])
|
| 22 |
+
self.assertEqual(len(cases), 39)
|
| 23 |
+
self.assertEqual(spec['data_release_sha256'], case_spec.digest(release))
|
| 24 |
+
for c, source in zip(cases, release['cases']):
|
| 25 |
+
self.assertEqual(c['runtime_profile'], source['runtime_profile'])
|
| 26 |
+
self.assertEqual(c['solver_processes'], source['required_solver_gpus'])
|
| 27 |
+
self.assertEqual(c['horizon'], source['selection_review']['native_episode_controls_for_costing'])
|
| 28 |
+
self.assertEqual(c['seeds'], [123])
|
| 29 |
+
self.assertEqual(c['episode_end'], 'native')
|
| 30 |
+
self.assertGreaterEqual(c['timeout_sec'], 1800)
|
| 31 |
+
self.assertEqual({c['backend'] for c in cases}, {'maia', 'jax', 'jax-fluids'})
|
| 32 |
+
self.assertEqual(max(c['observation_size'] for c in cases), 128)
|
| 33 |
+
self.assertEqual(max(c['action_size'] for c in cases), 24)
|
| 34 |
+
|
| 35 |
+
def test_unknown_duplicate_and_mixed_all_rejected(self):
|
| 36 |
+
for names in ([], ['unknown'], ['all', 'Cylinder_2D_Re200'],
|
| 37 |
+
['Cylinder_2D_Re200', 'Cylinder_2D_Re200']):
|
| 38 |
+
with self.subTest(names=names), self.assertRaises(InfrastructureError):
|
| 39 |
+
case_spec.select_cases(names)
|
| 40 |
+
|
| 41 |
+
def test_source_rejection_precedes_policy(self):
|
| 42 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 43 |
+
with self.assertRaises((InfrastructureError, OSError)):
|
| 44 |
+
case_spec.verify_resources(Path(directory), case_spec.select_cases(['all'])[1])
|
| 45 |
+
|
| 46 |
+
def test_missing_second_gpu_fails_before_native_solver_import(self):
|
| 47 |
+
import run_native
|
| 48 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 49 |
+
args = ['run_native.py', '--case', 'Cube_3D_Re3700', '--data', directory,
|
| 50 |
+
'--submission', directory, '--output', directory]
|
| 51 |
+
with patch.object(sys, 'argv', args), patch.object(run_native, 'verify_resources'), \
|
| 52 |
+
patch.object(run_native, 'local_only'), \
|
| 53 |
+
patch.object(run_native.subprocess, 'check_output', return_value='["GPU-test"]'):
|
| 54 |
+
with self.assertRaisesRegex(RuntimeError, 'requires 2 distinct GPUs'):
|
| 55 |
+
run_native.main()
|
| 56 |
+
self.assertTrue((Path(directory) / 'launcher-error.json').exists())
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class NativeReplayTests(unittest.TestCase):
|
| 60 |
+
def setUp(self):
|
| 61 |
+
self.temp = tempfile.TemporaryDirectory()
|
| 62 |
+
self.addCleanup(self.temp.cleanup)
|
| 63 |
+
self.root = Path(self.temp.name)
|
| 64 |
+
self.data = self.root / 'data'
|
| 65 |
+
self.data.mkdir()
|
| 66 |
+
self.package = self.root / 'candidate'
|
| 67 |
+
self.package.mkdir()
|
| 68 |
+
(self.package / 'README.md').write_text('Synthetic bookkeeping fixture, not a model.\n')
|
| 69 |
+
(self.package / 'infer.sh').write_text('exit 0\n')
|
| 70 |
+
self.names = ['Cylinder_2D_Re200', 'Channel_3D_Retau180']
|
| 71 |
+
self.output = self.root / 'results'
|
| 72 |
+
self.verify = patch.object(replay, 'verify_resources').start()
|
| 73 |
+
self.addCleanup(patch.stopall)
|
| 74 |
+
self.snapshots = []
|
| 75 |
+
|
| 76 |
+
def runner(self, case, data, package, output):
|
| 77 |
+
self.assertNotEqual(package, self.package)
|
| 78 |
+
self.assertEqual(package_hash(package), package_hash(self.package))
|
| 79 |
+
self.snapshots.append(str(package))
|
| 80 |
+
return {'status': 'ok', 'submission_sha256': package_hash(package), 'episodes': [
|
| 81 |
+
{'seed': seed, 'steps': case['horizon'], 'return': -4.0,
|
| 82 |
+
'primary_metric': dict(case['primary_metric'], status='ok', value=1.25),
|
| 83 |
+
'terminated': True, 'truncated': False} for seed in case['seeds']]}
|
| 84 |
+
|
| 85 |
+
def evaluate(self, runner=None):
|
| 86 |
+
return replay.evaluate_native(self.data, self.package, self.output, self.names,
|
| 87 |
+
runner=runner or self.runner)
|
| 88 |
+
|
| 89 |
+
def test_relocated_same_package_no_anchors_or_suite_required(self):
|
| 90 |
+
result = self.evaluate()
|
| 91 |
+
self.assertEqual(result['status'], 'ok')
|
| 92 |
+
self.assertEqual(result['successful_cases'], 2)
|
| 93 |
+
self.assertFalse(result['benchmark_validated'])
|
| 94 |
+
self.assertFalse(result['all_frozen_cases_selected'])
|
| 95 |
+
self.assertEqual(len(set(self.snapshots)), 1)
|
| 96 |
+
self.assertEqual(result['cases'][self.names[0]]['mean_return'], -4)
|
| 97 |
+
self.assertEqual(result['cases'][self.names[0]]['primary_metric']['value'], 1.25)
|
| 98 |
+
self.assertEqual(self.verify.call_count, 2)
|
| 99 |
+
self.assertFalse((self.output / 'reward.json').exists())
|
| 100 |
+
self.assertFalse((self.data / 'suite.json').exists())
|
| 101 |
+
|
| 102 |
+
def test_all_cases_keep_one_package_and_full_accounting(self):
|
| 103 |
+
self.names = ['all']
|
| 104 |
+
result = self.evaluate()
|
| 105 |
+
self.assertEqual(result['successful_cases'], 39)
|
| 106 |
+
self.assertTrue(result['all_frozen_cases_selected'])
|
| 107 |
+
self.assertFalse(result['benchmark_validated'])
|
| 108 |
+
self.assertEqual(len(set(self.snapshots)), 1)
|
| 109 |
+
|
| 110 |
+
def test_failures_are_explicit_and_remaining_cases_still_run(self):
|
| 111 |
+
def runner(case, *args):
|
| 112 |
+
if case['id'] == self.names[0]:
|
| 113 |
+
raise InfrastructureError('Synthetic solver failure')
|
| 114 |
+
row = self.runner(case, *args)
|
| 115 |
+
row.update(status='policy_error', error='Synthetic malformed action')
|
| 116 |
+
row.pop('episodes')
|
| 117 |
+
return row
|
| 118 |
+
result = self.evaluate(runner)
|
| 119 |
+
self.assertEqual(result['status'], 'completed_with_errors')
|
| 120 |
+
self.assertEqual(len(result['cases']), 2)
|
| 121 |
+
self.assertEqual(result['cases'][self.names[0]]['status'], 'infrastructure_error')
|
| 122 |
+
self.assertEqual(result['cases'][self.names[1]]['status'], 'policy_error')
|
| 123 |
+
self.assertNotIn('mean_return', result['cases'][self.names[1]])
|
| 124 |
+
self.assertFalse((self.output / 'reward.json').exists())
|
| 125 |
+
|
| 126 |
+
def test_missing_package_records_every_requested_case(self):
|
| 127 |
+
self.package = self.root / 'absent'
|
| 128 |
+
result = self.evaluate()
|
| 129 |
+
self.assertEqual(result['requested_cases'], 2)
|
| 130 |
+
self.assertTrue(all(r['status'] == 'policy_error' for r in result['cases'].values()))
|
| 131 |
+
|
| 132 |
+
def test_invalid_episode_or_package_identity_rejected(self):
|
| 133 |
+
corruptions = [lambda row: row.update(submission_sha256='wrong'),
|
| 134 |
+
lambda row: row['episodes'][0].update(steps=1),
|
| 135 |
+
lambda row: row['episodes'][0].update(seed=0),
|
| 136 |
+
lambda row: row['episodes'][0].update(**{'return': float('nan')}),
|
| 137 |
+
lambda row: row['episodes'][0].pop('primary_metric'),
|
| 138 |
+
lambda row: row['episodes'][0]['primary_metric'].update(value=float('nan')),
|
| 139 |
+
lambda row: row['episodes'][0].update(terminated=False, truncated=False)]
|
| 140 |
+
for i, corrupt in enumerate(corruptions):
|
| 141 |
+
self.output = self.root / f'bad-{i}'
|
| 142 |
+
def runner(*args):
|
| 143 |
+
row = self.runner(*args)
|
| 144 |
+
corrupt(row)
|
| 145 |
+
return row
|
| 146 |
+
with self.subTest(i=i):
|
| 147 |
+
result = self.evaluate(runner)
|
| 148 |
+
self.assertTrue(all(r['status'] == 'infrastructure_error' for r in result['cases'].values()))
|
| 149 |
+
|
| 150 |
+
def test_snapshot_mutation_rejects_entire_run(self):
|
| 151 |
+
def runner(case, data, package, output):
|
| 152 |
+
row = self.runner(case, data, package, output)
|
| 153 |
+
(package / 'README.md').write_text('Changed during replay')
|
| 154 |
+
return row
|
| 155 |
+
with self.assertRaisesRegex(InfrastructureError, 'snapshot mutated'):
|
| 156 |
+
self.evaluate(runner)
|
| 157 |
+
self.assertTrue((self.output / 'error.json').exists())
|
| 158 |
+
self.assertFalse((self.output / 'results.json').exists())
|
| 159 |
+
|
| 160 |
+
def test_resource_change_rejects_results(self):
|
| 161 |
+
self.verify.side_effect = [None, InfrastructureError('Source changed')]
|
| 162 |
+
with self.assertRaisesRegex(InfrastructureError, 'Source changed'):
|
| 163 |
+
self.evaluate()
|
| 164 |
+
self.assertFalse((self.output / 'results.json').exists())
|
| 165 |
+
|
| 166 |
+
def test_code_change_rejects_results(self):
|
| 167 |
+
with patch.object(replay, 'implementation_hash', side_effect=['before', 'after']):
|
| 168 |
+
with self.assertRaisesRegex(InfrastructureError, 'implementation changed'):
|
| 169 |
+
self.evaluate()
|
| 170 |
+
|
| 171 |
+
def test_policy_session_cleanup_and_pid_reuse_protection(self):
|
| 172 |
+
process = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'], start_new_session=True)
|
| 173 |
+
self.addCleanup(lambda: process.poll() is None and process.kill())
|
| 174 |
+
ticks = Path(f'/proc/{process.pid}/stat').read_text().rsplit(')', 1)[1].split()[19]
|
| 175 |
+
receipt = self.root / 'policy-process.json'
|
| 176 |
+
receipt.write_text(json.dumps({'pid': process.pid, 'start_ticks': 'stale'}))
|
| 177 |
+
replay.stop_policy(self.root)
|
| 178 |
+
self.assertIsNone(process.poll())
|
| 179 |
+
receipt.write_text(json.dumps({'pid': process.pid, 'start_ticks': ticks}))
|
| 180 |
+
replay.stop_policy(self.root)
|
| 181 |
+
self.assertEqual(process.wait(timeout=3), -9)
|
| 182 |
+
replay.stop_policy(self.root)
|
| 183 |
+
|
| 184 |
+
def test_immediate_policy_exit_is_not_an_infrastructure_error(self):
|
| 185 |
+
import native_envs
|
| 186 |
+
import run_native
|
| 187 |
+
env, policy = Mock(), Mock()
|
| 188 |
+
policy.process.pid = 999999999
|
| 189 |
+
case = case_spec.select_cases([self.names[0]])[1][0]
|
| 190 |
+
with patch.object(native_envs, 'make_env', return_value=env), \
|
| 191 |
+
patch.object(run_native, 'Policy', return_value=policy), \
|
| 192 |
+
patch.object(run_native, 'replay_episode', side_effect=PolicyError('Exited')):
|
| 193 |
+
run_native.worker(case, self.data, self.package, self.root)
|
| 194 |
+
self.assertEqual(json.loads((self.root / 'result.json').read_text())['status'], 'policy_error')
|
| 195 |
+
policy.abort.assert_called_once()
|
| 196 |
+
env.close.assert_called_once()
|
| 197 |
+
|
| 198 |
+
def test_overlapping_and_stale_outputs_rejected(self):
|
| 199 |
+
for output in (self.data / 'output', self.package / 'output', self.root):
|
| 200 |
+
self.output = output
|
| 201 |
+
with self.subTest(output=output), self.assertRaises(InfrastructureError):
|
| 202 |
+
self.evaluate()
|
| 203 |
+
self.output = self.root / 'results'
|
| 204 |
+
self.output.mkdir()
|
| 205 |
+
(self.output / 'reward.json').write_text('{"score":1}')
|
| 206 |
+
with self.assertRaisesRegex(InfrastructureError, 'empty'):
|
| 207 |
+
self.evaluate()
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
try:
|
| 211 |
+
import numpy as np
|
| 212 |
+
except ImportError:
|
| 213 |
+
np = None
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@unittest.skipIf(np is None, 'Native scalar adapters need NumPy from the task runtime')
|
| 217 |
+
class ReplayAdapterTests(unittest.TestCase):
|
| 218 |
+
def test_native_completion_and_scalar_diagnostics(self):
|
| 219 |
+
from native_envs import ReplayAdapter
|
| 220 |
+
class Env:
|
| 221 |
+
class Space:
|
| 222 |
+
dtype, shape = np.float32, (1,)
|
| 223 |
+
observation_space = action_space = Space()
|
| 224 |
+
def reset(self, seed):
|
| 225 |
+
self.count = 0
|
| 226 |
+
return np.zeros(1), {}
|
| 227 |
+
def step(self, action):
|
| 228 |
+
self.count += 1
|
| 229 |
+
return np.ones(1), np.float32(-1), self.count == 2, False, {'lift': np.array([2.])}
|
| 230 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 231 |
+
env = ReplayAdapter(Env(), {'id': 'synthetic', 'horizon': 2}, Path(directory))
|
| 232 |
+
env.reset(seed=123)
|
| 233 |
+
self.assertFalse(env.step([0])[2])
|
| 234 |
+
self.assertEqual(env.step([0])[4], {'lift': 2.0})
|
| 235 |
+
self.assertEqual(json.loads((Path(directory) / 'progress.json').read_text())['phase'], 'complete')
|
| 236 |
+
with self.assertRaises(InfrastructureError):
|
| 237 |
+
env.step([0])
|
| 238 |
+
env.case['horizon'] = 3
|
| 239 |
+
env.reset(seed=123)
|
| 240 |
+
env.step([0])
|
| 241 |
+
with self.assertRaisesRegex(InfrastructureError, 'termination differs'):
|
| 242 |
+
env.step([0])
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
if __name__ == '__main__':
|
| 246 |
+
unittest.main()
|
reproduction/files/08/08431c3d888f0a102552f1facf1ea72135d88e504584f2531dea1a5c0c979e2f/score_extra.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Score a run of extra.py against the references of the same split.
|
| 2 |
+
|
| 3 |
+
python score_extra.py --suite kappa|mof|amorphous|cleavage|neb --run RUN_DIR \
|
| 4 |
+
--inputs INPUTS_DIR --references REFERENCES_DIR
|
| 5 |
+
|
| 6 |
+
INPUTS_DIR is the label-free split directory given to extra.py; REFERENCES_DIR holds its
|
| 7 |
+
references.json(.gz). The two may be the same directory (development builds).
|
| 8 |
+
|
| 9 |
+
Missing or failed items are scored, never dropped:
|
| 10 |
+
- kappa: SRME as in Matbench Discovery (imaginary modes, broken symmetry and failures score 2).
|
| 11 |
+
- mof: MAPE of B0; each MOF's error is capped at 200 %, and a failed MOF scores the cap.
|
| 12 |
+
- amorphous: per-system energy RMSE (offset removed) and force RMSE, each relative to the reference
|
| 13 |
+
standard deviation; a failed structure scores about twice the error of predicting the mean
|
| 14 |
+
(energy error +-2 std, forces -F_ref).
|
| 15 |
+
- cleavage: relative MAE (MAE / mean |reference|); each slab's error is capped at 2 |reference|, and
|
| 16 |
+
a failed slab scores the cap.
|
| 17 |
+
- neb: barrier MAE over all paths with each error capped at 2 eV (diverging NEB runs give errors of
|
| 18 |
+
tens of eV); a failed path scores the cap. Also reports the converged fraction and the MAE over
|
| 19 |
+
converged paths.
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import gzip
|
| 25 |
+
import json
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
KAPPA_ERROR_MAX = 2.0
|
| 31 |
+
MOF_CAP = 2.0
|
| 32 |
+
NEB_CAP_EV = 2.0
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def load(path: Path):
|
| 36 |
+
return json.load(gzip.open(path)) if path.suffix == ".gz" else json.loads(path.read_text())
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def predictions(run: Path) -> dict[str, dict]:
|
| 40 |
+
out = {}
|
| 41 |
+
for f in (run / "items").glob("*.json"):
|
| 42 |
+
r = json.loads(f.read_text())
|
| 43 |
+
out[r["id"]] = r
|
| 44 |
+
return out
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def ok(p):
|
| 48 |
+
return p is not None and p.get("status") == "ok"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# ------------------------------------------------------------------------------------------ kappa
|
| 52 |
+
def kappa_avg(kappa) -> np.ndarray:
|
| 53 |
+
a = np.asarray(kappa, dtype=float)
|
| 54 |
+
if a.shape[-2:] == (3, 3):
|
| 55 |
+
return np.trace(a, axis1=-2, axis2=-1) / 3
|
| 56 |
+
if a.shape[-1] == 6:
|
| 57 |
+
return a[..., :3].mean(axis=-1)
|
| 58 |
+
if a.shape[-1] == 3:
|
| 59 |
+
return a.mean(axis=-1)
|
| 60 |
+
raise ValueError(f"unexpected kappa shape {a.shape}")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _finite(value, nonnegative=False):
|
| 64 |
+
try:
|
| 65 |
+
v = np.asarray(value, dtype=float)
|
| 66 |
+
except (TypeError, ValueError):
|
| 67 |
+
return None
|
| 68 |
+
if v.size == 0 or not np.all(np.isfinite(v)) or (nonnegative and np.any(v < 0)):
|
| 69 |
+
return None
|
| 70 |
+
return v
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def srme_one(pred: dict | None, ref: dict) -> tuple[float, float, bool]:
|
| 74 |
+
"""(SRME, SRD, censored) for one material, following matbench_discovery/metrics/phonons.py."""
|
| 75 |
+
true_total = float(np.ravel(ref["kappa_tot_avg"])[0])
|
| 76 |
+
true_mode = np.asarray(ref["mode_kappa_tot_avg"], dtype=float)
|
| 77 |
+
if not ok(pred):
|
| 78 |
+
return KAPPA_ERROR_MAX, -KAPPA_ERROR_MAX, True
|
| 79 |
+
censored = bool(pred.get("has_imag_ph_modes"))
|
| 80 |
+
expected_spg = ref.get("init_spg_num")
|
| 81 |
+
if not censored and pred.get("final_spg_num") and expected_spg:
|
| 82 |
+
censored = pred["final_spg_num"] != expected_spg
|
| 83 |
+
total = _finite(kappa_avg(pred["kappa_tot_rta"]) if pred.get("kappa_tot_rta") is not None else None, True)
|
| 84 |
+
srd = -KAPPA_ERROR_MAX
|
| 85 |
+
if total is not None and total.size == 1:
|
| 86 |
+
t = float(total.ravel()[0])
|
| 87 |
+
srd = 0.0 if t + true_total == 0 else KAPPA_ERROR_MAX * (t - true_total) / (t + true_total)
|
| 88 |
+
if censored or total is None or total.size != 1:
|
| 89 |
+
return KAPPA_ERROR_MAX, srd, True
|
| 90 |
+
mode = _finite(kappa_avg(pred["mode_kappa_tot_rta"]) if pred.get("mode_kappa_tot_rta") is not None else None)
|
| 91 |
+
# Predictions are produced in the process that imports the untrusted calculator.
|
| 92 |
+
# The quadrature normalizer belongs to the pinned reference, never that process.
|
| 93 |
+
weights = _finite(ref.get("weights"), True)
|
| 94 |
+
if mode is None or weights is None or weights.sum() <= 0 or mode.shape != true_mode.shape:
|
| 95 |
+
return KAPPA_ERROR_MAX, srd, True
|
| 96 |
+
micro = np.abs(mode - true_mode).sum(axis=tuple(range(1, mode.ndim))) / weights.sum()
|
| 97 |
+
denom = np.atleast_1d(total) + np.atleast_1d(true_total)
|
| 98 |
+
score = float(np.ravel(np.where(denom == 0, np.where(micro == 0, 0, KAPPA_ERROR_MAX),
|
| 99 |
+
KAPPA_ERROR_MAX * micro / denom))[0])
|
| 100 |
+
if not np.isfinite(score) or not 0 <= score <= KAPPA_ERROR_MAX:
|
| 101 |
+
return KAPPA_ERROR_MAX, srd, True
|
| 102 |
+
return score, srd, False
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def score_kappa(pred, root):
|
| 106 |
+
ref = {r["material_id"]: r for r in load(root / "references.json.gz")}
|
| 107 |
+
rows = {m: srme_one(pred.get(m), r) for m, r in sorted(ref.items())}
|
| 108 |
+
srme = np.array([r[0] for r in rows.values()]); srd = np.array([r[1] for r in rows.values()])
|
| 109 |
+
return {"items": len(rows), "kappa_SRME": float(srme.mean()), "kappa_SRE": float(np.abs(srd).mean()),
|
| 110 |
+
"kappa_SRD": float(srd.mean()), "censored_or_failed": int(sum(r[2] for r in rows.values()))}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ------------------------------------------------------------------------------------------ others
|
| 114 |
+
def score_mof(pred, root):
|
| 115 |
+
ref = {r["id"]: float(r["B0_GPa"]) for r in load(root / "references.json")}
|
| 116 |
+
err, failed = [], 0
|
| 117 |
+
for k, y in sorted(ref.items()):
|
| 118 |
+
p = pred.get(k)
|
| 119 |
+
b = p.get("B_GPa") if ok(p) else None
|
| 120 |
+
if b is None or not np.isfinite(b):
|
| 121 |
+
failed += 1; err.append(MOF_CAP)
|
| 122 |
+
else:
|
| 123 |
+
err.append(min(abs(b - y) / abs(y), MOF_CAP))
|
| 124 |
+
return {"items": len(ref), "bulk_modulus_MAPE_pct": float(100 * np.mean(err)), "failed": failed}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def score_amorphous(pred, root):
|
| 128 |
+
refs = load(root / "references.json.gz")
|
| 129 |
+
systems = sorted({r["system"] for r in refs})
|
| 130 |
+
out, failed = {"items": len(refs)}, 0
|
| 131 |
+
for s in systems:
|
| 132 |
+
rs = [r for r in refs if r["system"] == s]
|
| 133 |
+
er = np.array([r["energy_per_atom"] for r in rs])
|
| 134 |
+
d, fr, fp = [], [], []
|
| 135 |
+
for k, r in enumerate(rs):
|
| 136 |
+
p = pred.get(r["id"])
|
| 137 |
+
f_ref = np.asarray(r["forces"], dtype=float)
|
| 138 |
+
if ok(p) and np.isfinite(p["energy_per_atom"]) and np.shape(p["forces"]) == f_ref.shape \
|
| 139 |
+
and np.isfinite(p["forces"]).all():
|
| 140 |
+
d.append(p["energy_per_atom"] - r["energy_per_atom"]); fp.append(np.asarray(p["forces"], dtype=float))
|
| 141 |
+
else: # about twice the trivial predictor's error, so failing never helps
|
| 142 |
+
failed += 1; d.append((1 if k % 2 == 0 else -1) * 2 * er.std()); fp.append(-f_ref)
|
| 143 |
+
fr.append(f_ref)
|
| 144 |
+
d = np.array(d)
|
| 145 |
+
d = d - d.mean()
|
| 146 |
+
fr, fp = np.concatenate(fr), np.concatenate(fp)
|
| 147 |
+
out[f"{s}_energy_RelRMSE_pct"] = float(100 * np.sqrt((d ** 2).mean()) / er.std())
|
| 148 |
+
out[f"{s}_force_RelRMSE_pct"] = float(100 * np.sqrt(((fp - fr) ** 2).mean()) / fr.std())
|
| 149 |
+
out["energy_RelRMSE_pct_mean"] = float(np.mean([out[f"{s}_energy_RelRMSE_pct"] for s in systems]))
|
| 150 |
+
out["force_RelRMSE_pct_mean"] = float(np.mean([out[f"{s}_force_RelRMSE_pct"] for s in systems]))
|
| 151 |
+
out["failed"] = failed
|
| 152 |
+
return out
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def score_cleavage(pred, root):
|
| 156 |
+
ref = {r["id"]: float(r["cleavage_energy"]) for r in load(root / "references.json")}
|
| 157 |
+
y = np.array(list(ref.values()))
|
| 158 |
+
good = np.array([ok(pred.get(k)) and np.isfinite(pred[k]["cleavage_energy"]) for k in ref])
|
| 159 |
+
p = np.array([pred[k]["cleavage_energy"] if g else np.nan for k, g in zip(ref, good)])
|
| 160 |
+
err = np.where(good, np.minimum(np.abs(p - y), 2 * np.abs(y)), 2 * np.abs(y))
|
| 161 |
+
return {"items": len(ref), "cleavage_relMAE_pct": float(100 * err.mean() / np.abs(y).mean()),
|
| 162 |
+
"cleavage_MAE_eV_A2": float(err.mean()), "cleavage_signed_eV_A2": float((p - y)[good].mean()) if good.any() else None,
|
| 163 |
+
"failed": int((~good).sum())}
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def score_neb(pred, root):
|
| 167 |
+
ref = {r["id"]: float(r["barrier_eV"]) for r in load(root / "references.json")}
|
| 168 |
+
y = np.array(list(ref.values()))
|
| 169 |
+
good = np.array([ok(pred.get(k)) and np.isfinite(pred[k]["barrier_eV"]) for k in ref])
|
| 170 |
+
p = np.array([pred[k]["barrier_eV"] if g else np.nan for k, g in zip(ref, good)])
|
| 171 |
+
err = np.where(good, np.minimum(np.abs(p - y), NEB_CAP_EV), NEB_CAP_EV)
|
| 172 |
+
conv = np.array([g and bool(pred[k]["converged"]) for k, g in zip(ref, good)])
|
| 173 |
+
return {"items": len(ref), "barrier_MAE_eV": float(err.mean()),
|
| 174 |
+
"barrier_MAE_converged_eV": float(np.abs(p - y)[conv].mean()) if conv.any() else None,
|
| 175 |
+
"converged_frac": float(conv.mean()), "failed": int(len(ref) - sum(good))}
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
SCORERS = {"kappa": score_kappa, "mof": score_mof, "amorphous": score_amorphous,
|
| 179 |
+
"cleavage": score_cleavage, "neb": score_neb}
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def score(suite: str, run: Path, inputs: Path, references: Path) -> dict:
|
| 183 |
+
info = json.loads((run / "run.json").read_text())
|
| 184 |
+
import hashlib
|
| 185 |
+
if info.get("inputs_manifest_sha256") != hashlib.sha256((inputs / "manifest.json").read_bytes()).hexdigest():
|
| 186 |
+
raise SystemExit(f"{suite}: run was made on a different split")
|
| 187 |
+
return {"suite": suite, **SCORERS[suite](predictions(run), references), "complete": info["complete"]}
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def main():
|
| 191 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 192 |
+
ap.add_argument("--suite", choices=sorted(SCORERS), required=True)
|
| 193 |
+
ap.add_argument("--run", type=Path, required=True)
|
| 194 |
+
ap.add_argument("--inputs", type=Path, required=True)
|
| 195 |
+
ap.add_argument("--references", type=Path, required=True)
|
| 196 |
+
a = ap.parse_args()
|
| 197 |
+
print(json.dumps(score(a.suite, a.run, a.inputs, a.references), indent=1))
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if __name__ == "__main__":
|
| 201 |
+
main()
|
reproduction/files/08/08b0e3ae8a6e54b006cf60ffe74c63de172d0fa89714ff77df4f93866b1d63c1/grader.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Trusted scorer. Reads sealed predictions + private responses; never executes submission code.
|
| 3 |
+
|
| 4 |
+
Writes to --output:
|
| 5 |
+
reward.json {"reward": mean over test contexts of the FINAL-subset score, ...}
|
| 6 |
+
report.json full per-context / per-subset / per-stratum report (operator-facing)
|
| 7 |
+
agent_feedback.json leaderboard-subset scores only (what the runner may return to the agent)
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import json
|
| 14 |
+
import time
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from cellscore import cell_eval_version, score_context, sha256
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def harbor_reward(values):
|
| 23 |
+
"""Harbor parses reward.json as a flat object of finite numbers; strings, None and nested details
|
| 24 |
+
belong in report.json / status.json."""
|
| 25 |
+
import math as _math
|
| 26 |
+
return {k: v for k, v in values.items() if isinstance(v, (int, float)) and _math.isfinite(v)}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main() -> None:
|
| 30 |
+
ap = argparse.ArgumentParser()
|
| 31 |
+
ap.add_argument("--sealed", required=True, type=lambda x: Path(x).resolve())
|
| 32 |
+
ap.add_argument("--benchmark", required=True, type=lambda x: Path(x).resolve())
|
| 33 |
+
ap.add_argument("--private", required=True, type=lambda x: Path(x).resolve())
|
| 34 |
+
ap.add_argument("--output", required=True, type=lambda x: Path(x).resolve())
|
| 35 |
+
ap.add_argument("--wait-seconds", type=int, default=14400)
|
| 36 |
+
ap.add_argument("--threads", type=int)
|
| 37 |
+
args = ap.parse_args()
|
| 38 |
+
ready = args.sealed.parent / "READY"
|
| 39 |
+
deadline = time.monotonic() + args.wait_seconds
|
| 40 |
+
while not ready.is_file():
|
| 41 |
+
if time.monotonic() >= deadline:
|
| 42 |
+
raise TimeoutError("prediction snapshot was not published")
|
| 43 |
+
time.sleep(2)
|
| 44 |
+
snapshot_path = args.sealed / "snapshot.json"
|
| 45 |
+
if ready.read_text().strip() != sha256(snapshot_path):
|
| 46 |
+
raise ValueError("snapshot ready hash mismatch")
|
| 47 |
+
snapshot = json.loads(snapshot_path.read_text())
|
| 48 |
+
contexts = sorted(p.name for p in args.private.iterdir() if (p / "responses.h5ad").exists())
|
| 49 |
+
report = {"schema": "virtual-cell-zeroshot-report/v1", "cell_eval_version": cell_eval_version(),
|
| 50 |
+
"evaluation_mode": "isolated_model_replay", "contexts": {}}
|
| 51 |
+
finals, boards = [], []
|
| 52 |
+
scratch = args.output / "scratch"
|
| 53 |
+
for ctx in contexts:
|
| 54 |
+
priv = args.private / ctx
|
| 55 |
+
pm = json.loads((priv / "manifest.json").read_text())
|
| 56 |
+
if pm["responses_sha256"] != sha256(priv / "responses.h5ad"):
|
| 57 |
+
raise ValueError(f"{ctx}: private response checksum mismatch")
|
| 58 |
+
public = args.benchmark / ctx / "public"
|
| 59 |
+
entry = snapshot["contexts"].get(ctx)
|
| 60 |
+
if pm["requests_sha256"] != sha256(public / "requests.jsonl") or pm["public_basal_sha256"] != sha256(public / "basal.h5ad"):
|
| 61 |
+
raise ValueError(f"{ctx}: public inputs differ from the private manifest")
|
| 62 |
+
if not entry or entry.get("failed"):
|
| 63 |
+
report["contexts"][ctx] = {"status": "failed", "error": (entry or {}).get("error", "missing"),
|
| 64 |
+
"tier": pm["tier"], "final_score": 0.0, "leaderboard_score": 0.0}
|
| 65 |
+
finals.append(0.0); boards.append(0.0)
|
| 66 |
+
continue
|
| 67 |
+
pred = args.sealed / ctx / "predictions.h5ad"
|
| 68 |
+
if entry["predictions_sha256"] != sha256(pred) or entry["requests_sha256"] != sha256(public / "requests.jsonl") \
|
| 69 |
+
or entry["basal_sha256"] != sha256(public / "basal.h5ad"):
|
| 70 |
+
raise ValueError(f"{ctx}: sealed snapshot provenance mismatch")
|
| 71 |
+
subsets = {"leaderboard": [r["request_id"] for r in pm["requests"] if r["subset"] == "leaderboard"],
|
| 72 |
+
"final": [r["request_id"] for r in pm["requests"] if r["subset"] == "final"]}
|
| 73 |
+
groups = {"stratum": {r["request_id"]: r["stratum"] for r in pm["requests"]},
|
| 74 |
+
"target_seen": {r["request_id"]: ("withheld" if r["withheld"] else ("seen" if r["seen_in_training"] else "unseen"))
|
| 75 |
+
for r in pm["requests"]},
|
| 76 |
+
"final_by_stratum": {r["request_id"]: r["stratum"] for r in pm["requests"] if r["subset"] == "final"}}
|
| 77 |
+
baseline_dir = priv / "noeffect" if (priv / "noeffect").exists() else None
|
| 78 |
+
res = score_context(pred, priv / "basal.h5ad", priv / "responses.h5ad", public / "requests.jsonl",
|
| 79 |
+
scratch / ctx, subsets=subsets, groups=groups, threads=args.threads, baseline_dir=baseline_dir)
|
| 80 |
+
final = res["subsets"]["final"]["score"]; board = res["subsets"]["leaderboard"]["score"]
|
| 81 |
+
report["contexts"][ctx] = {"status": "ok", "tier": pm["tier"], "chemistry": pm["chemistry"],
|
| 82 |
+
"final_score": final, "leaderboard_score": board, "all_score": res["all"]["score"],
|
| 83 |
+
"final": res["subsets"]["final"], "leaderboard": res["subsets"]["leaderboard"],
|
| 84 |
+
"all": res["all"], "groups": res["groups"], "inference_seconds": entry.get("seconds")}
|
| 85 |
+
finals.append(final); boards.append(board)
|
| 86 |
+
reward = float(np.mean(finals)) if finals else 0.0
|
| 87 |
+
report["reward"] = reward
|
| 88 |
+
report["leaderboard_reward"] = float(np.mean(boards)) if boards else 0.0
|
| 89 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 90 |
+
(args.output / "report.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
|
| 91 |
+
(args.output / "agent_feedback.json").write_text(json.dumps({
|
| 92 |
+
"schema": "virtual-cell-zeroshot-feedback/v1", "cell_eval_version": report["cell_eval_version"],
|
| 93 |
+
"leaderboard_reward": report["leaderboard_reward"],
|
| 94 |
+
"contexts": {c: {"status": v["status"], "tier": v["tier"], "leaderboard_score": v["leaderboard_score"],
|
| 95 |
+
"leaderboard": v.get("leaderboard"), "error": v.get("error")} for c, v in report["contexts"].items()},
|
| 96 |
+
}, indent=2, sort_keys=True) + "\n")
|
| 97 |
+
(args.output / "reward.json").write_text(json.dumps(harbor_reward({
|
| 98 |
+
"reward": reward, "leaderboard_reward": report["leaderboard_reward"],
|
| 99 |
+
**{f"{c}_final": v["final_score"] for c, v in report["contexts"].items()},
|
| 100 |
+
**{f"{c}_leaderboard": v["leaderboard_score"] for c, v in report["contexts"].items()},
|
| 101 |
+
}), indent=2, sort_keys=True) + "\n")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
main()
|
reproduction/files/0b/0b18d04b2b1f948d7d230ff451c93a205521037a985a856a979ba38d3c3d47ad/common.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small, explicit interchange format. No model code is imported by the scorer."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from ase import Atoms
|
| 11 |
+
|
| 12 |
+
PROTOCOL = "atomistic-materials-v0.1"
|
| 13 |
+
PHONON_FIELDS = {
|
| 14 |
+
"max_freq": "K",
|
| 15 |
+
"avg_freq": "K",
|
| 16 |
+
"entropy": "J/(mol primitive cell K)",
|
| 17 |
+
"heat_capacity": "J/(mol primitive cell K)",
|
| 18 |
+
"free_energy": "kJ/mol primitive cell",
|
| 19 |
+
}
|
| 20 |
+
ELASTIC_FIELDS = {"bulk_modulus_vrh": "GPa", "shear_modulus_vrh": "GPa"}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def digest(path: Path, algorithm="sha256") -> str:
|
| 24 |
+
"""File digest; a directory (submission) digests its sorted relative paths and file digests."""
|
| 25 |
+
h = hashlib.new(algorithm)
|
| 26 |
+
if path.is_dir():
|
| 27 |
+
for item in sorted(p for p in path.rglob("*") if p.is_file() and "__pycache__" not in p.parts):
|
| 28 |
+
h.update(f"{item.relative_to(path).as_posix()}\0{digest(item, algorithm)}\n".encode())
|
| 29 |
+
return h.hexdigest()
|
| 30 |
+
with path.open("rb") as stream:
|
| 31 |
+
for block in iter(lambda: stream.read(1 << 20), b""):
|
| 32 |
+
h.update(block)
|
| 33 |
+
return h.hexdigest()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def with_oom_retry(run, attempts=4, wait=20.0):
|
| 37 |
+
"""run() again after a CUDA out-of-memory error, which other jobs on a shared GPU can cause.
|
| 38 |
+
|
| 39 |
+
The verifier runs every suite at once, so a GPU can fill up briefly; that is not the model's
|
| 40 |
+
failure. Any other error, or a fourth OOM, propagates and the case is recorded as failed."""
|
| 41 |
+
import gc
|
| 42 |
+
import time
|
| 43 |
+
for attempt in range(attempts):
|
| 44 |
+
try:
|
| 45 |
+
return run()
|
| 46 |
+
except Exception as error:
|
| 47 |
+
if type(error).__name__ != "OutOfMemoryError" or attempt == attempts - 1:
|
| 48 |
+
raise
|
| 49 |
+
gc.collect()
|
| 50 |
+
import torch
|
| 51 |
+
torch.cuda.empty_cache()
|
| 52 |
+
time.sleep(wait * (attempt + 1))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def write_json(path: Path, value) -> None:
|
| 56 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 57 |
+
path.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def write_rows(path: Path, rows) -> None:
|
| 61 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 62 |
+
with path.open("w") as stream:
|
| 63 |
+
for row in rows:
|
| 64 |
+
stream.write(json.dumps(row, allow_nan=False) + "\n")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def read_rows(path: Path) -> list[dict]:
|
| 68 |
+
with path.open() as stream:
|
| 69 |
+
return [json.loads(line) for line in stream if line.strip()]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def indexed(rows: list[dict]) -> dict[str, dict]:
|
| 73 |
+
result = {}
|
| 74 |
+
for row in rows:
|
| 75 |
+
key = row["id"]
|
| 76 |
+
if key in result:
|
| 77 |
+
raise ValueError(f"Duplicate ID: {key}")
|
| 78 |
+
result[key] = row
|
| 79 |
+
if not result:
|
| 80 |
+
raise ValueError("Empty evaluation")
|
| 81 |
+
return result
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def encode_atoms(atoms: Atoms) -> dict:
|
| 85 |
+
# Whitelist geometry: never serialize calc, info, site properties, or arrays
|
| 86 |
+
# such as DFT magnetic moments/charges/forces.
|
| 87 |
+
return {
|
| 88 |
+
"numbers": atoms.numbers.tolist(),
|
| 89 |
+
"positions": atoms.positions.tolist(),
|
| 90 |
+
"cell": atoms.cell.array.tolist(),
|
| 91 |
+
"pbc": atoms.pbc.tolist(),
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def decode_atoms(data: dict) -> Atoms:
|
| 96 |
+
required = {"numbers", "positions", "cell", "pbc"}
|
| 97 |
+
if set(data) != required:
|
| 98 |
+
raise ValueError(f"Unexpected atomic fields: {set(data) ^ required}")
|
| 99 |
+
atoms = Atoms(**data)
|
| 100 |
+
if not len(atoms) or not np.isfinite(atoms.positions).all():
|
| 101 |
+
raise ValueError("Invalid atomic coordinates")
|
| 102 |
+
if not np.isfinite(atoms.cell).all() or atoms.get_volume() <= 0:
|
| 103 |
+
raise ValueError("Invalid unit cell")
|
| 104 |
+
if not atoms.pbc.all():
|
| 105 |
+
raise ValueError("Core tasks require fully periodic crystals")
|
| 106 |
+
return atoms
|
reproduction/files/0c/0c445f2319b2c3aca9fa1587339f781fbc5000c4c27ee1b478e72b9d9a27538c/validate_fly_verifier.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Credential-free real-GPU canary for the adapted Pathfinder prediction boundary."""
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
from fly_boundary import enter,cleanup
|
| 9 |
+
|
| 10 |
+
root=Path('/workspace/research/run');root.mkdir(parents=True)
|
| 11 |
+
probe='''import os,socket,torch,json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
assert os.getuid()==10001
|
| 14 |
+
assert not os.access('/private',os.X_OK)
|
| 15 |
+
try:Path('/private/suite/label-canary').read_bytes()
|
| 16 |
+
except PermissionError:pass
|
| 17 |
+
else:raise AssertionError('private label read succeeded')
|
| 18 |
+
try:Path('/operator/.untrusted-write').write_text('bad')
|
| 19 |
+
except PermissionError:pass
|
| 20 |
+
else:raise AssertionError('source write succeeded')
|
| 21 |
+
for family in (socket.AF_INET,socket.AF_INET6):
|
| 22 |
+
try:s=socket.socket(family,socket.SOCK_STREAM)
|
| 23 |
+
except PermissionError:pass
|
| 24 |
+
else:s.close();raise AssertionError('external socket succeeded')
|
| 25 |
+
assert torch.cuda.device_count()==8
|
| 26 |
+
assert all('H100' in torch.cuda.get_device_name(i) for i in range(8))
|
| 27 |
+
assert all(float((torch.ones(4,device=f'cuda:{i}')*2).sum())==8 for i in range(8))
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
Path('rename-a').mkdir();Path('rename-b').mkdir();Path('rename-a/x').write_text('ok')
|
| 30 |
+
Path('rename-a/x').rename('rename-b/x')
|
| 31 |
+
print('FLY_BOUNDARY_GPU_AND_PRIVATE_LABEL_CHECKS_PASSED')
|
| 32 |
+
'''
|
| 33 |
+
try:
|
| 34 |
+
result=subprocess.run([sys.executable,'-c',probe],cwd=root,preexec_fn=lambda:enter(root),
|
| 35 |
+
capture_output=True,text=True,timeout=180,check=True)
|
| 36 |
+
print(result.stdout)
|
| 37 |
+
finally:cleanup()
|
| 38 |
+
Path('/logs/verifier/validation.json').write_text(json.dumps({'passed':True,'valid_benchmark_result':False,
|
| 39 |
+
'gpus':8,'private_labels_denied':True,'source_write_denied':True,'network_denied':True,
|
| 40 |
+
'cross_directory_rename_works':True,'native_numerical_pipeline_unchanged':True})+'\n')
|
| 41 |
+
Path('/logs/verifier/reward.json').write_text('{"canary_passed":1}\n')
|
reproduction/files/0d/0d0cbb759d4e8333988e9bdfdff8a8bccce42cff7b73d1d7ed3b23e0e2d584b5/test_release_contract.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Executable release, grading, corruption, and label-isolation contracts."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import importlib.util
|
| 4 |
+
import io
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sys
|
| 8 |
+
import tarfile
|
| 9 |
+
import zipfile
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
TASK = Path(__file__).resolve().parents[1]
|
| 14 |
+
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
|
| 15 |
+
sys.path.insert(0, str(PROJECT))
|
| 16 |
+
from qecbench.data import SCHEMA, DevelopmentDataset, load_condition, load_manifest, read_npz, sha256, write_json
|
| 17 |
+
from qecbench.scoring import InvalidPrediction, normalize, probabilities, score
|
| 18 |
+
from qecbench.stage_validation import stage
|
| 19 |
+
from baselines.alphaqubit_artifact import EXPECTED_GROUPS
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def module(name: str, path: Path):
|
| 23 |
+
spec = importlib.util.spec_from_file_location(name, path)
|
| 24 |
+
result = importlib.util.module_from_spec(spec)
|
| 25 |
+
spec.loader.exec_module(result)
|
| 26 |
+
return result
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
materializer = module("qec_materializer", TASK / "environment/data/materialize.py")
|
| 30 |
+
supervisor = module("qec_supervisor", TASK / "tests/main_verifier.py")
|
| 31 |
+
grader = module("qec_grader", TASK / "tests/grader.py")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.fixture
|
| 35 |
+
def suite(tmp_path: Path):
|
| 36 |
+
inputs, labels, predictions = (tmp_path / name for name in ("inputs", "labels", "predictions"))
|
| 37 |
+
for folder in (inputs, labels, predictions):
|
| 38 |
+
folder.mkdir()
|
| 39 |
+
rows, targets = [], []
|
| 40 |
+
for group in EXPECTED_GROUPS:
|
| 41 |
+
distance, basis = int(group[1]), group[4]
|
| 42 |
+
center = group.split("center_")[1]
|
| 43 |
+
for rounds in range(1, 26, 2):
|
| 44 |
+
name = f"surface_code_b{basis}_d{distance}_r{rounds:02}_center_{center}"
|
| 45 |
+
folder = inputs / name
|
| 46 |
+
folder.mkdir()
|
| 47 |
+
ids = np.array([991, 27, 64, 118], dtype=np.uint64)
|
| 48 |
+
detectors = np.zeros((4, (rounds * (distance**2 - 1) + 7) // 8), dtype=np.uint8)
|
| 49 |
+
np.savez(folder / "arrays.npz", sample_ids=ids, detectors=detectors)
|
| 50 |
+
(folder / "circuit_ideal.stim").write_text("fixture circuit\n")
|
| 51 |
+
target = np.array([0, 0, 0, 1], dtype=np.uint8)
|
| 52 |
+
np.savez(labels / f"{name}.npz", sample_ids=ids, labels=target)
|
| 53 |
+
np.savez(predictions / f"{name}.npz", sample_ids=ids[::-1], probabilities=np.array([1, 0, 0, 0], dtype=np.float32))
|
| 54 |
+
rows.append({"name": name, "group": group, "distance": distance, "basis": basis, "rounds": rounds,
|
| 55 |
+
"shots": 4, "num_detectors": rounds * (distance**2 - 1), "arrays": f"{name}/arrays.npz",
|
| 56 |
+
"arrays_sha256": sha256(folder / "arrays.npz"), "circuit": f"{name}/circuit_ideal.stim",
|
| 57 |
+
"circuit_sha256": sha256(folder / "circuit_ideal.stim")})
|
| 58 |
+
targets.append({"name": name, "arrays": f"{name}.npz", "arrays_sha256": sha256(labels / f"{name}.npz")})
|
| 59 |
+
write_json(inputs / "manifest.json", {"schema": SCHEMA, "split": "test", "conditions": rows})
|
| 60 |
+
write_json(labels / "manifest.json", {"schema": "surface-code-decoding-labels/v1", "input_manifest_sha256": sha256(inputs / "manifest.json"), "conditions": targets})
|
| 61 |
+
return inputs, labels, predictions, rows
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_frozen_normalization_anchors():
|
| 65 |
+
config = json.loads((PROJECT / "score_config.json").read_text())
|
| 66 |
+
assert normalize(config["lower_bound"], config)["score"] == 0
|
| 67 |
+
assert normalize(config["upper_bound"], config)["score"] == 1
|
| 68 |
+
assert normalize(1, config)["score_unclipped"] > 1
|
| 69 |
+
assert normalize(1, config)["score"] == normalize(1, config)["score_unclipped"] # no upper clip (v1.1.0)
|
| 70 |
+
assert normalize(0, config)["score_unclipped"] < 0
|
| 71 |
+
assert normalize(0, config)["score"] == 0
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_full_suite_reordering_and_perfect_score(suite):
|
| 75 |
+
inputs, labels, predictions, _ = suite
|
| 76 |
+
result = score(inputs, predictions, labels, PROJECT / "score_config.json")
|
| 77 |
+
assert result["shots"] == 520
|
| 78 |
+
assert result["performance"] == 1
|
| 79 |
+
assert result["score"] == result["score_unclipped"] > 1 # perfect decoding is above the TN anchor; no upper clip
|
| 80 |
+
assert result["failure_by_distance"] == {"d3": 0, "d5": 0}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def test_missing_prediction_is_invalid_not_infrastructure(suite):
|
| 84 |
+
inputs, labels, predictions, rows = suite
|
| 85 |
+
(predictions / f"{rows[0]['name']}.npz").unlink()
|
| 86 |
+
with pytest.raises(InvalidPrediction):
|
| 87 |
+
score(inputs, predictions, labels, PROJECT / "score_config.json")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@pytest.mark.parametrize("failure", ["nan", "float64", "duplicate", "extra-id", "zip-garbage", "encrypted", "compression"])
|
| 91 |
+
def test_bad_outputs_fail_closed(suite, failure):
|
| 92 |
+
inputs, _, predictions, rows = suite
|
| 93 |
+
row = rows[0]
|
| 94 |
+
ids = load_condition(inputs, row)["sample_ids"]
|
| 95 |
+
values = np.zeros(4, dtype=np.float32)
|
| 96 |
+
if failure == "nan":
|
| 97 |
+
values[0] = np.nan
|
| 98 |
+
elif failure == "float64":
|
| 99 |
+
values = values.astype(np.float64)
|
| 100 |
+
elif failure == "duplicate":
|
| 101 |
+
ids[1] = ids[0]
|
| 102 |
+
elif failure == "extra-id":
|
| 103 |
+
ids[1] += 1
|
| 104 |
+
path = predictions / f"{row['name']}.npz"
|
| 105 |
+
np.savez(path, sample_ids=ids, probabilities=values)
|
| 106 |
+
if failure == "zip-garbage":
|
| 107 |
+
path.write_bytes(b"not-a-zip")
|
| 108 |
+
if failure in ("encrypted", "compression"):
|
| 109 |
+
payload = bytearray(path.read_bytes())
|
| 110 |
+
for marker, offset in ((b"PK\x03\x04", 6), (b"PK\x01\x02", 8)):
|
| 111 |
+
cursor = 0
|
| 112 |
+
while (cursor := payload.find(marker, cursor)) >= 0:
|
| 113 |
+
payload[cursor + offset + (2 if failure == "compression" else 0)] = 99 if failure == "compression" else 1
|
| 114 |
+
cursor += 4
|
| 115 |
+
path.write_bytes(payload)
|
| 116 |
+
with pytest.raises(InvalidPrediction):
|
| 117 |
+
probabilities(predictions, row, load_condition(inputs, row)["sample_ids"])
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def test_trusted_label_corruption_is_infrastructure(suite):
|
| 121 |
+
inputs, labels, predictions, rows = suite
|
| 122 |
+
(labels / f"{rows[0]['name']}.npz").write_bytes(b"corrupt")
|
| 123 |
+
with pytest.raises(ValueError, match="Trusted label checksum"):
|
| 124 |
+
score(inputs, predictions, labels, PROJECT / "score_config.json")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def test_label_free_schema_and_development_split_guard(suite):
|
| 128 |
+
inputs, _, _, rows = suite
|
| 129 |
+
row = rows[0]
|
| 130 |
+
path = inputs / row["arrays"]
|
| 131 |
+
arrays = load_condition(inputs, row)
|
| 132 |
+
np.savez(path, **arrays, labels=np.zeros(4, dtype=np.uint8))
|
| 133 |
+
with pytest.raises(ValueError, match="Wrong array fields"):
|
| 134 |
+
load_condition(inputs, row)
|
| 135 |
+
with pytest.raises(ValueError, match="train/validation only"):
|
| 136 |
+
DevelopmentDataset(inputs, "test")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_symlink_prediction_rejected(suite, tmp_path):
|
| 140 |
+
inputs, _, predictions, rows = suite
|
| 141 |
+
row = rows[0]
|
| 142 |
+
path = predictions / f"{row['name']}.npz"
|
| 143 |
+
other = tmp_path / "outside.npz"
|
| 144 |
+
path.replace(other)
|
| 145 |
+
path.symlink_to(other)
|
| 146 |
+
with pytest.raises(InvalidPrediction):
|
| 147 |
+
probabilities(predictions, row, load_condition(inputs, row)["sample_ids"])
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def test_npz_bomb_and_forged_shape_rejected(tmp_path):
|
| 151 |
+
path = tmp_path / "bomb.npz"
|
| 152 |
+
np.savez_compressed(path, probabilities=np.zeros(100000, dtype=np.float32))
|
| 153 |
+
with pytest.raises(ValueError, match="expanded content"):
|
| 154 |
+
read_npz(path, 48)
|
| 155 |
+
stream = io.BytesIO()
|
| 156 |
+
np.lib.format.write_array_header_1_0(stream, {"descr": "<f4", "fortran_order": False, "shape": (2**60,)})
|
| 157 |
+
with zipfile.ZipFile(path, "w") as output:
|
| 158 |
+
output.writestr("probabilities.npy", stream.getvalue())
|
| 159 |
+
with pytest.raises(ValueError, match="shape disagrees"):
|
| 160 |
+
read_npz(path, 48)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def test_materializer_rejects_unsafe_tar_before_write(tmp_path):
|
| 164 |
+
archive = tmp_path / "unsafe.tar.gz"
|
| 165 |
+
with tarfile.open(archive, "w:gz") as output:
|
| 166 |
+
item = tarfile.TarInfo("development/../../escaped")
|
| 167 |
+
item.size = 1
|
| 168 |
+
output.addfile(item, io.BytesIO(b"x"))
|
| 169 |
+
with pytest.raises(ValueError, match="Unsafe archive"):
|
| 170 |
+
materializer.extract(archive, tmp_path / "dest", "development", 10)
|
| 171 |
+
assert not (tmp_path / "escaped").exists()
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def test_labeled_validation_staging(suite, tmp_path):
|
| 175 |
+
inputs, labels, _, rows = suite
|
| 176 |
+
manifest = json.loads((inputs / "manifest.json").read_text())
|
| 177 |
+
manifest["split"] = "validation"
|
| 178 |
+
for row in rows:
|
| 179 |
+
path = inputs / row["arrays"]
|
| 180 |
+
arrays = load_condition(inputs, row)
|
| 181 |
+
np.savez(path, **arrays, labels=np.zeros(4, dtype=np.uint8))
|
| 182 |
+
row["arrays_sha256"] = sha256(path)
|
| 183 |
+
manifest["conditions"] = rows
|
| 184 |
+
write_json(inputs / "manifest.json", manifest)
|
| 185 |
+
with pytest.raises(ValueError, match="physically label-free"):
|
| 186 |
+
load_manifest(inputs)
|
| 187 |
+
output = tmp_path / "stage"
|
| 188 |
+
stage(inputs, output, limit=3, seed=1, group=rows[0]["group"])
|
| 189 |
+
staged = load_manifest(output)
|
| 190 |
+
assert len(staged["conditions"]) == 13
|
| 191 |
+
assert {row["shots"] for row in staged["conditions"]} == {3}
|
| 192 |
+
assert set(load_condition(output, staged["conditions"][0])) == {"sample_ids", "detectors"}
|
| 193 |
+
predictions = tmp_path / "subset-predictions"
|
| 194 |
+
predictions.mkdir()
|
| 195 |
+
for row in staged["conditions"]:
|
| 196 |
+
arrays = load_condition(output, row)
|
| 197 |
+
np.savez(predictions / f"{row['name']}.npz", sample_ids=arrays["sample_ids"],
|
| 198 |
+
probabilities=np.zeros(row["shots"], dtype=np.float32))
|
| 199 |
+
report = score(output, predictions, inputs, PROJECT / "score_config.json", require_full_suite=False, validation=True)
|
| 200 |
+
assert report["shots"] == 39 and report["performance"] == 1
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def test_root_grader_isolation_topology():
|
| 204 |
+
import tomllib
|
| 205 |
+
import yaml
|
| 206 |
+
compose = yaml.safe_load((TASK / "tests/docker-compose.yaml").read_text())
|
| 207 |
+
for service in compose["services"].values():
|
| 208 |
+
assert service["network_mode"] == "none"
|
| 209 |
+
main = compose["services"]["main"]
|
| 210 |
+
assert main["deploy"]["resources"]["reservations"]["devices"] == [
|
| 211 |
+
{"driver": "nvidia", "count": 1, "capabilities": ["gpu"]}
|
| 212 |
+
]
|
| 213 |
+
development = yaml.safe_load((TASK / "environment/docker-compose.yaml").read_text())
|
| 214 |
+
# A Compose network override prevents Harbor's model API allowlist sidecar
|
| 215 |
+
# from attaching; the runner must apply the default-deny task policy.
|
| 216 |
+
assert "network_mode" not in development["services"]["main"]
|
| 217 |
+
assert "networks" not in development["services"]["main"]
|
| 218 |
+
task = tomllib.loads((TASK / "task.toml").read_text())
|
| 219 |
+
assert task["environment"]["network_mode"] == "no-network"
|
| 220 |
+
assert task["verifier"]["environment"]["network_mode"] == "no-network"
|
| 221 |
+
local = yaml.safe_load((TASK / "tests/docker-compose.local.yaml").read_text())
|
| 222 |
+
assert "gpus" not in local["services"]["main"]
|
| 223 |
+
assert all(not isinstance(volume, dict) or volume["target"] != "/private" for volume in main["volumes"])
|
| 224 |
+
trusted = compose["services"]["grader"]
|
| 225 |
+
assert any(isinstance(volume, dict) and volume["target"] == "/private" and volume["read_only"] for volume in trusted["volumes"])
|
| 226 |
+
assert all(not isinstance(volume, dict) or volume["target"] != "/workspace/submission" for volume in trusted["volumes"])
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def test_infrastructure_failure_emits_no_reward(tmp_path):
|
| 230 |
+
sealed, out = tmp_path / "sealed", tmp_path / "results"
|
| 231 |
+
sealed.mkdir()
|
| 232 |
+
token = "a" * 32
|
| 233 |
+
grader.grade(sealed, tmp_path / "absent", tmp_path / "private", PROJECT / "score_config.json", out,
|
| 234 |
+
{"run_id": token, "snapshot_sha256": "0" * 64})
|
| 235 |
+
assert json.loads((out / token / "report.json").read_text())["status"] == "infrastructure_error"
|
| 236 |
+
assert not (out / token / "reward.json").exists()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def test_invalid_submission_has_zero_not_missing_reward(tmp_path):
|
| 240 |
+
supervisor.invalid(tmp_path, "invalid_submission", ValueError("fixture"))
|
| 241 |
+
assert json.loads((tmp_path / "reward.json").read_text()) == {"reward": 0.0}
|
| 242 |
+
assert json.loads((tmp_path / "report.json").read_text())["model_quality_measured"] is False
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def test_submission_manifest_nonobject_rejected(tmp_path):
|
| 246 |
+
for name in ("infer.sh", "README.md", "requirements.lock"):
|
| 247 |
+
(tmp_path / name).write_text("fixture")
|
| 248 |
+
(tmp_path / "model_manifest.json").write_text("[]")
|
| 249 |
+
with pytest.raises(ValueError, match="Unsupported submission manifest"):
|
| 250 |
+
supervisor.validate_submission(tmp_path)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@pytest.mark.parametrize("case", ["nested-inventory", "symlink-root", "fifo"])
|
| 254 |
+
def test_materializer_exact_existing_inventory(tmp_path, case):
|
| 255 |
+
root = tmp_path / "development"
|
| 256 |
+
root.mkdir()
|
| 257 |
+
write_json(root / "inventory.json", {"schema": "surface-code-decoding-inventory/v1", "files": {}})
|
| 258 |
+
materializer.verify_role(root)
|
| 259 |
+
if case == "nested-inventory":
|
| 260 |
+
(root / "unexpected").mkdir()
|
| 261 |
+
(root / "unexpected/inventory.json").write_text("undeclared")
|
| 262 |
+
elif case == "symlink-root":
|
| 263 |
+
link = tmp_path / "linked"
|
| 264 |
+
link.symlink_to(root, target_is_directory=True)
|
| 265 |
+
root = link
|
| 266 |
+
else:
|
| 267 |
+
import os
|
| 268 |
+
os.mkfifo(root / "special")
|
| 269 |
+
with pytest.raises(ValueError):
|
| 270 |
+
materializer.verify_role(root)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def test_invalid_prediction_does_not_hide_late_infrastructure_corruption(suite):
|
| 274 |
+
inputs, labels, predictions, rows = suite
|
| 275 |
+
(predictions / f"{rows[0]['name']}.npz").unlink()
|
| 276 |
+
(labels / f"{rows[-1]['name']}.npz").write_bytes(b"corrupt")
|
| 277 |
+
with pytest.raises(ValueError, match="Trusted label checksum"):
|
| 278 |
+
score(inputs, predictions, labels, PROJECT / "score_config.json")
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def test_primary_uses_equal_distance_group_duration_weights(suite):
|
| 282 |
+
inputs, labels, predictions, rows = suite
|
| 283 |
+
chosen = [next(row for row in rows if row["distance"] == distance) for distance in (3, 5)]
|
| 284 |
+
for row in chosen:
|
| 285 |
+
ids = load_condition(inputs, row)["sample_ids"]
|
| 286 |
+
with np.load(labels / f"{row['name']}.npz", allow_pickle=False) as truth:
|
| 287 |
+
wrong = 1 - truth["labels"]
|
| 288 |
+
np.savez(predictions / f"{row['name']}.npz", sample_ids=ids, probabilities=wrong.astype(np.float32))
|
| 289 |
+
report = score(inputs, predictions, labels, PROJECT / "score_config.json")
|
| 290 |
+
# One failed duration in one group per distance: d3 has eight groups; d5 two.
|
| 291 |
+
expected = 0.5 * (1 / (8 * 13) + 1 / (2 * 13))
|
| 292 |
+
assert report["balanced_logical_failure"] == pytest.approx(expected)
|
| 293 |
+
assert report["balanced_logical_failure"] != pytest.approx(2 / 130)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
@pytest.fixture
|
| 297 |
+
def reusable_materialization(tmp_path):
|
| 298 |
+
import argparse
|
| 299 |
+
source = tmp_path / "source"
|
| 300 |
+
role = source / "development"
|
| 301 |
+
role.mkdir(parents=True)
|
| 302 |
+
(role / "payload.bin").write_bytes(b"verified data")
|
| 303 |
+
write_json(role / "inventory.json", {"schema": "surface-code-decoding-inventory/v1", "files": {
|
| 304 |
+
"payload.bin": {"bytes": 13, "sha256": sha256(role / "payload.bin")}}})
|
| 305 |
+
archive_root = tmp_path / "archives"
|
| 306 |
+
archive_root.mkdir()
|
| 307 |
+
archive = archive_root / "development.tar.gz"
|
| 308 |
+
lock = tmp_path / "lock.json"
|
| 309 |
+
|
| 310 |
+
def publish():
|
| 311 |
+
with tarfile.open(archive, "w:gz") as tar:
|
| 312 |
+
for path in sorted(role.iterdir()):
|
| 313 |
+
# Avoid NSS lookups in gettarinfo on cluster hosts.
|
| 314 |
+
item = tarfile.TarInfo(f"development/{path.name}")
|
| 315 |
+
item.size = path.stat().st_size
|
| 316 |
+
with path.open("rb") as stream:
|
| 317 |
+
tar.addfile(item, stream)
|
| 318 |
+
write_json(lock, {"schema": "surface-code-decoding-hf-release/v1", "release": "fixture",
|
| 319 |
+
"artifacts": {"development": {"repo_id": "local/fixture", "revision": "0" * 40,
|
| 320 |
+
"filename": archive.name, "bytes": archive.stat().st_size, "sha256": sha256(archive),
|
| 321 |
+
"expanded_bytes": sum(path.stat().st_size for path in role.iterdir())}}})
|
| 322 |
+
|
| 323 |
+
publish()
|
| 324 |
+
args = argparse.Namespace(from_sources=False, lock=lock, output=tmp_path / "restored",
|
| 325 |
+
roles=["development"], archive_dir=archive_root, cache_dir=None)
|
| 326 |
+
materializer.run(args)
|
| 327 |
+
return args, role, publish
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def test_reuse_skips_payload_extraction(reusable_materialization, monkeypatch):
|
| 331 |
+
args, _, _ = reusable_materialization
|
| 332 |
+
|
| 333 |
+
def forbidden_extract(*args, **kwargs):
|
| 334 |
+
raise AssertionError("Reused roles must not extract a second payload tree")
|
| 335 |
+
|
| 336 |
+
monkeypatch.setattr(materializer, "extract", forbidden_extract)
|
| 337 |
+
monkeypatch.setattr(materializer.tempfile, "TemporaryDirectory", forbidden_extract)
|
| 338 |
+
assert materializer.run(args)["status"] == "verified"
|
| 339 |
+
assert (args.output / "development/payload.bin").read_bytes() == b"verified data"
|
| 340 |
+
assert not list(args.output.glob(".qec-materialize-*"))
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def test_reuse_rejects_corrupt_existing_payload(reusable_materialization, monkeypatch):
|
| 344 |
+
args, _, _ = reusable_materialization
|
| 345 |
+
(args.output / "development/payload.bin").write_bytes(b"corrupt data!")
|
| 346 |
+
monkeypatch.setattr(materializer, "extract", lambda *a, **k: pytest.fail("Unexpected extraction"))
|
| 347 |
+
with pytest.raises(ValueError, match="checksum mismatch"):
|
| 348 |
+
materializer.run(args)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def test_reuse_rejects_different_hash_verified_inventory(reusable_materialization, monkeypatch):
|
| 352 |
+
args, source, publish = reusable_materialization
|
| 353 |
+
(source / "payload.bin").write_bytes(b"different release")
|
| 354 |
+
write_json(source / "inventory.json", {"schema": "surface-code-decoding-inventory/v1", "files": {
|
| 355 |
+
"payload.bin": {"bytes": 17, "sha256": sha256(source / "payload.bin")}}})
|
| 356 |
+
publish() # Lock authenticates this different archive, but the target is old.
|
| 357 |
+
monkeypatch.setattr(materializer, "extract", lambda *a, **k: pytest.fail("Unexpected extraction"))
|
| 358 |
+
with pytest.raises(ValueError, match="another release"):
|
| 359 |
+
materializer.run(args)
|
| 360 |
+
assert (args.output / "development/payload.bin").read_bytes() == b"verified data"
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
@pytest.mark.parametrize("case", ["symlink", "directory", "oversized", "unsafe-path"])
|
| 364 |
+
def test_archive_inventory_validates_paths_types_and_size(tmp_path, case):
|
| 365 |
+
archive = tmp_path / "archive.tar.gz"
|
| 366 |
+
with tarfile.open(archive, "w:gz") as tar:
|
| 367 |
+
item = tarfile.TarInfo("development/inventory.json")
|
| 368 |
+
payload = b"{}"
|
| 369 |
+
if case == "symlink":
|
| 370 |
+
item.type = tarfile.SYMTYPE
|
| 371 |
+
item.linkname = "outside"
|
| 372 |
+
elif case == "directory":
|
| 373 |
+
item.type = tarfile.DIRTYPE
|
| 374 |
+
else:
|
| 375 |
+
item.size = len(payload)
|
| 376 |
+
tar.addfile(item, io.BytesIO(payload) if item.isfile() else None)
|
| 377 |
+
if case == "unsafe-path":
|
| 378 |
+
other = tarfile.TarInfo("development/../outside")
|
| 379 |
+
other.size = 1
|
| 380 |
+
tar.addfile(other, io.BytesIO(b"x"))
|
| 381 |
+
with pytest.raises(ValueError):
|
| 382 |
+
materializer.archive_inventory(archive, "development", 1 if case == "oversized" else 100)
|
reproduction/files/0e/0e6e92803a5e581475f687f0ee03bfcab81c170775957d28668fd632a14c3e1b/benchmark_score.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned benchmark normalization shared by development and trusted grading."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
BOUNDS = json.loads(Path(__file__).with_name("score_bounds.json").read_text())
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def normalize(performance: float) -> dict[str, Any]:
|
| 13 |
+
"""Normalize Hit@1 against fixed reference anchors, preserving overperformance."""
|
| 14 |
+
if isinstance(performance, bool) or not math.isfinite(performance) or not 0 <= performance <= 1:
|
| 15 |
+
raise ValueError("Hit@1 must be a finite number in [0, 1]")
|
| 16 |
+
lower, upper = BOUNDS["lower"], BOUNDS["upper"]
|
| 17 |
+
if not 0 <= lower < upper <= 1:
|
| 18 |
+
raise ValueError("invalid benchmark score anchors")
|
| 19 |
+
unclipped = (performance - lower) / (upper - lower)
|
| 20 |
+
return {
|
| 21 |
+
"version": BOUNDS["version"], "metric": BOUNDS["metric"],
|
| 22 |
+
"direction": BOUNDS["direction"], "raw_performance": performance,
|
| 23 |
+
"lower_reference": lower, "upper_reference": upper,
|
| 24 |
+
"score": min(1.0, max(0.0, unclipped)), "unclipped_score": unclipped,
|
| 25 |
+
"saturation": "lower" if unclipped < 0 else "upper" if unclipped > 1 else None,
|
| 26 |
+
"at_or_above_upper_reference": performance >= upper,
|
| 27 |
+
}
|
reproduction/files/0e/0e79954672aa8606568a564fd0e1f8ceb76bfbdac6fda2eadea7650396b6de06/test_policy_isolation.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A root-run evaluator must drop the submitted policy to an unprivileged, short-lived process."""
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
import tempfile
|
| 6 |
+
import time
|
| 7 |
+
import unittest
|
| 8 |
+
from unittest.mock import patch
|
| 9 |
+
ISOLATED = {'HYDROGYM_POLICY_ISOLATION': '1'}
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'environment/evaluation'))
|
| 12 |
+
import protocol
|
| 13 |
+
from protocol import InfrastructureError, Policy
|
| 14 |
+
|
| 15 |
+
POLICY = r'''
|
| 16 |
+
import json, os, subprocess, sys
|
| 17 |
+
target = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "target.txt")).read().strip()
|
| 18 |
+
try:
|
| 19 |
+
open(target, "w").write("forged")
|
| 20 |
+
except OSError as error:
|
| 21 |
+
sys.stderr.write("write-denied %s\n" % type(error).__name__)
|
| 22 |
+
sys.stderr.write("uid=%d\n" % os.getuid()); sys.stderr.flush()
|
| 23 |
+
subprocess.Popen(["setsid", "sleep", "300"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 24 |
+
for line in sys.stdin:
|
| 25 |
+
request = json.loads(line)
|
| 26 |
+
reply = {"protocol": request["protocol"], "request_id": request["request_id"]}
|
| 27 |
+
reply.update({"reset": {"ready": True}, "act": {"action": [0.0]}, "close": {"closed": True}}[request["op"]])
|
| 28 |
+
print(json.dumps(reply), flush=True)
|
| 29 |
+
if request["op"] == "close":
|
| 30 |
+
break
|
| 31 |
+
'''
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def account_exists():
|
| 35 |
+
try:
|
| 36 |
+
import pwd
|
| 37 |
+
pwd.getpwuid(protocol.POLICY_UID)
|
| 38 |
+
return True
|
| 39 |
+
except KeyError:
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class IsolationSwitchTests(unittest.TestCase):
|
| 44 |
+
def test_isolation_is_off_unless_requested(self):
|
| 45 |
+
with patch.dict(os.environ, {}, clear=False):
|
| 46 |
+
os.environ.pop('HYDROGYM_POLICY_ISOLATION', None)
|
| 47 |
+
self.assertIsNone(protocol.policy_account())
|
| 48 |
+
|
| 49 |
+
@unittest.skipIf(os.geteuid() == 0, 'checks the non-root refusal')
|
| 50 |
+
def test_requested_isolation_refuses_non_root(self):
|
| 51 |
+
with patch.dict(os.environ, ISOLATED), self.assertRaises(InfrastructureError):
|
| 52 |
+
protocol.policy_account()
|
| 53 |
+
|
| 54 |
+
def test_verifier_requests_isolation_offline(self):
|
| 55 |
+
here = Path(__file__).resolve().parents[1]
|
| 56 |
+
self.assertIn('export HYDROGYM_POLICY_ISOLATION=1', (here / 'tests/test.sh').read_text())
|
| 57 |
+
self.assertIn('network_mode: none', (here / 'tests/docker-compose.yaml').read_text())
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@unittest.skipUnless(os.geteuid() == 0 and account_exists(), 'needs root and the policy account (task image)')
|
| 61 |
+
class PolicyIsolationTests(unittest.TestCase):
|
| 62 |
+
def test_policy_runs_unprivileged_cannot_write_results_and_leaves_no_process(self):
|
| 63 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 64 |
+
root = Path(tmp)
|
| 65 |
+
os.chmod(root, 0o755)
|
| 66 |
+
package = root / 'package'; package.mkdir(); os.chmod(package, 0o755)
|
| 67 |
+
(package / 'policy.py').write_text(POLICY)
|
| 68 |
+
(package / 'infer.sh').write_text('exec python3 "$(dirname "$0")/policy.py"\n')
|
| 69 |
+
results = root / 'results'; results.mkdir(mode=0o755)
|
| 70 |
+
forged = results / 'reward.json'
|
| 71 |
+
(package / 'target.txt').write_text(str(forged))
|
| 72 |
+
for path in package.iterdir():
|
| 73 |
+
path.chmod(0o444)
|
| 74 |
+
with patch.dict(os.environ, ISOLATED):
|
| 75 |
+
policy = Policy(package, root / 'policy.log', timeout=20)
|
| 76 |
+
policy.reset({'environment': 'x', 'family': 'x', 'seed': 1}, [1], [1], [-1.0], [1.0])
|
| 77 |
+
self.assertEqual(policy.act([0.5]), [0.0])
|
| 78 |
+
policy.close()
|
| 79 |
+
log = (root / 'policy.log').read_text()
|
| 80 |
+
self.assertIn(f'uid={protocol.POLICY_UID}', log)
|
| 81 |
+
self.assertIn('write-denied PermissionError', log)
|
| 82 |
+
self.assertFalse(forged.exists())
|
| 83 |
+
time.sleep(0.5)
|
| 84 |
+
def alive(proc): # killed children re-parented to a non-reaping PID 1 stay as zombies
|
| 85 |
+
try:
|
| 86 |
+
return proc.stat().st_uid == protocol.POLICY_UID and \
|
| 87 |
+
(proc / 'stat').read_text().rsplit(')', 1)[1].split()[0] != 'Z'
|
| 88 |
+
except FileNotFoundError:
|
| 89 |
+
return False
|
| 90 |
+
owners = [p for p in Path('/proc').iterdir() if p.name.isdigit() and alive(p)]
|
| 91 |
+
self.assertEqual(owners, [])
|
| 92 |
+
|
| 93 |
+
def test_missing_account_fails_closed(self):
|
| 94 |
+
with tempfile.TemporaryDirectory() as tmp, patch.object(protocol, 'POLICY_UID', 54321), \
|
| 95 |
+
patch.dict(os.environ, ISOLATED):
|
| 96 |
+
with self.assertRaises(InfrastructureError):
|
| 97 |
+
Policy(Path(tmp), Path(tmp) / 'policy.log', timeout=5)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == '__main__':
|
| 101 |
+
unittest.main()
|
reproduction/files/11/110a51b699d57fd0239157173866513fab41f5d1ceeb6208bc2466bfa942486f/test_prepare_hf.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline integrity and split-isolation checks for HF preparation."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import io
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sys
|
| 8 |
+
import tarfile
|
| 9 |
+
import tempfile
|
| 10 |
+
import unittest
|
| 11 |
+
|
| 12 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environment/data"))
|
| 13 |
+
from prepare_hf import (
|
| 14 |
+
copy_stream,
|
| 15 |
+
prepare_pretraining,
|
| 16 |
+
prepare_windows,
|
| 17 |
+
safe_path,
|
| 18 |
+
verify,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def archive(path, rows):
|
| 23 |
+
with tarfile.open(path, "w") as tar:
|
| 24 |
+
for name, data in rows:
|
| 25 |
+
data = data.encode()
|
| 26 |
+
m = tarfile.TarInfo(name)
|
| 27 |
+
m.size = len(data)
|
| 28 |
+
tar.addfile(m, io.BytesIO(data))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class PreparationTests(unittest.TestCase):
|
| 32 |
+
def test_manifest_paths(self):
|
| 33 |
+
for name in ["../escape", "/absolute", "a/../../b", "a\\b"]:
|
| 34 |
+
with self.assertRaises(ValueError):
|
| 35 |
+
safe_path(name)
|
| 36 |
+
self.assertEqual(str(safe_path("archives/train.tar")), "archives/train.tar")
|
| 37 |
+
|
| 38 |
+
def test_checksum_and_size(self):
|
| 39 |
+
with tempfile.TemporaryDirectory() as t:
|
| 40 |
+
p = Path(t) / "data"
|
| 41 |
+
p.write_bytes(b"abc")
|
| 42 |
+
entry = dict(path="data", size=3, sha256=hashlib.sha256(b"abc").hexdigest())
|
| 43 |
+
verify(p, entry)
|
| 44 |
+
p.write_bytes(b"abd")
|
| 45 |
+
with self.assertRaises(ValueError):
|
| 46 |
+
verify(p, entry)
|
| 47 |
+
|
| 48 |
+
def test_resume_must_match(self):
|
| 49 |
+
with tempfile.TemporaryDirectory() as t:
|
| 50 |
+
p = Path(t) / "data"
|
| 51 |
+
copy_stream(io.BytesIO(b"abc"), p)
|
| 52 |
+
copy_stream(io.BytesIO(b"abc"), p)
|
| 53 |
+
for value in [b"ab", b"abcd", b"xyz"]:
|
| 54 |
+
with self.assertRaises(ValueError):
|
| 55 |
+
copy_stream(io.BytesIO(value), p)
|
| 56 |
+
self.assertEqual(p.read_bytes(), b"abc")
|
| 57 |
+
|
| 58 |
+
def test_selected_aliases_and_exclusions(self):
|
| 59 |
+
with tempfile.TemporaryDirectory() as t:
|
| 60 |
+
p = Path(t)
|
| 61 |
+
archive(
|
| 62 |
+
p / "a.tar",
|
| 63 |
+
[("root/sample_9.h5", "selected"), ("root/sample_3.h5", "excluded")],
|
| 64 |
+
)
|
| 65 |
+
selection = dict(
|
| 66 |
+
source_samples=2,
|
| 67 |
+
kept=1,
|
| 68 |
+
samples=[dict(sample_index=0, source="sample_9.h5")],
|
| 69 |
+
excluded=["sample_3.h5"],
|
| 70 |
+
)
|
| 71 |
+
self.assertEqual(
|
| 72 |
+
prepare_pretraining([p / "a.tar"], selection, p / "out"), 1
|
| 73 |
+
)
|
| 74 |
+
self.assertEqual((p / "out/sample_0.h5").read_text(), "selected")
|
| 75 |
+
self.assertEqual(len(list((p / "out").iterdir())), 1)
|
| 76 |
+
self.assertEqual(
|
| 77 |
+
prepare_pretraining([p / "a.tar"], selection, p / "out"), 1
|
| 78 |
+
)
|
| 79 |
+
with self.assertRaises(ValueError):
|
| 80 |
+
prepare_pretraining([p / "a.tar", p / "a.tar"], selection, p / "out")
|
| 81 |
+
|
| 82 |
+
def test_missing_selected_member(self):
|
| 83 |
+
with tempfile.TemporaryDirectory() as t:
|
| 84 |
+
p = Path(t)
|
| 85 |
+
archive(p / "a.tar", [])
|
| 86 |
+
selection = dict(
|
| 87 |
+
source_samples=1,
|
| 88 |
+
kept=1,
|
| 89 |
+
samples=[dict(sample_index=0, source="sample_9.h5")],
|
| 90 |
+
excluded=[],
|
| 91 |
+
)
|
| 92 |
+
with self.assertRaises(ValueError):
|
| 93 |
+
prepare_pretraining([p / "a.tar"], selection, p / "out")
|
| 94 |
+
|
| 95 |
+
def test_native_trainval_payload_before_metadata(self):
|
| 96 |
+
with tempfile.TemporaryDirectory() as t:
|
| 97 |
+
p = Path(t)
|
| 98 |
+
rows = [("dataset/config.json", "{}")]
|
| 99 |
+
for split in ["train", "val", "test"]:
|
| 100 |
+
prefix = f"dataset/windows/spatial_split/{split}"
|
| 101 |
+
rows.extend(
|
| 102 |
+
[
|
| 103 |
+
(prefix + "/layers/label/value", "label-" + split),
|
| 104 |
+
(
|
| 105 |
+
prefix + "/metadata.json",
|
| 106 |
+
json.dumps({"options": {"split": split}}),
|
| 107 |
+
),
|
| 108 |
+
]
|
| 109 |
+
)
|
| 110 |
+
archive(p / "a.tar", rows)
|
| 111 |
+
expected = {"train": 1, "val": 1, "test": 1}
|
| 112 |
+
report = prepare_windows(p / "a.tar", p / "out", expected)
|
| 113 |
+
self.assertFalse(report["heldout_window_payloads_read"])
|
| 114 |
+
self.assertFalse((p / "out/windows/spatial_split/test").exists())
|
| 115 |
+
self.assertTrue(
|
| 116 |
+
(p / "out/windows/spatial_split/train/layers/label/value").exists()
|
| 117 |
+
)
|
| 118 |
+
self.assertEqual(
|
| 119 |
+
prepare_windows(p / "a.tar", p / "out", expected)["files"], 5
|
| 120 |
+
)
|
| 121 |
+
with self.assertRaises(ValueError):
|
| 122 |
+
prepare_windows(
|
| 123 |
+
p / "a.tar", p / "other", {"train": 2, "val": 1, "test": 1}
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def test_unsafe_archive_member(self):
|
| 127 |
+
with tempfile.TemporaryDirectory() as t:
|
| 128 |
+
p = Path(t)
|
| 129 |
+
archive(p / "a.tar", [("../sample_9.h5", "x")])
|
| 130 |
+
selection = dict(
|
| 131 |
+
source_samples=1,
|
| 132 |
+
kept=1,
|
| 133 |
+
samples=[dict(sample_index=0, source="sample_9.h5")],
|
| 134 |
+
excluded=[],
|
| 135 |
+
)
|
| 136 |
+
with self.assertRaises(ValueError):
|
| 137 |
+
prepare_pretraining([p / "a.tar"], selection, p / "out")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
unittest.main()
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class DownloadPipelineTests(unittest.TestCase):
|
| 145 |
+
def test_hub_revision_pin_and_component_selection(self):
|
| 146 |
+
from types import SimpleNamespace
|
| 147 |
+
from unittest.mock import patch
|
| 148 |
+
import prepare_hf
|
| 149 |
+
|
| 150 |
+
with tempfile.TemporaryDirectory() as t:
|
| 151 |
+
root = Path(t)
|
| 152 |
+
snapshot = root / "snapshot"
|
| 153 |
+
snapshot.mkdir()
|
| 154 |
+
payload = snapshot / "inputs"
|
| 155 |
+
payload.write_bytes(b"fixture")
|
| 156 |
+
entries = [
|
| 157 |
+
dict(
|
| 158 |
+
path="eval/awf/inputs.h5",
|
| 159 |
+
size=7,
|
| 160 |
+
sha256=hashlib.sha256(b"fixture").hexdigest(),
|
| 161 |
+
components=["probe"],
|
| 162 |
+
),
|
| 163 |
+
dict(
|
| 164 |
+
path="archives/unused.tar",
|
| 165 |
+
size=99,
|
| 166 |
+
sha256="0" * 64,
|
| 167 |
+
components=["pretrain"],
|
| 168 |
+
),
|
| 169 |
+
]
|
| 170 |
+
(snapshot / "manifest.json").write_text(
|
| 171 |
+
json.dumps(dict(schema_version=1, files=entries))
|
| 172 |
+
)
|
| 173 |
+
calls = []
|
| 174 |
+
revision = "a" * 40
|
| 175 |
+
|
| 176 |
+
def download(repo, name, **kwargs):
|
| 177 |
+
calls.append((repo, name, kwargs["revision"]))
|
| 178 |
+
return str(
|
| 179 |
+
snapshot / "manifest.json" if name == "manifest.json" else payload
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
hub = SimpleNamespace(
|
| 183 |
+
HfApi=lambda: SimpleNamespace(
|
| 184 |
+
dataset_info=lambda *args, **kwargs: SimpleNamespace(sha=revision)
|
| 185 |
+
),
|
| 186 |
+
hf_hub_download=download,
|
| 187 |
+
)
|
| 188 |
+
args = [
|
| 189 |
+
"prepare_hf",
|
| 190 |
+
"--repo",
|
| 191 |
+
"example/data",
|
| 192 |
+
"--revision",
|
| 193 |
+
"v1",
|
| 194 |
+
"--output",
|
| 195 |
+
str(root / "output"),
|
| 196 |
+
"--components",
|
| 197 |
+
"probe",
|
| 198 |
+
]
|
| 199 |
+
with (
|
| 200 |
+
patch.dict(sys.modules, {"huggingface_hub": hub}),
|
| 201 |
+
patch.object(sys, "argv", args),
|
| 202 |
+
):
|
| 203 |
+
prepare_hf.main()
|
| 204 |
+
prepare_hf.main()
|
| 205 |
+
self.assertEqual(
|
| 206 |
+
(root / "output/eval/awf/inputs.h5").read_bytes(), b"fixture"
|
| 207 |
+
)
|
| 208 |
+
self.assertTrue(all(r == revision for _, _, r in calls))
|
| 209 |
+
self.assertNotIn("archives/unused.tar", [n for _, n, _ in calls])
|
| 210 |
+
report = json.loads((root / "output/hf-prepared.json").read_text())
|
| 211 |
+
self.assertEqual(report["revision"], revision)
|
reproduction/files/12/12033212bd52ab4a3c31643ee1434fdf4b84489b59feb62322cba2c56c127ff2/replay.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run exported model in a filesystem/network-isolated process."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import errno
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import shutil
|
| 7 |
+
import subprocess
|
| 8 |
+
import tempfile
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
checks = Path(__file__).resolve().parents[1] / "environment/evaluation"
|
| 12 |
+
if not checks.is_dir():
|
| 13 |
+
checks = Path(__file__).resolve().parent
|
| 14 |
+
if not (checks / "package_contract.py").is_file():
|
| 15 |
+
checks = Path("/evaluation")
|
| 16 |
+
sys.path.insert(0, str(checks))
|
| 17 |
+
from package_contract import InvalidSubmission, validate_features
|
| 18 |
+
from namespace import command, direct
|
| 19 |
+
|
| 20 |
+
p = argparse.ArgumentParser()
|
| 21 |
+
p.add_argument("--model", type=Path, required=True)
|
| 22 |
+
p.add_argument("--input", type=Path, required=True)
|
| 23 |
+
p.add_argument("--output", type=Path, required=True)
|
| 24 |
+
p.add_argument("--no-namespace", action="store_true",
|
| 25 |
+
help="development only: run without Bubblewrap where user namespaces are unavailable")
|
| 26 |
+
a = p.parse_args()
|
| 27 |
+
a.output.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
# Only unlabeled pixels and an empty output directory enter model execution.
|
| 29 |
+
# Previous scores/predictions in the destination are never mounted.
|
| 30 |
+
with tempfile.TemporaryDirectory(prefix="olmo-replay-", dir=a.output) as temp:
|
| 31 |
+
workspace = Path(temp)
|
| 32 |
+
inputs = workspace / "input"
|
| 33 |
+
inputs.mkdir()
|
| 34 |
+
outputs = workspace / "output"
|
| 35 |
+
outputs.mkdir()
|
| 36 |
+
dst = inputs / "inputs.h5"
|
| 37 |
+
try:
|
| 38 |
+
dst.hardlink_to(a.input)
|
| 39 |
+
except OSError as exc:
|
| 40 |
+
if exc.errno not in (errno.EXDEV, errno.EPERM, errno.EACCES):
|
| 41 |
+
raise
|
| 42 |
+
shutil.copyfile(a.input, dst)
|
| 43 |
+
if a.no_namespace:
|
| 44 |
+
argv, environment = direct(a.model.resolve(), inputs.resolve(), outputs.resolve())
|
| 45 |
+
subprocess.run(argv, check=True, env=environment, cwd=a.model.resolve())
|
| 46 |
+
else:
|
| 47 |
+
subprocess.run(
|
| 48 |
+
command(a.model.resolve(), inputs.resolve(), outputs.resolve()), check=True
|
| 49 |
+
)
|
| 50 |
+
result = outputs / "features.npz"
|
| 51 |
+
try:
|
| 52 |
+
validate_features(result, a.input)
|
| 53 |
+
except InvalidSubmission as error:
|
| 54 |
+
print(str(error), file=sys.stderr)
|
| 55 |
+
raise SystemExit(42)
|
| 56 |
+
result.replace(a.output / "features.npz")
|
reproduction/files/13/13b471d6183aced98dc4c168348cdfe26bd35c28f03f2e06f9da94345dfc7d12/run_local.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the physical suites (discovery, phonons, elasticity) on local GPUs.
|
| 2 |
+
|
| 3 |
+
One worker process per GPU pulls chunks from distributed.chunk_plan, writes each chunk with
|
| 4 |
+
predict.run, and distributed.merge assembles and checks the complete run:
|
| 5 |
+
|
| 6 |
+
python run_local.py --inputs CASES.jsonl --artifact MODEL.pt [--energy-audit AUDIT.json] \
|
| 7 |
+
--output OUT_DIR [--gpus 0,1,2,3] [--factory uma|module:function]
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import json
|
| 13 |
+
import multiprocessing as mp
|
| 14 |
+
import os
|
| 15 |
+
import socket
|
| 16 |
+
import time
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
HERE = Path(__file__).resolve().parent
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _worker(gpu, queue, args, chunk_root):
|
| 23 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
|
| 24 |
+
import sys
|
| 25 |
+
sys.path.insert(0, str(HERE))
|
| 26 |
+
from common import write_rows
|
| 27 |
+
import predict
|
| 28 |
+
calculator = predict.load_calculator(args.factory, args.artifact, "cuda")
|
| 29 |
+
while True:
|
| 30 |
+
item = queue.get()
|
| 31 |
+
if item is None:
|
| 32 |
+
return
|
| 33 |
+
chunk, rows = item
|
| 34 |
+
directory = chunk_root / chunk["chunk_id"]
|
| 35 |
+
if (directory / "worker.json").exists():
|
| 36 |
+
continue
|
| 37 |
+
staging = chunk_root / f".{chunk['chunk_id']}.tmp"
|
| 38 |
+
staging.mkdir(parents=True, exist_ok=True)
|
| 39 |
+
write_rows(staging / "inputs.jsonl", rows)
|
| 40 |
+
started = time.monotonic()
|
| 41 |
+
predict.run(staging / "inputs.jsonl", staging / "out", args.factory, args.artifact, "cuda",
|
| 42 |
+
args.energy_audit, calculator=calculator, verbose=False)
|
| 43 |
+
for name in ("run.json", "predictions.jsonl"):
|
| 44 |
+
(staging / "out" / name).rename(staging / name)
|
| 45 |
+
(staging / "out").rmdir()
|
| 46 |
+
(staging / "worker.json").write_text(json.dumps({
|
| 47 |
+
"worker_id": f"{socket.gethostname()}-gpu{gpu}", "chunk_id": chunk["chunk_id"],
|
| 48 |
+
"chunk_input_sha256": chunk["input_sha256"], "seconds": time.monotonic() - started}))
|
| 49 |
+
staging.rename(directory)
|
| 50 |
+
print(json.dumps({"chunk": chunk["chunk_id"], "gpu": gpu}), flush=True)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def main():
|
| 54 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 55 |
+
parser.add_argument("--inputs", type=Path, required=True)
|
| 56 |
+
parser.add_argument("--artifact", type=Path, required=True)
|
| 57 |
+
parser.add_argument("--energy-audit", type=Path)
|
| 58 |
+
parser.add_argument("--factory", default="uma")
|
| 59 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 60 |
+
parser.add_argument("--gpus", default=os.environ.get("CUDA_VISIBLE_DEVICES", "0"))
|
| 61 |
+
args = parser.parse_args()
|
| 62 |
+
import sys
|
| 63 |
+
sys.path.insert(0, str(HERE))
|
| 64 |
+
from common import digest, indexed, read_rows
|
| 65 |
+
from distributed import chunk_plan, merge
|
| 66 |
+
cases = read_rows(args.inputs)
|
| 67 |
+
by_id = indexed(cases)
|
| 68 |
+
plan = chunk_plan(cases)
|
| 69 |
+
chunk_root = args.output.parent / f"{args.output.name}.chunks"
|
| 70 |
+
chunk_root.mkdir(parents=True, exist_ok=True)
|
| 71 |
+
ctx = mp.get_context("spawn")
|
| 72 |
+
queue = ctx.Queue()
|
| 73 |
+
for chunk in plan:
|
| 74 |
+
queue.put((chunk, [by_id[key] for key in chunk["case_ids"]]))
|
| 75 |
+
gpus = [g for g in args.gpus.split(",") if g != ""]
|
| 76 |
+
for _ in gpus:
|
| 77 |
+
queue.put(None)
|
| 78 |
+
procs = [ctx.Process(target=_worker, args=(g, queue, args, chunk_root)) for g in gpus]
|
| 79 |
+
for p in procs:
|
| 80 |
+
p.start()
|
| 81 |
+
for p in procs:
|
| 82 |
+
p.join()
|
| 83 |
+
# Chunks left by a crashed worker must not block interpreter exit on the queue's feeder thread.
|
| 84 |
+
queue.cancel_join_thread()
|
| 85 |
+
failed = [p.exitcode for p in procs if p.exitcode]
|
| 86 |
+
if failed:
|
| 87 |
+
raise SystemExit(f"worker failed with exit code {failed[0]}")
|
| 88 |
+
merge(args.inputs, chunk_root, plan, args.output, digest(args.artifact))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
main()
|
reproduction/files/15/154b329ae33e35d2e254590344f029ae4b85350111b0a9a00f0e95019db0ff25/test_scaffold.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
TASK_ROOT = Path(__file__).resolve().parents[1]
|
| 7 |
+
ENVIRONMENT = TASK_ROOT / "environment"
|
| 8 |
+
DELPHI = ENVIRONMENT / "references" / "delphi"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_task_metadata_is_versioned() -> None:
|
| 12 |
+
metadata = (TASK_ROOT / "task.toml").read_text(encoding="utf-8")
|
| 13 |
+
assert 'name = "ai4sci/natural-disease-progression"' in metadata
|
| 14 |
+
assert 'input_schema = "natural-disease-progression-input/v2"' in metadata
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_task_layers_exist() -> None:
|
| 18 |
+
assert (ENVIRONMENT / "data" / "README.md").is_file()
|
| 19 |
+
assert (ENVIRONMENT / "references" / "scaffold" / "data.py").is_file()
|
| 20 |
+
assert (ENVIRONMENT / "references" / "scaffold" / "predict.py").is_file()
|
| 21 |
+
assert (ENVIRONMENT / "baseline" / "temporal-gru" / "longitudinal.py").is_file()
|
| 22 |
+
assert (ENVIRONMENT / "evaluation" / "score.py").is_file()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_agent_surface_is_neural_architecture_development() -> None:
|
| 26 |
+
instruction = (TASK_ROOT / "instruction.md").read_text(encoding="utf-8")
|
| 27 |
+
contract = (ENVIRONMENT / "contract.md").read_text(encoding="utf-8")
|
| 28 |
+
dockerfile = (ENVIRONMENT / "Dockerfile").read_text(encoding="utf-8")
|
| 29 |
+
assert "neural architecture development track" in instruction
|
| 30 |
+
assert "does not obtain its final predictions from LightGBM" in instruction
|
| 31 |
+
assert "fixed population time scaling" in contract
|
| 32 |
+
assert "COPY starter /workspace/starter" not in dockerfile
|
| 33 |
+
assert "COPY data /workspace/data" not in dockerfile
|
| 34 |
+
assert "maintenance" not in dockerfile
|
| 35 |
+
assert "starter/tabular_baseline.py" not in dockerfile
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_real_evaluator_is_present() -> None:
|
| 39 |
+
source = (ENVIRONMENT / "evaluation" / "score.py").read_text()
|
| 40 |
+
assert "from risk_scoring import score" in source
|
| 41 |
+
assert "panel_scoring" in source
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_verifier_separates_public_and_trusted_inputs() -> None:
|
| 45 |
+
main = (TASK_ROOT / "tests" / "main_verifier.py").read_text()
|
| 46 |
+
grader = (TASK_ROOT / "tests" / "grader.py").read_text()
|
| 47 |
+
assert "--trusted" not in main
|
| 48 |
+
assert "--trusted" in grader
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_harbor_entry_runs_inference_not_unit_tests() -> None:
|
| 52 |
+
entry = (TASK_ROOT / "tests" / "test.sh").read_text()
|
| 53 |
+
assert "main_verifier.py" in entry
|
| 54 |
+
assert "pytest" not in entry
|
| 55 |
+
assert "/logs/verifier" in (TASK_ROOT / "tests" / "main_verifier.py").read_text()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_verifier_requires_review_readme_without_claiming_architecture_detection() -> None:
|
| 59 |
+
main = (TASK_ROOT / "tests" / "main_verifier.py").read_text(encoding="utf-8")
|
| 60 |
+
assert "submission/README.md is required for architecture review" in main
|
| 61 |
+
assert "cannot establish that infer.sh actually uses" in main
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_verifier_main_installs_official_starter_inference_dependencies() -> None:
|
| 65 |
+
dockerfile = (TASK_ROOT / "tests" / "Dockerfile").read_text(encoding="utf-8")
|
| 66 |
+
for dependency in ("lightgbm==4.6.0", "joblib==1.5.3"):
|
| 67 |
+
assert dependency in dockerfile
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_compose_mounts_do_not_expose_materialization_roots() -> None:
|
| 71 |
+
development = (ENVIRONMENT / "docker-compose.yaml").read_text()
|
| 72 |
+
verifier = (TASK_ROOT / "tests" / "docker-compose.yaml").read_text()
|
| 73 |
+
# task.toml owns the network policy (TASK_STANDARD); the compose file must not override it.
|
| 74 |
+
assert "network_mode" not in development
|
| 75 |
+
assert 'network_mode = "no-network"' in (TASK_ROOT / "task.toml").read_text()
|
| 76 |
+
assert "target: /workspace/data/train" in development
|
| 77 |
+
assert "target: /workspace/data/public/validation" in development
|
| 78 |
+
assert "target: /workspace/data/trusted/validation" in development
|
| 79 |
+
assert "target: /data" not in development
|
| 80 |
+
assert "/public/test" in verifier
|
| 81 |
+
assert "target: /trusted/test" in verifier
|
| 82 |
+
assert "target: /input" in verifier
|
| 83 |
+
assert "target: /trusted\n" not in verifier
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_delphi_demo_data_has_uint32_triples() -> None:
|
| 87 |
+
for split in ("train", "val"):
|
| 88 |
+
data = np.memmap(DELPHI / "data" / "ukb_simulated_data" / f"{split}.bin", dtype=np.uint32, mode="r")
|
| 89 |
+
assert data.size > 0
|
| 90 |
+
assert data.size % 3 == 0
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def test_vendored_python_compiles() -> None:
|
| 94 |
+
for name in ("model.py", "train.py", "utils.py", "configurator.py"):
|
| 95 |
+
source = (DELPHI / name).read_text(encoding="utf-8")
|
| 96 |
+
compile(source, str(DELPHI / name), "exec")
|
reproduction/files/15/1553aceb037cf137db93f3156f0bb339ca179b773e58552a6400ad51b1699538/main_verifier.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run the submitted calculator through every test suite as uid 10001 and seal the predictions.
|
| 3 |
+
|
| 4 |
+
All suites run at the same time, each with its own workers spread over every visible GPU, inside one
|
| 5 |
+
shared time budget: physical (WBM discovery, MDR phonons, MP elasticity) with run_local.py, and
|
| 6 |
+
thermal conductivity, MOF bulk modulus, amorphous AM26, cleavage and Li-migration NEB with extra.py.
|
| 7 |
+
The long-tailed suites (MOF, NEB) get the most workers and start their most expensive items first. The evaluator code
|
| 8 |
+
drives every relaxation, displacement and strain; the submission only supplies the calculator.
|
| 9 |
+
At the shared time limit (3 h by default) every suite stops: the cases it finished are kept and the
|
| 10 |
+
rest are scored as failures. A suite that crashes is sealed as it is: the grader scores its missing
|
| 11 |
+
cases as failures (extra suites) or marks the suite invalid (physical suites).
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import pwd
|
| 19 |
+
import shutil
|
| 20 |
+
import signal
|
| 21 |
+
import stat
|
| 22 |
+
import subprocess
|
| 23 |
+
import time
|
| 24 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
from verifier_common import sha256, tree_sha256, write_json
|
| 28 |
+
|
| 29 |
+
EVALUATION = Path("/evaluation") if Path("/evaluation").is_dir() else Path(__file__).resolve().parents[1] / "environment/evaluation"
|
| 30 |
+
EXTRA_SUITES = ("kappa", "mof", "amorphous", "cleavage", "neb")
|
| 31 |
+
SUITES = ("physical",) + EXTRA_SUITES
|
| 32 |
+
SCHEMA = "atomistic-materials-prediction-snapshot/v2"
|
| 33 |
+
MAX_SNAPSHOT_BYTES = 8 * 1024 ** 3
|
| 34 |
+
# Workers per GPU for each suite when they all run at once. MOF (EOS of large cells) and NEB (relaxed end
|
| 35 |
+
# points, then a climbing-image band) dominate the wall time, so they get the most workers; relaxations
|
| 36 |
+
# and phono3py leave a single worker's GPU mostly idle.
|
| 37 |
+
WORKERS_PER_GPU = {"physical": 2, "kappa": 2, "mof": 4, "amorphous": 1, "cleavage": 1, "neb": 3}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def harbor_reward(values):
|
| 41 |
+
"""Harbor parses reward.json as a flat object of finite numbers; strings, None and nested details
|
| 42 |
+
belong in report.json / status.json."""
|
| 43 |
+
import math as _math
|
| 44 |
+
return {k: v for k, v in values.items() if isinstance(v, (int, float)) and _math.isfinite(v)}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def validate_submission(root: Path):
|
| 48 |
+
root = root.resolve()
|
| 49 |
+
entry = root / "calculator.py"
|
| 50 |
+
if not entry.is_file() or entry.is_symlink():
|
| 51 |
+
raise FileNotFoundError("submission/calculator.py required")
|
| 52 |
+
for path in root.rglob("*"):
|
| 53 |
+
if path.is_symlink() and not path.resolve().is_relative_to(root):
|
| 54 |
+
raise ValueError(f"submission symlink escapes package: {path.relative_to(root)}")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def validate_input(root: Path):
|
| 58 |
+
for suite in SUITES:
|
| 59 |
+
inputs = root / suite / "inputs"
|
| 60 |
+
if not inputs.is_dir():
|
| 61 |
+
raise FileNotFoundError(f"missing verifier input: {inputs}")
|
| 62 |
+
if any(p.name.startswith(("references", "targets")) for p in (root / suite).rglob("*")):
|
| 63 |
+
raise ValueError(f"untrusted input contains references: {suite}")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def gpu_ids():
|
| 67 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES"):
|
| 68 |
+
return os.environ["CUDA_VISIBLE_DEVICES"]
|
| 69 |
+
out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True).stdout
|
| 70 |
+
return ",".join(str(i) for i in range(max(1, sum(line.startswith("GPU ") for line in out.splitlines()))))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def command(suite, inputs, submission, output, gpus):
|
| 74 |
+
py = "/opt/venv/bin/python"
|
| 75 |
+
if suite == "physical":
|
| 76 |
+
return [py, str(EVALUATION / "run_local.py"), "--inputs", str(inputs / "cases.jsonl"), "--factory", "submission",
|
| 77 |
+
"--artifact", str(submission), "--output", str(output), "--gpus", gpus]
|
| 78 |
+
return [py, str(EVALUATION / "extra.py"), "run", "--suite", suite, "--inputs", str(inputs), "--factory", "submission",
|
| 79 |
+
"--artifact", str(submission), "--output", str(output), "--gpus", gpus]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _agent_processes(uid):
|
| 83 |
+
result = []
|
| 84 |
+
for entry in Path("/proc").iterdir():
|
| 85 |
+
if not entry.name.isdigit():
|
| 86 |
+
continue
|
| 87 |
+
try:
|
| 88 |
+
status = (entry / "status").read_text()
|
| 89 |
+
real_uid = int(next(line for line in status.splitlines() if line.startswith("Uid:")).split()[1])
|
| 90 |
+
state = next(line for line in status.splitlines() if line.startswith("State:")).split()[1]
|
| 91 |
+
except (FileNotFoundError, PermissionError, StopIteration, ValueError):
|
| 92 |
+
continue
|
| 93 |
+
if real_uid == uid and state != "Z":
|
| 94 |
+
result.append(int(entry.name))
|
| 95 |
+
return result
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _stop_untrusted(uid):
|
| 99 |
+
# SIGKILLed GPU workers can take tens of seconds to exit while the driver tears down their CUDA
|
| 100 |
+
# contexts (seen at the time limit, with ~100 workers killed at once).
|
| 101 |
+
deadline = time.monotonic() + 180
|
| 102 |
+
while True:
|
| 103 |
+
for pid in _agent_processes(uid):
|
| 104 |
+
try:
|
| 105 |
+
os.kill(pid, signal.SIGKILL)
|
| 106 |
+
except ProcessLookupError:
|
| 107 |
+
pass
|
| 108 |
+
remaining = _agent_processes(uid)
|
| 109 |
+
if not remaining:
|
| 110 |
+
return
|
| 111 |
+
if time.monotonic() >= deadline:
|
| 112 |
+
raise RuntimeError(f"untrusted processes survived cleanup: {remaining}")
|
| 113 |
+
time.sleep(0.05)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def run_suite(suite, args, work, gpus, timeout):
|
| 117 |
+
agent = pwd.getpwnam("agent")
|
| 118 |
+
output = work / suite
|
| 119 |
+
env = {"PATH": "/opt/venv/bin:/usr/local/bin:/usr/bin:/bin", "HOME": agent.pw_dir, "PYTHONUNBUFFERED": "1",
|
| 120 |
+
"PIP_NO_INDEX": "1", "HF_HUB_OFFLINE": "1", "OMP_NUM_THREADS": "2",
|
| 121 |
+
# Many workers share each GPU; fewer fragmented blocks means fewer out-of-memory retries.
|
| 122 |
+
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}
|
| 123 |
+
|
| 124 |
+
def demote():
|
| 125 |
+
os.setgid(agent.pw_gid)
|
| 126 |
+
os.setuid(agent.pw_uid)
|
| 127 |
+
started = time.monotonic()
|
| 128 |
+
status = "complete"
|
| 129 |
+
with (work / f"{suite}.log").open("wb") as log:
|
| 130 |
+
process = subprocess.Popen(command(suite, args.input / suite / "inputs", args.submission, output, gpus),
|
| 131 |
+
cwd=work, env=env, stdout=log, stderr=subprocess.STDOUT,
|
| 132 |
+
start_new_session=True, preexec_fn=demote)
|
| 133 |
+
try:
|
| 134 |
+
code = process.wait(timeout=max(1, timeout))
|
| 135 |
+
if code:
|
| 136 |
+
status = f"exit {code}"
|
| 137 |
+
except subprocess.TimeoutExpired:
|
| 138 |
+
status = "timeout"
|
| 139 |
+
finally:
|
| 140 |
+
# Only this suite's process group: the other suites are still running as the same user.
|
| 141 |
+
# Anything that left the group is killed by the user-wide sweep after the last suite.
|
| 142 |
+
try:
|
| 143 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 144 |
+
except ProcessLookupError:
|
| 145 |
+
pass
|
| 146 |
+
if process.poll() is None:
|
| 147 |
+
process.wait()
|
| 148 |
+
return {"suite": suite, "status": status, "seconds": round(time.monotonic() - started, 1)}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def close_unfinished(suite, args, work):
|
| 152 |
+
"""After the shared time limit: keep what a suite finished and mark the rest as failed cases.
|
| 153 |
+
|
| 154 |
+
Physical: merge the finished chunks; the cases of unfinished chunks become failed records.
|
| 155 |
+
Extra suites: write the run record the driver would have written; items without a file are
|
| 156 |
+
scored as failures by score_extra."""
|
| 157 |
+
import sys
|
| 158 |
+
sys.path.insert(0, str(EVALUATION))
|
| 159 |
+
from common import digest, read_rows
|
| 160 |
+
reason = "verifier time limit reached"
|
| 161 |
+
output = work / suite
|
| 162 |
+
if suite == "physical":
|
| 163 |
+
from distributed import chunk_plan, merge
|
| 164 |
+
if (output / "run.json").exists():
|
| 165 |
+
return
|
| 166 |
+
inputs = args.input / suite / "inputs" / "cases.jsonl"
|
| 167 |
+
merge(inputs, work / "physical.chunks", chunk_plan(read_rows(inputs)), output, digest(args.submission),
|
| 168 |
+
unfinished_reason=reason)
|
| 169 |
+
return
|
| 170 |
+
if (output / "run.json").exists():
|
| 171 |
+
return
|
| 172 |
+
import hashlib
|
| 173 |
+
done = len(list((output / "items").glob("*.json"))) if (output / "items").is_dir() else 0
|
| 174 |
+
manifest = args.input / suite / "inputs" / "manifest.json"
|
| 175 |
+
write_json(output / "run.json", {
|
| 176 |
+
"protocol": "atomistic-extra-suites-v1", "suite": suite,
|
| 177 |
+
"inputs_manifest_sha256": hashlib.sha256(manifest.read_bytes()).hexdigest(),
|
| 178 |
+
"checkpoint_sha256": digest(args.submission), "factory": "submission",
|
| 179 |
+
"completed": done, "complete": False, "unfinished_reason": reason})
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _copy_snapshot(source: Path, destination: Path):
|
| 183 |
+
keep = ["run.json", "predictions.jsonl"] if (source / "predictions.jsonl").exists() else None
|
| 184 |
+
destination.mkdir(parents=True)
|
| 185 |
+
if not source.exists():
|
| 186 |
+
return
|
| 187 |
+
for path in source.rglob("*"):
|
| 188 |
+
mode = path.lstat().st_mode
|
| 189 |
+
if path.is_symlink() or not (stat.S_ISREG(mode) or stat.S_ISDIR(mode)):
|
| 190 |
+
raise ValueError(f"prediction output contains non-regular entry: {path.relative_to(source)}")
|
| 191 |
+
if keep:
|
| 192 |
+
for name in keep:
|
| 193 |
+
shutil.copyfile(source / name, destination / name)
|
| 194 |
+
else:
|
| 195 |
+
for name in ("run.json",):
|
| 196 |
+
if (source / name).is_file():
|
| 197 |
+
shutil.copyfile(source / name, destination / name)
|
| 198 |
+
if (source / "items").is_dir():
|
| 199 |
+
shutil.copytree(source / "items", destination / "items")
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _lock(root: Path):
|
| 203 |
+
for path in sorted(root.rglob("*"), reverse=True):
|
| 204 |
+
os.chown(path, 0, 0, follow_symlinks=False)
|
| 205 |
+
os.chmod(path, 0o500 if path.is_dir() else 0o400, follow_symlinks=False)
|
| 206 |
+
os.chown(root, 0, 0)
|
| 207 |
+
os.chmod(root, 0o500)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def main():
|
| 211 |
+
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 212 |
+
p.add_argument("--submission", type=Path, required=True)
|
| 213 |
+
p.add_argument("--input", type=Path, required=True)
|
| 214 |
+
p.add_argument("--sealed", type=Path, required=True)
|
| 215 |
+
p.add_argument("--output", type=Path, required=True)
|
| 216 |
+
p.add_argument("--timeout", type=int, default=10800, help="shared limit for all suites (s)")
|
| 217 |
+
p.add_argument("--grader-timeout", type=int, default=7200)
|
| 218 |
+
p.add_argument("--suites", default=",".join(SUITES))
|
| 219 |
+
p.add_argument("--workers-per-gpu", type=int, default=0, help="same for every suite (default: WORKERS_PER_GPU)")
|
| 220 |
+
p.add_argument("--no-wait", action="store_true")
|
| 221 |
+
a = p.parse_args()
|
| 222 |
+
a.output.mkdir(parents=True, exist_ok=True)
|
| 223 |
+
try:
|
| 224 |
+
validate_submission(a.submission)
|
| 225 |
+
validate_input(a.input)
|
| 226 |
+
except (FileNotFoundError, ValueError) as error:
|
| 227 |
+
# The package, not the verifier, failed: every metric is unavailable and the run scores 0.
|
| 228 |
+
from grader import expanded_score, flatten
|
| 229 |
+
aggregate = expanded_score({}, valid=False)
|
| 230 |
+
write_json(a.output / "report.json", {"status": "invalid_submission", "error": str(error)[:2000],
|
| 231 |
+
"aggregate": aggregate})
|
| 232 |
+
write_json(a.output / "reward.json", harbor_reward({"reward": 0.0, "crystal_potential_score": 0.0,
|
| 233 |
+
"invalid_submission": True, **flatten({})}))
|
| 234 |
+
return
|
| 235 |
+
work = a.output / "main"
|
| 236 |
+
work.mkdir()
|
| 237 |
+
agent = pwd.getpwnam("agent")
|
| 238 |
+
os.chown(work, agent.pw_uid, agent.pw_gid)
|
| 239 |
+
os.chmod(work, 0o700)
|
| 240 |
+
# The untrusted user reads a private copy of the package, whatever the snapshot's ownership.
|
| 241 |
+
package = work / "submission"
|
| 242 |
+
shutil.copytree(a.submission, package, symlinks=True)
|
| 243 |
+
for path in [package, *package.rglob("*")]:
|
| 244 |
+
os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False)
|
| 245 |
+
a.submission = package
|
| 246 |
+
# Label-free inputs, likewise copied so their host permissions cannot block the untrusted user.
|
| 247 |
+
inputs = work / "inputs"
|
| 248 |
+
shutil.copytree(a.input, inputs)
|
| 249 |
+
for path in [inputs, *inputs.rglob("*")]:
|
| 250 |
+
os.chmod(path, 0o555 if path.is_dir() else 0o444)
|
| 251 |
+
original_input, a.input = a.input, inputs
|
| 252 |
+
devices = gpu_ids().split(",")
|
| 253 |
+
deadline = time.monotonic() + a.timeout
|
| 254 |
+
suites = a.suites.split(",")
|
| 255 |
+
|
| 256 |
+
def launch(suite):
|
| 257 |
+
per_gpu = a.workers_per_gpu or WORKERS_PER_GPU[suite]
|
| 258 |
+
run = run_suite(suite, a, work, ",".join(devices * per_gpu), int(deadline - time.monotonic()))
|
| 259 |
+
print(json.dumps({"event": "suite_done", "workers": per_gpu * len(devices), **run}), flush=True)
|
| 260 |
+
return run
|
| 261 |
+
with ThreadPoolExecutor(max_workers=len(suites)) as pool:
|
| 262 |
+
runs = list(pool.map(launch, suites))
|
| 263 |
+
_stop_untrusted(agent.pw_uid)
|
| 264 |
+
for run in runs:
|
| 265 |
+
if run["status"] == "timeout":
|
| 266 |
+
close_unfinished(run["suite"], a, work)
|
| 267 |
+
temporary = a.sealed.with_name(a.sealed.name + f".tmp-{os.getpid()}")
|
| 268 |
+
for suite in a.suites.split(","):
|
| 269 |
+
_copy_snapshot(work / suite, temporary / suite)
|
| 270 |
+
size = sum(f.stat().st_size for f in temporary.rglob("*") if f.is_file())
|
| 271 |
+
if size > MAX_SNAPSHOT_BYTES:
|
| 272 |
+
raise ValueError("prediction snapshot exceeds 8 GiB")
|
| 273 |
+
snapshot = {"schema": SCHEMA, "runs": runs,
|
| 274 |
+
"inputs": {s: tree_sha256(original_input / s / "inputs") for s in a.suites.split(",")},
|
| 275 |
+
"predictions": {s: tree_sha256(temporary / s) for s in a.suites.split(",")}}
|
| 276 |
+
write_json(temporary / "snapshot.json", snapshot)
|
| 277 |
+
_lock(temporary)
|
| 278 |
+
os.replace(temporary, a.sealed)
|
| 279 |
+
(a.sealed.parent / "READY").write_text(sha256(a.sealed / "snapshot.json") + "\n")
|
| 280 |
+
if not a.no_wait:
|
| 281 |
+
results = a.sealed.parent / "results"
|
| 282 |
+
end = time.monotonic() + a.grader_timeout
|
| 283 |
+
while not (results / "reward.json").is_file():
|
| 284 |
+
if time.monotonic() >= end:
|
| 285 |
+
raise TimeoutError("grader did not publish reward")
|
| 286 |
+
time.sleep(2)
|
| 287 |
+
for name in ("report.json", "reward.json"):
|
| 288 |
+
shutil.copyfile(results / name, a.output / name)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
if __name__ == "__main__":
|
| 292 |
+
main()
|
reproduction/files/15/15779511279917cfb9d960cb391c0edf6e60b35d2b247738ad7fc93a38a399a5/runtime.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -eo pipefail
|
| 3 |
+
# Upstream image's documented MPI/solver stack; fail clearly if it changes.
|
| 4 |
+
source /etc/profile
|
| 5 |
+
module purge
|
| 6 |
+
module load MAIA/1.0-NVHPC-26.1
|
| 7 |
+
source /home/easybuild/venvs/hydrogym_gpu/bin/activate
|
| 8 |
+
set -u
|
| 9 |
+
export OMP_NUM_THREADS=1
|
| 10 |
+
export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1
|
| 11 |
+
export PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
| 12 |
+
exec "$@"
|
reproduction/files/16/1649bbc73b03f29924a080b6fd4830d1efa5ced52914253d1f54ab0ef86a27f2/test_resource_audit.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Resource coverage checks, not native CFD or scientific acceptance tests."""
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import unittest
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
DATA = Path(__file__).resolve().parents[1] / "environment/data"
|
| 11 |
+
spec = importlib.util.spec_from_file_location("resource_audit", DATA / "resource_audit.py")
|
| 12 |
+
resource_audit = importlib.util.module_from_spec(spec)
|
| 13 |
+
spec.loader.exec_module(resource_audit)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ResourceAuditTests(unittest.TestCase):
|
| 17 |
+
def setUp(self):
|
| 18 |
+
self.coverage = json.loads((DATA / "paper-coverage.json").read_text())
|
| 19 |
+
self.catalog = json.loads((DATA / "catalog.json").read_text())
|
| 20 |
+
self.report = resource_audit.audit(self.coverage, self.catalog)
|
| 21 |
+
|
| 22 |
+
def test_complete_table_accounting_does_not_exclude_cases(self):
|
| 23 |
+
self.assertEqual(self.report["paper_rows"], 55)
|
| 24 |
+
self.assertEqual(sum(self.report["resource_counts"].values()), 55)
|
| 25 |
+
self.assertEqual(self.report["scope_exclusions"], [])
|
| 26 |
+
self.assertEqual(self.report["resource_counts"]["missing_payload"], 9)
|
| 27 |
+
self.assertAlmostEqual(self.report["missing_payload_fraction"], 9 / 55)
|
| 28 |
+
self.assertNotIn("cases", self.report)
|
| 29 |
+
|
| 30 |
+
def test_checked_in_report_matches_reproducible_audit(self):
|
| 31 |
+
self.assertEqual(json.loads((DATA / "resource-audit.json").read_text()), self.report)
|
| 32 |
+
|
| 33 |
+
def test_4140_is_not_silently_4200_or_a_missing_family(self):
|
| 34 |
+
row = next(r for r in self.report["rows"] if r["family"] == "cavity"
|
| 35 |
+
and r["dimension"] == 2 and r["parameters"]["Re"] == 4200)
|
| 36 |
+
self.assertEqual(row["resource_status"], "parameter_mismatch")
|
| 37 |
+
self.assertEqual(row["candidate_payloads"], [])
|
| 38 |
+
self.assertIn("Cavity_2D_Re4140", row["related_not_equivalent"])
|
| 39 |
+
|
| 40 |
+
def test_dra_marker_and_mach_are_not_usable_payloads(self):
|
| 41 |
+
rows = {r["parameters"]["Mach"]: r for r in self.report["rows"]
|
| 42 |
+
if r["family"] == "dra2303"}
|
| 43 |
+
self.assertEqual(rows[0.2]["resource_status"], "partial_variant_payload")
|
| 44 |
+
self.assertEqual(rows[0.7]["resource_status"], "missing_payload")
|
| 45 |
+
self.assertEqual(len(rows[0.7]["marker_only"]), 2)
|
| 46 |
+
self.assertEqual(rows[0.7]["candidate_payloads"], [])
|
| 47 |
+
|
| 48 |
+
def test_firedrake_and_marl_are_not_discarded_for_adapter_gaps(self):
|
| 49 |
+
row = next(r for r in self.report["rows"] if r["family"] == "cylinder"
|
| 50 |
+
and r["dimension"] == 2 and r["parameters"]["Re"] == 100)
|
| 51 |
+
self.assertEqual(len(row["candidate_payloads"]), 2)
|
| 52 |
+
self.assertEqual(row["resource_status"], "candidate_payload_unvalidated")
|
| 53 |
+
marl = [r for r in self.report["rows"] if r["family"] == "cylinder-marl"]
|
| 54 |
+
self.assertEqual(len(marl), 2)
|
| 55 |
+
self.assertTrue(all(r["candidate_payloads"] for r in marl))
|
| 56 |
+
self.assertTrue(all(r["evaluation_status"] == "not_full_suite_validated" for r in marl))
|
| 57 |
+
|
| 58 |
+
def test_other_reynolds_number_does_not_replace_channel180(self):
|
| 59 |
+
catalog = copy.deepcopy(self.catalog)
|
| 60 |
+
catalog["directories"] = [d for d in catalog["directories"]
|
| 61 |
+
if d["name"] != "TCFmini_3D_Re180"]
|
| 62 |
+
report = resource_audit.audit(self.coverage, catalog)
|
| 63 |
+
row = next(r for r in report["rows"] if r["family"] == "turbulent-channel")
|
| 64 |
+
self.assertEqual(row["resource_status"], "parameter_mismatch")
|
| 65 |
+
self.assertEqual(row["related_not_equivalent"], ["TCFlarge_3D_Re207"])
|
| 66 |
+
|
| 67 |
+
def test_reject_inconsistent_revision(self):
|
| 68 |
+
self.catalog["revision"] = "different"
|
| 69 |
+
with self.assertRaisesRegex(ValueError, "revisions"):
|
| 70 |
+
resource_audit.audit(self.coverage, self.catalog)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
if __name__ == "__main__":
|
| 74 |
+
unittest.main()
|
reproduction/files/17/1756e9907b650c8ec13b6d0b30c3c09297586db754ebdf7f18cf6c6566514c4c/fetch_baseline.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download the pinned baseline using existing authorized Hugging Face access."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import shutil
|
| 7 |
+
|
| 8 |
+
from huggingface_hub import hf_hub_download
|
| 9 |
+
|
| 10 |
+
from common import digest, write_json
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def fetch(output: Path):
|
| 14 |
+
baseline = json.loads(Path(__file__).with_name("baseline.json").read_text())
|
| 15 |
+
if output.exists():
|
| 16 |
+
raise FileExistsError(output)
|
| 17 |
+
downloaded = Path(
|
| 18 |
+
hf_hub_download(
|
| 19 |
+
baseline["repository"],
|
| 20 |
+
baseline["filename"],
|
| 21 |
+
revision=baseline["revision"],
|
| 22 |
+
)
|
| 23 |
+
)
|
| 24 |
+
if digest(downloaded) != baseline["sha256"]:
|
| 25 |
+
raise ValueError("Baseline checkpoint checksum mismatch")
|
| 26 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 27 |
+
shutil.copyfile(downloaded, output)
|
| 28 |
+
write_json(output.with_suffix(".json"), baseline)
|
| 29 |
+
print(output)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 34 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 35 |
+
fetch(parser.parse_args().output)
|
reproduction/files/17/1788a1f2895aae12e5639dbf83cccffcb00b5ef9b850b60ed7bf2f37057fe140/pipeline.py
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The designability pipeline: LigandMPNN inverse folding plus RoseTTAFold3 refolding.
|
| 2 |
+
|
| 3 |
+
Runs inside the trusted grader only. It never imports, executes, or links against the
|
| 4 |
+
delivered submission; it consumes sealed coordinates.
|
| 5 |
+
|
| 6 |
+
Criteria follow the benchmark's per-track `success.txt` (vendored at
|
| 7 |
+
environment/data/targets/*/success.txt). FOUR sequences per backbone on every track -
|
| 8 |
+
the task's own uniform budget, against 8 for enzyme and sm_binder upstream. The
|
| 9 |
+
criterion is "pass if ANY sequence passes", so fewer sequences can only lower a pass
|
| 10 |
+
rate; these are conservative against the published numbers, never flattering.
|
| 11 |
+
|
| 12 |
+
enzyme 4 LigandMPNN sequences, 5 predictor models. Passes if ANY model for ANY
|
| 13 |
+
sequence has, after aligning on the motif backbone (N, CA, C), a motif
|
| 14 |
+
all-atom RMSD <= 1.5 A.
|
| 15 |
+
sm_binder 4 LigandMPNN sequences. backbone RMSD <= 1.5 A AND backbone-aligned
|
| 16 |
+
ligand RMSD <= 5 A AND interface min PAE <= 1.5 AND ipTM >= 0.8.
|
| 17 |
+
ppi_binder 4 ProteinMPNN sequences. min inter-chain PAE <= 1.5, plus binder
|
| 18 |
+
backbone RMSD <= 2 A.
|
| 19 |
+
unconditional
|
| 20 |
+
4 ProteinMPNN sequences. backbone RMSD <= 1.5 A.
|
| 21 |
+
|
| 22 |
+
LigandMPNN is selected exactly where the context carries a ligand; ProteinMPNN
|
| 23 |
+
otherwise. The enzyme ligand-clash term - the one published criterion measured on the raw
|
| 24 |
+
design rather than on the refold - is applied by grader.py before folding, purely to skip
|
| 25 |
+
a fold that cannot pass. The grader adds no criterion of its own; see
|
| 26 |
+
environment/evaluation/RESULTS.md.
|
| 27 |
+
|
| 28 |
+
ipTM and PAE require a complex-capable predictor, which is why RoseTTAFold3 is used
|
| 29 |
+
rather than ESMFold: ESMFold is single-chain and emits neither, and cannot model a
|
| 30 |
+
protein-ligand complex at all.
|
| 31 |
+
|
| 32 |
+
Pinned assets
|
| 33 |
+
-------------
|
| 34 |
+
LigandMPNN github.com/dauparas/LigandMPNN @ 26ec57ac976ade5379920dbd43c7f97a91cf82de
|
| 35 |
+
MIT. Weights fetched by its own get_model_params.sh, mirrored in
|
| 36 |
+
`environment/fetch_designability_weights.sh` with pinned sha256.
|
| 37 |
+
|
| 38 |
+
The ORIGINAL repository, deliberately - not the re-implementation in
|
| 39 |
+
foundry's `models/mpnn`. Upstream itself says to "use the old repositories
|
| 40 |
+
... for model benchmarking/comparison until the API and public weights
|
| 41 |
+
stabilize", and that warning is justified: run against the foundry
|
| 42 |
+
re-implementation, `ligand_mpnn` returned byte-identical sequences AND
|
| 43 |
+
confidences with and without a ligand that had 52 of 53 atoms within 5 A
|
| 44 |
+
of the backbone, reporting `ligand_interface_sequence_recovery=nan`. Its
|
| 45 |
+
ligand conditioning is inert, and ligand conditioning is the whole point
|
| 46 |
+
of two of the four tracks.
|
| 47 |
+
|
| 48 |
+
RoseTTAFold3 github.com/RosettaCommons/foundry @ b02eed6a6bdf8f44d14a80cc36e3da13c9f2291c
|
| 49 |
+
BSD-3, IPD/UW. Source vendored at `environment/evaluation/rf3`;
|
| 50 |
+
parameters are a public download (files.ipd.uw.edu), pinned by sha256 in
|
| 51 |
+
`environment/fetch_designability_weights.sh`.
|
| 52 |
+
|
| 53 |
+
RF3 replaces AlphaFold 3, whose parameters are not redistributable and so
|
| 54 |
+
had to be mounted by the operator - which kept designability off the
|
| 55 |
+
agent's own scoring path entirely. RF3's parameters ship, so the criterion
|
| 56 |
+
an agent optimises is the criterion it is graded on.
|
| 57 |
+
|
| 58 |
+
NOTE the consequence for comparability: the per-track thresholds below come
|
| 59 |
+
from RFdiffusion3's published `success.txt`, which was calibrated with
|
| 60 |
+
AlphaFold. Scoring with a different predictor does not preserve those
|
| 61 |
+
numbers' published meaning. This is a deliberate, recorded trade.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
import contextlib
|
| 65 |
+
import json
|
| 66 |
+
import os
|
| 67 |
+
import queue
|
| 68 |
+
import subprocess
|
| 69 |
+
import sys
|
| 70 |
+
import tempfile
|
| 71 |
+
import threading
|
| 72 |
+
from pathlib import Path
|
| 73 |
+
|
| 74 |
+
import numpy as np
|
| 75 |
+
|
| 76 |
+
from common import (IPTM_MIN, INTERFACE_PAE_MAX, LIGAND_RMSD_MAX, MODELS_PER_SEQUENCE,
|
| 77 |
+
MOTIF_RMSD_MAX, PPI_RMSD_MAX, SAMPLING_TEMPERATURE, SC_RMSD_MAX,
|
| 78 |
+
SEQUENCES_PER_BACKBONE, sha256)
|
| 79 |
+
from geometry import kabsch_rotation, superposed_rmsd, write_allatom_pdb
|
| 80 |
+
from residues import THREE_TO_ONE
|
| 81 |
+
|
| 82 |
+
LIGANDMPNN_COMMIT = "26ec57ac976ade5379920dbd43c7f97a91cf82de"
|
| 83 |
+
RF3_REVISION = "b02eed6a6bdf8f44d14a80cc36e3da13c9f2291c"
|
| 84 |
+
RF3_CHECKPOINT = "rf3_foundry_01_24_latest_remapped.ckpt"
|
| 85 |
+
# model_type -> the checkpoint run.py expects for it. Both are fetched by
|
| 86 |
+
# environment/fetch_designability_weights.sh.
|
| 87 |
+
LIGANDMPNN_WEIGHTS = {"ligand_mpnn": "ligandmpnn_v_32_010_25.pt",
|
| 88 |
+
"protein_mpnn": "proteinmpnn_v_48_020.pt"}
|
| 89 |
+
BINDER_CHAIN = "A"
|
| 90 |
+
TARGET_CHAIN = "B"
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class ScorerUnavailable(RuntimeError):
|
| 94 |
+
"""Raised when the pipeline cannot run. Never degrades into a zero score."""
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def sequence_of(restypes):
|
| 98 |
+
return "".join(THREE_TO_ONE.get(name, "X") for name in restypes)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _het_atom_name(element, index):
|
| 102 |
+
"""PDB columns 13-16 for a ligand atom. Always exactly four characters.
|
| 103 |
+
|
| 104 |
+
A one-character element sits in column 14 and a two-character element starts in 13,
|
| 105 |
+
so ` C12` is never confused with `CL1`. The index wraps rather than overflowing the
|
| 106 |
+
field: a ligand with more than 999 atoms would otherwise shift every later column,
|
| 107 |
+
and het atom names are never read back - LigandMPNN embeds these atoms by element
|
| 108 |
+
(`getElements()`), not by name.
|
| 109 |
+
"""
|
| 110 |
+
body = f"{index % 100:<2d}" # two digits is all the field has room for
|
| 111 |
+
name = f"{element[:2]}{body}" if len(element) >= 2 else f" {element}{body}"
|
| 112 |
+
assert len(name) == 4, name
|
| 113 |
+
return name
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def verify_assets(assets_root, ligandmpnn_root):
|
| 117 |
+
"""Fail loudly unless every pinned scoring asset is present.
|
| 118 |
+
|
| 119 |
+
Every message names the one command that fixes it, because this runs on whatever
|
| 120 |
+
cluster the operator has and a missing checkpoint must not read as a broken task.
|
| 121 |
+
"""
|
| 122 |
+
assets_root, ligandmpnn_root = Path(assets_root), Path(ligandmpnn_root)
|
| 123 |
+
fetch = ("bash environment/fetch_designability_weights.sh "
|
| 124 |
+
f"{assets_root}")
|
| 125 |
+
|
| 126 |
+
runner = ligandmpnn_root / "run.py"
|
| 127 |
+
if not runner.is_file():
|
| 128 |
+
raise ScorerUnavailable(
|
| 129 |
+
f"LigandMPNN {LIGANDMPNN_COMMIT} is not installed at {ligandmpnn_root}. "
|
| 130 |
+
"Both images COPY it there from environment/evaluation/ligandmpnn, which vendors that "
|
| 131 |
+
"revision; outside an image, point LIGANDMPNN_ROOT at that directory.")
|
| 132 |
+
weights = assets_root / "ligandmpnn_params"
|
| 133 |
+
missing = [name for name in (LIGANDMPNN_WEIGHTS.values())
|
| 134 |
+
if not (weights / name).is_file()]
|
| 135 |
+
if missing:
|
| 136 |
+
raise ScorerUnavailable(
|
| 137 |
+
f"LigandMPNN parameters missing from {weights}: {', '.join(missing)}. "
|
| 138 |
+
f"Run: {fetch}")
|
| 139 |
+
|
| 140 |
+
try:
|
| 141 |
+
import rf3 # noqa: F401
|
| 142 |
+
except ImportError as error:
|
| 143 |
+
raise ScorerUnavailable(
|
| 144 |
+
f"RoseTTAFold3 {RF3_REVISION} is not importable ({error}). Its source is "
|
| 145 |
+
"vendored at environment/evaluation/rf3; put that plus "
|
| 146 |
+
"starter/rfd3/src on PYTHONPATH.")
|
| 147 |
+
checkpoint = assets_root / "rf3" / RF3_CHECKPOINT
|
| 148 |
+
if not checkpoint.is_file():
|
| 149 |
+
raise ScorerUnavailable(
|
| 150 |
+
f"The RoseTTAFold3 checkpoint is not at {checkpoint}. Run: {fetch}")
|
| 151 |
+
|
| 152 |
+
return {"ligandmpnn": str(ligandmpnn_root), "ligandmpnn_params": str(weights),
|
| 153 |
+
"rf3_ckpt": str(checkpoint)}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def resolve_devices(devices=None):
|
| 157 |
+
"""Which GPUs grading may use - one worker per device, in physical ordinals.
|
| 158 |
+
|
| 159 |
+
Every fold and every inverse-folding call is already an isolated subprocess, so the
|
| 160 |
+
only thing needed to use N GPUs is to pin each subprocess to one of them. Ids are
|
| 161 |
+
taken from CUDA_VISIBLE_DEVICES when the environment restricts us, which keeps them
|
| 162 |
+
physical: the CUDA runtime reads that variable afresh in each child, so passing one
|
| 163 |
+
of the parent's ids through selects the same card the parent meant.
|
| 164 |
+
|
| 165 |
+
Returns [None] when no GPU is visible, meaning "inherit the environment" - one
|
| 166 |
+
worker, unpinned, which is the single-GPU behaviour this used to have.
|
| 167 |
+
"""
|
| 168 |
+
if devices:
|
| 169 |
+
return [str(device) for device in devices]
|
| 170 |
+
visible = os.environ.get("CUDA_VISIBLE_DEVICES")
|
| 171 |
+
if visible is not None:
|
| 172 |
+
return [part.strip() for part in visible.split(",") if part.strip()] or [None]
|
| 173 |
+
try:
|
| 174 |
+
import torch
|
| 175 |
+
count = torch.cuda.device_count()
|
| 176 |
+
except Exception: # noqa: BLE001 - no torch, no GPU
|
| 177 |
+
count = 0
|
| 178 |
+
return [str(index) for index in range(count)] or [None]
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class DesignabilityScorer:
|
| 182 |
+
"""Structure -> LigandMPNN sequences -> RoseTTAFold3 complexes -> per-track verdict.
|
| 183 |
+
|
| 184 |
+
Thread-safe across `evaluate` calls: each one leases a GPU for its duration and pins
|
| 185 |
+
its subprocesses to it, so `grader.score_track` can fold `len(self.devices)` designs
|
| 186 |
+
at once. Nothing else is shared - the weights live in the child processes, and every
|
| 187 |
+
call works in its own temporary directory.
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
def __init__(self, assets_root="/assets", ligandmpnn_root="/opt/ligandmpnn",
|
| 191 |
+
timeout=3600, devices=None):
|
| 192 |
+
self.paths = verify_assets(assets_root, ligandmpnn_root)
|
| 193 |
+
self.timeout = timeout
|
| 194 |
+
self.devices = resolve_devices(devices)
|
| 195 |
+
self._free = queue.Queue()
|
| 196 |
+
for device in self.devices:
|
| 197 |
+
self._free.put(device)
|
| 198 |
+
self._leased = threading.local()
|
| 199 |
+
|
| 200 |
+
@contextlib.contextmanager
|
| 201 |
+
def _lease(self):
|
| 202 |
+
"""Hold one GPU for the length of one design's scoring."""
|
| 203 |
+
device = self._free.get()
|
| 204 |
+
self._leased.device = device
|
| 205 |
+
try:
|
| 206 |
+
yield device
|
| 207 |
+
finally:
|
| 208 |
+
self._leased.device = None
|
| 209 |
+
self._free.put(device)
|
| 210 |
+
|
| 211 |
+
def _env(self):
|
| 212 |
+
"""Child environment, pinned to this thread's leased GPU if it has one."""
|
| 213 |
+
env = dict(os.environ)
|
| 214 |
+
device = getattr(self._leased, "device", None)
|
| 215 |
+
if device is not None:
|
| 216 |
+
env["CUDA_VISIBLE_DEVICES"] = str(device)
|
| 217 |
+
return env
|
| 218 |
+
|
| 219 |
+
# ---- inverse folding ------------------------------------------------
|
| 220 |
+
def design_sequences(self, track, structure, context, motif_map):
|
| 221 |
+
"""LigandMPNN sequences for one backbone, with the ligand in context."""
|
| 222 |
+
coordinates, mask, restypes = structure
|
| 223 |
+
count = SEQUENCES_PER_BACKBONE[track]
|
| 224 |
+
with tempfile.TemporaryDirectory() as scratch:
|
| 225 |
+
scratch = Path(scratch)
|
| 226 |
+
target = scratch / "design.pdb"
|
| 227 |
+
write_allatom_pdb(target, coordinates, mask, restypes)
|
| 228 |
+
# LigandMPNN reads het atoms from the same file, so append the ligand.
|
| 229 |
+
ligand = context.get("ligand_coords")
|
| 230 |
+
has_ligand = ligand is not None and np.size(ligand) > 0
|
| 231 |
+
if has_ligand:
|
| 232 |
+
names = context.get("ligand_ccd")
|
| 233 |
+
label = str(names[0]) if names is not None and len(names) else "LIG"
|
| 234 |
+
# LigandMPNN embeds each het atom by ELEMENT
|
| 235 |
+
# (`data_utils.parse_PDB` -> `getElements()` -> `element_dict`), so
|
| 236 |
+
# labelling the whole ligand carbon would hand the model the wrong
|
| 237 |
+
# chemistry. The context carries the real elements; use them.
|
| 238 |
+
elements = context.get("ligand_elements")
|
| 239 |
+
lines = target.read_text().splitlines()
|
| 240 |
+
lines = [line for line in lines if line not in ("TER", "END")]
|
| 241 |
+
for index, position in enumerate(np.asarray(ligand), start=1):
|
| 242 |
+
x, y, z = position
|
| 243 |
+
element = (str(elements[index - 1]).strip().upper()
|
| 244 |
+
if elements is not None and len(elements) >= index
|
| 245 |
+
else "C")
|
| 246 |
+
lines.append(
|
| 247 |
+
f"HETATM{9000 + index:>5d} {_het_atom_name(element, index)}"
|
| 248 |
+
f" {label:<3s} "
|
| 249 |
+
f"L{1:>4d} {x:>8.3f}{y:>8.3f}{z:>8.3f} 1.00 0.00"
|
| 250 |
+
+ " " * 10 + f"{element:>2s}")
|
| 251 |
+
target.write_text("\n".join(lines + ["TER", "END"]) + "\n")
|
| 252 |
+
|
| 253 |
+
# run.py reads the checkpoint belonging to --model_type, and every
|
| 254 |
+
# --checkpoint_* default is RELATIVE ("./model_params/..."). Passing only
|
| 255 |
+
# --checkpoint_ligand_mpnn while selecting protein_mpnn therefore resolves
|
| 256 |
+
# against the current directory and only works if it happens to be the
|
| 257 |
+
# LigandMPNN root. Pass the flag that matches the model.
|
| 258 |
+
model_type = "ligand_mpnn" if has_ligand else "protein_mpnn"
|
| 259 |
+
weights = {"ligand_mpnn": ("--checkpoint_ligand_mpnn",
|
| 260 |
+
"ligandmpnn_v_32_010_25.pt"),
|
| 261 |
+
"protein_mpnn": ("--checkpoint_protein_mpnn",
|
| 262 |
+
"proteinmpnn_v_48_020.pt")}[model_type]
|
| 263 |
+
command = [
|
| 264 |
+
sys.executable, str(Path(self.paths["ligandmpnn"]) / "run.py"),
|
| 265 |
+
"--model_type", model_type,
|
| 266 |
+
weights[0],
|
| 267 |
+
str(Path(self.paths["ligandmpnn_params"]) / weights[1]),
|
| 268 |
+
"--pdb_path", str(target),
|
| 269 |
+
"--out_folder", str(scratch),
|
| 270 |
+
"--batch_size", "1",
|
| 271 |
+
"--number_of_batches", str(count),
|
| 272 |
+
"--temperature", str(SAMPLING_TEMPERATURE),
|
| 273 |
+
"--seed", "37",
|
| 274 |
+
]
|
| 275 |
+
if motif_map:
|
| 276 |
+
# Motif residues keep their declared identities; only the scaffold is
|
| 277 |
+
# redesigned, which is what the enzyme criterion measures.
|
| 278 |
+
fixed = " ".join(f"{BINDER_CHAIN}{index + 1}" for index in sorted(motif_map))
|
| 279 |
+
command += ["--fixed_residues", fixed]
|
| 280 |
+
result = subprocess.run(command, capture_output=True, text=True,
|
| 281 |
+
timeout=self.timeout, env=self._env())
|
| 282 |
+
if result.returncode:
|
| 283 |
+
raise ScorerUnavailable(f"LigandMPNN failed: {result.stderr[-500:]}")
|
| 284 |
+
fasta = list((scratch / "seqs").glob("*.fa"))
|
| 285 |
+
if not fasta:
|
| 286 |
+
raise ScorerUnavailable("LigandMPNN produced no sequences")
|
| 287 |
+
sequences = []
|
| 288 |
+
for line in fasta[0].read_text().splitlines():
|
| 289 |
+
if line and not line.startswith(">"):
|
| 290 |
+
sequences.append(line.strip().split("/")[0])
|
| 291 |
+
# The first record is the input sequence echoed back.
|
| 292 |
+
return (sequences[1:] or sequences)[:count]
|
| 293 |
+
|
| 294 |
+
# ---- complex prediction ---------------------------------------------
|
| 295 |
+
def _components(self, sequence, context, scratch):
|
| 296 |
+
"""RF3 `components` for one designed complex, plus the chains to template."""
|
| 297 |
+
components = [{"seq": sequence, "chain_id": BINDER_CHAIN}]
|
| 298 |
+
templates = []
|
| 299 |
+
|
| 300 |
+
ccd = context.get("ligand_ccd")
|
| 301 |
+
if ccd is not None and len(ccd):
|
| 302 |
+
components += [{"ccd_code": str(code)} for code in ccd]
|
| 303 |
+
|
| 304 |
+
target = context.get("target_coords")
|
| 305 |
+
if target is not None and np.size(target):
|
| 306 |
+
# TEMPLATE the target rather than handing RF3 its bare sequence. A natural
|
| 307 |
+
# target chain does not fold single-sequence - measured predicted-vs-native
|
| 308 |
+
# CA RMSD of 5.3-17.7 A across the five benchmark targets - and an interface
|
| 309 |
+
# scored against an unfolded target is meaningless. RF3 is trained on
|
| 310 |
+
# explicit atomic templates and its docs give templating as the way to fold
|
| 311 |
+
# a chain without an MSA. Measured with the template: target CA RMSD 0.097 A.
|
| 312 |
+
target_pdb = scratch / "target.pdb"
|
| 313 |
+
if not target_pdb.is_file():
|
| 314 |
+
write_allatom_pdb(
|
| 315 |
+
target_pdb, np.asarray(target),
|
| 316 |
+
np.asarray(context["target_mask"], dtype=bool),
|
| 317 |
+
[str(res) for res in context["target_restypes"]],
|
| 318 |
+
chain=TARGET_CHAIN)
|
| 319 |
+
components.append({"path": str(target_pdb)})
|
| 320 |
+
templates.append(TARGET_CHAIN)
|
| 321 |
+
return components, templates
|
| 322 |
+
|
| 323 |
+
def predict_all(self, name, sequences, context, seeds):
|
| 324 |
+
"""Fold every designed sequence in ONE RF3 invocation.
|
| 325 |
+
|
| 326 |
+
Batching matters: RF3 loads a ~2.8 GB checkpoint per process, so folding eight
|
| 327 |
+
sequences as eight subprocesses spends most of its wall clock loading the same
|
| 328 |
+
weights. `inputs` takes a LIST of jobs, so one call covers a whole design.
|
| 329 |
+
|
| 330 |
+
Returns {job name -> [model record, ...]}, in the order given.
|
| 331 |
+
"""
|
| 332 |
+
with tempfile.TemporaryDirectory() as scratch:
|
| 333 |
+
scratch = Path(scratch)
|
| 334 |
+
jobs, names = [], []
|
| 335 |
+
for index, sequence in enumerate(sequences):
|
| 336 |
+
components, templates = self._components(sequence, context, scratch)
|
| 337 |
+
job_name = f"{name}-{index}"
|
| 338 |
+
job = {"name": job_name, "components": components}
|
| 339 |
+
if templates:
|
| 340 |
+
job["template_selection"] = templates
|
| 341 |
+
jobs.append(job)
|
| 342 |
+
names.append(job_name)
|
| 343 |
+
(scratch / "input.json").write_text(json.dumps(jobs))
|
| 344 |
+
|
| 345 |
+
# One seed; RF3 draws `diffusion_batch_size` diffusion samples from it, so
|
| 346 |
+
# that is what carries MODELS_PER_SEQUENCE. `seeds` is the caller's
|
| 347 |
+
# statement of how many models the criterion asks for.
|
| 348 |
+
command = [
|
| 349 |
+
sys.executable, "-c", "from rf3.cli import app; app()", "fold",
|
| 350 |
+
f"inputs={scratch / 'input.json'}",
|
| 351 |
+
f"out_dir={scratch / 'out'}",
|
| 352 |
+
f"ckpt_path={self.paths['rf3_ckpt']}",
|
| 353 |
+
f"diffusion_batch_size={max(1, len(list(seeds)))}",
|
| 354 |
+
"seed=37",
|
| 355 |
+
]
|
| 356 |
+
result = subprocess.run(command, capture_output=True, text=True,
|
| 357 |
+
timeout=self.timeout, env=self._env())
|
| 358 |
+
if result.returncode:
|
| 359 |
+
raise ScorerUnavailable(f"RoseTTAFold3 failed: {result.stderr[-500:]}")
|
| 360 |
+
|
| 361 |
+
out = {}
|
| 362 |
+
for job_name in names:
|
| 363 |
+
# RF3 writes `<name>/seed-N_sample-M/<name>_seed-N_sample-M_model.cif`
|
| 364 |
+
# plus one top-ranked `<name>_model.cif`. Read the SAMPLES: the enzyme
|
| 365 |
+
# criterion is "any of 5 predictor models", and matching only the ranked
|
| 366 |
+
# file silently reduces that to one. `*model.cif` also matches
|
| 367 |
+
# AlphaFold's bare `model.cif`, so either layout works.
|
| 368 |
+
directory = scratch / "out" / job_name
|
| 369 |
+
samples = sorted(directory.rglob("seed-*_sample-*/*model.cif"))
|
| 370 |
+
if not samples:
|
| 371 |
+
samples = sorted(directory.rglob("*_model.cif"))
|
| 372 |
+
out[job_name] = [self._read_model(path) for path in samples]
|
| 373 |
+
return [out[job_name] for job_name in names]
|
| 374 |
+
|
| 375 |
+
def predict(self, name, sequence, context, seeds):
|
| 376 |
+
"""Fold one designed complex. Returns one record per model."""
|
| 377 |
+
return self.predict_all(name, [sequence], context, seeds)[0]
|
| 378 |
+
|
| 379 |
+
def _read_model(self, model_path):
|
| 380 |
+
"""Extract designed-chain coordinates, ligand atoms, ipTM and interface PAE."""
|
| 381 |
+
try:
|
| 382 |
+
import gemmi
|
| 383 |
+
except ImportError as error:
|
| 384 |
+
raise ScorerUnavailable(f"gemmi is required to read predictor output: {error}")
|
| 385 |
+
structure = gemmi.read_structure(str(model_path))
|
| 386 |
+
structure.remove_alternative_conformations()
|
| 387 |
+
structure.remove_hydrogens()
|
| 388 |
+
tabulated = gemmi.find_tabulated_residue
|
| 389 |
+
|
| 390 |
+
backbone, ligand = [], []
|
| 391 |
+
for chain in structure[0]:
|
| 392 |
+
for residue in chain:
|
| 393 |
+
info = tabulated(residue.name)
|
| 394 |
+
if info is not None and info.is_amino_acid():
|
| 395 |
+
if chain.name != BINDER_CHAIN:
|
| 396 |
+
continue
|
| 397 |
+
atoms = {a.name: [a.pos.x, a.pos.y, a.pos.z] for a in residue}
|
| 398 |
+
if {"N", "CA", "C"} <= set(atoms):
|
| 399 |
+
backbone.append({"name": residue.name, "atoms": atoms})
|
| 400 |
+
elif not residue.is_water():
|
| 401 |
+
ligand.extend([a.pos.x, a.pos.y, a.pos.z] for a in residue)
|
| 402 |
+
|
| 403 |
+
# Two layouts: `<name>_model.cif` beside `<name>_summary_confidences.json`,
|
| 404 |
+
# and `seed-N_sample-M/model.cif` beside a bare `summary_confidences.json`.
|
| 405 |
+
stem = model_path.name.replace("_model.cif", "")
|
| 406 |
+
summary = model_path.parent / f"{stem}_summary_confidences.json"
|
| 407 |
+
if not summary.is_file():
|
| 408 |
+
summary = model_path.parent / "summary_confidences.json"
|
| 409 |
+
iptm = interface_pae = None
|
| 410 |
+
if summary.is_file():
|
| 411 |
+
payload = json.loads(summary.read_text())
|
| 412 |
+
iptm = payload.get("iptm")
|
| 413 |
+
pairs = payload.get("chain_pair_pae_min")
|
| 414 |
+
if isinstance(pairs, list) and pairs:
|
| 415 |
+
values = [pairs[i][j] for i in range(len(pairs))
|
| 416 |
+
for j in range(len(pairs[i])) if i != j
|
| 417 |
+
and isinstance(pairs[i][j], (int, float))]
|
| 418 |
+
interface_pae = min(values) if values else None
|
| 419 |
+
return {"backbone": backbone, "ligand": np.array(ligand) if ligand else None,
|
| 420 |
+
"iptm": iptm, "interface_pae": interface_pae}
|
| 421 |
+
|
| 422 |
+
# ---- per-track criteria ---------------------------------------------
|
| 423 |
+
@staticmethod
|
| 424 |
+
def _motif_arrays(residues, indices):
|
| 425 |
+
"""Atom14-shaped coordinates and mask for selected refolded residues."""
|
| 426 |
+
from residues import ATOM14, ATOM14_WIDTH, atom_slot
|
| 427 |
+
coordinates = np.zeros((len(indices), ATOM14_WIDTH, 3))
|
| 428 |
+
mask = np.zeros((len(indices), ATOM14_WIDTH), dtype=bool)
|
| 429 |
+
names = []
|
| 430 |
+
for row, index in enumerate(indices):
|
| 431 |
+
if index >= len(residues):
|
| 432 |
+
return None, None, None
|
| 433 |
+
residue = residues[index]
|
| 434 |
+
names.append(residue["name"])
|
| 435 |
+
if residue["name"] not in ATOM14:
|
| 436 |
+
continue
|
| 437 |
+
for atom, position in residue["atoms"].items():
|
| 438 |
+
slot = atom_slot(residue["name"], atom)
|
| 439 |
+
if slot is not None:
|
| 440 |
+
coordinates[row, slot] = position
|
| 441 |
+
mask[row, slot] = True
|
| 442 |
+
return coordinates, mask, names
|
| 443 |
+
|
| 444 |
+
def _motif_recapitulation(self, model, motif_map, context):
|
| 445 |
+
"""Align refolded motif on N/CA/C, then score all shared motif atoms."""
|
| 446 |
+
reference = context["motif_coords"]
|
| 447 |
+
reference_mask = np.asarray(context["motif_mask"], dtype=bool)
|
| 448 |
+
coordinates, mask, _ = self._motif_arrays(model["backbone"], motif_map)
|
| 449 |
+
if coordinates is None:
|
| 450 |
+
return None
|
| 451 |
+
shared = mask & reference_mask
|
| 452 |
+
frame = shared.copy()
|
| 453 |
+
frame[:, 3:] = False # align on N, CA, C only
|
| 454 |
+
if frame.sum() < 3:
|
| 455 |
+
# These contexts mostly carry fixed catalytic TIP atoms, not backbone: 25 of
|
| 456 |
+
# the 41 enzyme evaluation contexts have fewer than 3 backbone atoms in
|
| 457 |
+
# `motif_mask` (median 1, min 0). Returning None here made the criterion
|
| 458 |
+
# unsatisfiable by construction for 61% of the track. `geometry.py::
|
| 459 |
+
# backbone_aligned_motif_rmsd` has always had this fallback; keep the two
|
| 460 |
+
# in step.
|
| 461 |
+
frame = shared
|
| 462 |
+
if shared.sum() < 3:
|
| 463 |
+
return None
|
| 464 |
+
mobile, target = coordinates[frame], reference[frame]
|
| 465 |
+
offset_mobile, offset_target = mobile.mean(axis=0), target.mean(axis=0)
|
| 466 |
+
rotation = kabsch_rotation(mobile - offset_mobile, target - offset_target)
|
| 467 |
+
moved = (coordinates[shared] - offset_mobile) @ rotation.T + offset_target
|
| 468 |
+
return float(np.sqrt(np.mean(np.sum((moved - reference[shared]) ** 2, axis=1))))
|
| 469 |
+
|
| 470 |
+
@staticmethod
|
| 471 |
+
def _backbone_rmsd_and_transform(model, design_ca):
|
| 472 |
+
"""CA RMSD of a refolded chain against the design, plus the fitted transform."""
|
| 473 |
+
refolded = np.array([r["atoms"]["CA"] for r in model["backbone"]])
|
| 474 |
+
if refolded.shape[0] != design_ca.shape[0] or refolded.shape[0] < 3:
|
| 475 |
+
return None, None
|
| 476 |
+
offset_mobile, offset_target = refolded.mean(axis=0), design_ca.mean(axis=0)
|
| 477 |
+
rotation = kabsch_rotation(refolded - offset_mobile, design_ca - offset_target)
|
| 478 |
+
moved = (refolded - offset_mobile) @ rotation.T + offset_target
|
| 479 |
+
rmsd = float(np.sqrt(np.mean(np.sum((moved - design_ca) ** 2, axis=1))))
|
| 480 |
+
return rmsd, (offset_mobile, rotation, offset_target)
|
| 481 |
+
|
| 482 |
+
def evaluate(self, track, structure, context, motif_map=None):
|
| 483 |
+
"""Run the track's published criterion. Returns a verdict dict."""
|
| 484 |
+
with self._lease():
|
| 485 |
+
return self._evaluate(track, structure, context, motif_map)
|
| 486 |
+
|
| 487 |
+
def _evaluate(self, track, structure, context, motif_map):
|
| 488 |
+
coordinates, mask, restypes = structure
|
| 489 |
+
design_ca = coordinates[:, 1]
|
| 490 |
+
sequences = self.design_sequences(track, structure, context, motif_map)
|
| 491 |
+
seeds = list(range(MODELS_PER_SEQUENCE[track]))
|
| 492 |
+
best = {"passed": False, "sc_rmsd": float("inf"), "iptm": None,
|
| 493 |
+
"interface_pae": None, "ligand_rmsd": None, "motif_rmsd": None,
|
| 494 |
+
"sequences_tried": 0, "reason": "no sequence satisfied the criterion"}
|
| 495 |
+
|
| 496 |
+
# One RF3 call for the whole design, not one per sequence - see predict_all.
|
| 497 |
+
# This does mean every sequence is folded rather than stopping at the first
|
| 498 |
+
# success; the criterion is "any sequence passes", so the verdict is identical.
|
| 499 |
+
folded = self.predict_all("design", sequences, context, seeds)
|
| 500 |
+
|
| 501 |
+
for number, models in enumerate(folded):
|
| 502 |
+
best["sequences_tried"] = number + 1
|
| 503 |
+
for model in models:
|
| 504 |
+
rmsd, transform = self._backbone_rmsd_and_transform(model, design_ca)
|
| 505 |
+
if rmsd is None:
|
| 506 |
+
continue
|
| 507 |
+
record = {"sc_rmsd": rmsd, "iptm": model["iptm"],
|
| 508 |
+
"interface_pae": model["interface_pae"],
|
| 509 |
+
"ligand_rmsd": None, "motif_rmsd": None}
|
| 510 |
+
|
| 511 |
+
if track == "enzyme":
|
| 512 |
+
# Passes on motif recapitulation alone, by any model of any
|
| 513 |
+
# sequence. The ligand-clash half of the criterion is a geometry
|
| 514 |
+
# check on the design and is applied by the grader.
|
| 515 |
+
record["motif_rmsd"] = self._motif_recapitulation(
|
| 516 |
+
model, motif_map or [], context)
|
| 517 |
+
ok = (record["motif_rmsd"] is not None
|
| 518 |
+
and record["motif_rmsd"] <= MOTIF_RMSD_MAX)
|
| 519 |
+
elif track == "sm_binder":
|
| 520 |
+
ligand = context.get("ligand_coords")
|
| 521 |
+
if model["ligand"] is not None and ligand is not None and \
|
| 522 |
+
model["ligand"].shape == np.asarray(ligand).shape:
|
| 523 |
+
origin, rotation, destination = transform
|
| 524 |
+
moved = (model["ligand"] - origin) @ rotation.T + destination
|
| 525 |
+
record["ligand_rmsd"] = float(np.sqrt(np.mean(
|
| 526 |
+
np.sum((moved - np.asarray(ligand)) ** 2, axis=1))))
|
| 527 |
+
ok = (rmsd <= SC_RMSD_MAX
|
| 528 |
+
and record["ligand_rmsd"] is not None
|
| 529 |
+
and record["ligand_rmsd"] <= LIGAND_RMSD_MAX
|
| 530 |
+
and record["interface_pae"] is not None
|
| 531 |
+
and record["interface_pae"] <= INTERFACE_PAE_MAX
|
| 532 |
+
and record["iptm"] is not None
|
| 533 |
+
and record["iptm"] >= IPTM_MIN)
|
| 534 |
+
elif track == "ppi_binder":
|
| 535 |
+
# success.txt gives no PAE threshold for this track; the
|
| 536 |
+
# sm_binder value is reused and flagged as inferred.
|
| 537 |
+
ok = (rmsd <= PPI_RMSD_MAX
|
| 538 |
+
and record["interface_pae"] is not None
|
| 539 |
+
and record["interface_pae"] <= INTERFACE_PAE_MAX)
|
| 540 |
+
else:
|
| 541 |
+
ok = rmsd <= SC_RMSD_MAX
|
| 542 |
+
|
| 543 |
+
if rmsd < best["sc_rmsd"]:
|
| 544 |
+
best.update(record)
|
| 545 |
+
if ok:
|
| 546 |
+
best.update(record)
|
| 547 |
+
best["passed"] = True
|
| 548 |
+
best["reason"] = None
|
| 549 |
+
return best
|
| 550 |
+
return best
|
reproduction/files/18/18303172092c875b81bbb92d12d0c42e94404f0ee430741b1941645320036c5f/physics.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fixed protocols adapted from FAIRChem's MIT-licensed UMA benchmark recipes.
|
| 2 |
+
|
| 3 |
+
See THIRD_PARTY_NOTICES.md and PROTOCOLS.md for source revision and differences.
|
| 4 |
+
The calculator receives geometry only. These routines never open target files.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from ase import units
|
| 11 |
+
from ase.build import make_supercell
|
| 12 |
+
from ase.filters import FrechetCellFilter
|
| 13 |
+
from ase.optimize import FIRE
|
| 14 |
+
from phonopy import Phonopy
|
| 15 |
+
from phonopy.harmonic.dynmat_to_fc import get_commensurate_points
|
| 16 |
+
from phonopy.structure.atoms import PhonopyAtoms
|
| 17 |
+
from pymatgen.analysis.elasticity import DeformedStructureSet, ElasticTensor, Strain
|
| 18 |
+
from pymatgen.core import Structure
|
| 19 |
+
from pymatgen.io.phonopy import get_pmg_structure, get_phonopy_structure
|
| 20 |
+
|
| 21 |
+
from common import decode_atoms, encode_atoms
|
| 22 |
+
|
| 23 |
+
THZ_TO_K = units._hplanck * 1e12 / units._k
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def relax(atoms, calculator, *, fmax=0.02, cell=True):
|
| 27 |
+
atoms.calc = calculator
|
| 28 |
+
optimizer = FIRE(FrechetCellFilter(atoms) if cell else atoms, logfile=None)
|
| 29 |
+
converged = optimizer.run(fmax=fmax, steps=500)
|
| 30 |
+
return {"converged": bool(converged), "steps": optimizer.nsteps}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def discovery(case, calculator):
|
| 34 |
+
atoms = decode_atoms(case["atoms"])
|
| 35 |
+
diagnostics = relax(atoms, calculator)
|
| 36 |
+
return {
|
| 37 |
+
"energy": float(atoms.get_potential_energy()),
|
| 38 |
+
"atoms": encode_atoms(atoms),
|
| 39 |
+
"diagnostics": diagnostics,
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def make_phonon(case):
|
| 44 |
+
atoms = decode_atoms(case["atoms"])
|
| 45 |
+
cell = PhonopyAtoms(
|
| 46 |
+
numbers=atoms.numbers,
|
| 47 |
+
positions=atoms.positions,
|
| 48 |
+
cell=atoms.cell.array,
|
| 49 |
+
masses=case["phonon"]["masses"],
|
| 50 |
+
)
|
| 51 |
+
return Phonopy(
|
| 52 |
+
cell,
|
| 53 |
+
supercell_matrix=case["phonon"]["supercell_matrix"],
|
| 54 |
+
primitive_matrix=case["phonon"]["primitive_matrix"],
|
| 55 |
+
symprec=1e-4,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def phonon_observables(phonon):
|
| 60 |
+
# Same commensurate q-points as upstream; retain negative frequencies.
|
| 61 |
+
qpoints = get_commensurate_points(phonon.supercell_matrix)
|
| 62 |
+
phonon.run_qpoints(qpoints)
|
| 63 |
+
frequencies = phonon.get_qpoints_dict()["frequencies"] * THZ_TO_K
|
| 64 |
+
phonon.run_mesh((20, 20, 20))
|
| 65 |
+
phonon.run_thermal_properties(t_min=0, t_max=600, t_step=75)
|
| 66 |
+
thermal = phonon.get_thermal_properties_dict()
|
| 67 |
+
index = list(thermal["temperatures"]).index(300)
|
| 68 |
+
return {
|
| 69 |
+
"max_freq": float(frequencies.max()),
|
| 70 |
+
"avg_freq": float(frequencies.mean()),
|
| 71 |
+
**{
|
| 72 |
+
key: float(thermal[key][index])
|
| 73 |
+
for key in ("entropy", "heat_capacity", "free_energy")
|
| 74 |
+
},
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def phonons(case, calculator):
|
| 79 |
+
reference_geometry = make_phonon(case) # no DFT force constants
|
| 80 |
+
primitive = get_pmg_structure(reference_geometry.primitive).to_ase_atoms()
|
| 81 |
+
diagnostics = relax(primitive, calculator, fmax=0.005)
|
| 82 |
+
transform = (
|
| 83 |
+
np.linalg.inv(reference_geometry.primitive_matrix.T)
|
| 84 |
+
if reference_geometry.primitive_matrix is not None
|
| 85 |
+
else np.eye(3)
|
| 86 |
+
)
|
| 87 |
+
# Guard against silently truncating a nonintegral transformation.
|
| 88 |
+
if not np.allclose(transform, np.rint(transform), atol=1e-8):
|
| 89 |
+
raise ValueError("Nonintegral primitive-to-unit-cell transformation")
|
| 90 |
+
unitcell = make_supercell(primitive, np.rint(transform).astype(int))
|
| 91 |
+
phonon = Phonopy(
|
| 92 |
+
get_phonopy_structure(Structure.from_ase_atoms(unitcell)),
|
| 93 |
+
reference_geometry.supercell_matrix,
|
| 94 |
+
primitive_matrix=reference_geometry.primitive_matrix,
|
| 95 |
+
symprec=1e-4,
|
| 96 |
+
)
|
| 97 |
+
phonon.generate_displacements(distance=0.01)
|
| 98 |
+
phonon.forces = [
|
| 99 |
+
calculator.get_forces(get_pmg_structure(cell).to_ase_atoms())
|
| 100 |
+
for cell in phonon.supercells_with_displacements
|
| 101 |
+
]
|
| 102 |
+
phonon.produce_force_constants(fc_calculator="traditional")
|
| 103 |
+
# No post-fit force-constant symmetrization, matching the UMA protocol.
|
| 104 |
+
diagnostics.update(
|
| 105 |
+
n_displacements=len(phonon.supercells_with_displacements),
|
| 106 |
+
supercell_atoms=len(phonon.supercell),
|
| 107 |
+
)
|
| 108 |
+
return {**phonon_observables(phonon), "diagnostics": diagnostics}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def elasticity(case, calculator):
|
| 112 |
+
atoms = decode_atoms(case["atoms"])
|
| 113 |
+
diagnostics = relax(atoms, calculator)
|
| 114 |
+
equilibrium_stress = atoms.get_stress(voigt=False)
|
| 115 |
+
deformations = DeformedStructureSet(
|
| 116 |
+
Structure.from_ase_atoms(atoms),
|
| 117 |
+
norm_strains=(-0.01, -0.005, 0.005, 0.01),
|
| 118 |
+
shear_strains=(-0.06, -0.03, 0.03, 0.06),
|
| 119 |
+
)
|
| 120 |
+
stresses, relaxation_results = [], []
|
| 121 |
+
for structure in deformations:
|
| 122 |
+
strained = structure.to_ase_atoms()
|
| 123 |
+
relaxation_results.append(relax(strained, calculator, cell=False))
|
| 124 |
+
stresses.append(strained.get_stress(voigt=False))
|
| 125 |
+
tensor = ElasticTensor.from_independent_strains(
|
| 126 |
+
[Strain.from_deformation(d) for d in deformations.deformations],
|
| 127 |
+
stresses,
|
| 128 |
+
eq_stress=equilibrium_stress,
|
| 129 |
+
)
|
| 130 |
+
diagnostics["strained_relaxations"] = relaxation_results
|
| 131 |
+
return {
|
| 132 |
+
"bulk_modulus_vrh": float(tensor.k_vrh / units.GPa),
|
| 133 |
+
"shear_modulus_vrh": float(tensor.g_vrh / units.GPa),
|
| 134 |
+
"elastic_tensor_GPa": (tensor.voigt / units.GPa).tolist(),
|
| 135 |
+
"diagnostics": diagnostics,
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
CALCULATIONS = {"discovery": discovery, "phonons": phonons, "elasticity": elasticity}
|
reproduction/files/18/18f409937d30e1f78dd33ca4ac2fc24db941a319443551146fb09ad505dfb472/native_settings.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reviewed scalar MAIA settings; never alter geometry or replace native rewards."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
|
| 5 |
+
from protocol import InfrastructureError
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
ATTRIBUTES = {
|
| 9 |
+
"max_episode_steps": "max_episode_steps",
|
| 10 |
+
"substeps_per_action": "num_substeps_per_iteration",
|
| 11 |
+
"max_control": "MAX_CONTROL",
|
| 12 |
+
"omega": "omega",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def validate_settings(settings, horizon, episode_end="native"):
|
| 17 |
+
if episode_end not in ("native", "time_limit"):
|
| 18 |
+
raise InfrastructureError("Unknown reviewed episode_end convention")
|
| 19 |
+
if not isinstance(settings, dict) or set(settings) - ATTRIBUTES.keys():
|
| 20 |
+
raise InfrastructureError("Unknown/invalid reviewed native settings")
|
| 21 |
+
for key, value in settings.items():
|
| 22 |
+
if key in ("max_episode_steps", "substeps_per_action"):
|
| 23 |
+
minimum = 0 if key == "max_episode_steps" else 1
|
| 24 |
+
if type(value) is not int or value < minimum:
|
| 25 |
+
raise InfrastructureError(f"Invalid native setting: {key}")
|
| 26 |
+
elif type(value) not in (int, float) or not math.isfinite(value) or value < 0:
|
| 27 |
+
raise InfrastructureError(f"Invalid native setting: {key}")
|
| 28 |
+
if key == "max_control" and value == 0:
|
| 29 |
+
raise InfrastructureError("Native actuator limit must be positive")
|
| 30 |
+
offset = 1 if episode_end == "native" else 0
|
| 31 |
+
if "max_episode_steps" in settings and settings["max_episode_steps"] + offset != horizon:
|
| 32 |
+
raise InfrastructureError("Native completion setting and reviewed horizon disagree")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def apply_settings(env, case):
|
| 36 |
+
settings = case.get("native_settings", {})
|
| 37 |
+
episode_end = case.get("episode_end", "native")
|
| 38 |
+
validate_settings(settings, case["horizon"], episode_end)
|
| 39 |
+
defaults = {}
|
| 40 |
+
for key, attribute in ATTRIBUTES.items():
|
| 41 |
+
if not hasattr(env, attribute):
|
| 42 |
+
raise InfrastructureError(f"Pinned MAIA attribute missing: {attribute}")
|
| 43 |
+
value = getattr(env, attribute)
|
| 44 |
+
defaults[key] = int(value) if key in ("max_episode_steps", "substeps_per_action") else float(value)
|
| 45 |
+
for key, value in settings.items():
|
| 46 |
+
setattr(env, ATTRIBUTES[key], value)
|
| 47 |
+
effective = {key: settings.get(key, value) for key, value in defaults.items()}
|
| 48 |
+
offset = 1 if episode_end == "native" else 0
|
| 49 |
+
if env.max_episode_steps + offset != case["horizon"]:
|
| 50 |
+
raise InfrastructureError("Native horizon differs from the reviewed release")
|
| 51 |
+
return {"native_defaults": defaults, "effective": effective, "episode_end": episode_end}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def with_episode_limit(env, case):
|
| 55 |
+
"""Apply the same reviewed boundary in training and independent evaluation.
|
| 56 |
+
|
| 57 |
+
Legacy releases keep their native flags. Public StepCounter reconstructions
|
| 58 |
+
leave native max_episode_steps=horizon and truncate before native completion.
|
| 59 |
+
Never hide an early/native failure by relabelling it a timeout.
|
| 60 |
+
"""
|
| 61 |
+
if case.get("episode_end", "native") == "native":
|
| 62 |
+
return env
|
| 63 |
+
validate_settings(case.get("native_settings", {}), case["horizon"], case["episode_end"])
|
| 64 |
+
import gymnasium as gym
|
| 65 |
+
|
| 66 |
+
class ReviewedTimeLimit(gym.Wrapper):
|
| 67 |
+
def __init__(self):
|
| 68 |
+
super().__init__(env)
|
| 69 |
+
self.count = None
|
| 70 |
+
self.reviewed_protocol = env.reviewed_protocol
|
| 71 |
+
|
| 72 |
+
def reset(self, **kwargs):
|
| 73 |
+
result = self.env.reset(**kwargs)
|
| 74 |
+
self.count = 0
|
| 75 |
+
return result
|
| 76 |
+
|
| 77 |
+
def step(self, action):
|
| 78 |
+
if self.count is None or self.count >= case["horizon"]:
|
| 79 |
+
raise InfrastructureError("Reset is required before another reviewed episode")
|
| 80 |
+
observation, reward, terminated, truncated, info = self.env.step(action)
|
| 81 |
+
self.count += 1
|
| 82 |
+
if terminated or truncated:
|
| 83 |
+
raise InfrastructureError("Native completion preceded the reviewed external time limit")
|
| 84 |
+
return observation, reward, False, self.count == case["horizon"], info
|
| 85 |
+
|
| 86 |
+
return ReviewedTimeLimit()
|
reproduction/files/1a/1a17e381a1e20dff632e5a127d68deafe4786c27271e64de619787dff4f841c2/native_verifier.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Execute frozen upstream verifier entrypoints in credential-free Beaker jobs.
|
| 2 |
+
|
| 3 |
+
Prediction and trusted grading use separate jobs and mounts. Folding retains its
|
| 4 |
+
upstream single-process replay and is explicitly NOT called label-isolated.
|
| 5 |
+
No scientific verifier functions are replaced or monkey-patched.
|
| 6 |
+
"""
|
| 7 |
+
import ctypes
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import pwd
|
| 13 |
+
import platform
|
| 14 |
+
import re
|
| 15 |
+
import shutil
|
| 16 |
+
import signal
|
| 17 |
+
import socket
|
| 18 |
+
import subprocess
|
| 19 |
+
import sys
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
import gpu_access
|
| 23 |
+
import runtime
|
| 24 |
+
import sealed_sandbox
|
| 25 |
+
|
| 26 |
+
STATE = Path('/phase-state')
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def enter_offline_namespace():
|
| 30 |
+
import offline_network
|
| 31 |
+
record = offline_network.configure(STATE)
|
| 32 |
+
libc = ctypes.CDLL(None, use_errno=True)
|
| 33 |
+
for name, flag in (('user', offline_network.CLONE_NEWUSER), ('net', offline_network.CLONE_NEWNET)):
|
| 34 |
+
fd = os.open(f'/proc/{record["pid"]}/ns/{name}', os.O_RDONLY | os.O_CLOEXEC)
|
| 35 |
+
try:
|
| 36 |
+
if libc.setns(fd, flag):
|
| 37 |
+
raise OSError(ctypes.get_errno(), 'enter offline verifier namespace')
|
| 38 |
+
finally:
|
| 39 |
+
os.close(fd)
|
| 40 |
+
if socket.if_nameindex() != [(1, 'lo')]:
|
| 41 |
+
raise RuntimeError('Offline verifier namespace has external interfaces')
|
| 42 |
+
return record
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def validate_ready_marker(sealed_root):
|
| 46 |
+
"""Accept either upstream seal format, always checking the exact snapshot.
|
| 47 |
+
|
| 48 |
+
Surface-code uses JSON with a run ID. Molecular, Genome and Protein-sequence
|
| 49 |
+
use a plain SHA-256 line. The original scientific grader rechecks the seal.
|
| 50 |
+
"""
|
| 51 |
+
root = Path(sealed_root)
|
| 52 |
+
raw = (root/'READY').read_text().strip()
|
| 53 |
+
snapshot = root/'run/snapshot.json'
|
| 54 |
+
observed = hashlib.sha256(snapshot.read_bytes()).hexdigest()
|
| 55 |
+
if re.fullmatch('[0-9a-f]{64}', raw):
|
| 56 |
+
if raw != observed:
|
| 57 |
+
raise RuntimeError('Native seal marker is inconsistent')
|
| 58 |
+
return
|
| 59 |
+
marker = json.loads(raw)
|
| 60 |
+
if (not isinstance(marker, dict) or marker.get('snapshot_sha256') != observed
|
| 61 |
+
or not isinstance(marker.get('run_id'), str)
|
| 62 |
+
or json.loads(snapshot.read_text()).get('run_id') != marker['run_id']):
|
| 63 |
+
raise RuntimeError('Native seal marker is inconsistent')
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def run_until_sealed(command, log, seconds, sealed_root=Path('/sealed')):
|
| 67 |
+
"""End the native waiting supervisor only after its authenticated seal."""
|
| 68 |
+
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
| 69 |
+
deadline = time.monotonic() + seconds
|
| 70 |
+
sealed_ready = False
|
| 71 |
+
try:
|
| 72 |
+
while process.poll() is None:
|
| 73 |
+
if (sealed_root / 'READY').is_file():
|
| 74 |
+
validate_ready_marker(sealed_root)
|
| 75 |
+
sealed_ready = True
|
| 76 |
+
break
|
| 77 |
+
if time.monotonic() >= deadline:
|
| 78 |
+
raise TimeoutError('Verifier inference budget exhausted')
|
| 79 |
+
time.sleep(.1)
|
| 80 |
+
finally:
|
| 81 |
+
if process.poll() is None:
|
| 82 |
+
os.killpg(process.pid, signal.SIGTERM)
|
| 83 |
+
try:
|
| 84 |
+
process.wait(timeout=30)
|
| 85 |
+
except subprocess.TimeoutExpired:
|
| 86 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 87 |
+
process.wait()
|
| 88 |
+
return subprocess.CompletedProcess(command, 0 if sealed_ready else process.returncode)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def status(phase, **details):
|
| 92 |
+
runtime.write_json(STATE / 'status.json', {'phase': phase, 'unix': time.time(), **details})
|
| 93 |
+
print(json.dumps({'phase': phase, **details}), flush=True)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def copy_readonly_benchmark(source, destination, verify_contents=False):
|
| 97 |
+
"""Change permissions only on a private local copy of the input mount."""
|
| 98 |
+
source, destination = Path(source), Path(destination)
|
| 99 |
+
if destination.exists():
|
| 100 |
+
raise RuntimeError('Expected a fresh local benchmark directory')
|
| 101 |
+
shutil.copytree(source, destination, symlinks=False)
|
| 102 |
+
hashes = {}
|
| 103 |
+
def digest_file(path):
|
| 104 |
+
digest = hashlib.sha256()
|
| 105 |
+
with path.open('rb') as stream:
|
| 106 |
+
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
| 107 |
+
digest.update(block)
|
| 108 |
+
return digest.hexdigest()
|
| 109 |
+
for path in [destination, *destination.rglob('*')]:
|
| 110 |
+
path.chmod(0o555 if path.is_dir() else 0o444)
|
| 111 |
+
if verify_contents and path.is_file():
|
| 112 |
+
relative = path.relative_to(destination)
|
| 113 |
+
digest = digest_file(path)
|
| 114 |
+
if digest_file(source / relative) != digest:
|
| 115 |
+
raise RuntimeError(f'Local benchmark copy differs: {relative}')
|
| 116 |
+
hashes[str(relative)] = digest
|
| 117 |
+
return dict(source_permissions_modified=False, verified_file_sha256=hashes)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def main(phase):
|
| 121 |
+
entered = time.monotonic()
|
| 122 |
+
plan = json.loads(Path('/operator/plan.json').read_text())
|
| 123 |
+
cfg = plan['phases'][phase]
|
| 124 |
+
adapted = cfg.get('adapted_permissions', False)
|
| 125 |
+
if adapted:
|
| 126 |
+
import adapted_boundary
|
| 127 |
+
adapted_boundary.no_new_privileges()
|
| 128 |
+
os.setgroups([])
|
| 129 |
+
STATE.chmod(0o755)
|
| 130 |
+
kernel_features = {'kernel': platform.release(),
|
| 131 |
+
'landlock_abi': ctypes.CDLL(None, use_errno=True).syscall(444, 0, 0, 1)}
|
| 132 |
+
runtime.write_json(STATE / 'kernel-features.json', kernel_features)
|
| 133 |
+
status('preflight', task=plan['task'], role=phase, **kernel_features)
|
| 134 |
+
for key in list(os.environ):
|
| 135 |
+
if any(word in key.upper() for word in ('API_KEY', 'TOKEN', 'SECRET')):
|
| 136 |
+
os.environ.pop(key, None)
|
| 137 |
+
os.environ.update(PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1',
|
| 138 |
+
HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', PIP_NO_INDEX='1',
|
| 139 |
+
HF_HOME='/tmp/huggingface', MPLCONFIGDIR='/tmp/matplotlib',
|
| 140 |
+
XDG_CACHE_HOME='/tmp/verifier-cache',
|
| 141 |
+
NUMBA_CACHE_DIR='/tmp/verifier-cache/numba',
|
| 142 |
+
TRITON_CACHE_DIR='/tmp/verifier-cache/triton',
|
| 143 |
+
TORCH_EXTENSIONS_DIR='/tmp/verifier-cache/torch-extensions',
|
| 144 |
+
CUDA_CACHE_PATH='/tmp/verifier-cache/cuda')
|
| 145 |
+
os.environ.update(cfg.get('environment', {}))
|
| 146 |
+
crystal_cache_receipt = None
|
| 147 |
+
if cfg.get('isolated_crystal_dataset_cache'):
|
| 148 |
+
if plan['task'] != 'crystal-structure-generation' or phase != 'score':
|
| 149 |
+
raise RuntimeError('Crystal cache isolation is for trusted grading only')
|
| 150 |
+
import crystal_cache
|
| 151 |
+
crystal_cache_receipt = crystal_cache.prepare(
|
| 152 |
+
'/scorer-assets/huggingface/datasets', os.environ['HF_DATASETS_CACHE'])
|
| 153 |
+
crystal_cache_receipt['asset_manifest_sha256'] = hashlib.sha256(
|
| 154 |
+
Path('/scorer-assets/READY.json').read_bytes()).hexdigest()
|
| 155 |
+
runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt)
|
| 156 |
+
for rel, expected in plan['verifier_source_sha256'].items():
|
| 157 |
+
if hashlib.sha256((Path('/operator/task') / rel).read_bytes()).hexdigest() != expected:
|
| 158 |
+
raise RuntimeError(f'Frozen verifier source changed: {rel}')
|
| 159 |
+
offline = enter_offline_namespace() if cfg.get('loopback_namespace') else None
|
| 160 |
+
cpus = cfg['cpu_count']
|
| 161 |
+
affinity = sorted(os.sched_getaffinity(0))
|
| 162 |
+
if len(affinity) < cpus:
|
| 163 |
+
raise RuntimeError('Insufficient allocated CPUs')
|
| 164 |
+
os.sched_setaffinity(0, affinity[:cpus])
|
| 165 |
+
memory = sealed_sandbox.allocated_memory_limit()
|
| 166 |
+
if memory < cfg['memory_gib'] * 1024**3:
|
| 167 |
+
raise RuntimeError('Insufficient allocated RAM')
|
| 168 |
+
if cfg.get('local_benchmark_copy'):
|
| 169 |
+
status('copying_benchmark', task=plan['task'], role=phase)
|
| 170 |
+
# The GPU Landlock policy grants existing root children. Create this
|
| 171 |
+
# local root child first, so the later policy can grant it read access.
|
| 172 |
+
# This is trusted input staging; no submitted code has run yet.
|
| 173 |
+
receipt = copy_readonly_benchmark('/source-benchmark', '/benchmark',
|
| 174 |
+
cfg.get('verify_benchmark_copy', False))
|
| 175 |
+
runtime.write_json(STATE / 'benchmark-copy.json', receipt)
|
| 176 |
+
gpu_policy = None
|
| 177 |
+
if cfg['accessible_gpus']:
|
| 178 |
+
gpu_policy = gpu_access.configure(STATE, count=cfg['accessible_gpus'], strict_allocation=adapted)
|
| 179 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpu_policy['allowed_uuids'])
|
| 180 |
+
if adapted:
|
| 181 |
+
adapted_boundary.exact_gpu_allocation(gpu_policy)
|
| 182 |
+
else:
|
| 183 |
+
gpu_access.restrict_device_access(gpu_policy['denied_devices'])
|
| 184 |
+
if cfg.get('gpu_runtime', 'torch') == 'torch' and not adapted:
|
| 185 |
+
import torch
|
| 186 |
+
if torch.cuda.device_count() != cfg['accessible_gpus'] or not all(
|
| 187 |
+
'H100' in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())):
|
| 188 |
+
raise RuntimeError('Verifier did not receive the required H100 devices')
|
| 189 |
+
else:
|
| 190 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = ''
|
| 191 |
+
if phase == 'inference':
|
| 192 |
+
status('copying_submission', task=plan['task'], role=phase)
|
| 193 |
+
if cfg.get('native_uid_isolation'):
|
| 194 |
+
# The original PDE verifier explicitly supports this UID fallback.
|
| 195 |
+
# The mount is below a local root-only parent, never chmod shared data.
|
| 196 |
+
Path('/private').chmod(0o700)
|
| 197 |
+
Path('/tests').chmod(0o700)
|
| 198 |
+
elif plan['task'] != 'protein-folding-prediction':
|
| 199 |
+
for path in ('/private', '/labels'):
|
| 200 |
+
if Path(path).is_dir() and any(Path(path).iterdir()):
|
| 201 |
+
raise RuntimeError('Private labels unexpectedly mounted into inference')
|
| 202 |
+
package = Path('/workspace/submission')
|
| 203 |
+
if package.exists():
|
| 204 |
+
raise RuntimeError('Expected a fresh local submission directory')
|
| 205 |
+
shutil.copytree('/submission-source', package, symlinks=True)
|
| 206 |
+
status('checking_submission', task=plan['task'], role=phase)
|
| 207 |
+
if runtime.fingerprint(package) != plan['submission_sha256']:
|
| 208 |
+
raise RuntimeError('Frozen submission fingerprint mismatch')
|
| 209 |
+
try:
|
| 210 |
+
agent = pwd.getpwnam('agent')
|
| 211 |
+
except KeyError:
|
| 212 |
+
try:
|
| 213 |
+
agent = pwd.getpwuid(10001)
|
| 214 |
+
except KeyError:
|
| 215 |
+
subprocess.run(['/usr/sbin/useradd', '--create-home', '--uid', '10001', 'agent'], check=True)
|
| 216 |
+
agent = pwd.getpwnam('agent')
|
| 217 |
+
if agent.pw_uid != 10001:
|
| 218 |
+
raise RuntimeError('Unexpected inference user identity')
|
| 219 |
+
status('setting_submission_permissions', task=plan['task'], role=phase)
|
| 220 |
+
for path in [package, *package.rglob('*')]:
|
| 221 |
+
os.chown(path, agent.pw_uid, agent.pw_gid, follow_symlinks=False)
|
| 222 |
+
Path('/logs').mkdir(exist_ok=True)
|
| 223 |
+
# Some native images precreate this empty container-local mountpoint.
|
| 224 |
+
# rmdir fails closed if it contains anything; never remove existing logs.
|
| 225 |
+
if Path('/logs/verifier').is_dir() and not Path('/logs/verifier').is_symlink():
|
| 226 |
+
Path('/logs/verifier').rmdir()
|
| 227 |
+
Path('/logs/verifier').symlink_to(STATE / 'results', target_is_directory=True)
|
| 228 |
+
(STATE / 'results').mkdir()
|
| 229 |
+
if adapted and cfg.get('network_policy') != 'policy-children-only':
|
| 230 |
+
adapted_boundary.restrict_network()
|
| 231 |
+
elif not offline and not adapted:
|
| 232 |
+
runtime.deny_network()
|
| 233 |
+
if not adapted:
|
| 234 |
+
writable_roots = ['/phase-state', '/sealed', '/logs', '/workspace', '/tmp', '/dev', '/home', '/proc',
|
| 235 |
+
*cfg.get('writable_runtime_paths', [])]
|
| 236 |
+
if crystal_cache_receipt:
|
| 237 |
+
# The native image links /scorer-assets beneath /workspace. A
|
| 238 |
+
# writable ancestor defeats a read-only Landlock child rule.
|
| 239 |
+
# Trusted grading needs its output and scratch directories only.
|
| 240 |
+
writable_roots.remove('/workspace')
|
| 241 |
+
sealed_sandbox.filesystem(
|
| 242 |
+
readonly=['/operator', '/submission-source', '/benchmark', '/private', '/labels',
|
| 243 |
+
'/evaluation', '/tests', '/usr', '/bin', '/sbin', '/lib', '/lib64',
|
| 244 |
+
'/opt', '/etc', '/sys', '/run', '/data', '/scorer-assets',
|
| 245 |
+
*cfg.get('readonly_runtime_paths', [])],
|
| 246 |
+
# NVIDIA initialization requires writable procfs, as in the existing
|
| 247 |
+
# sealed adapter. Beaker's procfs protections and the upstream UID
|
| 248 |
+
# boundary still apply. Weka inputs and operator files stay read-only.
|
| 249 |
+
writable=writable_roots)
|
| 250 |
+
# Root also inherits the write restriction; this protects Weka source mounts
|
| 251 |
+
# even for the upstream folding evaluator, which does not drop privileges.
|
| 252 |
+
if adapted:
|
| 253 |
+
source_audit = adapted_boundary.audit_source_permissions(
|
| 254 |
+
['/operator', '/submission-source', '/source-benchmark', '/benchmark', '/data', '/labels', '/private'],
|
| 255 |
+
untrusted_uids=tuple(range(10001, 10009)))
|
| 256 |
+
else:
|
| 257 |
+
try:
|
| 258 |
+
Path('/operator/.write-probe').write_text('must be denied')
|
| 259 |
+
except PermissionError:
|
| 260 |
+
pass
|
| 261 |
+
else:
|
| 262 |
+
raise RuntimeError('Operator source mount is writable')
|
| 263 |
+
if crystal_cache_receipt:
|
| 264 |
+
try:
|
| 265 |
+
fd = os.open('/scorer-assets/READY.json', os.O_WRONLY | os.O_CLOEXEC)
|
| 266 |
+
except PermissionError:
|
| 267 |
+
crystal_cache_receipt['asset_write_denied'] = True
|
| 268 |
+
else:
|
| 269 |
+
os.close(fd)
|
| 270 |
+
raise RuntimeError('Prepared scorer assets remain writable')
|
| 271 |
+
runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt)
|
| 272 |
+
if cfg['accessible_gpus']:
|
| 273 |
+
# Test a fresh CUDA process AFTER all restrictions, with the same UID
|
| 274 |
+
# used by the native verifier. A parent probe before Landlock can pass
|
| 275 |
+
# while the actual inference child cannot initialize CUDA.
|
| 276 |
+
uid = 0 if plan['task'] == 'protein-folding-prediction' and not adapted else 10001
|
| 277 |
+
def demote_probe():
|
| 278 |
+
if uid:
|
| 279 |
+
os.setgid(uid)
|
| 280 |
+
os.setuid(uid)
|
| 281 |
+
probe = (
|
| 282 |
+
'import torch; '
|
| 283 |
+
f'assert torch.cuda.device_count() == {cfg["accessible_gpus"]}; '
|
| 284 |
+
'assert all("H100" in torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())); '
|
| 285 |
+
'assert all((torch.ones(4, device=f"cuda:{i}") * 2).sum().item() == 8 '
|
| 286 |
+
'for i in range(torch.cuda.device_count())); '
|
| 287 |
+
'print("CUDA_AFTER_SANDBOX_OK")')
|
| 288 |
+
if cfg.get('gpu_runtime') == 'jax':
|
| 289 |
+
probe = ('import jax; import jax.numpy as jnp; '
|
| 290 |
+
f'assert len(jax.devices("gpu")) == {cfg["accessible_gpus"]}; '
|
| 291 |
+
'assert all("H100" in d.device_kind for d in jax.devices("gpu")); '
|
| 292 |
+
'assert all(float(jnp.sum(jax.device_put(jnp.ones(4),d)*2)) == 8 '
|
| 293 |
+
'for d in jax.devices("gpu")); print("JAX_CUDA_AFTER_SANDBOX_OK")')
|
| 294 |
+
probe_env = {'PATH': '/opt/conda/bin:/opt/venv/bin:/usr/local/bin:/usr/bin:/bin',
|
| 295 |
+
'HOME': '/root' if uid == 0 else pwd.getpwuid(uid).pw_dir,
|
| 296 |
+
'CUDA_VISIBLE_DEVICES': os.environ['CUDA_VISIBLE_DEVICES'],
|
| 297 |
+
'PYTHONDONTWRITEBYTECODE': '1'}
|
| 298 |
+
if adapted and plan['task'] == 'fluid-flow-control':
|
| 299 |
+
# native_runtime.sh loads a module-provided libpython. Preserve
|
| 300 |
+
# only these runtime settings, never credentials, in the probe.
|
| 301 |
+
for key in ('PATH', 'LD_LIBRARY_PATH', 'OMP_NUM_THREADS',
|
| 302 |
+
'OPENBLAS_NUM_THREADS', 'XLA_PYTHON_CLIENT_PREALLOCATE'):
|
| 303 |
+
if key in os.environ:
|
| 304 |
+
probe_env[key] = os.environ[key]
|
| 305 |
+
with (STATE / 'gpu-child-probe.log').open('w') as log:
|
| 306 |
+
subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', probe], env=probe_env,
|
| 307 |
+
preexec_fn=demote_probe, stdout=log, stderr=subprocess.STDOUT,
|
| 308 |
+
timeout=120, check=True)
|
| 309 |
+
if cfg.get('dependency_probe'):
|
| 310 |
+
# Exercise the original runtime imports under the final restrictions
|
| 311 |
+
# before spending time loading test data. Cache files belong in /tmp,
|
| 312 |
+
# while installed libraries and frozen source mounts remain read-only.
|
| 313 |
+
with (STATE / 'dependency-probe.log').open('w') as log:
|
| 314 |
+
def dependency_identity():
|
| 315 |
+
os.setgroups([]); os.setgid(10001); os.setuid(10001)
|
| 316 |
+
if cfg.get('untrusted_whole_verifier'):
|
| 317 |
+
cache=Path('/tmp/verifier-cache');cache.mkdir(exist_ok=True)
|
| 318 |
+
os.chown(cache,10001,10001)
|
| 319 |
+
subprocess.run([cfg.get('driver_python', cfg['command'][0]), '-c', cfg['dependency_probe']],
|
| 320 |
+
stdout=log, stderr=subprocess.STDOUT, timeout=180, check=True,
|
| 321 |
+
preexec_fn=dependency_identity if cfg.get('untrusted_whole_verifier') else None)
|
| 322 |
+
receipt = {'task': plan['task'], 'role': phase, 'cpu_affinity': sorted(os.sched_getaffinity(0)),
|
| 323 |
+
'kernel_features': kernel_features,
|
| 324 |
+
'gpu_policy': gpu_policy, 'requested_memory_gib': cfg['memory_gib'],
|
| 325 |
+
'allocated_memory_bytes': memory, 'strict_benchmark_ram_cap': False,
|
| 326 |
+
'network': ('seccomp in unprivileged policy children; trusted simulator retains MPI sockets'
|
| 327 |
+
if cfg.get('network_policy') == 'policy-children-only' else
|
| 328 |
+
'isolated loopback namespace' if offline else 'IPv4/IPv6 socket creation denied; inherited by children'),
|
| 329 |
+
'offline_namespace': offline,
|
| 330 |
+
'source_mounts': f'POSIX permission audit ({source_audit} entries); non-root submission' if adapted else 'Landlock read-only',
|
| 331 |
+
'gpu_child_probe': 'passed after sandbox' if cfg['accessible_gpus'] else 'not applicable',
|
| 332 |
+
'dependency_probe': 'passed' if cfg.get('dependency_probe') else 'not requested',
|
| 333 |
+
'cache_environment': {key: os.environ[key] for key in (
|
| 334 |
+
'XDG_CACHE_HOME', 'NUMBA_CACHE_DIR', 'TRITON_CACHE_DIR',
|
| 335 |
+
'TORCH_EXTENSIONS_DIR', 'CUDA_CACHE_PATH')},
|
| 336 |
+
'label_isolated': plan.get('label_isolated', plan['task'] != 'protein-folding-prediction'),
|
| 337 |
+
'adapted_execution': adapted,
|
| 338 |
+
'scientific_scorer_modified': False}
|
| 339 |
+
runtime.write_json(STATE / 'preflight.json', receipt)
|
| 340 |
+
status('verifying', task=plan['task'], role=phase)
|
| 341 |
+
start = time.monotonic()
|
| 342 |
+
with (STATE / 'verifier.log').open('w') as log:
|
| 343 |
+
remaining = cfg['timeout_seconds'] - (time.monotonic() - entered)
|
| 344 |
+
if remaining <= 0:
|
| 345 |
+
raise TimeoutError('Verifier budget exhausted during initialization')
|
| 346 |
+
if cfg.get('stop_after_sealed_ready'):
|
| 347 |
+
# The native supervisor has already killed all model processes and
|
| 348 |
+
# sealed/hashes its predictions before writing READY. End only its
|
| 349 |
+
# wait-for-grader loop; the unchanged grader runs in a separate job.
|
| 350 |
+
result = run_until_sealed(cfg['command'], log, remaining)
|
| 351 |
+
else:
|
| 352 |
+
def run_identity():
|
| 353 |
+
os.setgroups([])
|
| 354 |
+
os.setgid(10001)
|
| 355 |
+
os.setuid(10001)
|
| 356 |
+
if cfg.get('untrusted_whole_verifier'):
|
| 357 |
+
os.chown(STATE / 'results', 10001, 10001)
|
| 358 |
+
result = subprocess.run(cfg['command'], stdout=log, stderr=subprocess.STDOUT,
|
| 359 |
+
timeout=remaining, start_new_session=True,
|
| 360 |
+
preexec_fn=run_identity if cfg.get('untrusted_whole_verifier') else None)
|
| 361 |
+
if result.returncode:
|
| 362 |
+
raise RuntimeError(f'Original verifier exited with status {result.returncode}; inspect verifier.log')
|
| 363 |
+
if cfg.get('verify_crystal_assets_after'):
|
| 364 |
+
remaining = cfg['timeout_seconds'] - (time.monotonic() - entered)
|
| 365 |
+
if remaining <= 0:
|
| 366 |
+
raise TimeoutError('Verifier budget exhausted before post-score asset validation')
|
| 367 |
+
with (STATE / 'asset-validation-after.log').open('w') as log:
|
| 368 |
+
subprocess.run([cfg['driver_python'], '-c',
|
| 369 |
+
'import sys;sys.path.insert(0,"/tests");from pathlib import Path;'
|
| 370 |
+
'from grader import validate_assets;validate_assets(Path("/scorer-assets"));'
|
| 371 |
+
'print("ORIGINAL_SCORER_ASSET_DIGEST_OK")'],
|
| 372 |
+
stdout=log, stderr=subprocess.STDOUT, timeout=remaining, check=True)
|
| 373 |
+
if hashlib.sha256(Path('/scorer-assets/READY.json').read_bytes()).hexdigest() != crystal_cache_receipt['asset_manifest_sha256']:
|
| 374 |
+
raise RuntimeError('Scorer asset manifest changed during grading')
|
| 375 |
+
crystal_cache_receipt['original_asset_digest_after'] = 'passed'
|
| 376 |
+
runtime.write_json(STATE / 'dataset-cache.json', crystal_cache_receipt)
|
| 377 |
+
elapsed = time.monotonic() - entered
|
| 378 |
+
reward_path = STATE / 'results/reward.json'
|
| 379 |
+
if phase == 'score':
|
| 380 |
+
score_root = Path('/sealed/results')
|
| 381 |
+
if cfg.get('results_by_run_id'):
|
| 382 |
+
score_root /= json.loads(Path('/sealed/READY').read_text())['run_id']
|
| 383 |
+
for name in ('reward.json', 'report.json', 'agent_feedback.json'):
|
| 384 |
+
source = score_root / name
|
| 385 |
+
if source.exists():
|
| 386 |
+
shutil.copy2(source, STATE / 'results' / name)
|
| 387 |
+
reward = json.loads(reward_path.read_text()) if reward_path.exists() else None
|
| 388 |
+
ready = Path('/sealed/READY').is_file()
|
| 389 |
+
if reward is None and not (phase == 'inference' and ready):
|
| 390 |
+
raise RuntimeError('Verifier produced neither a reward nor sealed predictions')
|
| 391 |
+
status('complete', task=plan['task'], role=phase, elapsed_seconds=elapsed,
|
| 392 |
+
reward=reward, sealed_ready=ready)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
if __name__ == '__main__':
|
| 396 |
+
try:
|
| 397 |
+
main(sys.argv[1])
|
| 398 |
+
except Exception as error:
|
| 399 |
+
status('failed', error=f'{type(error).__name__}: {error}')
|
| 400 |
+
raise
|
reproduction/files/1c/1c96f70bde6addcf83179c92f5e5a0a4b2aeb5c8bed1c5bfea6a5a167ff575b1/grader.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Trusted labels-only service; never executes a submitted model or source."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
from typing import Any
|
| 10 |
+
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
|
| 11 |
+
sys.path.insert(0, str(PROJECT))
|
| 12 |
+
from qecbench.data import contained, sha256, write_json
|
| 13 |
+
from qecbench.scoring import InvalidPrediction, score
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def grade(sealed: Path, inputs: Path, labels: Path, config: Path, output: Path,
|
| 17 |
+
ready: dict[str, Any]) -> None:
|
| 18 |
+
run_id = ready["run_id"]
|
| 19 |
+
target = output / run_id
|
| 20 |
+
target.mkdir(parents=True)
|
| 21 |
+
try:
|
| 22 |
+
snapshot_path = contained(sealed, "snapshot.json")
|
| 23 |
+
if sha256(snapshot_path) != ready["snapshot_sha256"]:
|
| 24 |
+
raise ValueError("Sealed snapshot hash mismatch")
|
| 25 |
+
snapshot = json.loads(snapshot_path.read_text())
|
| 26 |
+
if snapshot.get("schema") != "surface-code-decoding-snapshot/v1" or snapshot.get("run_id") != run_id:
|
| 27 |
+
raise ValueError("Sealed snapshot identity mismatch")
|
| 28 |
+
if snapshot.get("input_manifest_sha256") != sha256(inputs / "manifest.json"):
|
| 29 |
+
raise ValueError("Input/snapshot mismatch")
|
| 30 |
+
actual = {path.name for path in sealed.iterdir() if path.name != "snapshot.json"}
|
| 31 |
+
if actual != set(snapshot["files"]):
|
| 32 |
+
raise ValueError("Sealed snapshot file coverage mismatch")
|
| 33 |
+
for name, digest in snapshot["files"].items():
|
| 34 |
+
if sha256(contained(sealed, name)) != digest:
|
| 35 |
+
raise ValueError("Sealed prediction checksum mismatch")
|
| 36 |
+
try:
|
| 37 |
+
result = score(inputs, sealed, labels, config)
|
| 38 |
+
except InvalidPrediction as error:
|
| 39 |
+
result = {"schema": "surface-code-decoding-report/v1", "status": "invalid_prediction",
|
| 40 |
+
"model_quality_measured": False, "score": 0.0, "score_unclipped": None,
|
| 41 |
+
"performance": None, "error": str(error)}
|
| 42 |
+
result["run_id"] = run_id
|
| 43 |
+
write_json(target / "report.json", result)
|
| 44 |
+
write_json(target / "reward.json", {"reward": result["performance"]}) # raw P; the normalized score stays in report.json
|
| 45 |
+
except Exception as error:
|
| 46 |
+
write_json(target / "report.json", {"schema": "surface-code-decoding-report/v1", "run_id": run_id,
|
| 47 |
+
"status": "infrastructure_error", "model_quality_measured": False,
|
| 48 |
+
"error": f"{type(error).__name__}: {error}"})
|
| 49 |
+
write_json(target / "DONE", {"run_id": run_id})
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def main() -> None:
|
| 53 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 54 |
+
parser.add_argument("--sealed", type=Path, default=Path("/sealed/run"))
|
| 55 |
+
parser.add_argument("--input", type=Path, default=Path("/benchmark"))
|
| 56 |
+
parser.add_argument("--labels", type=Path, default=Path("/private"))
|
| 57 |
+
parser.add_argument("--config", type=Path, default=Path("/opt/task/score_config.json"))
|
| 58 |
+
parser.add_argument("--output", type=Path, default=Path("/sealed/results"))
|
| 59 |
+
parser.add_argument("--wait-seconds", type=int, default=3900)
|
| 60 |
+
args = parser.parse_args()
|
| 61 |
+
deadline = time.monotonic() + args.wait_seconds
|
| 62 |
+
while time.monotonic() < deadline:
|
| 63 |
+
ready = args.sealed.parent / "READY"
|
| 64 |
+
if ready.is_file():
|
| 65 |
+
payload = json.loads(ready.read_text())
|
| 66 |
+
run_id = payload.get("run_id", "")
|
| 67 |
+
if len(run_id) != 32 or any(c not in "0123456789abcdef" for c in run_id):
|
| 68 |
+
raise ValueError("Invalid trusted run identity")
|
| 69 |
+
grade(args.sealed, args.input, args.labels, args.config, args.output, payload)
|
| 70 |
+
return
|
| 71 |
+
time.sleep(0.25)
|
| 72 |
+
raise TimeoutError("Inference supervisor did not seal a submission")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
main()
|
reproduction/files/1d/1d5ba0e3f6977b88e95f7c60f3e009a37ea398b47c5488deb44875335aff74e5/test_research_tools.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regression tests for interrupted publication and scientific feedback."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import shutil
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import tempfile
|
| 11 |
+
import unittest
|
| 12 |
+
from unittest import mock
|
| 13 |
+
|
| 14 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 15 |
+
sys.path.insert(0, str(ROOT / 'environment/evaluation'))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load(name, path):
|
| 19 |
+
spec = importlib.util.spec_from_file_location(name, path)
|
| 20 |
+
module = importlib.util.module_from_spec(spec)
|
| 21 |
+
spec.loader.exec_module(module)
|
| 22 |
+
return module
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
publication = load('publication', ROOT / 'environment/baseline/starter/publication.py')
|
| 26 |
+
diagnostics = load('diagnostics', ROOT / 'environment/evaluation/diagnostics.py')
|
| 27 |
+
sys.modules['diagnostics'] = diagnostics
|
| 28 |
+
score = load('validation_score', ROOT / 'environment/evaluation/score.py')
|
| 29 |
+
paired = load('paired_score', ROOT / 'environment/evaluation/paired_bootstrap.py')
|
| 30 |
+
sys.path.insert(0, str(ROOT / 'tests'))
|
| 31 |
+
import main_verifier
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def build(stage, marker):
|
| 35 |
+
(stage / 'README.md').write_text(marker)
|
| 36 |
+
(stage / 'weights.pt').write_bytes(marker.encode())
|
| 37 |
+
(stage / 'config.json').write_text('{}')
|
| 38 |
+
(stage / 'infer.sh').write_text('#!/bin/bash\nprintf "%s\\n" ' + marker + '\n')
|
| 39 |
+
(stage / 'model_manifest.json').write_text(json.dumps({
|
| 40 |
+
'schema': 'massspecgym-retrieval-model/v1',
|
| 41 |
+
'checkpoint': {'path': 'weights.pt', 'sha256': hashlib.sha256(marker.encode()).hexdigest(), 'format': 'pytorch'},
|
| 42 |
+
'model_config': 'config.json', 'training_provenance': {'data': 'fixture', 'pretrained_assets': []},
|
| 43 |
+
}))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class NativePublicationTests(unittest.TestCase):
|
| 47 |
+
def setUp(self) -> None:
|
| 48 |
+
import torch
|
| 49 |
+
self.temporary = tempfile.TemporaryDirectory()
|
| 50 |
+
self.addCleanup(self.temporary.cleanup)
|
| 51 |
+
self.root = Path(self.temporary.name)
|
| 52 |
+
self.native = load('native_publish', ROOT / 'environment/baseline/starter/glacier/publish.py')
|
| 53 |
+
self.checkpoint = self.root / 'trained.ckpt'
|
| 54 |
+
self.state = {
|
| 55 |
+
'state_dict': {'fixture.weight': torch.tensor([1.0, 2.0])},
|
| 56 |
+
'hyper_parameters': json.loads((ROOT / 'environment/baseline/starter/glacier/config.json').read_text()),
|
| 57 |
+
'pytorch-lightning_version': '2.6.5', 'global_step': 10, 'epoch': 1,
|
| 58 |
+
'task_training': {'initialization': 'random', 'batch_size': 8,
|
| 59 |
+
'data_manifest_sha256': 'a' * 64},
|
| 60 |
+
}
|
| 61 |
+
torch.save(self.state, self.checkpoint)
|
| 62 |
+
self.fallback = self.root / 'fallback'
|
| 63 |
+
self.fallback.mkdir()
|
| 64 |
+
build(self.fallback, 'trained-fallback-fixture')
|
| 65 |
+
self.source = self.root / 'source'
|
| 66 |
+
(self.source / 'src/ms_pred').mkdir(parents=True)
|
| 67 |
+
(self.source / 'src/ms_pred/__init__.py').write_text('# source fixture\n')
|
| 68 |
+
(self.source / 'LICENSE').write_text('fixture license\n')
|
| 69 |
+
|
| 70 |
+
def command(self, destination: Path) -> list[str]:
|
| 71 |
+
return [sys.executable, str(ROOT / 'environment/baseline/starter/glacier/publish.py'),
|
| 72 |
+
'--checkpoint', str(self.checkpoint), '--fallback', str(self.fallback),
|
| 73 |
+
'--source-root', str(self.source), '--output-dir', str(destination)]
|
| 74 |
+
|
| 75 |
+
def assert_native_invocation(self, generation: Path, batch_size: int) -> None:
|
| 76 |
+
"""Exercise the published adapter with bounded stand-ins for model execution."""
|
| 77 |
+
native_infer = load('published_native_infer', generation / 'infer.py')
|
| 78 |
+
input_root, output_root = self.root / 'public-input', self.root / 'rankings'
|
| 79 |
+
|
| 80 |
+
def run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess:
|
| 81 |
+
script = Path(command[1]).name
|
| 82 |
+
if script == 'stage_input.py':
|
| 83 |
+
partition = Path(command[command.index('--output-root') + 1])
|
| 84 |
+
for branch in ('glacier', 'fallback'):
|
| 85 |
+
(partition / branch).mkdir(parents=True)
|
| 86 |
+
(partition / branch / 'queries.jsonl').write_text('{}\n')
|
| 87 |
+
elif script == 'prepare_glacier_candidates.py':
|
| 88 |
+
Path(command[command.index('--output') + 1]).write_text('smiles\nCCO\n')
|
| 89 |
+
elif script == 'merge_glacier_fallback.py':
|
| 90 |
+
(output_root / 'runtime.json').write_text('{}\n')
|
| 91 |
+
return subprocess.CompletedProcess(command, 0)
|
| 92 |
+
|
| 93 |
+
with mock.patch.object(sys, 'argv', ['infer.py', str(input_root), str(output_root)]), \
|
| 94 |
+
mock.patch.object(native_infer.subprocess, 'run', side_effect=run) as execute:
|
| 95 |
+
native_infer.main()
|
| 96 |
+
commands = [call.args[0] for call in execute.call_args_list]
|
| 97 |
+
predictor = next(command for command in commands if Path(command[1]).name == 'predict_smis_joint.py')
|
| 98 |
+
for option, value in {'--batch-size': batch_size, '--num-cpu-workers': 2,
|
| 99 |
+
'--feat-cache-size': 64, '--prefetch-factor': 1}.items():
|
| 100 |
+
self.assertEqual(predictor[predictor.index(option) + 1], str(value))
|
| 101 |
+
self.assertEqual(predictor[predictor.index('--checkpoint') + 1], str(generation / 'glacier.ckpt'))
|
| 102 |
+
scorer = next(command for command in commands if Path(command[1]).name == 'score_glacier_predictions.py')
|
| 103 |
+
self.assertEqual(scorer[scorer.index('--distance') + 1], 'entropy')
|
| 104 |
+
self.assertTrue(any(command[:2] == ['bash', str(generation / 'fallback/infer.sh')] for command in commands))
|
| 105 |
+
self.assertFalse((output_root / 'runtime.json').exists())
|
| 106 |
+
|
| 107 |
+
def test_default_and_cli_override_preserve_model_and_training(self) -> None:
|
| 108 |
+
import torch
|
| 109 |
+
configs = []
|
| 110 |
+
for name, override, batch_size in [('api-default', None, 64),
|
| 111 |
+
('cli-default', None, 64), ('cli-small', 8, 8)]:
|
| 112 |
+
with self.subTest(name=name):
|
| 113 |
+
destination = self.root / name
|
| 114 |
+
if name == 'api-default':
|
| 115 |
+
self.native.publish(self.checkpoint, self.fallback, self.source, destination)
|
| 116 |
+
else:
|
| 117 |
+
command = self.command(destination)
|
| 118 |
+
if override is not None:
|
| 119 |
+
command.extend(['--inference-batch-size', str(override)])
|
| 120 |
+
subprocess.run(command, check=True, capture_output=True, text=True)
|
| 121 |
+
# Publication must remain portable, including its selected generation.
|
| 122 |
+
relocated = self.root / (name + '-relocated')
|
| 123 |
+
shutil.move(destination, relocated)
|
| 124 |
+
manifest = main_verifier.validate_submission(relocated)
|
| 125 |
+
config = json.loads((relocated / manifest['model_config']).read_text())
|
| 126 |
+
configs.append(config)
|
| 127 |
+
self.assertEqual(config['batch_size'], batch_size)
|
| 128 |
+
self.assertEqual(config['training'], self.state['task_training'])
|
| 129 |
+
self.assertEqual(config['method'], 'native-glacier-with-trained-deepsets-fallback')
|
| 130 |
+
self.assertEqual(config['routing'], 'released_conditions_with_usable_observation_and_supported_pool')
|
| 131 |
+
self.assertEqual(manifest['training_provenance'], {
|
| 132 |
+
'data': 'MassSpecGym v1.5 train; validation for selection only', 'pretrained_assets': []})
|
| 133 |
+
saved = torch.load(relocated / manifest['checkpoint']['path'], weights_only=False)
|
| 134 |
+
self.assertTrue(torch.equal(saved.pop('state_dict')['fixture.weight'],
|
| 135 |
+
self.state['state_dict']['fixture.weight']))
|
| 136 |
+
self.assertEqual(saved, {key: value for key, value in self.state.items() if key != 'state_dict'})
|
| 137 |
+
generation = (relocated / manifest['model_config']).parent
|
| 138 |
+
for name in ['stage_input.py', 'config.json', 'train.py']:
|
| 139 |
+
source = ROOT / 'environment/baseline/starter/glacier' / name
|
| 140 |
+
target = generation / ('stage_input.py' if name == 'stage_input.py' else 'training/' + name)
|
| 141 |
+
self.assertEqual(target.read_bytes(), source.read_bytes())
|
| 142 |
+
self.assertEqual((generation / 'fallback/weights.pt').read_bytes(),
|
| 143 |
+
(self.fallback / 'weights.pt').read_bytes())
|
| 144 |
+
self.assert_native_invocation(generation, batch_size)
|
| 145 |
+
self.assertEqual(configs[0], configs[1])
|
| 146 |
+
self.assertEqual(configs[0], {**configs[2], 'batch_size': 64})
|
| 147 |
+
|
| 148 |
+
def test_invalid_api_batch_preserves_existing_publication(self) -> None:
|
| 149 |
+
destination = self.root / 'published'
|
| 150 |
+
self.native.publish(self.checkpoint, self.fallback, self.source, destination)
|
| 151 |
+
before = (destination / 'model_manifest.json').read_bytes()
|
| 152 |
+
for value in (0, -1, 1.5, '8', True):
|
| 153 |
+
with self.subTest(value=value), self.assertRaisesRegex(ValueError, 'positive integer'):
|
| 154 |
+
self.native.publish(self.checkpoint, self.fallback, self.source, destination,
|
| 155 |
+
inference_batch_size=value)
|
| 156 |
+
self.assertEqual((destination / 'model_manifest.json').read_bytes(), before)
|
| 157 |
+
|
| 158 |
+
def test_invalid_cli_batch_fails_before_publication(self) -> None:
|
| 159 |
+
destination = self.root / 'invalid'
|
| 160 |
+
for value in ('0', '-1', '1.5', 'invalid'):
|
| 161 |
+
with self.subTest(value=value):
|
| 162 |
+
result = subprocess.run(self.command(destination) + ['--inference-batch-size', value],
|
| 163 |
+
capture_output=True, text=True)
|
| 164 |
+
self.assertEqual(result.returncode, 2)
|
| 165 |
+
self.assertIn('inference batch size must be a positive integer', result.stderr)
|
| 166 |
+
self.assertFalse(destination.exists())
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class ResearchToolsTests(unittest.TestCase):
|
| 170 |
+
def test_native_routes_unsupported_valid_inputs_to_the_trained_fallback(self):
|
| 171 |
+
native = load('native_stage', ROOT / 'environment/baseline/starter/glacier/stage_input.py')
|
| 172 |
+
self.assertTrue(native.supports_pool([{'smiles': 'CCO'}], {1, 6, 7, 8}))
|
| 173 |
+
self.assertFalse(native.supports_pool([{'smiles': 'C' * 101}], {1, 6, 7, 8}))
|
| 174 |
+
self.assertFalse(native.supports_observation(dict(mzs=[1500.0], intensities=[1.0], precursor_mz=200.0)))
|
| 175 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 176 |
+
root = Path(temporary)
|
| 177 |
+
source = root / 'input'; source.mkdir()
|
| 178 |
+
ordinary = dict(query_id='ordinary', candidate_pool_id='p', mzs=[50.0],
|
| 179 |
+
intensities=[1.0], precursor_mz=100.0)
|
| 180 |
+
queries = [ordinary, dict(ordinary, query_id='outside', mzs=[1500.0]),
|
| 181 |
+
dict(ordinary, query_id='large-pool', candidate_pool_id='large')]
|
| 182 |
+
pools = [{'candidate_pool_id': 'p', 'candidates': [{'candidate_id': 'c', 'smiles': 'CCO'}]},
|
| 183 |
+
{'candidate_pool_id': 'large', 'candidates': [{'candidate_id': 'large-c', 'smiles': 'C' * 101}]}]
|
| 184 |
+
for filename, rows in [('queries.jsonl', queries), ('candidate_pools.jsonl', pools)]:
|
| 185 |
+
(source / filename).write_text(''.join(json.dumps(row) + '\n' for row in rows))
|
| 186 |
+
native.partition(source, root / 'output', {1, 6, 7, 8}, lambda query: True)
|
| 187 |
+
self.assertEqual((root / 'output/glacier-query-ids.txt').read_text(), 'ordinary\n')
|
| 188 |
+
fallback = [json.loads(line) for line in (root / 'output/fallback/queries.jsonl').read_text().splitlines()]
|
| 189 |
+
self.assertEqual({row['query_id'] for row in fallback}, {'outside', 'large-pool'})
|
| 190 |
+
self.assertEqual(len(fallback) + 1, len(queries))
|
| 191 |
+
|
| 192 |
+
def test_resuming_fit_state_does_not_refund_completed_validation(self):
|
| 193 |
+
native = load('native_train', ROOT / 'environment/baseline/starter/glacier/train.py')
|
| 194 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 195 |
+
root = Path(temporary)
|
| 196 |
+
# A fit checkpoint precedes expensive final validation/export.
|
| 197 |
+
self.assertEqual(native.charged_elapsed(root, 190), 190)
|
| 198 |
+
(root / 'result.json').write_text(json.dumps({'elapsed_seconds': 567}))
|
| 199 |
+
self.assertEqual(native.charged_elapsed(root, 190), 567)
|
| 200 |
+
# A later interrupted segment must retain its greater usage too.
|
| 201 |
+
self.assertEqual(native.charged_elapsed(root, 800), 800)
|
| 202 |
+
(root / 'budget-ledger.json').write_text(json.dumps({'elapsed_seconds': 900}))
|
| 203 |
+
self.assertEqual(native.charged_elapsed(root, 800), 900)
|
| 204 |
+
|
| 205 |
+
def test_unparseable_candidate_has_a_finite_fallback_but_training_stays_strict(self):
|
| 206 |
+
import torch
|
| 207 |
+
starter = load('starter_common', ROOT / 'environment/baseline/starter/common.py')
|
| 208 |
+
# Invalid in every RDKit version exercises the same boundary as legacy
|
| 209 |
+
# valences accepted by the task's RDKit 2023 but rejected by 2025.
|
| 210 |
+
with self.assertRaisesRegex(ValueError, 'invalid candidate SMILES'):
|
| 211 |
+
starter.morgan_fingerprint('not_a_smiles')
|
| 212 |
+
fp = starter.morgan_fingerprint('not_a_smiles', allow_unparseable=True)
|
| 213 |
+
self.assertTrue(torch.isfinite(fp).all())
|
| 214 |
+
self.assertEqual(tuple(fp.shape), (4096,))
|
| 215 |
+
self.assertEqual(int(torch.count_nonzero(fp)), 0)
|
| 216 |
+
self.assertTrue(torch.equal(starter.morgan_fingerprint('CCO'),
|
| 217 |
+
starter.morgan_fingerprint('CCO', allow_unparseable=True)))
|
| 218 |
+
|
| 219 |
+
def test_starter_accepts_valid_spectra_outside_its_preprocessing_window(self):
|
| 220 |
+
import torch
|
| 221 |
+
starter = load('starter_common', ROOT / 'environment/baseline/starter/common.py')
|
| 222 |
+
for mzs, intensities in [([1500.0], [1.0]), ([50.0, 1500.0], [0.0, 1.0])]:
|
| 223 |
+
with self.subTest(mzs=mzs):
|
| 224 |
+
encoded = starter.spectrum_tensor(dict(
|
| 225 |
+
mzs=mzs, intensities=intensities, precursor_mz=1600.0))
|
| 226 |
+
self.assertTrue(torch.isfinite(encoded).all())
|
| 227 |
+
self.assertEqual(tuple(encoded.shape), (61, 2))
|
| 228 |
+
self.assertEqual(float(encoded[0, 0]), 1600.0)
|
| 229 |
+
self.assertEqual(int(torch.count_nonzero(encoded[1:])), 0)
|
| 230 |
+
with self.assertRaisesRegex(ValueError, 'maximum intensity must be positive'):
|
| 231 |
+
starter.spectrum_tensor(dict(mzs=[1500.0], intensities=[0.0], precursor_mz=1600.0))
|
| 232 |
+
|
| 233 |
+
def test_declared_external_weights_are_not_authorized_by_manifest(self):
|
| 234 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 235 |
+
root = Path(temporary)
|
| 236 |
+
build(root, 'fixture')
|
| 237 |
+
manifest = main_verifier.validate_submission(root)
|
| 238 |
+
manifest['training_provenance']['pretrained_assets'] = [
|
| 239 |
+
{'name': 'external', 'revision': 'immutable', 'license': 'MIT'}]
|
| 240 |
+
(root / 'model_manifest.json').write_text(json.dumps(manifest))
|
| 241 |
+
with self.assertRaisesRegex(ValueError, 'no authorized pretrained'):
|
| 242 |
+
main_verifier.validate_submission(root)
|
| 243 |
+
|
| 244 |
+
def test_failed_publication_preserves_previous_runnable_model(self):
|
| 245 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 246 |
+
root = Path(temporary) / 'submission'
|
| 247 |
+
publication.publish_directory(root, lambda stage: build(stage, 'first'))
|
| 248 |
+
for path in [root, *root.rglob('*')]:
|
| 249 |
+
if path.is_dir():
|
| 250 |
+
self.assertEqual(path.stat().st_mode & 0o005, 0o005)
|
| 251 |
+
else:
|
| 252 |
+
self.assertEqual(path.stat().st_mode & 0o004, 0o004)
|
| 253 |
+
before = (root / 'model_manifest.json').read_bytes()
|
| 254 |
+
def interrupted(stage):
|
| 255 |
+
build(stage, 'unfinished')
|
| 256 |
+
raise RuntimeError('simulated preemption while exporting')
|
| 257 |
+
with self.assertRaises(RuntimeError):
|
| 258 |
+
publication.publish_directory(root, interrupted)
|
| 259 |
+
self.assertEqual(before, (root / 'model_manifest.json').read_bytes())
|
| 260 |
+
publication.publish_directory(root, lambda stage: build(stage, 'second'))
|
| 261 |
+
relocated = Path(temporary) / 'elsewhere'
|
| 262 |
+
shutil.copytree(root, relocated)
|
| 263 |
+
shutil.rmtree(root)
|
| 264 |
+
self.assertEqual(subprocess.check_output(['bash', str(relocated / 'infer.sh')], text=True).strip(), 'second')
|
| 265 |
+
# A reader which captured the old manifest still has all its assets.
|
| 266 |
+
old = json.loads(before)
|
| 267 |
+
self.assertEqual((relocated / old['checkpoint']['path']).read_text(), 'first')
|
| 268 |
+
compact = Path(temporary) / 'compact'
|
| 269 |
+
publication.snapshot_package(relocated, compact)
|
| 270 |
+
self.assertFalse((compact / old['checkpoint']['path']).exists())
|
| 271 |
+
self.assertEqual(subprocess.check_output(['bash', str(compact / 'infer.sh')], text=True).strip(), 'second')
|
| 272 |
+
|
| 273 |
+
def test_escaping_publication_is_rejected_without_replacing_manifest(self):
|
| 274 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 275 |
+
root = Path(temporary) / 'submission'
|
| 276 |
+
publication.publish_directory(root, lambda stage: build(stage, 'first'))
|
| 277 |
+
before = (root / 'model_manifest.json').read_bytes()
|
| 278 |
+
def escaping(stage):
|
| 279 |
+
build(stage, 'bad')
|
| 280 |
+
(stage / 'external').symlink_to('/etc/passwd')
|
| 281 |
+
with self.assertRaises(ValueError):
|
| 282 |
+
publication.publish_directory(root, escaping)
|
| 283 |
+
self.assertEqual(before, (root / 'model_manifest.json').read_bytes())
|
| 284 |
+
|
| 285 |
+
def test_cluster_bootstrap_keeps_spectrum_weighting(self):
|
| 286 |
+
# One molecule has nine spectra, the other one: macro would be 0.5.
|
| 287 |
+
report = diagnostics.cluster_interval([1] * 9 + [0], ['A'] * 9 + ['B'], resamples=500, seed=7)
|
| 288 |
+
self.assertEqual(report['estimate'], 0.9)
|
| 289 |
+
self.assertEqual(report['molecule_groups'], 2)
|
| 290 |
+
self.assertEqual(report['lower'], 0)
|
| 291 |
+
self.assertEqual(report['upper'], 1)
|
| 292 |
+
self.assertEqual(report, diagnostics.cluster_interval([1] * 9 + [0], ['A'] * 9 + ['B'], resamples=500, seed=7))
|
| 293 |
+
|
| 294 |
+
def test_no_difference_has_zero_paired_interval(self):
|
| 295 |
+
report = diagnostics.cluster_interval([0, 0, 0], ['A', 'A', 'B'], resamples=100)
|
| 296 |
+
self.assertEqual((report['estimate'], report['lower'], report['upper']), (0, 0, 0))
|
| 297 |
+
|
| 298 |
+
def test_paired_report_resamples_molecules_without_changing_delta(self):
|
| 299 |
+
truth = {f'q{i}': 'a' for i in range(10)}
|
| 300 |
+
baseline = {q: 'b' for q in truth}
|
| 301 |
+
challenger = {q: 'a' if q != 'q9' else 'b' for q in truth}
|
| 302 |
+
groups = {q: 'A' if q != 'q9' else 'B' for q in truth}
|
| 303 |
+
report = paired.compare(truth, baseline, challenger, confidence=0.95, resamples=500, seed=7, groups=groups)
|
| 304 |
+
self.assertEqual(report['delta'], 0.9)
|
| 305 |
+
self.assertEqual(report['molecule_groups'], 2)
|
| 306 |
+
self.assertEqual(report['interval'], [0, 1])
|
| 307 |
+
self.assertFalse(report['beats_reference'])
|
| 308 |
+
|
| 309 |
+
def test_validation_rejects_nested_or_partial_rankings(self):
|
| 310 |
+
with tempfile.TemporaryDirectory() as temporary:
|
| 311 |
+
path = Path(temporary) / 'rankings.jsonl'
|
| 312 |
+
for ranking in [[['a'], 'b'], ['a'], ['a', 'a']]:
|
| 313 |
+
path.write_text(json.dumps({'query_id': 'q', 'ranking': ranking}) + '\n')
|
| 314 |
+
with self.assertRaises(ValueError):
|
| 315 |
+
score.load_rankings(path, {'q': {'pool': 'p'}}, {'p': [{'candidate_id': 'a'}, {'candidate_id': 'b'}]})
|
| 316 |
+
|
| 317 |
+
def test_routing_does_not_treat_missing_energy_as_zero(self):
|
| 318 |
+
row = {'adduct': '[M+H]+', 'instrument_type': 'Orbitrap', 'collision_energy': None}
|
| 319 |
+
self.assertFalse(diagnostics.released_domain(row))
|
| 320 |
+
self.assertTrue(diagnostics.released_domain(dict(row, collision_energy=0.0)))
|
| 321 |
+
self.assertFalse(diagnostics.released_domain(dict(row, collision_energy=float('nan'))))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
if __name__ == '__main__':
|
| 325 |
+
unittest.main()
|
reproduction/files/1f/1f6f9a2579d1877217e9aba9c6c9eabcd30cac45975eee58c07e7a7bf00dd1ea/novelty.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Novelty against the fit corpus: the largest TM-score of a design to any fit chain.
|
| 2 |
+
|
| 3 |
+
Protein-design benchmarks report novelty as the maximum TM-score of each designable design to the PDB or the
|
| 4 |
+
training set, computed with Foldseek in TM-align mode (lower is more novel); generative models typically sit
|
| 5 |
+
around 0.45-0.8 depending on the task. A design therefore passes only if, besides the published designability
|
| 6 |
+
criterion, its maximum TM-score to the fit corpus is below `common.NOVELTY_MAX_TM`.
|
| 7 |
+
|
| 8 |
+
The reference is the fit corpus the agent trains on (`development/fit/structures`), mounted read-only into
|
| 9 |
+
the grader; its Foldseek database is built once per grading run (a few minutes on 16k structures).
|
| 10 |
+
"""
|
| 11 |
+
import os
|
| 12 |
+
import shutil
|
| 13 |
+
import subprocess
|
| 14 |
+
import tempfile
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
FOLDSEEK = os.environ.get("FOLDSEEK", "/opt/foldseek/bin/foldseek")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class FitNovelty:
|
| 21 |
+
def __init__(self, reference_dir, workdir=None, threads=None, foldseek=FOLDSEEK):
|
| 22 |
+
self.reference_dir = Path(reference_dir)
|
| 23 |
+
if not any(self.reference_dir.rglob("*.cif*")):
|
| 24 |
+
raise FileNotFoundError(f"novelty reference has no structures: {self.reference_dir}")
|
| 25 |
+
self.foldseek = foldseek
|
| 26 |
+
self.threads = str(threads or os.cpu_count() or 1)
|
| 27 |
+
self.work = Path(workdir or tempfile.mkdtemp(prefix="novelty-"))
|
| 28 |
+
self.db = self.work / "fitdb"
|
| 29 |
+
self._run("createdb", str(self.reference_dir), str(self.db), "--threads", self.threads)
|
| 30 |
+
|
| 31 |
+
def _run(self, *arguments):
|
| 32 |
+
subprocess.run([self.foldseek, *arguments], check=True, stdout=subprocess.DEVNULL,
|
| 33 |
+
stderr=subprocess.PIPE)
|
| 34 |
+
|
| 35 |
+
def max_tm(self, designs):
|
| 36 |
+
"""designs: {key: PDB path} -> {key: max TM-score (normalized by the design) to any fit chain}."""
|
| 37 |
+
if not designs:
|
| 38 |
+
return {}
|
| 39 |
+
query = Path(tempfile.mkdtemp(dir=self.work, prefix="query-"))
|
| 40 |
+
try:
|
| 41 |
+
names = {}
|
| 42 |
+
for index, (key, path) in enumerate(designs.items()):
|
| 43 |
+
name = f"q{index}"
|
| 44 |
+
shutil.copyfile(path, query / f"{name}.pdb")
|
| 45 |
+
names[name] = key
|
| 46 |
+
self._run("createdb", str(query), str(query / "db"), "--threads", self.threads)
|
| 47 |
+
# TM-align alignment of every prefilter hit; -a keeps the alignment so qtmscore can be reported.
|
| 48 |
+
self._run("search", str(query / "db"), str(self.db), str(query / "aln"), str(query / "tmp"),
|
| 49 |
+
"--alignment-type", "1", "-a", "-e", "inf", "--max-seqs", "1000", "-s", "9.5",
|
| 50 |
+
"--threads", self.threads)
|
| 51 |
+
self._run("convertalis", str(query / "db"), str(self.db), str(query / "aln"),
|
| 52 |
+
str(query / "hits.tsv"), "--format-output", "query,target,qtmscore")
|
| 53 |
+
best = {key: 0.0 for key in designs}
|
| 54 |
+
for line in (query / "hits.tsv").read_text().splitlines():
|
| 55 |
+
name, _, score = line.split("\t")
|
| 56 |
+
key = names.get(name.split("_")[0])
|
| 57 |
+
if key is not None:
|
| 58 |
+
best[key] = max(best[key], float(score))
|
| 59 |
+
return best
|
| 60 |
+
finally:
|
| 61 |
+
shutil.rmtree(query, ignore_errors=True)
|
reproduction/files/1f/1fb4ffce095d7d563544d2826539a9113032c80c3907c9e746c93e0dcbe677ff/make_zero_predictions.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Create the deterministic all-zero sanity baseline."""
|
| 2 |
+
import argparse,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import pyarrow as pa
|
| 5 |
+
import pyarrow.parquet as pq
|
| 6 |
+
|
| 7 |
+
ap=argparse.ArgumentParser();ap.add_argument("--input",type=Path,required=True);ap.add_argument("--output",type=Path,required=True);a=ap.parse_args()
|
| 8 |
+
m=json.loads((a.input/"manifest.json").read_text());d=len(m["scored_diseases"]);h=len(m["horizons_days"])
|
| 9 |
+
ids=pq.read_table(a.input/"samples.parquet",columns=["sample_id"])["sample_id"].to_pylist()
|
| 10 |
+
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))])
|
| 11 |
+
row_d=[0.0]*(d*h);row_h=[0.0]*h;a.output.parent.mkdir(parents=True,exist_ok=True)
|
| 12 |
+
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")
|
reproduction/files/1f/1fff1846a4ec5dcc7e2beb2eda5dbb97f35494d686a33e4a62974d482a8e583b/evaluate_native.sh
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
| 4 |
+
# Bootstrap the image's Python libraries without loading CUDA solver modules.
|
| 5 |
+
# The Python dispatcher selects the solver runtime separately for each case.
|
| 6 |
+
exec bash "$root/native_runtime.sh" jax python "$root/evaluate_native.py" "$@"
|
reproduction/files/22/224957d662239021e18f16650cebeefedd5515b8b94454d64fc3064e98bb1a43/test_contract.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Checks ID alignment, rejection of malformed output, and test isolation."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
import unittest
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
SCRIPT = Path(__file__).resolve().parents[1] / "environment/evaluation/probes.py"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ProbeContract(unittest.TestCase):
|
| 15 |
+
def test_alignment_failures_and_test_isolation(self):
|
| 16 |
+
with tempfile.TemporaryDirectory() as td:
|
| 17 |
+
root = Path(td)
|
| 18 |
+
rng = np.random.default_rng(24)
|
| 19 |
+
x = rng.normal(size=(110, 12))
|
| 20 |
+
y = x[:, 0] * 4 + x[:, 1] * 2
|
| 21 |
+
rows = [
|
| 22 |
+
{
|
| 23 |
+
"id": f"new-id-{i}",
|
| 24 |
+
"label": float(y[i]),
|
| 25 |
+
"split": "train" if i < 70 else "val" if i < 90 else "test",
|
| 26 |
+
}
|
| 27 |
+
for i in range(110)
|
| 28 |
+
]
|
| 29 |
+
labels = root / "labels.json"
|
| 30 |
+
labels.write_text(json.dumps(rows))
|
| 31 |
+
ids = np.array([r["id"] for r in rows])
|
| 32 |
+
features = root / "features.npz"
|
| 33 |
+
cmd = [
|
| 34 |
+
sys.executable,
|
| 35 |
+
str(SCRIPT),
|
| 36 |
+
"--features",
|
| 37 |
+
str(features),
|
| 38 |
+
"--labels",
|
| 39 |
+
str(labels),
|
| 40 |
+
"--task",
|
| 41 |
+
"lfmc",
|
| 42 |
+
"--output",
|
| 43 |
+
str(root / "score.json"),
|
| 44 |
+
"--final-test",
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
def run():
|
| 48 |
+
return subprocess.run(cmd, capture_output=True, text=True)
|
| 49 |
+
|
| 50 |
+
np.savez(features, ids=ids, features=x)
|
| 51 |
+
self.assertEqual(run().returncode, 0)
|
| 52 |
+
original = json.loads((root / "score.json").read_text())
|
| 53 |
+
perm = rng.permutation(len(ids))
|
| 54 |
+
np.savez(features, ids=ids[perm], features=x[perm])
|
| 55 |
+
self.assertEqual(run().returncode, 0)
|
| 56 |
+
self.assertEqual(original, json.loads((root / "score.json").read_text()))
|
| 57 |
+
for row in rows[90:]:
|
| 58 |
+
row["label"] += 100
|
| 59 |
+
labels.write_text(json.dumps(rows))
|
| 60 |
+
self.assertEqual(run().returncode, 0)
|
| 61 |
+
altered = json.loads((root / "score.json").read_text())
|
| 62 |
+
self.assertEqual(
|
| 63 |
+
original["probe"]["selected_parameter"],
|
| 64 |
+
altered["probe"]["selected_parameter"],
|
| 65 |
+
)
|
| 66 |
+
self.assertEqual(
|
| 67 |
+
original["probe"]["validation"], altered["probe"]["validation"]
|
| 68 |
+
)
|
| 69 |
+
self.assertNotEqual(original["probe"]["test"], altered["probe"]["test"])
|
| 70 |
+
np.savez(features, ids=ids[:-1], features=x[:-1])
|
| 71 |
+
self.assertNotEqual(run().returncode, 0)
|
| 72 |
+
np.savez(features, ids=np.repeat(ids[:1], len(ids)), features=x)
|
| 73 |
+
self.assertNotEqual(run().returncode, 0)
|
| 74 |
+
np.savez(
|
| 75 |
+
features,
|
| 76 |
+
ids=np.concatenate([ids, ids[:1]]),
|
| 77 |
+
features=np.concatenate([x, x[:1]]),
|
| 78 |
+
)
|
| 79 |
+
self.assertNotEqual(run().returncode, 0)
|
| 80 |
+
x[0, 0] = float("nan")
|
| 81 |
+
np.savez(features, ids=ids, features=x)
|
| 82 |
+
self.assertNotEqual(run().returncode, 0)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
unittest.main()
|
reproduction/files/24/24cdd224ba6133de77df91462bb66d12b3432ee2b21cd85e24379c7813b44561/check_training_recovery.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Real native-model recovery integration check; run in the GLACIER runtime."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main():
|
| 15 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 16 |
+
for name in ['data-root', 'fallback', 'output']:
|
| 17 |
+
parser.add_argument('--' + name, type=Path, required=True)
|
| 18 |
+
parser.add_argument('--source-root', type=Path, default=Path('/opt/ms-pred'))
|
| 19 |
+
parser.add_argument('--workers', type=int, default=0)
|
| 20 |
+
args = parser.parse_args()
|
| 21 |
+
args.output.mkdir(parents=True, exist_ok=False)
|
| 22 |
+
script = Path(__file__).resolve().parents[1] / 'environment/baseline/starter/glacier/train.py'
|
| 23 |
+
for name, steps, resume in [('resumed', 2, False), ('resumed', 4, True), ('continuous', 4, False)]:
|
| 24 |
+
command = [sys.executable, str(script), '--data-root', str(args.data_root),
|
| 25 |
+
'--source-root', str(args.source_root), '--work-dir', str(args.output / name),
|
| 26 |
+
'--fallback', str(args.fallback), '--submission-dir', str(args.output / (name + '-submission')),
|
| 27 |
+
'--max-steps', str(steps), '--device', 'cpu', '--workers', str(args.workers), '--batch-size', '1',
|
| 28 |
+
'--accumulate-grad-batches', '1', '--validate-every', '1', '--checkpoint-every', '500',
|
| 29 |
+
'--max-seconds', '600', '--trace-batches']
|
| 30 |
+
if resume:
|
| 31 |
+
command += ['--resume', str(args.output / name / 'last.ckpt')]
|
| 32 |
+
with (args.output / f'{name}-{steps}.log').open('w') as log:
|
| 33 |
+
subprocess.run(command, check=True, env=dict(os.environ, OMP_NUM_THREADS='2'), stdout=log, stderr=subprocess.STDOUT)
|
| 34 |
+
resumed = torch.load(args.output / 'resumed/last.ckpt', map_location='cpu', weights_only=False)
|
| 35 |
+
continuous = torch.load(args.output / 'continuous/last.ckpt', map_location='cpu', weights_only=False)
|
| 36 |
+
different = [key for key, value in resumed['state_dict'].items() if not torch.equal(value, continuous['state_dict'][key])]
|
| 37 |
+
same_batches = ((args.output / 'resumed/batch-trace.jsonl').read_bytes() ==
|
| 38 |
+
(args.output / 'continuous/batch-trace.jsonl').read_bytes())
|
| 39 |
+
report = {'global_steps': [resumed['global_step'], continuous['global_step']],
|
| 40 |
+
'magma_steps': [resumed['task_magma_step'], continuous['task_magma_step']],
|
| 41 |
+
'differing_parameter_tensors': different, 'identical_batch_order_and_rng': same_batches,
|
| 42 |
+
'scope': f'CPU, loader workers={args.workers}, same pinned runtime; not cross-hardware determinism'}
|
| 43 |
+
(args.output / 'report.json').write_text(json.dumps(report, indent=2) + '\n')
|
| 44 |
+
if different or not same_batches or report['global_steps'] != [4, 4] or report['magma_steps'] != [4, 4]:
|
| 45 |
+
raise AssertionError(report)
|
| 46 |
+
print(json.dumps(report, indent=2))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if __name__ == '__main__':
|
| 50 |
+
main()
|
reproduction/files/25/25821b034a3b87b31eb7bd03c266decee1a2de037c3680796119f04c0740c63d/test_heldout_confirmation.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A failed cohort cannot unlock test reporting; test labels cannot choose alpha."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import runpy
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import tempfile
|
| 11 |
+
import unittest
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from sklearn.linear_model import Ridge
|
| 15 |
+
from sklearn.pipeline import make_pipeline
|
| 16 |
+
from sklearn.preprocessing import StandardScaler
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class HeldoutConfirmationTest(unittest.TestCase):
|
| 20 |
+
def test_legacy_random_provenance(self):
|
| 21 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "docs/analysis"))
|
| 22 |
+
check = runpy.run_path(
|
| 23 |
+
str(Path(__file__).resolve().parents[1] / "docs/analysis/heldout_confirmation.py")
|
| 24 |
+
)["is_random_initialization"]
|
| 25 |
+
self.assertTrue(check({"checkpoint": None}))
|
| 26 |
+
self.assertTrue(check({"origin": "random_initialization"}))
|
| 27 |
+
self.assertFalse(check({}))
|
| 28 |
+
self.assertFalse(check({"checkpoint": "weights.pt"}))
|
| 29 |
+
self.assertFalse(
|
| 30 |
+
check(
|
| 31 |
+
{"origin": "official_public_pretrained_reference", "checkpoint": None}
|
| 32 |
+
)
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def test_lock_gate_and_fixed_probe_parameters(self):
|
| 36 |
+
script = Path(__file__).resolve().parents[1] / "docs/analysis/heldout_confirmation.py"
|
| 37 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 38 |
+
root = Path(tmp)
|
| 39 |
+
(root / "results").mkdir()
|
| 40 |
+
context = {"gpu_type": "a5000", "python_hash_seed": 0}
|
| 41 |
+
(root / "execution-context.json").write_text(json.dumps(context))
|
| 42 |
+
seeds, loader_seeds = [12536, 12539, 12540], [3622, 3625, 3626]
|
| 43 |
+
pairs = [
|
| 44 |
+
[f"large-random-eval-{seed}", f"train-{seed}-step6000"]
|
| 45 |
+
for seed in seeds
|
| 46 |
+
]
|
| 47 |
+
recipe = {"global_batch": 64, "checkpoint_step": "step6000"}
|
| 48 |
+
lock = {
|
| 49 |
+
"selected": pairs[0][1],
|
| 50 |
+
"checkpoint_step": 6000,
|
| 51 |
+
"training_recipe": recipe,
|
| 52 |
+
"policy": {"development_seed": seeds[0], "execution_context": context},
|
| 53 |
+
"confirmation": [
|
| 54 |
+
{
|
| 55 |
+
"name": f"train-{seed}",
|
| 56 |
+
"initialization_seed": seed,
|
| 57 |
+
"data_seed": loader,
|
| 58 |
+
"paired_random": pair[0],
|
| 59 |
+
}
|
| 60 |
+
for seed, loader, pair in zip(
|
| 61 |
+
seeds[1:], loader_seeds[1:], pairs[1:]
|
| 62 |
+
)
|
| 63 |
+
],
|
| 64 |
+
}
|
| 65 |
+
comparison = {
|
| 66 |
+
"split": "val",
|
| 67 |
+
"pairs": pairs,
|
| 68 |
+
"initialization_seeds": seeds,
|
| 69 |
+
"data_seeds": loader_seeds,
|
| 70 |
+
"execution_context": context,
|
| 71 |
+
"tasks": {"lfmc": {"three_seed_criterion_met": False}},
|
| 72 |
+
}
|
| 73 |
+
lock_path, comparison_path = root / "lock.json", root / "comparison.json"
|
| 74 |
+
lock_path.write_text(json.dumps(lock))
|
| 75 |
+
comparison_path.write_text(json.dumps(comparison))
|
| 76 |
+
cmd = [
|
| 77 |
+
sys.executable,
|
| 78 |
+
str(script),
|
| 79 |
+
"--data-root",
|
| 80 |
+
str(root),
|
| 81 |
+
"--lock",
|
| 82 |
+
str(lock_path),
|
| 83 |
+
"--validation-comparison",
|
| 84 |
+
str(comparison_path),
|
| 85 |
+
"--output",
|
| 86 |
+
str(root / "test.json"),
|
| 87 |
+
]
|
| 88 |
+
env = dict(
|
| 89 |
+
os.environ,
|
| 90 |
+
CUDA_VISIBLE_DEVICES="",
|
| 91 |
+
OMP_NUM_THREADS="1",
|
| 92 |
+
OPENBLAS_NUM_THREADS="1",
|
| 93 |
+
)
|
| 94 |
+
failed = subprocess.run(cmd, env=env, capture_output=True, text=True)
|
| 95 |
+
self.assertNotEqual(failed.returncode, 0)
|
| 96 |
+
self.assertIn("Validation confirmation has not passed", failed.stderr)
|
| 97 |
+
self.assertFalse((root / "eval").exists())
|
| 98 |
+
rng = np.random.default_rng(12)
|
| 99 |
+
y = rng.normal(size=100) * 3
|
| 100 |
+
ids = np.array([f"id-{i}" for i in range(len(y))])
|
| 101 |
+
rows = [
|
| 102 |
+
{
|
| 103 |
+
"id": str(id_),
|
| 104 |
+
"label": float(y[i]),
|
| 105 |
+
"split": "train" if i < 60 else "val" if i < 80 else "test",
|
| 106 |
+
"latlon": [float(i), 0.0],
|
| 107 |
+
}
|
| 108 |
+
for i, id_ in enumerate(ids)
|
| 109 |
+
]
|
| 110 |
+
labels = root / "eval/lfmc/labels.json"
|
| 111 |
+
labels.parent.mkdir(parents=True)
|
| 112 |
+
labels.write_text(json.dumps(rows))
|
| 113 |
+
names = [n for pair in pairs for n in pair] + ["large-raw"]
|
| 114 |
+
for name in names:
|
| 115 |
+
x = rng.normal(size=(len(y), 8))
|
| 116 |
+
if name.startswith("train-") or name == "large-raw":
|
| 117 |
+
x[:, 0] = y
|
| 118 |
+
feature = root / "features" / f"{name}-lfmc" / "features.npz"
|
| 119 |
+
feature.parent.mkdir(parents=True)
|
| 120 |
+
np.savez(feature, ids=ids, features=x.astype(np.float32))
|
| 121 |
+
x = x.astype(np.float32).astype(np.float64)
|
| 122 |
+
model = make_pipeline(StandardScaler(), Ridge(alpha=1.0)).fit(
|
| 123 |
+
x[:60], y[:60]
|
| 124 |
+
)
|
| 125 |
+
report = {
|
| 126 |
+
"features": str(feature),
|
| 127 |
+
"probe": {
|
| 128 |
+
"selected_parameter": 1.0,
|
| 129 |
+
"validation": {
|
| 130 |
+
"mae": float(
|
| 131 |
+
np.abs(model.predict(x[60:80]) - y[60:80]).mean()
|
| 132 |
+
)
|
| 133 |
+
},
|
| 134 |
+
},
|
| 135 |
+
}
|
| 136 |
+
(root / "results" / f"{name}-lfmc.json").write_text(json.dumps(report))
|
| 137 |
+
for seed, loader, pair in zip(seeds, loader_seeds, pairs):
|
| 138 |
+
for index, name in enumerate(pair):
|
| 139 |
+
package = root / "packages" / name
|
| 140 |
+
package.mkdir(parents=True)
|
| 141 |
+
(package / "encoder.pt").write_bytes(name.encode())
|
| 142 |
+
sha = hashlib.sha256(name.encode()).hexdigest()
|
| 143 |
+
provenance = {
|
| 144 |
+
"origin": "random_initialization"
|
| 145 |
+
if index == 0
|
| 146 |
+
else "own_from_scratch_training",
|
| 147 |
+
"initialization_seed": seed,
|
| 148 |
+
"data_seed": loader if index else None,
|
| 149 |
+
"training_recipe": recipe if index else None,
|
| 150 |
+
"variant": "v1/large",
|
| 151 |
+
"parameters": 307770368,
|
| 152 |
+
"infer_sha256": "fixture",
|
| 153 |
+
"encoder_sha256": sha,
|
| 154 |
+
}
|
| 155 |
+
if index == 0 and seed == seeds[0]:
|
| 156 |
+
del provenance["origin"]
|
| 157 |
+
provenance["checkpoint"] = None
|
| 158 |
+
(package / "provenance.json").write_text(json.dumps(provenance))
|
| 159 |
+
if name == lock["selected"]:
|
| 160 |
+
lock["encoder_sha256"] = sha
|
| 161 |
+
lock_path.write_text(json.dumps(lock))
|
| 162 |
+
comparison["tasks"]["lfmc"]["three_seed_criterion_met"] = True
|
| 163 |
+
comparison["tasks"]["lfmc"].update(
|
| 164 |
+
per_seed_gain=[1.0, 1.0, 1.0],
|
| 165 |
+
mean_seed_gain=1.0,
|
| 166 |
+
spatial_bootstrap_95_percent_interval=[0.1, 2.0],
|
| 167 |
+
seed_and_spatial_bootstrap_95_percent_interval=[0.1, 2.0],
|
| 168 |
+
)
|
| 169 |
+
comparison["tasks"]["lfmc"][
|
| 170 |
+
"seed_and_spatial_bootstrap_95_percent_interval"
|
| 171 |
+
][0] = -0.1
|
| 172 |
+
comparison_path.write_text(json.dumps(comparison))
|
| 173 |
+
failed = subprocess.run(cmd, env=env, capture_output=True, text=True)
|
| 174 |
+
self.assertNotEqual(failed.returncode, 0)
|
| 175 |
+
self.assertIn("flag disagrees", failed.stderr)
|
| 176 |
+
self.assertFalse((root / "test.json").exists())
|
| 177 |
+
comparison["tasks"]["lfmc"][
|
| 178 |
+
"seed_and_spatial_bootstrap_95_percent_interval"
|
| 179 |
+
][0] = 0.1
|
| 180 |
+
comparison_path.write_text(json.dumps(comparison))
|
| 181 |
+
run = subprocess.run(cmd, env=env, capture_output=True, text=True)
|
| 182 |
+
self.assertEqual(run.returncode, 0, run.stderr)
|
| 183 |
+
first = json.loads((root / "test.json").read_text())
|
| 184 |
+
self.assertEqual(first["paired_random_comparison"]["rows"], 20)
|
| 185 |
+
self.assertEqual(first["paired_random_comparison"]["groups"], 20)
|
| 186 |
+
repeated = subprocess.run(cmd, env=env, capture_output=True, text=True)
|
| 187 |
+
self.assertNotEqual(repeated.returncode, 0)
|
| 188 |
+
for row in rows[80:]:
|
| 189 |
+
row["label"] += 100
|
| 190 |
+
labels.write_text(json.dumps(rows))
|
| 191 |
+
cmd[-1] = str(root / "changed-test-labels.json")
|
| 192 |
+
run = subprocess.run(cmd, env=env, capture_output=True, text=True)
|
| 193 |
+
self.assertEqual(run.returncode, 0, run.stderr)
|
| 194 |
+
altered = json.loads((root / "changed-test-labels.json").read_text())
|
| 195 |
+
for name in names:
|
| 196 |
+
self.assertEqual(
|
| 197 |
+
first["models"][name]["selected_alpha_from_validation"],
|
| 198 |
+
altered["models"][name]["selected_alpha_from_validation"],
|
| 199 |
+
)
|
| 200 |
+
self.assertEqual(
|
| 201 |
+
first["models"][name]["validation_mae_check"],
|
| 202 |
+
altered["models"][name]["validation_mae_check"],
|
| 203 |
+
)
|
| 204 |
+
self.assertNotEqual(
|
| 205 |
+
first["models"][name]["test_mae"],
|
| 206 |
+
altered["models"][name]["test_mae"],
|
| 207 |
+
)
|
| 208 |
+
changed = root / "packages" / pairs[1][1] / "provenance.json"
|
| 209 |
+
provenance = json.loads(changed.read_text())
|
| 210 |
+
provenance["training_recipe"] = {"different": True}
|
| 211 |
+
changed.write_text(json.dumps(provenance))
|
| 212 |
+
cmd[-1] = str(root / "bad-recipe.json")
|
| 213 |
+
run = subprocess.run(cmd, env=env, capture_output=True, text=True)
|
| 214 |
+
self.assertNotEqual(run.returncode, 0)
|
| 215 |
+
self.assertIn("Training recipe differs", run.stderr)
|
| 216 |
+
self.assertFalse((root / "bad-recipe.json").exists())
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
if __name__ == "__main__":
|
| 220 |
+
unittest.main()
|