AntonioJun commited on
Commit
725dd83
·
verified ·
1 Parent(s): 1a4ba5a

code backup: corruption

Browse files
corruption/__pycache__/empirical.cpython-311.pyc CHANGED
Binary files a/corruption/__pycache__/empirical.cpython-311.pyc and b/corruption/__pycache__/empirical.cpython-311.pyc differ
 
corruption/__pycache__/launch.cpython-311.pyc CHANGED
Binary files a/corruption/__pycache__/launch.cpython-311.pyc and b/corruption/__pycache__/launch.cpython-311.pyc differ
 
corruption/__pycache__/run.cpython-311.pyc CHANGED
Binary files a/corruption/__pycache__/run.cpython-311.pyc and b/corruption/__pycache__/run.cpython-311.pyc differ
 
corruption/__pycache__/sample.cpython-311.pyc ADDED
Binary file (8.84 kB). View file
 
corruption/empirical.py CHANGED
@@ -16,8 +16,15 @@ corruption/chimera.py uses), which is deliberate: both modules should agree on w
16
 
17
  from __future__ import annotations
18
 
 
19
  import json
20
  import math
 
 
 
 
 
 
21
 
22
 
23
  def _center(instance):
@@ -129,3 +136,64 @@ def empirical_noise(code, residuals, rng, scale=1.0):
129
  kept[class_name] = survivors
130
  code["objects"] = kept
131
  return code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  from __future__ import annotations
18
 
19
+ import argparse
20
  import json
21
  import math
22
+ import sys
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
 
30
  def _center(instance):
 
136
  kept[class_name] = survivors
137
  code["objects"] = kept
138
  return code
139
+
140
+
141
+ def main():
142
+ """Measure the residual distribution over every scene with BOTH a perceived code
143
+ (at the given Step-2 config) and a ground-truth code, and write it to a JSON file
144
+ corruption.run's ``--residuals`` flag consumes."""
145
+ from encoder import config as encoder_config
146
+ from encoder.config import ground_truth_spatial_code_path
147
+ from harness.A.run import load_questions
148
+
149
+ parser = argparse.ArgumentParser()
150
+ parser.add_argument("--depth", required=True, choices=("relative", "metric"))
151
+ parser.add_argument("--tracking", required=True, choices=("tracking", "no tracking"))
152
+ parser.add_argument(
153
+ "--input-selection", required=True, choices=("uniform", "selective"),
154
+ dest="input_selection",
155
+ )
156
+ parser.add_argument("--frames", type=int, required=True)
157
+ parser.add_argument(
158
+ "--output", default=str(WORKSPACE_ROOT / "analysis" / "sam3_da3_residuals.json")
159
+ )
160
+ args = parser.parse_args()
161
+
162
+ pairs = []
163
+ seen = set()
164
+ for row in load_questions():
165
+ scene = row["scene_name"]
166
+ if scene in seen:
167
+ continue
168
+ seen.add(scene)
169
+ perceived_path = Path(
170
+ encoder_config.spatial_code_path(
171
+ scene, args.depth, args.input_selection, args.tracking, args.frames, "compact"
172
+ )
173
+ )
174
+ gt_path = Path(ground_truth_spatial_code_path(scene, "compact"))
175
+ if not (perceived_path.is_file() and gt_path.is_file()):
176
+ continue
177
+ with perceived_path.open(encoding="utf-8") as stream:
178
+ perceived = json.load(stream)
179
+ with gt_path.open(encoding="utf-8") as stream:
180
+ ground_truth = json.load(stream)
181
+ pairs.append((perceived, ground_truth))
182
+ if not pairs:
183
+ raise SystemExit(
184
+ "no scenes with both perceived and ground-truth compact codes at this config"
185
+ )
186
+
187
+ residuals = measure_residuals(pairs)
188
+ with open(args.output, "w", encoding="utf-8") as stream:
189
+ json.dump(residuals, stream, indent=1)
190
+ print(f"measured residuals over {len(pairs)} scene pair(s) -> {args.output}")
191
+ print(
192
+ f"matched {residuals['matched']}, missed {residuals['missed']} "
193
+ f"(rate {residuals['miss_rate']:.3f}), hallucinated {residuals['hallucinated']} "
194
+ f"(rate {residuals['hallucination_rate']:.3f})"
195
+ )
196
+
197
+
198
+ if __name__ == "__main__":
199
+ main()
corruption/launch.py CHANGED
@@ -40,6 +40,23 @@ def main():
40
  )
