diff --git a/harness/A/__init__.py b/harness/A/__init__.py index eda15f0f1aade5e7a3d291835028aab82388ae0f..c07077d3d66d84b735b0cd5c0978ea16e6695669 100644 --- a/harness/A/__init__.py +++ b/harness/A/__init__.py @@ -47,6 +47,12 @@ DO_SAMPLE = False EXTENDED_MAX_NEW_TOKENS = 2048 FORCE_ANSWER_PROMPT = "\nFinal answer:" +# The generation-protocol axis every harness sweeps: "base" is the paper's fixed +# 16-token protocol (plain answer()), "extended" is the 2048-token answer_extended +# protocol above. A results-path segment on every harness, so the two protocols' +# records can never collide on disk. +PROTOCOLS = ("base", "extended") + MODEL_PATHS = { "qwen3.5-4b": MODELS_ROOT / "qwen3.5-4b", "qwen3.5-2b": MODELS_ROOT / "qwen3.5-2b", diff --git a/harness/A/__pycache__/__init__.cpython-311.pyc b/harness/A/__pycache__/__init__.cpython-311.pyc index 0508ef598573a3b8a81ded2be42df34f68e54e49..7f0b547d53d70064c25142f4d0429503fdf88d27 100644 Binary files a/harness/A/__pycache__/__init__.cpython-311.pyc and b/harness/A/__pycache__/__init__.cpython-311.pyc differ diff --git a/harness/A/__pycache__/launch.cpython-311.pyc b/harness/A/__pycache__/launch.cpython-311.pyc index 01f55c4c783f264a2eb70841b2704c13850282b9..5b28794a5789d39b4b98dddbe7cf45370321164f 100644 Binary files a/harness/A/__pycache__/launch.cpython-311.pyc and b/harness/A/__pycache__/launch.cpython-311.pyc differ diff --git a/harness/A/__pycache__/run.cpython-311.pyc b/harness/A/__pycache__/run.cpython-311.pyc index 60361ef4d293a2690a0946904d10d5b391844e2f..7f2ab7c8b336772ede62c2d93c8b1faef8d6c9e8 100644 Binary files a/harness/A/__pycache__/run.cpython-311.pyc and b/harness/A/__pycache__/run.cpython-311.pyc differ diff --git a/harness/A/__pycache__/sweep.cpython-311.pyc b/harness/A/__pycache__/sweep.cpython-311.pyc index 1c44e70d568a5b01c8a19b8562e6cd8fccc243bf..5c8723025c38ff958b5cefc9b295ee500630690d 100644 Binary files a/harness/A/__pycache__/sweep.cpython-311.pyc and b/harness/A/__pycache__/sweep.cpython-311.pyc differ diff --git a/harness/A/launch.py b/harness/A/launch.py index f16f74cc4689fcc5f8ec2e33358b67ba8965423a..ad6238fecdb08d730b0cf05c7276b05d04ced604 100644 --- a/harness/A/launch.py +++ b/harness/A/launch.py @@ -103,9 +103,10 @@ def launch( extended=False, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, ): """Answer every question for ``selected`` scenes, sharded across every visible GPU.""" - condition = f"{model}/{frame_selection}/{frame_count}" + protocol = "extended" if extended else "base" + condition = f"{model}/{protocol}/{frame_selection}/{frame_count}" run = _load_run_module() - root = run.results_dir_for(model, frame_selection, frame_count, results_dir) + root = run.results_dir_for(model, protocol, frame_selection, frame_count, results_dir) pending = [] completed = 0 for scene in selected: diff --git a/harness/A/run.py b/harness/A/run.py index af11e58bc7799c684fe0c355f3189ebe6faff8a5..dca976b9e541c988e2202d4089b20b5b89fd68c4 100644 --- a/harness/A/run.py +++ b/harness/A/run.py @@ -93,11 +93,13 @@ def load_questions(jsonl_path=None, scene=None, scenes=None, limit=None): return rows -def results_dir_for(model, frame_selection, frame_count, results_dir=None): - """Return the result root isolated by model + frame-selection + frame-count.""" +def results_dir_for(model, protocol, frame_selection, frame_count, results_dir=None): + """Return the result root isolated by model + protocol + frame-selection + + frame-count. ``protocol`` is "base" (16-token) or "extended" (2048-token) -- a real + path segment, so the two protocols' records can never collide on disk.""" if results_dir is not None: return Path(results_dir) - return RESULTS_DIR / model / frame_selection / str(frame_count) + return RESULTS_DIR / model / protocol / frame_selection / str(frame_count) def _build_record(row, prompt, answer, metric_name, score, model, model_path, frame_info): @@ -108,7 +110,11 @@ def _build_record(row, prompt, answer, metric_name, score, model, model_path, fr "device": answer["device"], "dtype": answer["dtype"], "library_versions": answer["library_versions"], - "condition": f"{frame_info['frame_selection']}:{frame_info['frame_count']}", + "condition": ( + f"{frame_info['protocol']}:{frame_info['frame_selection']}:" + f"{frame_info['frame_count']}" + ), + "protocol": frame_info["protocol"], "frame_selection": frame_info["frame_selection"], "frame_count": frame_info["frame_count"], "video_path": frame_info["video_path"], @@ -153,7 +159,8 @@ def write_question_result( row, prompt, answer, metric_name, score, model, model_path, frame_info ) root = results_dir_for( - model, frame_info["frame_selection"], frame_info["frame_count"], results_dir + model, frame_info["protocol"], frame_info["frame_selection"], + frame_info["frame_count"], results_dir, ) scene_dir = root / record["scene"] scene_dir.mkdir(parents=True, exist_ok=True) @@ -239,6 +246,7 @@ def run( )["vsibench_score"] metric_name, score = _scalar_score(row["question_type"], score_doc) frame_info = { + "protocol": "extended" if extended else "base", "video_path": cached["video_path"], "frame_timestamps": cached["frame_timestamps"], "frame_indices": cached["frame_indices"], @@ -279,7 +287,7 @@ def main(): parser.add_argument( "--results-dir", default=None, - help="override the default results/A/// root", + help="override the default results/A//// root", ) parser.add_argument( "--no-write", diff --git a/harness/A/sweep.py b/harness/A/sweep.py index 8b89ed62ead89b9687a74d0a3bad2b12bd52f9ce..40b7228361638f41d70dca7232839f124840c81a 100644 --- a/harness/A/sweep.py +++ b/harness/A/sweep.py @@ -65,14 +65,21 @@ def build_plan(models, frame_selections, frame_counts): ] -def sweep(models, frame_selections, frame_counts, selected_scenes, results_dir=None, rebuild=False): +def sweep( + models, frame_selections, frame_counts, selected_scenes, results_dir=None, rebuild=False, + extended=False, +): """Run every (model, frame_selection, frame_count) triple across all visible GPUs.""" plan = build_plan(models, frame_selections, frame_counts) + protocol = "extended" if extended else "base" for index, (model, frame_selection, frame_count) in enumerate(plan, start=1): - print(f"=== sweep {index}/{len(plan)}: {model}/{frame_selection}/{frame_count} ===", flush=True) + print( + f"=== sweep {index}/{len(plan)}: {model}/{protocol}/{frame_selection}/{frame_count} ===", + flush=True, + ) harness_launch.launch( model, frame_selection, frame_count, selected_scenes, - results_dir=results_dir, rebuild=rebuild, + results_dir=results_dir, rebuild=rebuild, extended=extended, ) @@ -96,6 +103,11 @@ def main(): ) parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") + parser.add_argument( + "--extended", action="store_true", + help="run the whole sweep under the extended 2048-token protocol instead of the " + "fixed 16-token VSI-Bench protocol (the same flag harness.A.run/launch take)", + ) args = parser.parse_args() if args.scene and args.scenes: parser.error("positional scene and --scenes cannot be used together") @@ -119,7 +131,7 @@ def main(): sweep( models, frame_selections, frame_counts, selected, - results_dir=args.results_dir, rebuild=args.rebuild, + results_dir=args.results_dir, rebuild=args.rebuild, extended=args.extended, ) diff --git a/harness/B/__pycache__/launch.cpython-311.pyc b/harness/B/__pycache__/launch.cpython-311.pyc index 9a9e313ab8d6f206f5607fbab66b86e0e2c507db..b7b1868f28b3861caf066549a88f5bf014f2d0da 100644 Binary files a/harness/B/__pycache__/launch.cpython-311.pyc and b/harness/B/__pycache__/launch.cpython-311.pyc differ diff --git a/harness/B/__pycache__/run.cpython-311.pyc b/harness/B/__pycache__/run.cpython-311.pyc index f1277f1ad809cbcb27b4a26f76a436b88fcd34ba..b9040412c85083664c9460042426b558fce89808 100644 Binary files a/harness/B/__pycache__/run.cpython-311.pyc and b/harness/B/__pycache__/run.cpython-311.pyc differ diff --git a/harness/B/__pycache__/sweep.cpython-311.pyc b/harness/B/__pycache__/sweep.cpython-311.pyc index c59a5d6c97993337f5e07a3083a9655ce74d5f0a..a76a1240e45008678bafa9e4730402d246a40fab 100644 Binary files a/harness/B/__pycache__/sweep.cpython-311.pyc and b/harness/B/__pycache__/sweep.cpython-311.pyc differ diff --git a/harness/B/launch.py b/harness/B/launch.py index ffe9c546944062ec1b89d4bd7150d2172497a50d..8696b8e357a2dc3e6361a9395efbf89c068aea2f 100644 --- a/harness/B/launch.py +++ b/harness/B/launch.py @@ -50,7 +50,7 @@ def _load_run_module(): def _worker( tasks, results, model, spatial_code_format, input_selection, frame_count, depth, tracking, - results_dir, gpu, cpu_threads, reasoning_budget, force_budget, + results_dir, gpu, cpu_threads, extended, reasoning_budget, force_budget, ): if gpu is not None: os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) @@ -82,6 +82,7 @@ def _worker( scene=scene, results_dir=results_dir, adapter=adapter, + extended=extended, reasoning_budget=reasoning_budget, force_budget=force_budget, ) @@ -98,13 +99,18 @@ def _worker( def launch( model, spatial_code_format, input_selection, frame_count, selected, depth=DEFAULT_DEPTH, tracking=DEFAULT_TRACKING, results_dir=None, rebuild=False, - reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, + extended=True, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, ): """Answer every question for ``selected`` scenes, sharded across every visible GPU.""" - condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count}" + protocol = "extended" if extended else "base" + condition = ( + f"{model}/{protocol}/{spatial_code_format}/{depth}/{tracking}" + f"/{input_selection}/{frame_count}" + ) run = _load_run_module() root = run.results_dir_for( - model, spatial_code_format, depth, tracking, input_selection, frame_count, results_dir + model, protocol, spatial_code_format, depth, tracking, input_selection, frame_count, + results_dir, ) pending = [] completed = 0 @@ -142,7 +148,8 @@ def launch( target=_worker, args=( tasks, results, model, spatial_code_format, input_selection, frame_count, - depth, tracking, results_dir, gpu, cpu_threads, reasoning_budget, force_budget, + depth, tracking, results_dir, gpu, cpu_threads, extended, reasoning_budget, + force_budget, ), ) for gpu in assignments @@ -189,6 +196,10 @@ def main(): parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES) parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") + parser.add_argument( + "--base-protocol", action="store_true", + help="run harness.A's exact fixed 16-token protocol instead of the extended default", + ) parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) args = parser.parse_args() @@ -210,6 +221,7 @@ def main(): launch( args.model, args.spatial_code_format, args.input_selection, args.frames, selected, depth=args.depth, tracking=args.tracking, results_dir=args.results_dir, rebuild=args.rebuild, + extended=not args.base_protocol, reasoning_budget=args.reasoning_budget, force_budget=args.force_budget, ) diff --git a/harness/B/run.py b/harness/B/run.py index 8e6fc77f5b45acb145311be097bdaaebb9e3678a..f700ac2967b567c328a77fb1045694d15235cdf7 100644 --- a/harness/B/run.py +++ b/harness/B/run.py @@ -39,14 +39,17 @@ from harness.B import spatial_codes # noqa: E402 def results_dir_for( - model, spatial_code_format, depth, tracking, input_selection, frame_count, results_dir=None + model, protocol, spatial_code_format, depth, tracking, input_selection, frame_count, + results_dir=None, ): - """Return the result root isolated by model + spatial-code-format + depth + - tracking + input + frames.""" + """Return the result root isolated by model + protocol + spatial-code-format + + depth + tracking + input + frames. ``protocol`` is "base" (16-token) or "extended" + (2048-token) -- a real path segment, so the two protocols' records can never collide + on disk.""" if results_dir is not None: return Path(results_dir) return ( - RESULTS_DIR / model / spatial_code_format / depth / tracking + RESULTS_DIR / model / protocol / spatial_code_format / depth / tracking / input_selection / str(frame_count) ) @@ -60,10 +63,11 @@ def _build_record(row, prompt, answer, metric_name, score, model, model_path, co "dtype": answer["dtype"], "library_versions": answer["library_versions"], "condition": ( - f"{code_info['spatial_code_format']}:{code_info['depth']}:" - f"{code_info['tracking']}:{code_info['input_selection']}:" - f"{code_info['frame_count']}" + f"{code_info['protocol']}:{code_info['spatial_code_format']}:" + f"{code_info['depth']}:{code_info['tracking']}:" + f"{code_info['input_selection']}:{code_info['frame_count']}" ), + "protocol": code_info["protocol"], "spatial_code_format": code_info["spatial_code_format"], "input_selection": code_info["input_selection"], "frame_count": code_info["frame_count"], @@ -108,6 +112,7 @@ def write_question_result( record = _build_record(row, prompt, answer, metric_name, score, model, model_path, code_info) root = results_dir_for( model, + code_info["protocol"], code_info["spatial_code_format"], code_info["depth"], code_info["tracking"], @@ -138,6 +143,7 @@ def run( results_dir=None, write_results=True, adapter=None, + extended=True, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, ): @@ -147,9 +153,11 @@ def run( Uses ``adapter.answer_extended`` (a large ``reasoning_budget`` first pass, with a short forced second call only if the model doesn't conclude within it) as the - standing default protocol -- not harness.A's fixed 16-token budget -- since working - through a full spatial-code JSON before answering benefits from more room than a - short visual caption does. + standing default protocol -- since working through a full spatial-code JSON before + answering benefits from more room than a short visual caption does. + ``extended=False`` runs harness.A's exact fixed 16-token base protocol instead + (plain ``adapter.answer``), so the protocol x representation grid can be measured + with the identical generation mechanism in every cell. Pass a pre-loaded ``adapter`` (as harness.B.launch's persistent per-GPU workers do) to reuse one already-loaded model across many calls; the caller then owns unloading @@ -176,8 +184,12 @@ def run( prompt = code_prompts.build_prompt( cached["code"], row["question_type"], row["question"], row.get("options") ) - answer = adapter.answer_extended( - [], prompt, reasoning_budget=reasoning_budget, force_budget=force_budget + answer = ( + adapter.answer_extended( + [], prompt, reasoning_budget=reasoning_budget, force_budget=force_budget + ) + if extended + else adapter.answer([], prompt) ) doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]} score_doc = vsi_official_eval.vsibench_process_results( @@ -185,6 +197,7 @@ def run( )["vsibench_score"] metric_name, score = _scalar_score(row["question_type"], score_doc) code_info = { + "protocol": "extended" if extended else "base", "spatial_code_format": spatial_code_format, "input_selection": input_selection, "frame_count": frame_count, @@ -229,12 +242,18 @@ def main(): parser.add_argument("--device", default="cuda") parser.add_argument( "--results-dir", default=None, - help="override the default results/B////// root", + help="override the default results/B////" + "/// root", ) parser.add_argument( "--no-write", action="store_true", help="skip writing per-question JSON files; print/score only", ) + parser.add_argument( + "--base-protocol", action="store_true", + help="run harness.A's exact fixed 16-token protocol (plain answer()) instead of " + "the extended 2048-token default", + ) parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) args = parser.parse_args() @@ -257,6 +276,7 @@ def main(): device=args.device, results_dir=args.results_dir, write_results=not args.no_write, + extended=not args.base_protocol, reasoning_budget=args.reasoning_budget, force_budget=args.force_budget, ) diff --git a/harness/B/sweep.py b/harness/B/sweep.py index a33d4e1521212b1b74dc3154a25f8191589a0730..4da739042a48710d078cf0fef1362fe26ae0ebb7 100644 --- a/harness/B/sweep.py +++ b/harness/B/sweep.py @@ -52,20 +52,23 @@ def build_plan(models, spatial_code_formats, input_selections, frame_counts, dep def sweep( models, spatial_code_formats, input_selections, frame_counts, selected_scenes, depths=(DEFAULT_DEPTH,), trackings=(DEFAULT_TRACKING,), results_dir=None, rebuild=False, + extended=True, ): """Run every sweep combination across all visible GPUs.""" plan = build_plan(models, spatial_code_formats, input_selections, frame_counts, depths, trackings) + protocol = "extended" if extended else "base" for index, (model, spatial_code_format, depth, tracking, input_selection, frame_count) in enumerate( plan, start=1 ): print( - f"=== sweep {index}/{len(plan)}: " - f"{model}/{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count} ===", + f"=== sweep {index}/{len(plan)}: {model}/{protocol}/" + f"{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count} ===", flush=True, ) harness_launch.launch( model, spatial_code_format, input_selection, frame_count, selected_scenes, depth=depth, tracking=tracking, results_dir=results_dir, rebuild=rebuild, + extended=extended, ) @@ -100,6 +103,11 @@ def main(): ) parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") + parser.add_argument( + "--base-protocol", action="store_true", + help="run the whole sweep under harness.A's exact fixed 16-token protocol " + "instead of the extended 2048-token default", + ) args = parser.parse_args() if args.scene and args.scenes: parser.error("positional scene and --scenes cannot be used together") @@ -132,6 +140,7 @@ def main(): models, spatial_code_formats, input_selections, frame_counts, selected, depths=depths, trackings=trackings, results_dir=args.results_dir, rebuild=args.rebuild, + extended=not args.base_protocol, ) diff --git a/harness/C/__pycache__/launch.cpython-311.pyc b/harness/C/__pycache__/launch.cpython-311.pyc index 715df8b6698267d44c321f4a829396f6ead12a95..bf2fb2f0e4bf32bc14dce0fcb57df28754ba7d42 100644 Binary files a/harness/C/__pycache__/launch.cpython-311.pyc and b/harness/C/__pycache__/launch.cpython-311.pyc differ diff --git a/harness/C/__pycache__/run.cpython-311.pyc b/harness/C/__pycache__/run.cpython-311.pyc index 9d25e58c1f90f25fdfd2da8ac7b38693220b2511..0cd0f6b6665779534f14d73e2640e3f0bfb4edd2 100644 Binary files a/harness/C/__pycache__/run.cpython-311.pyc and b/harness/C/__pycache__/run.cpython-311.pyc differ diff --git a/harness/C/__pycache__/sweep.cpython-311.pyc b/harness/C/__pycache__/sweep.cpython-311.pyc index 4e7dbc820b00bd6b30bbe15e3d1dd36eb7e38c45..eb86f490c8f75e912c27d019ec8f6e7cac44c77f 100644 Binary files a/harness/C/__pycache__/sweep.cpython-311.pyc and b/harness/C/__pycache__/sweep.cpython-311.pyc differ diff --git a/harness/C/launch.py b/harness/C/launch.py index ff3b302919d1c2b64bdfe201c74e24b25c85d5f7..8dda962d837d58df6ceae556b850e61b564ec525 100644 --- a/harness/C/launch.py +++ b/harness/C/launch.py @@ -50,7 +50,7 @@ def _load_run_module(): def _worker( tasks, results, model, spatial_code_format, input_selection, frame_count, depth, tracking, - results_dir, gpu, cpu_threads, reasoning_budget, force_budget, + results_dir, gpu, cpu_threads, extended, reasoning_budget, force_budget, ): if gpu is not None: os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) @@ -85,6 +85,7 @@ def _worker( scene=scene, results_dir=results_dir, adapter=adapter, + extended=extended, reasoning_budget=reasoning_budget, force_budget=force_budget, ) @@ -101,13 +102,18 @@ def _worker( def launch( model, spatial_code_format, input_selection, frame_count, selected, depth=DEFAULT_DEPTH, tracking=DEFAULT_TRACKING, results_dir=None, rebuild=False, - reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, + extended=True, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, ): """Answer every question for ``selected`` scenes, sharded across every visible GPU.""" - condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count}" + protocol = "extended" if extended else "base" + condition = ( + f"{model}/{protocol}/{spatial_code_format}/{depth}/{tracking}" + f"/{input_selection}/{frame_count}" + ) run = _load_run_module() root = run.results_dir_for( - model, spatial_code_format, depth, tracking, input_selection, frame_count, results_dir + model, protocol, spatial_code_format, depth, tracking, input_selection, frame_count, + results_dir, ) pending = [] completed = 0 @@ -145,7 +151,8 @@ def launch( target=_worker, args=( tasks, results, model, spatial_code_format, input_selection, frame_count, - depth, tracking, results_dir, gpu, cpu_threads, reasoning_budget, force_budget, + depth, tracking, results_dir, gpu, cpu_threads, extended, reasoning_budget, + force_budget, ), ) for gpu in assignments @@ -192,6 +199,10 @@ def main(): parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES) parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") + parser.add_argument( + "--base-protocol", action="store_true", + help="run harness.A's exact fixed 16-token protocol instead of the extended default", + ) parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) args = parser.parse_args() @@ -213,6 +224,7 @@ def main(): launch( args.model, args.spatial_code_format, args.input_selection, args.frames, selected, depth=args.depth, tracking=args.tracking, results_dir=args.results_dir, rebuild=args.rebuild, + extended=not args.base_protocol, reasoning_budget=args.reasoning_budget, force_budget=args.force_budget, ) diff --git a/harness/C/run.py b/harness/C/run.py index deb3ee8a58f95bb3315718aeab51475fb711a76b..33f5be91be11d1bc733f2bf841921797cf2a11f5 100644 --- a/harness/C/run.py +++ b/harness/C/run.py @@ -40,14 +40,17 @@ from harness.C import prompts as combined_prompts # noqa: E402 def results_dir_for( - model, spatial_code_format, depth, tracking, input_selection, frame_count, results_dir=None + model, protocol, spatial_code_format, depth, tracking, input_selection, frame_count, + results_dir=None, ): - """Return the result root isolated by model + spatial-code-format + depth + - tracking + input + frames.""" + """Return the result root isolated by model + protocol + spatial-code-format + + depth + tracking + input + frames. ``protocol`` is "base" (16-token) or "extended" + (2048-token) -- a real path segment, so the two protocols' records can never collide + on disk.""" if results_dir is not None: return Path(results_dir) return ( - RESULTS_DIR / model / spatial_code_format / depth / tracking + RESULTS_DIR / model / protocol / spatial_code_format / depth / tracking / input_selection / str(frame_count) ) @@ -61,10 +64,11 @@ def _build_record(row, prompt, answer, metric_name, score, model, model_path, so "dtype": answer["dtype"], "library_versions": answer["library_versions"], "condition": ( - f"{source_info['spatial_code_format']}:{source_info['depth']}:" - f"{source_info['tracking']}:{source_info['input_selection']}:" - f"{source_info['frame_count']}" + f"{source_info['protocol']}:{source_info['spatial_code_format']}:" + f"{source_info['depth']}:{source_info['tracking']}:" + f"{source_info['input_selection']}:{source_info['frame_count']}" ), + "protocol": source_info["protocol"], "spatial_code_format": source_info["spatial_code_format"], "input_selection": source_info["input_selection"], "frame_count": source_info["frame_count"], @@ -112,6 +116,7 @@ def write_question_result( record = _build_record(row, prompt, answer, metric_name, score, model, model_path, source_info) root = results_dir_for( model, + source_info["protocol"], source_info["spatial_code_format"], source_info["depth"], source_info["tracking"], @@ -142,6 +147,7 @@ def run( results_dir=None, write_results=True, adapter=None, + extended=True, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, ): @@ -152,7 +158,10 @@ def run( Uses ``adapter.answer_extended`` (a large ``reasoning_budget`` first pass, with a short forced second call only if the model doesn't conclude within it) as the standing default protocol, same as harness.B, since C combines the same complex - spatial-code JSON with the video frames. + spatial-code JSON with the video frames. ``extended=False`` runs harness.A's exact + fixed 16-token base protocol instead (plain ``adapter.answer``), so the protocol x + representation grid can be measured with the identical generation mechanism in + every cell. Pass a pre-loaded ``adapter`` (as harness.C.launch's persistent per-GPU workers do) to reuse one already-loaded model across many calls; the caller then owns unloading @@ -190,9 +199,13 @@ def run( prompt = combined_prompts.build_prompt( cached["code"], row["question_type"], row["question"], row.get("options") ) - answer = adapter.answer_extended( - cached["frame_images"], prompt, - reasoning_budget=reasoning_budget, force_budget=force_budget, + answer = ( + adapter.answer_extended( + cached["frame_images"], prompt, + reasoning_budget=reasoning_budget, force_budget=force_budget, + ) + if extended + else adapter.answer(cached["frame_images"], prompt) ) doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]} score_doc = vsi_official_eval.vsibench_process_results( @@ -200,6 +213,7 @@ def run( )["vsibench_score"] metric_name, score = _scalar_score(row["question_type"], score_doc) source_info = { + "protocol": "extended" if extended else "base", "spatial_code_format": spatial_code_format, "input_selection": input_selection, "frame_count": frame_count, @@ -247,12 +261,18 @@ def main(): parser.add_argument("--device", default="cuda") parser.add_argument( "--results-dir", default=None, - help="override the default results/C////// root", + help="override the default results/C////" + "/// root", ) parser.add_argument( "--no-write", action="store_true", help="skip writing per-question JSON files; print/score only", ) + parser.add_argument( + "--base-protocol", action="store_true", + help="run harness.A's exact fixed 16-token protocol (plain answer()) instead of " + "the extended 2048-token default", + ) parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) args = parser.parse_args() @@ -275,6 +295,7 @@ def main(): device=args.device, results_dir=args.results_dir, write_results=not args.no_write, + extended=not args.base_protocol, reasoning_budget=args.reasoning_budget, force_budget=args.force_budget, ) diff --git a/harness/D/__pycache__/launch.cpython-311.pyc b/harness/D/__pycache__/launch.cpython-311.pyc index 24b17332ef7daf38a02b63abb88097c3ec1f5984..d817b8e804e2fcc5b27feb440ae633876fb4f968 100644 Binary files a/harness/D/__pycache__/launch.cpython-311.pyc and b/harness/D/__pycache__/launch.cpython-311.pyc differ diff --git a/harness/D/__pycache__/run.cpython-311.pyc b/harness/D/__pycache__/run.cpython-311.pyc index 51b37d4f0d0e7391984e5beae5e833bf9265b984..034600b553e4b451149c0ccfe47450b113ecceb0 100644 Binary files a/harness/D/__pycache__/run.cpython-311.pyc and b/harness/D/__pycache__/run.cpython-311.pyc differ diff --git a/harness/D/__pycache__/sweep.cpython-311.pyc b/harness/D/__pycache__/sweep.cpython-311.pyc index e6885d8ac398e0d280f2aa9840dcddff186afc24..331c316e787a926959f32ca5fd988b24a125993f 100644 Binary files a/harness/D/__pycache__/sweep.cpython-311.pyc and b/harness/D/__pycache__/sweep.cpython-311.pyc differ diff --git a/harness/D/run.py b/harness/D/run.py index d8b6b4c44837dd261fb130831cbb684ae160fdc0..53e577ffa0d20353a5cf0d9bdaf53f507309920d 100644 --- a/harness/D/run.py +++ b/harness/D/run.py @@ -28,11 +28,13 @@ from harness.D import prompts as code_prompts # noqa: E402 from harness.D import spatial_codes # noqa: E402 -def results_dir_for(model, spatial_code_format, results_dir=None): - """Return the result root isolated by model + spatial-code-format.""" +def results_dir_for(model, protocol, spatial_code_format, results_dir=None): + """Return the result root isolated by model + protocol + spatial-code-format. + ``protocol`` is "base" (16-token) or "extended" (2048-token) -- a real path + segment, so the two protocols' records can never collide on disk.""" if results_dir is not None: return Path(results_dir) - return RESULTS_DIR / model / spatial_code_format + return RESULTS_DIR / model / protocol / spatial_code_format def _build_record(row, prompt, answer, metric_name, score, model, model_path, code_info): @@ -43,7 +45,8 @@ def _build_record(row, prompt, answer, metric_name, score, model, model_path, co "device": answer["device"], "dtype": answer["dtype"], "library_versions": answer["library_versions"], - "condition": code_info["spatial_code_format"], + "condition": f"{code_info['protocol']}:{code_info['spatial_code_format']}", + "protocol": code_info["protocol"], "spatial_code_format": code_info["spatial_code_format"], "spatial_code_path": code_info["spatial_code_path"], "scene": row["scene_name"], @@ -82,7 +85,9 @@ def write_question_result( ): """Write one question's full, untruncated result record. Return (path, record).""" record = _build_record(row, prompt, answer, metric_name, score, model, model_path, code_info) - root = results_dir_for(model, code_info["spatial_code_format"], results_dir) + root = results_dir_for( + model, code_info["protocol"], code_info["spatial_code_format"], results_dir + ) scene_dir = root / record["scene"] scene_dir.mkdir(parents=True, exist_ok=True) path = scene_dir / f"{row['id']}.json" @@ -102,8 +107,10 @@ def run( results_dir=None, write_results=True, adapter=None, + extended=True, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, + code_transform=None, ): """Answer every matching question with one model, given its scene's GROUND-TRUTH spatial code as text (no video frames). Each question's full record is written to @@ -111,7 +118,14 @@ def run( Uses ``adapter.answer_extended`` as the standing default protocol, same as harness.B -- working through a full spatial-code JSON before answering benefits - from more room than a short visual caption does. + from more room than a short visual caption does. ``extended=False`` runs + harness.A's exact fixed 16-token base protocol instead (plain ``adapter.answer``). + + ``code_transform``, when given, is called as ``code_transform(code, scene_id, + spatial_code_format)`` on each freshly loaded code and its return value is what + the prompt is built from -- the hook the corruption module (README Theme 8) uses + to run corrupted codes through this EXACT prompt/adapter path instead of a + duplicated one. ``None`` (the default) leaves behavior byte-identical to before. Pass a pre-loaded ``adapter`` (as harness.D.launch's persistent per-GPU workers do) to reuse one already-loaded model across many calls; the caller then owns unloading @@ -131,13 +145,19 @@ def run( scene_id = row["scene_name"] if scene_id not in code_cache: code, path = spatial_codes.load_spatial_code(scene_id, spatial_code_format) + if code_transform is not None: + code = code_transform(code, scene_id, spatial_code_format) code_cache[scene_id] = {"code": code, "path": path} cached = code_cache[scene_id] prompt = code_prompts.build_prompt( cached["code"], row["question_type"], row["question"], row.get("options") ) - answer = adapter.answer_extended( - [], prompt, reasoning_budget=reasoning_budget, force_budget=force_budget + answer = ( + adapter.answer_extended( + [], prompt, reasoning_budget=reasoning_budget, force_budget=force_budget + ) + if extended + else adapter.answer([], prompt) ) doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]} score_doc = vsi_official_eval.vsibench_process_results( @@ -145,6 +165,7 @@ def run( )["vsibench_score"] metric_name, score = _scalar_score(row["question_type"], score_doc) code_info = { + "protocol": "extended" if extended else "base", "spatial_code_format": spatial_code_format, "spatial_code_path": cached["path"], } @@ -178,12 +199,17 @@ def main(): parser.add_argument("--device", default="cuda") parser.add_argument( "--results-dir", default=None, - help="override the default results/D// root", + help="override the default results/D/// root", ) parser.add_argument( "--no-write", action="store_true", help="skip writing per-question JSON files; print/score only", ) + parser.add_argument( + "--base-protocol", action="store_true", + help="run harness.A's exact fixed 16-token protocol (plain answer()) instead of " + "the extended 2048-token default", + ) parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) args = parser.parse_args() @@ -200,6 +226,7 @@ def main(): device=args.device, results_dir=args.results_dir, write_results=not args.no_write, + extended=not args.base_protocol, reasoning_budget=args.reasoning_budget, force_budget=args.force_budget, ) diff --git a/harness/E/__pycache__/launch.cpython-311.pyc b/harness/E/__pycache__/launch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64a319713e80ea343830f31cb1d0c5fe2a815be1 Binary files /dev/null and b/harness/E/__pycache__/launch.cpython-311.pyc differ diff --git a/harness/E/run.py b/harness/E/run.py new file mode 100644 index 0000000000000000000000000000000000000000..6ac4c2bd5f21d96ba0c8f06b8d2cde7fe6634e2b --- /dev/null +++ b/harness/E/run.py @@ -0,0 +1,218 @@ +"""Run one VLM over VSI-Bench questions completely blind -- question text only. + +Writes one JSON file per question in the identical shape harness.A/B/C/D use -- with no +frame or spatial-code provenance fields at all, since E receives no scene input of any +kind. Scoring reuses the same real, unmodified official scorer every harness uses. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402 +from harness.A import models as vlm_models # noqa: E402 +from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402 +from harness.E import RESULTS_DIR # noqa: E402 +from harness.E import prompts as blind_prompts # noqa: E402 + + +def results_dir_for(model, protocol, results_dir=None): + """Return the result root isolated by model + protocol. ``protocol`` is "base" + (16-token) or "extended" (2048-token) -- a real path segment, so the two protocols' + records can never collide on disk.""" + if results_dir is not None: + return Path(results_dir) + return RESULTS_DIR / model / protocol + + +def _build_record(row, prompt, answer, metric_name, score, model, model_path, protocol): + """Assemble one question's full, untruncated result record (nothing summarized).""" + return { + "model": model, + "model_path": str(model_path), + "device": answer["device"], + "dtype": answer["dtype"], + "library_versions": answer["library_versions"], + "condition": protocol, + "protocol": protocol, + "scene": row["scene_name"], + "dataset": row.get("dataset"), + "question_id": row["id"], + "question_type": row["question_type"], + "question": row["question"], + "options": row.get("options"), + "full_prompt": prompt, + "rendered_prompt": answer["prompt_text"], + "answer_expected": row["ground_truth"], + "answer_given": answer["answer_text"], + "answer_raw": answer["answer_raw"], + "input_token_count": answer["input_token_count"], + "vision_input_shapes": answer["vision_input_shapes"], + "output_token_ids": answer["output_token_ids"], + "output_token_count": answer["output_token_count"], + "hit_token_limit": answer["hit_token_limit"], + "eos_token_ids": answer["eos_token_ids"], + "generation_seconds": answer["generation_seconds"], + "generation_config": answer["generation_config"], + "reasoning_text": answer.get("reasoning_text"), + "reasoning_raw": answer.get("reasoning_raw"), + "reasoning_token_ids": answer.get("reasoning_token_ids"), + "reasoning_token_count": answer.get("reasoning_token_count"), + "reasoning_hit_limit": answer.get("reasoning_hit_limit"), + "forced": answer.get("forced", False), + "forced_input_token_count": answer.get("forced_input_token_count"), + "metric": metric_name, + "score": score, + } + + +def write_question_result( + row, prompt, answer, metric_name, score, model, model_path, protocol, results_dir=None +): + """Write one question's full, untruncated result record. Return (path, record).""" + record = _build_record(row, prompt, answer, metric_name, score, model, model_path, protocol) + root = results_dir_for(model, protocol, results_dir) + scene_dir = root / record["scene"] + scene_dir.mkdir(parents=True, exist_ok=True) + path = scene_dir / f"{row['id']}.json" + with path.open("w", encoding="utf-8") as stream: + json.dump(record, stream, indent=1) + return path, record + + +def run( + model, + scene=None, + scenes=None, + limit=None, + device="cuda", + jsonl_path=None, + results_dir=None, + write_results=True, + adapter=None, + extended=False, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, +): + """Answer every matching question with one model, completely blind (question text + only, no frames, no spatial code). Each question's full record is written to its + own JSON file as soon as it is answered (unless ``write_results=False``). + + Base 16-token protocol by default, exactly like harness.A; ``extended=True`` + switches to the same ``answer_extended`` protocol every other harness supports. + + Pass a pre-loaded ``adapter`` (as harness.E.launch's persistent per-GPU workers do) + to reuse one already-loaded model across many calls; the caller then owns unloading + it. Without one, ``run`` loads and unloads its own adapter, same as harness.A. + """ + rows = load_questions(jsonl_path, scene, scenes, limit) + if not rows: + return [] + owns_adapter = adapter is None + if owns_adapter: + adapter = vlm_models.get_adapter(model) + adapter.load_model(device) + protocol = "extended" if extended else "base" + results = [] + try: + for row in rows: + prompt = blind_prompts.build_prompt( + row["question_type"], row["question"], row.get("options") + ) + answer = ( + adapter.answer_extended( + [], prompt, reasoning_budget=reasoning_budget, force_budget=force_budget + ) + if extended + else adapter.answer([], prompt) + ) + doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]} + score_doc = vsi_official_eval.vsibench_process_results( + doc, [answer["answer_text"]] + )["vsibench_score"] + metric_name, score = _scalar_score(row["question_type"], score_doc) + if write_results: + path, record = write_question_result( + row, prompt, answer, metric_name, score, model, adapter.model_path, + protocol, results_dir, + ) + else: + path = None + record = _build_record( + row, prompt, answer, metric_name, score, model, adapter.model_path, protocol + ) + record["result_path"] = str(path) if path else None + results.append(record) + finally: + if owns_adapter: + adapter.unload() + return results + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", required=True, choices=vlm_models.available_models()) + parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene") + parser.add_argument("--limit", type=int, default=None, help="cap the number of questions") + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--results-dir", default=None, + help="override the default results/E// root", + ) + parser.add_argument( + "--no-write", action="store_true", + help="skip writing per-question JSON files; print/score only", + ) + parser.add_argument( + "--extended", action="store_true", + help=( + f"use a {EXTENDED_MAX_NEW_TOKENS}-token reasoning budget instead of the fixed " + f"{MAX_NEW_TOKENS}-token VSI-Bench protocol, with a short forced second call " + "only if the model doesn't conclude within it" + ), + ) + parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) + parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) + args = parser.parse_args() + if args.reasoning_budget < 1: + parser.error("--reasoning-budget must be positive") + if args.force_budget < 1: + parser.error("--force-budget must be positive") + + results = run( + args.model, + scene=args.scene, + limit=args.limit, + device=args.device, + results_dir=args.results_dir, + write_results=not args.no_write, + extended=args.extended, + reasoning_budget=args.reasoning_budget, + force_budget=args.force_budget, + ) + + for result in results: + print( + f"[{result['scene']}#{result['question_id']}] {result['question_type']}: " + f"pred={result['answer_given']!r} gt={result['answer_expected']!r} " + f"score={result['score']} ({result['generation_seconds']:.2f}s) -> " + f"{result['result_path']}" + ) + if results: + mean_score = sum(r["score"] for r in results) / len(results) + total_seconds = sum(r["generation_seconds"] for r in results) + print( + f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, " + f"total generation time={total_seconds:.1f}s" + ) + + +if __name__ == "__main__": + main() diff --git a/tests/test_C/test_run.py b/tests/test_C/test_run.py index c31960b86f6706cc4d8e38c3c39ecc761f1bf2a8..ce07db0739edd0a2936e60dcbc9e3796e7db7bb4 100644 --- a/tests/test_C/test_run.py +++ b/tests/test_C/test_run.py @@ -40,6 +40,7 @@ _FAKE_ROW = { } _FAKE_SOURCE_INFO = { + "protocol": "extended", "spatial_code_format": "explicit", "input_selection": "selective", "frame_count": 64, @@ -53,15 +54,18 @@ _FAKE_SOURCE_INFO = { def test_results_dir_for_matches_established_dimension_nesting(): - root = harness_run.results_dir_for("qwen3.5-4b", "compact", "metric", "tracking", "uniform", 32) + root = harness_run.results_dir_for( + "qwen3.5-4b", "extended", "compact", "metric", "tracking", "uniform", 32 + ) assert root == ( - C.RESULTS_DIR / "qwen3.5-4b" / "compact" / "metric" / "tracking" / "uniform" / "32" + C.RESULTS_DIR / "qwen3.5-4b" / "extended" / "compact" / "metric" / "tracking" + / "uniform" / "32" ) def test_results_dir_for_honors_explicit_override(tmp_path): root = harness_run.results_dir_for( - "qwen3.5-4b", "explicit", "relative", "no tracking", "selective", 16, tmp_path + "qwen3.5-4b", "base", "explicit", "relative", "no tracking", "selective", 16, tmp_path ) assert root == tmp_path @@ -86,7 +90,8 @@ def test_build_record_carries_both_frame_and_spatial_code_provenance(): assert record["question"] == "How many chairs?" assert record["answer_given"] == "4" assert record["vision_input_shapes"] == _FAKE_ANSWER["vision_input_shapes"] - assert record["condition"] == "explicit:metric:tracking:selective:64" + assert record["condition"] == "extended:explicit:metric:tracking:selective:64" + assert record["protocol"] == "extended" assert record["score"] == 1.0 diff --git a/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc b/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc index 68626dd5511c0f320962ee743d16a1bcd6a26120..90a5adcdcd786b0bf723d4835381d656c175a681 100644 Binary files a/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc and b/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc.323676 b/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc.323676 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc.323807 b/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc.323807 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_D/test_run.py b/tests/test_D/test_run.py index df02c80fd50f32fc7432d0577ad866ea8048cc82..da97f7d9ca41db4f1cf0b1d26a9ed86dfa0e3fed 100644 --- a/tests/test_D/test_run.py +++ b/tests/test_D/test_run.py @@ -40,18 +40,19 @@ _FAKE_ROW = { } _FAKE_CODE_INFO = { + "protocol": "extended", "spatial_code_format": "explicit", "spatial_code_path": "/workspace/data/spatial codes/ground truth/explicit/scene0001_00.json", } -def test_results_dir_for_matches_model_and_format_only(): - root = harness_run.results_dir_for("qwen3.5-4b", "compact") - assert root == D.RESULTS_DIR / "qwen3.5-4b" / "compact" +def test_results_dir_for_matches_model_protocol_and_format_only(): + root = harness_run.results_dir_for("qwen3.5-4b", "extended", "compact") + assert root == D.RESULTS_DIR / "qwen3.5-4b" / "extended" / "compact" def test_results_dir_for_honors_explicit_override(tmp_path): - root = harness_run.results_dir_for("qwen3.5-4b", "explicit", tmp_path) + root = harness_run.results_dir_for("qwen3.5-4b", "base", "explicit", tmp_path) assert root == tmp_path @@ -67,7 +68,8 @@ def test_build_record_preserves_every_field_untruncated(): assert record["spatial_code_format"] == "explicit" assert record["spatial_code_path"] == _FAKE_CODE_INFO["spatial_code_path"] # No depth/tracking/input_selection/frame_count -- ground truth has no such axis. - assert record["condition"] == "explicit" + assert record["condition"] == "extended:explicit" + assert record["protocol"] == "extended" assert "input_selection" not in record assert "frame_count" not in record assert "depth" not in record @@ -115,3 +117,37 @@ def test_build_record_defaults_reasoning_fields_when_absent(): ) assert record["reasoning_token_count"] is None assert record["forced"] is False + + +def test_run_code_transform_hook_replaces_the_loaded_code(monkeypatch, tmp_path): + """The corruption module's entry point: the hook's return value is what the + prompt is built from, and passing no hook keeps behavior identical.""" + scene = "13c3e046d7" + seen = {} + + def fake_load(scene_id, spatial_code_format): + return {"objects": {"chair": {"count": 1}}}, f"/fake/{scene_id}.json" + + class FakeAdapter: + model_path = "/fake/model" + + def answer_extended(self, frames, prompt, **kwargs): + seen["prompt"] = prompt + return { + "prompt_text": prompt, "answer_text": "1", "answer_raw": "1", + "input_token_count": 1, "vision_input_shapes": {}, + "output_token_ids": [1], "output_token_count": 1, + "hit_token_limit": False, "eos_token_ids": [1], + "generation_seconds": 0.0, "device": "cpu", "dtype": "float32", + "library_versions": {}, "generation_config": {}, + } + + monkeypatch.setattr(harness_run.spatial_codes, "load_spatial_code", fake_load) + replacement = {"objects": {"table": {"count": 9}}} + results = harness_run.run( + "qwen3.5-2b", scene=scene, adapter=FakeAdapter(), write_results=False, limit=1, + code_transform=lambda code, scene_id, fmt: replacement, + ) + assert results + assert '"table"' in seen["prompt"] + assert '"chair"' not in seen["prompt"] diff --git a/tests/test_E/__init__.py b/tests/test_E/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_E/__pycache__/__init__.cpython-311.pyc b/tests/test_E/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6850f53b38eb6ceaf19ecdba8b6580808e308896 Binary files /dev/null and b/tests/test_E/__pycache__/__init__.cpython-311.pyc differ diff --git a/tests/test_E/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc b/tests/test_E/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02da4644dac3ad6e5fe96ea0163c70c70ca5be7e Binary files /dev/null and b/tests/test_E/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_E/__pycache__/test_prompts.cpython-311-pytest-8.3.5.pyc b/tests/test_E/__pycache__/test_prompts.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a3c42e42c6f83bdbbf8368c44b72dd1515ecef7 Binary files /dev/null and b/tests/test_E/__pycache__/test_prompts.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_E/__pycache__/test_prompts.cpython-311-pytest-8.3.5.pyc.323676 b/tests/test_E/__pycache__/test_prompts.cpython-311-pytest-8.3.5.pyc.323676 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_E/__pycache__/test_prompts.cpython-311-pytest-8.3.5.pyc.323807 b/tests/test_E/__pycache__/test_prompts.cpython-311-pytest-8.3.5.pyc.323807 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_E/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc b/tests/test_E/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72d9a81fb9a15a0df544ce9c186b874043eb54d5 Binary files /dev/null and b/tests/test_E/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_E/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc.323676 b/tests/test_E/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc.323676 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_E/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc.323807 b/tests/test_E/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc.323807 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_E/__pycache__/test_sweep.cpython-311-pytest-8.3.5.pyc b/tests/test_E/__pycache__/test_sweep.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e14ec8ca0e44263aa41707d48be528531b1e7b4 Binary files /dev/null and b/tests/test_E/__pycache__/test_sweep.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_E/test_launch.py b/tests/test_E/test_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..87ebb0e51e40e8123c7d3aa0e4a520aa0ab531c4 --- /dev/null +++ b/tests/test_E/test_launch.py @@ -0,0 +1,53 @@ +"""Tests for harness/E/launch.py -- multi-GPU scene sharding for the blind floor.""" + +from harness.A.run import load_questions as harness_a_load_questions +from harness.E import launch + + +def test_launcher_imports(): + assert callable(launch.main) + + +def test_launch_skips_scene_already_fully_answered(tmp_path, capsys): + scene = "13c3e046d7" + rows = harness_a_load_questions(scene=scene) + assert rows, "fixture scene must have real questions in the VSI-Bench manifest" + + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + launch.launch("qwen3.5-2b", [scene], results_dir=tmp_path) + + output = capsys.readouterr().out + assert "skipped" in output + assert "DONE: 1 ok, 0 failed" in output + + +def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): + scene = "13c3e046d7" + rows = harness_a_load_questions(scene=scene) + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + monkeypatch.setattr(launch, "visible_gpus", lambda: []) + monkeypatch.setattr( + launch.mp, "get_context", + lambda *_: (_ for _ in ()).throw(RuntimeError("rebuild correctly reached worker dispatch")), + ) + try: + launch.launch("qwen3.5-2b", [scene], results_dir=tmp_path, rebuild=True) + except RuntimeError as exc: + assert "rebuild correctly reached worker dispatch" in str(exc) + else: + raise AssertionError("expected rebuild to force scene into the pending path") + + +def test_launch_protocols_use_separate_result_roots(): + run = launch._load_run_module() + base = run.results_dir_for("qwen3.5-2b", "base") + extended = run.results_dir_for("qwen3.5-2b", "extended") + assert base != extended diff --git a/tests/test_E/test_prompts.py b/tests/test_E/test_prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..41570afc460258064e85f423d6ec42294562c43d --- /dev/null +++ b/tests/test_E/test_prompts.py @@ -0,0 +1,48 @@ +"""Tests for harness/E/prompts.py -- blind question-only prompt construction.""" + +import pytest + +from harness.A.prompts import MCA_QUESTION_TYPES, NA_QUESTION_TYPES +from harness.E import prompts as blind_prompts + + +def test_na_question_prompt_is_question_plus_post_prompt_only(): + prompt = blind_prompts.build_prompt("object_counting", "How many chairs?") + assert prompt == "How many chairs?\n" + blind_prompts.NA_POST_PROMPT + + +def test_mca_question_prompt_includes_options_and_post_prompt(): + prompt = blind_prompts.build_prompt( + "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"] + ) + assert "Options:\nA. sofa\nB. table" in prompt + assert prompt.endswith(blind_prompts.MCA_POST_PROMPT) + + +def test_no_scene_language_anywhere(): + # Blind means blind: no context line claiming frames, video, or a spatial code. + prompt = blind_prompts.build_prompt("object_counting", "How many chairs?") + lowered = prompt.lower() + assert "frame" not in lowered + assert "video" not in lowered + assert "spatial code" not in lowered + + +def test_mca_question_requires_options(): + with pytest.raises(ValueError): + blind_prompts.build_prompt("route_planning", "Which way?", None) + + +def test_unknown_question_type_rejected(): + with pytest.raises(ValueError): + blind_prompts.build_prompt("not_a_real_type", "?", None) + + +@pytest.mark.parametrize("question_type", NA_QUESTION_TYPES) +def test_every_na_question_type_builds(question_type): + assert blind_prompts.build_prompt(question_type, "q?") + + +@pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES) +def test_every_mca_question_type_builds(question_type): + assert blind_prompts.build_prompt(question_type, "q?", ["A. x", "B. y"]) diff --git a/tests/test_E/test_run.py b/tests/test_E/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..be3114d89d56fbaf6233359a682b6ab939b896db --- /dev/null +++ b/tests/test_E/test_run.py @@ -0,0 +1,84 @@ +"""Tests for harness/E/run.py -- result-record shape and result-file writing.""" + +import json + +from harness import E +from harness.E import run as harness_run + +_FAKE_ANSWER = { + "prompt_text": "", + "answer_text": "4", + "answer_raw": "<|im_start|>assistant\n4<|im_end|>", + "input_token_count": 42, + "vision_input_shapes": {}, + "output_token_ids": [19, 151645], + "output_token_count": 2, + "hit_token_limit": False, + "eos_token_ids": [151645], + "generation_seconds": 0.2, + "device": "cuda", + "dtype": "bfloat16", + "library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"}, + "generation_config": { + "max_new_tokens": 16, + "do_sample": False, + "temperature": 0.0, + "top_p": None, + "top_k": None, + "enable_thinking": False, + }, +} + +_FAKE_ROW = { + "id": 7, + "scene_name": "scene0001_00", + "dataset": "scannet", + "question_type": "object_counting", + "question": "How many chairs?", + "options": None, + "ground_truth": "4", +} + + +def test_results_dir_for_matches_model_and_protocol_only(): + root = harness_run.results_dir_for("qwen3.5-4b", "base") + assert root == E.RESULTS_DIR / "qwen3.5-4b" / "base" + + +def test_results_dir_for_isolates_the_two_protocols(): + assert harness_run.results_dir_for("qwen3.5-4b", "base") != harness_run.results_dir_for( + "qwen3.5-4b", "extended" + ) + + +def test_results_dir_for_honors_explicit_override(tmp_path): + assert harness_run.results_dir_for("qwen3.5-4b", "base", tmp_path) == tmp_path + + +def test_build_record_has_no_scene_input_provenance(): + record = harness_run._build_record( + _FAKE_ROW, "full prompt text", _FAKE_ANSWER, "MRA:.5:.95:.05", 1.0, + "qwen3.5-4b", "/root/models/qwen3.5-4b", "base", + ) + assert record["condition"] == "base" + assert record["protocol"] == "base" + assert record["question"] == "How many chairs?" + assert record["answer_given"] == "4" + assert record["metric"] == "MRA:.5:.95:.05" + assert record["score"] == 1.0 + # Blind: no frame or spatial-code provenance of any kind. + assert "frame_selection" not in record + assert "video_path" not in record + assert "frame_indices" not in record + assert "spatial_code_format" not in record + assert "spatial_code_path" not in record + + +def test_write_question_result_writes_one_json_file_per_question(tmp_path): + path, record = harness_run.write_question_result( + _FAKE_ROW, "full prompt text", _FAKE_ANSWER, "MRA:.5:.95:.05", 1.0, + "qwen3.5-4b", "/root/models/qwen3.5-4b", "base", results_dir=tmp_path, + ) + assert path == tmp_path / "scene0001_00" / "7.json" + on_disk = json.loads(path.read_text()) + assert on_disk == record diff --git a/tests/test_E/test_sweep.py b/tests/test_E/test_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f61e326033716695ebaa681d2b2d78e88a119c --- /dev/null +++ b/tests/test_E/test_sweep.py @@ -0,0 +1,36 @@ +"""Tests for harness/E/sweep.py -- per-model blind-floor sweeping.""" + +import pytest + +from harness.E import sweep + + +def test_sweep_imports(): + assert callable(sweep.main) + + +def test_sweep_runs_every_model_through_launch(monkeypatch): + launched = [] + monkeypatch.setattr( + sweep.harness_launch, "launch", + lambda model, scenes, **kwargs: launched.append((model, kwargs.get("extended"))), + ) + sweep.sweep(["qwen3.5-2b", "qwen3.5-4b"], ["scene_a"], extended=True) + assert launched == [("qwen3.5-2b", True), ("qwen3.5-4b", True)] + + +def test_sweep_defaults_to_base_protocol(monkeypatch): + launched = [] + monkeypatch.setattr( + sweep.harness_launch, "launch", + lambda model, scenes, **kwargs: launched.append(kwargs.get("extended")), + ) + sweep.sweep(["qwen3.5-2b"], ["scene_a"]) + assert launched == [False] + + +def test_sweep_parser_rejects_unknown_model(monkeypatch, capsys): + monkeypatch.setattr("sys.argv", ["sweep", "--models", "not-a-model"]) + with pytest.raises(SystemExit): + sweep.main() + assert "unknown" in capsys.readouterr().err diff --git a/tests/test_analysis/__pycache__/test_aggregate.cpython-311-pytest-8.3.5.pyc b/tests/test_analysis/__pycache__/test_aggregate.cpython-311-pytest-8.3.5.pyc index c00f87676c071254fbf2238c7afbc3a0f8df6c74..3069be5d23851e124b8d6b6e7821f32e74189606 100644 Binary files a/tests/test_analysis/__pycache__/test_aggregate.cpython-311-pytest-8.3.5.pyc and b/tests/test_analysis/__pycache__/test_aggregate.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_analysis/__pycache__/test_compare.cpython-311-pytest-8.3.5.pyc b/tests/test_analysis/__pycache__/test_compare.cpython-311-pytest-8.3.5.pyc index 6cc14607fb2604e50c631f496a2832d4b653efa8..4a1a5241ce7b763988e59e109cccad2ec278d6ba 100644 Binary files a/tests/test_analysis/__pycache__/test_compare.cpython-311-pytest-8.3.5.pyc and b/tests/test_analysis/__pycache__/test_compare.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_analysis/__pycache__/test_cot_audit.cpython-311-pytest-8.3.5.pyc b/tests/test_analysis/__pycache__/test_cot_audit.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a59b665913cebd0fc5197a39eaea9d43a4f7325 Binary files /dev/null and b/tests/test_analysis/__pycache__/test_cot_audit.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_analysis/__pycache__/test_depth.cpython-311-pytest-8.3.5.pyc b/tests/test_analysis/__pycache__/test_depth.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90762bf1e7c8863501f27a334923098784b0835f Binary files /dev/null and b/tests/test_analysis/__pycache__/test_depth.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_analysis/__pycache__/test_solvability.cpython-311-pytest-8.3.5.pyc b/tests/test_analysis/__pycache__/test_solvability.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a838661b9e2a0018dae8dffb9e2d48e22665c41d Binary files /dev/null and b/tests/test_analysis/__pycache__/test_solvability.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_analysis/__pycache__/test_stats.cpython-311-pytest-8.3.5.pyc b/tests/test_analysis/__pycache__/test_stats.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70c84c72800e6eab97b9681a10af7ca39cd12238 Binary files /dev/null and b/tests/test_analysis/__pycache__/test_stats.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_analysis/__pycache__/test_sufficiency.cpython-311-pytest-8.3.5.pyc b/tests/test_analysis/__pycache__/test_sufficiency.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c6153eb73bfdcf49cf9ad2f9d4fa770834e5417 Binary files /dev/null and b/tests/test_analysis/__pycache__/test_sufficiency.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_analysis/test_aggregate.py b/tests/test_analysis/test_aggregate.py index 07a64e63048c5989edf5db48a1d5726f321aa8fc..263aa892c610cad5b0b09180e842813f5704cbaa 100644 --- a/tests/test_analysis/test_aggregate.py +++ b/tests/test_analysis/test_aggregate.py @@ -27,8 +27,8 @@ def _record( } -def test_results_dirs_cover_all_four_harnesses(): - assert set(harness_analysis.RESULTS_DIRS) == {"A", "B", "C", "D"} +def test_results_dirs_cover_every_harness(): + assert set(harness_analysis.RESULTS_DIRS) == {"A", "B", "C", "D", "E"} from harness.A import RESULTS_DIR as a_dir from harness.B import RESULTS_DIR as b_dir from harness.C import RESULTS_DIR as c_dir diff --git a/tests/test_analysis/test_compare.py b/tests/test_analysis/test_compare.py index cdfb3005f7370f2b03c1281f1fb3c539e0cadeae..3321c355a734d1bbc745450d4f24ef6a1204cd55 100644 --- a/tests/test_analysis/test_compare.py +++ b/tests/test_analysis/test_compare.py @@ -1,96 +1,92 @@ -"""Tests for analysis/compare.py -- cross-harness A vs B vs C comparison.""" +"""Tests for analysis/compare.py -- matched-question cross-harness comparison.""" from analysis import compare as analysis_compare -from analysis.aggregate import RESULTS_DIRS -def test_parse_a_key_splits_model_selection_frame_count(): - assert analysis_compare._parse_a_key("qwen3.5-2b/uniform:16") == ( - "qwen3.5-2b", "uniform", "16" - ) +def _record(harness, question_id, score, scene="scene_a", model="qwen3.5-2b"): + conditions = { + "A": "extended:selective:32", + "B": "extended:explicit:relative:tracking:selective:32", + "C": "extended:explicit:relative:tracking:selective:32", + "D": "extended:explicit", + "E": "extended", + } + return { + "model": model, + "condition": conditions[harness], + "question_id": question_id, + "scene": scene, + "question_type": "object_counting", + "answer_expected": "4", + "metric": "MRA:.5:.95:.05", + "score": score, + } -def test_parse_bc_key_splits_model_format_selection_frame_count(): - assert analysis_compare._parse_bc_key("qwen3.5-2b/explicit:selective:64") == ( - "qwen3.5-2b", "explicit", "selective", "64" +def test_parse_a_condition_splits_protocol_selection_frames(): + assert analysis_compare._parse_a_condition("base:uniform:16") == ( + "base", "uniform", "16" ) -def _fake_iter_records(results_dir): - return [{"dir": str(results_dir)}] - - -def _fake_aggregate_factory(by_dir): - def fake_aggregate(records): - return by_dir.get(records[0]["dir"], {}) +def test_parse_bc_condition_splits_all_six_axes(): + assert analysis_compare._parse_bc_condition( + "extended:explicit:relative:tracking:selective:64" + ) == ("extended", "explicit", "relative", "tracking", "selective", "64") - return fake_aggregate +def test_parse_d_condition_splits_protocol_and_format(): + assert analysis_compare._parse_d_condition("base:compact") == ("base", "compact") -def test_compare_joins_a_b_c_on_shared_dimensions(monkeypatch): - monkeypatch.setattr(analysis_compare, "iter_records", _fake_iter_records) - monkeypatch.setattr( - analysis_compare, - "aggregate", - _fake_aggregate_factory( - { - str(RESULTS_DIRS["A"]): { - "qwen3.5-2b/selective:64": {"official": {"overall": 47.5}}, - }, - str(RESULTS_DIRS["B"]): { - "qwen3.5-2b/explicit:selective:64": {"official": {"overall": 20.0}}, - }, - str(RESULTS_DIRS["C"]): { - "qwen3.5-2b/explicit:selective:64": {"official": {"overall": 60.0}}, - }, - } - ), - ) - rows = analysis_compare.compare() - key = ("qwen3.5-2b", "selective", "64") - assert rows[key]["A"] == 47.5 - assert rows[key]["B"]["explicit"] == 20.0 - assert rows[key]["C"]["explicit"] == 60.0 - - -def test_compare_leaves_missing_combinations_absent(monkeypatch): - monkeypatch.setattr(analysis_compare, "iter_records", _fake_iter_records) - monkeypatch.setattr( - analysis_compare, - "aggregate", - _fake_aggregate_factory( - { - str(RESULTS_DIRS["A"]): { - "qwen3.5-2b/uniform:8": {"official": {"overall": 40.0}}, - }, - } - ), - ) +def _patch_dirs(monkeypatch, by_dir): + from analysis.aggregate import RESULTS_DIRS - rows = analysis_compare.compare() - key = ("qwen3.5-2b", "uniform", "8") - assert rows[key]["A"] == 40.0 - assert rows[key]["B"] == {} - assert rows[key]["C"] == {} + def fake_iter_records(results_dir): + for harness, records in by_dir.items(): + if str(results_dir) == str(RESULTS_DIRS[harness]): + return list(records) + return [] + monkeypatch.setattr(analysis_compare, "iter_records", fake_iter_records) -def test_compare_uses_explicit_results_dirs_when_given(monkeypatch): - seen = [] - def recording_iter_records(results_dir): - seen.append(str(results_dir)) - return [{"dir": str(results_dir)}] +def test_compare_scores_only_the_shared_question_intersection(monkeypatch): + # A answered questions 1-3; B only 1-2 -- the row must be scored on {1, 2} for + # BOTH cells, with each cell's full count still reported. + _patch_dirs(monkeypatch, { + "A": [_record("A", 1, 1.0), _record("A", 2, 0.0), _record("A", 3, 1.0)], + "B": [_record("B", 1, 1.0), _record("B", 2, 1.0)], + }) + rows = analysis_compare.compare() + row = rows[("qwen3.5-2b", "extended", "selective", "32")] + assert row["common_count"] == 2 + assert row["cells"]["A"]["full_count"] == 3 + assert row["cells"]["B_explicit:relative:tracking"]["full_count"] == 2 + # A scored 1.0 on q1 and 0.0 on q2 -> 50.0 on the shared set (q3's 1.0 excluded). + assert row["cells"]["A"]["overall"] == 50.0 + assert row["cells"]["B_explicit:relative:tracking"]["overall"] == 100.0 + + +def test_compare_joins_d_and_e_on_model_and_protocol(monkeypatch): + _patch_dirs(monkeypatch, { + "A": [_record("A", 1, 1.0)], + "D": [_record("D", 1, 1.0)], + "E": [_record("E", 1, 0.0)], + }) + rows = analysis_compare.compare() + row = rows[("qwen3.5-2b", "extended", "selective", "32")] + assert row["cells"]["D_explicit"]["overall"] == 100.0 + assert row["cells"]["E"]["overall"] == 0.0 - monkeypatch.setattr(analysis_compare, "iter_records", recording_iter_records) - monkeypatch.setattr(analysis_compare, "aggregate", lambda records: {}) - analysis_compare.compare( - a_results_dir="/tmp/custom-a", - b_results_dir="/tmp/custom-b", - c_results_dir="/tmp/custom-c", - ) - assert seen == ["/tmp/custom-a", "/tmp/custom-b", "/tmp/custom-c"] +def test_compare_keeps_protocols_in_separate_rows(monkeypatch): + base_a = _record("A", 1, 1.0) + base_a["condition"] = "base:selective:32" + _patch_dirs(monkeypatch, {"A": [base_a, _record("A", 1, 0.0)]}) + rows = analysis_compare.compare() + assert ("qwen3.5-2b", "base", "selective", "32") in rows + assert ("qwen3.5-2b", "extended", "selective", "32") in rows def test_format_score_handles_none(): @@ -98,47 +94,23 @@ def test_format_score_handles_none(): assert analysis_compare._format_score(47.5) == "47.50" -def test_flatten_rows_produces_per_format_columns(): - rows = { - ("qwen3.5-2b", "selective", "64"): { - "A": 47.5, - "B": {"explicit": 20.0, "compact": 22.0}, - "C": {"explicit": 60.0}, - }, - } - flat = analysis_compare.flatten_rows(rows) - assert len(flat) == 1 - row = flat[0] - assert row["model"] == "qwen3.5-2b" - assert row["selection"] == "selective" - assert row["frames"] == "64" - assert row["A"] == 47.5 - assert row["B_explicit"] == 20.0 - assert row["B_compact"] == 22.0 - assert row["C_explicit"] == 60.0 - assert row["C_compact"] is None - - -def test_write_csv_round_trips_through_a_real_file(tmp_path): +def test_write_csv_round_trips_through_a_real_file(tmp_path, monkeypatch): import csv - rows = { - ("qwen3.5-2b", "selective", "64"): { - "A": 47.5, - "B": {"explicit": 20.0}, - "C": {"explicit": 60.0}, - }, - ("qwen3.5-4b", "uniform", "16"): {"A": 30.0, "B": {}, "C": {}}, - } + _patch_dirs(monkeypatch, { + "A": [_record("A", 1, 1.0)], + "B": [_record("B", 1, 1.0)], + }) + rows = analysis_compare.compare() csv_path = tmp_path / "compare.csv" analysis_compare.write_csv(rows, csv_path) with csv_path.open(encoding="utf-8") as stream: read_rows = list(csv.DictReader(stream)) - assert len(read_rows) == 2 - row_2b = next(r for r in read_rows if r["model"] == "qwen3.5-2b") - assert row_2b["A"] == "47.5" - assert row_2b["B_explicit"] == "20.0" - assert row_2b["C_explicit"] == "60.0" - row_4b = next(r for r in read_rows if r["model"] == "qwen3.5-4b") - assert row_4b["B_explicit"] == "" + assert len(read_rows) == 1 + row = read_rows[0] + assert row["model"] == "qwen3.5-2b" + assert row["protocol"] == "extended" + assert row["common_count"] == "1" + assert row["A"] == "100.0" + assert row["B_explicit:relative:tracking"] == "100.0" diff --git a/tests/test_analysis/test_cot_audit.py b/tests/test_analysis/test_cot_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fe4df6cc25541456fcca100ce1d02ca220811ebc --- /dev/null +++ b/tests/test_analysis/test_cot_audit.py @@ -0,0 +1,76 @@ +"""Tests for analysis/cot_audit.py -- deterministic reasoning-trace audit (H23).""" + +import json + +from analysis import cot_audit + + +def test_numbers_in_extracts_floats_and_ints(): + assert cot_audit.numbers_in("the sofa is 2.5 m from 3 chairs") == [2.5, 3.0] + + +def test_code_numbers_reads_nested_values_and_unit_strings(): + code = {"objects": {"chair": {"count": 2, "instances": [{"x": "4.98 meters"}]}}} + numbers = cot_audit.code_numbers(code) + assert 2.0 in numbers + assert 4.98 in numbers + + +def _record(tmp_path, reasoning, score=0.0, question="How far is the sofa?", options=None): + code = {"objects": {"sofa": {"instances": [{"x coordinate": "4.98 meters"}]}}} + code_path = tmp_path / "code.json" + code_path.write_text(json.dumps(code)) + return { + "question_id": 1, + "question_type": "object_abs_distance", + "score": score, + "reasoning_text": reasoning, + "spatial_code_path": str(code_path), + "question": question, + "options": options, + } + + +def test_audit_record_grounds_cited_code_values(tmp_path): + record = _record(tmp_path, "the sofa is at 4.98, so the answer is 4.98") + result = cot_audit.audit_record(record) + assert result["cited"] == 2 + assert result["fabricated"] == 0 + + +def test_audit_record_flags_fabricated_values(tmp_path): + record = _record(tmp_path, "the sofa is at 123.45 meters") + result = cot_audit.audit_record(record) + assert result["fabricated"] == 1 + assert result["fabricated_values"] == [123.45] + + +def test_small_integers_are_whitelisted_as_derived_counts(tmp_path): + record = _record(tmp_path, "there are 7 objects in total") + result = cot_audit.audit_record(record) + assert result["fabricated"] == 0 + + +def test_question_and_option_numbers_are_grounded(tmp_path): + record = _record( + tmp_path, "option B says 87.5", question="Which?", options=["A. 20.5", "B. 87.5"] + ) + assert cot_audit.audit_record(record)["fabricated"] == 0 + + +def test_audit_summary_splits_wrong_answers_by_fabrication(tmp_path): + records = [ + _record(tmp_path, "answer from 4.98", score=0.0), + _record(tmp_path, "made up 99.99", score=0.0), + _record(tmp_path, "correct, 4.98", score=1.0), + ] + _audits, summary = cot_audit.audit(records) + assert summary["audited"] == 3 + assert summary["wrong"] == 2 + assert summary["wrong_with_fabrication"] == 1 + assert summary["fabrication_share_of_wrong"] == 0.5 + + +def test_audit_skips_records_without_reasoning(tmp_path): + record = _record(tmp_path, None) + assert cot_audit.audit_record(record) is None diff --git a/tests/test_analysis/test_depth.py b/tests/test_analysis/test_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..aa9c4e83a4b7a096ab6a82149f51fd1dc19fa088 --- /dev/null +++ b/tests/test_analysis/test_depth.py @@ -0,0 +1,66 @@ +"""Tests for analysis/depth.py -- solver computation-depth transfer (H25).""" + +import json + +from analysis import depth + + +def _gt_code(): + return { + "spatial code schema": {}, + "objects": { + "chair": [ + { + "3D oriented bounding box": { + "3D oriented bounding box center coordinates": [0.0, 0.0, 0.5], + "3D oriented bounding box dimensions": [1.0, 1.0, 1.0], + "3D oriented bounding box orientation unit vectors": [ + [1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0], + ], + }, + "first visible time": 0.0, + } + ] + }, + "room": {"floor boundary polygons": []}, + } + + +def test_question_depth_counts_solver_operations(tmp_path): + code_path = tmp_path / "code.json" + code_path.write_text(json.dumps(_gt_code())) + record = { + "question_type": "object_counting", + "question": "How many chair(s) are in this room?", + "options": None, + "spatial_code_path": str(code_path), + } + ops = depth.question_depth(record, {}) + assert ops is not None and ops >= 1 + + +def test_question_depth_unreadable_code_returns_none(): + record = { + "question_type": "object_counting", + "question": "How many chairs?", + "options": None, + "spatial_code_path": "/does/not/exist.json", + } + assert depth.question_depth(record, {}) is None + + +def test_depth_table_buckets_by_operation_count(tmp_path): + code_path = tmp_path / "code.json" + code_path.write_text(json.dumps(_gt_code())) + records = [ + { + "question_type": "object_counting", + "question": "How many chair(s) are in this room?", + "options": None, + "spatial_code_path": str(code_path), + "score": 1.0, + } + ] + table, pairs = depth.depth_table(records) + assert len(pairs) == 1 + assert sum(stats["count"] for stats in table.values()) == 1 diff --git a/tests/test_analysis/test_solvability.py b/tests/test_analysis/test_solvability.py new file mode 100644 index 0000000000000000000000000000000000000000..2a24ff1f40ab5a7eb744aa2a1bc8f8cbd11b40ed --- /dev/null +++ b/tests/test_analysis/test_solvability.py @@ -0,0 +1,37 @@ +"""Tests for analysis/solvability.py -- solved-set overlap (H19, exploratory).""" + +from analysis import solvability + + +def _cell(scores): + return [{"question_id": qid, "score": score} for qid, score in scores.items()] + + +def test_overlap_restricts_to_shared_questions(): + cells = { + "A": _cell({1: 1.0, 2: 0.0, 3: 1.0}), + "B": _cell({1: 1.0, 2: 1.0}), # never answered 3 + } + report = solvability.overlap(cells) + assert report["questions"] == 2 + assert report["solved"] == {"A": 1, "B": 2} + + +def test_overlap_pairwise_jaccard_and_exclusives(): + cells = { + "A": _cell({1: 1.0, 2: 1.0, 3: 0.0}), + "B": _cell({1: 1.0, 2: 0.0, 3: 1.0}), + } + report = solvability.overlap(cells) + pair = report["pairs"]["A|B"] + assert pair["both"] == 1 + assert pair["only_A"] == 1 + assert pair["only_B"] == 1 + assert pair["jaccard"] == 1 / 3 + assert report["solved_by_all"] == 1 + assert report["solved_by_none"] == 0 + + +def test_overlap_empty_intersection(): + report = solvability.overlap({"A": _cell({1: 1.0}), "B": _cell({2: 1.0})}) + assert report == {"questions": 0} diff --git a/tests/test_analysis/test_stats.py b/tests/test_analysis/test_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..fe52bae62ed2afda92f32a5b5dc98c2398e1b00b --- /dev/null +++ b/tests/test_analysis/test_stats.py @@ -0,0 +1,59 @@ +"""Tests for analysis/stats.py -- scene-clustered paired bootstrap.""" + +from analysis import stats as analysis_stats + + +def _record(question_id, score, scene): + return {"question_id": question_id, "score": score, "scene": scene} + + +def test_paired_questions_matches_on_question_id_intersection(): + x = [_record(1, 1.0, "a"), _record(2, 0.0, "a"), _record(3, 1.0, "b")] + y = [_record(1, 0.0, "a"), _record(3, 1.0, "b"), _record(9, 1.0, "z")] + by_scene = analysis_stats.paired_questions(x, y) + assert by_scene == {"a": [(1.0, 0.0)], "b": [(1.0, 1.0)]} + + +def test_paired_bootstrap_returns_none_on_empty_intersection(): + assert analysis_stats.paired_bootstrap([_record(1, 1.0, "a")], [_record(2, 1.0, "a")]) is None + + +def test_paired_bootstrap_observed_delta_is_mean_paired_difference(): + x = [_record(1, 0.0, "a"), _record(2, 0.0, "a"), _record(3, 0.0, "b"), _record(4, 0.0, "b")] + y = [_record(1, 1.0, "a"), _record(2, 1.0, "a"), _record(3, 1.0, "b"), _record(4, 0.0, "b")] + result = analysis_stats.paired_bootstrap(x, y, iterations=200, seed=0) + assert result["delta"] == 0.75 + assert result["questions"] == 4 + assert result["scenes"] == 2 + assert result["ci_low"] <= result["delta"] <= result["ci_high"] + + +def test_paired_bootstrap_is_deterministic_for_a_fixed_seed(): + x = [_record(i, 0.0, f"s{i % 3}") for i in range(9)] + y = [_record(i, float(i % 2), f"s{i % 3}") for i in range(9)] + first = analysis_stats.paired_bootstrap(x, y, iterations=300, seed=7) + second = analysis_stats.paired_bootstrap(x, y, iterations=300, seed=7) + assert first == second + + +def test_paired_bootstrap_zero_delta_when_cells_identical(): + x = [_record(i, 1.0, "a") for i in range(4)] + result = analysis_stats.paired_bootstrap(x, list(x), iterations=100, seed=0) + assert result["delta"] == 0.0 + assert result["ci_low"] == 0.0 + assert result["ci_high"] == 0.0 + + +def test_paired_bootstrap_reports_a_floored_p_value(): + x = [_record(i, 0.0, f"s{i % 3}") for i in range(9)] + y = [_record(i, 1.0, f"s{i % 3}") for i in range(9)] + result = analysis_stats.paired_bootstrap(x, y, iterations=200, seed=0) + assert result["p_value"] == 1 / 200 # every resample is positive -> floor + + +def test_holm_bonferroni_adjusts_and_stays_monotone(): + adjusted = analysis_stats.holm_bonferroni({"a": 0.01, "b": 0.04, "c": 0.03}) + assert adjusted["a"] == 0.03 # 3 * 0.01 + assert adjusted["c"] == 0.06 # 2 * 0.03 + assert adjusted["b"] == 0.06 # 1 * 0.04 = 0.04, raised to running max + assert all(value <= 1.0 for value in adjusted.values()) diff --git a/tests/test_analysis/test_sufficiency.py b/tests/test_analysis/test_sufficiency.py new file mode 100644 index 0000000000000000000000000000000000000000..c185b4c7583d0fc762ef22071bc0580860790c0b --- /dev/null +++ b/tests/test_analysis/test_sufficiency.py @@ -0,0 +1,49 @@ +"""Tests for analysis/sufficiency.py -- solver-certified decomposition (H26).""" + +from analysis import sufficiency + + +def _solver(question_id, score): + return {"question_id": question_id, "score": score} + + +def _vlm(question_id, score, question_type="object_counting"): + return {"question_id": question_id, "score": score, "question_type": question_type} + + +def test_certificates_threshold(): + certs = sufficiency.certificates([_solver(1, 1.0), _solver(2, 0.4), _solver(3, None)]) + assert certs == {1: True, 2: False, 3: False} + + +def test_decompose_splits_proven_reasoning_from_information_failures(): + solver_records = [_solver(1, 1.0), _solver(2, 1.0), _solver(3, 0.0)] + vlm_records = [_vlm(1, 1.0), _vlm(2, 0.0), _vlm(3, 0.0)] + result = sufficiency.decompose(vlm_records, solver_records) + assert result["questions"] == 3 + # q1: certified + VLM correct; q2: certified + VLM wrong = PROVEN reasoning failure. + assert result["certified"]["count"] == 2 + assert result["certified"]["vlm_correct"] == 1 + assert result["certified"]["vlm_wrong"] == 1 + # q3: uncertified -- information failure, not reasoning evidence. + assert result["uncertified"]["count"] == 1 + + +def test_decompose_ignores_unmatched_and_excluded(): + solver_records = [_solver(1, 1.0)] + vlm_records = [ + _vlm(1, 1.0), + _vlm(2, 1.0), # solver never answered -> excluded from the join + _vlm(3, 1.0, question_type="obj_appearance_order"), + ] + result = sufficiency.decompose( + vlm_records, solver_records, exclude=("obj_appearance_order",) + ) + assert result["questions"] == 1 + + +def test_decompose_empty_bucket_stats(): + result = sufficiency.decompose([_vlm(1, 1.0)], [_solver(1, 1.0)]) + assert result["uncertified"] == { + "count": 0, "mean_score": None, "vlm_correct": 0, "vlm_wrong": 0, + } diff --git a/tests/test_corruption/__init__.py b/tests/test_corruption/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_corruption/__pycache__/__init__.cpython-311.pyc b/tests/test_corruption/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfd4f81ffed475b76fb38160af0e1d1cfab324e4 Binary files /dev/null and b/tests/test_corruption/__pycache__/__init__.cpython-311.pyc differ diff --git a/tests/test_corruption/__pycache__/test_chimera.cpython-311-pytest-8.3.5.pyc b/tests/test_corruption/__pycache__/test_chimera.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..372ff12e7afea23c5f24f23c64b1d87a7fcfac52 Binary files /dev/null and b/tests/test_corruption/__pycache__/test_chimera.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_corruption/__pycache__/test_empirical.cpython-311-pytest-8.3.5.pyc b/tests/test_corruption/__pycache__/test_empirical.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baa6779e9e24cb92efaa26461eef64d5ac59da2f Binary files /dev/null and b/tests/test_corruption/__pycache__/test_empirical.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_corruption/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc b/tests/test_corruption/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8479f8b5888ef13760f2de18d2fd2ae4c4f2192 Binary files /dev/null and b/tests/test_corruption/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_corruption/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc b/tests/test_corruption/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..332e9776eddb2247bf8fa6dee7a7746db703a7da Binary files /dev/null and b/tests/test_corruption/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_corruption/__pycache__/test_transforms.cpython-311-pytest-8.3.5.pyc b/tests/test_corruption/__pycache__/test_transforms.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d5adc480c4b097951ade15c74b4eb44323f8efc Binary files /dev/null and b/tests/test_corruption/__pycache__/test_transforms.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_corruption/test_chimera.py b/tests/test_corruption/test_chimera.py new file mode 100644 index 0000000000000000000000000000000000000000..6b39f387c9a1495fa01250baa3e3df17dea43e4d --- /dev/null +++ b/tests/test_corruption/test_chimera.py @@ -0,0 +1,84 @@ +"""Tests for corruption/chimera.py -- hybrid codes and the single-object probe.""" + +import random + +from corruption import chimera + + +def _instance(x, y, dims=(1.0, 1.0, 1.0), time=0.0): + return { + "3D oriented bounding box": { + "3D oriented bounding box center coordinates": [x, y, 0.5], + "3D oriented bounding box dimensions": list(dims), + "3D oriented bounding box orientation unit vectors": [ + [1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0], + ], + }, + "first visible time": time, + } + + +def _code(objects): + return {"spatial code schema": {}, "objects": objects, "room": {"floor boundary polygons": []}} + + +def test_gt_inventory_keeps_gt_counts_but_takes_perceived_boxes(): + gt = _code({"chair": [_instance(0.0, 0.0), _instance(5.0, 5.0)]}) + perceived = _code({"chair": [_instance(0.3, 0.1, dims=(9.0, 9.0, 9.0))]}) + hybrid, coverage = chimera.gt_inventory_perceived_geometry(gt, perceived) + # GT count preserved (2 chairs), nearest GT instance got the perceived box. + assert len(hybrid["objects"]["chair"]) == 2 + assert coverage == {"instances": 2, "swapped": 1} + boxes = [ + item["3D oriented bounding box"]["3D oriented bounding box dimensions"] + for item in hybrid["objects"]["chair"] + ] + assert [9.0, 9.0, 9.0] in boxes + + +def test_perceived_inventory_keeps_perceived_counts_but_takes_gt_boxes(): + gt = _code({"chair": [_instance(0.0, 0.0, dims=(2.0, 2.0, 2.0))]}) + perceived = _code( + {"chair": [_instance(0.4, 0.0), _instance(8.0, 8.0)], "ghost": [_instance(1.0, 1.0)]} + ) + hybrid, coverage = chimera.perceived_inventory_gt_geometry(gt, perceived) + # Perceived inventory preserved: 2 chairs + the hallucinated "ghost" class. + assert len(hybrid["objects"]["chair"]) == 2 + assert "ghost" in hybrid["objects"] + assert coverage["swapped"] == 1 # only one GT chair box available to give out + boxes = [ + item["3D oriented bounding box"]["3D oriented bounding box dimensions"] + for item in hybrid["objects"]["chair"] + ] + assert [2.0, 2.0, 2.0] in boxes + + +def test_chimeras_do_not_mutate_inputs(): + gt = _code({"chair": [_instance(0.0, 0.0)]}) + perceived = _code({"chair": [_instance(1.0, 1.0)]}) + frozen_gt, frozen_perceived = str(gt), str(perceived) + chimera.gt_inventory_perceived_geometry(gt, perceived) + chimera.perceived_inventory_gt_geometry(gt, perceived) + assert str(gt) == frozen_gt + assert str(perceived) == frozen_perceived + + +def test_perturb_single_object_changes_exactly_one_instance(): + code = _code( + {"chair": [_instance(0.0, 0.0), _instance(5.0, 5.0)], "table": [_instance(2.0, 2.0)]} + ) + out, info = chimera.perturb_single_object(code, random.Random(0)) + changed = 0 + for name in code["objects"]: + for before, after in zip(code["objects"][name], out["objects"][name]): + if before != after: + changed += 1 + assert changed == 1 + assert info["class"] in code["objects"] + + +def test_perturb_single_object_empty_code_is_a_noop(): + code = _code({}) + out, info = chimera.perturb_single_object(code, random.Random(0)) + assert out == code + assert info is None diff --git a/tests/test_corruption/test_empirical.py b/tests/test_corruption/test_empirical.py new file mode 100644 index 0000000000000000000000000000000000000000..a04a6f24de22c0f9b2b740b7aa48e1db5e1011b0 --- /dev/null +++ b/tests/test_corruption/test_empirical.py @@ -0,0 +1,79 @@ +"""Tests for corruption/empirical.py -- measured residuals and empirical noise.""" + +import random + +from corruption import empirical + + +def _instance(x, y, dims=(1.0, 1.0, 1.0)): + return { + "3D oriented bounding box": { + "3D oriented bounding box center coordinates": [x, y, 0.5], + "3D oriented bounding box dimensions": list(dims), + "3D oriented bounding box orientation unit vectors": [ + [1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0], + ], + }, + "first visible time": 0.0, + } + + +def _code(objects): + return {"spatial code schema": {}, "objects": objects, "room": {"floor boundary polygons": []}} + + +def test_measure_residuals_matches_missed_and_hallucinated(): + gt = _code({"chair": [_instance(0.0, 0.0), _instance(5.0, 5.0)]}) + perceived = _code({"chair": [_instance(0.5, 0.0)], "phantom": [_instance(9.0, 9.0)]}) + residuals = empirical.measure_residuals([(perceived, gt)]) + assert residuals["matched"] == 1 + assert residuals["missed"] == 1 # second GT chair unmatched + assert residuals["hallucinated"] == 1 # the phantom class + assert residuals["miss_rate"] == 0.5 + assert residuals["position_residuals"] == [[0.5, 0.0, 0.0]] + + +def test_measure_residuals_dimension_ratios(): + gt = _code({"chair": [_instance(0.0, 0.0, dims=(2.0, 2.0, 2.0))]}) + perceived = _code({"chair": [_instance(0.0, 0.0, dims=(1.0, 3.0, 2.0))]}) + residuals = empirical.measure_residuals([(perceived, gt)]) + assert residuals["dimension_ratios"] == [[0.5, 1.5, 1.0]] + + +def test_empirical_noise_at_zero_scale_is_identity(): + code = _code({"chair": [_instance(1.0, 1.0)]}) + residuals = { + "position_residuals": [[0.5, 0.5, 0.0]], + "dimension_ratios": [[2.0, 2.0, 2.0]], + "matched": 1, "missed": 1, "hallucinated": 1, + "miss_rate": 0.5, "hallucination_rate": 0.5, + } + out = empirical.empirical_noise(code, residuals, random.Random(0), scale=0.0) + assert out == code + + +def test_empirical_noise_applies_sampled_residuals(): + code = _code({"chair": [_instance(1.0, 1.0)]}) + residuals = { + "position_residuals": [[0.5, -0.5, 0.0]], + "dimension_ratios": [[2.0, 1.0, 1.0]], + "matched": 1, "missed": 0, "hallucinated": 0, + "miss_rate": 0.0, "hallucination_rate": 0.0, + } + out = empirical.empirical_noise(code, residuals, random.Random(0), scale=1.0) + box = out["objects"]["chair"][0]["3D oriented bounding box"] + assert box["3D oriented bounding box center coordinates"] == [1.5, 0.5, 0.5] + assert box["3D oriented bounding box dimensions"] == [2.0, 1.0, 1.0] + + +def test_empirical_noise_is_reproducible(): + code = _code({"chair": [_instance(1.0, 1.0), _instance(3.0, 3.0)]}) + residuals = { + "position_residuals": [[0.5, 0.0, 0.0], [-0.2, 0.1, 0.0]], + "dimension_ratios": [[1.1, 0.9, 1.0]], + "matched": 2, "missed": 1, "hallucinated": 1, + "miss_rate": 0.3, "hallucination_rate": 0.3, + } + first = empirical.empirical_noise(code, residuals, random.Random(7)) + second = empirical.empirical_noise(code, residuals, random.Random(7)) + assert first == second diff --git a/tests/test_corruption/test_launch.py b/tests/test_corruption/test_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..1016a9469dffdeb36be060fc8b24d87a7bb01c6c --- /dev/null +++ b/tests/test_corruption/test_launch.py @@ -0,0 +1,48 @@ +"""Tests for corruption/launch.py -- grid looping over conditions.""" + +import pytest + +from corruption import launch + + +def test_launch_imports(): + assert callable(launch.main) + + +def test_launch_rejects_unknown_transform(monkeypatch, capsys): + monkeypatch.setattr( + "sys.argv", + ["launch", "--transforms", "not-a-transform", "--magnitudes", "0.5", "--arm", "solver"], + ) + with pytest.raises(SystemExit): + launch.main() + assert "unknown transform" in capsys.readouterr().err + + +def test_launch_vlm_arm_requires_models(monkeypatch, capsys): + monkeypatch.setattr( + "sys.argv", + ["launch", "--transforms", "translate", "--magnitudes", "10", "--arm", "vlm"], + ) + with pytest.raises(SystemExit): + launch.main() + assert "requires --models" in capsys.readouterr().err + + +def test_launch_runs_the_full_grid_through_run_solver(monkeypatch): + conditions = [] + monkeypatch.setattr( + launch, "run_solver", + lambda transform, magnitude, fmt, **kwargs: conditions.append((transform, magnitude)) or [], + ) + monkeypatch.setattr( + "sys.argv", + [ + "launch", "--arm", "solver", + "--transforms", "translate,rotate-z", "--magnitudes", "10,90", + ], + ) + launch.main() + assert conditions == [ + ("translate", 10.0), ("translate", 90.0), ("rotate-z", 10.0), ("rotate-z", 90.0), + ] diff --git a/tests/test_corruption/test_run.py b/tests/test_corruption/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..3902acbad925724d0ef4695948dc99e69b916b8a --- /dev/null +++ b/tests/test_corruption/test_run.py @@ -0,0 +1,123 @@ +"""Tests for corruption/run.py -- condition orchestration, determinism, and the +certification gate, against real on-disk ground-truth codes.""" + +import pytest + +from corruption import run as corruption_run + +_SCENE = "13c3e046d7" +_OTHER_SCENE = "09c1414f1b" + + +def test_seed_is_deterministic_and_condition_specific(): + first = corruption_run._seed_for(_SCENE, "position-jitter", 0.25) + second = corruption_run._seed_for(_SCENE, "position-jitter", 0.25) + different = corruption_run._seed_for(_SCENE, "position-jitter", 0.5) + assert first == second + assert first != different + + +def test_corrupted_code_is_reproducible(): + first = corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "compact") + second = corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "compact") + assert first == second + + +def test_corrupted_explicit_is_derived_from_the_corrupted_compact(): + compact = corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "compact") + explicit = corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "explicit") + # Same corruption seed -> the explicit code's per-class counts must match the + # corrupted compact's own instance counts (consistency-by-construction). + for class_name, items in compact["objects"].items(): + assert explicit["objects"][class_name]["count"] == len(items) + + +def test_wrong_scene_returns_the_substitute_scenes_code(): + substituted = corruption_run.corrupted_code( + _SCENE, "wrong-scene", 0, "compact", wrong_scene=_OTHER_SCENE + ) + own = corruption_run.load_ground_truth_compact(_SCENE) + other = corruption_run.load_ground_truth_compact(_OTHER_SCENE) + assert substituted == other + assert substituted != own + + +def test_wrong_scene_requires_a_substitute(): + with pytest.raises(ValueError): + corruption_run.corrupted_code(_SCENE, "wrong-scene", 0, "compact") + + +def test_chimera_requires_perceived_config(): + with pytest.raises(ValueError): + corruption_run.corrupted_code(_SCENE, "chimera-gt-inventory", 0, "compact") + + +def test_empirical_requires_residuals(): + with pytest.raises(ValueError): + corruption_run.corrupted_code(_SCENE, "empirical", 1.0, "compact") + + +def test_unknown_transform_rejected(): + with pytest.raises(ValueError): + corruption_run.corrupted_code(_SCENE, "not-a-transform", 1.0, "compact") + + +def test_results_dir_for_isolates_every_axis(): + a = corruption_run.results_dir_for("vlm", "position-jitter", 0.25, "qwen3.5-4b") + b = corruption_run.results_dir_for("vlm", "position-jitter", 0.5, "qwen3.5-4b") + c = corruption_run.results_dir_for("solver", "position-jitter", 0.25, "symbolic") + assert len({a, b, c}) == 3 + + +def test_certify_rejects_non_invariance_transforms(): + with pytest.raises(ValueError): + corruption_run.certify_invariant(_SCENE, "position-jitter", 0.25) + + +def test_certify_translate_passes_on_a_real_scene(): + assert corruption_run.certify_invariant(_SCENE, "translate", 10.0) is True + + +def test_run_solver_answers_and_writes_records(tmp_path): + results = corruption_run.run_solver( + "position-jitter", 0.0, scenes=[_SCENE], results_dir=tmp_path + ) + assert results + for record in results: + assert record["model"] == "symbolic" + assert record["transform"] == "position-jitter" + assert record["scene"] == _SCENE + assert (tmp_path / _SCENE / f"{record['question_id']}.json").is_file() + + +def test_run_solver_zero_magnitude_jitter_matches_clean_ground_truth(): + # position-jitter at 0.0 is geometrically the identity, so the solver must score + # exactly what it scores on the clean ground-truth code. + from harness.D import symbolic_eval + + corrupted = corruption_run.run_solver( + "position-jitter", 0.0, scenes=[_SCENE], write_results=False + ) + clean = symbolic_eval.run( + spatial_code_format="explicit", scene=_SCENE, write_results=False + ) + corrupted_scores = {r["question_id"]: r["score"] for r in corrupted} + clean_scores = {r["question_id"]: r["score"] for r in clean} + assert corrupted_scores == clean_scores + + +def test_run_solver_respects_the_question_sample(tmp_path): + all_results = corruption_run.run_solver( + "position-jitter", 0.0, scenes=[_SCENE], write_results=False + ) + keep = {all_results[0]["question_id"]} + sampled = corruption_run.run_solver( + "position-jitter", 0.0, scenes=[_SCENE], question_ids=keep, write_results=False + ) + assert [r["question_id"] for r in sampled] == list(keep) + + +def test_make_code_transform_ignores_the_loaded_code(): + hook = corruption_run.make_code_transform("position-jitter", 0.25) + out = hook({"not": "used"}, _SCENE, "compact") + assert out == corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "compact") diff --git a/tests/test_corruption/test_transforms.py b/tests/test_corruption/test_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..0538ce176cc851bfa8885efefd4b759e3e97423f --- /dev/null +++ b/tests/test_corruption/test_transforms.py @@ -0,0 +1,154 @@ +"""Tests for corruption/transforms.py -- noise and invariance transform families.""" + +import math +import random + +from corruption import transforms + + +def _compact(classes=("chair", "table"), instances_per_class=2): + objects = {} + for class_index, name in enumerate(classes): + items = [] + for index in range(instances_per_class): + items.append( + { + "3D oriented bounding box": { + "3D oriented bounding box center coordinates": [ + float(class_index), float(index), 0.5, + ], + "3D oriented bounding box dimensions": [1.0, 2.0, 0.5], + "3D oriented bounding box orientation unit vectors": [ + [1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0], + ], + }, + "first visible time": float(index), + } + ) + objects[name] = items + return { + "spatial code schema": {}, + "objects": objects, + "room": { + "floor boundary polygons": [ + {"outer boundary coordinates": [[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]]} + ] + }, + } + + +def test_transforms_never_mutate_the_input(): + code = _compact() + frozen = str(code) + for name, transform in transforms.TRANSFORMS.items(): + transform(code, 0.5, random.Random(0)) + assert str(code) == frozen, f"{name} mutated its input" + + +def test_position_jitter_moves_centers_and_nothing_else(): + code = _compact() + out = transforms.position_jitter(code, 0.5, random.Random(0)) + before = code["objects"]["chair"][0]["3D oriented bounding box"] + after = out["objects"]["chair"][0]["3D oriented bounding box"] + assert before["3D oriented bounding box center coordinates"] != ( + after["3D oriented bounding box center coordinates"] + ) + assert before["3D oriented bounding box dimensions"] == ( + after["3D oriented bounding box dimensions"] + ) + + +def test_position_jitter_zero_sigma_is_identity_geometry(): + code = _compact() + out = transforms.position_jitter(code, 0.0, random.Random(0)) + assert out == code + + +def test_dimension_noise_never_collapses_a_dimension(): + code = _compact() + out = transforms.dimension_noise(code, 5.0, random.Random(0)) + for _name, instance in transforms._instances(out): + for value in instance["3D oriented bounding box"]["3D oriented bounding box dimensions"]: + assert value > 0.0 + + +def test_drop_objects_removes_emptied_classes_entirely(): + code = _compact() + out = transforms.drop_objects(code, 1.0, random.Random(0)) + assert out["objects"] == {} + + +def test_drop_objects_zero_fraction_drops_nothing(): + code = _compact() + out = transforms.drop_objects(code, 0.0, random.Random(0)) + assert out == code + + +def test_hallucinate_objects_only_ever_adds(): + code = _compact() + out = transforms.hallucinate_objects(code, 1.0, random.Random(0)) + for name in code["objects"]: + assert len(out["objects"][name]) == 2 * len(code["objects"][name]) + + +def test_class_swap_keeps_geometry_but_relabels(): + code = _compact() + out = transforms.class_swap(code, 1.0, random.Random(0)) + # Same set of class names, same total geometry, but at least one class's items moved. + assert sorted(out["objects"]) == sorted(code["objects"]) + assert any(out["objects"][name] != code["objects"][name] for name in code["objects"]) + + +def test_translate_shifts_centers_and_polygons_together(): + code = _compact() + out = transforms.translate(code, 10.0) + center = out["objects"]["chair"][0]["3D oriented bounding box"][ + "3D oriented bounding box center coordinates" + ] + assert center[:2] == [10.0, 10.0] + assert center[2] == 0.5 # height untouched + assert out["room"]["floor boundary polygons"][0]["outer boundary coordinates"][0] == [10.0, 10.0] + + +def test_rotate_z_preserves_pairwise_distances(): + code = _compact() + out = transforms.rotate_z(code, 90.0) + + def centers(c): + return [ + instance["3D oriented bounding box"]["3D oriented bounding box center coordinates"] + for _name, instance in transforms._instances(c) + ] + + before, after = centers(code), centers(out) + for i in range(len(before)): + for j in range(i + 1, len(before)): + assert math.dist(before[i], before[j]) == round( + math.dist(after[i], after[j]), 10 + ) or abs(math.dist(before[i], before[j]) - math.dist(after[i], after[j])) < 0.05 + + +def test_reorder_changes_only_order(): + code = _compact(classes=("a", "b", "c", "d")) + out = transforms.reorder(code, None, random.Random(3)) + assert sorted(out["objects"]) == sorted(code["objects"]) + for name in code["objects"]: + assert sorted(map(str, out["objects"][name])) == sorted(map(str, code["objects"][name])) + + +def test_round_precision_rounds_every_geometry_value(): + code = _compact() + code["objects"]["chair"][0]["3D oriented bounding box"][ + "3D oriented bounding box center coordinates" + ] = [0.123456, 1.987654, 0.5] + out = transforms.round_precision(code, 1) + assert out["objects"]["chair"][0]["3D oriented bounding box"][ + "3D oriented bounding box center coordinates" + ] == [0.1, 2.0, 0.5] + + +def test_seeded_transforms_are_reproducible(): + code = _compact() + first = transforms.position_jitter(code, 0.3, random.Random(42)) + second = transforms.position_jitter(code, 0.3, random.Random(42)) + assert first == second