prune-early 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Soham Kumar, Shreenidhi Sathyanarayanan, Aniruddha Mukherjee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: prune-early
3
+ Version: 1.0.0
4
+ Summary: Pick which video-generation candidates to finish from their first second, and stop the rest early
5
+ Author: Soham Kumar, Shreenidhi Sathyanarayanan, Aniruddha Mukherjee
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/sohamkumar1703/prune-early
8
+ Project-URL: Paper, https://github.com/sohamkumar1703/prune-early/blob/main/paper/report/main.pdf
9
+ Project-URL: Issues, https://github.com/sohamkumar1703/prune-early/issues
10
+ Keywords: video generation,best-of-n,verifier,physics,MAGI-1,autoregressive,pruning
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Topic :: Multimedia :: Video
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: numpy>=1.21
24
+ Requires-Dist: opencv-python-headless>=4.5
25
+ Provides-Extra: exact
26
+ Requires-Dist: opencv-python-headless==5.0.0.93; extra == "exact"
27
+ Provides-Extra: test
28
+ Requires-Dist: pytest>=7; extra == "test"
29
+ Dynamic: license-file
30
+
31
+ # prune-early
32
+
33
+ **Generate several videos, stop each after its first second, and finish only the best one.**
34
+
35
+ `prune-early` is a small, training-free judge for best-of-N video generation. Give it the candidates you made for one prompt. It reads only their first second, scores how much of each frame moves and how well that motion agrees with the other candidates, and tells you which ones to finish. With MAGI-1, picking 1 of 8 this way scored +4.46 Physics-IQ points above a random pick and cost 48% less GPU time than finishing all 8.
36
+
37
+ <p align="center"><img src="https://raw.githubusercontent.com/sohamkumar1703/prune-early/main/figures/overview.png" width="100%" alt="Method overview"></p>
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install prune-early
43
+ ```
44
+
45
+ It needs Python 3.9 or newer and runs on a CPU. Its only dependencies are NumPy and OpenCV.
46
+
47
+ To get exactly the scores from the paper, install the OpenCV version we used. Newer versions decode videos very slightly differently, which moved scores by up to about 0.1 in our check (the pick stayed the same).
48
+
49
+ ```bash
50
+ pip install "prune-early[exact]"
51
+ ```
52
+
53
+ ## Use it from the command line
54
+
55
+ Point it at a folder with the candidates of **one** prompt.
56
+
57
+ ```bash
58
+ prune-early candidates/
59
+ ```
60
+
61
+ ```
62
+ Candidates in candidates
63
+ rank video score decision
64
+ 1 candidate_003.mp4 +1.44 finish
65
+ 2 candidate_005.mp4 +1.23 stop
66
+ 3 candidate_006.mp4 +1.04 stop
67
+ 4 candidate_001.mp4 +0.84 stop
68
+ 5 candidate_002.mp4 -0.21 stop
69
+ 6 candidate_004.mp4 -0.48 stop
70
+ 7 candidate_000.mp4 -1.57 stop
71
+ 8 candidate_007.mp4 -13.44 stop
72
+
73
+ Finish 1 of 8: candidates/candidate_003.mp4
74
+ ```
75
+
76
+ These are 8 real MAGI-1 4.5B candidates of one Physics-IQ scenario. Candidate 7 barely moves, so it scores lowest.
77
+
78
+ More ways to call it.
79
+
80
+ ```bash
81
+ prune-early seed0.mp4 seed1.mp4 seed2.mp4 seed3.mp4 --keep 2 # list the videos, finish 2
82
+ prune-early "runs/*.mp4" --json # JSON for scripts
83
+ prune-early candidates/ --quiet # only the paths to finish
84
+ python -m prune_early candidates/ # same as prune-early
85
+ ```
86
+
87
+ ## Use it from Python
88
+
89
+ ```python
90
+ import prune_early
91
+
92
+ choice = prune_early.judge("candidates/", keep=1) # a folder, a pattern or a list of paths
93
+ print(choice) # the table above
94
+
95
+ choice.best # Path of the best candidate
96
+ choice.finish # paths to finish, best first
97
+ choice.stop # paths to stop
98
+ choice.scores # one score per candidate, in the order given, higher is better
99
+ choice.to_dict() # everything, ready for json.dump
100
+ ```
101
+
102
+ Shortcuts, if you only need one thing.
103
+
104
+ ```python
105
+ prune_early.score(["seed0.mp4", "seed1.mp4", "seed2.mp4"]) # one float per video, higher is better
106
+ prune_early.keep(["seed0.mp4", "seed1.mp4", "seed2.mp4"], 1) # indices to finish, best first
107
+ ```
108
+
109
+ Bad input raises `prune_early.PruneEarlyError` with a message that says what to fix, for example a missing file, a video OpenCV cannot read, or fewer than two candidates.
110
+
111
+ ## Things to know
112
+
113
+ - **Judge all candidates of a prompt together.** Each candidate is scored against the others, so the scores of one prompt cannot be compared with those of another.
114
+ - **Whole videos or just the first second both work.** Only the first second is read. To save GPU time, stop your generator after one second, judge, then continue only the kept candidates.
115
+ - **Score the frames as they will appear in the final video.** Encode the first second once, with the same codec and quality as your full videos. Re-compressing a clip changes the motion masks a little and can change the pick.
116
+ - **More candidates help.** The gain grows from 4 to 16 candidates.
117
+ - **It rewards agreement.** If most candidates make the same mistake, the judge keeps the mistake.
118
+
119
+ ## How it works
120
+
121
+ For each candidate the judge makes Physics-IQ-style motion masks of the first second (grayscale, blur, running background, threshold) and pools them to an 18×32 grid. It then computes three signals, how much of the frame moves, how much the moving area overlaps the other candidates' (consensus overlap), and how well the motion map correlates with theirs (consensus correlation). Each signal is rescaled within the prompt and the three are added. The judge was chosen on the released MAGI-1 24B videos and then frozen, so its settings never saw a test video. They ship with the package in `frozen_judge.json`.
122
+
123
+ ## Prune a real MAGI-1 run
124
+
125
+ The [GitHub repository](https://github.com/sohamkumar1703/prune-early) has `scripts/prune_magi.sh`, which runs N MAGI-1 seeds to their first second, judges them with this package, and resumes only the kept ones from where they paused.
126
+
127
+ ## Citation
128
+
129
+ ```bibtex
130
+ @misc{pruneearly2026,
131
+ title = {Prune Early: Judging Physics from the First Second of Autoregressive Video Generation},
132
+ author = {Kumar, Soham and Sathyanarayanan, Shreenidhi and Mukherjee, Aniruddha},
133
+ year = {2026},
134
+ url = {https://github.com/sohamkumar1703/prune-early}
135
+ }
136
+ ```
137
+
138
+ MIT license. Paper, code and results are on [GitHub](https://github.com/sohamkumar1703/prune-early).
@@ -0,0 +1,143 @@
1
+ # Prune Early: Judging Physics from the First Second of Autoregressive Video Generation
2
+
3
+ <p align="center">
4
+ <a href="paper/report/main.pdf"><img src="https://img.shields.io/badge/Paper-PDF-b31b1b" alt="Paper"></a>
5
+ <a href="paper/poster/poster.pdf"><img src="https://img.shields.io/badge/Poster-PDF-orange" alt="Poster"></a>
6
+ <a href="https://huggingface.co/datasets/Anates-Labs-Research/Physics-IQ-Verified"><img src="https://img.shields.io/badge/Benchmark-Physics--IQ%20Verified-yellow" alt="Physics-IQ Verified"></a>
7
+ <a href="https://github.com/SandAI-org/MAGI-1"><img src="https://img.shields.io/badge/Generator-MAGI--1-blue" alt="MAGI-1"></a>
8
+ </p>
9
+
10
+ Soham Kumar, Shreenidhi Sathyanarayanan, Aniruddha Mukherjee. Carnegie Mellon University.
11
+
12
+ Generate several videos, stop each after its **first second**, and finish only the one whose motion agrees most with the others. With MAGI-1 this gives more realistic physics than a random pick, beats the best published verifier, and costs **48% less GPU time** than finishing every candidate.
13
+
14
+ ## Latest News
15
+
16
+ - **Dec 2026.** Code, paper and poster released. `pip install prune-early` installs the judge, and `scripts/prune_magi.sh` runs the whole method with MAGI-1.
17
+
18
+ ## 1. About
19
+
20
+ Making several videos and keeping the best one gives more realistic physics, but every extra video costs a full run. MAGI-1 generates a video one second at a time, so we ask whether a judge can tell from the first second which candidates to keep, and stop the rest early.
21
+
22
+ Our judge needs no training. It reads where things move in the first second of each candidate and keeps the one whose motion agrees most with the others. We chose it on the released MAGI-1 24B videos, froze it, and tested it on 2,112 MAGI-1 4.5B-distill videos we generated for [Physics-IQ Verified](https://huggingface.co/datasets/Anates-Labs-Research/Physics-IQ-Verified).
23
+
24
+ ## 2. Method
25
+
26
+ <p align="center"><a href="figures/overview.png"><img src="figures/overview.png" width="100%" alt="Method overview"></a></p>
27
+
28
+ 1. Start N runs of MAGI-1 from the same input video, each with its own seed.
29
+ 2. When the first second is ready (24 frames, 45% of the GPU time of a run), turn each candidate into motion masks and pool them to an 18×32 grid.
30
+ 3. Score each candidate by three signals, how much of the frame moves (**area**), how much its moving area overlaps the others' (**consensus overlap**), and how well its motion map correlates with the others' (**consensus correlation**). Each is scaled within the prompt and the three are added.
31
+ 4. Finish the top K and stop the rest.
32
+
33
+ With 8 candidates and K = 1 this costs 8 × 0.45 + 0.55 = 4.15 full videos instead of 8. The judge itself takes about 1.4 s per prompt on a CPU.
34
+
35
+ ## 3. Results
36
+
37
+ Test set, 66 scenarios × 8 candidates of MAGI-1 4.5B-distill, scored with the official Physics-IQ Verified scorer.
38
+
39
+ | Pick 1 of 8 candidates at 1 s | Physics-IQ |
40
+ |---|---|
41
+ | Random | 44.51 |
42
+ | GeoPhys++ (best published verifier) | 45.29 |
43
+ | **Prune Early (ours)** | **48.97** (+4.46, 95% CI +2.49 to +6.61) |
44
+ | Oracle | 58.76 |
45
+
46
+ - Stopping the other 7 after one second saves **48% of GPU time** and still beats GeoPhys++ given the whole 5 s video (46.00).
47
+ - The gain holds on all three camera views and in every physics category, and grows with the number of candidates.
48
+
49
+ <p align="center"><a href="figures/curve.png"><img src="figures/curve.png" width="55%" alt="Quality against GPU time"></a></p>
50
+
51
+ <p align="center"><a href="figures/examples.png"><img src="figures/examples.png" width="100%" alt="Picks on three test scenarios"></a></p>
52
+
53
+ Picks on three test scenarios, with the Physics-IQ score of each pick. The last row is a failure. Details are in the [paper](paper/report/main.pdf).
54
+
55
+ ## 4. Quick start
56
+
57
+ ### 4.1 Install the judge
58
+
59
+ The judge runs on any computer with Python 3.9 or newer (Linux, macOS or Windows) and needs only a CPU.
60
+
61
+ ```bash
62
+ pip install prune-early
63
+ ```
64
+
65
+ Add `[exact]` (`pip install "prune-early[exact]"`) to get exactly the paper's scores, with the OpenCV version we used.
66
+
67
+ ### 4.2 Judge candidates you already have
68
+
69
+ Give it the candidates of **one** prompt, as a folder, a pattern or a list of videos. Whole videos or just their first second both work. It prints which ones to finish.
70
+
71
+ ```bash
72
+ prune-early candidates/ --keep 1
73
+ ```
74
+
75
+ The same from Python.
76
+
77
+ ```python
78
+ import prune_early
79
+
80
+ choice = prune_early.judge("candidates/", keep=1)
81
+ print(choice) # rank, score and finish or stop for each candidate
82
+ choice.best # the candidate to finish
83
+ ```
84
+
85
+ Run `prune-early --help` for more options, such as `--json` for scripts. The [package page](prune_early/README.md) has the full guide.
86
+
87
+ ### 4.3 Generate with MAGI-1 and prune early
88
+
89
+ This part runs on Linux with an NVIDIA GPU with at least 40 GB of memory (we used A100 40 GB) and [conda](https://docs.conda.io/en/latest/miniconda.html). It needs the repository.
90
+
91
+ ```bash
92
+ git clone https://github.com/sohamkumar1703/prune-early.git && cd prune-early
93
+ ```
94
+
95
+ One-time setup. It makes a conda environment `magi`, clones MAGI-1 into `external/` and downloads about 36 GB of weights.
96
+
97
+ ```bash
98
+ bash scripts/setup_magi.sh
99
+ ```
100
+
101
+ Then give it a prompt and an input video for MAGI-1 to continue. It makes the first second of 8 seeds, judges them, and finishes the best one.
102
+
103
+ ```bash
104
+ GPU=0 bash scripts/prune_magi.sh --prompt "A ball rolls off the table and falls to the floor." --prefix my_clip.mp4 --candidates 8 --keep 1 --out results
105
+ ```
106
+
107
+ The finished video is in `results/final/`, the first seconds in `results/first_second/`, and the judge's scores and timings in `results/result.json`. Each candidate is paused after its first second, and the kept one continues from there (`scripts/magi_resume.py`), so 8 candidates with `--keep 1` cost about 4.15 full videos instead of 8.
108
+
109
+ ## 5. Repository
110
+
111
+ ```
112
+ prune_early/ the judge, the prune-early package on PyPI with its command
113
+ tests/ tests of the package on small synthetic videos
114
+ scripts/ setup_magi.sh, prune_magi.sh (the method with MAGI-1 on a CUDA GPU) and magi_resume.py
115
+ get_started/ notebooks 1 to 7, a guided tour from the benchmark to choosing and testing the judge
116
+ figures/ images for this page
117
+ paper/ what produced the paper's results
118
+ report/ the paper (LaTeX source and PDF)
119
+ generation/ GPU scripts that made our 2,112 videos and ran the GPU baselines
120
+ analysis/ scoring and every table and figure of the paper
121
+ data/, outputs/ our videos, their scores and every result file the paper quotes
122
+ poster/ the poster (PDF)
123
+ ```
124
+
125
+ `prune_early/frozen_judge.py` and `frozen_judge.json` are the frozen judge. They have not changed since the judge was chosen, before any test video existed. Because they are frozen, `frozen_judge.json` still calls notebook 5 by its earlier name, 03b.
126
+
127
+ ## 6. Acknowledgements
128
+
129
+ We use, without changes, the [Physics-IQ scorer](https://github.com/google-deepmind/physics-IQ-benchmark), [MAGI-1](https://github.com/SandAI-org/MAGI-1), [GeoPhys](https://github.com/ChristianInterno/GeoPhys), V-JEPA 2, [VideoScore2](https://github.com/TIGER-AI-Lab/VideoScore2) and [TAPNet](https://github.com/google-deepmind/tapnet) (TRAJAN). Setup scripts clone them into `external/`. Our code is released under the MIT license (LICENSE). Physics-IQ videos, including the frames shown here, follow their own terms. This work was a course project for CMU 10-423/623/723 Generative AI. We used Claude to help write analysis code and draft text, and checked every script against a known answer.
130
+
131
+ ## 7. Citation
132
+
133
+ ```bibtex
134
+ @misc{pruneearly2026,
135
+ title = {Prune Early: Judging Physics from the First Second of Autoregressive Video Generation},
136
+ author = {Kumar, Soham and Sathyanarayanan, Shreenidhi and Mukherjee, Aniruddha},
137
+ year = {2026}
138
+ }
139
+ ```
140
+
141
+ ## 8. Contact
142
+
143
+ Please open a GitHub issue for questions about the code or the results.
@@ -0,0 +1,108 @@
1
+ # prune-early
2
+
3
+ **Generate several videos, stop each after its first second, and finish only the best one.**
4
+
5
+ `prune-early` is a small, training-free judge for best-of-N video generation. Give it the candidates you made for one prompt. It reads only their first second, scores how much of each frame moves and how well that motion agrees with the other candidates, and tells you which ones to finish. With MAGI-1, picking 1 of 8 this way scored +4.46 Physics-IQ points above a random pick and cost 48% less GPU time than finishing all 8.
6
+
7
+ <p align="center"><img src="https://raw.githubusercontent.com/sohamkumar1703/prune-early/main/figures/overview.png" width="100%" alt="Method overview"></p>
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install prune-early
13
+ ```
14
+
15
+ It needs Python 3.9 or newer and runs on a CPU. Its only dependencies are NumPy and OpenCV.
16
+
17
+ To get exactly the scores from the paper, install the OpenCV version we used. Newer versions decode videos very slightly differently, which moved scores by up to about 0.1 in our check (the pick stayed the same).
18
+
19
+ ```bash
20
+ pip install "prune-early[exact]"
21
+ ```
22
+
23
+ ## Use it from the command line
24
+
25
+ Point it at a folder with the candidates of **one** prompt.
26
+
27
+ ```bash
28
+ prune-early candidates/
29
+ ```
30
+
31
+ ```
32
+ Candidates in candidates
33
+ rank video score decision
34
+ 1 candidate_003.mp4 +1.44 finish
35
+ 2 candidate_005.mp4 +1.23 stop
36
+ 3 candidate_006.mp4 +1.04 stop
37
+ 4 candidate_001.mp4 +0.84 stop
38
+ 5 candidate_002.mp4 -0.21 stop
39
+ 6 candidate_004.mp4 -0.48 stop
40
+ 7 candidate_000.mp4 -1.57 stop
41
+ 8 candidate_007.mp4 -13.44 stop
42
+
43
+ Finish 1 of 8: candidates/candidate_003.mp4
44
+ ```
45
+
46
+ These are 8 real MAGI-1 4.5B candidates of one Physics-IQ scenario. Candidate 7 barely moves, so it scores lowest.
47
+
48
+ More ways to call it.
49
+
50
+ ```bash
51
+ prune-early seed0.mp4 seed1.mp4 seed2.mp4 seed3.mp4 --keep 2 # list the videos, finish 2
52
+ prune-early "runs/*.mp4" --json # JSON for scripts
53
+ prune-early candidates/ --quiet # only the paths to finish
54
+ python -m prune_early candidates/ # same as prune-early
55
+ ```
56
+
57
+ ## Use it from Python
58
+
59
+ ```python
60
+ import prune_early
61
+
62
+ choice = prune_early.judge("candidates/", keep=1) # a folder, a pattern or a list of paths
63
+ print(choice) # the table above
64
+
65
+ choice.best # Path of the best candidate
66
+ choice.finish # paths to finish, best first
67
+ choice.stop # paths to stop
68
+ choice.scores # one score per candidate, in the order given, higher is better
69
+ choice.to_dict() # everything, ready for json.dump
70
+ ```
71
+
72
+ Shortcuts, if you only need one thing.
73
+
74
+ ```python
75
+ prune_early.score(["seed0.mp4", "seed1.mp4", "seed2.mp4"]) # one float per video, higher is better
76
+ prune_early.keep(["seed0.mp4", "seed1.mp4", "seed2.mp4"], 1) # indices to finish, best first
77
+ ```
78
+
79
+ Bad input raises `prune_early.PruneEarlyError` with a message that says what to fix, for example a missing file, a video OpenCV cannot read, or fewer than two candidates.
80
+
81
+ ## Things to know
82
+
83
+ - **Judge all candidates of a prompt together.** Each candidate is scored against the others, so the scores of one prompt cannot be compared with those of another.
84
+ - **Whole videos or just the first second both work.** Only the first second is read. To save GPU time, stop your generator after one second, judge, then continue only the kept candidates.
85
+ - **Score the frames as they will appear in the final video.** Encode the first second once, with the same codec and quality as your full videos. Re-compressing a clip changes the motion masks a little and can change the pick.
86
+ - **More candidates help.** The gain grows from 4 to 16 candidates.
87
+ - **It rewards agreement.** If most candidates make the same mistake, the judge keeps the mistake.
88
+
89
+ ## How it works
90
+
91
+ For each candidate the judge makes Physics-IQ-style motion masks of the first second (grayscale, blur, running background, threshold) and pools them to an 18×32 grid. It then computes three signals, how much of the frame moves, how much the moving area overlaps the other candidates' (consensus overlap), and how well the motion map correlates with theirs (consensus correlation). Each signal is rescaled within the prompt and the three are added. The judge was chosen on the released MAGI-1 24B videos and then frozen, so its settings never saw a test video. They ship with the package in `frozen_judge.json`.
92
+
93
+ ## Prune a real MAGI-1 run
94
+
95
+ The [GitHub repository](https://github.com/sohamkumar1703/prune-early) has `scripts/prune_magi.sh`, which runs N MAGI-1 seeds to their first second, judges them with this package, and resumes only the kept ones from where they paused.
96
+
97
+ ## Citation
98
+
99
+ ```bibtex
100
+ @misc{pruneearly2026,
101
+ title = {Prune Early: Judging Physics from the First Second of Autoregressive Video Generation},
102
+ author = {Kumar, Soham and Sathyanarayanan, Shreenidhi and Mukherjee, Aniruddha},
103
+ year = {2026},
104
+ url = {https://github.com/sohamkumar1703/prune-early}
105
+ }
106
+ ```
107
+
108
+ MIT license. Paper, code and results are on [GitHub](https://github.com/sohamkumar1703/prune-early).
@@ -0,0 +1,23 @@
1
+ """Prune Early: decide which video-generation candidates to finish, from their first second.
2
+
3
+ Generate several candidates for the same prompt, stop each after its first second, and keep the ones
4
+ whose motion agrees most with the others. Only the kept candidates are finished.
5
+
6
+ import prune_early
7
+
8
+ choice = prune_early.judge("candidates/", keep=1) # a folder, a pattern or a list of videos
9
+ print(choice) # ranks, scores and finish / stop for each
10
+ choice.best # the candidate to finish
11
+
12
+ The videos can be the first second alone or whole videos (only the first second is read).
13
+ Judge all candidates of a prompt together, because each one is compared with the others.
14
+
15
+ The judge is frozen. Its settings are in frozen_judge.json and were not changed after testing began.
16
+ """
17
+ from prune_early._api import Choice, PruneEarlyError, VideoError, find_videos, judge, keep, score
18
+ from prune_early.early_signals import motion_grid
19
+ from prune_early.frozen_judge import first_second_grids, score_from_grids, signals_from_grids
20
+
21
+ __version__ = "1.0.0"
22
+ __all__ = ["judge", "score", "keep", "Choice", "PruneEarlyError", "VideoError", "find_videos",
23
+ "score_from_grids", "signals_from_grids", "first_second_grids", "motion_grid", "__version__"]
@@ -0,0 +1,3 @@
1
+ from prune_early.cli import main
2
+
3
+ main()
@@ -0,0 +1,174 @@
1
+ """The friendly front door to the frozen judge: input checks, clear errors and a readable result.
2
+
3
+ Nothing here changes what the judge decides. Every score comes from frozen_judge.score_from_grids,
4
+ and the ranking is the same stable sort as frozen_judge.keep.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import glob
9
+ import os
10
+ import re
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Iterable, List, Sequence, Union
14
+
15
+ import cv2
16
+ import numpy as np
17
+
18
+ from prune_early import frozen_judge
19
+
20
+ VIDEO_EXTENSIONS = (".mp4", ".mov", ".avi", ".mkv", ".webm", ".m4v")
21
+ PathLike = Union[str, os.PathLike]
22
+
23
+
24
+ class PruneEarlyError(ValueError):
25
+ """A problem with the input, explained in plain words."""
26
+
27
+
28
+ class VideoError(PruneEarlyError):
29
+ """A video that is missing, unreadable or too short."""
30
+
31
+
32
+ def _natural_key(path: Path):
33
+ """Sort seed2 before seed10."""
34
+ return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", str(path))]
35
+
36
+
37
+ def find_videos(videos: Union[PathLike, Iterable[PathLike]]) -> List[Path]:
38
+ """Turn a folder, a glob pattern or a list of paths into a list of video files.
39
+
40
+ A folder gives every video file directly inside it, sorted naturally (seed2 before seed10).
41
+ A pattern such as "runs/*.mp4" is expanded. A list keeps its order.
42
+ """
43
+ items = [videos] if isinstance(videos, (str, os.PathLike)) else list(videos)
44
+ found: List[Path] = []
45
+ for item in items:
46
+ path = Path(item).expanduser()
47
+ if path.is_dir():
48
+ inside = sorted((p for p in path.iterdir() if p.suffix.lower() in VIDEO_EXTENSIONS), key=_natural_key)
49
+ if not inside:
50
+ raise VideoError(f"no video files in the folder {path} (looked for {', '.join(VIDEO_EXTENSIONS)})")
51
+ found.extend(inside)
52
+ elif path.exists():
53
+ found.append(path)
54
+ elif any(c in str(item) for c in "*?["):
55
+ matches = sorted((Path(p) for p in glob.glob(str(path))), key=_natural_key)
56
+ if not matches:
57
+ raise VideoError(f"no files match {item}")
58
+ found.extend(matches)
59
+ else:
60
+ raise VideoError(f"video not found: {item}")
61
+ return found
62
+
63
+
64
+ def _check_readable(path: Path) -> None:
65
+ video = cv2.VideoCapture(str(path))
66
+ ok_first, _ = video.read()
67
+ ok_second, _ = video.read()
68
+ video.release()
69
+ if not ok_first:
70
+ raise VideoError(f"OpenCV cannot read {path}. If it plays elsewhere, re-encode it to H.264, for example "
71
+ f"ffmpeg -i {path.name} -c:v libx264 fixed.mp4")
72
+ if not ok_second:
73
+ raise VideoError(f"{path} has only one frame, and the judge needs motion, so at least two frames")
74
+
75
+
76
+ def _prepare(videos, keep=None) -> List[Path]:
77
+ paths = find_videos(videos)
78
+ if len(paths) < 2:
79
+ raise PruneEarlyError("give at least two candidates of the same prompt, because the judge compares them "
80
+ f"with each other (got {len(paths)})")
81
+ if keep is not None:
82
+ if isinstance(keep, bool) or not isinstance(keep, (int, np.integer)):
83
+ raise PruneEarlyError(f"keep must be a whole number, got {keep!r}")
84
+ if not 1 <= keep <= len(paths):
85
+ raise PruneEarlyError(f"keep must be between 1 and the number of candidates ({len(paths)}), got {keep}")
86
+ for path in paths:
87
+ _check_readable(path)
88
+ return paths
89
+
90
+
91
+ @dataclass
92
+ class Choice:
93
+ """What the judge decided for one prompt.
94
+
95
+ videos the candidates, in the order given
96
+ scores one score per candidate, higher is better (a sum of three within-prompt z-scores)
97
+ ranking indices of all candidates, best first
98
+ keep how many to finish
99
+ """
100
+ videos: List[Path]
101
+ scores: List[float]
102
+ ranking: List[int]
103
+ keep: int = 1
104
+ signals: dict = field(default_factory=dict, repr=False)
105
+
106
+ @property
107
+ def kept(self) -> List[int]:
108
+ """Indices of the candidates to finish, best first."""
109
+ return self.ranking[:self.keep]
110
+
111
+ @property
112
+ def finish(self) -> List[Path]:
113
+ """The videos to finish, best first."""
114
+ return [self.videos[i] for i in self.kept]
115
+
116
+ @property
117
+ def stop(self) -> List[Path]:
118
+ """The videos to stop, in the order given."""
119
+ kept = set(self.kept)
120
+ return [v for i, v in enumerate(self.videos) if i not in kept]
121
+
122
+ @property
123
+ def best(self) -> Path:
124
+ """The single best candidate."""
125
+ return self.videos[self.ranking[0]]
126
+
127
+ def to_dict(self) -> dict:
128
+ return {"keep": self.keep,
129
+ "finish": [str(v) for v in self.finish],
130
+ "stop": [str(v) for v in self.stop],
131
+ "candidates": [{"video": str(self.videos[i]), "rank": r + 1, "score": round(self.scores[i], 4),
132
+ "decision": "finish" if r < self.keep else "stop",
133
+ "signals": {k: float(v[i]) for k, v in self.signals.items()}}
134
+ for r, i in enumerate(self.ranking)]}
135
+
136
+ def __str__(self) -> str:
137
+ parents = {v.parent for v in self.videos}
138
+ names = [v.name if len(parents) == 1 else str(v) for v in self.videos]
139
+ width = max(len(n) for n in names + ["video"])
140
+ lines = [f"Candidates in {next(iter(parents))}"] if len(parents) == 1 else []
141
+ lines.append(f"{'rank':>4} {'video':<{width}} {'score':>7} decision")
142
+ for r, i in enumerate(self.ranking):
143
+ lines.append(f"{r + 1:>4} {names[i]:<{width}} {self.scores[i]:+7.2f} "
144
+ f"{'finish' if r < self.keep else 'stop'}")
145
+ return "\n".join(lines)
146
+
147
+
148
+ def judge(videos, keep: int = 1) -> Choice:
149
+ """Judge the candidates of ONE prompt from their first second and decide which to finish.
150
+
151
+ videos a folder, a glob pattern such as "runs/*.mp4", or a list of video paths. They can be whole
152
+ videos or just their first second, only the first second is read.
153
+ keep how many candidates to finish (default 1)
154
+
155
+ >>> choice = prune_early.judge("candidates/", keep=1)
156
+ >>> print(choice) # a table of ranks, scores and decisions
157
+ >>> choice.best # path of the best candidate
158
+ """
159
+ paths = _prepare(videos, keep)
160
+ grids = [frozen_judge.first_second_grids(p) for p in paths]
161
+ scores = np.asarray(frozen_judge.score_from_grids(grids), dtype=float)
162
+ ranking = [int(i) for i in np.argsort(-scores, kind="stable")]
163
+ return Choice(videos=paths, scores=[float(s) for s in scores], ranking=ranking, keep=int(keep),
164
+ signals=frozen_judge.signals_from_grids(grids))
165
+
166
+
167
+ def score(videos) -> List[float]:
168
+ """One score per candidate of a single prompt, in the order given. Higher is better."""
169
+ return judge(videos).scores
170
+
171
+
172
+ def keep(videos, k: int = 1) -> List[int]:
173
+ """Indices of the k candidates to finish, best first."""
174
+ return judge(videos, keep=k).kept
@@ -0,0 +1,51 @@
1
+ """Command line entry point, installed as `prune-early` (also `python -m prune_early`).
2
+
3
+ prune-early candidates/ # every video in a folder
4
+ prune-early seed0.mp4 seed1.mp4 seed2.mp4 --keep 2
5
+ prune-early "runs/*.mp4" --json # machine-readable output
6
+
7
+ Scores every candidate of one prompt from its first second and prints which ones to finish.
8
+ """
9
+ import argparse
10
+ import json
11
+ import sys
12
+
13
+ import prune_early
14
+
15
+ EXAMPLES = """examples:
16
+ prune-early candidates/ judge every video in a folder, finish 1
17
+ prune-early seed0.mp4 seed1.mp4 seed2.mp4 --keep 2
18
+ prune-early "runs/*.mp4" --json print JSON for scripts
19
+
20
+ Give the candidates of ONE prompt. Whole videos or just their first second both work.
21
+ """
22
+
23
+
24
+ def main(argv=None):
25
+ parser = argparse.ArgumentParser(
26
+ prog="prune-early", epilog=EXAMPLES, formatter_class=argparse.RawDescriptionHelpFormatter,
27
+ description="Pick which candidates of one prompt to finish, from their first second.")
28
+ parser.add_argument("videos", nargs="+", help="candidate videos, a folder of them, or a pattern like 'runs/*.mp4'")
29
+ parser.add_argument("-k", "--keep", type=int, default=1, help="how many candidates to finish (default 1)")
30
+ parser.add_argument("--json", action="store_true", help="print the result as JSON")
31
+ parser.add_argument("-q", "--quiet", action="store_true", help="print only the videos to finish, one per line")
32
+ parser.add_argument("-V", "--version", action="version", version=f"prune-early {prune_early.__version__}")
33
+ args = parser.parse_args(argv)
34
+
35
+ try:
36
+ choice = prune_early.judge(args.videos, keep=args.keep)
37
+ except prune_early.PruneEarlyError as error:
38
+ print(f"prune-early: error: {error}", file=sys.stderr)
39
+ sys.exit(2)
40
+
41
+ if args.json:
42
+ print(json.dumps(choice.to_dict(), indent=2))
43
+ elif args.quiet:
44
+ print("\n".join(str(v) for v in choice.finish))
45
+ else:
46
+ print(choice)
47
+ print(f"\nFinish {choice.keep} of {len(choice.videos)}: " + ", ".join(str(v) for v in choice.finish))
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main()
@@ -0,0 +1,149 @@
1
+ """
2
+ Early-judge signals computed from the first seconds of each candidate, for step 3.
3
+
4
+ Two families:
5
+ per-patch signals from GeoPhys's released per-patch steps: for every 16x16 patch, how its
6
+ features move frame to frame (speed, turning, acceleration, ...), then
7
+ summarised over the patches (mean, top 25 %, a middle band, ...)
8
+ pixel motion from Physics-IQ-style motion masks (blur, running average, threshold):
9
+ how much moves, where, whether it agrees with where the OTHER attempts move
10
+ (consensus), and whether it continues where things moved in the real past
11
+
12
+ Every signal is returned as a 198 x 16 table, rescaled within each scenario (median 0, typical
13
+ spread 1) so signals can be compared and added. Direction is not fixed here: a tuning step decides
14
+ whether low or high is good.
15
+ """
16
+ from pathlib import Path
17
+
18
+ import cv2
19
+ import numpy as np
20
+
21
+
22
+ # ------------------------------------------------------------- per-patch --
23
+ def per_patch_signals(seconds, stores, scenarios):
24
+ """All GeoPhys per-patch signals over the first `seconds` (12 frames per second).
25
+
26
+ Careful: GeoPhys's released "spd" steps are divided by each patch's mean speed over the WHOLE
27
+ video, which is information from the future for an early judge. So we never read them: our
28
+ "spd" is rebuilt from the raw steps, divided by the mean speed over the first `seconds` only."""
29
+ from geophys import members as geophys_members
30
+ from geophys.signals import token_signals, token_reduce
31
+ from geophys.ensemble import z_mad
32
+ frames = int(round(12 * seconds))
33
+ index = {s: i for i, s in enumerate(scenarios)}
34
+ pool = {}
35
+ for backbone in ("dinov2", "dinov3", "cornet", "vonenet"):
36
+ for prep in ("direct", "hf"):
37
+ for variant in ("raw", "l2", "spd"):
38
+ tables = {}
39
+ for half in ("v2v", "v2v16"):
40
+ store = geophys_members.open_store(half, backbone, prep, stores)
41
+ steps = store.tokens("raw" if variant == "spd" else variant)
42
+ if steps is None: # not downloaded for this store
43
+ break
44
+ sq = np.array(steps[0][:, 0, :, :frames - 1], np.float32)
45
+ dot = np.array(steps[1][:, 0, :, :frames - 2], np.float32)
46
+ sq[sq == 0] = np.nan
47
+ dot[np.isnan(sq[..., :-1])] = np.nan
48
+ if variant == "spd": # divide by each patch's speed so far, not the whole video's
49
+ speed = np.nanmean(np.sqrt(np.clip(sq, 0, None)), axis=-1, keepdims=True) + 1e-8
50
+ sq, dot = sq / speed ** 2, dot / speed ** 2
51
+ for signal, per_patch in token_signals(sq, dot).items():
52
+ for summary, values in token_reduce(per_patch).items():
53
+ table = tables.setdefault(f"{backbone} {prep} patch-{variant} {signal} {summary}",
54
+ np.full((len(scenarios), 16), np.nan))
55
+ for entry in store.meta["index"]:
56
+ table[index[entry["scen"]], entry["cand"]] = values[entry["vi"]]
57
+ for name, table in tables.items():
58
+ if np.isfinite(table).mean() > 0.9:
59
+ pool[name] = np.nan_to_num(z_mad(table))
60
+ return pool
61
+
62
+
63
+ # ---------------------------------------------------------- pixel motion --
64
+ WIDTH, HEIGHT, GRID_H, GRID_W = 480, 270, 18, 32
65
+ _KERNEL = np.ones((5, 5), np.uint8)
66
+
67
+
68
+ def motion_grid(path, max_frames=None):
69
+ """Physics-IQ's motion mask recipe at 480x270, pooled to an 18 x 32 grid of
70
+ 'fraction of pixels moving', one grid per frame."""
71
+ video = cv2.VideoCapture(str(path))
72
+ frames = []
73
+ while True:
74
+ ok, frame = video.read()
75
+ if not ok:
76
+ break
77
+ small = cv2.resize(frame, (WIDTH, HEIGHT), interpolation=cv2.INTER_AREA)
78
+ frames.append(cv2.GaussianBlur(cv2.cvtColor(small, cv2.COLOR_BGR2GRAY), (5, 5), 0))
79
+ if max_frames and len(frames) >= max_frames:
80
+ break
81
+ video.release()
82
+ background = frames[0].astype("float")
83
+ grids = [np.zeros((GRID_H, GRID_W), np.float32)]
84
+ for gray in frames[1:]:
85
+ cv2.accumulateWeighted(gray, background, 0.3)
86
+ mask = cv2.threshold(cv2.absdiff(gray, cv2.convertScaleAbs(background)), 10, 255, cv2.THRESH_BINARY)[1]
87
+ mask = cv2.morphologyEx(cv2.morphologyEx(mask, cv2.MORPH_OPEN, _KERNEL), cv2.MORPH_CLOSE, _KERNEL)
88
+ grids.append(cv2.resize((mask > 0).astype(np.float32), (GRID_W, GRID_H), interpolation=cv2.INTER_AREA))
89
+ return np.stack(grids)
90
+
91
+
92
+ def all_motion_grids(scenarios, candidates_folder, conditioning_folder, cache_file, n_jobs=8):
93
+ """Motion grids of the first 2.5 s of every attempt and the last 3 s of every real past.
94
+ Cached to one file (about 4 MB); the first run takes about 15 minutes."""
95
+ cache_file = Path(cache_file)
96
+ if cache_file.exists():
97
+ saved = np.load(cache_file)
98
+ return saved["attempts"], saved["past"]
99
+ from joblib import Parallel, delayed
100
+ conditioning_folder, candidates_folder = Path(conditioning_folder), Path(candidates_folder)
101
+ past_paths = [next(conditioning_folder.glob(f"{s.split('_')[0]}_*take-1*.mp4")) for s in scenarios]
102
+ past = Parallel(n_jobs=n_jobs)(delayed(motion_grid)(p) for p in past_paths)
103
+ past = np.stack([g[-90:] if len(g) >= 90 else np.pad(g, ((90 - len(g), 0), (0, 0), (0, 0))) for g in past])
104
+ attempt_paths = [candidates_folder / s / f"candidate_{c:03d}.mp4" for s in scenarios for c in range(16)]
105
+ attempts = Parallel(n_jobs=n_jobs, batch_size=16)(delayed(motion_grid)(p, 60) for p in attempt_paths)
106
+ attempts = np.stack(attempts).reshape(len(scenarios), 16, 60, GRID_H, GRID_W)
107
+ attempts = (attempts * 255).round().astype(np.uint8)
108
+ past = (past * 255).round().astype(np.uint8)
109
+ cache_file.parent.mkdir(parents=True, exist_ok=True)
110
+ np.savez_compressed(cache_file, attempts=attempts, past=past)
111
+ return attempts, past
112
+
113
+
114
+ def _corr(x, y):
115
+ x = x - x.mean(); y = y - y.mean()
116
+ d = np.sqrt((x * x).sum() * (y * y).sum())
117
+ return float((x * y).sum() / d) if d > 0 else 0.0
118
+
119
+
120
+ def pixel_motion_signals(attempts, past, seconds):
121
+ """13 signals from the motion grids over the first `seconds` (24 frames per second)."""
122
+ from geophys.ensemble import z_mad
123
+ A = attempts[:, :, 1:int(round(24 * seconds))].astype(np.float32) / 255 # skip frame 0 (always empty)
124
+ R = past[:, -30:].astype(np.float32) / 255 # last second of the real past
125
+ n, c = A.shape[:2]
126
+ names = ["amount", "amount_first_half", "amount_second_half", "frozen_frames", "peak", "area",
127
+ "overlap_with_past", "corr_with_past", "outside_past", "consensus_corr", "consensus_overlap"]
128
+ out = {k: np.zeros((n, c)) for k in names}
129
+ for i in range(n):
130
+ past_map = R[i].sum(0); past_area = R[i].max(0) > 0.1
131
+ past_near = cv2.dilate(past_area.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0
132
+ maps = A[i].sum(1); areas = A[i].max(1) > 0.1
133
+ for k in range(c):
134
+ a = A[i, k]; per_frame = a.mean((1, 2)); half = len(a) // 2
135
+ out["amount"][i, k] = a.mean()
136
+ out["amount_first_half"][i, k] = a[:half].mean()
137
+ out["amount_second_half"][i, k] = a[half:].mean()
138
+ out["frozen_frames"][i, k] = (per_frame < 0.001).mean()
139
+ out["peak"][i, k] = per_frame.max()
140
+ out["area"][i, k] = areas[k].mean()
141
+ union = (areas[k] | past_area).sum()
142
+ out["overlap_with_past"][i, k] = (areas[k] & past_area).sum() / union if union else 0
143
+ out["corr_with_past"][i, k] = _corr(maps[k], past_map)
144
+ out["outside_past"][i, k] = (maps[k] * ~past_near).sum() / (maps[k].sum() + 1e-9) if past_area.any() else 0
145
+ others = [o for o in range(c) if o != k]
146
+ out["consensus_corr"][i, k] = np.mean([_corr(maps[k], maps[o]) for o in others])
147
+ out["consensus_overlap"][i, k] = np.mean([(areas[k] & areas[o]).sum() / max((areas[k] | areas[o]).sum(), 1)
148
+ for o in others])
149
+ return {f"pixel motion {k}": np.nan_to_num(z_mad(v)) for k, v in out.items()}
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "pixel-motion consensus judge",
3
+ "frozen_on": "2026-10-28",
4
+ "chosen_on": "all 198 Physics-IQ Verified scenarios, 16 released MAGI-1 24B V2V candidates each (GeoPhys release); greedy choice of 3 signals and their directions by within-scenario Spearman agreement with the true score (notebook 03b's choose())",
5
+ "seconds": 1.0,
6
+ "assumed_fps": 24,
7
+ "motion_mask": "Physics-IQ recipe at 480x270: grayscale, 5x5 Gaussian blur, running average 0.3, absdiff threshold 10, 5x5 open then close; pooled to an 18x32 grid (prune_early/early_signals.py, motion_grid)",
8
+ "area_threshold": 0.1,
9
+ "signals": [
10
+ {
11
+ "name": "consensus_overlap",
12
+ "prefer": "higher"
13
+ },
14
+ {
15
+ "name": "area",
16
+ "prefer": "higher"
17
+ },
18
+ {
19
+ "name": "consensus_corr",
20
+ "prefer": "higher"
21
+ }
22
+ ],
23
+ "combine": "sum of within-scenario robust z-scores ((x - median) / (1.4826 * MAD), clipped to +-30)",
24
+ "keep_rule": "finish the K candidates with the highest total; K = 4 of 16 is the main setting",
25
+ "evidence": "10 tune/test splits by experiment (notebook 03b): +1.21 points over equal-compute best-of-M at keep 4 (9/10 splits > 0), +1.18 at keep 8 (9/10). In-sample on all 198 after freezing: +1.02 / +0.99 (not a test).",
26
+ "input_rule": "Score the first second exactly as it will appear in the final candidate video: frames encoded once, with the same codec and quality as the full videos. Never score a clip that was decoded and compressed again (in a check, double compression changed 16 % of the keep-4 choices).",
27
+ "checks": "Frozen code reproduces the tuned signals exactly (198/198 identical keep-4 sets on the tuning grids); from the raw released MP4s it keeps the same 4 in 99.5 % of picks (in-sample gain +1.11 at keep 4, +1.01 at keep 8; not a test)."
28
+ }
@@ -0,0 +1,72 @@
1
+ """
2
+ The frozen early judge (step 4). Chosen on 2026-10-28 on all 198 released MAGI-1 scenarios, then
3
+ fixed: do NOT change anything in this file or in frozen_judge.json once new videos exist.
4
+
5
+ What it does, for one scenario: read the first second of each candidate, make Physics-IQ-style
6
+ motion masks, and score each candidate by three signals (all "higher is better"):
7
+ consensus_overlap how much the area where it moves overlaps where the other candidates move
8
+ area how much of the frame moves at all
9
+ consensus_corr the same as consensus_overlap, but weighting by how much moves where
10
+ Each signal is rescaled within the scenario (median 0, typical spread 1) and the three are added.
11
+ Keep the K candidates with the highest total.
12
+
13
+ Only the first second of the candidates is used: no real future frames, no later frames.
14
+
15
+ from prune_early import frozen_judge
16
+ scores = frozen_judge.score(list_of_16_mp4_paths) # higher = better
17
+ keep = frozen_judge.keep(list_of_16_mp4_paths, 4) # indices of the 4 to finish
18
+ """
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import cv2
23
+ import numpy as np
24
+
25
+ from prune_early.early_signals import _corr, motion_grid
26
+
27
+ SPEC = json.load(open(Path(__file__).with_name("frozen_judge.json")))
28
+
29
+
30
+ def first_second_grids(path, seconds=SPEC["seconds"]):
31
+ """Motion grids (18 x 32, fraction of pixels moving) for the first `seconds` of one video."""
32
+ fps = cv2.VideoCapture(str(path)).get(cv2.CAP_PROP_FPS) or SPEC["assumed_fps"]
33
+ return motion_grid(path, max_frames=int(round(fps * seconds)))
34
+
35
+
36
+ def signals_from_grids(grids):
37
+ """grids: one [frames, 18, 32] array per candidate. Returns {signal: [n_candidates]} (raw values)."""
38
+ moving = [g[1:].astype(np.float32) for g in grids] # frame 0 has no motion; float32 as when tuned
39
+ maps = [m.sum(0) for m in moving] # where, and how much, each candidate moves
40
+ areas = [m.max(0) > SPEC["area_threshold"] for m in moving] # where it moves at all
41
+ n = len(grids)
42
+ out = {"consensus_overlap": np.zeros(n), "area": np.zeros(n), "consensus_corr": np.zeros(n)}
43
+ for k in range(n):
44
+ others = [o for o in range(n) if o != k]
45
+ out["area"][k] = areas[k].mean()
46
+ out["consensus_corr"][k] = np.mean([_corr(maps[k], maps[o]) for o in others])
47
+ out["consensus_overlap"][k] = np.mean([(areas[k] & areas[o]).sum() / max((areas[k] | areas[o]).sum(), 1)
48
+ for o in others])
49
+ return out
50
+
51
+
52
+ def robust_z(values):
53
+ """Within-scenario rescaling: (x - median) / (1.4826 * MAD), clipped to +-30 (GeoPhys's z_mad)."""
54
+ values = np.asarray(values, np.float64)
55
+ median = np.median(values)
56
+ spread = 1.4826 * np.median(np.abs(values - median)) + 1e-9
57
+ return np.clip((values - median) / spread, -30, 30)
58
+
59
+
60
+ def score_from_grids(grids):
61
+ raw = signals_from_grids(grids)
62
+ return sum(robust_z(raw[s["name"]]) * (1 if s["prefer"] == "higher" else -1) for s in SPEC["signals"])
63
+
64
+
65
+ def score(paths):
66
+ """One score per candidate video of a single scenario; higher = better. Needs all candidates together."""
67
+ return score_from_grids([first_second_grids(p) for p in paths])
68
+
69
+
70
+ def keep(paths, k):
71
+ """Indices of the k candidates to finish (best first)."""
72
+ return list(np.argsort(-score(paths), kind="stable")[:k])
File without changes
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: prune-early
3
+ Version: 1.0.0
4
+ Summary: Pick which video-generation candidates to finish from their first second, and stop the rest early
5
+ Author: Soham Kumar, Shreenidhi Sathyanarayanan, Aniruddha Mukherjee
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/sohamkumar1703/prune-early
8
+ Project-URL: Paper, https://github.com/sohamkumar1703/prune-early/blob/main/paper/report/main.pdf
9
+ Project-URL: Issues, https://github.com/sohamkumar1703/prune-early/issues
10
+ Keywords: video generation,best-of-n,verifier,physics,MAGI-1,autoregressive,pruning
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Topic :: Multimedia :: Video
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: numpy>=1.21
24
+ Requires-Dist: opencv-python-headless>=4.5
25
+ Provides-Extra: exact
26
+ Requires-Dist: opencv-python-headless==5.0.0.93; extra == "exact"
27
+ Provides-Extra: test
28
+ Requires-Dist: pytest>=7; extra == "test"
29
+ Dynamic: license-file
30
+
31
+ # prune-early
32
+
33
+ **Generate several videos, stop each after its first second, and finish only the best one.**
34
+
35
+ `prune-early` is a small, training-free judge for best-of-N video generation. Give it the candidates you made for one prompt. It reads only their first second, scores how much of each frame moves and how well that motion agrees with the other candidates, and tells you which ones to finish. With MAGI-1, picking 1 of 8 this way scored +4.46 Physics-IQ points above a random pick and cost 48% less GPU time than finishing all 8.
36
+
37
+ <p align="center"><img src="https://raw.githubusercontent.com/sohamkumar1703/prune-early/main/figures/overview.png" width="100%" alt="Method overview"></p>
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install prune-early
43
+ ```
44
+
45
+ It needs Python 3.9 or newer and runs on a CPU. Its only dependencies are NumPy and OpenCV.
46
+
47
+ To get exactly the scores from the paper, install the OpenCV version we used. Newer versions decode videos very slightly differently, which moved scores by up to about 0.1 in our check (the pick stayed the same).
48
+
49
+ ```bash
50
+ pip install "prune-early[exact]"
51
+ ```
52
+
53
+ ## Use it from the command line
54
+
55
+ Point it at a folder with the candidates of **one** prompt.
56
+
57
+ ```bash
58
+ prune-early candidates/
59
+ ```
60
+
61
+ ```
62
+ Candidates in candidates
63
+ rank video score decision
64
+ 1 candidate_003.mp4 +1.44 finish
65
+ 2 candidate_005.mp4 +1.23 stop
66
+ 3 candidate_006.mp4 +1.04 stop
67
+ 4 candidate_001.mp4 +0.84 stop
68
+ 5 candidate_002.mp4 -0.21 stop
69
+ 6 candidate_004.mp4 -0.48 stop
70
+ 7 candidate_000.mp4 -1.57 stop
71
+ 8 candidate_007.mp4 -13.44 stop
72
+
73
+ Finish 1 of 8: candidates/candidate_003.mp4
74
+ ```
75
+
76
+ These are 8 real MAGI-1 4.5B candidates of one Physics-IQ scenario. Candidate 7 barely moves, so it scores lowest.
77
+
78
+ More ways to call it.
79
+
80
+ ```bash
81
+ prune-early seed0.mp4 seed1.mp4 seed2.mp4 seed3.mp4 --keep 2 # list the videos, finish 2
82
+ prune-early "runs/*.mp4" --json # JSON for scripts
83
+ prune-early candidates/ --quiet # only the paths to finish
84
+ python -m prune_early candidates/ # same as prune-early
85
+ ```
86
+
87
+ ## Use it from Python
88
+
89
+ ```python
90
+ import prune_early
91
+
92
+ choice = prune_early.judge("candidates/", keep=1) # a folder, a pattern or a list of paths
93
+ print(choice) # the table above
94
+
95
+ choice.best # Path of the best candidate
96
+ choice.finish # paths to finish, best first
97
+ choice.stop # paths to stop
98
+ choice.scores # one score per candidate, in the order given, higher is better
99
+ choice.to_dict() # everything, ready for json.dump
100
+ ```
101
+
102
+ Shortcuts, if you only need one thing.
103
+
104
+ ```python
105
+ prune_early.score(["seed0.mp4", "seed1.mp4", "seed2.mp4"]) # one float per video, higher is better
106
+ prune_early.keep(["seed0.mp4", "seed1.mp4", "seed2.mp4"], 1) # indices to finish, best first
107
+ ```
108
+
109
+ Bad input raises `prune_early.PruneEarlyError` with a message that says what to fix, for example a missing file, a video OpenCV cannot read, or fewer than two candidates.
110
+
111
+ ## Things to know
112
+
113
+ - **Judge all candidates of a prompt together.** Each candidate is scored against the others, so the scores of one prompt cannot be compared with those of another.
114
+ - **Whole videos or just the first second both work.** Only the first second is read. To save GPU time, stop your generator after one second, judge, then continue only the kept candidates.
115
+ - **Score the frames as they will appear in the final video.** Encode the first second once, with the same codec and quality as your full videos. Re-compressing a clip changes the motion masks a little and can change the pick.
116
+ - **More candidates help.** The gain grows from 4 to 16 candidates.
117
+ - **It rewards agreement.** If most candidates make the same mistake, the judge keeps the mistake.
118
+
119
+ ## How it works
120
+
121
+ For each candidate the judge makes Physics-IQ-style motion masks of the first second (grayscale, blur, running background, threshold) and pools them to an 18×32 grid. It then computes three signals, how much of the frame moves, how much the moving area overlaps the other candidates' (consensus overlap), and how well the motion map correlates with theirs (consensus correlation). Each signal is rescaled within the prompt and the three are added. The judge was chosen on the released MAGI-1 24B videos and then frozen, so its settings never saw a test video. They ship with the package in `frozen_judge.json`.
122
+
123
+ ## Prune a real MAGI-1 run
124
+
125
+ The [GitHub repository](https://github.com/sohamkumar1703/prune-early) has `scripts/prune_magi.sh`, which runs N MAGI-1 seeds to their first second, judges them with this package, and resumes only the kept ones from where they paused.
126
+
127
+ ## Citation
128
+
129
+ ```bibtex
130
+ @misc{pruneearly2026,
131
+ title = {Prune Early: Judging Physics from the First Second of Autoregressive Video Generation},
132
+ author = {Kumar, Soham and Sathyanarayanan, Shreenidhi and Mukherjee, Aniruddha},
133
+ year = {2026},
134
+ url = {https://github.com/sohamkumar1703/prune-early}
135
+ }
136
+ ```
137
+
138
+ MIT license. Paper, code and results are on [GitHub](https://github.com/sohamkumar1703/prune-early).
@@ -0,0 +1,19 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ prune_early/README.md
5
+ prune_early/__init__.py
6
+ prune_early/__main__.py
7
+ prune_early/_api.py
8
+ prune_early/cli.py
9
+ prune_early/early_signals.py
10
+ prune_early/frozen_judge.json
11
+ prune_early/frozen_judge.py
12
+ prune_early/py.typed
13
+ prune_early.egg-info/PKG-INFO
14
+ prune_early.egg-info/SOURCES.txt
15
+ prune_early.egg-info/dependency_links.txt
16
+ prune_early.egg-info/entry_points.txt
17
+ prune_early.egg-info/requires.txt
18
+ prune_early.egg-info/top_level.txt
19
+ tests/test_prune_early.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ prune-early = prune_early.cli:main
@@ -0,0 +1,8 @@
1
+ numpy>=1.21
2
+ opencv-python-headless>=4.5
3
+
4
+ [exact]
5
+ opencv-python-headless==5.0.0.93
6
+
7
+ [test]
8
+ pytest>=7
@@ -0,0 +1 @@
1
+ prune_early
@@ -0,0 +1,54 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "prune-early"
7
+ version = "1.0.0"
8
+ description = "Pick which video-generation candidates to finish from their first second, and stop the rest early"
9
+ readme = "prune_early/README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ authors = [
14
+ { name = "Soham Kumar" },
15
+ { name = "Shreenidhi Sathyanarayanan" },
16
+ { name = "Aniruddha Mukherjee" },
17
+ ]
18
+ keywords = ["video generation", "best-of-n", "verifier", "physics", "MAGI-1", "autoregressive", "pruning"]
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Intended Audience :: Science/Research",
22
+ "Intended Audience :: Developers",
23
+ "Operating System :: OS Independent",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3 :: Only",
26
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
27
+ "Topic :: Multimedia :: Video",
28
+ "Typing :: Typed",
29
+ ]
30
+ dependencies = ["numpy>=1.21", "opencv-python-headless>=4.5"]
31
+
32
+ [project.optional-dependencies]
33
+ exact = ["opencv-python-headless==5.0.0.93"]
34
+ test = ["pytest>=7"]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/sohamkumar1703/prune-early"
38
+ Paper = "https://github.com/sohamkumar1703/prune-early/blob/main/paper/report/main.pdf"
39
+ Issues = "https://github.com/sohamkumar1703/prune-early/issues"
40
+
41
+ [project.scripts]
42
+ prune-early = "prune_early.cli:main"
43
+
44
+ [tool.setuptools]
45
+ packages = ["prune_early"]
46
+
47
+ [tool.setuptools.package-data]
48
+ prune_early = ["frozen_judge.json", "py.typed"]
49
+
50
+ [tool.setuptools.exclude-package-data]
51
+ prune_early = ["README.md"]
52
+
53
+ [tool.pytest.ini_options]
54
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,96 @@
1
+ """Tests on small synthetic videos, so they run anywhere in a few seconds."""
2
+ import json
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import pytest
7
+
8
+ import prune_early
9
+ from prune_early import cli, frozen_judge
10
+
11
+
12
+ def write_video(path, dx, frames=30, fps=24, size=(160, 90)):
13
+ """A white square that moves dx pixels per frame on a gray background."""
14
+ writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, size)
15
+ for t in range(frames):
16
+ frame = np.full((size[1], size[0], 3), 90, np.uint8)
17
+ x = 10 + int(dx * t)
18
+ cv2.rectangle(frame, (x, 30), (x + 20, 50), (255, 255, 255), -1)
19
+ writer.write(frame)
20
+ writer.release()
21
+ return path
22
+
23
+
24
+ @pytest.fixture
25
+ def candidates(tmp_path):
26
+ folder = tmp_path / "candidates"
27
+ folder.mkdir()
28
+ for i, dx in enumerate([3, 3, 3, 0, 2]): # seed3 does not move
29
+ write_video(folder / f"seed{i}.mp4", dx)
30
+ write_video(folder / "seed10.mp4", 3)
31
+ return folder
32
+
33
+
34
+ def test_matches_the_frozen_judge(candidates):
35
+ paths = prune_early.find_videos(candidates)
36
+ choice = prune_early.judge(paths, keep=2)
37
+ assert np.allclose(choice.scores, frozen_judge.score(paths))
38
+ assert choice.kept == [int(i) for i in frozen_judge.keep(paths, 2)]
39
+
40
+
41
+ def test_folder_pattern_and_list_agree(candidates):
42
+ by_folder = prune_early.judge(candidates)
43
+ by_pattern = prune_early.judge(str(candidates / "*.mp4"))
44
+ by_list = prune_early.judge(by_folder.videos)
45
+ assert by_folder.scores == by_pattern.scores == by_list.scores
46
+ assert [p.name for p in by_folder.videos][-1] == "seed10.mp4" # natural order
47
+
48
+
49
+ def test_still_candidate_is_stopped(candidates):
50
+ choice = prune_early.judge(candidates, keep=3)
51
+ assert candidates / "seed3.mp4" in choice.stop
52
+ assert len(choice.finish) == 3 and choice.best == choice.finish[0]
53
+
54
+
55
+ def test_shortcuts(candidates):
56
+ paths = prune_early.find_videos(candidates)
57
+ assert prune_early.keep(paths, 2) == prune_early.judge(paths, keep=2).kept
58
+ assert len(prune_early.score(paths)) == len(paths)
59
+
60
+
61
+ @pytest.mark.parametrize("bad", [0, 7, 1.5, True])
62
+ def test_bad_keep(candidates, bad):
63
+ with pytest.raises(prune_early.PruneEarlyError, match="keep"):
64
+ prune_early.judge(candidates, keep=bad)
65
+
66
+
67
+ def test_bad_inputs(tmp_path, candidates):
68
+ with pytest.raises(prune_early.VideoError, match="not found"):
69
+ prune_early.judge([tmp_path / "missing.mp4", tmp_path / "also.mp4"])
70
+ with pytest.raises(prune_early.PruneEarlyError, match="at least two"):
71
+ prune_early.judge([candidates / "seed0.mp4"])
72
+ (tmp_path / "broken.mp4").write_bytes(b"not a video")
73
+ with pytest.raises(prune_early.VideoError, match="cannot read"):
74
+ prune_early.judge([candidates / "seed0.mp4", tmp_path / "broken.mp4"])
75
+ empty = tmp_path / "empty"
76
+ empty.mkdir()
77
+ with pytest.raises(prune_early.VideoError, match="no video files"):
78
+ prune_early.judge(empty)
79
+
80
+
81
+ def test_cli_table_json_quiet(candidates, capsys):
82
+ cli.main([str(candidates), "--keep", "2"])
83
+ out = capsys.readouterr().out
84
+ assert "finish" in out and "Finish 2 of 6" in out
85
+ cli.main([str(candidates), "--json"])
86
+ data = json.loads(capsys.readouterr().out)
87
+ assert len(data["finish"]) == 1 and len(data["candidates"]) == 6
88
+ cli.main([str(candidates), "-k", "2", "-q"])
89
+ assert len(capsys.readouterr().out.split()) == 2
90
+
91
+
92
+ def test_cli_error_is_friendly(tmp_path, capsys):
93
+ with pytest.raises(SystemExit) as stop:
94
+ cli.main([str(tmp_path / "nope.mp4"), str(tmp_path / "nope2.mp4")])
95
+ assert stop.value.code == 2
96
+ assert "video not found" in capsys.readouterr().err