41
  parser.add_argument("--scenes", default=None, help="comma-separated scenes")
42
  parser.add_argument("--sample", default=None, help="JSON list of question ids")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  args = parser.parse_args()
44
 
45
  transforms = [t.strip() for t in args.transforms.split(",") if t.strip()]
@@ -63,19 +80,37 @@ def main():
63
  with open(args.sample, encoding="utf-8") as stream:
64
  question_ids = set(json.load(stream))
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  conditions = [(t, m) for t in transforms for m in magnitudes]
67
  for index, (transform, magnitude) in enumerate(conditions, start=1):
68
  print(f"=== corruption {index}/{len(conditions)}: {transform}@{magnitude} ===", flush=True)
69
  if args.arm in ("solver", "both"):
70
  results = run_solver(
71
  transform, magnitude, args.spatial_code_format,
72
- scenes=scenes, question_ids=question_ids,
73
  )
74
  print(f" [solver] {len(results)} questions", flush=True)
75
  for model in models:
76
  results = run_vlm(
77
  model, transform, magnitude, args.spatial_code_format,
78
- scenes=scenes, question_ids=question_ids,
79
  )
80
  print(f" [{model}] {len(results)} questions", flush=True)
81
 
 
40
  )
41
  parser.add_argument("--scenes", default=None, help="comma-separated scenes")
42
  parser.add_argument("--sample", default=None, help="JSON list of question ids")
43
+ parser.add_argument(
44
+ "--depth", default=None, choices=("relative", "metric"),
45
+ help="chimera transforms only: the perceived codes' Step-2 config",
46
+ )
47
+ parser.add_argument(
48
+ "--tracking", default=None, choices=("tracking", "no tracking"),
49
+ help="chimera transforms only",
50
+ )
51
+ parser.add_argument(
52
+ "--input-selection", default=None, choices=("uniform", "selective"),
53
+ dest="input_selection", help="chimera transforms only",
54
+ )
55
+ parser.add_argument("--frames", type=int, default=None, help="chimera transforms only")
56
+ parser.add_argument(
57
+ "--residuals", default=None,
58
+ help="empirical transform only: corruption.empirical's measured-residuals JSON",
59
+ )
60
  args = parser.parse_args()
61
 
62
  transforms = [t.strip() for t in args.transforms.split(",") if t.strip()]
 
80
  with open(args.sample, encoding="utf-8") as stream:
81
  question_ids = set(json.load(stream))
82
 
83
+ condition_kwargs = {}
84
+ if any(t.startswith("chimera") for t in transforms):
85
+ if None in (args.depth, args.tracking, args.input_selection, args.frames):
86
+ parser.error(
87
+ "chimera transforms require --depth/--tracking/--input-selection/--frames"
88
+ )
89
+ condition_kwargs["perceived_config"] = {
90
+ "depth": args.depth,
91
+ "tracking": args.tracking,
92
+ "input_selection": args.input_selection,
93
+ "frame_count": args.frames,
94
+ }
95
+ if "empirical" in transforms:
96
+ if not args.residuals:
97
+ parser.error("the empirical transform requires --residuals")
98
+ with open(args.residuals, encoding="utf-8") as stream:
99
+ condition_kwargs["residuals"] = json.load(stream)
100
+
101
  conditions = [(t, m) for t in transforms for m in magnitudes]
102
  for index, (transform, magnitude) in enumerate(conditions, start=1):
103
  print(f"=== corruption {index}/{len(conditions)}: {transform}@{magnitude} ===", flush=True)
104
  if args.arm in ("solver", "both"):
105
  results = run_solver(
106
  transform, magnitude, args.spatial_code_format,
107
+ scenes=scenes, question_ids=question_ids, **condition_kwargs,
108
  )
109
  print(f" [solver] {len(results)} questions", flush=True)
110
  for model in models:
111
  results = run_vlm(
112
  model, transform, magnitude, args.spatial_code_format,
113
+ scenes=scenes, question_ids=question_ids, **condition_kwargs,
114
  )
115
  print(f" [{model}] {len(results)} questions", flush=True)
116
 
corruption/run.py CHANGED
@@ -67,6 +67,28 @@ def load_ground_truth_compact(scene):
67
  return code
68
 
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  def corrupted_compact(
71
  scene, transform, magnitude, perceived_config=None, residuals=None, wrong_scene=None
72
  ):
@@ -146,6 +168,7 @@ def run_vlm(
146
  )
147
  if question_ids is not None:
148
  results = [r for r in results if r["question_id"] in question_ids]
 
