Ravenveil commited on
Commit
e581637
·
verified ·
1 Parent(s): 486bb77

upload reference paper code (RAF, OVOW, ViPE, PhysGen3D, Taichi MPM, PSIVG, Mitsuba, 4DCodeBench, PhysLoop, IMPACT note)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +72 -0
  2. 论文参考代码/4DCodeBench/.dockerignore +9 -0
  3. 论文参考代码/4DCodeBench/.gitignore +18 -0
  4. 论文参考代码/4DCodeBench/README.md +344 -0
  5. 论文参考代码/4DCodeBench/assets/logo.png +3 -0
  6. 论文参考代码/4DCodeBench/assets/logo_dark.png +3 -0
  7. 论文参考代码/4DCodeBench/assets/teaser.jpg +3 -0
  8. 论文参考代码/4DCodeBench/checker/__init__.py +1 -0
  9. 论文参考代码/4DCodeBench/checker/__main__.py +22 -0
  10. 论文参考代码/4DCodeBench/checker/check.py +409 -0
  11. 论文参考代码/4DCodeBench/checker/paths.py +19 -0
  12. 论文参考代码/4DCodeBench/checker/preview.py +149 -0
  13. 论文参考代码/4DCodeBench/checker/solution.py +55 -0
  14. 论文参考代码/4DCodeBench/config/__init__.py +1 -0
  15. 论文参考代码/4DCodeBench/config/annotation.py +9 -0
  16. 论文参考代码/4DCodeBench/config/estimates.py +58 -0
  17. 论文参考代码/4DCodeBench/config/models.py +38 -0
  18. 论文参考代码/4DCodeBench/config/sampling.py +45 -0
  19. 论文参考代码/4DCodeBench/config/scorer.py +6 -0
  20. 论文参考代码/4DCodeBench/config/uni3d.py +25 -0
  21. 论文参考代码/4DCodeBench/config/world.py +32 -0
  22. 论文参考代码/4DCodeBench/docs/agent-setup.md +39 -0
  23. 论文参考代码/4DCodeBench/docs/checkpoints.md +55 -0
  24. 论文参考代码/4DCodeBench/docs/spec.md +191 -0
  25. 论文参考代码/4DCodeBench/environment.yml +25 -0
  26. 论文参考代码/4DCodeBench/harness/agent/Dockerfile +45 -0
  27. 论文参考代码/4DCodeBench/harness/agent_context/TASK.md +91 -0
  28. 论文参考代码/4DCodeBench/harness/agent_context/render-settings.md +80 -0
  29. 论文参考代码/4DCodeBench/harness/agent_context/world-format.md +135 -0
  30. 论文参考代码/4DCodeBench/harness/apptainer/10_nvidia.json +6 -0
  31. 论文参考代码/4DCodeBench/harness/base/Dockerfile +65 -0
  32. 论文参考代码/4DCodeBench/harness/base/verify_gpu.py +216 -0
  33. 论文参考代码/4DCodeBench/harness/runtime/agents.py +96 -0
  34. 论文参考代码/4DCodeBench/harness/runtime/common.py +211 -0
  35. 论文参考代码/4DCodeBench/harness/runtime/cost.py +301 -0
  36. 论文参考代码/4DCodeBench/harness/runtime/infer.py +401 -0
  37. 论文参考代码/4DCodeBench/harness/runtime/jobs.py +53 -0
  38. 论文参考代码/4DCodeBench/harness/runtime/launch.py +169 -0
  39. 论文参考代码/4DCodeBench/harness/runtime/score.py +210 -0
  40. 论文参考代码/4DCodeBench/harness/runtime/templates/jobs.example.toml +16 -0
  41. 论文参考代码/4DCodeBench/harness/runtime/templates/runtime.example.toml +67 -0
  42. 论文参考代码/4DCodeBench/harness/scorer/Dockerfile +65 -0
  43. 论文参考代码/4DCodeBench/harness/scorer/requirements-cuda.txt +7 -0
  44. 论文参考代码/4DCodeBench/harness/scorer/requirements-nodeps.txt +3 -0
  45. 论文参考代码/4DCodeBench/harness/scorer/requirements.txt +13 -0
  46. 论文参考代码/4DCodeBench/harness/stirrup/local_backend.py +559 -0
  47. 论文参考代码/4DCodeBench/harness/stirrup/runner.py +311 -0
  48. 论文参考代码/4DCodeBench/scorer/__init__.py +6 -0
  49. 论文参考代码/4DCodeBench/scorer/__main__.py +100 -0
  50. 论文参考代码/4DCodeBench/scorer/analytic/__init__.py +6 -0
.gitattributes CHANGED
@@ -4639,3 +4639,75 @@ OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_anim_blender_physi
4639
  OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_anim_blender_physics_with_deform.glb filter=lfs diff=lfs merge=lfs -text
4640
  OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_point_cloud_frame_all.ply filter=lfs diff=lfs merge=lfs -text
4641
  02_PHYSIC_Training-Free-Particle-Guidance/paper.pdf filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4639
  OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_anim_blender_physics_with_deform.glb filter=lfs diff=lfs merge=lfs -text
4640
  OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_point_cloud_frame_all.ply filter=lfs diff=lfs merge=lfs -text
4641
  02_PHYSIC_Training-Free-Particle-Guidance/paper.pdf filter=lfs diff=lfs merge=lfs -text
