AntonioJun commited on
Commit
7ebdd1b
·
verified ·
1 Parent(s): 0bd3042

code backup: calibration (calibration module + question_ids plumbing + pilot sample)

Browse files
calibration/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reasoning-budget calibration pilot: find the right EXTENDED budget before the
2
+ main sweeps commit to one.
3
+
4
+ Everything is operator-specified -- no baked-in defaults decide the experiment: the
5
+ budget list (--budgets), the exact question set (--questions / --questions-file),
6
+ and the spatial-code format (--spatial-code-format) are all required CLI inputs.
7
+ Each (model, budget) pair runs through harness.B's unmodified extended path (only
8
+ ``reasoning_budget`` varies), restricted to the given questions; multi-GPU comes
9
+ free because harness.B.launch already shards scenes across every visible GPU (e.g.
10
+ 4 H100s). calibration.report then shows, per budget: official accuracy,
11
+ forced-continuation rate, natural-stop reasoning length, and latency, with a fixed
12
+ recommendation rule.
13
+
14
+ The main plan's 2048 default stays pre-registered; if this pilot moves it, that is a
15
+ documented pre-launch decision (record the chosen value in
16
+ analysis/preregistration.md before Step 1), not a mid-experiment change.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ from pathlib import Path
23
+
24
+ from harness.A import WORKSPACE_ROOT
25
+
26
+ # One JSON per question:
27
+ # results/calibration/<model>/<spatial_code_format>/<budget>/<scene>/<question_id>.json
28
+ RESULTS_DIR = Path(
29
+ os.environ.get("VSI_CALIBRATION_RESULTS_DIR", WORKSPACE_ROOT / "results" / "calibration")
30
+ )
calibration/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.57 kB). View file
 
calibration/__pycache__/report.cpython-311.pyc ADDED
Binary file (11 kB). View file
 
calibration/__pycache__/run.cpython-311.pyc ADDED
Binary file (10.9 kB). View file
 
