prune-early 1.0.0__py3-none-any.whl

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,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()
prune_early/_api.py ADDED
@@ -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
prune_early/cli.py ADDED
@@ -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])
prune_early/py.typed ADDED
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,14 @@
1
+ prune_early/__init__.py,sha256=SHPMKLgN6U7JJy_4jPIxdZSAtgz8uVaOasB1App7UHk,1331
2
+ prune_early/__main__.py,sha256=AfHiSlMBHgLJO2bcR1Fs55NqpIKmDDf0zukWKNuYNR8,41
3
+ prune_early/_api.py,sha256=xBeF3HrdCAeqsgUh0rWRG_BkR-x45adXpB6NptAzC2A,6944
4
+ prune_early/cli.py,sha256=SQFrN2xznCR4pOxGR_UHxAbidJkIQm43PHmyjR01EY0,2144
5
+ prune_early/early_signals.py,sha256=WxqqWpKvhvVyj-nlSwe8R_sgcZ_VCFufohf1NFQ8Lhw,8416
6
+ prune_early/frozen_judge.json,sha256=eWgRD6a5lqs2aSKzF9jMTgRbL5-QHrWYizLgoREAXf4,1794
7
+ prune_early/frozen_judge.py,sha256=lBF_iCNVkpDlBqa6P6cjJokHwvosVqagf2R7Li7FQGk,3359
8
+ prune_early/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ prune_early-1.0.0.dist-info/licenses/LICENSE,sha256=wkKIaf2m7suV1pRaPzcDRjESr6cGJ6L4Y3Wb-x4Zgz4,1117
10
+ prune_early-1.0.0.dist-info/METADATA,sha256=vbiXx4qh9hMHK0wXt0whWghxvqJIOt0mqiTErD-zb5U,6502
11
+ prune_early-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ prune_early-1.0.0.dist-info/entry_points.txt,sha256=wcFat4LhLh1t9fnJjQ3Kc6IDP1ibL7rbR-siNGok70Q,53
13
+ prune_early-1.0.0.dist-info/top_level.txt,sha256=Ew9B4x7IihRj1sb8Ws7tKHcSmGBMtAJtHI0c1Movu1c,12
14
+ prune_early-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ prune-early = prune_early.cli:main
@@ -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 @@
1
+ prune_early