149
  return results
150
 
151
 
@@ -200,6 +223,8 @@ def run_solver(
200
  else:
201
  record["result_path"] = None
202
  results.append(record)
 
 
203
  return results
204
 
205
 
@@ -226,6 +251,40 @@ def certify_invariant(scene, transform, magnitude, spatial_code_format="explicit
226
  return True
227
 
228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  def main():
230
  parser = argparse.ArgumentParser()
231
  parser.add_argument("--arm", required=True, choices=("vlm", "solver", "certify"))
@@ -243,7 +302,32 @@ def main():
243
  help="path to a JSON list of question ids (the pre-registered sample)",
244
  )
245
  parser.add_argument("--results-dir", default=None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  args = parser.parse_args()
 
247
 
248
  scenes = None
249
  if args.scenes:
@@ -269,13 +353,13 @@ def main():
269
  results = run_vlm(
270
  args.model, args.transform, args.magnitude, args.spatial_code_format,
271
  scenes=scenes, limit=args.limit, question_ids=question_ids,
272
- results_dir=args.results_dir,
273
  )
274
  else:
275
  results = run_solver(
276
  args.transform, args.magnitude, args.spatial_code_format,
277
  scenes=scenes, limit=args.limit, question_ids=question_ids,
278
- results_dir=args.results_dir,
279
  )
280
  if results:
281
  mean_score = sum(r["score"] for r in results) / len(results)
 
67
  return code
68
 
69
 
70
+ def single_object_info(scene, magnitude):
71
+ """Reconstruct WHICH object the single-object probe perturbed for this scene --
72
+ fully determined by the frozen seed, so it can be recovered at any time. H6's
73
+ analysis needs this to select the questions that mention the perturbed object."""
74
+ rng = random.Random(_seed_for(scene, "single-object", magnitude))
75
+ _code, info = chimera_mod.perturb_single_object(load_ground_truth_compact(scene), rng)
76
+ return info
77
+
78
+
79
+ def _write_perturbation_sidecars(results, transform, magnitude, root):
80
+ """For single-object runs, record the perturbed object's identity next to each
81
+ scene's result files (_perturbation.json) -- without it the H6 conflict-question
82
+ set cannot be constructed."""
83
+ if transform != "single-object":
84
+ return
85
+ for scene in {record["scene"] for record in results}:
86
+ scene_dir = Path(root) / scene
87
+ scene_dir.mkdir(parents=True, exist_ok=True)
88
+ with (scene_dir / "_perturbation.json").open("w", encoding="utf-8") as stream:
89
+ json.dump(single_object_info(scene, magnitude), stream, indent=1)
90
+
91
+
92
  def corrupted_compact(
93
  scene, transform, magnitude, perceived_config=None, residuals=None, wrong_scene=None
94
  ):
 
168
  )
169
  if question_ids is not None:
170
  results = [r for r in results if r["question_id"] in question_ids]
171
+ _write_perturbation_sidecars(results, transform, magnitude, root)
172
  return results
173
 
174
 
 
223
  else:
224
  record["result_path"] = None
225
  results.append(record)
226
+ if write_results:
227
+ _write_perturbation_sidecars(results, transform, magnitude, root)
228
  return results
229
 
230
 
 
251
  return True
252
 
253
 
254
+ def _condition_kwargs(args, parser):
255
+ """Build the per-condition keyword arguments the special transforms need,
256
+ validating that the right flags were given for the requested transform."""
257
+ kwargs = {}
258
+ if args.transform in CHIMERA_CONDITIONS:
259
+ missing = [
260
+ flag for flag, value in (
261
+ ("--depth", args.depth), ("--tracking", args.tracking),
262
+ ("--input-selection", args.input_selection), ("--frames", args.frames),
263
+ ) if value is None
264
+ ]
265
+ if missing:
266
+ parser.error(f"{args.transform} requires {', '.join(missing)} (the Step-2 config)")
267
+ kwargs["perceived_config"] = {
268
+ "depth": args.depth,
269
+ "tracking": args.tracking,
270
+ "input_selection": args.input_selection,
271
+ "frame_count": args.frames,
272
+ }
273
+ if args.transform == "wrong-scene":
274
+ if not args.wrong_scene:
275
+ parser.error("wrong-scene requires --wrong-scene (the substitute scene id)")
276
+ kwargs["wrong_scene"] = args.wrong_scene
277
+ if args.transform == "empirical":
278
+ if not args.residuals:
279
+ parser.error(
280
+ "empirical requires --residuals (measure them first: "
281
+ "python -m corruption.empirical --help)"
282
+ )
283
+ with open(args.residuals, encoding="utf-8") as stream:
284
+ kwargs["residuals"] = json.load(stream)
285
+ return kwargs
286
+
287
+
288
  def main():
289
  parser = argparse.ArgumentParser()
290
  parser.add_argument("--arm", required=True, choices=("vlm", "solver", "certify"))
 
302
  help="path to a JSON list of question ids (the pre-registered sample)",
303
  )