calibration/report.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Report the budget-calibration grid and recommend a reasoning budget.
2
+
3
+ Per (model, budget) cell, over the exact question-id intersection shared by every
4
+ budget of that model (so no budget is scored on an easier subset): official overall
5
+ accuracy, forced-continuation rate, mean reasoning tokens on natural stops, and mean
6
+ generation seconds. Recommendation rule (stated up front, not tuned after looking):
7
+ the SMALLEST budget whose overall is within ``--tolerance`` points of that model's
8
+ best AND whose forced rate is at most ``--max-forced-rate`` -- accuracy saturation
9
+ alone is not enough, because a budget that forces half its answers is measuring the
10
+ force prompt, not the model's reasoning.
11
+
12
+ Usage:
13
+ python -m calibration.report [--tolerance 1.0] [--max-forced-rate 0.15] [--json]
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+ import statistics
21
+ import sys
22
+ from collections import defaultdict
23
+ from pathlib import Path
24
+
25
+ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
26
+ if str(WORKSPACE_ROOT) not in sys.path:
27
+ sys.path.insert(0, str(WORKSPACE_ROOT))
28
+
29
+ from analysis.aggregate import _official_scores, iter_records # noqa: E402
30
+ from calibration import RESULTS_DIR # noqa: E402
31
+
32
+
33
+ def load_grid(results_dir=None):
34
+ """{"<model>/<format>/<depth>/<tracking>/<input>/<frames>": {budget: {question_id:
35
+ record}}} from the calibration tree. Budget directories are found by walking to
36
+ every all-digit directory whose PARENT chain starts at the root -- frame-count
37
+ directories are also numeric, so a budget leaf is specifically a numeric
38
+ directory whose own subdirectories are scene result folders (contain .json
39
+ files), not further numeric config levels."""
40
+ root = Path(results_dir or RESULTS_DIR)
41
+ grid = defaultdict(dict)
42
+ if not root.is_dir():
43
+ return dict(grid)
44
+ for budget_dir in sorted(root.rglob("*")):
45
+ if not budget_dir.is_dir() or not budget_dir.name.isdigit():
46
+ continue
47
+ # A budget leaf holds scene folders with question JSONs directly below it.
48
+ has_question_files = any(
49
+ child.is_dir() and any(grand.suffix == ".json" for grand in child.iterdir())
50
+ for child in budget_dir.iterdir()
51
+ )
52
+ if not has_question_files:
53
+ continue
54
+ records = {r["question_id"]: r for r in iter_records(budget_dir)}
55
+ if records:
56
+ cell = str(budget_dir.parent.relative_to(root))
57
+ grid[cell][int(budget_dir.name)] = records
58
+ return dict(grid)
59
+
60
+
61
+ def cell_stats(records):
62
+ """Accuracy + budget-behavior stats for one (model, budget) cell's records."""
63
+ rows = list(records)
64
+ forced = [1.0 if r.get("forced") else 0.0 for r in rows]
65
+ natural_lengths = [
66
+ r["reasoning_token_count"]
67
+ for r in rows
68
+ if r.get("reasoning_token_count") is not None and not r.get("forced")
69
+ ]
70
+ return {
71
+ "count": len(rows),
72
+ "overall": _official_scores(rows).get("overall"),
73
+ "forced_rate": statistics.mean(forced) if forced else None,
74
+ "natural_reasoning_tokens_mean": (
75
+ statistics.mean(natural_lengths) if natural_lengths else None
76
+ ),
77
+ "generation_seconds_mean": statistics.mean(r["generation_seconds"] for r in rows),
78
+ }
79
+
80
+
81
+ def report(grid, tolerance=1.0, max_forced_rate=0.15):
82
+ """{model: {"budgets": {budget: stats}, "recommended": budget_or_None}} over each
83
+ model's shared question intersection across its budgets."""
84
+ out = {}
85
+ for model, budgets in grid.items():
86
+ common = set.intersection(*(set(records) for records in budgets.values()))
87
+ stats = {
88
+ budget: cell_stats(records[qid] for qid in common)
89
+ for budget, records in sorted(budgets.items())
90
+ }
91
+ scored = {b: s for b, s in stats.items() if s["overall"] is not None}
92
+ recommended = None
93
+ if scored:
94
+ best = max(s["overall"] for s in scored.values())
95
+ for budget in sorted(scored):
96
+ s = scored[budget]
97
+ if s["overall"] >= best - tolerance and (
98
+ s["forced_rate"] is None or s["forced_rate"] <= max_forced_rate
99
+ ):
100
+ recommended = budget
101
+ break
102
+ out[model] = {
103
+ "questions": len(common),
104
+ "budgets": stats,
105
+ "recommended": recommended,
106
+ }
107
+ return out
108
+
109
+
110
+ def main():
111
+ parser = argparse.ArgumentParser()
112
+ parser.add_argument("--results-dir", default=None)
113
+ parser.add_argument(
114
+ "--tolerance", type=float, default=1.0,
115
+ help="accuracy points a budget may trail the best and still be recommended",
116
+ )
117
+ parser.add_argument(
118
+ "--max-forced-rate", type=float, default=0.15, dest="max_forced_rate",
119
+ help="maximum acceptable forced-continuation rate for a recommended budget",
120
+ )
121
+ parser.add_argument("--json", action="store_true")
122
+ args = parser.parse_args()
123
+
124
+ grid = load_grid(args.results_dir)
125
+ if not grid:
126
+ print("no calibration results found -- run calibration.run first")
127
+ raise SystemExit(1)
128
+ result = report(grid, tolerance=args.tolerance, max_forced_rate=args.max_forced_rate)
129
+ if args.json:
130
+ print(json.dumps(result, indent=1))
131
+ return
132
+ for model, model_report in result.items():
133
+ print(f"=== {model} ({model_report['questions']} shared questions) ===")
134
+ for budget, stats in model_report["budgets"].items():
135
+ overall = f"{stats['overall']:.2f}" if stats["overall"] is not None else "-"
136
+ forced = f"{stats['forced_rate']:.3f}" if stats["forced_rate"] is not None else "-"
137
+ natural = (
138
+ f"{stats['natural_reasoning_tokens_mean']:.0f}"
139
+ if stats["natural_reasoning_tokens_mean"] is not None else "-"
140
+ )
141
+ print(
142
+ f" {budget:>6} tokens: overall={overall} forced_rate={forced} "
143
+ f"natural_reasoning_mean={natural} "
144
+ f"gen_seconds_mean={stats['generation_seconds_mean']:.2f}"
145
+ )
146
+ print(f" RECOMMENDED: {model_report['recommended']}")
147
+ print(
148
+ "\nIf the recommendation differs from the pre-registered 2048, record the new "
149
+ "value in analysis/preregistration.md BEFORE Step 1 runs."
150
+ )
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
calibration/run.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the reasoning-budget grid: every (model, budget) pair through
2
+ harness.B.launch, restricted to the operator's exact question list, one pair at a
3
+ time, each saturating every visible GPU.
4
+
5
+ The operator decides everything: which budgets, which questions, which format, and
6
+ which perceived-code config (depth / tracking / input selection / frame count) --
7
+ scenes are derived automatically from the given question ids, and every axis is a
8
+ results-path segment so pilots at different configs can never collide.
9
+
10
+ Usage (pilot on 4 H100s):
11
+ python -m calibration.run --models all --budgets 256,512,1024 \\
12
+ --questions 12,34,56,789 --spatial-code-format explicit \\
13
+ --depth metric --tracking tracking --input-selection selective --frames 64
14
+ python -m calibration.run --models qwen3.5-4b --budgets 512,1024,2048 \\
15
+ --questions-file my_pilot_questions.json --spatial-code-format compact \\
16
+ --depth relative --tracking tracking --input-selection selective --frames 32
17
+
18
+ Then: python -m calibration.report
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
29
+ if str(WORKSPACE_ROOT) not in sys.path:
30
+ sys.path.insert(0, str(WORKSPACE_ROOT))
31
+
32
+ from calibration import RESULTS_DIR # noqa: E402
33
+ from harness.A import models as vlm_models # noqa: E402
34
+ from harness.A.run import load_questions # noqa: E402
35
+ from harness.A.sweep import _parse_csv_choice # noqa: E402
36
+ from harness.B import ( # noqa: E402
37
+ DEPTH_VARIANTS,
38
+ INPUT_SELECTIONS,
39
+ SPATIAL_CODE_FORMATS,
40
+ TRACKING_MODES,
41
+ )
42
+ from harness.B import launch as harness_b_launch # noqa: E402
43
+
44
+
45
+ def results_dir_for(model, spatial_code_format, depth, tracking, input_selection, frame_count, budget):
46
+ """Return the result root isolated by every pilot axis -- model, format, the full
47
+ perceived-code config, and the reasoning budget -- so no two pilots collide."""
48
+ return (
49
+ RESULTS_DIR / model / spatial_code_format / depth / tracking
50
+ / input_selection / str(frame_count) / str(budget)
51
+ )
52
+
53
+
54
+ def build_plan(models, budgets):
55
+ """Every (model, budget) pair, cheapest budget first so early results land
56
+ soonest and a mid-pilot abort still yields comparable low-budget cells."""
57
+ return [(model, budget) for budget in sorted(budgets) for model in models]
58
+
59
+
60
+ def scenes_for(question_ids):
61
+ """The scenes covering the given question ids (harness.B.launch shards by
62
+ scene). Raises on ids that don't exist in the manifest -- a typo in the pilot's
63
+ question list should fail loudly, not silently shrink the pilot."""
64
+ scene_of = {row["id"]: row["scene_name"] for row in load_questions()}
65
+ unknown = sorted(qid for qid in question_ids if qid not in scene_of)
66
+ if unknown:
67
+ raise ValueError(f"question id(s) not in the VSI-Bench manifest: {unknown}")
68
+ return sorted({scene_of[qid] for qid in question_ids})
69
+
70
+
71
+ def run_grid(
72
+ models, budgets, question_ids, spatial_code_format,
73
+ depth, tracking, input_selection, frame_count,
74
+ rebuild=False,
75
+ ):
76
+ """Run every (model, budget) pair through harness.B.launch -- the unmodified
77
+ extended path, only ``reasoning_budget`` varies -- on the operator's questions."""
78
+ question_ids = set(question_ids)
79
+ selected_scenes = scenes_for(question_ids)
80
+ print(
81
+ f"pilot: {len(question_ids)} question(s) over {len(selected_scenes)} scene(s), "
82
+ f"format={spatial_code_format}, config={depth}/{tracking}/{input_selection}/"
83
+ f"{frame_count}, budgets={sorted(budgets)}",
84
+ flush=True,
85
+ )
86
+ plan = build_plan(models, budgets)
87
+ for index, (model, budget) in enumerate(plan, start=1):
88
+ print(f"=== calibration {index}/{len(plan)}: {model} @ {budget} tokens ===", flush=True)
89
+ harness_b_launch.launch(
90
+ model, spatial_code_format, input_selection, frame_count, selected_scenes,
91
+ depth=depth, tracking=tracking,
92
+ results_dir=results_dir_for(
93
+ model, spatial_code_format, depth, tracking, input_selection,
94
+ frame_count, budget,
95
+ ),
96
+ rebuild=rebuild,
97
+ reasoning_budget=budget,
98
+ question_ids=question_ids,
99
+ )
100
+
101
+
102
+ def main():
103
+ parser = argparse.ArgumentParser()
104
+ parser.add_argument(
105
+ "--models", required=True,
106
+ help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}",
107
+ )
108
+ parser.add_argument(
109
+ "--budgets", required=True,
110
+ help="comma-separated reasoning budgets in tokens -- entirely your choice",
111
+ )
112
+ parser.add_argument(
113
+ "--questions", default=None,
114
+ help="comma-separated VSI-Bench question ids to test",
115
+ )
116
+ parser.add_argument(
117
+ "--questions-file", default=None, dest="questions_file",
118
+ help="path to a JSON list of question ids (alternative to --questions)",
119
+ )
120
+ parser.add_argument(
121
+ "--spatial-code-format", required=True, choices=SPATIAL_CODE_FORMATS,
122
+ dest="spatial_code_format",
123
+ )
124
+ parser.add_argument("--depth", required=True, choices=DEPTH_VARIANTS)
125
+ parser.add_argument("--tracking", required=True, choices=TRACKING_MODES)
126
+ parser.add_argument(
127
+ "--input-selection", required=True, choices=INPUT_SELECTIONS,
128
+ dest="input_selection",
129
+ )
130
+ parser.add_argument("--frames", type=int, required=True)
131
+ parser.add_argument("--rebuild", action="store_true")
132
+ args = parser.parse_args()
133
+
134
+ try:
135
+ models = _parse_csv_choice(args.models, vlm_models.available_models(), "--models")
136
+ except ValueError as exc:
137
+ parser.error(str(exc))
138
+ budgets = []
139
+ for item in args.budgets.split(","):
140
+ item = item.strip()
141
+ if not item:
142
+ continue
143
+ budget = int(item)
144
+ if budget < 1:
145
+ parser.error(f"budget {budget} must be positive")
146
+ budgets.append(budget)
147
+ if not budgets:
148
+ parser.error("--budgets must name at least one budget")
149
+
150
+ if bool(args.questions) == bool(args.questions_file):
151
+ parser.error("give exactly one of --questions or --questions-file")
152
+ if args.questions:
153
+ question_ids = [int(q.strip()) for q in args.questions.split(",") if q.strip()]
154
+ else:
155
+ with open(args.questions_file, encoding="utf-8") as stream:
156
+ question_ids = [int(q) for q in json.load(stream)]
157
+ if not question_ids:
158
+ parser.error("no question ids given")
159
+
160
+ if args.frames < 1:
161
+ parser.error("--frames must be positive")
162
+ try:
163
+ run_grid(
164
+ models, budgets, question_ids, args.spatial_code_format,
165
+ args.depth, args.tracking, args.input_selection, args.frames,
166
+ rebuild=args.rebuild,
167
+ )
168
+ except ValueError as exc:
169
+ parser.error(str(exc))
170
+
171
+
172
+ if __name__ == "__main__":
173
+ main()