4642
+ 论文参考代码/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/city.exr filter=lfs diff=lfs merge=lfs -text
4643
+ 论文参考代码/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/courtyard.exr filter=lfs diff=lfs merge=lfs -text
4644
+ 论文参考代码/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/forest.exr filter=lfs diff=lfs merge=lfs -text
4645
+ 论文参考代码/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/interior.exr filter=lfs diff=lfs merge=lfs -text
4646
+ 论文参考代码/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/night.exr filter=lfs diff=lfs merge=lfs -text
4647
+ 论文参考代码/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunrise.exr filter=lfs diff=lfs merge=lfs -text
4648
+ 论文参考代码/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunset.exr filter=lfs diff=lfs merge=lfs -text
4649
+ 论文参考代码/PhysGen3D/data/hdr/apple.exr filter=lfs diff=lfs merge=lfs -text
4650
+ 论文参考代码/PhysGen3D/data/hdr/apple_pillow.exr filter=lfs diff=lfs merge=lfs -text
4651
+ 论文参考代码/PhysGen3D/data/hdr/bowl.exr filter=lfs diff=lfs merge=lfs -text
4652
+ 论文参考代码/PhysGen3D/data/hdr/bowling.exr filter=lfs diff=lfs merge=lfs -text
4653
+ 论文参考代码/PhysGen3D/data/hdr/box.exr filter=lfs diff=lfs merge=lfs -text
4654
+ 论文参考代码/PhysGen3D/data/hdr/car2.exr filter=lfs diff=lfs merge=lfs -text
4655
+ 论文参考代码/PhysGen3D/data/hdr/car_in_mountain.exr filter=lfs diff=lfs merge=lfs -text
4656
+ 论文参考代码/PhysGen3D/data/hdr/car_on_road.exr filter=lfs diff=lfs merge=lfs -text
4657
+ 论文参考代码/PhysGen3D/data/hdr/car_toy.exr filter=lfs diff=lfs merge=lfs -text
4658
+ 论文参考代码/PhysGen3D/data/hdr/car_toy2.exr filter=lfs diff=lfs merge=lfs -text
4659
+ 论文参考代码/PhysGen3D/data/hdr/cat.exr filter=lfs diff=lfs merge=lfs -text
4660
+ 论文参考代码/PhysGen3D/data/hdr/clock.exr filter=lfs diff=lfs merge=lfs -text
4661
+ 论文参考代码/PhysGen3D/data/hdr/dog.exr filter=lfs diff=lfs merge=lfs -text
4662
+ 论文参考代码/PhysGen3D/data/hdr/fox.exr filter=lfs diff=lfs merge=lfs -text
4663
+ 论文参考代码/PhysGen3D/data/hdr/fox2.exr filter=lfs diff=lfs merge=lfs -text
4664
+ 论文参考代码/PhysGen3D/data/hdr/golf.exr filter=lfs diff=lfs merge=lfs -text
4665
+ 论文参考代码/PhysGen3D/data/hdr/greenapple.exr filter=lfs diff=lfs merge=lfs -text
4666
+ 论文参考代码/PhysGen3D/data/hdr/kitchen.exr filter=lfs diff=lfs merge=lfs -text
4667
+ 论文参考代码/PhysGen3D/data/hdr/manyapple.exr filter=lfs diff=lfs merge=lfs -text
4668
+ 论文参考代码/PhysGen3D/data/hdr/multiobject.exr filter=lfs diff=lfs merge=lfs -text
4669
+ 论文参考代码/PhysGen3D/data/hdr/panda2.exr filter=lfs diff=lfs merge=lfs -text
4670
+ 论文参考代码/PhysGen3D/data/hdr/pencil.exr filter=lfs diff=lfs merge=lfs -text
4671
+ 论文参考代码/PhysGen3D/data/hdr/potato.exr filter=lfs diff=lfs merge=lfs -text
4672
+ 论文参考代码/PhysGen3D/data/hdr/rabbit.exr filter=lfs diff=lfs merge=lfs -text
4673
+ 论文参考代码/PhysGen3D/data/hdr/sphinx.exr filter=lfs diff=lfs merge=lfs -text
4674
+ 论文参考代码/PhysGen3D/data/hdr/tabletop.exr filter=lfs diff=lfs merge=lfs -text
4675
+ 论文参考代码/PhysGen3D/data/hdr/tabletop2.exr filter=lfs diff=lfs merge=lfs -text
4676
+ 论文参考代码/PhysGen3D/data/hdr/tabletop3.exr filter=lfs diff=lfs merge=lfs -text
4677
+ 论文参考代码/PhysGen3D/data/hdr/teddy.exr filter=lfs diff=lfs merge=lfs -text
4678
+ 论文参考代码/PhysGen3D/data/hdr/tennis.exr filter=lfs diff=lfs merge=lfs -text
4679
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/meshes/Airplane/textures/diffuse.dds filter=lfs diff=lfs merge=lfs -text
4680
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/meshes/chopping-board/source/chopping_board.glb filter=lfs diff=lfs merge=lfs -text
4681
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/meshes/icecream_dispenser.obj filter=lfs diff=lfs merge=lfs -text
4682
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/urdf/go2/dae/base.dae filter=lfs diff=lfs merge=lfs -text
4683
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/urdf/kuka_iiwa/meshes/link_0.stl filter=lfs diff=lfs merge=lfs -text
4684
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/urdf/kuka_iiwa/meshes/link_1.stl filter=lfs diff=lfs merge=lfs -text
4685
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/hand.stl filter=lfs diff=lfs merge=lfs -text
4686
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link0.stl filter=lfs diff=lfs merge=lfs -text
4687
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link1.stl filter=lfs diff=lfs merge=lfs -text
4688
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link2.stl filter=lfs diff=lfs merge=lfs -text
4689
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link3.stl filter=lfs diff=lfs merge=lfs -text
4690
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link4.stl filter=lfs diff=lfs merge=lfs -text
4691
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link5.stl filter=lfs diff=lfs merge=lfs -text
4692
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link5_dark.stl filter=lfs diff=lfs merge=lfs -text
4693
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link6.stl filter=lfs diff=lfs merge=lfs -text
4694
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link6_dark.stl filter=lfs diff=lfs merge=lfs -text
4695
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link7.stl filter=lfs diff=lfs merge=lfs -text
4696
+ 论文参考代码/RAF/third_party/genesis-world/genesis/assets/xml/franka_sim/meshes/visual/link7_dark.stl filter=lfs diff=lfs merge=lfs -text
4697
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/ParticleMesher/ParticleMesherPy/libboost_iostreams.so.1.73.0 filter=lfs diff=lfs merge=lfs -text
4698
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/ParticleMesher/ParticleMesherPy/libopenvdb.so.11.0 filter=lfs diff=lfs merge=lfs -text
4699
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/ParticleMesher/ParticleMesherPy/libparticle_mesher.so filter=lfs diff=lfs merge=lfs -text
4700
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/ParticleMesher/ParticleMesherPy/libtbb.so.12 filter=lfs diff=lfs merge=lfs -text
4701
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/ParticleMesher/ParticleMesherPy/ParticleMesherPy.cpython-39-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
4702
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/OpenSans-Bold.ttf filter=lfs diff=lfs merge=lfs -text
4703
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/OpenSans-BoldItalic.ttf filter=lfs diff=lfs merge=lfs -text
4704
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/OpenSans-ExtraBold.ttf filter=lfs diff=lfs merge=lfs -text
4705
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/OpenSans-ExtraBoldItalic.ttf filter=lfs diff=lfs merge=lfs -text
4706
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/OpenSans-Italic.ttf filter=lfs diff=lfs merge=lfs -text
4707
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/OpenSans-Light.ttf filter=lfs diff=lfs merge=lfs -text
4708
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/OpenSans-LightItalic.ttf filter=lfs diff=lfs merge=lfs -text
4709
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/OpenSans-Regular.ttf filter=lfs diff=lfs merge=lfs -text
4710
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/OpenSans-Semibold.ttf filter=lfs diff=lfs merge=lfs -text
4711
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/OpenSans-SemiboldItalic.ttf filter=lfs diff=lfs merge=lfs -text
4712
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/pyrender/fonts/UbuntuMono-Regular.ttf filter=lfs diff=lfs merge=lfs -text
4713
+ 论文参考代码/RAF/third_party/genesis-world/genesis/ext/VolumeSampling filter=lfs diff=lfs merge=lfs -text
论文参考代码/4DCodeBench/.dockerignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .auth
3
+ .local
4
+ cases
5
+ data
6
+ runs
7
+ __pycache__
8
+ *.pyc
9
+ checkpoints
论文参考代码/4DCodeBench/.gitignore ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+
4
+ # credentials and local configuration
5
+ .env
6
+ .auth/
7
+ .local/
8
+
9
+ # data
10
+ /cases
11
+ /data
12
+ /runs
13
+ # 4DCodeBench/Results before scripts/place_renders.py, and the judge's frame cache
14
+ /results
15
+ frame_cache/
16
+
17
+ # model weights, from scripts/download_checkpoints.sh
18
+ /checkpoints
论文参考代码/4DCodeBench/README.md ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="./assets/logo_dark.png">
4
+ <img src="./assets/logo.png" width="360" alt="4DCodeBench logo">
5
+ </picture>
6
+ </p>
7
+
8
+ <h1 align="center">4DCodeBench: Benchmarking Agents on Inverse Graphics of Dynamic Scenes</h1>
9
+
10
+ <div align="center">
11
+ <p>
12
+ <a href="https://ruihong04.github.io/">Ruihong Shen</a><sup>1*†</sup>&nbsp;&nbsp;
13
+ <a href="https://zzigak.github.io/">Žiga Kovačič</a><sup>2*</sup>&nbsp;&nbsp;
14
+ <a href="https://kulits.github.io/">Peter Kulits</a><sup>2,3*</sup>&nbsp;&nbsp;
15
+ <a href="https://xingruiwang.github.io/">Xingrui Wang</a><sup>1</sup>&nbsp;&nbsp;
16
+ <a href="https://kyleleey.github.io/">Zizhang Li</a><sup>2</sup>&nbsp;&nbsp;
17
+ <a href="https://cocosci.mit.edu/josh-tenenbaum/">Joshua B. Tenenbaum</a><sup>4</sup>&nbsp;&nbsp;
18
+ <a href="https://www.cs.jhu.edu/~ayuille/">Alan Yuille</a><sup>1</sup>&nbsp;&nbsp;
19
+ <a href="https://beckschen.github.io/">Jieneng Chen</a><sup>2‡</sup>&nbsp;&nbsp;
20
+ <a href="https://jiajunwu.com/">Jiajun Wu</a><sup>2‡</sup>
21
+ </p>
22
+ <p>
23
+ <sup>1</sup>Johns Hopkins University &nbsp;&nbsp;&nbsp;
24
+ <sup>2</sup>Stanford University &nbsp;&nbsp;&nbsp;
25
+ <sup>3</sup>Max Planck Institute for Intelligent Systems &nbsp;&nbsp;&nbsp;
26
+ <sup>4</sup>Massachusetts Institute of Technology
27
+ </p>
28
+ <p>
29
+ <sup>*</sup> Equal contribution, listed in random order &nbsp;&nbsp;&nbsp;
30
+ <sup>‡</sup> Equal co-advising &nbsp;&nbsp;&nbsp;
31
+ <sup>†</sup> Work done during a summer internship.
32
+ </p>
33
+ </div>
34
+
35
+ <p align="center">
36
+ <a href='https://4dcodebench.com/' target="_blank">
37
+ <img src='https://img.shields.io/badge/Project-Page-blue?style=plastic&logo=google-chrome&logoColor=white' alt='Project Page'>
38
+ </a>
39
+ <a href='https://arxiv.org/abs/2610.03715' target="_blank">
40
+ <img src='https://img.shields.io/badge/Paper-Arxiv-B31B1B?style=plastic&logo=arxiv&logoColor=white' alt='Paper'>
41
+ </a>
42
+ <a href='https://huggingface.co/4DCodeBench' target="_blank">
43
+ <img src='https://img.shields.io/badge/Dataset-Hugging_Face-yellow?style=plastic&logo=huggingface&logoColor=white' alt='Dataset'>
44
+ </a>
45
+ </p>
46
+
47
+ <img src='./assets/teaser.jpg'>
48
+
49
+ Can a coding agent watch a video of a physical event and write a program that reconstructs it? 4DCodeBench tests this on 200 videos: 100 real-world videos and 100 simulated videos. For each video, the agent writes graphics code to reproduce the scene's geometry, its motion over time, and its appearance in the rendered video.
50
+
51
+ The benchmark has two main stages. **Inference** runs a coding agent on a reference video and saves its submission. **Scoring** evaluates that submission against the reference. The harness is the set of scripts that launches these stages, supplies their inputs, and collects their outputs. A separate viewer lets you inspect the reconstructions and scores.
52
+
53
+ ## News
54
+
55
+ - **2026-10-08**: Released [Dataset-Model-Estimation](https://huggingface.co/datasets/4DCodeBench/Dataset-Model-Estimation), the precomputed reference estimates for scoring.
56
+ - **2026-10-05**: Paper released on [arXiv](https://arxiv.org/abs/2610.03715).
57
+
58
+ ## Setup
59
+
60
+ ### Clone the repository
61
+
62
+ ```bash
63
+ git clone https://github.com/4DCodeBench/4DCodeBench
64
+ cd 4DCodeBench
65
+ ```
66
+
67
+ Run the commands below from the repository root unless stated otherwise.
68
+
69
+ ### Requirements
70
+
71
+ To run agents and score their submissions, you need an NVIDIA GPU and Python 3.11 or later on the host. The host runs the harness; the agent and scorer have their own environments.
72
+
73
+ - **Inference:** Docker with the NVIDIA Container Toolkit, or SingularityCE / Apptainer, to run the agent container. You also need credentials for the agent you choose; see [agent setup](docs/agent-setup.md).
74
+ - **Scoring:** the scorer container, or the [conda environment](#conda-environment) for running the scoring stages directly. Scoring also requires [model checkpoints](docs/checkpoints.md) for the models used to evaluate the reconstruction.
75
+ - **VLM-as-judge, if you use it:** an [OpenRouter API key](https://openrouter.ai/keys), set as `OPENROUTER_API_KEY`, and FFmpeg. This is a separate evaluation described [below](#vlm-as-judge).
76
+
77
+ ### Build the container images
78
+
79
+ A container image packages the software needed to run a stage. The harness starts a container from that image for each agent run or scoring process, so those dependencies do not need to be installed on the host.
80
+
81
+ Inference uses the `agent` image, which includes the graphics tools, agent CLIs, and submission checker. Scoring uses a separate `scorer` image with the evaluation models' dependencies and visualization tools. The `sim-base` image supplies the shared graphics environment from which the agent image is built.
82
+
83
+ For Docker, build the images from the repository root:
84
+
85
+ ```bash
86
+ docker build -t 4dcb/sim-base:dev -f harness/base/Dockerfile .
87
+ docker build -t 4dcb/agent:dev -f harness/agent/Dockerfile .
88
+ docker build -t 4dcb/scorer:dev -f harness/scorer/Dockerfile .
89
+ ```
90
+
91
+ | Image | Used for | Included software |
92
+ |---|---|---|
93
+ | `sim-base` | Building the agent image | CUDA 13, Blender 5.2, and PyTorch |
94
+ | `agent` | Running coding agents | `sim-base`, agent CLIs, and the checker |
95
+ | `scorer` | Scoring submissions and generating visualizations | PyTorch with CUDA 13, OpenVDB, the scorer, and the visualizer |
96
+
97
+ If you are only running inference, build `sim-base` and `agent`. If you are scoring existing submissions, you need the scorer environment.
98
+
99
+ For SingularityCE / Apptainer, convert the runtime images to SIF files:
100
+
101
+ ```bash
102
+ apptainer build 4dcb-agent-dev.sif docker-daemon://4dcb/agent:dev
103
+ apptainer build 4dcb-scorer-dev.sif docker-daemon://4dcb/scorer:dev
104
+ ```
105
+
106
+ Set `backend = "sif"` in the runtime configuration and configure it to use the corresponding SIF files.
107
+
108
+ ### Conda environment
109
+
110
+ You can also run the scorer, visualizer, and viewer in a conda environment. This uses the same package versions as the scorer image and supports [running the scoring stages directly](#running-the-stages-directly).
111
+
112
+ ```bash
113
+ conda env create -f environment.yml
114
+ conda activate 4dcodebench
115
+ scripts/setup_env.sh
116
+ ```
117
+
118
+ `environment.yml` installs Python 3.12, the CUDA 13.0 toolkit, FFmpeg, and OpenVDB. `scripts/setup_env.sh` then installs PyTorch and the pinned packages from `harness/scorer/requirements*.txt` using uv, compiles CUDA extensions for the local GPUs, and builds `scorer-vdb`.
119
+
120
+ ## Download the data
121
+
122
+ Each benchmark case has a reference video for the agent and separate data for evaluation. Download both if you plan to run inference and scoring:
123
+
124
+ ```bash
125
+ python scripts/download_data.py
126
+ ```
127
+
128
+ If you only want to run agents, the reference videos are enough:
129
+
130
+ ```bash
131
+ python scripts/download_data.py --videos-only
132
+ ```
133
+
134
+ The script downloads [Dataset-Real-World](https://huggingface.co/datasets/4DCodeBench/Dataset-Real-World) and [Dataset-Synthetic](https://huggingface.co/datasets/4DCodeBench/Dataset-Synthetic) into `cases/` and `data/`. Add `--kind real` or `--kind synthetic` to download only one dataset, and `--estimates` to also download the precomputed reference estimates from [Dataset-Model-Estimation](https://huggingface.co/datasets/4DCodeBench/Dataset-Model-Estimation) (53 GB). Files already in place are skipped, so you can resume an interrupted download by running the command again.
135
+
136
+ The download script requires `huggingface_hub`, `h5py`, `hdf5plugin`, `numpy`, `opencv-python`, and FFmpeg. The synthetic reference worlds occupy about 65 GB once unpacked.
137
+
138
+ ### Where inputs and outputs are stored
139
+
140
+ The workflow uses three directories under the repository root:
141
+
142
+ - **`cases/`** holds the reference videos shown to agents.
143
+ - **`data/`** holds evaluation data, including reference geometry for synthetic cases and dynamic masks for real cases. The scoring preparation stage also writes its reference estimates here.
144
+ - **`runs/`** holds agent submissions, logs, scores, and visualizations.
145
+
146
+ ```text
147
+ cases/<kind>/<case>/
148
+ └── reference.mp4
149
+ data/<kind>/<case>/
150
+ ├── world/
151
+ ├── annotation/
152
+ │ └── dynamic_mask.npz
153
+ └── estimates/
154
+ runs/<kind>/<case>/<agent>-<model>-<effort>/<trial>/
155
+ ├── workspace/
156
+ │ ├── world/
157
+ │ └── solution/
158
+ ├── logs/
159
+ ├── session/
160
+ ├── run.json
161
+ ├── results/
162
+ └── viz/
163
+ ```
164
+
165
+ Here, `<kind>` is `real` or `synthetic`, `<case>` identifies the video, and `<trial>` identifies a repeated run. In job configuration, the `case` field accepts either `<case>` or `<kind>/<case>`.
166
+
167
+ The agent receives only `reference.mp4` from the case files; evaluation data in `data/` is not mounted into its container. For synthetic cases, `data/<kind>/<case>/world/` contains the reference world. For real cases, `annotation/dynamic_mask.npz` contains the annotated dynamic mask. The `prepare` stage writes reference estimates to `estimates/`.
168
+
169
+ Each run saves the reconstructed world under `workspace/world/` and the agent's solution under `workspace/solution/`. Agent logs and CLI session transcripts go into `logs/` and `session/`. `run.json` records the command, exit status, wall time, token usage, cost, and step counts. Scoring writes to `results/`, and visualization writes to `viz/`.
170
+
171
+ ## Run agents
172
+
173
+ ### Configure the jobs and runtime
174
+
175
+ The inference and scoring harness commands each take two TOML files: one describes the runs you want, and the other describes how to run them on your machine. Copy the templates from `harness/runtime/templates/` into `.local/` and fill them in. The commands below use `.local/jobs.toml` and `.local/runtime.toml`.
176
+
177
+ | Argument | Configuration |
178
+ |---|---|
179
+ | `--jobs` | The cases, agents, models, effort settings, and trial count |
180
+ | `--runtime` | Data directories, container images, time limits, network settings, credentials, and checkpoint directory |
181
+
182
+ In the jobs file, each `[[job]]` entry specifies `case`, `agent`, `model`, and `effort`. The top-level `trials` value determines how many times each entry runs. An entry with its own `trial = N` runs only that trial.
183
+
184
+ ### Set up agent credentials
185
+
186
+ Each agent needs access to its model provider. For agents that use a credential file, place or link that file under `.auth/`; the harness mounts it only into that agent's container. See [agent setup](docs/agent-setup.md) for login and credential-linking instructions.
187
+
188
+ | Agent | CLI | Credential file | Credential source |
189
+ |---|---|---|---|
190
+ | `claude` | Claude Code | `.auth/claude.json` | `~/.claude/.credentials.json` |
191
+ | `codex` | Codex CLI | `.auth/gpt.json` | `~/.codex/auth.json` |
192
+ | `antigravity` | Antigravity CLI | `.auth/gemini.json` | Antigravity OAuth token |
193
+ | `stirrup` | Artificial Analysis' Stirrup, for any OpenAI-compatible endpoint | None | `OPENAI_BASE_URL` and `OPENAI_API_KEY` under `[agent.stirrup.env]` |
194
+
195
+ ### Start inference
196
+
197
+ ```bash
198
+ python harness/runtime/infer.py --jobs .local/jobs.toml --runtime .local/runtime.toml
199
+ ```
200
+
201
+ For each run, the harness starts an agent container with a read-only task description at `/task` and the reference video at `/input/reference.mp4`. The task description includes the required world format and render settings. The agent works in `/workspace`, which is empty at the start.
202
+
203
+ These are paths inside the container. When the container exits, the harness keeps only the agent's `world/` and `solution/` output directories from `/workspace` and places them in the run's `workspace/` directory on the host. See [the specification](docs/spec.md) for the submission format.
204
+
205
+ Jobs run sequentially, each with the whole GPU and the wall-clock limit set by `[agent] timeout_sec` (6 hours by default). Re-running a trial replaces that trial's previous run.
206
+
207
+ Add `--dry-run` to print the container commands without starting the runs.
208
+
209
+ The harness estimates cost using [LiteLLM's price table](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json) at a pinned revision. If a model is missing from that table, its `cost_usd` is `null`.
210
+
211
+ ## Score submissions
212
+
213
+ Scoring uses the saved submissions in `runs/` and the evaluation data in `data/`. Configure the scorer image and checkpoint directory in the runtime file, and make sure you have downloaded the evaluation data and [model checkpoints](docs/checkpoints.md).
214
+
215
+ On the first scoring pass, run both preparation and scoring:
216
+
217
+ ```bash
218
+ python harness/runtime/score.py --jobs .local/jobs.toml --runtime .local/runtime.toml --stage prepare,score
219
+ ```
220
+
221
+ The two stages do different work:
222
+
223
+ 1. **`prepare`** computes reference estimates from each case's input video: optical flow, tracks, depth, a point map, and DINOv3 / TIPS features. These give the scorer reference measurements to compare with the reconstruction. They are stored in `data/<kind>/<case>/estimates/` and reused when scoring later runs of the same case. With `download_data.py --estimates`, they come precomputed and `prepare` can be skipped.
224
+ 2. **`score`** evaluates each submitted reconstruction and writes `reward.json`, `reward.detail.json`, and the arrays used by the metrics to that run's `results/` directory.
225
+
226
+ Once reference estimates exist, you can run scoring alone by omitting `--stage`; the default stage is `score`.
227
+
228
+ The harness splits runs across the GPUs listed in `CUDA_VISIBLE_DEVICES`. It starts one scorer container per GPU, and each container loads each model once for all of its runs.
229
+
230
+ ### Scoring options
231
+
232
+ - **`--stage <stages>`:** choose a comma-separated list of `prepare`, `score`, and `viz`. Selected stages always run in that order. Use `prepare,score,viz` to also generate videos showing the reference, reconstruction, and errors for flow, tracks, depth, dynamic masks, and DINOv3 / TIPS features. These videos are saved in each run's `viz/` directory.
233
+ - **`--type <types>`:** recompute selected metric types, such as `trajectory,semantic`, while keeping the other entries in `results/`.
234
+ - **`--sanity`:** also score each synthetic case's reference world and save the results in `data/<kind>/<case>/sanity/`. This shows how the metrics score a perfect reconstruction.
235
+ - **`--dry-run`:** print the container commands without running them.
236
+
237
+ ### Running the stages directly
238
+
239
+ If you use the [conda environment](#conda-environment), you can invoke the scorer and visualizer directly instead of launching them through `harness/runtime/score.py`. A JSON manifest tells these commands which worlds to evaluate and where to write their outputs.
240
+
241
+ For example, save the following as `manifest.json`:
242
+
243
+ ```json
244
+ [{"case": "synthetic/B_01", "world": "runs/synthetic/B_01/claude-claude-opus-5-high/1/workspace/world",
245
+ "out": "runs/synthetic/B_01/claude-claude-opus-5-high/1"}]
246
+ ```
247
+
248
+ Replace the example with your case and run paths. World paths in the manifest must start with `cases/`, `data/`, or `runs/`.
249
+
250
+ From the repository root, with the conda environment active:
251
+
252
+ ```bash
253
+ roots="--manifest manifest.json --cases cases --data data --checkpoints checkpoints"
254
+ python -m scorer.prepare $roots # compute reference estimates, once per case
255
+ python -m scorer $roots --runs runs # write metrics to each run's results/
256
+ python -m visualizer $roots --runs runs # optionally write videos to each run's viz/
257
+ ```
258
+
259
+ ## VLM-as-judge
260
+
261
+ Alongside the metrics below, the paper uses two evaluations in which a vision-language model judges rendered videos: visual question answering (VQA) and pairwise preference. In VQA, the judge answers questions about the videos; in pairwise evaluation, its preferences are used to compute Elo ratings.
262
+
263
+ The code in `vlm_judge/` runs these evaluations using videos in `cases/` and `runs/`. It requires FFmpeg and an OpenRouter API key:
264
+
265
+ ```bash
266
+ export OPENROUTER_API_KEY=...
267
+ python3 vlm_judge/judge.py vqa --system <agent>-<model>-<effort> --out answers.jsonl
268
+ python3 vlm_judge/judge.py score answers.jsonl
269
+ python3 vlm_judge/judge.py pairwise --out pairs.jsonl
270
+ python3 vlm_judge/judge.py elo pairs.jsonl
271
+ ```
272
+
273
+ Replace `<agent>-<model>-<effort>` with the system directory name used in your runs. The `vqa` command saves the judge's answers, and `score` scores those answers. The `pairwise` command saves preference judgments, and `elo` computes ratings from them.
274
+
275
+ To compare a new system with the systems in the paper, download their renders and place them under `runs/` before running the pairwise evaluation:
276
+
277
+ ```bash
278
+ hf download 4DCodeBench/Results --repo-type dataset --local-dir results
279
+ python scripts/place_renders.py results
280
+ ```
281
+
282
+ See [the VLM-as-judge README](vlm_judge/README.md) for prompts, gates, and scoring rules.
283
+
284
+ ## Inspect results in the viewer
285
+
286
+ The viewer is a read-only web interface for comparing reconstructions with their reference videos and inspecting scores. Start it from the repository root:
287
+
288
+ ```bash
289
+ python viewer/server.py --port 8130
290
+ ```
291
+
292
+ Then open [http://localhost:8130](http://localhost:8130). The server requires Python with `numpy` and `h5py`; the conda environment provides these dependencies.
293
+
294
+ By default, the viewer reads `cases/`, `data/`, and `runs/` under the repository root. Use `--cases`, `--data`, and `--runs` to point it at different directories.
295
+
296
+ - **Case view:** compare the render with the reference, watch the `viz/` videos, inspect submitted meshes and trajectories in 3D, and view per-frame measurements.
297
+ - **Results:** compare metrics averaged per model and effort setting.
298
+ - **Metrics:** read the definition of each metric.
299
+
300
+ ## Metrics
301
+
302
+ The metrics compare appearance, geometry, and motion. Real-world cases use video-based reference estimates and annotations; synthetic cases also provide reference worlds for 3D comparisons. The table shows which metrics apply to each dataset and the keys used in `reward.json`.
303
+
304
+ | Family | Metric | `reward.json` key | Cases |
305
+ |---|---|---|---|
306
+ | Perceptual | DINOv3 similarity | `semantic_dinov3` | All |
307
+ | 2D Dynamics | Flow | `flow_distribution` | Real |
308
+ | | Track2D | `track2d_dtw` | Real |
309
+ | | Dynamic IoU | `dynamic_iou` | All |
310
+ | 2.5D Geometry | Depth error (lower is better) | `depth_error` | Real |
311
+ | 3D Geometry | Scene 3D | `scene_3d` | Synthetic |
312
+ | 3D Dynamics | Trajectory DTW | `trajectory_dtw` | Synthetic |
313
+ | | EMD step | `emd_step` | Synthetic |
314
+ | Additional | TIPS similarity, GeoPhys DINOv3 | `semantic_tips`, `geophys_dinov3` | All |
315
+ | | Uni3D MoGe | `uni3d_moge_scene` | Real |
316
+ | | Uni3D point, Occupancy DTW | `uni3d_point_scene`, `occupancy_dtw` | Synthetic |
317
+ | Geometry quality | Watertight, manifold, non-degenerate, no self-intersection, no interpenetration | `mesh_*`, `interpenetration` | All |
318
+
319
+ All metrics range from 0 to 1, with higher values indicating better results, except depth error, which ranges from 0 to 2 and is lower-is-better. If a metric does not apply or cannot be computed, it records a state instead of a number: `not_applicable`, `excluded`, `error`, or `uncomputable`. See [the evaluation specification](docs/spec.md#evaluation) for definitions, gates, and states.
320
+
321
+ ## Repository layout
322
+
323
+ | Directory | Contents |
324
+ |---|---|
325
+ | `harness/` | Container build files, the task description given to agents (`agent_context/`), and the inference and scoring launchers (`infer.py` and `score.py`) |
326
+ | `checker/` | Public world-format checker, installed in the agent image |
327
+ | `scorer/` | Scoring code, installed in the scorer image; `prepare/` computes reference estimates |
328
+ | `visualizer/` | Code for generating scored runs' `viz/` videos, installed in the scorer image |
329
+ | `viewer/` | Read-only web viewer for scored runs |
330
+ | `vlm_judge/` | VQA and pairwise evaluations, prompts, and question set |
331
+ | `config/` | Constants shared by the checker and scorer |
332
+ | `scripts/` | `download_data.py`, `download_checkpoints.sh`, `setup_env.sh` (conda setup), and `place_renders.py` (the paper's renders for VLM-as-judge) |
333
+ | `docs/` | [World format and metrics](docs/spec.md), [agent setup](docs/agent-setup.md), and [model checkpoints](docs/checkpoints.md) |
334
+
335
+ ## Citation
336
+
337
+ ```bibtex
338
+ @article{shen20264dcodebench,
339
+ title={{4DCodeBench}: Benchmarking Agents on Inverse Graphics of Dynamic Scenes},
340
+ author={Shen, Ruihong and Kova{\v{c}}i{\v{c}}, {\v{Z}}iga and Kulits, Peter and Wang, Xingrui and Li, Zizhang and Tenenbaum, Joshua B. and Yuille, Alan and Chen, Jieneng and Wu, Jiajun},
341
+ journal={arXiv preprint arXiv:2610.03715},
342
+ year={2026}
343
+ }
344
+ ```
论文参考代码/4DCodeBench/assets/logo.png ADDED

Git LFS Details

  • SHA256: c14e9200f6f76a13941dac8b5dd555790aab40ea7187b3dc5a5b804ba5d6b205
  • Pointer size: 131 Bytes
  • Size of remote file: 370 kB
论文参考代码/4DCodeBench/assets/logo_dark.png ADDED

Git LFS Details

  • SHA256: 55a1ea8cb84b8cb8d8d198c8588cfeb03cc55fe0daf8b9d63e194637b2dd8219
  • Pointer size: 131 Bytes
  • Size of remote file: 310 kB
论文参考代码/4DCodeBench/assets/teaser.jpg ADDED

Git LFS Details

  • SHA256: 9fc9aef1117efee110aebb08bb946624aee60f8c0eb7a34c90aba1605b338be1
  • Pointer size: 131 Bytes
  • Size of remote file: 360 kB
论文参考代码/4DCodeBench/checker/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Agent-visible 4DCodeBench delivery checker."""
论文参考代码/4DCodeBench/checker/__main__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check the fixed Agent delivery directory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from .check import check_world
8
+ from .paths import SOLUTION_DIR, WORLD_DIR
9
+ from .solution import check_links, check_solution
10
+
11
+
12
+ def main() -> int:
13
+ violations = check_links(WORLD_DIR) + check_links(SOLUTION_DIR) + check_world(WORLD_DIR) + check_solution(SOLUTION_DIR)
14
+ for violation in violations:
15
+ print(violation)
16
+ return 1 if violations else 0
17
+
18
+
19
+ if __name__ == "__main__":
20
+ if len(sys.argv) != 1:
21
+ raise SystemExit("checker takes no arguments")
22
+ raise SystemExit(main())
论文参考代码/4DCodeBench/checker/check.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public format and self-consistency checks for one submitted world."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import re
8
+ import subprocess
9
+ import zipfile
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+
14
+ from config.world import (
15
+ CAMERA_EXTRINSIC_KEY,
16
+ CAMERA_FILENAME,
17
+ CAMERA_INTRINSICS_KEY,
18
+ DYNAMICS_DIRNAME,
19
+ DYNAMICS_FACES_KEY,
20
+ DYNAMICS_IDS_KEY,
21
+ DYNAMICS_POS_KEY,
22
+ DYNAMICS_TETS_KEY,
23
+ FACES_DTYPE,
24
+ INDEX_DTYPE,
25
+ MESH_FACES_KEY,
26
+ MESH_VERTICES_KEY,
27
+ MESHES_DIRNAME,
28
+ NPZ_SUFFIX,
29
+ POS_DTYPE,
30
+ VIDEO_FILENAME,
31
+ )
32
+
33
+ Violation = str
34
+ UNREADABLE = (OSError, zipfile.BadZipFile, ValueError, KeyError)
35
+ MEMBER_RE = re.compile(r"^(vertices|faces)_(\d{4})$")
36
+ ORTHONORMAL_TOL = 1e-4 # float32 round-off in a 3x3 product, not a judgement
37
+
38
+
39
+ def _msg(name: str, field: str, text: str) -> str:
40
+ return f"{name}: {field} {text}"
41
+
42
+
43
+ def check_world(root: str | Path) -> list[Violation]:
44
+ """Return every format or internal-consistency violation in one world."""
45
+
46
+ root = Path(root)
47
+ violations: list[Violation] = []
48
+
49
+ _, errors = _check_camera(root / CAMERA_FILENAME)
50
+ violations.extend(errors)
51
+
52
+ frame_count, errors = _check_video(root / VIDEO_FILENAME)
53
+ violations.extend(errors)
54
+
55
+ meshes, declared, errors = _check_meshes(root / MESHES_DIRNAME, frame_count)
56
+ violations.extend(errors)
57
+
58
+ moving, errors = _check_dynamics(root / DYNAMICS_DIRNAME, declared, frame_count)
59
+ violations.extend(errors)
60
+
61
+ # The static rule needs the full set of moving ids, so it waits for a readable dynamics/.
62
+ if moving is not None:
63
+ liquid, errors = _check_solver(root, set(meshes))
64
+ violations.extend(errors)
65
+ for oid in sorted(set(meshes) - moving - liquid):
66
+ violations.extend(_check_static(oid, meshes[oid]))
67
+ return violations
68
+
69
+
70
+ def _check_camera(path: Path) -> tuple[tuple[np.ndarray, np.ndarray] | None, list[Violation]]:
71
+ """Return `(intrinsics, extrinsic)` when both are well formed, and the violations."""
72
+
73
+ if not path.exists():
74
+ return None, [_msg(CAMERA_FILENAME, "path", "is required")]
75
+ try:
76
+ payload = json.loads(path.read_text(encoding="utf-8"))
77
+ except (OSError, json.JSONDecodeError) as exc:
78
+ return None, [_msg(CAMERA_FILENAME, "json", str(exc))]
79
+ if not isinstance(payload, dict):
80
+ return None, [_msg(CAMERA_FILENAME, "json", "must be an object")]
81
+
82
+ violations: list[Violation] = []
83
+ matrices: dict[str, np.ndarray] = {}
84
+ for key, shape in ((CAMERA_INTRINSICS_KEY, (3, 3)), (CAMERA_EXTRINSIC_KEY, (4, 4))):
85
+ if key not in payload:
86
+ violations.append(_msg(CAMERA_FILENAME, key, "is required"))
87
+ continue
88
+ try:
89
+ matrix = np.asarray(payload[key], dtype=np.float64)
90
+ except (TypeError, ValueError) as exc:
91
+ violations.append(_msg(CAMERA_FILENAME, key, f"is not numeric: {exc}"))
92
+ continue
93
+ if matrix.shape != shape:
94
+ violations.append(_msg(CAMERA_FILENAME, key, f"shape {matrix.shape} is not {shape}"))
95
+ elif not np.isfinite(matrix).all():
96
+ violations.append(_msg(CAMERA_FILENAME, key, "must be finite"))
97
+ else:
98
+ matrices[key] = matrix
99
+ if len(matrices) < 2:
100
+ return None, violations
101
+
102
+ rotation = matrices[CAMERA_EXTRINSIC_KEY][:3, :3]
103
+ if (np.abs(rotation.T @ rotation - np.eye(3)).max() > ORTHONORMAL_TOL
104
+ or np.linalg.det(rotation) < 0):
105
+ violations.append(_msg(CAMERA_FILENAME, CAMERA_EXTRINSIC_KEY,
106
+ "rotation block must be a proper orthonormal matrix"))
107
+ return None, violations
108
+ return (matrices[CAMERA_INTRINSICS_KEY], matrices[CAMERA_EXTRINSIC_KEY]), violations
109
+
110
+
111
+ def _check_video(path: Path) -> tuple[int | None, list[Violation]]:
112
+ """F is the frame count ffprobe reads from render.mp4."""
113
+
114
+ if not path.exists():
115
+ return None, [_msg(VIDEO_FILENAME, "path", "is required")]
116
+ command = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_frames",
117
+ "-show_entries", "stream=nb_read_frames", "-of", "json", str(path)]
118
+ result = subprocess.run(command, capture_output=True, text=True, check=False)
119
+ if result.returncode != 0:
120
+ return None, [_msg(VIDEO_FILENAME, "ffprobe", result.stderr.strip())]
121
+ try:
122
+ frames = int(json.loads(result.stdout)["streams"][0]["nb_read_frames"])
123
+ except (KeyError, IndexError, ValueError) as exc:
124
+ return None, [_msg(VIDEO_FILENAME, "ffprobe", f"missing frame count: {exc}")]
125
+ return frames, []
126
+
127
+
128
+ def _check_meshes(
129
+ directory: Path, frame_count: int | None
130
+ ) -> tuple[dict[int, dict[int, tuple[np.ndarray, np.ndarray]]], set[int], list[Violation]]:
131
+ """Return the loaded archives, every id a file name declares, and the violations."""
132
+
133
+ if not directory.is_dir():
134
+ return {}, set(), [_msg(MESHES_DIRNAME, "path", "is required")]
135
+
136
+ meshes: dict[int, dict[int, tuple[np.ndarray, np.ndarray]]] = {}
137
+ declared: set[int] = set()
138
+ violations: list[Violation] = []
139
+ for path in sorted(directory.iterdir()):
140
+ name = f"{MESHES_DIRNAME}/{path.name}"
141
+ if path.suffix != NPZ_SUFFIX or not path.stem.isdigit() or int(path.stem) <= 0:
142
+ violations.append(_msg(name, "name", "must be <positive id>.npz"))
143
+ continue
144
+ oid = int(path.stem)
145
+ if oid in declared:
146
+ violations.append(_msg(name, "id", f"{oid} is already declared"))
147
+ continue
148
+ declared.add(oid)
149
+ frames, errors = _read_mesh(name, path, frame_count)
150
+ violations.extend(errors)
151
+ if frames is not None:
152
+ meshes[oid] = frames
153
+ return meshes, declared, violations
154
+
155
+
156
+ def _read_mesh(
157
+ name: str, path: Path, frame_count: int | None
158
+ ) -> tuple[dict[int, tuple[np.ndarray, np.ndarray]] | None, list[Violation]]:
159
+ try:
160
+ with np.load(path) as data:
161
+ members = list(data.files)
162
+ stray = [key for key in members if not MEMBER_RE.match(key)]
163
+ if stray:
164
+ return None, [_msg(name, stray[0], "is not a vertices_TTTT/faces_TTTT member")]
165
+ vertex_frames = {int(key[-4:]) for key in members if key.startswith("vertices_")}
166
+ face_frames = {int(key[-4:]) for key in members if key.startswith("faces_")}
167
+ if not vertex_frames and not face_frames:
168
+ return None, [_msg(name, "members", "must hold at least one frame")]
169
+ if vertex_frames != face_frames:
170
+ odd = min(vertex_frames ^ face_frames)
171
+ return None, [_msg(name, f"frame {odd:04d}", "must pair vertices with faces")]
172
+ frames = sorted(vertex_frames)
173
+ if frames != list(range(frames[0], frames[-1] + 1)):
174
+ return None, [_msg(name, "frames", "must be one contiguous interval")]
175
+ if frame_count is not None and frames[-1] >= frame_count:
176
+ return None, [_msg(name, f"frame {frames[-1]:04d}",
177
+ f"is outside the {frame_count} frame timeline")]
178
+ loaded: dict[int, tuple[np.ndarray, np.ndarray]] = {}
179
+ for frame in frames:
180
+ pair, error = _check_frame_mesh(name, data, frame)
181
+ if error is not None:
182
+ return None, [error]
183
+ loaded[frame] = pair
184
+ except UNREADABLE as exc:
185
+ return None, [_msg(name, "npz", str(exc))]
186
+ return loaded, []
187
+
188
+
189
+ def _check_frame_mesh(name: str, data, frame: int) -> tuple[tuple[np.ndarray, np.ndarray] | None,
190
+ Violation | None]:
191
+ vertices_key, faces_key = MESH_VERTICES_KEY.format(frame=frame), MESH_FACES_KEY.format(frame=frame)
192
+ vertices, faces = data[vertices_key], data[faces_key]
193
+ if vertices.dtype != np.dtype(POS_DTYPE):
194
+ return None, _msg(name, vertices_key, f"dtype {vertices.dtype} != float32")
195
+ if vertices.ndim != 2 or vertices.shape[1] != 3:
196
+ return None, _msg(name, vertices_key, f"shape {vertices.shape} is not (V,3)")
197
+ if not np.isfinite(vertices).all():
198
+ return None, _msg(name, vertices_key, "must be finite")
199
+ if faces.dtype != np.dtype(FACES_DTYPE):
200
+ return None, _msg(name, faces_key, f"dtype {faces.dtype} != int32")
201
+ if faces.ndim != 2 or faces.shape[1] != 3:
202
+ return None, _msg(name, faces_key, f"shape {faces.shape} is not (T,3)")
203
+ if len(faces) and ((faces < 0).any() or faces.max() >= len(vertices)):
204
+ return None, _msg(name, faces_key, "index outside the vertex array")
205
+ return (vertices, faces), None
206
+
207
+
208
+ def _check_dynamics(
209
+ directory: Path, mesh_ids: set[int], frame_count: int | None
210
+ ) -> tuple[set[int] | None, list[Violation]]:
211
+ """Return the ids listed by every archive, or None when one could not be read."""
212
+
213
+ if not directory.is_dir():
214
+ return None, [_msg(DYNAMICS_DIRNAME, "path", "is required")]
215
+
216
+ moving: set[int] | None = set()
217
+ violations: list[Violation] = []
218
+ for path in sorted(directory.glob(f"*{NPZ_SUFFIX}")):
219
+ ids, errors = _read_dynamics(f"{DYNAMICS_DIRNAME}/{path.name}", path, mesh_ids, frame_count)
220
+ violations.extend(errors)
221
+ if ids is None:
222
+ moving = None
223
+ elif moving is not None:
224
+ moving.update(ids)
225
+ return moving, violations
226
+
227
+
228
+ def _read_dynamics(
229
+ name: str, path: Path, mesh_ids: set[int], frame_count: int | None
230
+ ) -> tuple[set[int] | None, list[Violation]]:
231
+ """Return the ids this archive lists, or None when they could not be read."""
232
+
233
+ try:
234
+ with np.load(path) as data:
235
+ members = set(data.files)
236
+ stray = sorted(members - {DYNAMICS_POS_KEY, DYNAMICS_IDS_KEY,
237
+ DYNAMICS_FACES_KEY, DYNAMICS_TETS_KEY})
238
+ if stray:
239
+ return None, [_msg(name, stray[0], "is not a known member")]
240
+ for key in (DYNAMICS_POS_KEY, DYNAMICS_IDS_KEY):
241
+ if key not in members:
242
+ return None, [_msg(name, key, "is required")]
243
+ if DYNAMICS_FACES_KEY in members and DYNAMICS_TETS_KEY in members:
244
+ return None, [_msg(
245
+ name,
246
+ "connectivity",
247
+ "cannot contain both faces and tets; use faces for a surface mesh or tets for a tetrahedral mesh",
248
+ )]
249
+ arrays = {key: data[key] for key in members}
250
+ except UNREADABLE as exc:
251
+ return None, [_msg(name, "npz", str(exc))]
252
+
253
+ violations: list[Violation] = []
254
+ pos = arrays[DYNAMICS_POS_KEY]
255
+ if pos.dtype != np.dtype(POS_DTYPE):
256
+ violations.append(_msg(name, DYNAMICS_POS_KEY, f"dtype {pos.dtype} != float32"))
257
+ elif pos.ndim != 3 or pos.shape[2] != 3:
258
+ violations.append(_msg(name, DYNAMICS_POS_KEY, f"shape {pos.shape} is not (F,N,3)"))
259
+ elif frame_count is not None and pos.shape[0] != frame_count:
260
+ violations.append(_msg(name, DYNAMICS_POS_KEY,
261
+ f"F {pos.shape[0]} != {VIDEO_FILENAME} {frame_count}"))
262
+ else:
263
+ error = _check_lifetimes(name, pos)
264
+ if error is not None:
265
+ violations.append(error)
266
+
267
+ ids = arrays[DYNAMICS_IDS_KEY]
268
+ listed: set[int] | None = None
269
+ if ids.dtype != np.dtype(INDEX_DTYPE):
270
+ violations.append(_msg(name, DYNAMICS_IDS_KEY, f"dtype {ids.dtype} != uint16"))
271
+ elif ids.ndim != 1 or len(ids) < 1:
272
+ violations.append(_msg(name, DYNAMICS_IDS_KEY, f"shape {ids.shape} is not (M,) with M >= 1"))
273
+ else:
274
+ listed = {int(value) for value in ids}
275
+ missing = sorted(listed - mesh_ids)
276
+ if missing:
277
+ violations.append(_msg(name, DYNAMICS_IDS_KEY,
278
+ f"id {missing[0]} has no {MESHES_DIRNAME}/ archive"))
279
+
280
+ columns = pos.shape[1] if pos.ndim == 3 else None
281
+ for key, width in ((DYNAMICS_FACES_KEY, 3), (DYNAMICS_TETS_KEY, 4)):
282
+ if key not in arrays:
283
+ continue
284
+ index = arrays[key]
285
+ if index.dtype != np.dtype(FACES_DTYPE):
286
+ violations.append(_msg(name, key, f"dtype {index.dtype} != int32"))
287
+ elif index.ndim != 2 or index.shape[1] != width:
288
+ violations.append(_msg(name, key, f"shape {index.shape} is not (T,{width})"))
289
+ elif columns is not None and len(index) and ((index < 0).any() or index.max() >= columns):
290
+ violations.append(_msg(name, key, f"index outside the {columns} columns of {DYNAMICS_POS_KEY}"))
291
+ return listed, violations
292
+
293
+
294
+ def _check_lifetimes(name: str, pos: np.ndarray) -> Violation | None:
295
+ """Every column is all finite or all NaN per frame, over one contiguous non-empty interval."""
296
+
297
+ alive = np.isfinite(pos).all(axis=2)
298
+ mixed = ~(alive | np.isnan(pos).all(axis=2))
299
+ if mixed.any():
300
+ frame, column = np.argwhere(mixed)[0]
301
+ return _msg(name, f"{DYNAMICS_POS_KEY}[{frame},{column}]", "must be all finite or all NaN")
302
+
303
+ empty = np.flatnonzero(~alive.any(axis=0))
304
+ if len(empty):
305
+ return _msg(name, f"{DYNAMICS_POS_KEY}[:,{int(empty[0])}]", "has empty lifetime")
306
+ padded = np.zeros((len(alive) + 1, alive.shape[1]), dtype=bool)
307
+ padded[1:] = alive
308
+ starts = (padded[1:] & ~padded[:-1]).sum(axis=0)
309
+ broken = np.flatnonzero(starts > 1)
310
+ if len(broken):
311
+ return _msg(name, f"{DYNAMICS_POS_KEY}[:,{int(broken[0])}]", "has non-contiguous lifetime")
312
+ return None
313
+
314
+
315
+ SOLVER_DIRNAME = "solver"
316
+ SOLVER_MANIFEST = "manifest.json"
317
+ SOLVER_KEYS = ("cache", "fps", "time_scale", "metres_per_unit",
318
+ "domain_min", "frames", "liquid_ids")
319
+ SOLVER_POSITIVE = ("fps", "time_scale", "metres_per_unit") # each a positive finite number
320
+ DOMAIN_MIN_LENGTH = 3
321
+
322
+
323
+ def _number(value: object) -> bool:
324
+ """A finite real number, and not a bool, which Python counts as an int."""
325
+
326
+ return (isinstance(value, (int, float)) and not isinstance(value, bool)
327
+ and math.isfinite(value))
328
+
329
+
330
+ def _check_solver(root: Path, mesh_ids: set[int]) -> tuple[set[int], list[Violation]]:
331
+ """The ids a liquid renders through, and whatever is wrong with `solver/`.
332
+
333
+ A liquid whose solver keeps no particle identity is listed by no `dynamics/`
334
+ archive and is not static either: its tracks are extracted from the bake
335
+ afterwards. It names itself here instead, so the static rule has to know
336
+ about this directory or it reads every such liquid as a broken static object.
337
+ """
338
+
339
+ solver = root / SOLVER_DIRNAME
340
+ if not solver.exists():
341
+ return set(), [] # optional, and absent is the common case
342
+ name = f"{SOLVER_DIRNAME}/{SOLVER_MANIFEST}"
343
+ path = solver / SOLVER_MANIFEST
344
+ if not path.is_file():
345
+ return set(), [_msg(name, "path", "is required when solver/ exists")]
346
+ try:
347
+ manifest = json.loads(path.read_text(encoding="utf-8"))
348
+ except Exception as exc:
349
+ return set(), [_msg(name, "json", f"is not readable: {exc}")]
350
+ if not isinstance(manifest, dict):
351
+ return set(), [_msg(name, "json", "must be an object")]
352
+
353
+ violations = []
354
+ for key in SOLVER_KEYS:
355
+ if key not in manifest:
356
+ violations.append(_msg(name, key, "is required"))
357
+ cache = manifest.get("cache")
358
+ if isinstance(cache, str) and not (solver / cache).is_dir():
359
+ violations.append(_msg(name, "cache", f"names {cache!r}, which is not a directory here"))
360
+
361
+ # The five that carry numbers are checked for what they hold, not only that they are
362
+ # there. A manifest naming every key and holding a null in one of them reads as clean
363
+ # and then fails extraction after the run is over, which is the worst time to find out.
364
+ for key in SOLVER_POSITIVE:
365
+ value = manifest.get(key)
366
+ if key in manifest and not (_number(value) and value > 0):
367
+ violations.append(_msg(name, key, f"must be a positive finite number, not {value!r}"))
368
+ corner = manifest.get("domain_min")
369
+ if "domain_min" in manifest and not (
370
+ isinstance(corner, list) and len(corner) == DOMAIN_MIN_LENGTH
371
+ and all(_number(v) for v in corner)):
372
+ violations.append(_msg(name, "domain_min",
373
+ f"must be {DOMAIN_MIN_LENGTH} finite numbers, not {corner!r}"))
374
+ span = manifest.get("frames")
375
+ if "frames" in manifest and not (
376
+ isinstance(span, list) and len(span) == 2
377
+ and all(isinstance(v, int) and not isinstance(v, bool) and v >= 0 for v in span)
378
+ and span[0] <= span[1]):
379
+ violations.append(_msg(name, "frames",
380
+ f"must be two frame numbers, first no later than last, not {span!r}"))
381
+
382
+ ids = manifest.get("liquid_ids")
383
+ if not isinstance(ids, list) or not ids or not all(isinstance(v, int) for v in ids):
384
+ violations.append(_msg(name, "liquid_ids", "must be a non-empty list of mesh ids"))
385
+ return set(), violations
386
+ missing = sorted(set(ids) - mesh_ids)
387
+ if missing:
388
+ violations.append(_msg(name, "liquid_ids", f"names ids with no mesh archive: {missing}"))
389
+ return set(ids), violations
390
+
391
+
392
+ def _check_static(oid: int, frames: dict[int, tuple[np.ndarray, np.ndarray]]) -> list[Violation]:
393
+ """An id no dynamics archive lists holds the same arrays at every frame."""
394
+
395
+ name = f"{MESHES_DIRNAME}/{oid}{NPZ_SUFFIX}"
396
+ ordered = sorted(frames)
397
+ first_vertices, first_faces = frames[ordered[0]]
398
+ for frame in ordered[1:]:
399
+ vertices, faces = frames[frame]
400
+ if not np.array_equal(vertices, first_vertices):
401
+ return [_msg(name, MESH_VERTICES_KEY.format(frame=frame),
402
+ f"differs from frame {ordered[0]:04d} but no {DYNAMICS_DIRNAME}/ archive lists id {oid}")]
403
+ if not np.array_equal(faces, first_faces):
404
+ return [_msg(name, MESH_FACES_KEY.format(frame=frame),
405
+ f"differs from frame {ordered[0]:04d} but no {DYNAMICS_DIRNAME}/ archive lists id {oid}")]
406
+ return []
407
+
408
+
409
+ __all__ = ["check_world"]
论文参考代码/4DCodeBench/checker/paths.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed Agent container interface."""
2
+
3
+ from pathlib import Path
4
+
5
+ WORKSPACE_DIR = Path("/workspace")
6
+ WORLD_DIR = WORKSPACE_DIR / "world"
7
+ SOLUTION_DIR = WORKSPACE_DIR / "solution"
8
+ SOLUTION_ENTRYPOINT = SOLUTION_DIR / "build.sh"
9
+ VIDEO_PATH = Path("/input/reference.mp4")
10
+ HOME_DIR = Path("/root")
11
+
12
+ __all__ = [
13
+ "HOME_DIR",
14
+ "SOLUTION_DIR",
15
+ "SOLUTION_ENTRYPOINT",
16
+ "VIDEO_PATH",
17
+ "WORKSPACE_DIR",
18
+ "WORLD_DIR",
19
+ ]
论文参考代码/4DCodeBench/checker/preview.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Draw one frame of the exported world the way the scorer will see it.
2
+
3
+ python -m checker.preview # frame 0 of /workspace/world -> /workspace/tmp/preview_0000.png
4
+
5
+ The scorer never looks at `render.mp4` to learn where the geometry is: it projects `meshes/`
6
+ through `camera.json`. This tool does the same projection with a plain z-buffer rasteriser
7
+ and writes one PNG with two panels: the frame of `render.mp4` on the left, the exported
8
+ geometry seen through the exported camera on the right (one colour per mesh id, lit by its
9
+ face normal). Look at it: if the right panel does not line up with the left one, `camera.json`
10
+ or `meshes/` do not describe what was rendered, and every metric will be scored against the
11
+ wrong geometry. It judges nothing and prints nothing.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import subprocess
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+
23
+ from config.world import (
24
+ CAMERA_EXTRINSIC_KEY,
25
+ CAMERA_FILENAME,
26
+ CAMERA_INTRINSICS_KEY,
27
+ MESH_FACES_KEY,
28
+ MESH_VERTICES_KEY,
29
+ MESHES_DIRNAME,
30
+ NPZ_SUFFIX,
31
+ VIDEO_FILENAME,
32
+ )
33
+
34
+ from .paths import WORKSPACE_DIR, WORLD_DIR
35
+
36
+ PREVIEW_DIR = WORKSPACE_DIR / "tmp"
37
+ FRAME = 0
38
+ BACKGROUND = np.array([40, 40, 40], dtype=np.uint8)
39
+
40
+
41
+ def preview(world: Path, frame: int, out: Path) -> None:
42
+ """Write the two-panel image for `frame`."""
43
+
44
+ camera = json.loads((world / CAMERA_FILENAME).read_text(encoding="utf-8"))
45
+ intrinsics = np.asarray(camera[CAMERA_INTRINSICS_KEY], dtype=np.float64)
46
+ extrinsic = np.asarray(camera[CAMERA_EXTRINSIC_KEY], dtype=np.float64)
47
+
48
+ rendered = _video_frame(world / VIDEO_FILENAME, frame)
49
+ height, width = rendered.shape[:2]
50
+
51
+ drawn = np.tile(BACKGROUND, (height, width, 1))
52
+ depth = np.full((height, width), np.inf)
53
+ for path in sorted((world / MESHES_DIRNAME).glob(f"*{NPZ_SUFFIX}")):
54
+ oid = int(path.stem)
55
+ with np.load(path) as data:
56
+ vkey, fkey = MESH_VERTICES_KEY.format(frame=frame), MESH_FACES_KEY.format(frame=frame)
57
+ if vkey not in data or not len(data[fkey]):
58
+ continue
59
+ vertices, faces = data[vkey].astype(np.float64), data[fkey]
60
+ camera_points = (vertices - extrinsic[:3, 3]) @ extrinsic[:3, :3]
61
+ _rasterise(camera_points, faces, intrinsics, _colour(oid), drawn, depth)
62
+
63
+ out.parent.mkdir(parents=True, exist_ok=True)
64
+ _write_png(np.concatenate([rendered, drawn], axis=1), out)
65
+
66
+
67
+ def _rasterise(points: np.ndarray, faces: np.ndarray, intrinsics: np.ndarray,
68
+ colour: np.ndarray, drawn: np.ndarray, depth: np.ndarray) -> None:
69
+ """Z-buffer every triangle in front of the camera into `drawn`."""
70
+
71
+ height, width = depth.shape
72
+ tri = points[faces] # (T, 3, 3)
73
+ in_front = (tri[:, :, 2] > 1e-6).all(axis=1)
74
+ tri = tri[in_front]
75
+ if not len(tri):
76
+ return
77
+ normal = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0])
78
+ normal /= np.linalg.norm(normal, axis=1, keepdims=True) + 1e-12
79
+ shade = 0.35 + 0.65 * np.abs(normal[:, 2]) # headlight from the camera
80
+ pixels = tri @ intrinsics.T
81
+ uv = pixels[:, :, :2] / pixels[:, :, 2:3] # (T, 3, 2)
82
+ z = tri[:, :, 2]
83
+ lo = np.clip(np.floor(uv.min(axis=1)), 0, [width - 1, height - 1]).astype(int)
84
+ hi = np.clip(np.ceil(uv.max(axis=1)), 0, [width - 1, height - 1]).astype(int)
85
+ visible = ((uv.max(axis=1) >= 0) & (uv.min(axis=1) < [width, height])).all(axis=1)
86
+ order = np.argsort(-z.mean(axis=1)) # far to near: fewer overdraw checks
87
+ for t in order:
88
+ if not visible[t]:
89
+ continue
90
+ (x0, y0), (x1, y1) = lo[t], hi[t]
91
+ xs, ys = np.meshgrid(np.arange(x0, x1 + 1) + 0.5, np.arange(y0, y1 + 1) + 0.5)
92
+ (ax, ay), (bx, by), (cx, cy) = uv[t]
93
+ area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)
94
+ if abs(area) < 1e-12:
95
+ continue
96
+ w0 = ((bx - xs) * (cy - ys) - (by - ys) * (cx - xs)) / area
97
+ w1 = ((cx - xs) * (ay - ys) - (cy - ys) * (ax - xs)) / area
98
+ w2 = 1.0 - w0 - w1
99
+ inside = (w0 >= 0) & (w1 >= 0) & (w2 >= 0)
100
+ if not inside.any():
101
+ continue
102
+ # Screen-space weights interpolate inverse depth under perspective.
103
+ inverse_depth = w0 / z[t, 0] + w1 / z[t, 1] + w2 / z[t, 2]
104
+ zpix = np.full(w0.shape, np.inf, dtype=np.float32)
105
+ np.divide(1.0, inverse_depth, out=zpix, where=inside)
106
+ window = depth[y0:y1 + 1, x0:x1 + 1]
107
+ nearer = inside & (zpix < window)
108
+ window[nearer] = zpix[nearer]
109
+ drawn[y0:y1 + 1, x0:x1 + 1][nearer] = (colour * shade[t]).astype(np.uint8)
110
+
111
+
112
+ def _colour(oid: int) -> np.ndarray:
113
+ """A distinct, bright colour per id (golden-angle hue)."""
114
+
115
+ hue = (oid * 0.618033988749895) % 1.0
116
+ k = np.array([0.0, 2.0, 4.0])
117
+ rgb = np.clip(np.abs(((hue * 6.0 + k) % 6.0) - 3.0) - 1.0, 0.0, 1.0)
118
+ return (255 * (0.25 + 0.75 * rgb))
119
+
120
+
121
+ def _video_frame(path: Path, frame: int) -> np.ndarray:
122
+ probe = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
123
+ "stream=width,height", "-of", "csv=p=0", str(path)],
124
+ capture_output=True, text=True, check=True)
125
+ width, height = (int(v) for v in probe.stdout.strip().split(",")[:2])
126
+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-vf", f"select=eq(n\\,{frame})",
127
+ "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
128
+ capture_output=True, check=True).stdout
129
+ if len(raw) != width * height * 3:
130
+ raise SystemExit(f"{path}: could not decode frame {frame}")
131
+ return np.frombuffer(raw, dtype=np.uint8).reshape(height, width, 3)
132
+
133
+
134
+ def _write_png(image: np.ndarray, out: Path) -> None:
135
+ height, width = image.shape[:2]
136
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
137
+ "-s", f"{width}x{height}", "-i", "-", str(out)],
138
+ input=np.ascontiguousarray(image).tobytes(), check=True)
139
+
140
+
141
+ def main() -> int:
142
+ preview(WORLD_DIR, FRAME, PREVIEW_DIR / f"preview_{FRAME:04d}.png")
143
+ return 0
144
+
145
+
146
+ if __name__ == "__main__":
147
+ if len(sys.argv) != 1:
148
+ raise SystemExit("checker.preview takes no arguments")
149
+ raise SystemExit(main())
论文参考代码/4DCodeBench/checker/solution.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public structure checks for the submitted solution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ Violation = str
9
+
10
+
11
+ def check_solution(root: str | Path) -> list[Violation]:
12
+ """Return delivery-structure violations for one solution directory."""
13
+
14
+ root = Path(root)
15
+ if not root.exists():
16
+ return [f"{root.name}: path is required"]
17
+ if not root.is_dir():
18
+ return [f"{root.name}: path must be a directory"]
19
+
20
+ entrypoint = root / "build.sh"
21
+ if not entrypoint.exists():
22
+ return [f"{root.name}/build.sh: path is required"]
23
+ if not entrypoint.is_file():
24
+ return [f"{root.name}/build.sh: path must be a file"]
25
+ violations = []
26
+ if entrypoint.stat().st_mode & 0o111 == 0:
27
+ violations.append(f"{root.name}/build.sh: must be executable")
28
+ for path in sorted(path for path in root.rglob("*") if path.is_file()):
29
+ if path.suffix not in {".py", ".sh"}:
30
+ violations.append(f"{root.name}/{path.relative_to(root)}: only .py and .sh files are allowed")
31
+ return violations
32
+
33
+
34
+ def check_links(root: str | Path) -> list[Violation]:
35
+ """Symbolic links anywhere in a delivery directory, the directory itself included.
36
+
37
+ The delivery must be real files: a link is not collected, so whatever it points
38
+ at is missing from the returned world or solution.
39
+ """
40
+
41
+ root = Path(root)
42
+ if root.is_symlink():
43
+ return [f"{root.name}: must be a directory, not a symbolic link"]
44
+ if not root.is_dir():
45
+ return []
46
+ violations = []
47
+ for directory, subdirectories, files in os.walk(root):
48
+ for entry in sorted(subdirectories + files):
49
+ path = Path(directory) / entry
50
+ if path.is_symlink():
51
+ violations.append(f"{root.name}/{path.relative_to(root)}: symbolic links are not allowed; write the file itself")
52
+ return violations
53
+
54
+
55
+ __all__ = ["check_links", "check_solution"]
论文参考代码/4DCodeBench/config/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Scorer, estimator and world-format constants shared across the repository."""
论文参考代码/4DCodeBench/config/annotation.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """File layout of a real case's dynamic-object annotation.
2
+
3
+ `data/real/<case>/annotation/dynamic_mask.npz` holds `mask`, uint8 of shape
4
+ `(frames, height, width)`: 0 is background, 1 is dynamic.
5
+ """
6
+
7
+ ANNOTATION_DIRNAME = "annotation"
8
+ MASK_FILENAME = "dynamic_mask.npz"
9
+ MASK_KEY = "mask"
论文参考代码/4DCodeBench/config/estimates.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """File layout of the reference-side estimates of a case's `reference.mp4`.
2
+
3
+ `python -m scorer.prepare` computes these once per case; the scorer loads them:
4
+
5
+ data/<kind>/<case>/estimates/flow.h5 RAFT flow, `flow (F'-1, H, W, 2)`
6
+ float16 in full-resolution pixels,
7
+ `valid (F'-1, H, W)` bool, `stride`
8
+ data/<kind>/<case>/estimates/tracks.npz CoTracker3 tracks of a full-image
9
+ grid on frame 0, `tracks (Q, F', 2)`
10
+ float32 full-resolution pixels,
11
+ `visible (Q, F')`, the start pixels
12
+ `queries (Q, 3)` `(0, x, y)`,
13
+ `step`, `shape`, `stride`
14
+ data/<kind>/<case>/estimates/moge.npz MoGe-3 point map of frame 0,
15
+ `points (H, W, 3)` float32 in
16
+ camera metres up to the model's own
17
+ scale, `mask (H, W)` bool,
18
+ `intrinsics (3, 3)` normalised to
19
+ the unit image, `shape [H, W]`,
20
+ `model`
21
+ data/<kind>/<case>/estimates/semantic_<name>.npz
22
+ one per semantic backbone, its
23
+ `embeddings (n, D)` float32 and the
24
+ `stride` they are on
25
+ data/<kind>/<case>/estimates/geophys_<name>.npz
26
+ `trajectory (T, 1024)` float32,
27
+ `stride`, `layer`
28
+ data/<kind>/<case>/estimates/depth.h5 Video Depth Anything `disparity
29
+ (F', h, w)` float16 on the model's
30
+ own output grid, `shape [F, H, W]`
31
+ the video's own, `fps`, `stride`
32
+
33
+ All archives except the point map are on the case's sampled timeline
34
+ (`config.sampling`): `F'` is `ceil(F / stride)`, flow step `k` is the displacement
35
+ from sampled frame `k` to `k + 1`, and each archive stores its `stride`. The point
36
+ map covers frame 0 only.
37
+
38
+ The score of a case's reference world against itself (the per-metric ceiling):
39
+
40
+ data/<kind>/<case>/sanity/results/ reward.json and the metrics' arrays
41
+ """
42
+
43
+ ESTIMATES_DIRNAME = "estimates"
44
+ SANITY_DIRNAME = "sanity"
45
+ RESULTS_DIRNAME = "results"
46
+ REWARD_FILENAME = "reward.json"
47
+ VIZ_DIRNAME = "viz"
48
+
49
+ FLOW_FILENAME = "flow.h5"
50
+ TRACKS_FILENAME = "tracks.npz"
51
+ MOGE_FILENAME = "moge.npz"
52
+ SEMANTIC_FILENAME = "semantic_{name}.npz"
53
+ GEOPHYS_FILENAME = "geophys_{name}.npz"
54
+ DEPTH_FILENAME = "depth.h5"
55
+ RASTER_DEPTH_FILENAME = "raster_depth.h5"
56
+
57
+ MOGE_POINTS_KEY = "points"
58
+ MOGE_MASK_KEY = "mask"
论文参考代码/4DCodeBench/config/models.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checkpoint names and layer choices of the pretrained models.
2
+
3
+ Each model is a directory under one checkpoint store, loaded offline. In the scorer
4
+ container the store is the `/checkpoints` mount; `scripts/download_checkpoints.sh`
5
+ fills one (docs/checkpoints.md).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ DINOV3 = "dinov3-vitl16-pretrain-lvd1689m"
13
+ TIPS = "tipsv2-l14"
14
+ VIDEO_DEPTH_ANYTHING = "video-depth-anything-large"
15
+ RAFT = "raft-large"
16
+ COTRACKER = "cotracker3"
17
+ MOGE = "moge-3-vitl"
18
+
19
+ GEOPHYS_MODELS = {DINOV3: "dinov3"} # GeoPhys backbone -> archive tag
20
+
21
+ # GeoPhys readout layer, counted from 1 over the transformer blocks, as selected by
22
+ # Interno et al. (Fig. 2, Table 3) for a ViT-L. `DEPTH` is the backbone's block count;
23
+ # `block_for` converts the layer to the from-the-end index of `backbones.*.tokens(block=)`.
24
+ READOUT = {DINOV3: 18}
25
+ DEPTH = {DINOV3: 24}
26
+
27
+
28
+ def block_for(name: str, layer: int | None = None) -> int:
29
+ """Return the from-the-end `block=` index of `layer` (default: `READOUT[name]`)."""
30
+
31
+ return (READOUT[name] if layer is None else layer) - DEPTH[name] - 1
32
+
33
+
34
+ def checkpoint(name: str, root: str | Path) -> Path:
35
+ """Return the path of model `name` under the checkpoint store `root`."""
36
+
37
+ return Path(root) / name
38
+
论文参考代码/4DCodeBench/config/sampling.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The sampled evaluation timeline of a case.
2
+
3
+ Flow, Track2D, Depth, Semantic and GeoPhys use frames `0, k, 2k, ...` of an
4
+ `F`-frame video, with the stride fixed by `F` alone:
5
+
6
+ k = min { k >= 1 : ceil(F / k) <= MAX_FRAMES }
7
+
8
+ A video of at most `MAX_FRAMES` frames has `k = 1`. The video gate still requires
9
+ `render.mp4` to carry all `F` frames.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import numpy as np
15
+
16
+ MAX_FRAMES = 300 # the most frames the sampled timeline holds
17
+
18
+
19
+ def stride_for(frames: int) -> int:
20
+ """Return the smallest stride with `ceil(frames / stride) <= MAX_FRAMES`."""
21
+
22
+ frames = int(frames)
23
+ if frames <= MAX_FRAMES:
24
+ return 1
25
+ stride = 1
26
+ while -(-frames // stride) > MAX_FRAMES:
27
+ stride += 1
28
+ return stride
29
+
30
+
31
+ def sampled_length(frames: int, stride: int | None = None) -> int:
32
+ """Return the number of sampled frames of a `frames`-frame video, `ceil(frames / stride)`."""
33
+
34
+ stride = stride_for(frames) if stride is None else int(stride)
35
+ return -(-int(frames) // max(stride, 1))
36
+
37
+
38
+ def sampled_indices(frames: int, stride: int | None = None) -> np.ndarray:
39
+ """Return the sampled frame indices `0, k, 2k, ...` as int64."""
40
+
41
+ stride = stride_for(frames) if stride is None else int(stride)
42
+ return np.arange(0, int(frames), max(stride, 1), dtype=np.int64)
43
+
44
+
45
+ __all__ = ["MAX_FRAMES", "sampled_indices", "sampled_length", "stride_for"]
论文参考代码/4DCodeBench/config/scorer.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Constants of the scoring rules."""
2
+
3
+ N = 16384 # target material sample count of the reference's frame 0
4
+ SEED = 0 # random seed of the metric samplers
5
+ BAND_FRACTION = 0.0025 # DynamicIoU ignored band along the gt boundary, fraction of diagonal
6
+ CLOSE_FRACTION = 0.0025 # real-case DynamicIoU closing radius of the submission mask, same unit
论文参考代码/4DCodeBench/config/uni3d.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checkpoint path and build arguments of the Uni3D-L point tower.
2
+
3
+ The model is vendored under `scorer.metrics.uni3d` and embeds a cloud as a
4
+ 1024-dimensional vector; the Uni3D metrics compare two embeddings by cosine.
5
+ """
6
+
7
+ from pathlib import Path
8
+
9
+ from easydict import EasyDict
10
+
11
+ UNI3D_CHECKPOINT = Path("uni3d-l/model.pt") # relative to the checkpoint store
12
+
13
+ UNI3D_ARGS = EasyDict(
14
+ pc_model="eva02_large_patch14_448",
15
+ pretrained_pc="",
16
+ drop_path_rate=0.0,
17
+ pc_feat_dim=1024,
18
+ embed_dim=1024,
19
+ group_size=64,
20
+ num_group=512,
21
+ pc_encoder_dim=512,
22
+ )
23
+
24
+ UNI3D_POINTS = 10000 # points per embedded cloud
25
+ UNI3D_COLOUR = 0.4 # constant RGB value given to every point
论文参考代码/4DCodeBench/config/world.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Names and dtypes fixed by the 4DCodeBench world format."""
2
+
3
+ import numpy as np
4
+
5
+ CAMERA_FILENAME = "camera.json"
6
+ MESHES_DIRNAME = "meshes"
7
+ DYNAMICS_DIRNAME = "dynamics"
8
+ VIDEO_FILENAME = "render.mp4"
9
+ NPZ_SUFFIX = ".npz"
10
+
11
+ CAMERA_INTRINSICS_KEY = "intrinsics"
12
+ CAMERA_EXTRINSIC_KEY = "extrinsic"
13
+
14
+ # meshes/<id>.npz: one member pair per frame of the object's lifetime
15
+ MESH_VERTICES_KEY = "vertices_{frame:04d}"
16
+ MESH_FACES_KEY = "faces_{frame:04d}"
17
+
18
+ # dynamics/<name>.npz: one piece of material
19
+ DYNAMICS_POS_KEY = "pos" # (F, N, 3) float32; NaN outside a column's lifetime
20
+ DYNAMICS_IDS_KEY = "ids" # (M,) uint16; the mesh ids that display this material
21
+ DYNAMICS_FACES_KEY = "faces" # (T, 3) int32; optional
22
+ DYNAMICS_TETS_KEY = "tets" # (K, 4) int32; optional
23
+
24
+ # columns a liquid tracer archive may hold
25
+ TRACER_POINTS = 16384
26
+ TRACER_FILENAME = "tracers.npz"
27
+
28
+ POS_DTYPE = np.float32
29
+ FACES_DTYPE = np.int32
30
+ INDEX_DTYPE = np.uint16
31
+ OBJECT_ID_DTYPE = np.uint16
32
+ CAMERA_DTYPE = np.float64
论文参考代码/4DCodeBench/docs/agent-setup.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Agent Setup
2
+
3
+ Each agent runs headlessly inside a container. During inference, `infer.py` mounts three read-only paths into the container: `/task` (task specification), `/input/reference.mp4` (reference video), and the agent's credential file. Agent execution commands are defined in [`harness/runtime/agents.py`](../harness/runtime/agents.py).
4
+
5
+ | Agent | CLI | Credential File | Reasoning Efforts |
6
+ |---|---|---|---|
7
+ | `claude` | Claude Code | `.auth/claude.json` | `low`, `medium`, `high`, `xhigh`, `max` |
8
+ | `codex` | Codex CLI | `.auth/gpt.json` | `low`, `medium`, `high`, `xhigh`, `max` |
9
+ | `antigravity` | Antigravity CLI | `.auth/gemini.json` | `low`, `medium`, `high` |
10
+ | `stirrup` | Artificial Analysis' Stirrup | None | Passed as `reasoning_effort` (omitted if `none`) |
11
+
12
+ ## 1. Authenticate on the Host
13
+
14
+ Log in once on the host with the target billing account. The host CLIs generate the required credentials:
15
+
16
+ | Agent | Login Command | Credential File |
17
+ |---|---|---|
18
+ | `claude` | `claude`, then `/login` | `~/.claude/.credentials.json` |
19
+ | `codex` | `codex login` (or `printenv OPENAI_API_KEY \| codex login --with-api-key`) | `~/.codex/auth.json` |
20
+ | `antigravity` | `agy` (complete Google sign-in) | `~/.gemini/antigravity-cli/antigravity-oauth-token` |
21
+
22
+ ## 2. Link Credentials into `.auth/`
23
+
24
+ From the repository root, create symbolic links:
25
+
26
+ ```bash
27
+ mkdir -p .auth
28
+ ln -s ~/.claude/.credentials.json .auth/claude.json
29
+ ln -s ~/.codex/auth.json .auth/gpt.json
30
+ ln -s ~/.gemini/antigravity-cli/antigravity-oauth-token .auth/gemini.json
31
+ ```
32
+
33
+ Use symbolic links rather than static copies. Because containers mount credentials read-only, they cannot refresh expired tokens internally. Symbolic links propagate host token refreshes into the container automatically. If a run fails with an authentication error, re-authenticate on the host.
34
+
35
+ To switch accounts, link an alternative file (e.g., `.auth/gpt_team.json`) and update the `credential` path in `runtime.toml` under `[agent.<name>]`.
36
+
37
+ ## 3. Stirrup (Direct API Endpoints)
38
+
39
+ `stirrup` connects directly to any OpenAI-compatible Chat Completions endpoint without credential files. Configure `OPENAI_BASE_URL` and `OPENAI_API_KEY` under `[agent.stirrup.env]` in `runtime.toml`. The runtime forwards the `model` parameter directly to the endpoint.
论文参考代码/4DCodeBench/docs/checkpoints.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Checkpoints
2
+
3
+ Scoring loads all model checkpoints from one local directory, mounted read-only at `/checkpoints` in the scorer container. Inference needs none of them, so if you only run inference you can skip this page.
4
+
5
+ > **Note**: `facebook/dinov3-vitl16-pretrain-lvd1689m` is gated; ensure your Hugging Face account has access and is authenticated (`HF_TOKEN` or `hf auth login`) before downloading.
6
+
7
+ ## 1. Download Checkpoints
8
+
9
+ Download and verify all required weights (~6.7 GB total):
10
+
11
+ ```bash
12
+ scripts/download_checkpoints.sh # default: ./checkpoints
13
+ scripts/download_checkpoints.sh /data/ckpt # or custom directory
14
+ ```
15
+
16
+ The script pins each model to the benchmark revision, validates SHA-256 checksums, and resumes interrupted downloads.
17
+
18
+ ## 2. Configuration
19
+
20
+ In `runtime.toml` (template: `harness/runtime/templates/runtime.example.toml`):
21
+
22
+ ```toml
23
+ [scorer]
24
+ checkpoints = "checkpoints" # path relative to repo root, or absolute
25
+ ```
26
+
27
+ When running the scoring stages directly, outside the harness:
28
+
29
+ ```bash
30
+ python -m scorer.prepare --checkpoints <DIR> ...
31
+ python -m scorer --checkpoints <DIR> ...
32
+ python -m visualizer --checkpoints <DIR> ...
33
+ ```
34
+
35
+ ## Checkpoint Registry
36
+
37
+ Directory names must remain unchanged, as the scorer locates models by these paths (`config/models.py`, `config/uni3d.py`).
38
+
39
+ | Directory | Weight File | Source | Revision | SHA-256 |
40
+ |---|---|---|---|---|
41
+ | `dinov3-vitl16-pretrain-lvd1689m` | `model.safetensors` | [facebook/dinov3-vitl16-pretrain-lvd1689m](https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m) | `ea8dc28` | `dcb2e451…` |
42
+ | `tipsv2-l14` | `model.safetensors` | [google/tipsv2-l14](https://huggingface.co/google/tipsv2-l14) | `52847a7` | `c75707ea…` |
43
+ | `video-depth-anything-large` | `video_depth_anything_vitl.pth` | [depth-anything/Video-Depth-Anything-Large](https://huggingface.co/depth-anything/Video-Depth-Anything-Large) | `7aafbcb` | `43df27c6…` |
44
+ | `raft-large` | `raft_large_C_T_SKHT_V2.pth` | torchvision `Raft_Large_Weights.C_T_SKHT_V2` | -- | `ff5fadd5…` |
45
+ | `cotracker3` | `scaled_offline.pth` | [facebook/cotracker3](https://huggingface.co/facebook/cotracker3) | `bf55ea5` | `2670d456…` |
46
+ | `moge-3-vitl` | `model.pt` | [Ruicheng/moge-3-vitl](https://huggingface.co/Ruicheng/moge-3-vitl) | `184008f` | `9b41b7b9…` |
47
+ | `uni3d-l` | `model.pt` | [BAAI/Uni3D](https://huggingface.co/BAAI/Uni3D), `modelzoo/uni3d-l/model.pt` | `3d8233b` | `540a3caf…` |
48
+
49
+ ### Models by Stage
50
+
51
+ | Stage | Models Used |
52
+ |---|---|
53
+ | `prepare` | RAFT (Flow), CoTracker3 (Track2D), Video Depth Anything (Depth), MoGe-3 (Uni3D MoGe), DINOv3 (Semantic, GeoPhys), TIPSv2 (Semantic) |
54
+ | `score` | DINOv3, TIPSv2, Uni3D |
55
+ | `viz` | DINOv3, TIPSv2 (feature visualizations) |
论文参考代码/4DCodeBench/docs/spec.md ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # World Format and Evaluation Specification
2
+
3
+ This document defines the 4D world package format and how a run is scored. It is not part of the agent image. Benchmark agents receive a self-contained task summary in `/task/` (`TASK.md`, `world-format.md`, and `render-settings.md`), `/input/reference.mp4`, and the public checker (`python -m checker`).
4
+
5
+ ## World directory
6
+
7
+ ```text
8
+ world/
9
+ ├── camera.json
10
+ ├── render.mp4
11
+ ├── meshes/
12
+ │ └── <id>.npz
13
+ ├── dynamics/
14
+ │ └── <name>.npz
15
+ └── solver/ (identity-less liquid only)
16
+ ├── manifest.json
17
+ └── <cache>/
18
+ ```
19
+
20
+ | entry | contents |
21
+ |---|---|
22
+ | `camera.json` | `{"intrinsics": K, "extrinsic": E}` |
23
+ | `render.mp4` | the rendered video |
24
+ | `meshes/<id>.npz` | the geometry shown in `render.mp4`, per object: `vertices_TTTT` `(V_t, 3)` float32, `faces_TTTT` `(T_t, 3)` int32 |
25
+ | `dynamics/<name>.npz` | `pos` `(F, N, 3)` float32, `ids` `(M,)` uint16; optionally `faces` `(T, 3)` or `tets` `(K, 4)` int32 |
26
+ | `solver/` | `manifest.json` and the solver's cache, only for a liquid whose solver keeps no particle identity |
27
+
28
+ - Coordinates are world-space metres, Z-up.
29
+ - All frame-indexed data share a synchronized timeline of $F$ frames (the frame count of `render.mp4`): frame $t$ across `render.mp4`, `dynamics/`, and `meshes/` describes the same instant.
30
+
31
+ ## `camera.json`
32
+
33
+ A UTF-8 JSON object with `intrinsics`, one 3×3 pinhole matrix, and `extrinsic`, one 4×4 camera-to-world transform constant across all frames (static camera). Pixel $(i, j)$ covers $[i, i+1) \times [j, j+1)$ with centre $(i+0.5,\, j+0.5)$; the centred principal point is $(W/2,\, H/2)$. Camera axes are +x right, +y down, +z forward. A world point $p$ projects to image coordinates via $K R^\top (p - t)$, where $R$ and $t$ are the rotation and translation components of `extrinsic`.
34
+
35
+ ## `meshes/`
36
+
37
+ One archive per rendered object, named `<id>.npz` with `<id>` a positive integer unique within the world. An archive holds `vertices_TTTT` with shape `(V, 3)`, dtype `float32`, finite world-space metres, and `faces_TTTT` with shape `(T, 3)`, dtype `int32`, indexing that frame's vertices, for every frame `TTTT` (four-digit, zero-padded) of one contiguous interval of frames below $F$. A frame at which the object has no geometry holds empty arrays. Vertex count and topology are free to change between frames; an archive carries no cross-frame correspondence.
38
+
39
+ Any object ID not referenced in `dynamics/` is classified as static: its `vertices` and `faces` must be identical at every frame of its active interval.
40
+
41
+ ## `dynamics/`
42
+
43
+ One archive per piece of material, under any file name unique within the directory. `pos` has shape `(F, N, 3)` and dtype `float32`; column $j$ traces one material point across the entire sequence, `pos[t, j]` its position at frame $t$, finite over one contiguous interval of at least one frame and NaN elsewhere. `ids` has shape `(M,)`, dtype `uint16`, $M \ge 1$, and lists the ids of the `meshes/` archives that display this material; an id may appear in several archives.
44
+
45
+ All moving geometry must be referenced in the `ids` of at least one `dynamics/` archive. An archive holds at most one connectivity member, `faces` or `tets`, fixed across all frames and indexing columns of `pos`:
46
+
47
+ | material | `pos` | connectivity |
48
+ |---|---|---|
49
+ | surface mesh (rigid body, cloth, shell, soft-body surface) | simulation mesh vertices | `faces` `(T, 3)` int32 |
50
+ | tetrahedral mesh (FEM) | mesh vertices | `tets` `(K, 4)` int32 |
51
+ | particles (MPM, SPH, granular, PBD) | every particle by slot, NaN where the slot is inactive | none |
52
+ | liquid without particle identity (e.g. Mantaflow, which reseeds every frame) | no archive; the solver bake goes under `solver/` | none |
53
+
54
+ For identity-less liquids, the scorer advects up to `TRACER_POINTS` (16,384) tracer columns from the simulation cache at scoring time. Its surface mesh is stored in `meshes/`, and all other moving objects require their own `dynamics/` archives.
55
+
56
+ ## `solver/`
57
+
58
+ Present only for an identity-less liquid. `manifest.json` is one JSON object with seven members:
59
+
60
+ | member | value |
61
+ |---|---|
62
+ | `cache` | name of the solver cache directory beside `manifest.json` |
63
+ | `fps` | the domain's frame rate, positive and finite |
64
+ | `time_scale` | the domain's time scale, positive and finite; advances solver time by `time_scale / fps` seconds per frame |
65
+ | `metres_per_unit` | positive and finite |
66
+ | `domain_min` | three finite numbers: the corner of the domain object's bounding box in world metres (the domain object box, not the evaluated liquid surface) |
67
+ | `frames` | `[first, last]` frames covered, `first <= last` |
68
+ | `liquid_ids` | non-empty list of `meshes/` ids that render the liquid |
69
+
70
+ An ID in `liquid_ids` must not appear in any `dynamics/` archive and is exempt from the static-object consistency check.
71
+
72
+ ## `render.mp4`
73
+
74
+ An H.264 MP4 rendered by Blender Cycles, with the frame count, resolution, and frame rate of the input `reference.mp4`. Benchmark reference videos use integer frame rates. Every object in the rendered scene is exported to `meshes/` under its ID, so that `meshes/`, seen through `camera.json`, matches `render.mp4` frame by frame, with nothing rendered that is not exported. Non-mesh elements (curves, point clouds, particles, hair, and volumes) must be converted to triangle meshes before rendering and exported as such.
75
+
76
+ ## Evaluation
77
+
78
+ A reconstruction is scored against the reference video on every scene, and against the reference world on synthetic scenes. The main metrics form five families:
79
+
80
+ | family | reference | metrics |
81
+ |---|---|---|
82
+ | Perceptual | video | DINOv3 similarity |
83
+ | 2D Dynamics | video | Dynamic IoU; Flow and Track2D (real) |
84
+ | 2.5D Geometry | video | Depth error (real) |
85
+ | 3D Geometry | world | Scene 3D (synthetic) |
86
+ | 3D Dynamics | world | Trajectory DTW, EMD step (synthetic) |
87
+
88
+ The paper's Overall score averages the five families. [Additional metrics](#additional-metrics) and [geometry quality](#geometry-quality) are reported separately. The scorer writes per-metric readings only.
89
+
90
+ ### Executability and scoring
91
+
92
+ Two validation gates determine scoring eligibility:
93
+
94
+ | gate | passes when | on failure |
95
+ |---|---|---|
96
+ | video | `render.mp4` decodes and matches the reference video's resolution, frame count and frame rate | scoring halts; all metrics receive `error` |
97
+ | world | every world entry and `solution/build.sh` exist, and the [checker](#checker) reports no violation | geometry metrics receive `error`; DINOv3, TIPS and GeoPhys, which read `render.mp4` only, are still computed |
98
+
99
+ Each metric yields a numerical score or one of four status states (in order of precedence):
100
+
101
+ | state | meaning |
102
+ |---|---|
103
+ | `not_applicable` | the metric does not apply to this kind of scene: reference-world metrics on real scenes; Flow, Track2D, Depth error and Uni3D MoGe on synthetic scenes |
104
+ | `excluded` | the scene's primary object is transparent (six real scenes) and the metric compares rasterised geometry with the video: Dynamic IoU, Flow, Track2D, Depth error, Uni3D MoGe |
105
+ | `error` | a validation gate failed or the reconstruction data is defective; `reward.detail.json` records the cause |
106
+ | `uncomputable` | the reference lacks the required ground-truth signal (e.g. no moving points); omitted across all models |
107
+
108
+ When computing aggregates, `error` is assigned the metric's worst possible value: 0 for similarities and 2 for Depth error.
109
+
110
+ ### Sampled timeline
111
+
112
+ DINOv3, TIPS, GeoPhys, Flow, Track2D and Depth error read the frames $0, s, 2s, \dots$, with stride $s$ the smallest integer such that $\lceil F/s \rceil \le 300$; a video of at most 300 frames is read at every frame. $T$ denotes the number of frames read, and $k$ indexes them. The `prepare` stage computes the reference estimates on the same timeline.
113
+
114
+ ### Metrics on all scenes
115
+
116
+ Let $x_k$ and $\hat x_k$ be frame $k$ of the reference and rendered videos.
117
+
118
+ **DINOv3 similarity** (`semantic_dinov3`). With $e_k$ and $\hat e_k$ the DINOv3 class-token embeddings of $x_k$ and $\hat x_k$, the mean frame-wise cosine similarity mapped to $[0, 1]$:
119
+ $$\mathrm{DINOv3}=\frac12\Big(1+\frac1T\sum_k \frac{e_k^\top \hat e_k}{\|e_k\|\,\|\hat e_k\|}\Big).$$
120
+
121
+ **Dynamic IoU** (`dynamic_iou`). $\hat M_k$ is the rasterised mask of the reconstruction's dynamic objects and $M_k$ the reference dynamic mask, rasterised from the reference world or annotated by hand for real videos. A thin band $B_k$ along the reference boundary is ignored, as in PASCAL VOC. On real scenes the reconstruction's mask is morphologically closed first, so granular material covers the region it fills.
122
+ $$\mathrm{DynIoU}=\frac1T\sum_k\frac{|(M_k\cap\hat M_k)\setminus B_k|}{|(M_k\cup\hat M_k)\setminus B_k|}.$$
123
+
124
+ ### Metrics on real videos
125
+
126
+ The reference side is estimated from `reference.mp4` with off-the-shelf models; the reconstruction side is computed analytically from the 4D world, not estimated from its render.
127
+
128
+ **Depth error** (`depth_error`, lower is better). $\tilde d_k$ is the Video Depth Anything disparity of $x_k$ and $\tilde{\hat d}_k$ the disparity of the reconstruction's meshes rasterised through its camera, each normalised by its median and mean absolute deviation, as in MiDaS. On the covered pixels, $E_k$ is the mean absolute difference with the largest 1% of residuals discarded. Uncovered pixels count as error 1, so with coverage $c_k$:
129
+ $$\mathrm{DepthErr}=\frac1T\sum_k\big(c_kE_k+(1-c_k)\big)\in[0,2].$$
130
+
131
+ **Flow** (`flow_distribution`). $U_k$ is the RAFT flow of the reference and $\hat U_k$ the reconstruction's analytic flow between frames $k$ and $k+1$ of the sampled timeline, at pixels valid on both sides that move more than 0.5 px on either. $\mathcal K$ is the set of steps with such pixels. At each step the two flows are compared as unordered sets by sliced Wasserstein distance, normalised by the RMS magnitudes $m$ of both sides:
132
+ $$\mathrm{Flow}=1-\frac1{|\mathcal K|}\sum_{k\in\mathcal K}\min\Big(1,\frac{\mathrm{SW}(U_k,\hat U_k)}{m(U_k)+m(\hat U_k)}\Big).$$
133
+ A step where the reference exhibits motion but the reconstruction contains no geometry receives a penalty value of 1.
134
+
135
+ **Track2D** (`track2d_dtw`). CoTracker3 tracks a grid of query points through the reference video. On the reconstruction, the surface point under each query is followed through the 4D world and projected, so path $i$ on one side corresponds to path $i$ on the other. The $n$ reference paths kept are those with a textured seed that travel more than 2% of the image diagonal $\delta$ after camera-motion compensation (the grid's shared drift removed). $D_i$ is the per-step DTW distance between corresponding paths in units of $\delta$, capped at $\kappa=0.03$:
136
+ $$\mathrm{Track2D}=1-\frac1n\sum_i\frac{\min(D_i,\kappa)}{\kappa}.$$
137
+
138
+ ### Metrics on synthetic scenes
139
+
140
+ The metrics below compare the reconstruction with the reference world in 3D, after registration.
141
+
142
+ **Registration.** $\mathcal P$ is the point cloud of surfaces visible at frame 0 of the reference world, with RMS radius $\sigma$; all 3D distances are in units of $\sigma$. Two similarity transforms are fitted by trimmed ICP, one on the two worlds' visible surfaces at frame 0 and one on their dynamic objects' surfaces over 16 frames. The transformation that minimizes registration error to $\mathcal P$ under the reference camera viewpoint is selected.
143
+
144
+ **Scene 3D** (`scene_3d`). $\hat{\mathcal P}$ is the registered reconstruction's frame-0 surface seen through the reference camera, and $D_\kappa$ the symmetric Chamfer distance with per-point distances capped at $\kappa=0.5$:
145
+ $$\mathrm{Scene3D}=1-D_\kappa(\mathcal P,\hat{\mathcal P})/\kappa.$$
146
+
147
+ **Trajectory DTW** (`trajectory_dtw`), Lagrangian view. Dynamic matter of both worlds is sampled at one voxel size and each sample is followed over its lifetime, giving up to 8192 3D paths $\{\tau_i\}$, $\{\hat\tau_j\}$ per side. A one-to-one assignment $\pi$ is solved by the Hungarian algorithm on DTW distances, capped at $\kappa=1$:
148
+ $$\mathrm{TrajDTW}=1-\frac1n\sum_i\frac{\min\big(\mathrm{DTW}(\tau_i,\hat\tau_{\pi(i)}),\kappa\big)}{\kappa}.$$
149
+
150
+ **EMD step** (`emd_step`), Eulerian view. $U_k$ and $\hat U_k$ are the one-step 3D displacements of the samples at frame $k$, compared as unordered sets by sliced Wasserstein distance. Normalising by the total motion over the video keeps near-static frames from dominating:
151
+ $$\mathrm{EMD\ step}=\max\Big(0,\,1-\frac{\sum_k\mathrm{SW}(U_k,\hat U_k)}{\sum_k\big(m(U_k)+m(\hat U_k)\big)}\Big).$$
152
+
153
+ ### Additional metrics
154
+
155
+ **TIPS similarity** (`semantic_tips`, all scenes). DINOv3 similarity with TIPSv2 embeddings in place of DINOv3.
156
+
157
+ **GeoPhys DINOv3** (`geophys_dinov3`, all scenes). Each video becomes a trajectory of DINOv3 layer-18 patch tokens, spatially averaged. Five regularity descriptors $\phi$ of the trajectory (GeoPhys) are compared as $1-\frac15\sum_\phi|\phi-\hat\phi|/(\phi+\hat\phi)$.
158
+
159
+ **Uni3D point** (`uni3d_point_scene`, synthetic). Cosine similarity of the Uni3D embeddings of the registered frame-0 clouds of Scene 3D, mapped to $[0, 1]$ as $(1+\cos)/2$.
160
+
161
+ **Uni3D MoGe** (`uni3d_moge_scene`, real). Cosine similarity of the Uni3D embeddings of the reconstruction's frame-0 visible surface and the MoGe-3 point map of $x_0$, mapped to $[0, 1]$ as $(1+\cos)/2$.
162
+
163
+ **Occupancy DTW** (`occupancy_dtw`, synthetic). The two worlds' matter is sampled as point sets at 16 evenly spaced frames. Every reference frame is compared with every reconstruction frame by sliced Wasserstein distance capped at 0.5; the score is one minus the per-step DTW cost of that matrix divided by the cap. No particle identity is required.
164
+
165
+ ### Geometry quality
166
+
167
+ Computed from the reconstructed world alone, over the runs that pass the world gate: the fraction of mesh components across all frames that are watertight, manifold, non-degenerate and free of self-intersections (`mesh_watertight`, `mesh_manifold`, `mesh_clean_faces`, `mesh_no_self_intersection`), and no interpenetration (`interpenetration`), one minus the fraction of vertices inside another object.
168
+
169
+ ### Output
170
+
171
+ Each run's `results/` holds:
172
+
173
+ - `reward.json`: one entry per metric, a number or a state.
174
+ - `reward.detail.json`: intermediate readings, strides, the fitted registration, and the cause of every non-number.
175
+ - the arrays behind each metric (`.npz`, `.h5`).
176
+
177
+ ## Checker
178
+
179
+ `python -m checker` inspects `/workspace/world` and `/workspace/solution`, takes no arguments, reports all format violations, and exits with a non-zero code on failure. It checks:
180
+
181
+ - the four entries exist and are readable;
182
+ - `camera.json`: shapes, finiteness, and a proper orthonormal rotation block in `extrinsic`;
183
+ - `meshes/`: member names, dtypes, shapes, face indices, finiteness and contiguous frame intervals;
184
+ - `dynamics/`: dtypes, shapes, index ranges and per-column lifetimes;
185
+ - every listed id has a mesh archive;
186
+ - $F$ agrees between `render.mp4` and every `pos`, and every mesh frame is below $F$;
187
+ - a static object's arrays are identical across its interval;
188
+ - `solver/`, if present: the seven `manifest.json` members are valid, and `cache` and `liquid_ids` resolve;
189
+ - `solution/` holds an executable `build.sh` and only `.py` / `.sh` files.
190
+
191
+ `python -m checker.preview` writes `/workspace/tmp/preview_0000.png`: frame 0 of `render.mp4` beside frame 0 of `meshes/` z-buffered through `camera.json` (one color per ID). Because it uses the scorer's projection, it visually verifies camera alignment before delivery.
论文参考代码/4DCodeBench/environment.yml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Conda environment for the scorer, the visualizer and the viewer, outside a container.
2
+ #
3
+ # conda env create -f environment.yml
4
+ # conda activate 4dcodebench
5
+ # scripts/setup_env.sh
6
+ #
7
+ # Conda provides Python, the CUDA 13.0 toolkit and the native libraries; setup_env.sh
8
+ # installs the Python packages of the scorer image with uv and builds `scorer-vdb`.
9
+ name: 4dcodebench
10
+ channels:
11
+ - conda-forge
12
+ - nodefaults
13
+ dependencies:
14
+ - python=3.12
15
+ - cuda-version=13.0
16
+ - cuda-nvcc
17
+ - cuda-libraries-dev
18
+ - cuda-cccl
19
+ - gxx=13
20
+ - ffmpeg
21
+ - libgl
22
+ - openvdb=13.0.0
23
+ - tbb-devel
24
+ - git
25
+ - uv
论文参考代码/4DCodeBench/harness/agent/Dockerfile ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM 4dcb/sim-base:dev
2
+
3
+ ENV DEBIAN_FRONTEND=noninteractive \
4
+ NODE_MAJOR=22 \
5
+ PYTHONPATH=/opt/4dcb
6
+
7
+ # The three agent CLIs: Claude Code, Codex and Antigravity. The image holds no
8
+ # credentials; each run mounts only its own CLI's credential file.
9
+ RUN apt-get update && apt-get install -y --no-install-recommends \
10
+ curl \
11
+ ca-certificates \
12
+ procps \
13
+ ripgrep \
14
+ && curl -fsSL https://deb.nodesource.com/setup_${NODE_MAJOR}.x | bash - \
15
+ && apt-get install -y --no-install-recommends nodejs \
16
+ && npm install -g @anthropic-ai/claude-code @openai/codex \
17
+ && curl -fsSL https://antigravity.google/cli/install.sh | bash -s -- --dir /usr/local/bin \
18
+ && mkdir -p /root/.local/bin \
19
+ && for cli in claude codex agy; do ln -sf "$(command -v $cli)" /usr/local/bin/$cli; ln -sf "$(command -v $cli)" /root/.local/bin/$cli; done \
20
+ && rm -rf /var/lib/apt/lists/*
21
+
22
+ RUN pip install --no-cache-dir numpy==2.3.1
23
+
24
+ # Blender's Python API reference as offline HTML in /opt/blender-docs, without
25
+ # Sphinx's .doctrees build cache.
26
+ RUN curl -fsSL https://docs.blender.org/api/5.2/blender_python_reference_5_2.zip \
27
+ -o /tmp/bpydocs.zip && \
28
+ python3 -c "import zipfile; z = zipfile.ZipFile('/tmp/bpydocs.zip'); \
29
+ z.extractall('/opt', [n for n in z.namelist() if '/.doctrees/' not in n])" && \
30
+ mv /opt/blender_python_reference_5_2 /opt/blender-docs && \
31
+ rm /tmp/bpydocs.zip
32
+ RUN mkdir -p /opt/4dcb/config
33
+ COPY config/__init__.py config/world.py /opt/4dcb/config/
34
+ COPY checker /opt/4dcb/checker
35
+
36
+ # Artificial Analysis' Stirrup agent loop, for the `stirrup` agent
37
+ RUN pip install --no-cache-dir stirrup==0.2.0
38
+
39
+ RUN mkdir -p \
40
+ /root/.claude/projects \
41
+ /root/.codex/sessions \
42
+ /root/.gemini/antigravity-cli/brain \
43
+ /root/.stirrup
44
+
45
+ WORKDIR /workspace
论文参考代码/4DCodeBench/harness/agent_context/TASK.md ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `input.mp4` is a video of a dynamic scene.
2
+ Your task is to write graphics code that, when rendered, reproduces the observed 4D scene.
3
+
4
+ Your reconstruction should model the scene and its dynamics explicitly.
5
+ It should be both visually and physically consistent with the target.
6
+ Render the result in Blender, matching the input's dimensions, framerate, and camera.
7
+
8
+ ## Scoring
9
+ Your solution will be scored frame-by-frame.
10
+ It will also be evaluated against the ground-truth 3D geometry.
11
+ Accordingly, solutions that represent motion or appearance in 2D or copy from the video instead of explicitly modeling the scene will be strongly penalized.
12
+ The autograder will fail submissions that copy pixels from the input video into the Blender scene for any purpose, such as to texture objects; all must be programmatically defined.
13
+
14
+ ## Output
15
+ The output should contain two directories:
16
+ 1. `{{paths.solution}}` is the program, an executable `build.sh`, and the Python it runs.
17
+ 2. `{{paths.world}}` is its output, holding the camera, the render, the geometry at every frame, and the 3D state of the moving matter over time.
18
+
19
+ `build.sh` takes no arguments, does **not** read the video file, and writes all of `{{paths.world}}` from nothing.
20
+ Both are required to verify that the reconstruction is reproducible.
21
+
22
+ Run `python -m checker` to confirm that what you have written is in the correct format.
23
+ The packaged checker does not contain the privileged autograder.
24
+
25
+ ## How to build the scene and its motion
26
+
27
+ One option is to do all of it in Blender: describe the 3D scene and its motion
28
+ through time there, and render that 4D sequence. You can also write external
29
+ graphics code or programs using the libraries provided to describe the motion of the scene
30
+ through time, and use Blender only to render the final 4D sequence. NumPy,
31
+ SciPy, PyTorch, Taichi, Warp and Trimesh are installed, and anything else on the
32
+ machine is fair game.
33
+
34
+ However the motion is computed, the evolution of the scene has to be rendered
35
+ with Blender, through the camera you export.
36
+
37
+ The rendered geometry in `meshes/` may change freely from frame to frame, vertex count and
38
+ topology included, as happens with liquids or fractures. `dynamics/` is where the
39
+ frame-to-frame correspondence lives: column `j` of `pos` is the same piece of
40
+ material at every frame, so `pos[t, j]` and `pos[t+1, j]` are that matter one
41
+ frame apart. Geometry rebuilt independently at each frame cannot give you that.
42
+
43
+ ## Output format
44
+
45
+ The full format of `{{paths.world}}` is in `{{paths.task}}/world-format.md`.
46
+ It lists every file with its dtype and shape, the camera conventions, and what to return for a liquid.
47
+ Read it before you write your export.
48
+
49
+ ### Program: `{{paths.solution}}`
50
+
51
+ `{{paths.solution}}` should contain an executable `build.sh` and the `.py` and `.sh` files it runs, in any layout.
52
+ Running `bash build.sh` should write the complete `{{paths.world}}`, replacing anything already there.
53
+ It cannot read the video, access the network, install packages, or load assets shipped alongside it.
54
+ Anyone with this environment should be able to rebuild your world by running it.
55
+
56
+ ### World: `{{paths.world}}`
57
+
58
+ ```
59
+ world/
60
+ camera.json {"intrinsics": K, "extrinsic": E}, the fixed camera
61
+ render.mp4 the rendered video
62
+ meshes/<id>.npz each rendered object's triangles at every frame
63
+ dynamics/<name>.npz each piece of moving material's positions over time
64
+ solver/ a liquid solver's own bake, if it keeps no particle identity
65
+ ```
66
+
67
+ `meshes/` is the geometry that gets rendered, and its vertex count and topology may change from frame to frame.
68
+ `dynamics/` describes how the 3D geometry of the moving objects moves through time: `pos` has shape `(F, N, 3)`, and column `j` is the same piece of material at every frame.
69
+ Static objects need only a `meshes/` archive.
70
+ The points in `dynamics/` are the vertices of your simulation mesh for a rigid body, cloth or soft body, and the particles for MPM, SPH or sand.
71
+
72
+ All positions are in world-space metres, with Z up.
73
+ `render.mp4` must match `{{paths.video}}` in frame count, frame rate and resolution, or it will not be scored.
74
+ Every file in `meshes/` and `dynamics/` uses the same `F` frames.
75
+ Each frame of `render.mp4` should show exactly the triangles in `meshes/` and nothing else.
76
+
77
+ ### Environment
78
+
79
+ The environment has FFmpeg, FFprobe, ImageMagick, Python and Blender.
80
+ You can run Blender as the `blender` executable or import it in Python as `bpy`.
81
+ NumPy, SciPy, PyTorch, Taichi, Warp, Trimesh, Pillow and the checker are available in Python.
82
+ The Blender Python API reference is in `/opt/blender-docs`.
83
+ `{{paths.task}}/render-settings.md` has the render settings we expect.
84
+
85
+ ### Checking your work
86
+
87
+ `python -m checker` reports every format error, and a world that fails it scores zero.
88
+ `python -m checker.preview` saves `/workspace/tmp/preview_0000.png`, with frame 0 of `render.mp4` next to your `meshes/` projected through `camera.json`.
89
+ If the two don't line up, your camera or meshes don't match what you rendered.
90
+ Neither tool checks whether your world matches the video.
91
+ Put intermediate files in `/workspace/tmp`, not in `world/` or `solution/`.
论文参考代码/4DCodeBench/harness/agent_context/render-settings.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Render settings this runtime expects
2
+
3
+ The task asks for `render.mp4` at the input video's frame count, resolution and
4
+ frame rate, rendered through the camera you export. How you get there is your
5
+ business; these are the settings this machine is set up for, and the ones the
6
+ reference worlds were rendered with.
7
+
8
+ ## Final render
9
+
10
+ Cycles, at the input video's own width and height, `resolution_percentage = 100`,
11
+ 128 samples, denoising on. Rendering smaller and scaling up changes what the
12
+ image-based metrics see, so render at the size you deliver.
13
+
14
+ ## GPU
15
+
16
+ The runtime provides an NVIDIA GPU. Cycles falls back to the CPU silently when
17
+ OptiX is not configured, which turns a twenty-minute render into an overnight
18
+ one, so configure it explicitly and fail loudly if it is missing:
19
+
20
+ ```python
21
+ scene.render.engine = "CYCLES"
22
+ preferences = bpy.context.preferences.addons["cycles"].preferences
23
+ preferences.compute_device_type = "OPTIX"
24
+ preferences.get_devices()
25
+ optix_devices = [device for device in preferences.devices if device.type == "OPTIX"]
26
+ if not optix_devices:
27
+ raise RuntimeError("No OptiX device is available")
28
+ for device in preferences.devices:
29
+ device.use = device.type == "OPTIX"
30
+ scene.cycles.device = "GPU"
31
+ scene.render.resolution_x = input_width
32
+ scene.render.resolution_y = input_height
33
+ scene.render.resolution_percentage = 100
34
+ scene.cycles.samples = 128
35
+ scene.cycles.use_denoising = True
36
+ ```
37
+
38
+ ## Writing the video
39
+
40
+ Two things about `render.mp4` that fail loudly only after a long render, and are
41
+ worth setting before you start one.
42
+
43
+ `file_format = "FFMPEG"` is rejected unless the media type is set first. Blender
44
+ 5 splits `ImageFormatSettings` by media, and the default is `IMAGE`, so the video
45
+ formats are not in the enum until you ask for them:
46
+
47
+ ```python
48
+ scene.render.image_settings.media_type = "VIDEO" # or FFMPEG is not selectable
49
+ scene.render.image_settings.file_format = "FFMPEG"
50
+ scene.render.ffmpeg.format = "MPEG4"
51
+ scene.render.ffmpeg.codec = "H264"
52
+ scene.render.fps = round(input_fps) # and fps_base for a fractional rate
53
+ ```
54
+
55
+ Blender names the file after the frame range, so a `filepath` of `.../render`
56
+ becomes `render0001-0251.mp4` and the delivery is missing the `render.mp4` the
57
+ format asks for. Spell the name out and turn the suffix off:
58
+
59
+ ```python
60
+ scene.render.use_file_extension = False
61
+ scene.render.filepath = str(world / "render.mp4")
62
+ ```
63
+
64
+ Check what you actually wrote before you deliver: `ffprobe -count_frames` on your
65
+ `render.mp4` and on the input should agree on frame count, width, height and
66
+ frame rate. The gate compares exactly those four and refuses the world outright
67
+ when they differ, before any metric is read.
68
+
69
+ ## While you are iterating
70
+
71
+ EEVEE at half size is much faster and good enough to check framing, motion and
72
+ timing against the video:
73
+
74
+ ```python
75
+ scene.render.engine = "BLENDER_EEVEE"
76
+ scene.render.resolution_percentage = 50
77
+ ```
78
+
79
+ Switch back to the settings above for what you deliver. A long Cycles render is
80
+ worth waiting for; let the command run to completion rather than polling it.
论文参考代码/4DCodeBench/harness/agent_context/world-format.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The World Package Format
2
+
3
+ The exact format of the world directory you return. TASK.md has the short
4
+ version and the rules that cost the most when they are wrong; this is the full
5
+ contract. `python -m checker` enforces all of it and prints every violation, and
6
+ a world that does not pass the checker scores zero.
7
+
8
+ Four entries: `camera.json`, `render.mp4`, `meshes/`, `dynamics/`. Plus
9
+ `solver/` for a liquid whose solver keeps no particle identity. Coordinates are
10
+ world-space metres, Z-up. All frame-indexed data share one timeline of `F`
11
+ frames, `F` being the frame count of `render.mp4`: frame `t` of the video, of
12
+ every `dynamics/` array and of every mesh archive is the same instant.
13
+
14
+ ```
15
+ world/
16
+ camera.json {"intrinsics": K, "extrinsic": E}
17
+ render.mp4 the rendered video
18
+ meshes/<id>.npz vertices_TTTT (V_t,3) float32, faces_TTTT (T_t,3) int32
19
+ dynamics/<name>.npz pos (F,N,3) float32, ids (M,) uint16; faces (T,3) int32 for a mesh, tets (K,4) int32 for a tetrahedral mesh
20
+ solver/manifest.json and the solver's own cache, for an identity-less liquid only
21
+ ```
22
+
23
+ ## `camera.json`
24
+
25
+ `camera.json` carries `intrinsics`, a 3×3 pinhole matrix in pixels, and
26
+ `extrinsic`, a 4×4 camera-to-world transform in metres. Both are shared by every
27
+ frame: the camera does not move. Camera axes are +x right, +y down, +z
28
+ forward, so a world point `p` projects proportionally to `K R^T (p - t)`; pixel
29
+ `(i, j)` has centre `(i+0.5, j+0.5)` and the principal point is `(W/2, H/2)`.
30
+ The scorer projects your geometry exactly this way, so getting it wrong shows up
31
+ as geometry sitting off the render.
32
+
33
+ ## `meshes/`
34
+
35
+ One archive per rendered object, `<id>.npz`, `<id>` a positive integer unique
36
+ within the world. **Every rendered object needs one, including a liquid.** One
37
+ member pair per frame of the object's lifetime, which is one contiguous interval
38
+ below `F`: `vertices_TTTT` `(V, 3)` float32, finite world-space metres, and
39
+ `faces_TTTT` `(T, 3)` int32 indexing that frame's vertices; `TTTT` is the
40
+ zero-padded frame index. A frame where the object has no geometry holds empty
41
+ arrays. Vertex count and topology may change between frames; the archive
42
+ carries no cross-frame correspondence.
43
+
44
+ An object no `dynamics/` archive lists is static: identical `vertices` and
45
+ `faces` at every frame of its lifetime. The exception is an identity-less liquid,
46
+ which is listed by no archive and is not static; its ids go in
47
+ `solver/manifest.json` under `liquid_ids`.
48
+
49
+ ## `dynamics/`
50
+
51
+ The state your description produced: one archive per piece of moving material,
52
+ any unique file name. Every rendered object that moves is listed in the `ids` of
53
+ some archive, except an identity-less liquid, which is named in
54
+ `solver/manifest.json` instead.
55
+
56
+ - `pos` `(F, N, 3)` float32. Column `j` is one piece of material through the whole
57
+ video: `pos[t, j]` is its position at frame `t`, finite over one contiguous
58
+ interval of at least one frame (its lifetime) and NaN outside it. A column is
59
+ the same material at every frame it exists; it is not rebuilt per frame.
60
+ - `ids` `(M,)` uint16, `M ≥ 1`: the `meshes/` ids that display this material. One
61
+ material may be displayed by several objects, and one object may display
62
+ several materials.
63
+ - Connectivity, the same at every frame, indexing columns of `pos`. At most one
64
+ member, `faces` or `tets`, according to how your dynamics represent the
65
+ material:
66
+ - surface mesh (rigid body, cloth, shell, soft-body surface): `pos` holds the
67
+ dynamics mesh's vertices, `faces` `(T, 3)` int32 its triangles;
68
+ - tetrahedral mesh (FEM): `pos` its vertices, `tets` `(K, 4)` int32 its
69
+ tetrahedra;
70
+ - particles (MPM, SPH, granular, PBD): `pos` holds every particle by slot, no
71
+ connectivity member; a slot is NaN where the particle is not active;
72
+ - a liquid whose solver keeps no particle identity, such as Blender's fluid
73
+ (Mantaflow), which reseeds its particles every frame: write no archive and
74
+ build no tracer columns. Ship the bake under `solver/` and the tracks are
75
+ extracted from it afterwards. Its per-frame mesh still goes in `meshes/`
76
+ like anything else, and every other moving object still needs its archive.
77
+
78
+ Every `pos` array has exactly `F` rows, and every mesh frame index falls below
79
+ `F`.
80
+
81
+ ## `solver/`
82
+
83
+ The solver's own bake, so the tracks can be extracted afterwards. Required only
84
+ for an identity-less liquid; omit it otherwise.
85
+
86
+ ```
87
+ world/solver/
88
+ manifest.json one JSON object, the seven members below
89
+ <cache>/ the solver's cache directory, exactly as written
90
+ ```
91
+
92
+ For Blender's `FLUID` domain: set `cache_type = "ALL"` before baking, or nothing
93
+ is written to disk and there is no bake to ship. Bake the full timeline, copy the
94
+ `cache_directory` whole with its `config/`, `data/` and `mesh/` subdirectories,
95
+ and do not clear it afterwards.
96
+
97
+ `manifest.json` carries the seven things the cache does not:
98
+
99
+ - `cache`, the directory name;
100
+ - `fps` and `time_scale`, the domain's own, so one frame is known to advance
101
+ `time_scale / fps` seconds of solver time;
102
+ - `metres_per_unit`;
103
+ - `domain_min`, the domain object's own box corner in world metres. Take it from
104
+ the object's box, not its evaluated mesh, which is the liquid surface and
105
+ shrinks with the pool;
106
+ - `frames`, first and last covered;
107
+ - `liquid_ids`, the `meshes/` ids rendering it.
108
+
109
+ ## `render.mp4`
110
+
111
+ An H.264 MP4 with the same frame count, resolution and frame rate as the input
112
+ video, rendered through `camera.json`. Those four are checked before anything
113
+ else is looked at, and a world that misses any of them is refused whole: not one
114
+ metric is read and the attempt scores nothing. So confirm what you actually
115
+ wrote, rather than what you meant to write:
116
+
117
+ ```bash
118
+ ffprobe -v error -select_streams v:0 -count_frames \
119
+ -show_entries stream=nb_read_frames,width,height,r_frame_rate \
120
+ -of csv=p=0 world/render.mp4
121
+ ```
122
+
123
+ and check it against the same reading of the input video. At every frame each
124
+ rendered object is exactly the triangle mesh stored under its id in `meshes/`,
125
+ and no geometry appears that is not in `meshes/`, so convert curves, volumes and
126
+ point clouds to triangles before rendering them. Lights, materials and world
127
+ shading are not geometry and are yours to choose.
128
+
129
+ ## What the checker checks
130
+
131
+ `python -m checker` prints every violation of the format above: missing entries,
132
+ wrong dtypes and shapes, indices out of range, lifetimes that are not
133
+ contiguous, a rotation block that is not orthonormal, a frame count that
134
+ disagrees with the video, an id in `ids` with no mesh archive, a static object
135
+ whose arrays change.
论文参考代码/4DCodeBench/harness/apptainer/10_nvidia.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "file_format_version" : "1.0.0",
3
+ "ICD" : {
4
+ "library_path" : "libEGL_nvidia.so.0"
5
+ }
6
+ }
论文参考代码/4DCodeBench/harness/base/Dockerfile ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:13.0.2-devel-ubuntu24.04
2
+
3
+ ENV DEBIAN_FRONTEND=noninteractive \
4
+ PYTHONUNBUFFERED=1 \
5
+ NVIDIA_VISIBLE_DEVICES=all \
6
+ NVIDIA_DRIVER_CAPABILITIES=compute,utility,graphics,display \
7
+ PATH="/opt/venv/bin:/opt/blender:$PATH"
8
+
9
+ # system packages: ffmpeg, ImageMagick and the headless GL, EGL and Vulkan libraries
10
+ RUN apt-get update && apt-get install -y --no-install-recommends \
11
+ python3 \
12
+ python3-pip \
13
+ python3-venv \
14
+ ffmpeg \
15
+ curl \
16
+ xz-utils \
17
+ ca-certificates \
18
+ libgl1 \
19
+ libglx-mesa0 \
20
+ libegl1 \
21
+ libgles2 \
22
+ libglib2.0-0 \
23
+ libsm6 \
24
+ libxext6 \
25
+ libxrender1 \
26
+ libgomp1 \
27
+ libxkbcommon0 \
28
+ libxkbcommon-x11-0 \
29
+ libxfixes3 \
30
+ libxi6 \
31
+ libxxf86vm1 \
32
+ libxcursor1 \
33
+ libxinerama1 \
34
+ libxrandr2 \
35
+ libvulkan1 \
36
+ mesa-vulkan-drivers \
37
+ imagemagick \
38
+ && rm -rf /var/lib/apt/lists/*
39
+
40
+ # CPython 3.13 as python3, the version the `bpy` 5.2.0 wheel (Blender as a Python module)
41
+ # is built for.
42
+ RUN curl -fsSL "https://github.com/astral-sh/python-build-standalone/releases/download/20260901/cpython-3.13.15%2B20260901-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz" \
43
+ | tar -xz -C /opt && ln -sf /opt/python/bin/python3.13 /usr/local/bin/python3
44
+
45
+ # Blender 5.2.0 as a standalone binary too: it bakes Mantaflow fluid, and its bundled Python
46
+ # has the OpenVDB, USD, OpenImageIO, MaterialX and OpenColorIO bindings the wheel lacks.
47
+ RUN mkdir -p /opt/blender && \
48
+ curl -fsSL -H "User-Agent: Mozilla/5.0" \
49
+ https://download.blender.org/release/Blender5.2/blender-5.2.0-linux-x64.tar.xz \
50
+ | tar -xJ -C /opt/blender --strip-components=1
51
+
52
+ # /opt/venv: bpy, CUDA 13 PyTorch and the solution libraries, including Taichi and Warp
53
+ # for solutions that write their own simulator.
54
+ RUN python3 -m venv /opt/venv && \
55
+ /opt/venv/bin/pip install --no-cache-dir --upgrade pip && \
56
+ /opt/venv/bin/pip install --no-cache-dir bpy==5.2.0 torch==2.13.0 scipy==1.18.0 trimesh==5.0.0 pillow==11.3.0 \
57
+ taichi==1.7.4 warp-lang==1.17.0
58
+
59
+ # GPU smoke test, the default command
60
+ COPY harness/base/verify_gpu.py /usr/local/bin/verify_gpu.py
61
+ RUN chmod +x /usr/local/bin/verify_gpu.py
62
+
63
+ WORKDIR /workspace
64
+
65
+ CMD ["/usr/local/bin/verify_gpu.py"]
论文参考代码/4DCodeBench/harness/base/verify_gpu.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """GPU smoke test of the sim-base image; the image's default command.
3
+
4
+ Checks, in order: nvidia-smi runs; nvcc is CUDA 13.0; Blender Cycles renders a
5
+ frame on a CUDA or OptiX device; PyTorch 2.13.0 with CUDA 13.0 runs a matmul on
6
+ the GPU. Exits 0 when all pass, non-zero with a message at the first failure.
7
+ """
8
+
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+
15
+
16
+ EXPECTED_CUDA_VERSION = "13.0"
17
+ EXPECTED_TORCH_VERSION = "2.13.0"
18
+
19
+
20
+ def log_section(title: str) -> None:
21
+ print(f"\n{'=' * 70}")
22
+ print(f" {title}")
23
+ print(f"{'=' * 70}\n")
24
+
25
+
26
+ def verify_nvidia_smi() -> None:
27
+ log_section("1. Verifying nvidia-smi and GPU visibility")
28
+ try:
29
+ result = subprocess.run(
30
+ ["nvidia-smi"],
31
+ capture_output=True,
32
+ text=True,
33
+ check=True,
34
+ )
35
+ print(result.stdout)
36
+ except FileNotFoundError:
37
+ print("[FAIL] 'nvidia-smi' executable not found on PATH.", file=sys.stderr)
38
+ sys.exit(1)
39
+ except subprocess.CalledProcessError as e:
40
+ print(f"[FAIL] 'nvidia-smi' exited with error code {e.returncode}:", file=sys.stderr)
41
+ print(e.stderr, file=sys.stderr)
42
+ sys.exit(1)
43
+ print("[PASS] nvidia-smi executed successfully.")
44
+
45
+
46
+ def verify_cuda_toolkit() -> None:
47
+ log_section("2. Verifying CUDA 13.0 Toolkit")
48
+ result = subprocess.run(
49
+ ["nvcc", "--version"],
50
+ capture_output=True,
51
+ text=True,
52
+ check=True,
53
+ )
54
+ print(result.stdout)
55
+ if f"release {EXPECTED_CUDA_VERSION}" not in result.stdout:
56
+ raise RuntimeError(
57
+ f"nvcc is not from CUDA {EXPECTED_CUDA_VERSION}: {result.stdout.strip()}"
58
+ )
59
+ print(f"[PASS] CUDA Toolkit {EXPECTED_CUDA_VERSION} is available.")
60
+
61
+
62
+ def verify_blender_cycles_gpu() -> None:
63
+ log_section("3. Verifying Blender 5.2 Cycles GPU Rendering (CUDA/OPTIX)")
64
+ blender_bin = shutil.which("blender")
65
+ if not blender_bin:
66
+ print("[FAIL] 'blender' executable not found on PATH.", file=sys.stderr)
67
+ sys.exit(1)
68
+
69
+ blender_test_script = """
70
+ import bpy
71
+ import sys
72
+ import os
73
+
74
+ print(f"Blender Version: {bpy.app.version_string}")
75
+
76
+ # Access Cycles preferences
77
+ cpref = bpy.context.preferences.addons['cycles'].preferences
78
+ cpref.get_devices()
79
+
80
+ print("Probing available compute device types...")
81
+ chosen_backend = None
82
+ for dt in ('OPTIX', 'CUDA'):
83
+ try:
84
+ cpref.compute_device_type = dt
85
+ cpref.get_devices()
86
+ gpu_devs = [d for d in cpref.devices if d.type == dt]
87
+ print(f" Backend '{dt}': found {len(gpu_devs)} GPU device(s) -> {[d.name for d in gpu_devs]}")
88
+ if gpu_devs and chosen_backend is None:
89
+ chosen_backend = dt
90
+ except Exception as e:
91
+ print(f" Backend '{dt}' probe failed: {e}")
92
+
93
+ if not chosen_backend:
94
+ print("[FAIL] No CUDA or OPTIX GPU devices detected by Blender Cycles!", file=sys.stderr)
95
+ sys.exit(1)
96
+
97
+ print(f"Configuring Blender Cycles to use {chosen_backend} backend...")
98
+ cpref.compute_device_type = chosen_backend
99
+ cpref.get_devices()
100
+
101
+ active_gpus = []
102
+ active_cpus = []
103
+ for dev in cpref.devices:
104
+ if dev.type == chosen_backend:
105
+ dev.use = True
106
+ active_gpus.append(dev.name)
107
+ else:
108
+ dev.use = False
109
+ if dev.type == 'CPU':
110
+ active_cpus.append(dev.name)
111
+
112
+ assert len(active_gpus) > 0, f"No GPU devices enabled for backend {chosen_backend}"
113
+ print(f"Enabled GPU device(s): {active_gpus}")
114
+ print(f"Disabled CPU device(s): {active_cpus}")
115
+
116
+ # Configure scene for GPU render
117
+ scene = bpy.context.scene
118
+ scene.render.engine = 'CYCLES'
119
+ scene.cycles.device = 'GPU'
120
+ scene.render.resolution_x = 64
121
+ scene.render.resolution_y = 64
122
+ scene.cycles.samples = 4
123
+
124
+ temp_output = "/tmp/blender_smoke_test_render.png"
125
+ scene.render.filepath = temp_output
126
+
127
+ print("Rendering test frame using Cycles GPU...")
128
+ bpy.ops.render.render(write_still=True)
129
+
130
+ if not os.path.exists(temp_output) or os.path.getsize(temp_output) == 0:
131
+ print(f"[FAIL] Rendered output file missing or empty: {temp_output}", file=sys.stderr)
132
+ sys.exit(1)
133
+
134
+ # Verify device configuration
135
+ assert scene.render.engine == 'CYCLES', f"Engine is {scene.render.engine}, expected CYCLES"
136
+ assert scene.cycles.device == 'GPU', f"Cycles device is {scene.cycles.device}, expected GPU"
137
+ assert cpref.compute_device_type in ('OPTIX', 'CUDA'), f"Compute device type is {cpref.compute_device_type}"
138
+
139
+ # Cleanup
140
+ try:
141
+ os.remove(temp_output)
142
+ except OSError:
143
+ pass
144
+
145
+ print(f"[PASS] Blender Cycles GPU render succeeded on device(s): {active_gpus} (backend: {chosen_backend}).")
146
+ """
147
+
148
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
149
+ f.write(blender_test_script)
150
+ script_path = f.name
151
+
152
+ try:
153
+ result = subprocess.run(
154
+ [blender_bin, "-b", "--python", script_path],
155
+ capture_output=True,
156
+ text=True,
157
+ check=True,
158
+ )
159
+ print(result.stdout)
160
+ if result.stderr:
161
+ print("Blender stderr (diagnostics):", result.stderr)
162
+ except subprocess.CalledProcessError as e:
163
+ print(f"[FAIL] Blender render test failed with exit code {e.returncode}:", file=sys.stderr)
164
+ print(e.stdout, file=sys.stderr)
165
+ print(e.stderr, file=sys.stderr)
166
+ sys.exit(1)
167
+ finally:
168
+ if os.path.exists(script_path):
169
+ os.remove(script_path)
170
+
171
+
172
+ def verify_torch_gpu() -> None:
173
+ log_section("4. Verifying PyTorch CUDA 13.0")
174
+ try:
175
+ import torch
176
+ print(f"PyTorch version: {torch.__version__}")
177
+ print(f"PyTorch CUDA runtime: {torch.version.cuda}")
178
+ if torch.__version__.split("+", 1)[0] != EXPECTED_TORCH_VERSION:
179
+ raise RuntimeError(
180
+ f"PyTorch {torch.__version__} != expected {EXPECTED_TORCH_VERSION}"
181
+ )
182
+ if torch.version.cuda != EXPECTED_CUDA_VERSION:
183
+ raise RuntimeError(
184
+ f"PyTorch CUDA {torch.version.cuda} != expected {EXPECTED_CUDA_VERSION}"
185
+ )
186
+ print(f"PyTorch CUDA available: {torch.cuda.is_available()}")
187
+ if not torch.cuda.is_available():
188
+ print("[FAIL] PyTorch cannot access CUDA GPU.", file=sys.stderr)
189
+ sys.exit(1)
190
+ print(f"PyTorch CUDA Device 0: {torch.cuda.get_device_name(0)}")
191
+
192
+ x = torch.rand(1024, 1024, device="cuda")
193
+ y = (x @ x).sum()
194
+ assert y.is_cuda, "Matmul result tensor is not on CUDA device!"
195
+ print(f"CUDA matmul checksum: {float(y):.3f}")
196
+ print("[PASS] PyTorch CUDA tensors succeeded.")
197
+
198
+ except Exception as e:
199
+ import traceback
200
+ print(f"[FAIL] PyTorch GPU verification encountered an exception: {e}", file=sys.stderr)
201
+ traceback.print_exc()
202
+ sys.exit(1)
203
+
204
+
205
+ def main() -> None:
206
+ print("Starting 4DCodeBench Base Environment GPU Verification Smoke Test...")
207
+ verify_nvidia_smi()
208
+ verify_cuda_toolkit()
209
+ verify_blender_cycles_gpu()
210
+ verify_torch_gpu()
211
+ log_section("ALL GPU VERIFICATIONS PASSED SUCCESSFULLY")
212
+ sys.exit(0)
213
+
214
+
215
+ if __name__ == "__main__":
216
+ main()
论文参考代码/4DCodeBench/harness/runtime/agents.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The headless command line of each agent, and the agent registry.
2
+
3
+ All agents run in one image. `infer.py` adds each agent's environment and mounts
4
+ only that agent's credential file.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Agent:
14
+ """One agent: its name, accepted efforts (empty: any), and transcript dir under $HOME."""
15
+
16
+ name: str
17
+ efforts: tuple[str, ...]
18
+ session_dir: str
19
+
20
+ def command(self, task_path: str, workspace_path: str, model: str, effort: str, timeout_sec: int) -> list[str]:
21
+ raise NotImplementedError
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class ClaudeCode(Agent):
26
+ def command(self, task_path: str, workspace_path: str, model: str, effort: str, timeout_sec: int) -> list[str]:
27
+ return [
28
+ "bash", "-c",
29
+ (
30
+ f'claude -p "$(cat {task_path})" --model {model} --effort {effort} '
31
+ f"--permission-mode dontAsk --allowedTools Bash Edit Write Read Glob Grep NotebookEdit "
32
+ f"--output-format json"
33
+ ),
34
+ ]
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Codex(Agent):
39
+ def command(self, task_path: str, workspace_path: str, model: str, effort: str, timeout_sec: int) -> list[str]:
40
+ return [
41
+ "bash", "-c",
42
+ (
43
+ f'codex exec "$(cat {task_path})" --model {model} '
44
+ f'-c model_reasoning_effort="{effort}" '
45
+ # plugin sync is off: it copies bundles into ~/.codex at startup and can block exit
46
+ f"--disable plugins --disable remote_plugin "
47
+ f"--dangerously-bypass-approvals-and-sandbox --skip-git-repo-check -C {workspace_path} --json"
48
+ ),
49
+ ]
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Antigravity(Agent):
54
+ def command(self, task_path: str, workspace_path: str, model: str, effort: str, timeout_sec: int) -> list[str]:
55
+ return [
56
+ "bash", "-c",
57
+ (
58
+ f'agy -p "$(cat {task_path})" --model {model} --effort {effort} '
59
+ f"--dangerously-skip-permissions --output-format json --print-timeout {timeout_sec}s"
60
+ ),
61
+ ]
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Stirrup(Agent):
66
+ """Artificial Analysis' Stirrup agent loop: harness/stirrup/runner.py at /opt/stirrup."""
67
+
68
+ def command(self, task_path: str, workspace_path: str, model: str, effort: str, timeout_sec: int) -> list[str]:
69
+ return ["bash", "-c", f"python3 /opt/stirrup/runner.py {task_path} {workspace_path} {model} {effort} {timeout_sec}"]
70
+
71
+
72
+ AGENTS: dict[str, Agent] = {
73
+ # stirrup takes any effort and sends it as reasoning_effort
74
+ "stirrup": Stirrup(name="stirrup", efforts=(), session_dir=".stirrup"),
75
+ "claude": ClaudeCode(
76
+ name="claude",
77
+ efforts=("low", "medium", "high", "xhigh", "max"),
78
+ session_dir=".claude/projects",
79
+ ),
80
+ "codex": Codex(
81
+ name="codex",
82
+ efforts=("low", "medium", "high", "xhigh", "max"),
83
+ session_dir=".codex/sessions",
84
+ ),
85
+ "antigravity": Antigravity(
86
+ name="antigravity",
87
+ efforts=("low", "medium", "high"),
88
+ session_dir=".gemini/antigravity-cli/brain",
89
+ ),
90
+ }
91
+
92
+
93
+ def agent(name: str) -> Agent:
94
+ if name not in AGENTS:
95
+ raise KeyError(f"unknown agent {name!r}; known: {sorted(AGENTS)}")
96
+ return AGENTS[name]
论文参考代码/4DCodeBench/harness/runtime/common.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared runtime configuration and process helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shlex
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ import tomllib
12
+
13
+ REPO = Path(__file__).resolve().parents[2]
14
+
15
+
16
+ def log(*items: object) -> None:
17
+ print("[RUN]", *items)
18
+ sys.stdout.flush()
19
+
20
+
21
+ CASE_VIDEO = "reference.mp4"
22
+ # the agent's task: this directory, rendered and mounted read-only at TASK_MOUNT
23
+ TASK_CONTEXT = REPO / "harness" / "agent_context"
24
+ TASK_ENTRYPOINT = "TASK.md"
25
+ TASK_MOUNT = Path("/task")
26
+ # one run's directory: runs/<kind>/<case>/<agent>-<model>-<effort>/<trial>/
27
+ RUN_WORKSPACE = "workspace" # the collected world/ and solution/
28
+ RUN_LOGS = "logs" # agent.log, the CLI's stdout and stderr
29
+ RUN_SESSION = "session" # the CLI's own transcript
30
+ RUN_RECORD = "run.json"
31
+ AGENT_LOG = "agent.log"
32
+
33
+
34
+ def read_toml(path: Path) -> dict:
35
+ return tomllib.loads(path.read_text(encoding="utf-8"))
36
+
37
+
38
+ def host_path(value: str) -> Path:
39
+ path = Path(value)
40
+ return path if path.is_absolute() else REPO / path
41
+
42
+
43
+ def display(command: list[str]) -> str:
44
+ return shlex.join(command)
45
+
46
+
47
+ def require_file(path: Path, label: str) -> Path:
48
+ if not path.is_file():
49
+ raise FileNotFoundError(f"{label} does not exist: {path}")
50
+ return path
51
+
52
+
53
+ def resolve_case(cases_root: Path, case: str) -> str:
54
+ """Return `<kind>/<case>` for a case given as `<case>` or `<kind>/<case>`.
55
+
56
+ `runs/` and `data/` mirror this path under `cases/`. A bare name is looked up
57
+ under each kind and must match exactly one; a case not on disk raises.
58
+ """
59
+
60
+ parts = Path(case).parts
61
+ if len(parts) == 2:
62
+ if not (cases_root / case).is_dir():
63
+ raise FileNotFoundError(f"case does not exist: {cases_root / case}")
64
+ return "/".join(parts)
65
+ if len(parts) != 1:
66
+ raise ValueError(f"a case is named <case> or <kind>/<case>, not {case!r}")
67
+ found = [kind.name for kind in sorted(cases_root.iterdir())
68
+ if kind.is_dir() and (kind / case).is_dir()]
69
+ if len(found) != 1:
70
+ raise FileNotFoundError(f"{case!r} names {len(found)} cases under {cases_root}")
71
+ return f"{found[0]}/{case}"
72
+
73
+
74
+ def run_process(command: list[str], log_path: Path, timeout_sec: int) -> int:
75
+ """Run `command` with its output in `log_path`; kill it and return 124 on timeout."""
76
+
77
+ log("$", display(command))
78
+ with log_path.open("w", encoding="utf-8") as handle:
79
+ process = subprocess.Popen(command, stdout=handle, stderr=subprocess.STDOUT, text=True)
80
+ try:
81
+ return process.wait(timeout=timeout_sec)
82
+ except subprocess.TimeoutExpired:
83
+ process.kill()
84
+ handle.write(f"\n[RUN] killed after {timeout_sec}s\n")
85
+ return 124
86
+
87
+
88
+ def network_args(mode: str) -> list[str]:
89
+ if mode == "default":
90
+ return []
91
+ if mode == "no-network":
92
+ return ["--network", "none"]
93
+ raise ValueError(f"unsupported network_mode {mode!r}")
94
+
95
+
96
+ def sif_network_args(mode: str) -> list[str]:
97
+ if mode == "default":
98
+ return []
99
+ if mode == "no-network":
100
+ return ["--net", "--network", "none"]
101
+ raise ValueError(f"unsupported network_mode {mode!r}")
102
+
103
+
104
+ def gpu_args(count: int, *, backend: str) -> list[str]:
105
+ """GPU flags for one container.
106
+
107
+ Docker gets `--gpus device=$CUDA_VISIBLE_DEVICES` when that is set, else `--gpus <count>`.
108
+ SIF gets `--nv`; `device_environment` passes the pinned device.
109
+ """
110
+
111
+ if count < 0:
112
+ raise ValueError("gpus must be non-negative")
113
+ if count == 0:
114
+ return []
115
+ if backend != "docker":
116
+ return ["--nv"]
117
+ selection = os.environ.get("CUDA_VISIBLE_DEVICES")
118
+ return ["--gpus", f"device={selection}" if selection else str(count)]
119
+
120
+
121
+ # thread-pool sizes for OpenMP (torch), the BLAS behind numpy, numexpr and OpenCV
122
+ THREAD_VARIABLES = ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS",
123
+ "NUMEXPR_NUM_THREADS", "OPENCV_FOR_THREADS_NUM", "CV_NUM_THREADS")
124
+
125
+
126
+ def thread_environment(cpus: int) -> dict[str, str]:
127
+ """Set every thread pool in THREAD_VARIABLES to the container's CPU count."""
128
+
129
+ return {name: str(max(1, int(cpus))) for name in THREAD_VARIABLES}
130
+
131
+
132
+ def device_environment() -> dict[str, str]:
133
+ """Return `CUDA_VISIBLE_DEVICES` for a SIF `--env` flag, or {} when unset.
134
+
135
+ `--cleanenv` drops it, and the `*ENV_` passthrough prefix differs between
136
+ Apptainer and SingularityCE.
137
+ """
138
+
139
+ selection = os.environ.get("CUDA_VISIBLE_DEVICES")
140
+ return {"CUDA_VISIBLE_DEVICES": selection} if selection else {}
141
+
142
+
143
+ def docker_command(runtime: dict, arguments: list[str]) -> list[str]:
144
+ return [runtime["docker"]["executable"], *arguments]
145
+
146
+
147
+ Mount = tuple[Path | None, Path | str, str]
148
+
149
+
150
+ def mount_args(flag: str, mounts: list[Mount]) -> list[str]:
151
+ """Return `-v`/`-B` flag pairs for `mounts`, skipping a `None` source.
152
+
153
+ Every mount names its mode explicitly, `ro` or `rw`.
154
+ """
155
+
156
+ arguments = []
157
+ for source, target, mode in mounts:
158
+ if source is None:
159
+ continue
160
+ if mode not in ("ro", "rw"):
161
+ raise ValueError(f"a mount is ro or rw, not {mode!r}")
162
+ arguments += [flag, f"{source}:{target}:{mode}"]
163
+ return arguments
164
+
165
+
166
+ def container_command(runtime: dict, environment: dict, image: str,
167
+ mounts: list[Mount], command: list[str]) -> list[str]:
168
+ """Build the Docker or SIF command that runs `command` in `image` with `mounts`.
169
+
170
+ `command[0]` replaces the Docker entry point; SIF passes `command` to `exec`.
171
+ Both backends take GPUs, network mode and thread counts from `environment`;
172
+ Docker also applies its CPU and memory limits.
173
+ """
174
+
175
+ backend = runtime["backend"]
176
+ gpus = int(environment["gpus"])
177
+ threads = thread_environment(environment["cpus"])
178
+
179
+ if backend == "docker":
180
+ return docker_command(runtime, [
181
+ "run",
182
+ "--rm",
183
+ f"--cpus={environment['cpus']}",
184
+ f"--memory={environment['memory_mb']}m",
185
+ *[argument for name, value in threads.items() for argument in ("--env", f"{name}={value}")],
186
+ *gpu_args(gpus, backend=backend),
187
+ *network_args(environment["network_mode"]),
188
+ "--entrypoint",
189
+ command[0],
190
+ *mount_args("-v", mounts),
191
+ image,
192
+ *command[1:],
193
+ ])
194
+
195
+ if backend == "sif":
196
+ variables = threads | device_environment()
197
+ return [
198
+ runtime["sif"]["executable"],
199
+ "exec",
200
+ *gpu_args(gpus, backend=backend),
201
+ *sif_network_args(environment["network_mode"]),
202
+ "--containall",
203
+ "--no-home",
204
+ "--cleanenv",
205
+ *[argument for name, value in variables.items() for argument in ("--env", f"{name}={value}")],
206
+ *mount_args("-B", mounts),
207
+ image,
208
+ *command,
209
+ ]
210
+
211
+ raise ValueError(f"unsupported runtime backend {backend!r}")
论文参考代码/4DCodeBench/harness/runtime/cost.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Token usage, cost and step counts of agent runs.
2
+
3
+ python harness/runtime/cost.py <runs_root> # recompute them into every run.json
4
+
5
+ Prices come from LiteLLM's price table at a pinned revision. A model is looked up
6
+ by its normalised name: lower case, no provider path, no serving suffix (`-fp8`,
7
+ `-sglang`, ...). `stirrup` models use OpenRouter's rates first, the CLIs' models
8
+ their provider's. An unlisted model keeps its usage and gets a null `cost_usd`.
9
+
10
+ `steps` counts model responses and `tool_calls` the tool invocations in them,
11
+ both read from the session transcript.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from pathlib import Path
18
+ from urllib.request import urlopen
19
+
20
+ from agents import agent
21
+
22
+ PRICES_URL = ("https://raw.githubusercontent.com/BerriAI/litellm/"
23
+ "b79fc9f1b0249cb533391dd7c941082f0cd6ddb1/model_prices_and_context_window.json")
24
+ PRICES_CACHE = Path.home() / ".cache" / "4dcodebench" / "model_prices_and_context_window.json"
25
+ # suffixes of served model names that the price table does not carry
26
+ SERVING_SUFFIXES = ("-sglang", "-vllm", "-fp8", "-nvfp4", "-awq", "-int4", "-int8")
27
+ PRICE_FIELDS = ("input_cost_per_token", "output_cost_per_token", "cache_read_input_token_cost",
28
+ "cache_creation_input_token_cost")
29
+ # Stirrup usage counts each request's prefix shared with the previous one as cached;
30
+ # cost bills this fraction of those tokens at the cache-read rate.
31
+ CACHE_HIT_RATE = 0.95
32
+
33
+
34
+ def _lines(path: Path) -> list[dict]:
35
+ # JSON lines of a transcript; unparsable lines (a truncated last line) are skipped
36
+ found = []
37
+ for line in path.read_text(encoding="utf-8").splitlines():
38
+ if line.startswith("{"):
39
+ try:
40
+ found.append(json.loads(line))
41
+ except json.JSONDecodeError:
42
+ continue
43
+ return found
44
+
45
+
46
+ def _stirrup_usage(session: Path) -> dict | None:
47
+ # sums `step` lines, whose token counters are cumulative per file; the input shared
48
+ # with the previous request counts as cached
49
+ inputs, completion = [], 0
50
+ for transcript in sorted(session.rglob("[0-9]*.jsonl")):
51
+ last_in = last_out = 0
52
+ for item in _lines(transcript):
53
+ if item.get("type") != "step":
54
+ continue
55
+ inputs.append(item["input_tokens"] - last_in)
56
+ completion += item["output_tokens"] - last_out
57
+ last_in, last_out = item["input_tokens"], item["output_tokens"]
58
+ if not inputs:
59
+ return None
60
+ cached = sum(min(previous, current) for previous, current in zip(inputs, inputs[1:]))
61
+ return {
62
+ "input_tokens": sum(inputs) - cached,
63
+ "cached_input_tokens": cached,
64
+ "cache_write_tokens": 0,
65
+ "output_tokens": completion,
66
+ "reasoning_output_tokens": 0,
67
+ }
68
+
69
+
70
+ def _accumulated_usage(source: Path, family: str) -> dict | None:
71
+ """Sum token counts over a claude or codex session's request records, subagents included."""
72
+
73
+ totals = dict.fromkeys(("input_tokens", "cached_input_tokens", "cache_write_tokens",
74
+ "output_tokens", "reasoning_output_tokens"), 0)
75
+ files = sorted(source.rglob("*.jsonl")) if source.is_dir() else [source] if source.is_file() else []
76
+ counted, seen = False, set()
77
+ for transcript in files:
78
+ for item in _lines(transcript):
79
+ if family == "claude":
80
+ # one line per content block; usage repeats per message id, counted once
81
+ message = item.get("message") if isinstance(item.get("message"), dict) else {}
82
+ raw = message.get("usage")
83
+ if not raw or message.get("id") in seen:
84
+ continue
85
+ seen.add(message.get("id"))
86
+ totals["input_tokens"] += raw.get("input_tokens", 0)
87
+ totals["cached_input_tokens"] += raw.get("cache_read_input_tokens", 0)
88
+ totals["cache_write_tokens"] += raw.get("cache_creation_input_tokens", 0)
89
+ totals["output_tokens"] += raw.get("output_tokens", 0)
90
+ totals["reasoning_output_tokens"] += (raw.get("output_tokens_details") or {}).get("thinking_tokens", 0)
91
+ elif family == "codex":
92
+ payload = item.get("payload")
93
+ if item.get("type") != "event_msg" or not isinstance(payload, dict) \
94
+ or payload.get("type") != "token_count":
95
+ continue
96
+ raw = (payload.get("info") or {}).get("last_token_usage")
97
+ if not raw:
98
+ continue
99
+ totals["input_tokens"] += raw.get("input_tokens", 0) - raw.get("cached_input_tokens", 0)
100
+ totals["cached_input_tokens"] += raw.get("cached_input_tokens", 0)
101
+ totals["output_tokens"] += raw.get("output_tokens", 0)
102
+ totals["reasoning_output_tokens"] += raw.get("reasoning_output_tokens", 0)
103
+ else:
104
+ return None
105
+ counted = True
106
+ return totals if counted else None
107
+
108
+
109
+ def summarize_cost(path: Path, family: str, model: str) -> dict | None:
110
+ """Return usage and cost of one run from its agent.log, falling back to the session."""
111
+
112
+ if family == "stirrup": # read from the session transcript
113
+ usage = _stirrup_usage(path.parents[1] / "session")
114
+ if usage is None:
115
+ return None
116
+ elif family == "antigravity":
117
+ payloads = _lines(path)
118
+ payload = next((item for item in reversed(payloads) if "usage" in item), None)
119
+ if payload is None:
120
+ return None
121
+ raw = payload["usage"]
122
+ usage = {
123
+ "input_tokens": raw["input_tokens"],
124
+ "cached_input_tokens": raw.get("cache_read_tokens", 0),
125
+ "cache_write_tokens": 0,
126
+ "output_tokens": raw["output_tokens"],
127
+ "reasoning_output_tokens": raw.get("thinking_tokens", 0),
128
+ }
129
+ elif family == "claude":
130
+ # summed from the session transcripts; the agent.log summary line is the fallback
131
+ usage = _accumulated_usage(path.parents[1] / "session", family)
132
+ payload = next((item for item in reversed(_lines(path)) if "usage" in item), None)
133
+ if usage is None and payload is None:
134
+ return None
135
+ if usage is None:
136
+ raw = payload["usage"]
137
+ usage = {
138
+ "input_tokens": raw["input_tokens"],
139
+ "cached_input_tokens": raw["cache_read_input_tokens"],
140
+ "cache_write_tokens": raw["cache_creation_input_tokens"],
141
+ "output_tokens": raw["output_tokens"],
142
+ "reasoning_output_tokens": raw.get("output_tokens_details", {}).get("thinking_tokens", 0),
143
+ }
144
+ elif family == "codex":
145
+ payloads = _lines(path)
146
+ payload = next((item for item in reversed(payloads) if item.get("type") == "turn.completed"), None)
147
+ if payload is None:
148
+ usage = _accumulated_usage(path.parents[1] / "session", family)
149
+ return None if usage is None else _price(usage, family, model)
150
+ raw = payload["usage"]
151
+ usage = {
152
+ "input_tokens": raw["input_tokens"] - raw["cached_input_tokens"],
153
+ "cached_input_tokens": raw["cached_input_tokens"],
154
+ "cache_write_tokens": 0,
155
+ "output_tokens": raw["output_tokens"],
156
+ "reasoning_output_tokens": raw["reasoning_output_tokens"],
157
+ }
158
+ else:
159
+ raise ValueError(f"unsupported agent family {family!r}")
160
+
161
+ return _price(usage, family, model)
162
+
163
+
164
+ def _table() -> dict:
165
+ """Return the pinned price table, downloading it once into the user's cache."""
166
+
167
+ if not PRICES_CACHE.is_file():
168
+ PRICES_CACHE.parent.mkdir(parents=True, exist_ok=True)
169
+ with urlopen(PRICES_URL, timeout=60) as response:
170
+ data = response.read()
171
+ partial = PRICES_CACHE.with_suffix(".part")
172
+ partial.write_bytes(data)
173
+ partial.replace(PRICES_CACHE)
174
+ return json.loads(PRICES_CACHE.read_text(encoding="utf-8"))
175
+
176
+
177
+ def normalize(model: str) -> str:
178
+ """Return `model` lower-cased, without provider path or serving suffixes."""
179
+
180
+ name = model.lower().rsplit("/", 1)[-1]
181
+ while name.endswith(SERVING_SUFFIXES):
182
+ name = name[:name.rindex("-")]
183
+ return name
184
+
185
+
186
+ def price_entry(table: dict, model: str, family: str) -> tuple[str, dict] | None:
187
+ """Return the table's key and entry for `model`, or None when it is not listed."""
188
+
189
+ name = normalize(model)
190
+ exact = [key for key in table if key.lower() == name]
191
+ routed = sorted(key for key in table
192
+ if key.lower().startswith("openrouter/") and key.lower().rsplit("/", 1)[-1] == name)
193
+ ordered = routed + exact if family == "stirrup" else exact + routed
194
+ if not ordered:
195
+ # listed only under other providers: used when they all charge the same
196
+ others = sorted(key for key in table if key.lower().rsplit("/", 1)[-1] == name)
197
+ rates = {json.dumps({field: table[key].get(field) for field in PRICE_FIELDS}) for key in others}
198
+ ordered = others if len(rates) == 1 else []
199
+ return (ordered[0], table[ordered[0]]) if ordered else None
200
+
201
+
202
+ def _price(usage: dict, family: str, model: str) -> dict:
203
+ """Return usage and its cost in USD; the cost is None for a model without a price."""
204
+
205
+ hits = round(usage["cached_input_tokens"] * CACHE_HIT_RATE) if family == "stirrup" else usage["cached_input_tokens"]
206
+ misses = usage["input_tokens"] + usage["cached_input_tokens"] - hits
207
+ try:
208
+ found = price_entry(_table(), model, family)
209
+ except OSError: # no network and no cached table: usage without cost
210
+ found = None
211
+ entry = found[1] if found else {}
212
+ rate, output = entry.get("input_cost_per_token"), entry.get("output_cost_per_token")
213
+ if rate is None or output is None:
214
+ return {"usage": usage, "cost_usd": None}
215
+ # without a cache price, cached and written tokens bill at the input rate
216
+ cached = entry["cache_read_input_token_cost"] if entry.get("cache_read_input_token_cost") is not None else rate
217
+ written = entry["cache_creation_input_token_cost"] if entry.get("cache_creation_input_token_cost") is not None else rate
218
+ cost = (misses * rate + hits * cached + usage["cache_write_tokens"] * written
219
+ + usage["output_tokens"] * output)
220
+ return {"usage": usage, "cost_usd": round(cost, 6)}
221
+
222
+
223
+ def _claude_steps(session_root: Path) -> tuple[int, int] | None:
224
+ # one `assistant` line per content block; a model call is one message id
225
+ transcripts = sorted(session_root.rglob("*.jsonl"))
226
+ if not transcripts:
227
+ return None
228
+ calls, tools = set(), 0
229
+ for transcript in transcripts:
230
+ for item in _lines(transcript):
231
+ if item.get("type") != "assistant":
232
+ continue
233
+ message = item.get("message") or {}
234
+ calls.add(message.get("id") or item.get("uuid"))
235
+ tools += sum(1 for block in message.get("content") or [] if block.get("type") == "tool_use")
236
+ return len(calls), tools
237
+
238
+
239
+ def _codex_steps(session: Path) -> tuple[int, int] | None:
240
+ # one `token_count` event per model response; tool calls are response items
241
+ transcripts = sorted(session.rglob("rollout-*.jsonl"))
242
+ if not transcripts:
243
+ return None
244
+ calls = tools = 0
245
+ for transcript in transcripts:
246
+ for item in _lines(transcript):
247
+ payload = item.get("payload") or {}
248
+ kind = payload.get("type") if isinstance(payload, dict) else None
249
+ if item.get("type") == "event_msg" and kind == "token_count":
250
+ calls += 1
251
+ if item.get("type") == "response_item" and kind in ("custom_tool_call", "function_call"):
252
+ tools += 1
253
+ return calls, tools
254
+
255
+
256
+ def _antigravity_steps(session: Path) -> tuple[int, int] | None:
257
+ # one `PLANNER_RESPONSE` step per model response, carrying its tool calls
258
+ transcripts = sorted(session.glob("*/.system_generated/logs/transcript_full.jsonl"))
259
+ if not transcripts:
260
+ return None
261
+ calls = tools = 0
262
+ for transcript in transcripts:
263
+ for item in _lines(transcript):
264
+ if item.get("type") != "PLANNER_RESPONSE":
265
+ continue
266
+ calls += 1
267
+ tools += len(item.get("tool_calls") or [])
268
+ return calls, tools
269
+
270
+
271
+ def _stirrup_steps(session: Path) -> tuple[int, int] | None:
272
+ # one `step` line per model response; `tool_calls` is cumulative within a session file
273
+ transcripts = sorted(session.rglob("[0-9]*.jsonl"))
274
+ if not transcripts:
275
+ return None
276
+ calls = tools = 0
277
+ for transcript in transcripts:
278
+ steps = [item for item in _lines(transcript) if item.get("type") == "step"]
279
+ calls += len(steps)
280
+ tools += steps[-1]["tool_calls"] if steps else 0
281
+ return calls, tools
282
+
283
+
284
+ STEP_READERS = {"codex": _codex_steps, "antigravity": _antigravity_steps, "stirrup": _stirrup_steps}
285
+
286
+
287
+ def summarize_steps(session_root: Path, family: str) -> dict | None:
288
+ """Return `steps` and `tool_calls` of one run's session, or None without a transcript."""
289
+
290
+ session = session_root / agent(family).session_dir
291
+ if family == "claude":
292
+ found = _claude_steps(session_root)
293
+ elif family == "stirrup":
294
+ found = _stirrup_steps(session_root)
295
+ elif session.is_dir():
296
+ found = STEP_READERS[family](session)
297
+ else:
298
+ return None
299
+ if found is None:
300
+ return None
301
+ return {"steps": found[0], "tool_calls": found[1]}
论文参考代码/4DCodeBench/harness/runtime/infer.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run each job's agent on its case and collect the delivered world/ and solution/.
2
+
3
+ python harness/runtime/infer.py --jobs J.toml --runtime R.toml [--dry-run]
4
+
5
+ Jobs run one after another, each in its own agent container. Each run goes to
6
+ `runs/<kind>/<case>/<agent>-<model>-<effort>/<trial>/`, replacing an existing one.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import time
20
+ from pathlib import Path
21
+
22
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
23
+
24
+ import launch
25
+ from agents import agent as get_agent
26
+ from common import (
27
+ AGENT_LOG,
28
+ CASE_VIDEO,
29
+ REPO,
30
+ RUN_LOGS,
31
+ RUN_RECORD,
32
+ RUN_SESSION,
33
+ RUN_WORKSPACE,
34
+ TASK_CONTEXT,
35
+ TASK_ENTRYPOINT,
36
+ TASK_MOUNT,
37
+ display,
38
+ docker_command,
39
+ host_path,
40
+ log,
41
+ network_args,
42
+ require_file,
43
+ resolve_case,
44
+ run_process,
45
+ sif_network_args,
46
+ )
47
+ from cost import summarize_cost, summarize_steps
48
+
49
+ sys.path.insert(0, str(REPO))
50
+
51
+ from checker.paths import (
52
+ HOME_DIR,
53
+ SOLUTION_DIR,
54
+ SOLUTION_ENTRYPOINT,
55
+ VIDEO_PATH,
56
+ WORKSPACE_DIR,
57
+ WORLD_DIR,
58
+ )
59
+
60
+ STIRRUP_DIR = Path(__file__).resolve().parents[1] / "stirrup" # bound at /opt/stirrup
61
+ PLACEHOLDER = re.compile(r"{{([a-z_]+(?:\.[a-z_]+)*)}}")
62
+
63
+
64
+ def agent_gpu_args(backend: str) -> list[str]:
65
+ """GPU flags for the agent container: `--nv` on SIF; on Docker, the pinned devices or all."""
66
+
67
+ if backend == "sif":
68
+ return ["--nv"]
69
+ if backend == "docker":
70
+ visible = os.environ.get("CUDA_VISIBLE_DEVICES")
71
+ return ["--gpus", f"device={visible}" if visible else "all"]
72
+ raise ValueError(f"unsupported runtime backend {backend!r}")
73
+
74
+
75
+ def prepare_agent_context(target: Path) -> None:
76
+ """Copy the agent context to `target` and fill the `{{paths.*}}` placeholders of TASK.md."""
77
+
78
+ shutil.copytree(TASK_CONTEXT, target)
79
+ entrypoint = target / TASK_ENTRYPOINT
80
+ template = entrypoint.read_text(encoding="utf-8")
81
+ context = {
82
+ "paths": {
83
+ "task": TASK_MOUNT,
84
+ "video": VIDEO_PATH,
85
+ "world": WORLD_DIR,
86
+ "solution": SOLUTION_DIR,
87
+ },
88
+ }
89
+
90
+ def replace(match: re.Match) -> str:
91
+ value: object = context
92
+ for key in match.group(1).split("."):
93
+ value = value[key]
94
+ if isinstance(value, (dict, list)):
95
+ raise TypeError(f"task placeholder {match.group(0)} is not scalar")
96
+ return str(value)
97
+
98
+ rendered = PLACEHOLDER.sub(replace, template)
99
+ if "{{" in rendered or "}}" in rendered:
100
+ raise ValueError("task template contains an invalid placeholder")
101
+ entrypoint.write_text(rendered, encoding="utf-8")
102
+
103
+
104
+ def agent_command(
105
+ runtime: dict,
106
+ run_dir: Path,
107
+ case_dir: Path,
108
+ workspace_source: Path,
109
+ context_source: Path,
110
+ name: str,
111
+ model: str,
112
+ effort: str,
113
+ ) -> list[str]:
114
+ """Build the container command of one agent run.
115
+
116
+ Mounts a fresh home, the empty workspace, the task (ro), the video (ro), the
117
+ session directory and the agent's credential file (ro).
118
+ """
119
+
120
+ backend = runtime["backend"]
121
+ agent_spec = runtime["agent"]
122
+ environment = agent_spec["environment"]
123
+ cli = get_agent(name)
124
+ settings = agent_spec.get(name, {})
125
+ credential_mount: list[str] = []
126
+ if "credential" in settings:
127
+ credential = require_file(host_path(runtime["auth_root"]) / settings["credential"], f"{name} credential")
128
+ credential_mount = [f"{credential}:{settings['container']}:ro"]
129
+ variables = {key: str(value) for key, value in settings.get("env", {}).items()}
130
+ task_path = TASK_MOUNT / TASK_ENTRYPOINT
131
+ inner = cli.command(
132
+ str(task_path), str(WORKSPACE_DIR), model, effort, int(agent_spec["timeout_sec"])
133
+ )
134
+ session_source = run_dir / RUN_SESSION / cli.session_dir
135
+ session_source.mkdir(parents=True, exist_ok=True)
136
+ session_target = HOME_DIR / cli.session_dir
137
+ video_source = case_dir / CASE_VIDEO
138
+ require_file(video_source, "case input video")
139
+ image = agent_spec["image"][backend]
140
+ # Both backends mount a fresh, empty home in place of the image's.
141
+ home_source = workspace_source.parent / "home"
142
+ home_source.mkdir()
143
+ # The session mount point must exist in the host home, since a bind cannot
144
+ # create its destination inside another bind.
145
+ (home_source / cli.session_dir).mkdir(parents=True, exist_ok=True)
146
+
147
+ if backend == "docker":
148
+ arguments = [
149
+ "run",
150
+ "--rm",
151
+ *agent_gpu_args(backend),
152
+ *network_args(environment["network_mode"]),
153
+ *(item for key, value in variables.items() for item in ("--env", f"{key}={value}")),
154
+ "-v",
155
+ f"{home_source}:{HOME_DIR}",
156
+ "-v",
157
+ f"{workspace_source}:{WORKSPACE_DIR}",
158
+ "-v",
159
+ f"{context_source}:{TASK_MOUNT}:ro",
160
+ "-v",
161
+ f"{video_source}:{VIDEO_PATH}:ro",
162
+ "-v",
163
+ f"{session_source}:{session_target}",
164
+ *(("-v", f"{STIRRUP_DIR}:/opt/stirrup:ro") if name == "stirrup" else ()),
165
+ *(item for mount in credential_mount for item in ("-v", mount)),
166
+ "-w",
167
+ str(WORKSPACE_DIR),
168
+ image,
169
+ *inner,
170
+ ]
171
+ return docker_command(runtime, arguments)
172
+
173
+ if backend == "sif":
174
+ pack_env: list[str] = []
175
+ pack_bind: list[str] = []
176
+ # NVIDIA's EGL vendor file, so glvnd dispatches EEVEE to the library `--nv` binds.
177
+ egl_icd = Path(__file__).resolve().parents[1] / "apptainer" / "10_nvidia.json"
178
+ if egl_icd.is_file():
179
+ pack_bind += ["-B", f"{egl_icd}:/usr/share/glvnd/egl_vendor.d/10_nvidia.json:ro"]
180
+ # nvidia-smi is bound directly: `--nv` places it via an underlay that fails with many binds
181
+ if Path("/usr/bin/nvidia-smi").is_file():
182
+ pack_bind += ["-B", "/usr/bin/nvidia-smi:/usr/bin/nvidia-smi:ro"]
183
+ # /tmp and /var/tmp live in this run's staging directory.
184
+ scratch_root = workspace_source.parent / "scratch"
185
+ for sub, dest in (("tmp", "/tmp"), ("vartmp", "/var/tmp")):
186
+ (scratch_root / sub).mkdir(parents=True, exist_ok=True)
187
+ pack_bind += ["-B", f"{scratch_root / sub}:{dest}"]
188
+ # `--cleanenv` drops the GPU pin, so it is passed explicitly.
189
+ if "CUDA_VISIBLE_DEVICES" in os.environ:
190
+ pack_env += ["--env", f"CUDA_VISIBLE_DEVICES={os.environ['CUDA_VISIBLE_DEVICES']}"]
191
+ if name == "stirrup":
192
+ pack_bind += ["-B", f"{STIRRUP_DIR}:/opt/stirrup:ro"]
193
+ return [
194
+ runtime["sif"]["executable"],
195
+ "exec",
196
+ *agent_gpu_args(backend),
197
+ *sif_network_args(environment["network_mode"]),
198
+ *(item for key, value in variables.items() for item in ("--env", f"{key}={value}")),
199
+ *pack_env,
200
+ "--containall",
201
+ "--cleanenv",
202
+ # own PID namespace, so an agent's `pkill` cannot reach other processes on the node
203
+ "--pid",
204
+ "--home",
205
+ f"{home_source}:{HOME_DIR}",
206
+ "--writable-tmpfs",
207
+ "--pwd",
208
+ str(WORKSPACE_DIR),
209
+ "-B",
210
+ f"{workspace_source}:{WORKSPACE_DIR}",
211
+ "-B",
212
+ f"{context_source}:{TASK_MOUNT}:ro",
213
+ "-B",
214
+ f"{video_source}:{VIDEO_PATH}:ro",
215
+ "-B",
216
+ f"{session_source}:{session_target}",
217
+ *pack_bind,
218
+ *(item for mount in credential_mount for item in ("-B", mount)),
219
+ image,
220
+ *inner,
221
+ ]
222
+
223
+ raise ValueError(f"unsupported runtime backend {backend!r}")
224
+
225
+
226
+ def collect_delivery(source: Path, target: Path, dropped: list[str] | None = None) -> list[str]:
227
+ """Copy world/ and solution/ from `source` to `target`; return the names copied.
228
+
229
+ Symbolic links are neither followed nor copied, since they would resolve on the
230
+ host; each one's workspace path is appended to `dropped`.
231
+ """
232
+
233
+ dropped = [] if dropped is None else dropped
234
+
235
+ def skip_links(directory: str, entries: list[str]) -> list[str]:
236
+ links = [entry for entry in entries if os.path.islink(os.path.join(directory, entry))]
237
+ dropped.extend(os.path.relpath(os.path.join(directory, entry), source) for entry in links)
238
+ return links
239
+
240
+ names = []
241
+ for name in (WORLD_DIR.name, SOLUTION_DIR.name):
242
+ directory = source / name
243
+ if directory.is_symlink():
244
+ dropped.append(name)
245
+ continue
246
+ if directory.is_dir():
247
+ target.mkdir(parents=True, exist_ok=True)
248
+ shutil.copytree(directory, target / name, symlinks=True, ignore=skip_links)
249
+ names.append(name)
250
+ return names
251
+
252
+
253
+ def ownership_release_command(runtime: dict, workspace: Path, session: Path) -> list[str] | None:
254
+ """Return the Docker command that chowns the workspace and session to the host user.
255
+
256
+ None on the SIF backend, whose files already belong to the host user.
257
+ """
258
+
259
+ if runtime["backend"] == "sif":
260
+ return None
261
+ if runtime["backend"] != "docker":
262
+ raise ValueError(f"unsupported runtime backend {runtime['backend']!r}")
263
+ return docker_command(
264
+ runtime,
265
+ [
266
+ "run",
267
+ "--rm",
268
+ "--network",
269
+ "none",
270
+ "-v",
271
+ f"{workspace}:{WORKSPACE_DIR}",
272
+ "-v",
273
+ f"{session}:/session",
274
+ runtime["agent"]["image"]["docker"],
275
+ "chown",
276
+ "-R",
277
+ f"{os.getuid()}:{os.getgid()}",
278
+ str(WORKSPACE_DIR),
279
+ "/session",
280
+ ],
281
+ )
282
+
283
+
284
+ def one_infer(job: dict, runtime: dict, dry_run: bool) -> dict:
285
+ """Run one job, write its run.json, and return the record."""
286
+
287
+ case, name = job["case"], job["agent"]
288
+ model, effort = job["model"], job["effort"]
289
+ trial = int(job["trial"])
290
+ cases_root = host_path(runtime["cases_root"])
291
+ case = resolve_case(cases_root, case) # `<kind>/<case>`
292
+ case_dir = cases_root / case
293
+ cli = get_agent(name)
294
+ if cli.efforts and effort not in cli.efforts: # empty: any value
295
+ raise ValueError(f"{name} has no effort {effort!r}; it takes {list(cli.efforts)}")
296
+
297
+ final_dir = host_path(runtime["runs_root"]) / case / f"{name}-{model}-{effort}" / str(trial)
298
+
299
+ with tempfile.TemporaryDirectory(prefix="4dcb-run-") as temporary:
300
+ staging = Path(temporary)
301
+ if dry_run:
302
+ run_dir = staging / "run" # a dry run leaves runs/ untouched
303
+ else:
304
+ run_dir = final_dir
305
+ if run_dir.exists():
306
+ shutil.rmtree(run_dir)
307
+ (run_dir / RUN_LOGS).mkdir(parents=True, exist_ok=True)
308
+ workspace_source = staging / "workspace"
309
+ context_source = staging / "task"
310
+ workspace_source.mkdir()
311
+ prepare_agent_context(context_source)
312
+ agent_cmd = agent_command(
313
+ runtime,
314
+ run_dir,
315
+ case_dir,
316
+ workspace_source,
317
+ context_source,
318
+ name,
319
+ model,
320
+ effort,
321
+ )
322
+ record = {
323
+ "case": case,
324
+ "agent": name,
325
+ "model": model,
326
+ "effort": effort,
327
+ "trial": trial,
328
+ "backend": runtime["backend"],
329
+ "session": RUN_SESSION,
330
+ "agent_command": display(agent_cmd),
331
+ }
332
+ if dry_run:
333
+ log("$", record["agent_command"])
334
+ log("dry run, nothing executed")
335
+ return record
336
+
337
+ try:
338
+ started = time.time()
339
+ record["agent_exit"] = run_process(
340
+ agent_cmd,
341
+ run_dir / RUN_LOGS / AGENT_LOG,
342
+ int(runtime["agent"]["timeout_sec"]),
343
+ )
344
+ record["agent_seconds"] = round(time.time() - started, 1)
345
+ try:
346
+ cost = summarize_cost(run_dir / RUN_LOGS / AGENT_LOG, name, model)
347
+ if cost is not None:
348
+ record.update(cost)
349
+ except Exception as exc: # a parse failure is recorded, not raised
350
+ record["cost_error"] = str(exc)[:200]
351
+ try:
352
+ steps = summarize_steps(run_dir / RUN_SESSION, name)
353
+ if steps is not None:
354
+ record.update(steps)
355
+ except Exception as exc:
356
+ record["steps_error"] = str(exc)[:200]
357
+ collection = run_dir / RUN_WORKSPACE
358
+ dropped: list[str] = []
359
+ record["artifacts"] = collect_delivery(workspace_source, collection, dropped)
360
+ if dropped:
361
+ record["symlinks_dropped"] = dropped
362
+ log("symlinks left out of the delivery:", ", ".join(dropped))
363
+ finally:
364
+ release = ownership_release_command(runtime, workspace_source, run_dir / RUN_SESSION)
365
+ if release is not None:
366
+ subprocess.run(release, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, check=True)
367
+
368
+ world = collection / WORLD_DIR.name
369
+ solution = collection / SOLUTION_DIR.name
370
+ entrypoint = solution / SOLUTION_ENTRYPOINT.name
371
+ record["delivered"] = world.is_dir() and solution.is_dir() and entrypoint.is_file()
372
+ if record["delivered"]:
373
+ log("world and solution delivered")
374
+ else:
375
+ log("incomplete delivery")
376
+
377
+ (run_dir / RUN_RECORD).write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8")
378
+ log(json.dumps({key: value for key, value in record.items() if not key.endswith("_command")}, sort_keys=True))
379
+
380
+ return record
381
+
382
+
383
+ def succeeded(record: dict) -> bool:
384
+ return record.get("agent_exit") == 0 and bool(record.get("delivered"))
385
+
386
+
387
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
388
+ parser = argparse.ArgumentParser(description="Run a list of inference jobs.")
389
+ parser.add_argument("--jobs", type=Path, required=True, help="the job list")
390
+ parser.add_argument("--runtime", type=Path, required=True, help="the deployment configuration")
391
+ parser.add_argument("--dry-run", action="store_true")
392
+ return parser.parse_args(argv)
393
+
394
+
395
+ def main(argv: list[str] | None = None) -> int:
396
+ args = parse_args(argv)
397
+ return launch.execute("infer", args.jobs, args.runtime, args.dry_run)
398
+
399
+
400
+ if __name__ == "__main__":
401
+ raise SystemExit(main())
论文参考代码/4DCodeBench/harness/runtime/jobs.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load a jobs file and expand it into one entry per trial.
2
+
3
+ A jobs file holds `trials` and `[[job]]` entries of case, agent, model and effort.
4
+ Inference runs the expanded list one entry at a time; scoring shards it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ import tomllib
12
+
13
+ KEYS = ("case", "agent", "model", "effort")
14
+
15
+
16
+ def load_jobs(path: Path) -> list[dict]:
17
+ """Return one dict per trial; a job with its own `trial` key yields that trial alone."""
18
+
19
+ document = tomllib.loads(path.read_text(encoding="utf-8"))
20
+ trials = int(document.get("trials", 1))
21
+ if trials < 1:
22
+ raise ValueError(f"{path}: trials must be at least 1")
23
+ entries = document.get("job", [])
24
+ if not entries:
25
+ raise ValueError(f"{path}: contains no [[job]] entries")
26
+
27
+ jobs = []
28
+ for entry in entries:
29
+ missing = [key for key in KEYS if key not in entry]
30
+ if missing:
31
+ raise ValueError(f"{path}: a job is missing {missing}")
32
+ unknown = sorted(set(entry) - set(KEYS) - {"trial"})
33
+ if unknown:
34
+ raise ValueError(f"{path}: a job carries unknown keys {unknown}")
35
+ if "trial" in entry:
36
+ jobs.append({key: entry[key] for key in KEYS} | {"trial": int(entry["trial"])})
37
+ continue
38
+ for trial in range(1, trials + 1):
39
+ jobs.append({key: entry[key] for key in KEYS} | {"trial": trial})
40
+
41
+ keys = [tuple(job[key] for key in (*KEYS, "trial")) for job in jobs]
42
+ if len(keys) != len(set(keys)):
43
+ raise ValueError(f"{path}: duplicate case/agent/model/effort/trial entries")
44
+ return jobs
45
+
46
+
47
+ def label(item: dict) -> str:
48
+ """Return a flat, filesystem-safe name for one work item: a job or a shard."""
49
+
50
+ if "shard" in item:
51
+ return Path(item["shard"]).stem
52
+ case = str(item["case"]).replace("/", "-")
53
+ return f"{case}-{item['agent']}-{item['model']}-{item['effort']}-{item['trial']}"
论文参考代码/4DCodeBench/harness/runtime/launch.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run a job list through `infer` or the scoring stages on this machine.
2
+
3
+ `infer.py` calls `execute` and `score.py` calls `stages`. `infer` runs its jobs one
4
+ after another in this process. A scoring stage splits the list into shards and runs
5
+ them in parallel, one child process (`launch.py --index ...`) per visible GPU.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import queue
14
+ import subprocess
15
+ import sys
16
+ import threading
17
+ from pathlib import Path
18
+
19
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
20
+
21
+ from common import host_path, log, read_toml
22
+ from jobs import label, load_jobs
23
+
24
+ ACTIONS = ("infer", "prepare", "score", "viz")
25
+ STAGES = ("prepare", "score", "viz") # handled by score.py; their items are shards
26
+
27
+
28
+ def action_module(action: str):
29
+ """Import and return the module of one action: `infer` or `score`.
30
+
31
+ Imported lazily, since both modules import this one.
32
+ """
33
+
34
+ if action not in ACTIONS:
35
+ raise ValueError(f"unknown action {action!r}; known: {list(ACTIONS)}")
36
+ return __import__("score" if action in STAGES else action)
37
+
38
+
39
+ def one(action: str, item: dict, runtime: dict, dry_run: bool) -> dict:
40
+ """Run one item: one agent job, or one shard of one scoring stage."""
41
+
42
+ module = action_module(action)
43
+ if action in STAGES:
44
+ return module.one_shard(action, item, runtime, dry_run)
45
+ return module.one_infer(item, runtime, dry_run)
46
+
47
+
48
+ def gpus_available() -> list[str]:
49
+ """Return the devices in `CUDA_VISIBLE_DEVICES`, one per worker slot; `[""]` when unset."""
50
+
51
+ selection = os.environ.get("CUDA_VISIBLE_DEVICES", "")
52
+ return [item.strip() for item in selection.split(",") if item.strip()] or [""]
53
+
54
+
55
+ def sequential(action: str, items: list[dict], runtime: dict, dry_run: bool) -> int:
56
+ """Run `items` one after another in this process and print a summary."""
57
+
58
+ records = []
59
+ for item in items:
60
+ log(f"{action} {label(item)}")
61
+ records.append(one(action, item, runtime, dry_run))
62
+ keys = ("case", "agent", "model", "effort", "trial", "backend", "delivered",
63
+ "stage", "shard", "worlds", "exit")
64
+ summary = [{key: record[key] for key in keys if key in record} for record in records]
65
+ print(json.dumps(summary, indent=2, sort_keys=True))
66
+ if dry_run:
67
+ return 0
68
+ return int(not all(action_module(action).succeeded(record) for record in records))
69
+
70
+
71
+ def execute(action: str, jobs_path: Path, runtime_path: Path, dry_run: bool) -> int:
72
+ """Run one action over the job list."""
73
+
74
+ return stages([action], jobs_path, runtime_path, dry_run)
75
+
76
+
77
+ def stages(actions: list[str], jobs_path: Path, runtime_path: Path, dry_run: bool,
78
+ options: dict[str, dict] | None = None) -> int:
79
+ """Run the job list through each action in turn with `options[action]`.
80
+
81
+ A scoring stage writes its shard list to `<action>-work.json` and runs it with `batch`.
82
+ """
83
+
84
+ loaded = load_jobs(host_path(str(jobs_path)))
85
+ runtime = read_toml(host_path(str(runtime_path)))
86
+ status = 0
87
+ for action in actions:
88
+ extra = (options or {}).get(action, {})
89
+ if action not in STAGES:
90
+ status |= sequential(action, [job | extra for job in loaded], runtime, dry_run)
91
+ continue
92
+ items = action_module(action).shards(action, loaded, runtime, extra, dry_run)
93
+ if dry_run:
94
+ status |= sequential(action, items, runtime, dry_run)
95
+ continue
96
+ manifest = Path(items[0]["shard"]).parent / f"{action}-work.json"
97
+ manifest.write_text(json.dumps(items, indent=2) + "\n", encoding="utf-8")
98
+ status |= batch(action, manifest, host_path(str(runtime_path)), manifest.parent)
99
+ return status
100
+
101
+
102
+ def worker(action: str, manifest_path: Path, runtime_path: Path, index: int, gpu: str) -> int:
103
+ """Run item `index` of the manifest on device `gpu`; an empty `gpu` pins nothing."""
104
+
105
+ if gpu:
106
+ os.environ["CUDA_VISIBLE_DEVICES"] = gpu
107
+ job = json.loads(manifest_path.read_text(encoding="utf-8"))[index]
108
+ record = one(action, job, read_toml(runtime_path), False)
109
+ return 0 if action_module(action).succeeded(record) else 1
110
+
111
+
112
+ def batch(action: str, manifest_path: Path, runtime_path: Path, log_dir: Path) -> int:
113
+ """Run every item of the manifest, one child process per visible device at a time.
114
+
115
+ Each child's output goes to `<log_dir>/<action>-<index>-<label>.out`. Returns 1 if any failed.
116
+ """
117
+
118
+ entries = json.loads(manifest_path.read_text(encoding="utf-8"))
119
+ devices = gpus_available()
120
+ todo: queue.SimpleQueue[int] = queue.SimpleQueue()
121
+ for index in range(len(entries)):
122
+ todo.put(index)
123
+ failures: list[int] = []
124
+ lock = threading.Lock()
125
+
126
+ def slot(gpu: str) -> None:
127
+ while True:
128
+ try:
129
+ index = todo.get_nowait()
130
+ except queue.Empty:
131
+ return
132
+ name = label(entries[index])
133
+ path = log_dir / f"{action}-{index}-{name}.out"
134
+ with open(path, "w", encoding="utf-8") as sink:
135
+ result = subprocess.run(
136
+ [sys.executable, __file__, "--action", action,
137
+ "--manifest", str(manifest_path), "--runtime", str(runtime_path),
138
+ "--index", str(index), "--gpu", gpu],
139
+ stdout=sink, stderr=subprocess.STDOUT, check=False,
140
+ )
141
+ with lock:
142
+ if result.returncode != 0:
143
+ failures.append(index)
144
+ print(f"[batch] gpu {gpu or 'all'} {action} {index} {name}: "
145
+ f"{'ok' if result.returncode == 0 else 'FAILED'} ({path.name})", flush=True)
146
+
147
+ threads = [threading.Thread(target=slot, args=(gpu,)) for gpu in devices[:len(entries)]]
148
+ for thread in threads:
149
+ thread.start()
150
+ for thread in threads:
151
+ thread.join()
152
+ print(f"[batch] {len(entries) - len(failures)}/{len(entries)} ok"
153
+ + (f", failed indices {sorted(failures)}" if failures else ""), flush=True)
154
+ return 1 if failures else 0
155
+
156
+
157
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
158
+ parser = argparse.ArgumentParser(description="Run one item of a work list (used by `batch`).")
159
+ parser.add_argument("--action", choices=ACTIONS, required=True)
160
+ parser.add_argument("--manifest", type=Path, required=True)
161
+ parser.add_argument("--runtime", type=Path, required=True)
162
+ parser.add_argument("--index", type=int, required=True)
163
+ parser.add_argument("--gpu", required=True)
164
+ return parser.parse_args(argv)
165
+
166
+
167
+ if __name__ == "__main__":
168
+ args = parse_args()
169
+ raise SystemExit(worker(args.action, args.manifest, args.runtime, args.index, args.gpu))
论文参考代码/4DCodeBench/harness/runtime/score.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the scoring stages over the runs a job list names.
2
+
3
+ python harness/runtime/score.py --jobs J.toml --runtime R.toml [--stage prepare,score,viz]
4
+
5
+ `--stage` selects stages, which run in this order (default: `score`):
6
+
7
+ prepare `python -m scorer.prepare` writes each case's `estimates/` from its
8
+ `reference.mp4`; one entry per case. `--only` limits the groups.
9
+ score `python -m scorer` writes each run's `results/`: `reward.json`,
10
+ `reward.detail.json` and one `.npz` per metric. `--type` limits the metrics.
11
+ viz `python -m visualizer` renders each run's `viz/` videos. `--media` limits them.
12
+
13
+ `--sanity` adds each synthetic case's reference world to score and viz, written to
14
+ `data/<kind>/<case>/sanity/`.
15
+
16
+ Entries are sharded round-robin, one shard per device in `CUDA_VISIBLE_DEVICES`
17
+ (one when unset), and each shard runs in one scorer container. The container mounts
18
+ `/cases` (ro), `/data` (rw), `/runs` (rw, not for prepare), `/checkpoints` (ro) and
19
+ its shard at `/manifest.json`. Shard manifests and container logs go under
20
+ `<runs_root>/manifests/`. `[scorer] timeout_sec` bounds one container.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import json
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
31
+
32
+ import launch
33
+ from common import (
34
+ REPO,
35
+ RUN_WORKSPACE,
36
+ container_command,
37
+ display,
38
+ host_path,
39
+ log,
40
+ resolve_case,
41
+ run_process,
42
+ )
43
+
44
+ sys.path.insert(0, str(REPO))
45
+
46
+ from checker.paths import WORLD_DIR
47
+ from config.estimates import SANITY_DIRNAME
48
+ from scorer.paths import (
49
+ CASES_ROOT,
50
+ CHECKPOINTS_DIR,
51
+ DATA_ROOT,
52
+ MANIFEST_PATH,
53
+ RUNS_ROOT,
54
+ WORLD_DIRNAME,
55
+ )
56
+
57
+ STAGES = launch.STAGES
58
+ MANIFEST_DIRNAME = "manifests" # shard manifests and container logs
59
+ COMMANDS = {
60
+ "prepare": ("python", "-m", "scorer.prepare"),
61
+ "score": ("python", "-m", "scorer"),
62
+ "viz": ("python", "-m", "visualizer"),
63
+ }
64
+ # per stage: the flag that narrows its work, and the option that supplies it
65
+ OPTIONS = {"prepare": ("--only", "only"), "score": ("--type", "type"), "viz": ("--media", "media")}
66
+
67
+
68
+ def stage_command(stage: str, runtime: dict, manifest: Path, flags: list[str]) -> list[str]:
69
+ """Build the container command of one stage over one shard.
70
+
71
+ Prepare gets no `/runs` mount. `/data` is writable, since prepare and sanity entries
72
+ write there.
73
+ """
74
+
75
+ scorer = runtime["scorer"]
76
+ store = scorer.get("checkpoints")
77
+ if stage == "score":
78
+ flags = [*flags, "--task-timeout", str(scorer.get("task_timeout_sec", 1800)),
79
+ "--prepare-timeout", str(scorer.get("task_prepare_timeout_sec", 600))]
80
+ for name, seconds in scorer.get("task_timeouts", {}).items():
81
+ flags.extend(["--timeout", f"{name}={seconds}"])
82
+ runs = host_path(runtime["runs_root"]).resolve() if stage != "prepare" else None
83
+ return container_command(runtime, scorer["environment"], scorer["image"][runtime["backend"]], [
84
+ (host_path(runtime["cases_root"]).resolve(), CASES_ROOT, "ro"),
85
+ (host_path(runtime["data_root"]).resolve(), DATA_ROOT, "rw"),
86
+ (runs, RUNS_ROOT, "rw"),
87
+ (host_path(store).resolve() if store else None, CHECKPOINTS_DIR, "ro"),
88
+ (manifest.resolve(), MANIFEST_PATH, "ro"),
89
+ ], [*COMMANDS[stage], "--manifest", str(MANIFEST_PATH), *flags])
90
+
91
+
92
+ def entries(stage: str, jobs: list[dict], runtime: dict, sanity: bool) -> list[dict]:
93
+ """Return the manifest entries of a job list: one per case for prepare, else one per world.
94
+
95
+ Each world entry names its `case`, its `world` and the `out` directory for its outputs.
96
+ """
97
+
98
+ cases_root = host_path(runtime["cases_root"])
99
+ named = [job | {"case": resolve_case(cases_root, job["case"])} for job in jobs]
100
+ cases = list(dict.fromkeys(job["case"] for job in named))
101
+ if stage == "prepare":
102
+ return [{"case": case} for case in cases]
103
+
104
+ found = []
105
+ for job in named:
106
+ run = f"runs/{job['case']}/{job['agent']}-{job['model']}-{job['effort']}/{int(job['trial'])}"
107
+ found.append({"case": job["case"], "world": f"{run}/{RUN_WORKSPACE}/{WORLD_DIR.name}",
108
+ "out": run})
109
+ if sanity:
110
+ data_root = host_path(runtime["data_root"])
111
+ found += [{"case": case, "world": f"data/{case}/{WORLD_DIRNAME}",
112
+ "out": f"data/{case}/{SANITY_DIRNAME}"}
113
+ for case in cases if (data_root / case / WORLD_DIRNAME).is_dir()]
114
+ return found
115
+
116
+
117
+ def shards(stage: str, jobs: list[dict], runtime: dict, options: dict, dry_run: bool) -> list[dict]:
118
+ """Split the entries round-robin into one shard per device and write each manifest.
119
+
120
+ Returns one item per non-empty shard: its manifest path, entry count and stage flags.
121
+ """
122
+
123
+ count = len(launch.gpus_available())
124
+ flag, option = OPTIONS[stage]
125
+ flags = [flag, options[option]] if options.get(option) else []
126
+ directory = host_path(runtime["runs_root"]) / MANIFEST_DIRNAME
127
+ if not dry_run:
128
+ directory.mkdir(parents=True, exist_ok=True)
129
+ listed = entries(stage, jobs, runtime, bool(options.get("sanity")))
130
+ made = []
131
+ for index in range(max(count, 1)):
132
+ part = listed[index::count]
133
+ if not part:
134
+ continue
135
+ manifest = directory / f"{stage}-{index}.json"
136
+ if not dry_run:
137
+ manifest.write_text(json.dumps(part, indent=2) + "\n", encoding="utf-8")
138
+ made.append({"stage": stage, "shard": str(manifest), "worlds": len(part),
139
+ "flags": flags})
140
+ return made
141
+
142
+
143
+ def one_shard(stage: str, item: dict, runtime: dict, dry_run: bool) -> dict:
144
+ """Run one shard of one stage and return its record, with `exit` unless a dry run."""
145
+
146
+ scorer = runtime["scorer"]
147
+ manifest = Path(item["shard"])
148
+ command = stage_command(stage, runtime, manifest, item["flags"])
149
+ record = {"stage": stage, "shard": manifest.name, "worlds": item["worlds"],
150
+ "command": display(command)}
151
+
152
+ if dry_run:
153
+ log("$", display(command))
154
+ log("dry run, nothing executed")
155
+ return record
156
+
157
+ record["exit"] = run_process(command, manifest.with_suffix(".log"),
158
+ int(scorer.get(f"{stage}_timeout_sec", scorer["timeout_sec"])))
159
+ log(json.dumps({key: value for key, value in record.items() if key != "command"},
160
+ sort_keys=True))
161
+ return record
162
+
163
+
164
+ def succeeded(record: dict) -> bool:
165
+ return record.get("exit") == 0
166
+
167
+
168
+ def parse_stages(value: str) -> list[str]:
169
+ """Return the comma-separated stages in their fixed run order; raise on an unknown one."""
170
+
171
+ wanted = [name for name in value.split(",") if name]
172
+ unknown = sorted(set(wanted) - set(STAGES))
173
+ if unknown or not wanted:
174
+ raise ValueError(f"--stage names {list(STAGES)}, not {value!r}")
175
+ return [name for name in STAGES if name in wanted]
176
+
177
+
178
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
179
+ parser = argparse.ArgumentParser(description="Score a list of delivered runs.")
180
+ parser.add_argument("--jobs", type=Path, required=True, help="the job list")
181
+ parser.add_argument("--runtime", type=Path, required=True, help="the deployment configuration")
182
+ parser.add_argument("--stage", default="score",
183
+ help=f"the stages to run, comma-separated, out of {list(STAGES)}; "
184
+ "always in that order, and only scoring by default")
185
+ parser.add_argument("--type", default=None,
186
+ help="metric types to rescore on their own, comma-separated "
187
+ "(e.g. trajectory); the rest of results/ is left as it is")
188
+ parser.add_argument("--media", default=None,
189
+ help="media groups the viz stage renders, comma-separated "
190
+ "(e.g. flow,tracks); everything by default")
191
+ parser.add_argument("--only", default=None,
192
+ help="the estimate groups the prepare stage computes, comma-separated "
193
+ "(e.g. semantic,depth); all of them by default")
194
+ parser.add_argument("--sanity", action="store_true",
195
+ help="score and render each case's own reference world too, into "
196
+ "data/<kind>/<case>/sanity/")
197
+ parser.add_argument("--dry-run", action="store_true")
198
+ return parser.parse_args(argv)
199
+
200
+
201
+ def main(argv: list[str] | None = None) -> int:
202
+ args = parse_args(argv)
203
+ options = {"prepare": {"only": args.only},
204
+ "score": {"type": args.type, "sanity": args.sanity},
205
+ "viz": {"media": args.media, "sanity": args.sanity}}
206
+ return launch.stages(parse_stages(args.stage), args.jobs, args.runtime, args.dry_run, options)
207
+
208
+
209
+ if __name__ == "__main__":
210
+ raise SystemExit(main())
论文参考代码/4DCodeBench/harness/runtime/templates/jobs.example.toml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The job list: which case each agent runs, and how many trials of each.
2
+ # Every [[job]] is expanded to `trials` entries, one per trial number.
3
+
4
+ trials = 1
5
+
6
+ [[job]]
7
+ case = "synthetic/B_01" # bare case name or <kind>/<case>
8
+ agent = "claude" # claude, codex, antigravity or stirrup
9
+ model = "<MODEL>"
10
+ effort = "medium" # claude/codex: low..max; antigravity: low..high; stirrup: forwarded to the endpoint as-is
11
+
12
+ [[job]]
13
+ case = "real/abc_130k_01_dual_arm_robotic"
14
+ agent = "codex"
15
+ model = "<MODEL>"
16
+ effort = "high"
论文参考代码/4DCodeBench/harness/runtime/templates/runtime.example.toml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deployment configuration: where things live on this machine and how containers
2
+ # are started. Copy it, fill in the placeholders, and pass it as `--runtime`.
3
+ # Relative paths resolve against the repository root.
4
+
5
+ backend = "docker" # "docker" or "sif" (SingularityCE / Apptainer)
6
+ cases_root = "cases" # <kind>/<case>/reference.mp4
7
+ data_root = "data" # <kind>/<case>/world, annotation/ and estimates/: the scorer's hidden inputs
8
+ runs_root = "runs"
9
+ auth_root = ".auth" # the CLIs' credential files
10
+
11
+ [agent]
12
+ timeout_sec = 21600 # one run's wall-clock budget
13
+
14
+ [agent.image]
15
+ docker = "4dcb/agent:dev"
16
+ sif = "<IMAGE_ROOT>/4dcb-agent-dev.sif"
17
+
18
+ [agent.environment]
19
+ network_mode = "default" # the CLI must reach its model provider
20
+
21
+ # One table per agent. `credential` names a file under auth_root and `container`
22
+ # the path it is mounted at; both are optional, and given together. `[agent.X.env]`
23
+ # adds environment variables for that CLI alone.
24
+ [agent.claude]
25
+ credential = "claude.json"
26
+ container = "/root/.claude/.credentials.json"
27
+
28
+ [agent.claude.env]
29
+ BASH_MAX_TIMEOUT_MS = "21600000" # 6 h, the run's own budget: no shorter limit on one command
30
+
31
+ [agent.codex]
32
+ credential = "gpt.json"
33
+ container = "/root/.codex/auth.json"
34
+
35
+ [agent.antigravity]
36
+ credential = "gemini.json"
37
+ container = "/root/.gemini/antigravity-cli/antigravity-oauth-token"
38
+
39
+ # The `stirrup` agent (harness/stirrup/runner.py) drives any OpenAI-compatible
40
+ # Chat Completions endpoint and needs no credential file, only its address.
41
+ [agent.stirrup.env]
42
+ OPENAI_BASE_URL = "http://127.0.0.1:8000/v1"
43
+ OPENAI_API_KEY = "local"
44
+
45
+ [scorer]
46
+ timeout_sec = 3600 # one container, which walks a whole shard
47
+ # prepare_timeout_sec = 3600 # the prepare stage's own limit; timeout_sec without it
48
+ # viz_timeout_sec = 3600 # the viz stage's own limit; timeout_sec without it
49
+ # task_timeout_sec = 1800 # one metric or one world's model inference
50
+ # task_prepare_timeout_sec = 600 # one geometry preparation or model load
51
+ checkpoints = "checkpoints" # model weights (docs/checkpoints.md), mounted read-only
52
+
53
+ [scorer.image]
54
+ docker = "4dcb/scorer:dev"
55
+ sif = "<IMAGE_ROOT>/4dcb-scorer-dev.sif"
56
+
57
+ [scorer.environment]
58
+ network_mode = "no-network"
59
+ cpus = 8
60
+ memory_mb = 32768
61
+ gpus = 1
62
+
63
+ [docker]
64
+ executable = "docker"
65
+
66
+ [sif]
67
+ executable = "singularity" # or "apptainer"
论文参考代码/4DCodeBench/harness/scorer/Dockerfile ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stage 1 builds OpenVDB and the `scorer-vdb` helper. The runtime stage is the PyTorch
2
+ # CUDA devel image, whose toolkit the CUDA extensions below compile against.
3
+ FROM ubuntu:24.04 AS vdb
4
+ RUN apt-get update && apt-get install -y --no-install-recommends \
5
+ ca-certificates git cmake make g++ libtbb-dev libblosc-dev libboost-iostreams-dev zlib1g-dev
6
+ RUN git clone --depth 1 --branch v13.0.0 https://github.com/AcademySoftwareFoundation/openvdb.git /src && \
7
+ cmake -S /src -B /build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/opt/openvdb \
8
+ -DOPENVDB_BUILD_BINARIES=OFF -DOPENVDB_CORE_STATIC=OFF -DUSE_EXPLICIT_INSTANTIATION=OFF && \
9
+ cmake --build /build -j4 && cmake --install /build
10
+ COPY scorer/vdb.cpp /vdb.cpp
11
+ RUN g++ -O2 -std=c++17 /vdb.cpp -I/opt/openvdb/include -L/opt/openvdb/lib \
12
+ -Wl,-rpath,/opt/openvdb/lib -lopenvdb -ltbb -o /opt/openvdb/scorer-vdb
13
+
14
+ FROM pytorch/pytorch:2.13.0-cuda13.0-cudnn9-devel
15
+
16
+ ENV DEBIAN_FRONTEND=noninteractive \
17
+ PYTHONUNBUFFERED=1 \
18
+ PATH="/usr/local/bin:$PATH" \
19
+ NVIDIA_VISIBLE_DEVICES=all \
20
+ NVIDIA_DRIVER_CAPABILITIES=compute,utility \
21
+ PIP_BREAK_SYSTEM_PACKAGES=1 \
22
+ HF_HUB_OFFLINE=1 \
23
+ TRANSFORMERS_OFFLINE=1 \
24
+ TORCH_CUDA_ARCH_LIST="7.5;8.0;8.6;8.9;9.0;10.0;12.0+PTX"
25
+
26
+ # runtime libraries for the metrics and video decoding
27
+ RUN apt-get update && apt-get install -y --no-install-recommends \
28
+ ffmpeg \
29
+ libgl1 \
30
+ libglx-mesa0 \
31
+ libopengl0 \
32
+ libgomp1 \
33
+ libspatialindex-dev \
34
+ ca-certificates \
35
+ git \
36
+ && rm -rf /var/lib/apt/lists/*
37
+
38
+ # Python packages, shared with the conda environment (environment.yml).
39
+ COPY harness/scorer/requirements*.txt /tmp/requirements/
40
+ RUN pip install --no-cache-dir -r /tmp/requirements/requirements.txt && \
41
+ FORCE_CUDA=1 pip install --no-cache-dir --no-build-isolation -r /tmp/requirements/requirements-cuda.txt && \
42
+ pip install --no-cache-dir --no-deps -r /tmp/requirements/requirements-nodeps.txt
43
+
44
+ RUN apt-get update && apt-get install -y --no-install-recommends \
45
+ libtbb12 libblosc1 libboost-iostreams1.83.0 && rm -rf /var/lib/apt/lists/*
46
+ COPY --from=vdb /opt/openvdb /opt/openvdb
47
+ RUN ln -s /opt/openvdb/scorer-vdb /usr/local/bin/scorer-vdb
48
+
49
+ # The stages of `harness/runtime/score.py`: `scorer.prepare`, `scorer` and `visualizer`.
50
+ COPY config /opt/4dcb/config
51
+ COPY scorer /opt/4dcb/scorer
52
+ COPY visualizer /opt/4dcb/visualizer
53
+ ENV PYTHONPATH=/opt/4dcb
54
+ # Model-loader and library caches go to /tmp; the home directory is read-only under
55
+ # `--containall --no-home`.
56
+ ENV HF_HOME=/tmp/hf-home \
57
+ XDG_CACHE_HOME=/tmp/xdg-cache \
58
+ TORCH_HOME=/tmp/torch-home \
59
+ MPLCONFIGDIR=/tmp/mpl \
60
+ TRITON_CACHE_DIR=/tmp/triton \
61
+ FLEX_GEMM_AUTOTUNE_CACHE_PATH=/tmp/flex_gemm/autotune_cache.json
62
+
63
+ WORKDIR /workspace
64
+
65
+ ENTRYPOINT ["python", "-m", "scorer"]
论文参考代码/4DCodeBench/harness/scorer/requirements-cuda.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Packages built from source against the installed torch: install with --no-build-isolation.
2
+ # nvdiffrast, pytorch3d and flex-gemm compile CUDA extensions (pytorch3d needs FORCE_CUDA=1).
3
+ nvdiffrast @ git+https://github.com/NVlabs/nvdiffrast@253ac4fcea7de5f396371124af597e6cc957bfae
4
+ pytorch3d @ git+https://github.com/facebookresearch/pytorch3d.git@978cd99221b9e0a6a568f1d427854d73363265cf
5
+ cotracker @ git+https://github.com/facebookresearch/co-tracker.git@82e02e8029753ad4ef13cf06be7f4fc5facdda4d
6
+ utils3d_moge @ git+https://github.com/EasternJournalist/utils3d-moge.git@62f09d58509485564e24d5d9f6aac9ee9ebc0c37
7
+ flex-gemm @ git+https://github.com/JeffreyXiang/FlexGEMM.git@b2fadb29d41846c7981ade6801ffc689fae119cf
论文参考代码/4DCodeBench/harness/scorer/requirements-nodeps.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # MoGe-3: install with --no-deps. Its declared dependencies cover the demo and training
2
+ # code; inference needs only packages from the other two files.
3
+ moge @ git+https://github.com/microsoft/MoGe.git@74fbce054ebed49800de42d0ad0e83495065719a
论文参考代码/4DCodeBench/harness/scorer/requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The scorer's PyPI packages, on top of torch 2.13.0 and torchvision 0.28.0 (CUDA 13.0).
2
+ numpy==2.3.1
3
+ h5py==3.16.0
4
+ scipy==1.18.0
5
+ trimesh==4.11.1
6
+ rtree==1.4.1
7
+ libigl==2.6.2
8
+ timm==1.0.28
9
+ easydict==1.13
10
+ transformers==4.57.1
11
+ opencv-python-headless==4.11.0.86
12
+ sentencepiece==0.2.2
13
+ ninja
论文参考代码/4DCodeBench/harness/stirrup/local_backend.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stirrup's local shell backend (stirrup 0.2.0, tools/code_backends/local.py) with three changes for sandboxed
2
+ agents: stdin is closed, output is collected as it arrives, and reading stops once the direct child exits.
3
+ """
4
+ """Local execution environment backend for code execution in an isolated temp directory."""
5
+
6
+ import contextlib
7
+ import logging
8
+ import os
9
+ import re
10
+ import shutil
11
+ import signal
12
+ import subprocess
13
+ import tempfile
14
+ from pathlib import Path
15
+
16
+ import anyio
17
+
18
+ from stirrup.core.models import ImageContentBlock, Tool, ToolUseCountMetadata
19
+
20
+ from stirrup.tools.code_backends.base import (
21
+ SHELL_TIMEOUT,
22
+ CodeExecToolProvider,
23
+ CodeExecutionParams,
24
+ CommandResult,
25
+ OutputSourceRoot,
26
+ SaveOutputFilesResult,
27
+ UploadedFile,
28
+ UploadFilesResult,
29
+ _atomic_write_bytes,
30
+ _host_output_destination_identity,
31
+ _save_host_output_files,
32
+ )
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ class LocalCodeExecToolProvider(CodeExecToolProvider):
38
+ """Local code execution tool provider using an isolated temp directory.
39
+
40
+ Commands are executed with the temp directory as the working directory.
41
+ An optional allowlist can restrict which commands are permitted.
42
+
43
+ Usage with Agent:
44
+ from stirrup.clients.chat_completions_client import ChatCompletionsClient
45
+
46
+ client = ChatCompletionsClient(model="gpt-5.6-luna", max_tokens=8_192, context_window_tokens=1_000_000)
47
+ agent = Agent(
48
+ client=client,
49
+ name="assistant",
50
+ tools=[LocalCodeExecToolProvider(), CALCULATOR_TOOL],
51
+ )
52
+
53
+ async with agent.session(output_dir="./output") as session:
54
+ await session.run("Run some Python code")
55
+
56
+ Standalone usage:
57
+ provider = LocalCodeExecToolProvider()
58
+
59
+ async with provider as tool:
60
+ # tool is a Tool instance for code execution
61
+ result = await provider.run_command("python script.py")
62
+ await provider.save_output_files(["output.txt"], "/path/to/output")
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ *,
68
+ allowed_commands: list[str] | None = None,
69
+ temp_base_dir: Path | str | None = None,
70
+ description: str | None = None,
71
+ shell_timeout: int = SHELL_TIMEOUT,
72
+ ) -> None:
73
+ """Initialize LocalCodeExecToolProvider configuration.
74
+
75
+ Args:
76
+ allowed_commands: Optional list of regex patterns. When set,
77
+ commands are matched against the patterns and run
78
+ without a shell, with literal arguments. When
79
+ None, all commands are allowed and run through
80
+ bash.
81
+ temp_base_dir: Optional base directory for creating the execution environment
82
+ temp directory. If None, uses the system default temp directory.
83
+ description: Optional description of the tool. If None, uses the default description.
84
+ shell_timeout: Per-command wall-clock timeout (seconds) for every
85
+ ``code_exec`` invocation, and the default for direct
86
+ ``run_command`` calls that pass ``timeout=None``. Defaults to
87
+ ``SHELL_TIMEOUT``.
88
+
89
+ """
90
+ super().__init__(allowed_commands=allowed_commands, shell_timeout=shell_timeout)
91
+ self._temp_dir: Path | None = None
92
+ self._temp_base_dir: Path | None = Path(temp_base_dir) if temp_base_dir else None
93
+ self._description = (
94
+ description
95
+ or "Execute a shell command in the execution environment. Returns exit code, stdout, and stderr as XML. Use `uv` to manage packages."
96
+ )
97
+
98
+ @property
99
+ def temp_dir(self) -> Path | None:
100
+ """Return the temp directory path, or None if not started."""
101
+ return self._temp_dir
102
+
103
+ def _check_absolute_paths(self, argv: list[str] | None, cmd: str) -> CommandResult | None:
104
+ """Check if a command references absolute paths that escape the temp directory.
105
+
106
+ Args:
107
+ argv: Parsed arguments when an allowlist is configured, else None.
108
+ cmd: Raw command, run through Bash when there is no allowlist.
109
+
110
+ Returns:
111
+ CommandResult with error if absolute paths detected, None otherwise.
112
+
113
+ Note:
114
+ This check is specific to LocalCodeExecToolProvider since Docker and E2B
115
+ providers are already sandboxed and absolute paths are safe within them.
116
+ """
117
+ # argv is what actually runs, so the patterns must see it rather than
118
+ # the raw string: quoting inside a path (``/et''c/passwd``) survives in
119
+ # the string but not in the parsed argument. Home-directory spellings
120
+ # are only expanded by Bash, so they are checked on that path alone.
121
+ absolute_patterns = [
122
+ r"/(?:home|Users|tmp|var|etc)/", # /home/, /Users/, /tmp/, etc.
123
+ ]
124
+ if argv is None:
125
+ absolute_patterns += [
126
+ r"~/", # ~/path - home directory shortcut
127
+ r"\$HOME/", # $HOME/path
128
+ r"\$\{HOME\}/", # ${HOME}/path
129
+ ]
130
+ for target in argv if argv is not None else [cmd]:
131
+ if any(re.search(pattern, target) for pattern in absolute_patterns):
132
+ return CommandResult(
133
+ exit_code=1,
134
+ stdout="",
135
+ stderr=(
136
+ "Command appears to use absolute paths which could write outside "
137
+ "the execution environment. Use relative paths instead."
138
+ ),
139
+ error_kind="absolute_path_detected",
140
+ advice=(
141
+ "Use relative paths (e.g., './output.txt' instead of '~/output.txt'). "
142
+ "For full filesystem access, use DockerCodeExecToolProvider or E2BCodeExecToolProvider."
143
+ ),
144
+ )
145
+ return None
146
+
147
+ async def __aenter__(self) -> "Tool[CodeExecutionParams, ToolUseCountMetadata]":
148
+ """Create temp directory and return the code_exec tool."""
149
+ if self._temp_base_dir:
150
+ self._temp_base_dir.mkdir(parents=True, exist_ok=True)
151
+ self._temp_dir = Path(tempfile.mkdtemp(prefix="local_exec_env_", dir=self._temp_base_dir))
152
+ logger.debug("Created local execution environment temp directory: %s", self._temp_dir)
153
+ return self.get_code_exec_tool(description=self._description)
154
+
155
+ async def __aexit__(
156
+ self,
157
+ exc_type: type[BaseException] | None,
158
+ exc_val: BaseException | None,
159
+ exc_tb: object,
160
+ ) -> None:
161
+ """Cleanup the local execution environment."""
162
+ if self._temp_dir and self._temp_dir.exists():
163
+ try:
164
+ shutil.rmtree(self._temp_dir)
165
+ except Exception as exc:
166
+ logger.warning("Failed to cleanup temp directory %s: %s", self._temp_dir, exc)
167
+ self._temp_dir = None
168
+
169
+ def _resolve_and_validate_path(self, path: str) -> Path:
170
+ """Resolve a path and validate it's within the temp directory.
171
+
172
+ Args:
173
+ path: File path (relative or absolute within the temp dir).
174
+
175
+ Returns:
176
+ Resolved absolute Path.
177
+
178
+ Raises:
179
+ RuntimeError: If environment not started.
180
+ ValueError: If path is outside temp directory.
181
+ FileNotFoundError: If path does not exist (for reads).
182
+
183
+ """
184
+ if self._temp_dir is None:
185
+ raise RuntimeError("ExecutionEnvironment not started.")
186
+
187
+ resolved = Path(path)
188
+ if not resolved.is_absolute():
189
+ resolved = self._temp_dir / resolved
190
+
191
+ # Security: ensure path is within temp directory
192
+ try:
193
+ resolved.resolve().relative_to(self._temp_dir.resolve())
194
+ except ValueError as e:
195
+ raise ValueError(f"Path is outside execution environment: {path}") from e
196
+
197
+ return resolved
198
+
199
+ async def read_file_bytes(self, path: str) -> bytes:
200
+ """Read file content as bytes from the temp directory.
201
+
202
+ Args:
203
+ path: File path (relative or absolute within the temp dir).
204
+
205
+ Returns:
206
+ File contents as bytes.
207
+
208
+ Raises:
209
+ RuntimeError: If environment not started.
210
+ ValueError: If path is outside temp directory.
211
+ FileNotFoundError: If file does not exist.
212
+
213
+ """
214
+ resolved = self._resolve_and_validate_path(path)
215
+ if not resolved.exists():
216
+ raise FileNotFoundError(f"File not found: {path}")
217
+ return resolved.read_bytes()
218
+
219
+ async def write_file_bytes(self, path: str, content: bytes) -> None:
220
+ """Write bytes to a file in the temp directory.
221
+
222
+ Args:
223
+ path: Destination path (relative or absolute within the temp dir).
224
+ content: File contents to write.
225
+
226
+ Raises:
227
+ RuntimeError: If environment not started.
228
+ ValueError: If path is outside temp directory.
229
+
230
+ """
231
+ resolved = self._resolve_and_validate_path(path)
232
+ _atomic_write_bytes(content, resolved)
233
+
234
+ async def file_exists(self, path: str) -> bool:
235
+ """Check if a file exists in the temp directory.
236
+
237
+ Args:
238
+ path: File path (relative or absolute within the temp dir).
239
+
240
+ Returns:
241
+ True if the file exists, False otherwise.
242
+
243
+ Raises:
244
+ RuntimeError: If environment not started.
245
+ ValueError: If path is outside temp directory.
246
+
247
+ """
248
+ resolved = self._resolve_and_validate_path(path)
249
+ return resolved.exists() and resolved.is_file()
250
+
251
+ async def is_directory(self, path: str) -> bool:
252
+ """Check if a path is a directory in the temp directory.
253
+
254
+ Args:
255
+ path: Path (relative or absolute within the temp dir).
256
+
257
+ Returns:
258
+ True if the path exists and is a directory, False otherwise.
259
+
260
+ Raises:
261
+ RuntimeError: If environment not started.
262
+ ValueError: If path is outside temp directory.
263
+
264
+ """
265
+ resolved = self._resolve_and_validate_path(path)
266
+ return resolved.exists() and resolved.is_dir()
267
+
268
+ async def list_files(self, path: str) -> list[str]:
269
+ """List all files recursively in a directory within the temp directory.
270
+
271
+ Args:
272
+ path: Directory path (relative or absolute within the temp dir).
273
+
274
+ Returns:
275
+ List of file paths (relative to the given path) for all files in the directory.
276
+ Returns an empty list if the path is a file or doesn't exist.
277
+
278
+ Raises:
279
+ RuntimeError: If environment not started.
280
+ ValueError: If path is outside temp directory.
281
+
282
+ """
283
+ resolved = self._resolve_and_validate_path(path)
284
+ if not resolved.exists() or not resolved.is_dir():
285
+ return []
286
+
287
+ files = []
288
+ for file_path in resolved.rglob("*"):
289
+ if file_path.is_file():
290
+ rel_path = file_path.relative_to(resolved)
291
+ files.append(str(rel_path))
292
+ return files
293
+
294
+ async def run_command(self, cmd: str, *, timeout: int | None = None) -> CommandResult:
295
+ """Execute command in the temp directory.
296
+
297
+ Args:
298
+ cmd: Shell command to execute (bash syntax).
299
+ timeout: Maximum time in seconds to wait for command completion.
300
+ If None, falls back to ``self._shell_timeout`` (set in
301
+ ``__init__``), so direct callers share the same budget as the
302
+ LLM ``code_exec`` tool.
303
+
304
+ Returns:
305
+ CommandResult with exit_code, stdout, stderr, and optional error info.
306
+
307
+ """
308
+ if self._temp_dir is None:
309
+ raise RuntimeError(
310
+ "ExecutionEnvironment not started. Ensure current Agent is equipped with a CodeExecToolProvider."
311
+ )
312
+ if timeout is None:
313
+ timeout = self._shell_timeout
314
+
315
+ # With an allowlist, the parsed argv must run directly (no shell).
316
+ argv, rejection = self._prepare_command(cmd)
317
+ if rejection is not None:
318
+ return rejection
319
+
320
+ # Check for absolute paths (local environment is not sandboxed)
321
+ absolute_path_error = self._check_absolute_paths(argv, cmd)
322
+ if absolute_path_error:
323
+ return absolute_path_error
324
+
325
+ process = None
326
+ try:
327
+ with anyio.fail_after(timeout):
328
+ # start_new_session=True puts the child at the head of its own
329
+ # session, so pgid == child pid and we can killpg the whole tree
330
+ # on timeout. Without it, process.kill() only terminates the
331
+ # root process, leaving grandchildren reparented to init (same
332
+ # bug shape as the docker orphan leak that motivated this PR).
333
+ process = await anyio.open_process(
334
+ argv if argv is not None else ["bash", "-c", cmd],
335
+ stdin=subprocess.DEVNULL, # a never-closed stdin pipe hangs any command that reads stdin
336
+ stdout=subprocess.PIPE,
337
+ stderr=subprocess.PIPE,
338
+ cwd=self._temp_dir,
339
+ start_new_session=True,
340
+ )
341
+
342
+ # Read all output from streams concurrently
343
+ stdout_chunks: list[bytes] = []
344
+ stderr_chunks: list[bytes] = []
345
+
346
+ async def read_stdout() -> None:
347
+ if process.stdout:
348
+ async for chunk in process.stdout:
349
+ stdout_chunks.append(chunk)
350
+
351
+ async def read_stderr() -> None:
352
+ if process.stderr:
353
+ async for chunk in process.stderr:
354
+ stderr_chunks.append(chunk)
355
+
356
+ async with anyio.create_task_group() as tg:
357
+ tg.start_soon(read_stdout)
358
+ tg.start_soon(read_stderr)
359
+ # stop reading once the direct child has exited: a backgrounded subshell that inherited
360
+ # the pipes would otherwise hold the tool call open until its timeout
361
+ await process.wait()
362
+ await anyio.sleep(0.5)
363
+ tg.cancel_scope.cancel()
364
+
365
+ return CommandResult(
366
+ exit_code=process.returncode or 0,
367
+ stdout=b"".join(stdout_chunks).decode("utf-8", errors="replace"),
368
+ stderr=b"".join(stderr_chunks).decode("utf-8", errors="replace"),
369
+ )
370
+
371
+ except TimeoutError:
372
+ if process:
373
+ with contextlib.suppress(ProcessLookupError):
374
+ os.killpg(process.pid, signal.SIGKILL)
375
+ with anyio.move_on_after(5):
376
+ await process.wait()
377
+ return CommandResult(
378
+ exit_code=1,
379
+ stdout="",
380
+ stderr=f"Command timed out after {timeout} seconds",
381
+ error_kind="timeout",
382
+ )
383
+ except Exception as exc:
384
+ return CommandResult(
385
+ exit_code=1,
386
+ stdout="",
387
+ stderr=str(exc),
388
+ error_kind="execution_error",
389
+ )
390
+
391
+ async def save_output_files(
392
+ self,
393
+ paths: list[str],
394
+ output_dir: Path | str,
395
+ dest_env: "CodeExecToolProvider | None" = None,
396
+ ) -> SaveOutputFilesResult:
397
+ """Copy files from the temp directory to a destination.
398
+
399
+ Source files remain in the execution environment. Existing destination
400
+ files are atomically replaced, while duplicate destinations within one
401
+ call are rejected and reported in ``failed``.
402
+
403
+ When dest_env is provided (cross-environment transfer), files are copied
404
+ using the base class implementation via read/write primitives.
405
+
406
+ Args:
407
+ paths: List of file paths in the execution environment (relative or absolute).
408
+ Relative paths are resolved against the execution environment temp directory.
409
+ output_dir: Directory path to save files to.
410
+ dest_env: If provided, output_dir is interpreted as a path within dest_env
411
+ (cross-environment transfer). If None, output_dir is a local
412
+ filesystem path.
413
+
414
+ Returns:
415
+ SaveOutputFilesResult containing lists of saved files and any failures.
416
+
417
+ """
418
+ if self._temp_dir is None:
419
+ raise RuntimeError(
420
+ "ExecutionEnvironment not started. Ensure current Agent is equipped with a CodeExecToolProvider."
421
+ )
422
+
423
+ # If dest_env is provided, use the base class implementation (cross-env transfer)
424
+ if dest_env is not None:
425
+ return await super().save_output_files(paths, output_dir, dest_env)
426
+
427
+ return _save_host_output_files(
428
+ paths,
429
+ output_dir,
430
+ source_roots=self.output_source_roots(),
431
+ resolve_source=self._resolve_and_validate_path,
432
+ )
433
+
434
+ def output_source_roots(self) -> tuple[OutputSourceRoot, ...]:
435
+ """Return absolute execution roots accepted when resolving output paths."""
436
+ return (OutputSourceRoot.for_host(self._temp_dir),) if self._temp_dir is not None else ()
437
+
438
+ async def output_destination_identity(self, destination: str, output_root: Path | str) -> str:
439
+ """Validate a cross-environment destination and return its host identity."""
440
+ resolved_destination = self._resolve_and_validate_path(destination)
441
+ resolved_root = self._resolve_and_validate_path(str(output_root))
442
+ return _host_output_destination_identity(resolved_destination, resolved_root)
443
+
444
+ async def upload_files(
445
+ self,
446
+ *paths: Path | str,
447
+ source_env: "CodeExecToolProvider | None" = None,
448
+ dest_dir: str | None = None,
449
+ ) -> UploadFilesResult:
450
+ """Upload files to the execution environment.
451
+
452
+ When source_env is None (local filesystem), files are COPIED (not moved) -
453
+ originals remain on the local filesystem.
454
+ Directories are uploaded recursively, preserving their structure.
455
+
456
+ When source_env is provided (cross-environment transfer), files are copied
457
+ using the base class implementation via read/write primitives.
458
+
459
+ Args:
460
+ *paths: File or directory paths to upload. If source_env is None, these
461
+ are local filesystem paths. If source_env is provided, these are
462
+ paths within source_env.
463
+ source_env: If provided, paths are within source_env. If None, paths are
464
+ local filesystem paths.
465
+ dest_dir: Destination subdirectory within the temp directory.
466
+ If None, files are placed directly in the temp directory.
467
+
468
+ Returns:
469
+ UploadFilesResult containing lists of uploaded files and any failures.
470
+
471
+ """
472
+ if self._temp_dir is None:
473
+ raise RuntimeError(
474
+ "ExecutionEnvironment not started. Ensure current Agent is equipped with a CodeExecToolProvider."
475
+ )
476
+
477
+ # If source_env is provided, use the base class implementation (cross-env transfer)
478
+ if source_env is not None:
479
+ return await super().upload_files(*paths, source_env=source_env, dest_dir=dest_dir)
480
+
481
+ # Local filesystem - use optimized copy operation
482
+ dest_base = self._temp_dir / dest_dir if dest_dir else self._temp_dir
483
+ dest_base.mkdir(parents=True, exist_ok=True)
484
+
485
+ result = UploadFilesResult()
486
+
487
+ for source in paths:
488
+ source = Path(source).resolve()
489
+
490
+ if not source.exists():
491
+ result.failed[str(source)] = "File or directory does not exist"
492
+ logger.warning("Upload source does not exist: %s", source)
493
+ continue
494
+
495
+ try:
496
+ if source.is_file():
497
+ dest = dest_base / source.name
498
+ shutil.copy2(source, dest)
499
+ result.uploaded.append(
500
+ UploadedFile(
501
+ source_path=source,
502
+ dest_path=str(dest.relative_to(self._temp_dir)),
503
+ size=source.stat().st_size,
504
+ ),
505
+ )
506
+ logger.debug("Uploaded file: %s -> %s", source, dest)
507
+
508
+ elif source.is_dir():
509
+ # If dest_dir was explicitly provided, copy contents directly to dest_base
510
+ # Otherwise, create a subdirectory with the source's name
511
+ if dest_dir:
512
+ dest = dest_base
513
+ # Copy contents of source directory into dest_base
514
+ for item in source.iterdir():
515
+ item_dest = dest / item.name
516
+ if item.is_file():
517
+ shutil.copy2(item, item_dest)
518
+ else:
519
+ shutil.copytree(item, item_dest, dirs_exist_ok=True)
520
+ else:
521
+ dest = dest_base / source.name
522
+ shutil.copytree(source, dest, dirs_exist_ok=True)
523
+ # Track all individual files uploaded
524
+ for file_path in source.rglob("*"):
525
+ if file_path.is_file():
526
+ relative = file_path.relative_to(source)
527
+ dest_file = dest / relative
528
+ result.uploaded.append(
529
+ UploadedFile(
530
+ source_path=file_path,
531
+ dest_path=str(dest_file.relative_to(self._temp_dir)),
532
+ size=file_path.stat().st_size,
533
+ ),
534
+ )
535
+ logger.debug("Uploaded directory: %s -> %s", source, dest)
536
+
537
+ except Exception as exc:
538
+ result.failed[str(source)] = str(exc)
539
+ logger.exception("Failed to upload: %s", source)
540
+
541
+ return result
542
+
543
+ async def view_image(self, path: str) -> ImageContentBlock:
544
+ """Read and return an image file from the local execution environment.
545
+
546
+ Args:
547
+ path: Path to image file (relative to temp directory, or absolute within it).
548
+
549
+ Returns:
550
+ ImageContentBlock containing the image data.
551
+
552
+ Raises:
553
+ RuntimeError: If execution environment not started.
554
+ FileNotFoundError: If file does not exist.
555
+ ValueError: If path is outside temp directory, is a directory, or not a valid image.
556
+
557
+ """
558
+ file_bytes = await self.read_file_bytes(path)
559
+ return ImageContentBlock(data=file_bytes)
论文参考代码/4DCodeBench/harness/stirrup/runner.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run the task with Artificial Analysis' Stirrup agent loop inside the agent container.
3
+
4
+ runner.py <task_path> <workspace> <model> <effort> <timeout_sec>
5
+
6
+ Calls an OpenAI-compatible endpoint (`OPENAI_BASE_URL`, `OPENAI_API_KEY`) with the
7
+ tools code_exec (bash in the workspace), view_image and finish. Each event is
8
+ appended to $HOME/.stirrup/session/<run>.jsonl. Limits are set by `FDCB_*` variables.
9
+ """
10
+
11
+ import asyncio
12
+ import inspect
13
+ import json
14
+ import os
15
+ import re
16
+ import sys
17
+ import time
18
+ import urllib.request
19
+ from pathlib import Path
20
+
21
+ # requests go to the endpoint directly, never through a proxy
22
+ os.environ.setdefault("no_proxy", "*")
23
+ os.environ.setdefault("NO_PROXY", "*")
24
+ for variable in ("http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY"):
25
+ os.environ.pop(variable, None)
26
+
27
+ from local_backend import LocalCodeExecToolProvider # adapted copy of Stirrup's local backend
28
+ from stirrup import Agent
29
+ from stirrup.clients.chat_completions_client import ChatCompletionsClient
30
+ from stirrup.core.exceptions import OutputTokenLimitError
31
+ from stirrup.core.models import ToolResult
32
+ from stirrup.tools import SIMPLE_FINISH_TOOL
33
+ from stirrup.tools.view_image import ViewImageToolProvider
34
+ from stirrup.utils.logging import AgentLoggerBase
35
+
36
+ task_path, workspace, model, effort, timeout_sec = (
37
+ sys.argv[1], Path(sys.argv[2]), sys.argv[3], sys.argv[4], int(sys.argv[5]))
38
+ BASE_URL = os.environ.get("OPENAI_BASE_URL", "http://127.0.0.1:8000/v1")
39
+ MAX_TURNS = 500
40
+ CONTEXT_TOKENS = 262144
41
+ MAX_TOKENS = 65536 # output budget of one response
42
+ MAX_TOKENS_RETRY = 131072 # output budget of the one retry after a truncated response
43
+ REQUEST_TIMEOUT = 1800 # seconds per request
44
+ SHELL_TIMEOUT = 36000 # seconds per shell command
45
+ SUMMARIZE_AT = 0.7 # share of the context window at which Stirrup summarises
46
+ RECONNECT_MINUTES = 45 # how long `generate` retries an unreachable endpoint
47
+ # The job's effort is sent as `reasoning_effort`; "none" omits the parameter.
48
+ EFFORT = None if effort.strip().lower() in ("", "none", "off") else effort
49
+ CONNECTION_ERRORS = ("APIConnectionError", "APITimeoutError", "ConnectError", "ReadTimeout", "RemoteProtocolError")
50
+ CONNECTION_MESSAGES = ("Connection error", "Connection refused", "Error code: 502", "Error code: 503", "Error code: 504")
51
+ # context-overflow errors of SGLang (includes the prompt size) and vLLM (does not)
52
+ SGLANG_OVERFLOW = re.compile(r"maximum context length of (\d+) tokens\. You requested a total of (\d+) tokens: "
53
+ r"(\d+) tokens from the input")
54
+ VLLM_OVERFLOW = re.compile(r"maximum context length is (\d+) tokens.*?requested (\d+) output tokens", re.S)
55
+
56
+
57
+ def is_connection_error(exc: Exception) -> bool:
58
+ return type(exc).__name__ in CONNECTION_ERRORS or any(text in str(exc) for text in CONNECTION_MESSAGES)
59
+
60
+
61
+ async def wait_healthy(deadline: float) -> None:
62
+ """Poll the endpoint's /health until it returns 200 or `deadline` passes."""
63
+
64
+ def healthy() -> bool:
65
+ try:
66
+ return urllib.request.urlopen(BASE_URL.rsplit("/v1", 1)[0] + "/health", timeout=10).status == 200
67
+ except Exception: # noqa: BLE001
68
+ return False
69
+
70
+ while time.time() < deadline and not await asyncio.to_thread(healthy):
71
+ await asyncio.sleep(15)
72
+
73
+
74
+ class Client(ChatCompletionsClient):
75
+ """Stirrup's client with retries on connection errors and on output-budget overflows."""
76
+
77
+ def __init__(self, *args, **kwargs):
78
+ super().__init__(*args, **kwargs)
79
+ # copy vLLM's `message.reasoning` into `reasoning_content`, the field Stirrup reads
80
+ completions = getattr(getattr(getattr(self, "_client", None), "chat", None), "completions", None)
81
+ if completions is None:
82
+ return
83
+ create = completions.create
84
+
85
+ async def create_with_reasoning(*a, **kw):
86
+ response = await create(*a, **kw)
87
+ for choice in getattr(response, "choices", None) or []:
88
+ message = choice.message
89
+ if not getattr(message, "reasoning_content", None) and getattr(message, "reasoning", None):
90
+ message.reasoning_content = message.reasoning
91
+ return response
92
+
93
+ completions.create = create_with_reasoning
94
+
95
+ async def generate(self, messages, tools=None, **kw):
96
+ """Retry connection errors for RECONNECT_MINUTES, waiting 30 s and for /health each time."""
97
+
98
+ deadline = time.time() + 60 * RECONNECT_MINUTES
99
+ while True:
100
+ try:
101
+ return await self._generate_fitted(messages, tools, **kw)
102
+ except Exception as exc: # noqa: BLE001
103
+ if not is_connection_error(exc) or time.time() > deadline:
104
+ raise
105
+ print(f"[stirrup] endpoint unreachable ({type(exc).__name__}); retrying", file=sys.stderr)
106
+ await asyncio.sleep(30)
107
+ await wait_healthy(deadline)
108
+
109
+ async def _generate_fitted(self, messages, tools=None, **kw):
110
+ """Run one step, retrying with a smaller output budget on a context overflow.
111
+
112
+ A response cut off at the output budget is retried once with MAX_TOKENS_RETRY.
113
+ """
114
+
115
+ saved = self._max_tokens
116
+ try:
117
+ try:
118
+ return await super().generate(messages, tools, **kw)
119
+ except OutputTokenLimitError:
120
+ self._max_tokens = MAX_TOKENS_RETRY
121
+ print(f"[stirrup] output budget exhausted at {saved}; retrying with {MAX_TOKENS_RETRY}",
122
+ file=sys.stderr)
123
+ return await super().generate(messages, tools, **kw)
124
+ except Exception as exc: # noqa: BLE001
125
+ sglang = SGLANG_OVERFLOW.search(str(exc))
126
+ if not sglang and not VLLM_OVERFLOW.search(str(exc)):
127
+ raise
128
+ # SGLang's error gives the room left in the window; vLLM's does not
129
+ fitted = [max(1024, int(sglang.group(1)) - int(sglang.group(3)) - 512)] if sglang else []
130
+ last = exc
131
+ for budget in [*fitted, 32768, 16384, 8192, 4096, 2048]:
132
+ if budget >= saved:
133
+ continue
134
+ self._max_tokens = budget
135
+ print(f"[stirrup] prompt near the window: retrying with output budget {budget}", file=sys.stderr)
136
+ try:
137
+ return await super().generate(messages, tools, **kw)
138
+ except Exception as retry: # noqa: BLE001
139
+ last = retry
140
+ if not re.search(r"requested (\d+) output tokens|You requested a total of", str(retry)):
141
+ raise
142
+ raise last
143
+ finally:
144
+ self._max_tokens = saved
145
+
146
+
147
+ class WorkspaceExec(LocalCodeExecToolProvider):
148
+ """Stirrup's local shell, rooted at the persistent workspace instead of a temporary dir."""
149
+
150
+ async def __aenter__(self):
151
+ self._temp_dir = workspace
152
+ workspace.mkdir(parents=True, exist_ok=True)
153
+ return self.get_code_exec_tool(description=self._description)
154
+
155
+ async def __aexit__(self, *args):
156
+ return None
157
+
158
+ def get_view_image_tool(self, *args, **kwargs):
159
+ """Return view_image with failures reported as a short text result."""
160
+
161
+ tool = super().get_view_image_tool(*args, **kwargs)
162
+ executor = tool.executor
163
+
164
+ async def guarded(params):
165
+ path = getattr(params, "path", None) or getattr(params, "image_path", None) or ""
166
+ try:
167
+ result = executor(params)
168
+ return await result if inspect.isawaitable(result) else result
169
+ except Exception as exc: # noqa: BLE001
170
+ return ToolResult(content=f"[view_image] {path}: cannot be shown ({type(exc).__name__}: "
171
+ f"{str(exc)[:200]}). Convert it to a PNG/JPG first.")
172
+
173
+ tool.executor = guarded
174
+ return tool
175
+
176
+ def _check_absolute_paths(self, argv, cmd):
177
+ # Stirrup's check rejects /tmp/, /home/, /var/ and /etc/ paths; the container is the sandbox
178
+ return None
179
+
180
+
181
+ def _strip(value):
182
+ """Return a pydantic dump made JSON-safe, image and binary payloads replaced by their size."""
183
+
184
+ if isinstance(value, dict):
185
+ if value.get("kind") == "image_content_block" or isinstance(value.get("data"), (bytes, bytearray)):
186
+ return {"kind": "image", "bytes": len(value.get("data") or b""), "mime": value.get("mime_type")}
187
+ return {key: _strip(item) for key, item in value.items()}
188
+ if isinstance(value, list):
189
+ return [_strip(item) for item in value]
190
+ if isinstance(value, (bytes, bytearray)):
191
+ return f"<{len(value)} bytes>"
192
+ return value
193
+
194
+
195
+ class JsonlLogger(AgentLoggerBase):
196
+ """Logger that appends one flushed JSON line per event, in place of Stirrup's console logger."""
197
+
198
+ def __init__(self, path: Path):
199
+ try:
200
+ super().__init__()
201
+ except TypeError:
202
+ super().__init__(depth=0)
203
+ if not hasattr(self, "depth"):
204
+ self.depth = 0
205
+ path.parent.mkdir(parents=True, exist_ok=True)
206
+ self.file = path.open("a", encoding="utf-8")
207
+
208
+ def __enter__(self):
209
+ return self
210
+
211
+ def __exit__(self, *args):
212
+ self.file.close()
213
+
214
+ def _write(self, **record):
215
+ record["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
216
+ self.file.write(json.dumps(record, default=str) + "\n")
217
+ self.file.flush()
218
+
219
+ def _dump(self, message):
220
+ try:
221
+ return _strip(message.model_dump())
222
+ except Exception: # noqa: BLE001
223
+ return str(message)[:2000]
224
+
225
+ def on_step(self, step, tool_calls=0, input_tokens=0, output_tokens=0):
226
+ self._write(type="step", step=step, tool_calls=tool_calls, input_tokens=input_tokens,
227
+ output_tokens=output_tokens)
228
+
229
+ def assistant_message(self, turn, max_turns, assistant_message):
230
+ self._write(type="assistant", turn=turn, message=self._dump(assistant_message))
231
+
232
+ def user_message(self, user_message):
233
+ self._write(type="user", message=self._dump(user_message))
234
+
235
+ def task_message(self, task):
236
+ self._write(type="task", task=task if isinstance(task, str) else _strip(task))
237
+
238
+ def tool_result(self, tool_message):
239
+ self._write(type="tool", message=self._dump(tool_message))
240
+
241
+ def context_summarization_start(self, pct_used, cutoff):
242
+ self._write(type="summarization_start", pct_used=pct_used, cutoff=cutoff)
243
+
244
+ def context_summarization_complete(self, summary, bridge):
245
+ self._write(type="summarization_complete", summary=summary[:4000], bridge=bridge[:2000])
246
+
247
+ def debug(self, message, *args):
248
+ pass
249
+
250
+ def info(self, message, *args):
251
+ try:
252
+ self._write(type="info", text=(message % args) if args else str(message))
253
+ except Exception: # noqa: BLE001
254
+ self._write(type="info", text=str(message))
255
+
256
+ def warning(self, message, *args):
257
+ self._write(type="warning", text=str(message))
258
+
259
+ def error(self, message, *args):
260
+ self._write(type="error", text=str(message))
261
+
262
+
263
+ async def main() -> int:
264
+ task = Path(task_path).read_text(encoding="utf-8")
265
+ client = Client(
266
+ model=model,
267
+ base_url=BASE_URL,
268
+ api_key=os.environ.get("OPENAI_API_KEY", "local"),
269
+ max_tokens=MAX_TOKENS,
270
+ context_window_tokens=CONTEXT_TOKENS,
271
+ reasoning_effort=EFFORT,
272
+ timeout=REQUEST_TIMEOUT,
273
+ max_retries=0, # `Client.generate` does the retrying
274
+ )
275
+ shell = WorkspaceExec(temp_base_dir=workspace, shell_timeout=SHELL_TIMEOUT)
276
+ home = Path(os.environ.get("HOME", "/root"))
277
+ run_id = time.strftime("%Y%m%d-%H%M%S")
278
+ logger = JsonlLogger(home / ".stirrup" / "session" / f"{run_id}.jsonl")
279
+ agent = Agent(
280
+ client=client,
281
+ name="4dcb",
282
+ max_turns=MAX_TURNS,
283
+ tools=[shell, ViewImageToolProvider(shell)],
284
+ finish_tool=SIMPLE_FINISH_TOOL,
285
+ # summarise at `SUMMARIZE_AT` of the window; unwind turns on overflow
286
+ context_summarization_cutoff=SUMMARIZE_AT,
287
+ recover_from_context_overflow=True,
288
+ logger=logger,
289
+ )
290
+ async with agent.session(output_dir=str(home / ".stirrup" / "output" / run_id)) as session:
291
+ try:
292
+ finish, history, _ = await asyncio.wait_for(session.run(task), timeout=timeout_sec)
293
+ logger.info("finished: %s", str(finish)[:500])
294
+ except asyncio.TimeoutError:
295
+ logger.info("timeout")
296
+ print("[stirrup] timeout", file=sys.stderr)
297
+ return 124
298
+ except Exception as exc: # noqa: BLE001
299
+ message = str(exc)
300
+ if "context length" in message or "context window" in message.lower() or "Input length" in message:
301
+ # an exhausted context window ends the run with exit 0
302
+ logger.error("context_limit: " + message[:500])
303
+ print(f"[stirrup] context limit reached ({message[:200]})", file=sys.stderr)
304
+ return 0
305
+ raise
306
+ print(f"[stirrup] finished turns={len(history)} finish={finish}")
307
+ return 0
308
+
309
+
310
+ if __name__ == "__main__":
311
+ sys.exit(asyncio.run(main()))
论文参考代码/4DCodeBench/scorer/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Hidden reference-grounded 4DCodeBench scorer."""
2
+
3
+ import os
4
+
5
+ # libigl runs single-threaded; the scorer parallelises across frame workers.
6
+ os.environ.setdefault("IGL_NUM_THREADS", "1")
论文参考代码/4DCodeBench/scorer/__main__.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """`python -m scorer`: score every world a manifest names.
2
+
3
+ Runs the gates for every world, then the geometry, Semantic, GeoPhys and Uni3D
4
+ passes in turn. Each metric is written to `reward.json` when it completes. Exits
5
+ nonzero when any world had a failure.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ from pathlib import Path
12
+
13
+ from .execution import Timeouts, Worker
14
+ from .paths import (
15
+ CASES_ROOT,
16
+ CHECKPOINTS_DIR,
17
+ DATA_ROOT,
18
+ MANIFEST_PATH,
19
+ RUNS_ROOT,
20
+ Roots,
21
+ load_manifest,
22
+ )
23
+ from .score import (
24
+ TYPES,
25
+ gate,
26
+ geometry_pass,
27
+ geophys_pass,
28
+ semantic_pass,
29
+ uni3d_pass,
30
+ )
31
+ from .tasks import GeometryTasks
32
+
33
+
34
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
35
+ parser = argparse.ArgumentParser(prog="python -m scorer",
36
+ description="Score every world a manifest names.")
37
+ parser.add_argument("--manifest", type=Path, default=MANIFEST_PATH,
38
+ help="the worlds to score, as the harness wrote them")
39
+ parser.add_argument("--cases", type=Path, default=CASES_ROOT, help="the cases root")
40
+ parser.add_argument("--data", type=Path, default=DATA_ROOT, help="the case data root")
41
+ parser.add_argument("--runs", type=Path, default=RUNS_ROOT, help="the runs root")
42
+ parser.add_argument("--checkpoints", type=Path, default=CHECKPOINTS_DIR,
43
+ help="the model store the semantic and Uni3D readings load from")
44
+ parser.add_argument("--type", action="append", default=None,
45
+ help=f"metric types to read on their own, out of {list(TYPES)}; "
46
+ "repeatable or comma-separated; everything by default")
47
+ parser.add_argument("--task-timeout", type=float, default=1800, help="seconds per metric or world inference")
48
+ parser.add_argument("--prepare-timeout", type=float, default=600, help="seconds per geometry preparation or model load")
49
+ parser.add_argument("--timeout", action="append", default=[], metavar="TASK=SECONDS",
50
+ help="override one task deadline; repeatable")
51
+ args = parser.parse_args(argv)
52
+ args.overrides = {}
53
+ for value in args.timeout:
54
+ try:
55
+ name, seconds = value.split("=", 1)
56
+ args.overrides[name] = float(seconds)
57
+ except ValueError:
58
+ parser.error("--timeout requires TASK=SECONDS")
59
+ if any(value <= 0 for value in [args.task_timeout, args.prepare_timeout, *args.overrides.values()]):
60
+ parser.error("timeouts must be positive")
61
+ if args.type is not None:
62
+ args.type = [name for item in args.type for name in item.split(",") if name]
63
+ unknown = sorted(set(args.type) - set(TYPES))
64
+ if unknown:
65
+ parser.error(f"--type names {list(TYPES)}, not {unknown}")
66
+ return args
67
+
68
+
69
+
70
+ def main(argv: list[str] | None = None) -> int:
71
+ args = parse_args(argv)
72
+ roots = Roots(cases=args.cases, data=args.data, runs=args.runs, checkpoints=args.checkpoints)
73
+ entries = load_manifest(args.manifest, roots)
74
+ wanted = set(args.type) if args.type else set(TYPES)
75
+ limits = Timeouts(args.task_timeout, args.prepare_timeout, args.overrides)
76
+ print(f"{len(entries)} world(s), types {sorted(wanted)}", flush=True)
77
+ items = []
78
+ worker = None
79
+ try:
80
+ for entry in entries:
81
+ if worker is None:
82
+ worker = Worker(GeometryTasks, limits.seconds("worker", True))
83
+ items.append(gate(entry, wanted, worker, limits))
84
+ if not worker.alive:
85
+ worker.close()
86
+ worker = None
87
+ finally:
88
+ if worker is not None:
89
+ worker.close()
90
+ geometry_pass(items, limits)
91
+ semantic_pass(items, limits)
92
+ geophys_pass(items, limits)
93
+ uni3d_pass(items, limits)
94
+ failed = sum(item.failed for item in items)
95
+ print(f"{len(items) - failed}/{len(items)} completed without failures", flush=True)
96
+ return int(bool(failed))
97
+
98
+
99
+ if __name__ == "__main__":
100
+ raise SystemExit(main())
论文参考代码/4DCodeBench/scorer/analytic/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Submission-side optical flow and point tracks, computed from the world's geometry.
2
+
3
+ Flow and tracks are computed from a submission's meshes, material columns and
4
+ camera; estimators run only on the case's reference video. `advection` seeds
5
+ and advects the tracers of an identity-less liquid.
6
+ """