304
  parser.add_argument("--results-dir", default=None)
305
+ parser.add_argument(
306
+ "--depth", default=None, choices=("relative", "metric"),
307
+ help="chimera only: the perceived codes' Step-2 config",
308
+ )
309
+ parser.add_argument(
310
+ "--tracking", default=None, choices=("tracking", "no tracking"),
311
+ help="chimera only: the perceived codes' Step-2 config",
312
+ )
313
+ parser.add_argument(
314
+ "--input-selection", default=None, choices=("uniform", "selective"),
315
+ dest="input_selection", help="chimera only: the perceived codes' Step-2 config",
316
+ )
317
+ parser.add_argument(
318
+ "--frames", type=int, default=None,
319
+ help="chimera only: the perceived codes' Step-2 config",
320
+ )
321
+ parser.add_argument(
322
+ "--wrong-scene", default=None, dest="wrong_scene",
323
+ help="wrong-scene only: the substitute scene id",
324
+ )
325
+ parser.add_argument(
326
+ "--residuals", default=None,
327
+ help="empirical only: path to corruption.empirical's measured-residuals JSON",
328
+ )
329
  args = parser.parse_args()
330
+ condition_kwargs = _condition_kwargs(args, parser)
331
 
332
  scenes = None
333
  if args.scenes:
 
353
  results = run_vlm(
354
  args.model, args.transform, args.magnitude, args.spatial_code_format,
355
  scenes=scenes, limit=args.limit, question_ids=question_ids,
356
+ results_dir=args.results_dir, **condition_kwargs,
357
  )
358
  else:
359
  results = run_solver(
360
  args.transform, args.magnitude, args.spatial_code_format,
361
  scenes=scenes, limit=args.limit, question_ids=question_ids,
362
+ results_dir=args.results_dir, **condition_kwargs,
363
  )
364
  if results:
365
  mean_score = sum(r["score"] for r in results) / len(results)
corruption/sample.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate the pre-registered corruption-arm question sample.
2
+
3
+ Implements EXACTLY the procedure frozen in analysis/preregistration.md: a balanced
4
+ draw of ~600 questions over the 7 non-appearance-order categories (~85 each; the
5
+ three object_rel_direction_* subtypes share the relative-direction budget), from
6
+ scenes that have BOTH a perceived spatial code at the frozen Step-2 config AND a
7
+ ground-truth code, spread over as many distinct scenes as the draw allows, sampled
8
+ with the frozen RNG seed. Writes the realized question-id list to
9
+ analysis/corruption_sample.json (and prints coverage stats) so it can be committed
10
+ to the pre-registration immediately after Step 2, before any corruption run.
11
+
12
+ Usage (after Step 2, with the winning config):
13
+ python -m corruption.sample --depth relative --tracking tracking \\
14
+ --input-selection selective --frames 32
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import random
22
+ import sys
23
+ from collections import defaultdict
24
+ from pathlib import Path
25
+
26
+ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
27
+ if str(WORKSPACE_ROOT) not in sys.path:
28
+ sys.path.insert(0, str(WORKSPACE_ROOT))
29
+
30
+ from corruption import SAMPLE_SEED # noqa: E402
31
+ from encoder import config as encoder_config # noqa: E402
32
+ from encoder.config import ground_truth_spatial_code_path # noqa: E402
33
+ from harness.A.run import load_questions # noqa: E402
34
+
35
+ # The 7 sampled categories (appearance order excluded for circularity -- see
36
+ # analysis/preregistration.md); the direction subtypes pool into one budget.
37
+ CATEGORY_BUDGETS = {
38
+ "object_counting": 85,
39
+ "object_abs_distance": 85,
40
+ "object_size_estimation": 85,
41
+ "room_size_estimation": 85,
42
+ "object_rel_distance": 85,
43
+ "object_rel_direction": 85, # easy+medium+hard pooled
44
+ "route_planning": 85,
45
+ }
46
+
47
+ DEFAULT_OUTPUT = WORKSPACE_ROOT / "analysis" / "corruption_sample.json"
48
+
49
+
50
+ def _budget_key(question_type):
51
+ if question_type.startswith("object_rel_direction"):
52
+ return "object_rel_direction"
53
+ return question_type
54
+
55
+
56
+ def eligible_scenes(depth, input_selection, tracking, frame_count):
57
+ """Scenes having BOTH a perceived code at the given config AND a ground-truth
58
+ code on disk -- required by the empirical calibration and chimera arms."""
59
+ scenes = set()
60
+ for row in load_questions():
61
+ scene = row["scene_name"]
62
+ if scene in scenes:
63
+ continue
64
+ perceived = Path(
65
+ encoder_config.spatial_code_path(
66
+ scene, depth, input_selection, tracking, frame_count, "compact"
67
+ )
68
+ )
69
+ ground_truth = Path(ground_truth_spatial_code_path(scene, "compact"))
70
+ if perceived.is_file() and ground_truth.is_file():
71
+ scenes.add(scene)
72
+ return scenes
73
+
74
+
75
+ def draw_sample(scenes, seed=SAMPLE_SEED, budgets=None):
76
+ """Draw the balanced sample: within each category budget, scenes are cycled
77
+ round-robin (maximizing distinct-scene spread) with per-scene question order and
78
+ scene order both shuffled by the frozen seed."""
79
+ budgets = dict(budgets or CATEGORY_BUDGETS)
80
+ rng = random.Random(seed)
81
+ by_bucket_scene = defaultdict(lambda: defaultdict(list))
82
+ for row in load_questions():
83
+ if row["scene_name"] not in scenes:
84
+ continue
85
+ bucket = _budget_key(row["question_type"])
86
+ if bucket in budgets:
87
+ by_bucket_scene[bucket][row["scene_name"]].append(row["id"])
88
+
89
+ sampled = []
90
+ for bucket in sorted(budgets):
91
+ scene_queues = {}
92
+ for scene, ids in by_bucket_scene[bucket].items():
93
+ ids = list(ids)
94
+ rng.shuffle(ids)
95
+ scene_queues[scene] = ids
96
+ order = sorted(scene_queues)
97
+ rng.shuffle(order)
98
+ remaining = budgets[bucket]
99
+ while remaining > 0 and any(scene_queues[scene] for scene in order):
100
+ for scene in order:
101
+ if remaining == 0:
102
+ break
103
+ if scene_queues[scene]:
104
+ sampled.append(scene_queues[scene].pop())
105
+ remaining -= 1
106
+ return sorted(sampled)
107
+
108
+
109
+ def main():
110
+ parser = argparse.ArgumentParser()
111
+ parser.add_argument("--depth", required=True, choices=("relative", "metric"))
112
+ parser.add_argument("--tracking", required=True, choices=("tracking", "no tracking"))
113
+ parser.add_argument(
114
+ "--input-selection", required=True, choices=("uniform", "selective"),
115
+ dest="input_selection",
116
+ )
117
+ parser.add_argument("--frames", type=int, required=True)
118
+ parser.add_argument("--output", default=str(DEFAULT_OUTPUT))
119
+ parser.add_argument(
120
+ "--seed", type=int, default=SAMPLE_SEED,
121
+ help="frozen in analysis/preregistration.md -- do not change for real runs",
122
+ )
123
+ args = parser.parse_args()
124
+
125
+ scenes = eligible_scenes(args.depth, args.input_selection, args.tracking, args.frames)
126
+ if not scenes:
127
+ raise SystemExit(
128
+ "no eligible scenes: need BOTH perceived (Step 2) and ground-truth codes on disk"
129
+ )
130
+ sample = draw_sample(scenes, seed=args.seed)
131
+
132
+ scene_of = {row["id"]: row["scene_name"] for row in load_questions()}
133
+ distinct_scenes = {scene_of[qid] for qid in sample}
134
+ with open(args.output, "w", encoding="utf-8") as stream:
135
+ json.dump(sample, stream, indent=1)
136
+ print(f"wrote {len(sample)} question ids to {args.output}")
137
+ print(f"eligible scenes: {len(scenes)}; distinct scenes in sample: {len(distinct_scenes)}")
138
+ print(
139
+ "NOW: commit this file into the repository and re-run the code backup so the "
140
+ "realized sample is timestamped before any corruption run "
141
+ "(analysis/preregistration.md)."
142
+ )
143
+
144
+
145
+ if __name__ == "__main__":
146
+ main()