diff --git a/encoder/__pycache__/ground_truth.cpython-311.pyc b/encoder/__pycache__/ground_truth.cpython-311.pyc index 60f2eba08e378cb90f7e7d9af1c1fddfaa2d5a0d..efcd19de27d921cb2383ba25ee276d70998e4f40 100644 Binary files a/encoder/__pycache__/ground_truth.cpython-311.pyc and b/encoder/__pycache__/ground_truth.cpython-311.pyc differ diff --git a/harness/A/__pycache__/launch.cpython-311.pyc b/harness/A/__pycache__/launch.cpython-311.pyc index f38555b2e489912d1708b0dcbe2c7f388c4c1c66..44d2292fb5b03297a261476ea2c100751e5d9f3b 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/launch.py b/harness/A/launch.py index 00d366646c834951825ea1295ab5973ebfabf4ba..cf95e9875499995e4eeb214c749b5a75b6fd753e 100644 --- a/harness/A/launch.py +++ b/harness/A/launch.py @@ -47,12 +47,24 @@ def _load_run_module(): def scenes(): """Return unique VSI-Bench scenes in their original manifest order.""" with open(JSONL) as manifest: - return list(dict.fromkeys(str(json.loads(line)["scene_name"]) for line in manifest)) + return list( + dict.fromkeys(str(json.loads(line)["scene_name"]) for line in manifest) + ) def _worker( - tasks, results, model, frame_selection, frame_count, results_dir, gpu, cpu_threads, - extended, reasoning_budget, force_budget, truncated_budget, + tasks, + results, + model, + frame_selection, + frame_count, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, + truncated_budget, ): if gpu is not None: os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) @@ -100,8 +112,15 @@ def _worker( def launch( - model, frame_selection, frame_count, selected, results_dir=None, rebuild=False, - extended=False, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, + model, + frame_selection, + frame_count, + selected, + results_dir=None, + rebuild=False, + extended=False, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, truncated_budget=None, ): """Answer every question for ``selected`` scenes, sharded across every visible GPU. @@ -112,23 +131,30 @@ def launch( if extended and truncated_budget is not None: raise ValueError("extended and truncated_budget are mutually exclusive") protocol = ( - f"{reasoning_budget}" if extended - else f"truncated/{truncated_budget}" if truncated_budget is not None - else "base" + f"{reasoning_budget}" + if extended + else f"truncated/{truncated_budget}" if truncated_budget is not None else "base" ) condition = f"{model}/{protocol}/{frame_selection}/{frame_count}" run = _load_run_module() - root = run.results_dir_for(model, protocol, 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: rows = run.load_questions(scene=scene) - answered = all( - (root / scene / f"{row['id']}.json").is_file() for row in rows - ) + if not rows: + raise ValueError( + f"no questions found for scene {scene!r}; check the manifest/scene selection" + ) + answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows) if answered and not rebuild: completed += 1 - print(f"[{condition} {completed}/{len(selected)}] {scene}: skipped", flush=True) + print( + f"[{condition} {completed}/{len(selected)}] {scene}: skipped", + flush=True, + ) else: pending.append(scene) if not pending: @@ -156,8 +182,18 @@ def launch( context.Process( target=_worker, args=( - tasks, results, model, frame_selection, frame_count, results_dir, - gpu, cpu_threads, extended, reasoning_budget, force_budget, truncated_budget, + tasks, + results, + model, + frame_selection, + frame_count, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, + truncated_budget, ), ) for gpu in assignments @@ -188,11 +224,14 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("scene", nargs="?") parser.add_argument( - "--scenes", help="comma-separated scenes (cannot be combined with positional scene)" + "--scenes", + help="comma-separated scenes (cannot be combined with positional scene)", ) parser.add_argument("--model", required=True, choices=vlm_models.available_models()) parser.add_argument( - "--frame-selection", default=DEFAULT_FRAME_SELECTION, choices=FRAME_SELECTIONS, + "--frame-selection", + default=DEFAULT_FRAME_SELECTION, + choices=FRAME_SELECTIONS, dest="frame_selection", ) parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO) @@ -210,7 +249,9 @@ def main(): parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) parser.add_argument( - "--truncated-budget", type=int, default=None, + "--truncated-budget", + type=int, + default=None, help="raw-budget arm: base-protocol mechanics (single generation, no forced " "rescue) at this token cap, under its own truncated/ path segment " "(mutually exclusive with --extended)", @@ -236,10 +277,16 @@ def main(): if args.extended and args.truncated_budget is not None: parser.error("--extended and --truncated-budget are mutually exclusive") launch( - args.model, args.frame_selection, args.frames, selected, - results_dir=args.results_dir, rebuild=args.rebuild, - extended=args.extended, reasoning_budget=args.reasoning_budget, - force_budget=args.force_budget, truncated_budget=args.truncated_budget, + args.model, + args.frame_selection, + args.frames, + selected, + results_dir=args.results_dir, + rebuild=args.rebuild, + extended=args.extended, + reasoning_budget=args.reasoning_budget, + force_budget=args.force_budget, + truncated_budget=args.truncated_budget, ) diff --git a/harness/A/models.py b/harness/A/models.py index da54d2a74f7c9ea55af9b105b42c83f79335cc7e..c9083ab86974dbeee708d03bc5094dd161052ca7 100644 --- a/harness/A/models.py +++ b/harness/A/models.py @@ -79,8 +79,13 @@ class VLMAdapter(ABC): """ @abstractmethod - def answer_extended(self, frames, question, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, - force_budget=MAX_NEW_TOKENS): + def answer_extended( + self, + frames, + question, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, + ): """Same record shape as ``answer``, but with a much larger first-pass budget to work through the input before answering. If the model does not conclude within that budget (hits it without emitting an end-of-sequence token), a short forced @@ -97,8 +102,10 @@ class VLMAdapter(ABC): whether a silent no-op is acceptable for their arm.""" if "enable_thinking" not in type(self).chat_template_kwargs: return False - self.chat_template_kwargs = {**type(self).chat_template_kwargs, - "enable_thinking": bool(enabled)} + self.chat_template_kwargs = { + **type(self).chat_template_kwargs, + "enable_thinking": bool(enabled), + } return True def unload(self): @@ -138,11 +145,18 @@ class _TransformersVLMAdapter(VLMAdapter): """Render one chat turn to both plain text and tokenized model inputs.""" messages = [{"role": "user", "content": _numbered_content(frames, question)}] prompt_text = self.processor.apply_chat_template( - messages, add_generation_prompt=True, tokenize=False, **self.chat_template_kwargs, + messages, + add_generation_prompt=True, + tokenize=False, + **self.chat_template_kwargs, ) inputs = self.processor.apply_chat_template( - messages, add_generation_prompt=True, tokenize=True, - return_dict=True, return_tensors="pt", **self.chat_template_kwargs, + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt", + **self.chat_template_kwargs, ).to(self.device) # Shapes of every non-text processor output (pixel_values, image_grid_thw, ...) -- # generic across model families instead of hunting each one's own vision placeholder @@ -169,8 +183,12 @@ class _TransformersVLMAdapter(VLMAdapter): start = time.monotonic() with torch.no_grad(): generated = self.model.generate( - **inputs, max_new_tokens=max_new_tokens, do_sample=DO_SAMPLE, - temperature=None, top_p=None, top_k=None, + **inputs, + max_new_tokens=max_new_tokens, + do_sample=DO_SAMPLE, + temperature=None, + top_p=None, + top_k=None, ) if self.device.startswith("cuda"): torch.cuda.synchronize() @@ -179,11 +197,12 @@ class _TransformersVLMAdapter(VLMAdapter): def _decode_new_tokens(self, generated, input_token_count, max_new_tokens, eos_ids): """Split one generate() output into new-token ids + decoded text + hit-limit flag.""" output_token_ids = generated[0][input_token_count:].tolist() - hit_token_limit = ( - len(output_token_ids) >= max_new_tokens - and (not output_token_ids or output_token_ids[-1] not in eos_ids) + hit_token_limit = len(output_token_ids) >= max_new_tokens and ( + not output_token_ids or output_token_ids[-1] not in eos_ids ) - answer_text = self.processor.decode(output_token_ids, skip_special_tokens=True).strip() + answer_text = self.processor.decode( + output_token_ids, skip_special_tokens=True + ).strip() answer_raw = self.processor.decode(output_token_ids, skip_special_tokens=False) return output_token_ids, hit_token_limit, answer_text, answer_raw @@ -201,8 +220,8 @@ class _TransformersVLMAdapter(VLMAdapter): input_token_count = int(inputs["input_ids"].shape[1]) generated, generation_seconds = self._generate(inputs, cap) eos_ids = self._eos_ids() - output_token_ids, hit_token_limit, answer_text, answer_raw = self._decode_new_tokens( - generated, input_token_count, cap, eos_ids + output_token_ids, hit_token_limit, answer_text, answer_raw = ( + self._decode_new_tokens(generated, input_token_count, cap, eos_ids) ) return { @@ -229,8 +248,13 @@ class _TransformersVLMAdapter(VLMAdapter): }, } - def answer_extended(self, frames, question, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, - force_budget=MAX_NEW_TOKENS): + def answer_extended( + self, + frames, + question, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, + ): import torch if self.model is None or self.processor is None: @@ -241,7 +265,9 @@ class _TransformersVLMAdapter(VLMAdapter): generated, reasoning_seconds = self._generate(inputs, reasoning_budget) reasoning_token_ids, reasoning_hit_limit, reasoning_text, reasoning_raw = ( - self._decode_new_tokens(generated, input_token_count, reasoning_budget, eos_ids) + self._decode_new_tokens( + generated, input_token_count, reasoning_budget, eos_ids + ) ) thinking = bool(self.chat_template_kwargs.get("enable_thinking")) @@ -257,9 +283,11 @@ class _TransformersVLMAdapter(VLMAdapter): # budget to extract that answer. Multimodal tensors (pixel_values, etc.) must # be resupplied -- the continued sequence still contains the original image # placeholder tokens, and generate() recomputes their embeddings from scratch. - force_text = ("\n\n" + FORCE_ANSWER_PROMPT) if ( - thinking and not think_closed - ) else FORCE_ANSWER_PROMPT + force_text = ( + ("\n\n" + FORCE_ANSWER_PROMPT) + if (thinking and not think_closed) + else FORCE_ANSWER_PROMPT + ) force_prompt_ids = self.processor.tokenizer( force_text, return_tensors="pt", add_special_tokens=False )["input_ids"].to(self.device) @@ -276,17 +304,27 @@ class _TransformersVLMAdapter(VLMAdapter): # placeholder, so pad with zeros. Per-patch tensors (pixel_values, # image_grid_thw, ...) don't depend on sequence length at all and pass # through unchanged -- this check is what tells the two apart. - if hasattr(value, "shape") and value.dim() >= 2 and value.shape[1] == input_token_count: - pad = value.new_zeros((value.shape[0], added_length) + tuple(value.shape[2:])) + if ( + hasattr(value, "shape") + and value.dim() >= 2 + and value.shape[1] == input_token_count + ): + pad = value.new_zeros( + (value.shape[0], added_length) + tuple(value.shape[2:]) + ) value = torch.cat([value, pad], dim=1) continued_inputs[key] = value continued_inputs["input_ids"] = continued_ids continued_inputs["attention_mask"] = continued_mask forced_input_token_count = int(continued_ids.shape[1]) - forced_generated, forced_seconds = self._generate(continued_inputs, force_budget) - output_token_ids, hit_token_limit, answer_text, answer_raw = self._decode_new_tokens( - forced_generated, forced_input_token_count, force_budget, eos_ids + forced_generated, forced_seconds = self._generate( + continued_inputs, force_budget + ) + output_token_ids, hit_token_limit, answer_text, answer_raw = ( + self._decode_new_tokens( + forced_generated, forced_input_token_count, force_budget, eos_ids + ) ) generation_seconds += forced_seconds else: @@ -380,5 +418,7 @@ def get_adapter(model): """Create one unloaded adapter bound to a registered model's checkpoint path.""" adapter_type = _ADAPTERS.get(model) if adapter_type is None: - raise KeyError(f"unknown harness model {model!r}; expected one of {available_models()}") + raise KeyError( + f"unknown harness model {model!r}; expected one of {available_models()}" + ) return adapter_type(MODEL_PATHS[model]) diff --git a/harness/A/sweep.py b/harness/A/sweep.py index a28ee63d528e9b0c665457b8ba445a68381f65fe..00f55d1b7e5550956cd72f7305092765fffa3259 100644 --- a/harness/A/sweep.py +++ b/harness/A/sweep.py @@ -33,7 +33,9 @@ def _parse_csv_choice(value, valid, flag): return list(valid) unknown = [item for item in items if item not in valid] if unknown: - raise ValueError(f"unknown {flag} value(s) {unknown}; expected one of {valid} (or 'all')") + raise ValueError( + f"unknown {flag} value(s) {unknown}; expected one of {valid} (or 'all')" + ) return list(dict.fromkeys(items)) @@ -66,15 +68,22 @@ def build_plan(models, frame_selections, frame_counts): def sweep( - models, frame_selections, frame_counts, selected_scenes, results_dir=None, rebuild=False, - extended=False, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, truncated_budget=None, + models, + frame_selections, + frame_counts, + selected_scenes, + results_dir=None, + rebuild=False, + extended=False, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + truncated_budget=None, ): """Run every (model, frame_selection, frame_count) triple across all visible GPUs.""" plan = build_plan(models, frame_selections, frame_counts) protocol = ( - f"{reasoning_budget}" if extended - else f"truncated/{truncated_budget}" if truncated_budget is not None - else "base" + f"{reasoning_budget}" + if extended + else f"truncated/{truncated_budget}" if truncated_budget is not None else "base" ) for index, (model, frame_selection, frame_count) in enumerate(plan, start=1): print( @@ -82,9 +91,15 @@ def sweep( flush=True, ) harness_launch.launch( - model, frame_selection, frame_count, selected_scenes, - results_dir=results_dir, rebuild=rebuild, extended=extended, - reasoning_budget=reasoning_budget, truncated_budget=truncated_budget, + model, + frame_selection, + frame_count, + selected_scenes, + results_dir=results_dir, + rebuild=rebuild, + extended=extended, + reasoning_budget=reasoning_budget, + truncated_budget=truncated_budget, ) @@ -92,35 +107,45 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("scene", nargs="?") parser.add_argument( - "--scenes", help="comma-separated scenes (cannot be combined with positional scene)" + "--scenes", + help="comma-separated scenes (cannot be combined with positional scene)", ) parser.add_argument( - "--models", required=True, + "--models", + required=True, help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}", ) parser.add_argument( - "--frame-selections", required=True, dest="frame_selections", + "--frame-selections", + required=True, + dest="frame_selections", help=f"comma-separated selections (or 'all'); one of {FRAME_SELECTIONS}", ) parser.add_argument( - "--frames", required=True, + "--frames", + required=True, help="comma-separated frame counts, e.g. 16,32,64", ) parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") parser.add_argument( - "--extended", action="store_true", + "--extended", + action="store_true", help="run the whole sweep under the extended protocol instead of the fixed " "16-token VSI-Bench protocol (the same flag harness.A.run/launch take)", ) parser.add_argument( - "--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS, + "--reasoning-budget", + type=int, + default=EXTENDED_MAX_NEW_TOKENS, dest="reasoning_budget", help="extended-protocol first-pass budget (the calibrated value from " "analysis/preregistration.md, e.g. 512)", ) parser.add_argument( - "--truncated-budget", type=int, default=None, + "--truncated-budget", + type=int, + default=None, help="raw-budget arm: base-protocol mechanics (single generation, no forced " "rescue) at this token cap (mutually exclusive with --extended)", ) @@ -131,7 +156,9 @@ def main(): parser.error("--extended and --truncated-budget are mutually exclusive") try: - models = _parse_csv_choice(args.models, vlm_models.available_models(), "--models") + models = _parse_csv_choice( + args.models, vlm_models.available_models(), "--models" + ) frame_selections = _parse_csv_choice( args.frame_selections, FRAME_SELECTIONS, "--frame-selections" ) @@ -148,9 +175,15 @@ def main(): selected = [args.scene] if args.scene else harness_launch.scenes() sweep( - models, frame_selections, frame_counts, selected, - results_dir=args.results_dir, rebuild=args.rebuild, extended=args.extended, - reasoning_budget=args.reasoning_budget, truncated_budget=args.truncated_budget, + models, + frame_selections, + frame_counts, + selected, + results_dir=args.results_dir, + rebuild=args.rebuild, + extended=args.extended, + reasoning_budget=args.reasoning_budget, + truncated_budget=args.truncated_budget, ) diff --git a/harness/B/__init__.py b/harness/B/__init__.py index 0a04165c86fb1355ddce96bea7df594aa13b7714..6aa2feb660a7dbbbb904bcaa0ce82c2459e0f0e9 100644 --- a/harness/B/__init__.py +++ b/harness/B/__init__.py @@ -15,7 +15,14 @@ from pathlib import Path from encoder.config import DEPTH_VARIANTS, TRACKING_MODES -from harness.A import DO_SAMPLE, JSONL, MAX_NEW_TOKENS, MODEL_PATHS, TEMPERATURE, WORKSPACE_ROOT +from harness.A import ( + DO_SAMPLE, + JSONL, + MAX_NEW_TOKENS, + MODEL_PATHS, + TEMPERATURE, + WORKSPACE_ROOT, +) # Same two on-disk spatial-code schemas encoder/geometric.py can build. SPATIAL_CODE_FORMATS = ("explicit", "compact") @@ -37,6 +44,4 @@ FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_B_FRAMES_PER_VIDEO", "32")) # One JSON per question, matching harness.A's layout: # results/B////////.json -RESULTS_DIR = Path( - os.environ.get("VSI_HARNESS_B_RESULTS_DIR", "/root/results/B") -) +RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_B_RESULTS_DIR", "/root/results/B")) diff --git a/harness/B/__pycache__/__init__.cpython-311.pyc b/harness/B/__pycache__/__init__.cpython-311.pyc index cca5e901d34697dbb531a0579391531c6872d347..4631037e7704f48189e847e57c5463bf121f6ebe 100644 Binary files a/harness/B/__pycache__/__init__.cpython-311.pyc and b/harness/B/__pycache__/__init__.cpython-311.pyc differ diff --git a/harness/B/__pycache__/launch.cpython-311.pyc b/harness/B/__pycache__/launch.cpython-311.pyc index d7d19d99efd88a14a80d963f603f3e1dab2437c7..41b1e9dd37c921f823d532564bf778ff90b3fae8 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 566adec6f9900ab4331e94bb812a293089b20a30..19198cad8d4886f0f7822267b0d23c1f589027d7 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/prompts.py b/harness/B/prompts.py index 42ca36b834fccc15bd8e843932b8798416b44537..8626498a28d43e68672589b59a57727c437ab6da 100644 --- a/harness/B/prompts.py +++ b/harness/B/prompts.py @@ -16,7 +16,12 @@ from __future__ import annotations import json -from harness.A.prompts import MCA_POST_PROMPT, MCA_QUESTION_TYPES, NA_POST_PROMPT, NA_QUESTION_TYPES +from harness.A.prompts import ( + MCA_POST_PROMPT, + MCA_QUESTION_TYPES, + NA_POST_PROMPT, + NA_QUESTION_TYPES, +) # Deliberately vague about which fields are present -- compact and explicit carry # different fields (e.g. only explicit has a distance table and appearance order; only @@ -66,61 +71,63 @@ REASONING_BREVITY_NOTE = ( "or re-derive values you have already found." ) -PROSE_LEGEND = "\n\n".join([ - ( - "You are a multimodal reasoning model that interprets structured scene inputs. " - "You will be provided with the spatial code of a scanned room." - ), - ( - "Below is the spatial code of a scanned room. " - "It is a JSON description of the room. " - "It is built automatically from a video walkthrough." - ), - ( - "Every value below that is a physical measurement is written as a STRING. " - "It already names its own unit, such as \"1.46 meters\", \"3.0 seconds\", or " - "\"91 degrees\"." - ), - ( - "The objects section lists object classes that were detected in the room. " - "An object class is a category of object, such as \"chair\" or \"table\". " - "Each object class has a count, the number of objects of that class that are in " - "the room. " - "Each object class has a list of instances, the individual objects of that class " - "that were detected in the room. " - "Each instance has a position given as \"x coordinate\", \"y coordinate\" and " - "\"height above floor\". " - "X coordinate is the instance's distance in meters along one fixed horizontal " - "direction of the room. " - "Y coordinate is the instance's distance in meters along a second fixed horizontal " - "direction perpendicular to the first. " - "Height above floor is the instance's vertical distance in meters above the floor. " - "These directions are the same for everything in the room. " - "Each instance also has a \"longest dimension\", the length in meters of that " - "instance's single longest side." - ), - ( - "The room section describes the room as a whole. " - "The room also has a \"floor area\", the total floor area of the room in square " - "meters." - ), - ( - "The \"closest classes distance meters from\" section has, for every object class, " - "the distance to each other class and the closeness rank of each other class. " - "Distance is the minimum distance in meters between an instance of the class and an " - "instance of the other class. " - "Closeness rank orders the other classes by nearness to the class. " - "Rank 1 is the nearest class. The largest rank is the farthest class. " - "The larger the rank, the farther the class." - ), - ( - "The \"appearance order\" section lists every object class in the order it " - "appeared in the video. " - "The leftmost class in the list is the class that appeared earliest. " - "The rightmost class in the list is the class that appeared last. " - "The further right a class is in the list, the later it appeared." - ), -]) +PROSE_LEGEND = "\n\n".join( + [ + ( + "You are a multimodal reasoning model that interprets structured scene inputs. " + "You will be provided with the spatial code of a scanned room." + ), + ( + "Below is the spatial code of a scanned room. " + "It is a JSON description of the room. " + "It is built automatically from a video walkthrough." + ), + ( + "Every value below that is a physical measurement is written as a STRING. " + 'It already names its own unit, such as "1.46 meters", "3.0 seconds", or ' + '"91 degrees".' + ), + ( + "The objects section lists object classes that were detected in the room. " + 'An object class is a category of object, such as "chair" or "table". ' + "Each object class has a count, the number of objects of that class that are in " + "the room. " + "Each object class has a list of instances, the individual objects of that class " + "that were detected in the room. " + 'Each instance has a position given as "x coordinate", "y coordinate" and ' + '"height above floor". ' + "X coordinate is the instance's distance in meters along one fixed horizontal " + "direction of the room. " + "Y coordinate is the instance's distance in meters along a second fixed horizontal " + "direction perpendicular to the first. " + "Height above floor is the instance's vertical distance in meters above the floor. " + "These directions are the same for everything in the room. " + 'Each instance also has a "longest dimension", the length in meters of that ' + "instance's single longest side." + ), + ( + "The room section describes the room as a whole. " + 'The room also has a "floor area", the total floor area of the room in square ' + "meters." + ), + ( + 'The "closest classes distance meters from" section has, for every object class, ' + "the distance to each other class and the closeness rank of each other class. " + "Distance is the minimum distance in meters between an instance of the class and an " + "instance of the other class. " + "Closeness rank orders the other classes by nearness to the class. " + "Rank 1 is the nearest class. The largest rank is the farthest class. " + "The larger the rank, the farther the class." + ), + ( + 'The "appearance order" section lists every object class in the order it ' + "appeared in the video. " + "The leftmost class in the list is the class that appeared earliest. " + "The rightmost class in the list is the class that appeared last. " + "The further right a class is in the list, the later it appeared." + ), + ] +) def distance_only_table(spatial_code): @@ -132,9 +139,7 @@ def distance_only_table(spatial_code): table = code.get("closest classes distance meters from") if table: code["closest classes distance meters from"] = { - class_name: { - other: entry["distance"] for other, entry in neighbors.items() - } + class_name: {other: entry["distance"] for other, entry in neighbors.items()} for class_name, neighbors in table.items() } return code @@ -178,8 +183,13 @@ def render_code(spatial_code, serialization="json"): def build_prompt( - spatial_code, question_type, question, options=None, - serialization="json", context_line=None, reasoning_note=False, + spatial_code, + question_type, + question, + options=None, + serialization="json", + context_line=None, + reasoning_note=False, ): """Return the full text prompt: context line, the spatial code itself, the question, and the same VSI-Bench post-prompt harness.A uses for the same question_type. @@ -187,8 +197,16 @@ def build_prompt( defaults reproduce the standard prompt byte-for-byte.""" code_text = render_code(spatial_code, serialization) pre_prompt = PRE_PROMPT if context_line is None else context_line - na_post = (REASONING_BREVITY_NOTE + "\n" + NA_POST_PROMPT) if reasoning_note else NA_POST_PROMPT - mca_post = (REASONING_BREVITY_NOTE + "\n" + MCA_POST_PROMPT) if reasoning_note else MCA_POST_PROMPT + na_post = ( + (REASONING_BREVITY_NOTE + "\n" + NA_POST_PROMPT) + if reasoning_note + else NA_POST_PROMPT + ) + mca_post = ( + (REASONING_BREVITY_NOTE + "\n" + MCA_POST_PROMPT) + if reasoning_note + else MCA_POST_PROMPT + ) if serialization == "yaml" and context_line is None: # The context line must not claim JSON when the code is rendered as YAML -- # otherwise the serialization arm would carry a false description as a diff --git a/harness/B/run.py b/harness/B/run.py index 93b14aae6db9b698cea0af0bbb51b2d5896b1026..e9da0e9b9ece775095e6ed43155413c7b34f4834 100644 --- a/harness/B/run.py +++ b/harness/B/run.py @@ -45,7 +45,13 @@ from harness.B.prompts import ( # noqa: E402 def results_dir_for( - model, protocol, spatial_code_format, depth, tracking, input_selection, frame_count, + model, + protocol, + spatial_code_format, + depth, + tracking, + input_selection, + frame_count, results_dir=None, ): """Return the result root isolated by model + protocol + spatial-code-format + @@ -56,12 +62,20 @@ def results_dir_for( if results_dir is not None: return Path(results_dir) return ( - RESULTS_DIR / model / protocol / spatial_code_format / depth / tracking - / input_selection / str(frame_count) + RESULTS_DIR + / model + / protocol + / spatial_code_format + / depth + / tracking + / input_selection + / str(frame_count) ) -def _build_record(row, prompt, answer, metric_name, score, model, model_path, code_info): +def _build_record( + row, prompt, answer, metric_name, score, model, model_path, code_info +): """Assemble one question's full, untruncated result record (nothing summarized).""" return { "model": model, @@ -113,10 +127,20 @@ def _build_record(row, prompt, answer, metric_name, score, model, model_path, co def write_question_result( - row, prompt, answer, metric_name, score, model, model_path, code_info, results_dir=None + row, + prompt, + answer, + metric_name, + score, + model, + model_path, + code_info, + 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, code_info) + record = _build_record( + row, prompt, answer, metric_name, score, model, model_path, code_info + ) root = results_dir_for( model, code_info["protocol"], @@ -211,7 +235,12 @@ def run( scene_id = row["scene_name"] if scene_id not in code_cache: code, path = spatial_codes.load_spatial_code( - scene_id, depth, input_selection, tracking, frame_count, spatial_code_format + scene_id, + depth, + input_selection, + tracking, + frame_count, + spatial_code_format, ) if strip_schema_legend: # Legend-ablation arm: identical data, no embedded field legend. @@ -221,27 +250,37 @@ def run( 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"), - serialization=serialization, context_line=context_line, + cached["code"], + row["question_type"], + row["question"], + row.get("options"), + serialization=serialization, + context_line=context_line, reasoning_note=reasoning_note, ) answer = ( adapter.answer_extended( - [], prompt, reasoning_budget=reasoning_budget, force_budget=force_budget + [], + prompt, + reasoning_budget=reasoning_budget, + force_budget=force_budget, ) if extended else adapter.answer([], prompt, max_new_tokens=raw_budget) ) - doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]} + 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) code_info = { "protocol": ( - f"{reasoning_budget}" if extended - else f"truncated/{raw_budget}" if raw_budget is not None - else "base" + f"{reasoning_budget}" + if extended + else f"truncated/{raw_budget}" if raw_budget is not None else "base" ), "spatial_code_format": spatial_code_format, "input_selection": input_selection, @@ -252,13 +291,27 @@ def run( } if write_results: path, record = write_question_result( - row, prompt, answer, metric_name, score, model, adapter.model_path, - code_info, results_dir, + row, + prompt, + answer, + metric_name, + score, + model, + adapter.model_path, + code_info, + results_dir, ) else: path = None record = _build_record( - row, prompt, answer, metric_name, score, model, adapter.model_path, code_info + row, + prompt, + answer, + metric_name, + score, + model, + adapter.model_path, + code_info, ) record["result_path"] = str(path) if path else None results.append(record) @@ -273,73 +326,97 @@ def main(): 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( - "--spatial-code-format", default=DEFAULT_SPATIAL_CODE_FORMAT, - choices=SPATIAL_CODE_FORMATS, dest="spatial_code_format", + "--spatial-code-format", + default=DEFAULT_SPATIAL_CODE_FORMAT, + choices=SPATIAL_CODE_FORMATS, + dest="spatial_code_format", ) parser.add_argument( - "--input-selection", default=DEFAULT_INPUT_SELECTION, - choices=INPUT_SELECTIONS, dest="input_selection", + "--input-selection", + default=DEFAULT_INPUT_SELECTION, + choices=INPUT_SELECTIONS, + dest="input_selection", ) parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO) parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS) parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES) - parser.add_argument("--limit", type=int, default=None, help="cap the number of questions") + 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, + "--results-dir", + default=None, help="override the default results/B////" "/// root", ) parser.add_argument( - "--no-write", action="store_true", + "--no-write", + action="store_true", help="skip writing per-question JSON files; print/score only", ) parser.add_argument( - "--serialization", default="json", choices=SERIALIZATIONS, + "--serialization", + default="json", + choices=SERIALIZATIONS, help="robustness arm only: render the identical code dict as YAML instead of " "JSON (pair with an explicit --results-dir so the arm stays isolated)", ) parser.add_argument( - "--paraphrase-context", action="store_true", dest="paraphrase_context", + "--paraphrase-context", + action="store_true", + dest="paraphrase_context", help="robustness arm only: use the pre-registered paraphrased context line " "(pair with an explicit --results-dir)", ) parser.add_argument( - "--no-schema-legend", action="store_true", dest="strip_schema_legend", + "--no-schema-legend", + action="store_true", + dest="strip_schema_legend", help="legend-ablation arm: drop the embedded 'spatial code schema' block from " "the code before prompting (identical data, no legend; pair with an explicit " "--results-dir)", ) parser.add_argument( - "--prose-legend", action="store_true", dest="prose_legend", + "--prose-legend", + action="store_true", + dest="prose_legend", help="legacy-legend arm: drop the embedded schema block AND use the legacy " "prose legend as the context block (pair with an explicit --results-dir)", ) parser.add_argument( - "--reasoning-note", action="store_true", dest="reasoning_note", + "--reasoning-note", + action="store_true", + dest="reasoning_note", help="prefix the Thinking-with-Spatial-Code step-by-step note to the " "post-prompt (pair with an explicit --results-dir)", ) parser.add_argument( - "--thinking", action="store_true", + "--thinking", + action="store_true", help="enable the model's native thinking mode (Qwen only; errors on models " "without the switch; pair with an explicit --results-dir)", ) parser.add_argument( - "--base-protocol", action="store_true", + "--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) parser.add_argument( - "--truncated-budget", type=int, default=None, + "--truncated-budget", + type=int, + default=None, help="raw-budget arm: base-protocol mechanics (single generation, no forced " "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive " "with --base-protocol)", ) parser.add_argument( - "--flat-distance-table", action="store_true", dest="flat_distance_table", + "--flat-distance-table", + action="store_true", + dest="flat_distance_table", help="flat-table arm: flatten the distance table's two-level nesting into " "single-level ' to ' keys, identical information (pair with " "an explicit --results-dir)", @@ -372,10 +449,13 @@ def main(): raw_budget=args.truncated_budget, serialization=args.serialization, context_line=( - PROSE_LEGEND if args.prose_legend - else PARAPHRASE_PRE_PROMPT if args.paraphrase_context - else NO_LEGEND_PRE_PROMPT if args.strip_schema_legend - else None + PROSE_LEGEND + if args.prose_legend + else ( + PARAPHRASE_PRE_PROMPT + if args.paraphrase_context + else NO_LEGEND_PRE_PROMPT if args.strip_schema_legend else None + ) ), strip_schema_legend=args.strip_schema_legend or args.prose_legend, reasoning_note=args.reasoning_note, diff --git a/harness/C/__init__.py b/harness/C/__init__.py index 04c3ab3289c5d15fa8e78ec91192b9f1574183fd..5eb052278ddf0bd1df7af069af49322298ece3a6 100644 --- a/harness/C/__init__.py +++ b/harness/C/__init__.py @@ -45,6 +45,4 @@ FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_C_FRAMES_PER_VIDEO", "32")) # One JSON per question, matching harness.A/B's layout: # results/C////////.json -RESULTS_DIR = Path( - os.environ.get("VSI_HARNESS_C_RESULTS_DIR", "/root/results/C") -) +RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_C_RESULTS_DIR", "/root/results/C")) diff --git a/harness/C/__pycache__/__init__.cpython-311.pyc b/harness/C/__pycache__/__init__.cpython-311.pyc index 0649f8a7669266dd6ad377cf799337ec508381fb..df55062158b013035717bdca8d8970939ae856f6 100644 Binary files a/harness/C/__pycache__/__init__.cpython-311.pyc and b/harness/C/__pycache__/__init__.cpython-311.pyc differ diff --git a/harness/C/__pycache__/launch.cpython-311.pyc b/harness/C/__pycache__/launch.cpython-311.pyc index d2d609d17e3cface2ed95f14761c3d06d98571f1..e013bb30a601ff077ddae68b9cc95ac3ec93a4f2 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__/overlay.cpython-311.pyc b/harness/C/__pycache__/overlay.cpython-311.pyc index 0f39121c1f86d3d38c9a014abe2661ca5ea8b618..4440255babe92d4f12289b2592697cf6fe45a5f4 100644 Binary files a/harness/C/__pycache__/overlay.cpython-311.pyc and b/harness/C/__pycache__/overlay.cpython-311.pyc differ diff --git a/harness/C/__pycache__/overlay_launch.cpython-311.pyc b/harness/C/__pycache__/overlay_launch.cpython-311.pyc index 1c0fd843feb57e093bfd3a7f7e49bd82b11536f8..60490bd255421e6920978827fcf4c8aed5404943 100644 Binary files a/harness/C/__pycache__/overlay_launch.cpython-311.pyc and b/harness/C/__pycache__/overlay_launch.cpython-311.pyc differ diff --git a/harness/C/__pycache__/prompts.cpython-311.pyc b/harness/C/__pycache__/prompts.cpython-311.pyc index 3e4fc1fe846580828f936213af8ef5337e21c638..b2ab6463df4323597b7788d8d42167e824f4ab35 100644 Binary files a/harness/C/__pycache__/prompts.cpython-311.pyc and b/harness/C/__pycache__/prompts.cpython-311.pyc differ diff --git a/harness/C/__pycache__/run.cpython-311.pyc b/harness/C/__pycache__/run.cpython-311.pyc index 509d801f8caec1f2b15fe5d29b724f47d18ea126..701df1f5532c152c007ce665db01b1d401cfc064 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 7a0a29ed4503699675d81db81dfd9c0edc083b4b..bdc702fda61e0d58c13be302959df3a6fd8f0cf7 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 a0353dd1a8b1c17028c9ca5896007a8924e41a93..5f9e32a6f70f899e5e170fbd848f5ebb86d35233 100644 --- a/harness/C/launch.py +++ b/harness/C/launch.py @@ -49,12 +49,25 @@ def _load_run_module(): def _worker( - tasks, results, model, spatial_code_format, input_selection, frame_count, depth, tracking, - results_dir, gpu, cpu_threads, extended, reasoning_budget, force_budget, + tasks, + results, + model, + spatial_code_format, + input_selection, + frame_count, + depth, + tracking, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, strip_schema_legend, frame_linked, overlay, - raw_budget, flat_distance_table, + raw_budget, + flat_distance_table, ): if gpu is not None: os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) @@ -109,13 +122,23 @@ def _worker( def launch( - model, spatial_code_format, input_selection, frame_count, selected, - depth=DEFAULT_DEPTH, tracking=DEFAULT_TRACKING, results_dir=None, rebuild=False, - extended=True, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, + model, + spatial_code_format, + input_selection, + frame_count, + selected, + depth=DEFAULT_DEPTH, + tracking=DEFAULT_TRACKING, + results_dir=None, + rebuild=False, + extended=True, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, strip_schema_legend=False, frame_linked=False, overlay=False, - raw_budget=None, flat_distance_table=False, + raw_budget=None, + flat_distance_table=False, ): """Answer every question for ``selected`` scenes, sharded across every visible GPU. @@ -125,9 +148,9 @@ def launch( if extended and raw_budget is not None: raise ValueError("extended and raw_budget are mutually exclusive") protocol = ( - f"{reasoning_budget}" if extended - else f"truncated/{raw_budget}" if raw_budget is not None - else "base" + f"{reasoning_budget}" + if extended + else f"truncated/{raw_budget}" if raw_budget is not None else "base" ) condition = ( f"{model}/{protocol}/{spatial_code_format}/{depth}/{tracking}" @@ -135,7 +158,13 @@ def launch( ) run = _load_run_module() root = run.results_dir_for( - model, protocol, spatial_code_format, depth, tracking, input_selection, frame_count, + model, + protocol, + spatial_code_format, + depth, + tracking, + input_selection, + frame_count, results_dir, overlay=overlay, ) @@ -143,10 +172,17 @@ def launch( completed = 0 for scene in selected: rows = run.load_questions(scene=scene) + if not rows: + raise ValueError( + f"no questions found for scene {scene!r}; check the manifest/scene selection" + ) answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows) if answered and not rebuild: completed += 1 - print(f"[{condition} {completed}/{len(selected)}] {scene}: skipped", flush=True) + print( + f"[{condition} {completed}/{len(selected)}] {scene}: skipped", + flush=True, + ) else: pending.append(scene) if not pending: @@ -174,9 +210,24 @@ def launch( context.Process( target=_worker, args=( - tasks, results, model, spatial_code_format, input_selection, frame_count, - depth, tracking, results_dir, gpu, cpu_threads, extended, reasoning_budget, - force_budget, strip_schema_legend, frame_linked, overlay, raw_budget, + tasks, + results, + model, + spatial_code_format, + input_selection, + frame_count, + depth, + tracking, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, + strip_schema_legend, + frame_linked, + overlay, + raw_budget, flat_distance_table, ), ) @@ -208,16 +259,21 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("scene", nargs="?") parser.add_argument( - "--scenes", help="comma-separated scenes (cannot be combined with positional scene)" + "--scenes", + help="comma-separated scenes (cannot be combined with positional scene)", ) parser.add_argument("--model", required=True, choices=vlm_models.available_models()) parser.add_argument( - "--spatial-code-format", default=DEFAULT_SPATIAL_CODE_FORMAT, - choices=SPATIAL_CODE_FORMATS, dest="spatial_code_format", + "--spatial-code-format", + default=DEFAULT_SPATIAL_CODE_FORMAT, + choices=SPATIAL_CODE_FORMATS, + dest="spatial_code_format", ) parser.add_argument( - "--input-selection", default=DEFAULT_INPUT_SELECTION, - choices=INPUT_SELECTIONS, dest="input_selection", + "--input-selection", + default=DEFAULT_INPUT_SELECTION, + choices=INPUT_SELECTIONS, + dest="input_selection", ) parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO) parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS) @@ -225,34 +281,45 @@ def main(): parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") parser.add_argument( - "--base-protocol", action="store_true", + "--base-protocol", + action="store_true", help="run harness.A's exact fixed 16-token protocol instead of the extended default", ) parser.add_argument( - "--overlay-ids", action="store_true", dest="overlay", + "--overlay-ids", + action="store_true", + dest="overlay", help="strong correspondence arm: stamp instance ids onto the frames at each " "instance's projected position and add matching ids to the code (defaults to " "/root/results/C/overlay; pair with --no-schema-legend)", ) parser.add_argument( - "--frame-linked-code", action="store_true", dest="frame_linked", + "--frame-linked-code", + action="store_true", + dest="frame_linked", help="correspondence arm: add per-instance 'first visible in: frame N' pointers " "(pair with an explicit --results-dir)", ) parser.add_argument( - "--no-schema-legend", action="store_true", dest="strip_schema_legend", + "--no-schema-legend", + action="store_true", + dest="strip_schema_legend", help="drop the embedded schema legend (the amended main-run design)", ) parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) parser.add_argument( - "--truncated-budget", type=int, default=None, + "--truncated-budget", + type=int, + default=None, help="raw-budget arm: base-protocol mechanics (single generation, no forced " "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive " "with --base-protocol)", ) parser.add_argument( - "--flat-distance-table", action="store_true", dest="flat_distance_table", + "--flat-distance-table", + action="store_true", + dest="flat_distance_table", help="flat-table arm: flatten the distance table's two-level nesting into " "single-level ' to ' keys, identical information (pair with " "an explicit --results-dir)", @@ -278,11 +345,19 @@ def main(): if args.base_protocol and args.truncated_budget is not None: parser.error("--base-protocol and --truncated-budget are mutually exclusive") 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, + 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 and args.truncated_budget is None, raw_budget=args.truncated_budget, - reasoning_budget=args.reasoning_budget, force_budget=args.force_budget, + reasoning_budget=args.reasoning_budget, + force_budget=args.force_budget, strip_schema_legend=args.strip_schema_legend, frame_linked=args.frame_linked, overlay=args.overlay, diff --git a/harness/C/overlay.py b/harness/C/overlay.py index bad347477d9fd8a2acd6f6b4e0564fc5d1eca0e7..13e3168e40957eb44ed7048f9d51ad03e481957b 100644 --- a/harness/C/overlay.py +++ b/harness/C/overlay.py @@ -85,7 +85,11 @@ def _place_label_box(anchor_x, anchor_y, width, height, placed, frame_h, step): offset = direction * step * ((attempt + 1) // 2) top = anchor_y + offset box = (anchor_x, top, anchor_x + width, top + height) - if 0 <= box[1] and box[3] <= frame_h and not any(_boxes_overlap(box, p) for p in placed): + if ( + 0 <= box[1] + and box[3] <= frame_h + and not any(_boxes_overlap(box, p) for p in placed) + ): return box, attempt > 0 return box, True @@ -136,7 +140,9 @@ def _load_raw_sam3_boxes(scene_id, input_selection, tracking, frame_count): per frame, per masklet.""" import torch - path = encoder_config.sam3_cache_file(scene_id, input_selection, tracking, frame_count) + path = encoder_config.sam3_cache_file( + scene_id, input_selection, tracking, frame_count + ) if not Path(path).is_file(): raise FileNotFoundError( f"no raw SAM3 cache found for scene {scene_id!r} at {path} -- the strong " @@ -152,7 +158,8 @@ def _load_raw_sam3_boxes(scene_id, input_selection, tracking, frame_count): obj_ids = outputs.get("out_obj_ids", []) boxes = outputs.get("out_boxes_xywh", []) frames[int(entry["frame_index"])] = { - int(oid): tuple(float(v) for v in box) for oid, box in zip(obj_ids, boxes) + int(oid): tuple(float(v) for v in box) + for oid, box in zip(obj_ids, boxes) } out[str(class_name)] = frames return out @@ -166,11 +173,57 @@ def overlay_frame_cache_dir(scene_id, depth, input_selection, tracking, frame_co room_gravity on the depth-specific geometry cache). Format is always explicit (the only format the correspondence arms support), so it isn't part of the path.""" return ( - encoder_config.CACHE_ROOT / "overlay-frames" / depth / tracking / input_selection - / str(frame_count) / scene_id + encoder_config.CACHE_ROOT + / "overlay-frames" + / depth + / tracking + / input_selection + / str(frame_count) + / scene_id ) +def overlay_spatial_code_path(scene_id, depth, input_selection, tracking, frame_count): + """Return the durable overlay-code JSON path for one scene/config. + + Overlay codes are stored under the configured spatial-code root's top-level + ``overlay`` directory so an overlay run has a browsable code artifact matching + the stamped frames, instead of only an in-memory prompt transform. + """ + encoder_config._validate_dimensions(depth, input_selection, tracking, frame_count) + return ( + encoder_config.CODES_ROOT + / "overlay" + / encoder_config.MODEL + / depth + / tracking + / input_selection + / str(frame_count) + / "explicit" + / f"{scene_id}.json" + ) + + +def load_or_create_overlay_code( + explicit_code, scene_id, depth, input_selection, tracking, frame_count +): + """Load an existing overlay code, or create and save it from ``explicit_code``. + + The saved code is exactly ``instance_ids(explicit_code)``. Existing files are + trusted as the durable artifact for that scene/config and are not rewritten. + Returns ``(code, path)``. + """ + path = overlay_spatial_code_path( + scene_id, depth, input_selection, tracking, frame_count + ) + if path.is_file(): + return json.loads(path.read_text(encoding="utf-8")), str(path) + code = instance_ids(explicit_code) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(code, indent=1) + "\n", encoding="utf-8") + return code, str(path) + + def _load_cached_frames(cache_dir, frame_count): """Return (stamped_frame_copies, per_frame_visible_labels) if a complete cache exists at ``cache_dir`` (every frame PNG plus the labels sidecar present), else @@ -195,7 +248,13 @@ def _save_cached_frames(cache_dir, stamped, visible): def stamp_frames( - frame_images, explicit_code, scene_id, depth, input_selection, tracking, frame_count, + frame_images, + explicit_code, + scene_id, + depth, + input_selection, + tracking, + frame_count, use_cache=True, ): """Return (stamped_frame_copies, per_frame_visible_labels). For every code @@ -213,7 +272,9 @@ def stamp_frames( it across every model/run that touches this scene/config is a pure speed win. Pass False to force a fresh computation (e.g. after a code or overlay-logic change, before the cache is known to be stale and worth clearing).""" - cache_dir = overlay_frame_cache_dir(scene_id, depth, input_selection, tracking, frame_count) + cache_dir = overlay_frame_cache_dir( + scene_id, depth, input_selection, tracking, frame_count + ) if use_cache: cached = _load_cached_frames(cache_dir, frame_count) if cached is not None: @@ -246,19 +307,24 @@ def stamp_frames( frame_labels = [] for label, class_name, oids in labels: frame_detections = raw_boxes.get(class_name, {}).get(frame_index, {}) - box = next((frame_detections[oid] for oid in oids if oid in frame_detections), None) + box = next( + (frame_detections[oid] for oid in oids if oid in frame_detections), None + ) if box is None: continue # SAM3's own tracker did not report this instance in this frame nx, ny, nw, nh = box # normalized [0,1] -- SAM3's own box, verbatim bx0, by0 = nx * hi_res_size[0], ny * hi_res_size[1] bw, bh = nw * hi_res_size[0], nh * hi_res_size[1] draw.rectangle( - [bx0, by0, bx0 + bw, by0 + bh], outline="red", width=max(2, _SUPERSAMPLE) + [bx0, by0, bx0 + bw, by0 + bh], + outline="red", + width=max(2, _SUPERSAMPLE), ) px, py = bx0 + bw / 2, by0 + bh / 2 draw.ellipse( [px - marker_r, py - marker_r, px + marker_r, py + marker_r], - outline="red", width=max(2, _SUPERSAMPLE), + outline="red", + width=max(2, _SUPERSAMPLE), ) # Flip the label to the opposite side of the marker whenever its default # placement would run off the frame -- a label clipped at the image edge is @@ -267,15 +333,26 @@ def stamp_frames( text_height = _FONT_SIZE * _SUPERSAMPLE * 1.3 gap = 8 * _SUPERSAMPLE text_x = ( - px - gap - text_width if px + gap + text_width > hi_res_size[0] else px + gap + px - gap - text_width + if px + gap + text_width > hi_res_size[0] + else px + gap + ) + anchor_y = ( + py + 4 * _SUPERSAMPLE + if py - 10 * _SUPERSAMPLE < 0 + else py - 10 * _SUPERSAMPLE ) - anchor_y = py + 4 * _SUPERSAMPLE if py - 10 * _SUPERSAMPLE < 0 else py - 10 * _SUPERSAMPLE # Nudge this label's box away from every label already placed in this # frame -- a crowded cluster fans its labels out instead of stacking them # into an unreadable smear (see _place_label_box's docstring). label_box, was_nudged = _place_label_box( - text_x, anchor_y, text_width, text_height, placed_boxes, - hi_res_size[1], step=text_height + 2 * _SUPERSAMPLE, + text_x, + anchor_y, + text_width, + text_height, + placed_boxes, + hi_res_size[1], + step=text_height + 2 * _SUPERSAMPLE, ) placed_boxes.append(label_box) if was_nudged: @@ -289,17 +366,24 @@ def stamp_frames( anchor_y_mid = (label_box[1] + label_box[3]) / 2 draw.line( [(px, py), (anchor_x, anchor_y_mid)], - fill=(255, 70, 55, 210), width=max(2, _SUPERSAMPLE), + fill=(255, 70, 55, 210), + width=max(2, _SUPERSAMPLE), ) # A thin dark stroke (not a solid fill box) keeps the label legible # against any background without blotting out the photo underneath it. draw.text( - (label_box[0], label_box[1]), label, font=_LABEL_FONT, fill="#ff4030", - stroke_width=max(2, _SUPERSAMPLE), stroke_fill=(0, 0, 0, 235), + (label_box[0], label_box[1]), + label, + font=_LABEL_FONT, + fill="#ff4030", + stroke_width=max(2, _SUPERSAMPLE), + stroke_fill=(0, 0, 0, 235), ) frame_labels.append(label) overlay_layer = overlay_layer.resize(image.size, Image.LANCZOS) - composited = Image.alpha_composite(image.convert("RGBA"), overlay_layer).convert("RGB") + composited = Image.alpha_composite( + image.convert("RGBA"), overlay_layer + ).convert("RGB") stamped.append(composited) visible.append(frame_labels) if use_cache: diff --git a/harness/C/overlay_launch.py b/harness/C/overlay_launch.py index 70c7a6ad2ef3a934752a8bfa09ef05e18540141b..261f90a77ab05be6fde6dd5d31c37732bf3d9906 100644 --- a/harness/C/overlay_launch.py +++ b/harness/C/overlay_launch.py @@ -84,15 +84,26 @@ def _generate_one(args): video_path, frame_count, input_selection ) overlay.stamp_frames( - frame_images, code, scene, depth, input_selection, tracking, frame_count, + frame_images, + code, + scene, + depth, + input_selection, + tracking, + frame_count, use_cache=True, ) + overlay.load_or_create_overlay_code( + code, scene, depth, input_selection, tracking, frame_count + ) return scene, True, None except Exception: return scene, False, traceback.format_exc() -def launch(depth, input_selection, tracking, frame_count, selected, rebuild=False, workers=0): +def launch( + depth, input_selection, tracking, frame_count, selected, rebuild=False, workers=0 +): """Pre-generate the overlay-frame cache for every scene in ``selected`` that has both required dependencies. Returns (succeeded, failed, skipped_missing_deps) scene-name lists.""" @@ -103,7 +114,9 @@ def launch(depth, input_selection, tracking, frame_count, selected, rebuild=Fals else: missing.append(scene) if missing: - print(f"[overlay-launch] {len(missing)} scene(s) missing a code or SAM3 cache, skipped:") + print( + f"[overlay-launch] {len(missing)} scene(s) missing a code or SAM3 cache, skipped:" + ) print(f" {missing}") if not rebuild: @@ -112,7 +125,13 @@ def launch(depth, input_selection, tracking, frame_count, selected, rebuild=Fals cache_dir = overlay.overlay_frame_cache_dir( scene, depth, input_selection, tracking, frame_count ) - if overlay._load_cached_frames(cache_dir, frame_count) is not None: + code_path = overlay.overlay_spatial_code_path( + scene, depth, input_selection, tracking, frame_count + ) + if ( + overlay._load_cached_frames(cache_dir, frame_count) is not None + and code_path.is_file() + ): continue pending.append(scene) skipped = len(eligible) - len(pending) @@ -122,13 +141,19 @@ def launch(depth, input_selection, tracking, frame_count, selected, rebuild=Fals pending = eligible if not pending: - print(f"[overlay-launch] DONE: 0 generated, {len(eligible) - len(pending)} skipped") + print( + f"[overlay-launch] DONE: 0 generated, {len(eligible) - len(pending)} skipped" + ) return [], [], missing worker_count = workers if workers > 0 else _available_cpu_count() worker_count = min(worker_count, len(pending)) - print(f"[overlay-launch] generating {len(pending)} scene(s) with {worker_count} worker(s)") - tasks = [(scene, depth, input_selection, tracking, frame_count) for scene in pending] + print( + f"[overlay-launch] generating {len(pending)} scene(s) with {worker_count} worker(s)" + ) + tasks = [ + (scene, depth, input_selection, tracking, frame_count) for scene in pending + ] with mp.get_context("spawn").Pool(worker_count) as pool: results = pool.map(_generate_one, tasks) @@ -149,17 +174,25 @@ def main(): parser.add_argument("--tracking", required=True) parser.add_argument("--input", required=True, dest="input_selection") parser.add_argument("--frames", type=int, required=True) - parser.add_argument("--scenes", default=None, help="comma-separated scenes (default: all)") + parser.add_argument( + "--scenes", default=None, help="comma-separated scenes (default: all)" + ) parser.add_argument("--rebuild", action="store_true") parser.add_argument("--workers", type=int, default=0, help="0 = all available CPUs") args = parser.parse_args() selected = ( [s.strip() for s in args.scenes.split(",") if s.strip()] - if args.scenes else all_scenes() + if args.scenes + else all_scenes() ) _succeeded, failed, _missing = launch( - args.depth, args.input_selection, args.tracking, args.frames, selected, - rebuild=args.rebuild, workers=args.workers, + args.depth, + args.input_selection, + args.tracking, + args.frames, + selected, + rebuild=args.rebuild, + workers=args.workers, ) if failed: raise SystemExit(1) diff --git a/harness/C/prompts.py b/harness/C/prompts.py index 046fd3d847fab075c376303d2723ff3d6decf1b9..e0c3c22d97c340908e738d7df9d58eea67d8c5c4 100644 --- a/harness/C/prompts.py +++ b/harness/C/prompts.py @@ -31,7 +31,9 @@ PRE_PROMPT = FRAMES_PRE_PROMPT + " Also provided is a spatial code: " + CODE_DES # No-legend variant: same literal composition, minus the legend claim -- keeps C's # line a strict concatenation of A's sentence and B's (no-legend) description. NO_LEGEND_PRE_PROMPT = ( - FRAMES_PRE_PROMPT + " Also provided is a spatial code: " + NO_LEGEND_CODE_DESCRIPTION + FRAMES_PRE_PROMPT + + " Also provided is a spatial code: " + + NO_LEGEND_CODE_DESCRIPTION ) # Strong correspondence arm (Set-of-Marks overlays): the no-legend line plus ONE added @@ -80,7 +82,9 @@ def frame_linked_code(explicit_code, compact_code, frame_timestamps): return code -def build_prompt(spatial_code, question_type, question, options=None, context_line=None): +def build_prompt( + spatial_code, question_type, question, options=None, context_line=None +): """Return the full trailing text block: context line, the spatial code itself, the question, and the same VSI-Bench post-prompt harness.A uses for the same question_type. Frames themselves are prepended separately by the caller via @@ -94,7 +98,9 @@ def build_prompt(spatial_code, question_type, question, options=None, context_li if not options: raise ValueError(f"question_type {question_type!r} requires options") options_block = "Options:\n" + "\n".join(options) - return "\n".join([pre_prompt, code_text, question, options_block, MCA_POST_PROMPT]) + return "\n".join( + [pre_prompt, code_text, question, options_block, MCA_POST_PROMPT] + ) raise ValueError( f"unknown question_type {question_type!r}; " f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}" diff --git a/harness/C/run.py b/harness/C/run.py index 1bc249f7b9b03241021ef884660bde1044d99159..7258feb38a819c69a63979221b0c06e6074dd3b7 100644 --- a/harness/C/run.py +++ b/harness/C/run.py @@ -42,8 +42,15 @@ from harness.C.prompts import NO_LEGEND_PRE_PROMPT # noqa: E402 def results_dir_for( - model, protocol, spatial_code_format, depth, tracking, input_selection, frame_count, - results_dir=None, overlay=False, + model, + protocol, + spatial_code_format, + depth, + tracking, + input_selection, + frame_count, + results_dir=None, + overlay=False, ): """Return the result root isolated by model + protocol + spatial-code-format + depth + tracking + input + frames. ``protocol`` is "base" (16-token) or @@ -53,12 +60,20 @@ def results_dir_for( return Path(results_dir) root = RESULTS_DIR / "overlay" if overlay else RESULTS_DIR return ( - root / model / protocol / spatial_code_format / depth / tracking - / input_selection / str(frame_count) + root + / model + / protocol + / spatial_code_format + / depth + / tracking + / input_selection + / str(frame_count) ) -def _build_record(row, prompt, answer, metric_name, score, model, model_path, source_info): +def _build_record( + row, prompt, answer, metric_name, score, model, model_path, source_info +): """Assemble one question's full, untruncated result record (nothing summarized).""" return { "model": model, @@ -113,10 +128,20 @@ def _build_record(row, prompt, answer, metric_name, score, model, model_path, so def write_question_result( - row, prompt, answer, metric_name, score, model, model_path, source_info, results_dir=None + row, + prompt, + answer, + metric_name, + score, + model, + model_path, + source_info, + 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, source_info) + record = _build_record( + row, prompt, answer, metric_name, score, model, model_path, source_info + ) root = results_dir_for( model, source_info["protocol"], @@ -126,6 +151,7 @@ def write_question_result( source_info["input_selection"], source_info["frame_count"], results_dir, + overlay=source_info.get("overlay", False), ) scene_dir = root / record["scene"] scene_dir.mkdir(parents=True, exist_ok=True) @@ -202,13 +228,20 @@ def run( "no-legend context line, which is only truthful without the embedded schema" ) protocol = ( - f"{reasoning_budget}" if extended - else f"truncated/{raw_budget}" if raw_budget is not None - else "base" + f"{reasoning_budget}" + if extended + else f"truncated/{raw_budget}" if raw_budget is not None else "base" ) results_dir = results_dir_for( - model, protocol, spatial_code_format, depth, tracking, input_selection, - frame_count, results_dir, overlay=overlay, + model, + protocol, + spatial_code_format, + depth, + tracking, + input_selection, + frame_count, + results_dir, + overlay=overlay, ) rows = load_questions(jsonl_path, scene, scenes, limit) if not rows: @@ -224,15 +257,27 @@ def run( scene_id = row["scene_name"] if scene_id not in source_cache: video_path = inference_config.video_path(scene_id, row.get("dataset")) - frame_images, frame_timestamps, frame_indices = frame_sampling.sample_frames( - video_path, frame_count, input_selection + frame_images, frame_timestamps, frame_indices = ( + frame_sampling.sample_frames( + video_path, frame_count, input_selection + ) ) code, code_path = spatial_codes.load_spatial_code( - scene_id, depth, input_selection, tracking, frame_count, spatial_code_format + scene_id, + depth, + input_selection, + tracking, + frame_count, + spatial_code_format, ) if frame_linked: compact_code, _ = spatial_codes.load_spatial_code( - scene_id, depth, input_selection, tracking, frame_count, "compact" + scene_id, + depth, + input_selection, + tracking, + frame_count, + "compact", ) code = combined_prompts.frame_linked_code( code, compact_code, frame_timestamps @@ -241,10 +286,17 @@ def run( from harness.C import overlay as overlay_module frame_images, _visible = overlay_module.stamp_frames( - frame_images, code, scene_id, depth, input_selection, tracking, + frame_images, + code, + scene_id, + depth, + input_selection, + tracking, frame_count, ) - code = overlay_module.instance_ids(code) + code, code_path = overlay_module.load_or_create_overlay_code( + code, scene_id, depth, input_selection, tracking, frame_count + ) if strip_schema_legend: code = {k: v for k, v in code.items() if k != "spatial code schema"} if flat_distance_table: @@ -265,18 +317,28 @@ def run( else: context_line = None prompt = combined_prompts.build_prompt( - cached["code"], row["question_type"], row["question"], row.get("options"), + cached["code"], + row["question_type"], + row["question"], + row.get("options"), context_line=context_line, ) answer = ( adapter.answer_extended( - cached["frame_images"], prompt, - reasoning_budget=reasoning_budget, force_budget=force_budget, + cached["frame_images"], + prompt, + reasoning_budget=reasoning_budget, + force_budget=force_budget, ) if extended - else adapter.answer(cached["frame_images"], prompt, max_new_tokens=raw_budget) + else adapter.answer( + cached["frame_images"], prompt, max_new_tokens=raw_budget + ) ) - doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]} + 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"] @@ -292,16 +354,31 @@ def run( "video_path": cached["video_path"], "frame_indices": cached["frame_indices"], "frame_timestamps": cached["frame_timestamps"], + "overlay": overlay, } if write_results: path, record = write_question_result( - row, prompt, answer, metric_name, score, model, adapter.model_path, - source_info, results_dir, + row, + prompt, + answer, + metric_name, + score, + model, + adapter.model_path, + source_info, + results_dir, ) else: path = None record = _build_record( - row, prompt, answer, metric_name, score, model, adapter.model_path, source_info + row, + prompt, + answer, + metric_name, + score, + model, + adapter.model_path, + source_info, ) record["result_path"] = str(path) if path else None results.append(record) @@ -316,57 +393,76 @@ def main(): 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( - "--spatial-code-format", default=DEFAULT_SPATIAL_CODE_FORMAT, - choices=SPATIAL_CODE_FORMATS, dest="spatial_code_format", + "--spatial-code-format", + default=DEFAULT_SPATIAL_CODE_FORMAT, + choices=SPATIAL_CODE_FORMATS, + dest="spatial_code_format", ) parser.add_argument( - "--input-selection", default=DEFAULT_INPUT_SELECTION, - choices=INPUT_SELECTIONS, dest="input_selection", + "--input-selection", + default=DEFAULT_INPUT_SELECTION, + choices=INPUT_SELECTIONS, + dest="input_selection", ) parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO) parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS) parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES) - parser.add_argument("--limit", type=int, default=None, help="cap the number of questions") + 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, + "--results-dir", + default=None, help="override the default results/C////" "/// root", ) parser.add_argument( - "--no-write", action="store_true", + "--no-write", + action="store_true", help="skip writing per-question JSON files; print/score only", ) parser.add_argument( - "--base-protocol", action="store_true", + "--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( - "--overlay-ids", action="store_true", dest="overlay", + "--overlay-ids", + action="store_true", + dest="overlay", help="strong correspondence arm: stamp instance ids onto the frames at each " "instance's projected position and add matching ids to the code (defaults to " "/root/results/C/overlay; pair with --no-schema-legend)", ) parser.add_argument( - "--frame-linked-code", action="store_true", dest="frame_linked", + "--frame-linked-code", + action="store_true", + dest="frame_linked", help="correspondence arm: add per-instance 'first visible in: frame N' pointers " "(pair with an explicit --results-dir)", ) parser.add_argument( - "--no-schema-legend", action="store_true", dest="strip_schema_legend", + "--no-schema-legend", + action="store_true", + dest="strip_schema_legend", help="drop the embedded schema legend (the amended main-run design)", ) parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) parser.add_argument( - "--truncated-budget", type=int, default=None, + "--truncated-budget", + type=int, + default=None, help="raw-budget arm: base-protocol mechanics (single generation, no forced " "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive " "with --base-protocol)", ) parser.add_argument( - "--flat-distance-table", action="store_true", dest="flat_distance_table", + "--flat-distance-table", + action="store_true", + dest="flat_distance_table", help="flat-table arm: flatten the distance table's two-level nesting into " "single-level ' to ' keys, identical information (pair with " "an explicit --results-dir)", diff --git a/harness/C/sweep.py b/harness/C/sweep.py index 397a9ee82790451abcc9b341185ed5251bd1c02f..ede36cd119c49b66738aa9cb2d892ba73c5a6c4b 100644 --- a/harness/C/sweep.py +++ b/harness/C/sweep.py @@ -35,7 +35,9 @@ from harness.B import ( # noqa: E402 from harness.C import launch as harness_launch # noqa: E402 -def build_plan(models, spatial_code_formats, input_selections, frame_counts, depths, trackings): +def build_plan( + models, spatial_code_formats, input_selections, frame_counts, depths, trackings +): """Return every (model, spatial_code_format, depth, tracking, input_selection, frame_count) 6-tuple in the sweep, in a stable, cheapest-first-ish order (frame count sorted first).""" @@ -51,30 +53,57 @@ 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, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, strip_schema_legend=False, - frame_linked=False, overlay=False, raw_budget=None, flat_distance_table=False, + models, + spatial_code_formats, + input_selections, + frame_counts, + selected_scenes, + depths=(DEFAULT_DEPTH,), + trackings=(DEFAULT_TRACKING,), + results_dir=None, + rebuild=False, + extended=True, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + strip_schema_legend=False, + frame_linked=False, + overlay=False, + raw_budget=None, + flat_distance_table=False, ): """Run every sweep combination across all visible GPUs.""" - plan = build_plan(models, spatial_code_formats, input_selections, frame_counts, depths, trackings) + plan = build_plan( + models, spatial_code_formats, input_selections, frame_counts, depths, trackings + ) protocol = ( - f"{reasoning_budget}" if extended - else f"truncated/{raw_budget}" if raw_budget is not None - else "base" + f"{reasoning_budget}" + if extended + else f"truncated/{raw_budget}" if raw_budget is not None else "base" ) - for index, (model, spatial_code_format, depth, tracking, input_selection, frame_count) in enumerate( - plan, start=1 - ): + for index, ( + model, + spatial_code_format, + depth, + tracking, + input_selection, + frame_count, + ) in enumerate(plan, start=1): print( 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, reasoning_budget=reasoning_budget, + model, + spatial_code_format, + input_selection, + frame_count, + selected_scenes, + depth=depth, + tracking=tracking, + results_dir=results_dir, + rebuild=rebuild, + extended=extended, + reasoning_budget=reasoning_budget, strip_schema_legend=strip_schema_legend, frame_linked=frame_linked, overlay=overlay, @@ -87,66 +116,87 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("scene", nargs="?") parser.add_argument( - "--scenes", help="comma-separated scenes (cannot be combined with positional scene)" + "--scenes", + help="comma-separated scenes (cannot be combined with positional scene)", ) parser.add_argument( - "--models", required=True, + "--models", + required=True, help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}", ) parser.add_argument( - "--spatial-code-formats", required=True, dest="spatial_code_formats", + "--spatial-code-formats", + required=True, + dest="spatial_code_formats", help=f"comma-separated formats (or 'all'); one of {SPATIAL_CODE_FORMATS}", ) parser.add_argument( - "--input-selections", required=True, dest="input_selections", + "--input-selections", + required=True, + dest="input_selections", help=f"comma-separated selections (or 'all'); one of {INPUT_SELECTIONS}", ) parser.add_argument( "--frames", required=True, help="comma-separated frame counts, e.g. 16,32,64" ) parser.add_argument( - "--depths", default=DEFAULT_DEPTH, + "--depths", + default=DEFAULT_DEPTH, help=f"comma-separated depths (or 'all'); one of {DEPTH_VARIANTS}", ) parser.add_argument( - "--trackings", default=DEFAULT_TRACKING, + "--trackings", + default=DEFAULT_TRACKING, help=f"comma-separated tracking modes (or 'all'); one of {TRACKING_MODES}", ) parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") parser.add_argument( - "--base-protocol", action="store_true", + "--base-protocol", + action="store_true", help="run the whole sweep under 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, + "--reasoning-budget", + type=int, + default=EXTENDED_MAX_NEW_TOKENS, dest="reasoning_budget", help="extended-protocol first-pass budget (the calibrated value from " "preregistration.md, e.g. 512)", ) parser.add_argument( - "--overlay-ids", action="store_true", dest="overlay", + "--overlay-ids", + action="store_true", + dest="overlay", help="strong correspondence arm: stamp instance ids onto the frames at each " "instance's projected position and add matching ids to the code (defaults to " "/root/results/C/overlay; pair with --no-schema-legend)", ) parser.add_argument( - "--frame-linked-code", action="store_true", dest="frame_linked", + "--frame-linked-code", + action="store_true", + dest="frame_linked", help="correspondence arm: add per-instance 'first visible in: frame N' pointers " "(pair with an explicit --results-dir)", ) parser.add_argument( - "--no-schema-legend", action="store_true", dest="strip_schema_legend", + "--no-schema-legend", + action="store_true", + dest="strip_schema_legend", help="drop the embedded schema legend (the amended main-run design)", ) parser.add_argument( - "--truncated-budget", type=int, default=None, + "--truncated-budget", + type=int, + default=None, help="raw-budget arm: base-protocol mechanics (single generation, no forced " "rescue) at this token cap (mutually exclusive with --base-protocol)", ) parser.add_argument( - "--flat-distance-table", action="store_true", dest="flat_distance_table", + "--flat-distance-table", + action="store_true", + dest="flat_distance_table", help="flat-table arm: flatten the distance table's two-level nesting into " "single-level ' to ' keys, identical information", ) @@ -157,7 +207,9 @@ def main(): parser.error("--base-protocol and --truncated-budget are mutually exclusive") try: - models = _parse_csv_choice(args.models, vlm_models.available_models(), "--models") + models = _parse_csv_choice( + args.models, vlm_models.available_models(), "--models" + ) spatial_code_formats = _parse_csv_choice( args.spatial_code_formats, SPATIAL_CODE_FORMATS, "--spatial-code-formats" ) @@ -181,9 +233,15 @@ def main(): selected = [args.scene] if args.scene else scenes() sweep( - models, spatial_code_formats, input_selections, frame_counts, selected, - depths=depths, trackings=trackings, - results_dir=args.results_dir, rebuild=args.rebuild, + 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 and args.truncated_budget is None, reasoning_budget=args.reasoning_budget, strip_schema_legend=args.strip_schema_legend, diff --git a/harness/D/__init__.py b/harness/D/__init__.py index 8850c7eed8894b811715961cc0fb177c2c785c81..6043adb3af8a64d22fb7467c176d474fce2d58d6 100644 --- a/harness/D/__init__.py +++ b/harness/D/__init__.py @@ -25,13 +25,18 @@ from __future__ import annotations import os from pathlib import Path -from harness.A import DO_SAMPLE, JSONL, MAX_NEW_TOKENS, MODEL_PATHS, TEMPERATURE, WORKSPACE_ROOT +from harness.A import ( + DO_SAMPLE, + JSONL, + MAX_NEW_TOKENS, + MODEL_PATHS, + TEMPERATURE, + WORKSPACE_ROOT, +) from harness.B import SPATIAL_CODE_FORMATS DEFAULT_SPATIAL_CODE_FORMAT = "explicit" # One JSON per question, matching harness.B's layout minus the axes ground truth doesn't # have: results/D//code////.json -RESULTS_DIR = Path( - os.environ.get("VSI_HARNESS_D_RESULTS_DIR", "/root/results/D") -) +RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_D_RESULTS_DIR", "/root/results/D")) diff --git a/harness/D/__pycache__/__init__.cpython-311.pyc b/harness/D/__pycache__/__init__.cpython-311.pyc index a54b8f1304315e95876f3b233d8e911c38c2f320..4e4cd0a8b24edcb1145f88b3d929ab7a2a62862a 100644 Binary files a/harness/D/__pycache__/__init__.cpython-311.pyc and b/harness/D/__pycache__/__init__.cpython-311.pyc differ diff --git a/harness/D/__pycache__/launch.cpython-311.pyc b/harness/D/__pycache__/launch.cpython-311.pyc index d8a4d81e97d97ad60939492fbeb538b7bcd4a006..4828a70558b19fbe017a0e959d0dc19de463e7eb 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__/prompts.cpython-311.pyc b/harness/D/__pycache__/prompts.cpython-311.pyc index 4b21eedad2b077a43c3f6a05b6a8dea1ac8dc41a..20418871f70b07cfb472f52d9ec9afc2a37cd57f 100644 Binary files a/harness/D/__pycache__/prompts.cpython-311.pyc and b/harness/D/__pycache__/prompts.cpython-311.pyc differ diff --git a/harness/D/__pycache__/run.cpython-311.pyc b/harness/D/__pycache__/run.cpython-311.pyc index 58e0f07bb911d0ce20253c20e96494eb4103c106..85f11d7fe099290e9372cac7b9696d777ecad779 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 a84b9f7014cd8de2f83a9fe892897dca62e64d80..f7e1d7b66f1e0458c901b3299d117b259a4a6859 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/__pycache__/symbolic_eval.cpython-311.pyc b/harness/D/__pycache__/symbolic_eval.cpython-311.pyc index f63af1d598493603aaf55b4d813f32254eb7b818..1b6cb3df9348d3053cdb5523861557836c1f40c2 100644 Binary files a/harness/D/__pycache__/symbolic_eval.cpython-311.pyc and b/harness/D/__pycache__/symbolic_eval.cpython-311.pyc differ diff --git a/harness/D/launch.py b/harness/D/launch.py index c9dfba968fdb68c8cf17d42b1ed307bf9bc1e9e7..11634691418b515fe3c91cbbeeb6edd3ae5ade45 100644 --- a/harness/D/launch.py +++ b/harness/D/launch.py @@ -26,7 +26,11 @@ if str(WORKSPACE_ROOT) not in sys.path: from encoder.ground_truth import scenes as ground_truth_scenes # noqa: E402 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.B import DEFAULT_INPUT_SELECTION, FRAMES_PER_VIDEO, INPUT_SELECTIONS # noqa: E402 +from harness.B import ( + DEFAULT_INPUT_SELECTION, + FRAMES_PER_VIDEO, + INPUT_SELECTIONS, +) # noqa: E402 from harness.D import DEFAULT_SPATIAL_CODE_FORMAT, SPATIAL_CODE_FORMATS # noqa: E402 from inference.launch import available_cpu_count, visible_gpus # noqa: E402 @@ -39,9 +43,24 @@ def _load_run_module(): return module -def _worker(tasks, results, model, spatial_code_format, results_dir, gpu, cpu_threads, - extended, reasoning_budget, force_budget, strip_schema_legend, - frames, frame_selection, frame_count, raw_budget, flat_distance_table): +def _worker( + tasks, + results, + model, + spatial_code_format, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, + strip_schema_legend, + frames, + frame_selection, + frame_count, + raw_budget, + flat_distance_table, +): if gpu is not None: os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"): @@ -89,11 +108,20 @@ def _worker(tasks, results, model, spatial_code_format, results_dir, gpu, cpu_th def launch( - model, spatial_code_format, selected, results_dir=None, rebuild=False, - extended=True, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, + model, + spatial_code_format, + selected, + results_dir=None, + rebuild=False, + extended=True, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, strip_schema_legend=False, - frames=False, frame_selection=DEFAULT_INPUT_SELECTION, frame_count=FRAMES_PER_VIDEO, - raw_budget=None, flat_distance_table=False, + frames=False, + frame_selection=DEFAULT_INPUT_SELECTION, + frame_count=FRAMES_PER_VIDEO, + raw_budget=None, + flat_distance_table=False, ): """Answer every question for ``selected`` scenes, sharded across every visible GPU. @@ -103,26 +131,38 @@ def launch( if extended and raw_budget is not None: raise ValueError("extended and raw_budget are mutually exclusive") protocol = ( - f"{reasoning_budget}" if extended - else f"truncated/{raw_budget}" if raw_budget is not None - else "base" + f"{reasoning_budget}" + if extended + else f"truncated/{raw_budget}" if raw_budget is not None else "base" ) condition = f"{model}/{protocol}/{spatial_code_format}" if frames: condition += f"/frames/{frame_selection}/{frame_count}" run = _load_run_module() root = run.results_dir_for( - model, protocol, spatial_code_format, results_dir, - frames=frames, frame_selection=frame_selection, frame_count=frame_count, + model, + protocol, + spatial_code_format, + results_dir, + frames=frames, + frame_selection=frame_selection, + frame_count=frame_count, ) pending = [] completed = 0 for scene in selected: rows = run.load_questions(scene=scene) + if not rows: + raise ValueError( + f"no questions found for scene {scene!r}; check the manifest/scene selection" + ) answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows) if answered and not rebuild: completed += 1 - print(f"[{condition} {completed}/{len(selected)}] {scene}: skipped", flush=True) + print( + f"[{condition} {completed}/{len(selected)}] {scene}: skipped", + flush=True, + ) else: pending.append(scene) if not pending: @@ -150,9 +190,22 @@ def launch( context.Process( target=_worker, args=( - tasks, results, model, spatial_code_format, results_dir, gpu, cpu_threads, - extended, reasoning_budget, force_budget, strip_schema_legend, - frames, frame_selection, frame_count, raw_budget, flat_distance_table, + tasks, + results, + model, + spatial_code_format, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, + strip_schema_legend, + frames, + frame_selection, + frame_count, + raw_budget, + flat_distance_table, ), ) for gpu in assignments @@ -194,47 +247,65 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("scene", nargs="?") parser.add_argument( - "--scenes", help="comma-separated scenes (cannot be combined with positional scene)" + "--scenes", + help="comma-separated scenes (cannot be combined with positional scene)", ) parser.add_argument("--model", required=True, choices=vlm_models.available_models()) parser.add_argument( - "--spatial-code-format", default=DEFAULT_SPATIAL_CODE_FORMAT, - choices=SPATIAL_CODE_FORMATS, dest="spatial_code_format", + "--spatial-code-format", + default=DEFAULT_SPATIAL_CODE_FORMAT, + choices=SPATIAL_CODE_FORMATS, + dest="spatial_code_format", ) parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") parser.add_argument( - "--base-protocol", action="store_true", + "--base-protocol", + action="store_true", help="run harness.A's exact fixed 16-token protocol instead of the extended default", ) parser.add_argument( - "--no-schema-legend", action="store_true", dest="strip_schema_legend", + "--no-schema-legend", + action="store_true", + dest="strip_schema_legend", help="drop the embedded schema legend (the amended main-run design)", ) parser.add_argument( - "--with-frames", action="store_true", dest="frames", + "--with-frames", + action="store_true", + dest="frames", help="frames+ground-truth-code arm: also sample and show the scene's raw video " "frames alongside the ground-truth code (default sampling: uniform, 32 frames -- " "the frozen Step-1 config)", ) parser.add_argument( - "--frame-selection", default=DEFAULT_INPUT_SELECTION, choices=INPUT_SELECTIONS, - dest="frame_selection", help="only used with --with-frames", + "--frame-selection", + default=DEFAULT_INPUT_SELECTION, + choices=INPUT_SELECTIONS, + dest="frame_selection", + help="only used with --with-frames", ) parser.add_argument( - "--frames-per-video", type=int, default=FRAMES_PER_VIDEO, dest="frame_count", + "--frames-per-video", + type=int, + default=FRAMES_PER_VIDEO, + dest="frame_count", help="only used with --with-frames", ) parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) parser.add_argument( - "--truncated-budget", type=int, default=None, + "--truncated-budget", + type=int, + default=None, help="raw-budget arm: base-protocol mechanics (single generation, no forced " "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive " "with --base-protocol)", ) parser.add_argument( - "--flat-distance-table", action="store_true", dest="flat_distance_table", + "--flat-distance-table", + action="store_true", + dest="flat_distance_table", help="flat-table arm: flatten the distance table's two-level nesting into " "single-level ' to ' keys, identical information (pair with " "an explicit --results-dir)", @@ -260,11 +331,17 @@ def main(): if args.base_protocol and args.truncated_budget is not None: parser.error("--base-protocol and --truncated-budget are mutually exclusive") launch( - args.model, args.spatial_code_format, selected, - results_dir=args.results_dir, rebuild=args.rebuild, + args.model, + args.spatial_code_format, + selected, + results_dir=args.results_dir, + rebuild=args.rebuild, extended=not args.base_protocol and args.truncated_budget is None, - frames=args.frames, frame_selection=args.frame_selection, frame_count=args.frame_count, - reasoning_budget=args.reasoning_budget, force_budget=args.force_budget, + frames=args.frames, + frame_selection=args.frame_selection, + frame_count=args.frame_count, + reasoning_budget=args.reasoning_budget, + force_budget=args.force_budget, strip_schema_legend=args.strip_schema_legend, raw_budget=args.truncated_budget, flat_distance_table=args.flat_distance_table, diff --git a/harness/D/prompts.py b/harness/D/prompts.py index ab495cd7f93c5f1a475bb632482ece073a732bd5..cd5f4e88f1f1b1a61000b9c1b8a80ba5ec6ac6ab 100644 --- a/harness/D/prompts.py +++ b/harness/D/prompts.py @@ -12,11 +12,18 @@ from __future__ import annotations import json -from harness.A.prompts import MCA_POST_PROMPT, MCA_QUESTION_TYPES, NA_POST_PROMPT, NA_QUESTION_TYPES +from harness.A.prompts import ( + MCA_POST_PROMPT, + MCA_QUESTION_TYPES, + NA_POST_PROMPT, + NA_QUESTION_TYPES, +) from harness.B.prompts import NO_LEGEND_PRE_PROMPT, PRE_PROMPT -def build_prompt(spatial_code, question_type, question, options=None, context_line=None): +def build_prompt( + spatial_code, question_type, question, options=None, context_line=None +): """Return the full text prompt: context line, the spatial code itself, the question, and the same VSI-Bench post-prompt harness.A uses for the same question_type. ``context_line`` overrides the standard PRE_PROMPT (the no-legend main-run design @@ -29,7 +36,9 @@ def build_prompt(spatial_code, question_type, question, options=None, context_li if not options: raise ValueError(f"question_type {question_type!r} requires options") options_block = "Options:\n" + "\n".join(options) - return "\n".join([pre_prompt, code_text, question, options_block, MCA_POST_PROMPT]) + return "\n".join( + [pre_prompt, code_text, question, options_block, MCA_POST_PROMPT] + ) raise ValueError( f"unknown question_type {question_type!r}; " f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}" diff --git a/harness/D/run.py b/harness/D/run.py index 9bf4cadc7629d208155de73441513e222246add6..4fa04979c7bca076d03e6714631e73656f81b3f1 100644 --- a/harness/D/run.py +++ b/harness/D/run.py @@ -25,18 +25,31 @@ from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402 from harness.A import frames as frame_sampling # 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.B import DEFAULT_INPUT_SELECTION, FRAMES_PER_VIDEO, INPUT_SELECTIONS # noqa: E402 +from harness.B import ( + DEFAULT_INPUT_SELECTION, + FRAMES_PER_VIDEO, + INPUT_SELECTIONS, +) # noqa: E402 from harness.B.prompts import flat_distance_table as _flat_distance_table # noqa: E402 from harness.C import prompts as combined_prompts # noqa: E402 -from harness.D import DEFAULT_SPATIAL_CODE_FORMAT, RESULTS_DIR, SPATIAL_CODE_FORMATS # noqa: E402 +from harness.D import ( + DEFAULT_SPATIAL_CODE_FORMAT, + RESULTS_DIR, + SPATIAL_CODE_FORMATS, +) # noqa: E402 from harness.D import prompts as code_prompts # noqa: E402 from harness.D.prompts import NO_LEGEND_PRE_PROMPT # noqa: E402 from harness.D import spatial_codes # noqa: E402 def results_dir_for( - model, protocol, spatial_code_format, results_dir=None, - frames=False, frame_selection=DEFAULT_INPUT_SELECTION, frame_count=FRAMES_PER_VIDEO, + model, + protocol, + spatial_code_format, + results_dir=None, + frames=False, + frame_selection=DEFAULT_INPUT_SELECTION, + frame_count=FRAMES_PER_VIDEO, ): """Return the result root isolated by model + protocol + spatial-code-format. ``protocol`` is "base" (16-token) or "" (e.g. "512") -- a real path segment, so records from different protocols OR @@ -49,13 +62,21 @@ def results_dir_for( records must never share a path with the text-only condition's.""" if results_dir is not None: return Path(results_dir) - root = RESULTS_DIR / model / ("code + frames" if frames else "code") / protocol / spatial_code_format + root = ( + RESULTS_DIR + / model + / ("code + frames" if frames else "code") + / protocol + / spatial_code_format + ) if frames: root = root / frame_selection / str(frame_count) return root -def _build_record(row, prompt, answer, metric_name, score, model, model_path, code_info): +def _build_record( + row, prompt, answer, metric_name, score, model, model_path, code_info +): """Assemble one question's full, untruncated result record (nothing summarized). ``code_info`` carries frame provenance (``video_path``, ``frame_indices``, @@ -64,7 +85,9 @@ def _build_record(row, prompt, answer, metric_name, score, model, model_path, co fields (``reasoning_text`` etc.) are present-but-null rather than absent.""" condition = f"{code_info['protocol']}:{code_info['spatial_code_format']}" if code_info.get("frames"): - condition += f":frames:{code_info['frame_selection']}:{code_info['frame_count']}" + condition += ( + f":frames:{code_info['frame_selection']}:{code_info['frame_count']}" + ) return { "model": model, "model_path": str(model_path), @@ -113,12 +136,25 @@ def _build_record(row, prompt, answer, metric_name, score, model, model_path, co def write_question_result( - row, prompt, answer, metric_name, score, model, model_path, code_info, results_dir=None + row, + prompt, + answer, + metric_name, + score, + model, + model_path, + code_info, + 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, code_info) + 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"], results_dir, + model, + code_info["protocol"], + code_info["spatial_code_format"], + results_dir, frames=code_info.get("frames", False), frame_selection=code_info.get("frame_selection", DEFAULT_INPUT_SELECTION), frame_count=code_info.get("frame_count", FRAMES_PER_VIDEO), @@ -215,7 +251,9 @@ def run( for row in rows: scene_id = row["scene_name"] if scene_id not in code_cache: - code, path = spatial_codes.load_spatial_code(scene_id, spatial_code_format) + 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) if strip_schema_legend: @@ -224,47 +262,64 @@ def run( code = _flat_distance_table(code) entry = {"code": code, "path": path} if frames: - video_path = inference_config.video_path(scene_id, row.get("dataset")) - frame_images, frame_timestamps, frame_indices = frame_sampling.sample_frames( - video_path, frame_count, frame_selection + video_path = inference_config.video_path( + scene_id, row.get("dataset") + ) + frame_images, frame_timestamps, frame_indices = ( + frame_sampling.sample_frames( + video_path, frame_count, frame_selection + ) ) entry.update( - video_path=video_path, frame_images=frame_images, - frame_timestamps=frame_timestamps, frame_indices=frame_indices, + video_path=video_path, + frame_images=frame_images, + frame_timestamps=frame_timestamps, + frame_indices=frame_indices, ) code_cache[scene_id] = entry cached = code_cache[scene_id] if frames: context_line = ( - combined_prompts.NO_LEGEND_PRE_PROMPT if strip_schema_legend + combined_prompts.NO_LEGEND_PRE_PROMPT + if strip_schema_legend else combined_prompts.PRE_PROMPT ) else: context_line = NO_LEGEND_PRE_PROMPT if strip_schema_legend else None prompt = code_prompts.build_prompt( - cached["code"], row["question_type"], row["question"], row.get("options"), + cached["code"], + row["question_type"], + row["question"], + row.get("options"), context_line=context_line, ) answer = ( adapter.answer_extended( - cached["frame_images"] if frames else [], prompt, - reasoning_budget=reasoning_budget, force_budget=force_budget, + cached["frame_images"] if frames else [], + prompt, + reasoning_budget=reasoning_budget, + force_budget=force_budget, ) if extended else adapter.answer( - cached["frame_images"] if frames else [], prompt, max_new_tokens=raw_budget + cached["frame_images"] if frames else [], + prompt, + max_new_tokens=raw_budget, ) ) - doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]} + 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) code_info = { "protocol": ( - f"{reasoning_budget}" if extended - else f"truncated/{raw_budget}" if raw_budget is not None - else "base" + f"{reasoning_budget}" + if extended + else f"truncated/{raw_budget}" if raw_budget is not None else "base" ), "spatial_code_format": spatial_code_format, "spatial_code_path": cached["path"], @@ -277,13 +332,27 @@ def run( } if write_results: path, record = write_question_result( - row, prompt, answer, metric_name, score, model, adapter.model_path, - code_info, results_dir, + row, + prompt, + answer, + metric_name, + score, + model, + adapter.model_path, + code_info, + results_dir, ) else: path = None record = _build_record( - row, prompt, answer, metric_name, score, model, adapter.model_path, code_info + row, + prompt, + answer, + metric_name, + score, + model, + adapter.model_path, + code_info, ) record["result_path"] = str(path) if path else None results.append(record) @@ -298,52 +367,73 @@ def main(): 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( - "--spatial-code-format", default=DEFAULT_SPATIAL_CODE_FORMAT, - choices=SPATIAL_CODE_FORMATS, dest="spatial_code_format", + "--spatial-code-format", + default=DEFAULT_SPATIAL_CODE_FORMAT, + choices=SPATIAL_CODE_FORMATS, + dest="spatial_code_format", + ) + parser.add_argument( + "--limit", type=int, default=None, help="cap the number of questions" ) - 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, + "--results-dir", + default=None, help="override the default results/D//// root", ) parser.add_argument( - "--no-write", action="store_true", + "--no-write", + action="store_true", help="skip writing per-question JSON files; print/score only", ) parser.add_argument( - "--base-protocol", action="store_true", + "--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( - "--no-schema-legend", action="store_true", dest="strip_schema_legend", + "--no-schema-legend", + action="store_true", + dest="strip_schema_legend", help="drop the embedded schema legend (the amended main-run design)", ) parser.add_argument( - "--with-frames", action="store_true", dest="frames", + "--with-frames", + action="store_true", + dest="frames", help="frames+ground-truth-code arm: also sample and show the scene's raw video " "frames alongside the ground-truth code (default sampling: uniform, 32 frames -- " "the frozen Step-1 config)", ) parser.add_argument( - "--frame-selection", default=DEFAULT_INPUT_SELECTION, choices=INPUT_SELECTIONS, - dest="frame_selection", help="only used with --with-frames", + "--frame-selection", + default=DEFAULT_INPUT_SELECTION, + choices=INPUT_SELECTIONS, + dest="frame_selection", + help="only used with --with-frames", ) parser.add_argument( - "--frames-per-video", type=int, default=FRAMES_PER_VIDEO, dest="frame_count", + "--frames-per-video", + type=int, + default=FRAMES_PER_VIDEO, + dest="frame_count", help="only used with --with-frames", ) parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) parser.add_argument( - "--truncated-budget", type=int, default=None, + "--truncated-budget", + type=int, + default=None, help="raw-budget arm: base-protocol mechanics (single generation, no forced " "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive " "with --base-protocol)", ) parser.add_argument( - "--flat-distance-table", action="store_true", dest="flat_distance_table", + "--flat-distance-table", + action="store_true", + dest="flat_distance_table", help="flat-table arm: flatten the distance table's two-level nesting into " "single-level ' to ' keys, identical information (pair with " "an explicit --results-dir)", diff --git a/harness/D/sweep.py b/harness/D/sweep.py index 59fe26756c1f966f6a0e924df35c2e11e3a22edf..143e52bd569f8390248d1ed18142c709b2bb1d18 100644 --- a/harness/D/sweep.py +++ b/harness/D/sweep.py @@ -25,7 +25,12 @@ if str(WORKSPACE_ROOT) not in sys.path: from harness.A import models as vlm_models # noqa: E402 from harness.A import EXTENDED_MAX_NEW_TOKENS # noqa: E402 from harness.A.sweep import _parse_csv_choice # noqa: E402 -from harness.B import DEFAULT_INPUT_SELECTION, FRAMES_PER_VIDEO, INPUT_SELECTIONS, SPATIAL_CODE_FORMATS # noqa: E402 +from harness.B import ( + DEFAULT_INPUT_SELECTION, + FRAMES_PER_VIDEO, + INPUT_SELECTIONS, + SPATIAL_CODE_FORMATS, +) # noqa: E402 from harness.D import launch as harness_launch # noqa: E402 @@ -39,30 +44,48 @@ def build_plan(models, spatial_code_formats): def sweep( - models, spatial_code_formats, selected_scenes, results_dir=None, rebuild=False, - extended=True, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, strip_schema_legend=False, - frames=False, frame_selection=DEFAULT_INPUT_SELECTION, frame_count=FRAMES_PER_VIDEO, - raw_budget=None, flat_distance_table=False, + models, + spatial_code_formats, + selected_scenes, + results_dir=None, + rebuild=False, + extended=True, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + strip_schema_legend=False, + frames=False, + frame_selection=DEFAULT_INPUT_SELECTION, + frame_count=FRAMES_PER_VIDEO, + raw_budget=None, + flat_distance_table=False, ): """Run every (model, spatial_code_format) pair across all visible GPUs.""" plan = build_plan(models, spatial_code_formats) protocol = ( - f"{reasoning_budget}" if extended - else f"truncated/{raw_budget}" if raw_budget is not None - else "base" + f"{reasoning_budget}" + if extended + else f"truncated/{raw_budget}" if raw_budget is not None else "base" ) for index, (model, spatial_code_format) in enumerate(plan, start=1): print( f"=== sweep {index}/{len(plan)}: {model}/{protocol}/{spatial_code_format}" - + (f"/frames/{frame_selection}/{frame_count}" if frames else "") + " ===", + + (f"/frames/{frame_selection}/{frame_count}" if frames else "") + + " ===", flush=True, ) harness_launch.launch( - model, spatial_code_format, selected_scenes, - results_dir=results_dir, rebuild=rebuild, extended=extended, - reasoning_budget=reasoning_budget, strip_schema_legend=strip_schema_legend, - frames=frames, frame_selection=frame_selection, frame_count=frame_count, - raw_budget=raw_budget, flat_distance_table=flat_distance_table, + model, + spatial_code_format, + selected_scenes, + results_dir=results_dir, + rebuild=rebuild, + extended=extended, + reasoning_budget=reasoning_budget, + strip_schema_legend=strip_schema_legend, + frames=frames, + frame_selection=frame_selection, + frame_count=frame_count, + raw_budget=raw_budget, + flat_distance_table=flat_distance_table, ) @@ -70,55 +93,76 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("scene", nargs="?") parser.add_argument( - "--scenes", help="comma-separated scenes (cannot be combined with positional scene)" + "--scenes", + help="comma-separated scenes (cannot be combined with positional scene)", ) parser.add_argument( - "--models", required=True, + "--models", + required=True, help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}", ) parser.add_argument( - "--spatial-code-formats", default="all", dest="spatial_code_formats", + "--spatial-code-formats", + default="all", + dest="spatial_code_formats", help=f"comma-separated formats (or 'all'); one of {SPATIAL_CODE_FORMATS}", ) parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") parser.add_argument( - "--base-protocol", action="store_true", + "--base-protocol", + action="store_true", help="run the whole sweep under 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, + "--reasoning-budget", + type=int, + default=EXTENDED_MAX_NEW_TOKENS, dest="reasoning_budget", help="extended-protocol first-pass budget (the calibrated value from " "analysis/preregistration.md, e.g. 512)", ) parser.add_argument( - "--no-schema-legend", action="store_true", dest="strip_schema_legend", + "--no-schema-legend", + action="store_true", + dest="strip_schema_legend", help="drop the embedded schema legend (the amended main-run design)", ) parser.add_argument( - "--with-frames", action="store_true", dest="frames", + "--with-frames", + action="store_true", + dest="frames", help="frames+ground-truth-code arm: also sample and show the scene's raw video " "frames alongside the ground-truth code (default sampling: uniform, 32 frames -- " "the frozen Step-1 config)", ) parser.add_argument( - "--frame-selection", default=DEFAULT_INPUT_SELECTION, choices=INPUT_SELECTIONS, - dest="frame_selection", help="only used with --with-frames", + "--frame-selection", + default=DEFAULT_INPUT_SELECTION, + choices=INPUT_SELECTIONS, + dest="frame_selection", + help="only used with --with-frames", ) parser.add_argument( - "--frames-per-video", type=int, default=FRAMES_PER_VIDEO, dest="frame_count", + "--frames-per-video", + type=int, + default=FRAMES_PER_VIDEO, + dest="frame_count", help="only used with --with-frames", ) parser.add_argument( - "--truncated-budget", type=int, default=None, + "--truncated-budget", + type=int, + default=None, help="raw-budget arm: base-protocol mechanics (single generation, no forced " "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive " "with --base-protocol)", ) parser.add_argument( - "--flat-distance-table", action="store_true", dest="flat_distance_table", + "--flat-distance-table", + action="store_true", + dest="flat_distance_table", help="flat-table arm: flatten the distance table's two-level nesting into " "single-level ' to ' keys, identical information", ) @@ -133,7 +177,9 @@ def main(): parser.error("--base-protocol and --truncated-budget are mutually exclusive") try: - models = _parse_csv_choice(args.models, vlm_models.available_models(), "--models") + models = _parse_csv_choice( + args.models, vlm_models.available_models(), "--models" + ) spatial_code_formats = _parse_csv_choice( args.spatial_code_formats, SPATIAL_CODE_FORMATS, "--spatial-code-formats" ) @@ -149,12 +195,17 @@ def main(): selected = [args.scene] if args.scene else harness_launch.scenes() sweep( - models, spatial_code_formats, selected, - results_dir=args.results_dir, rebuild=args.rebuild, + models, + spatial_code_formats, + selected, + results_dir=args.results_dir, + rebuild=args.rebuild, extended=not args.base_protocol and args.truncated_budget is None, reasoning_budget=args.reasoning_budget, strip_schema_legend=args.strip_schema_legend, - frames=args.frames, frame_selection=args.frame_selection, frame_count=args.frame_count, + frames=args.frames, + frame_selection=args.frame_selection, + frame_count=args.frame_count, raw_budget=args.truncated_budget, flat_distance_table=args.flat_distance_table, ) diff --git a/harness/D/symbolic_eval.py b/harness/D/symbolic_eval.py index 4dc4e09139287d36319320998ef661edc135ee5f..aa206a14618d3631517e25e35e655265c9390cbb 100644 --- a/harness/D/symbolic_eval.py +++ b/harness/D/symbolic_eval.py @@ -55,12 +55,22 @@ 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) - code_cache[scene_id] = {"adapted": adapters.adapt_spatial_code(code), "path": path} + code_cache[scene_id] = { + "adapted": adapters.adapt_spatial_code(code), + "path": path, + } cached = code_cache[scene_id] - answer = solver.answer(row["question_type"], row["question"], row["options"], cached["adapted"]) + answer = solver.answer( + row["question_type"], row["question"], row["options"], cached["adapted"] + ) pred_str = "" if answer is None else str(answer) - doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]} - score_doc = vsi_official_eval.vsibench_process_results(doc, [pred_str])["vsibench_score"] + doc = { + "question_type": row["question_type"], + "ground_truth": row["ground_truth"], + } + score_doc = vsi_official_eval.vsibench_process_results(doc, [pred_str])[ + "vsibench_score" + ] _metric_name, score = _scalar_score(row["question_type"], score_doc) record = { "scene": scene_id, @@ -98,12 +108,15 @@ def main(): parser.add_argument("scene", nargs="?") parser.add_argument("--scenes", help="comma-separated scenes") parser.add_argument( - "--spatial-code-format", default=DEFAULT_SPATIAL_CODE_FORMAT, - choices=SPATIAL_CODE_FORMATS, dest="spatial_code_format", + "--spatial-code-format", + default=DEFAULT_SPATIAL_CODE_FORMAT, + choices=SPATIAL_CODE_FORMATS, + dest="spatial_code_format", ) parser.add_argument("--limit", type=int, default=None) parser.add_argument( - "--results-dir", default=None, + "--results-dir", + default=None, help="override the default results/symbolic/ground truth/ root", ) parser.add_argument("--no-write", action="store_true") @@ -112,7 +125,9 @@ def main(): parser.error("positional scene and --scenes cannot be used together") selected = None if args.scenes: - selected = list(dict.fromkeys(s.strip() for s in args.scenes.split(",") if s.strip())) + selected = list( + dict.fromkeys(s.strip() for s in args.scenes.split(",") if s.strip()) + ) results = run( spatial_code_format=args.spatial_code_format, diff --git a/harness/E/__init__.py b/harness/E/__init__.py index 9391607ded780093b7f1b2ed1498ea47fb84fe10..d33b2e6ae03fe3cbfea57f3cee1df04f2de811e2 100644 --- a/harness/E/__init__.py +++ b/harness/E/__init__.py @@ -28,6 +28,4 @@ from harness.A import ( ) # One JSON per question: results/E////.json -RESULTS_DIR = Path( - os.environ.get("VSI_HARNESS_E_RESULTS_DIR", "/root/results/E") -) +RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_E_RESULTS_DIR", "/root/results/E")) diff --git a/harness/E/__pycache__/__init__.cpython-311.pyc b/harness/E/__pycache__/__init__.cpython-311.pyc index 4a29ee43be390546cfd9be284052c101e160f31a..2a485de5744cf7ca444ffe0c7d10cc0b9642fa8f 100644 Binary files a/harness/E/__pycache__/__init__.cpython-311.pyc and b/harness/E/__pycache__/__init__.cpython-311.pyc differ diff --git a/harness/E/__pycache__/launch.cpython-311.pyc b/harness/E/__pycache__/launch.cpython-311.pyc index e2d2aa8c7eb375621cd3b84297f0b2b361728493..70ab9303f9dbe09e002e2697a27504a46f1ebec2 100644 Binary files a/harness/E/__pycache__/launch.cpython-311.pyc and b/harness/E/__pycache__/launch.cpython-311.pyc differ diff --git a/harness/E/__pycache__/prompts.cpython-311.pyc b/harness/E/__pycache__/prompts.cpython-311.pyc index a708e3d0711e0d06a63447aa9269bf8ad4ed7b68..03d87bbf1fb12a51987701703aa8dc5010d59acf 100644 Binary files a/harness/E/__pycache__/prompts.cpython-311.pyc and b/harness/E/__pycache__/prompts.cpython-311.pyc differ diff --git a/harness/E/__pycache__/run.cpython-311.pyc b/harness/E/__pycache__/run.cpython-311.pyc index fe8c99a961de1c2cdf843d707fb164cdbc744075..9dece9043b6c56476e7a68fd04612e3196e72ad4 100644 Binary files a/harness/E/__pycache__/run.cpython-311.pyc and b/harness/E/__pycache__/run.cpython-311.pyc differ diff --git a/harness/E/__pycache__/sweep.cpython-311.pyc b/harness/E/__pycache__/sweep.cpython-311.pyc index db21b7ed4ec49444f3d0750754174552c5807e35..f3dde78212ad17acf445cef6d71346f9e47762e0 100644 Binary files a/harness/E/__pycache__/sweep.cpython-311.pyc and b/harness/E/__pycache__/sweep.cpython-311.pyc differ diff --git a/harness/E/launch.py b/harness/E/launch.py index a32774bf4329b509562d14e0f0f4fec287fa077e..ed6ce7159f906631fdcccf9549d2530b09e5fa42 100644 --- a/harness/E/launch.py +++ b/harness/E/launch.py @@ -35,8 +35,17 @@ def _load_run_module(): return module -def _worker(tasks, results, model, results_dir, gpu, cpu_threads, extended, - reasoning_budget, force_budget): +def _worker( + tasks, + results, + model, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, +): if gpu is not None: os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"): @@ -77,8 +86,13 @@ def _worker(tasks, results, model, results_dir, gpu, cpu_threads, extended, def launch( - model, selected, results_dir=None, rebuild=False, extended=False, - reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, + model, + selected, + results_dir=None, + rebuild=False, + extended=False, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, ): """Answer every question for ``selected`` scenes, sharded across every visible GPU.""" protocol = f"{reasoning_budget}" if extended else "base" @@ -89,10 +103,17 @@ def launch( completed = 0 for scene in selected: rows = run.load_questions(scene=scene) + if not rows: + raise ValueError( + f"no questions found for scene {scene!r}; check the manifest/scene selection" + ) answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows) if answered and not rebuild: completed += 1 - print(f"[{condition} {completed}/{len(selected)}] {scene}: skipped", flush=True) + print( + f"[{condition} {completed}/{len(selected)}] {scene}: skipped", + flush=True, + ) else: pending.append(scene) if not pending: @@ -120,8 +141,15 @@ def launch( context.Process( target=_worker, args=( - tasks, results, model, results_dir, gpu, cpu_threads, extended, - reasoning_budget, force_budget, + tasks, + results, + model, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, ), ) for gpu in assignments @@ -152,13 +180,15 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("scene", nargs="?") parser.add_argument( - "--scenes", help="comma-separated scenes (cannot be combined with positional scene)" + "--scenes", + help="comma-separated scenes (cannot be combined with positional scene)", ) parser.add_argument("--model", required=True, choices=vlm_models.available_models()) parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") parser.add_argument( - "--extended", action="store_true", + "--extended", + action="store_true", help="use the extended 2048-token protocol instead of the fixed 16-token default", ) parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) @@ -178,8 +208,12 @@ def main(): if args.force_budget < 1: parser.error("--force-budget must be positive") launch( - args.model, selected, results_dir=args.results_dir, rebuild=args.rebuild, - extended=args.extended, reasoning_budget=args.reasoning_budget, + args.model, + selected, + results_dir=args.results_dir, + rebuild=args.rebuild, + extended=args.extended, + reasoning_budget=args.reasoning_budget, force_budget=args.force_budget, ) diff --git a/harness/E/prompts.py b/harness/E/prompts.py index f40487766e20b0daf8f6b120371ce6ed90dbe902..f02d579104f12d1da2db673393d6f9fa583ca80a 100644 --- a/harness/E/prompts.py +++ b/harness/E/prompts.py @@ -9,7 +9,12 @@ plus the same post-prompt every other harness uses for that question type. from __future__ import annotations -from harness.A.prompts import MCA_POST_PROMPT, MCA_QUESTION_TYPES, NA_POST_PROMPT, NA_QUESTION_TYPES +from harness.A.prompts import ( + MCA_POST_PROMPT, + MCA_QUESTION_TYPES, + NA_POST_PROMPT, + NA_QUESTION_TYPES, +) def build_prompt(question_type, question, options=None): diff --git a/harness/E/run.py b/harness/E/run.py index 4ffcec62f0a2a7a78bb3e9795cfc7d77aca11d63..69a834991ad6ec6f8388f60bf5deea53a562889b 100644 --- a/harness/E/run.py +++ b/harness/E/run.py @@ -74,10 +74,20 @@ def _build_record(row, prompt, answer, metric_name, score, model, model_path, pr def write_question_result( - row, prompt, answer, metric_name, score, model, model_path, protocol, results_dir=None + 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) + 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) @@ -128,25 +138,45 @@ def run( ) answer = ( adapter.answer_extended( - [], prompt, reasoning_budget=reasoning_budget, force_budget=force_budget + [], + 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"]} + 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, + 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 + row, + prompt, + answer, + metric_name, + score, + model, + adapter.model_path, + protocol, ) record["result_path"] = str(path) if path else None results.append(record) @@ -160,18 +190,23 @@ 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( + "--limit", type=int, default=None, help="cap the number of questions" + ) parser.add_argument("--device", default="cuda") parser.add_argument( - "--results-dir", default=None, + "--results-dir", + default=None, help="override the default results/E// root", ) parser.add_argument( - "--no-write", action="store_true", + "--no-write", + action="store_true", help="skip writing per-question JSON files; print/score only", ) parser.add_argument( - "--extended", action="store_true", + "--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 " diff --git a/harness/E/sweep.py b/harness/E/sweep.py index 52678344933f39b1df9828e6eef275bb11617dc6..733a9abfeed6a8a9289e4a4f287543e08268a831 100644 --- a/harness/E/sweep.py +++ b/harness/E/sweep.py @@ -23,7 +23,11 @@ from harness.E import launch as harness_launch # noqa: E402 def sweep( - models, selected_scenes, results_dir=None, rebuild=False, extended=False, + models, + selected_scenes, + results_dir=None, + rebuild=False, + extended=False, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, ): """Run every model across all visible GPUs.""" @@ -31,8 +35,12 @@ def sweep( for index, model in enumerate(models, start=1): print(f"=== sweep {index}/{len(models)}: {model}/{protocol} ===", flush=True) harness_launch.launch( - model, selected_scenes, results_dir=results_dir, rebuild=rebuild, - extended=extended, reasoning_budget=reasoning_budget, + model, + selected_scenes, + results_dir=results_dir, + rebuild=rebuild, + extended=extended, + reasoning_budget=reasoning_budget, ) @@ -40,21 +48,26 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("scene", nargs="?") parser.add_argument( - "--scenes", help="comma-separated scenes (cannot be combined with positional scene)" + "--scenes", + help="comma-separated scenes (cannot be combined with positional scene)", ) parser.add_argument( - "--models", required=True, + "--models", + required=True, help=f"comma-separated models (or 'all'); one of {vlm_models.available_models()}", ) parser.add_argument("--results-dir", default=None) parser.add_argument("--rebuild", action="store_true") parser.add_argument( - "--extended", action="store_true", + "--extended", + action="store_true", help="run the whole sweep under the extended protocol instead of the fixed " "16-token default", ) parser.add_argument( - "--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS, + "--reasoning-budget", + type=int, + default=EXTENDED_MAX_NEW_TOKENS, dest="reasoning_budget", help="extended-protocol first-pass budget (the calibrated value from " "analysis/preregistration.md, e.g. 512)", @@ -64,7 +77,9 @@ def main(): parser.error("positional scene and --scenes cannot be used together") try: - models = _parse_csv_choice(args.models, vlm_models.available_models(), "--models") + models = _parse_csv_choice( + args.models, vlm_models.available_models(), "--models" + ) except ValueError as exc: parser.error(str(exc)) @@ -79,8 +94,12 @@ def main(): selected = [args.scene] if args.scene else scenes() sweep( - models, selected, results_dir=args.results_dir, rebuild=args.rebuild, - extended=args.extended, reasoning_budget=args.reasoning_budget, + models, + selected, + results_dir=args.results_dir, + rebuild=args.rebuild, + extended=args.extended, + reasoning_budget=args.reasoning_budget, ) diff --git a/harness/F/__init__.py b/harness/F/__init__.py index ff2ebf36a36f2849f9344e36fca526c277b7e4fd..fa5c8e5ca6795e01f0a730a4262f5219de7997d8 100644 --- a/harness/F/__init__.py +++ b/harness/F/__init__.py @@ -1,4 +1,5 @@ """Harness F: deterministic symbolic reasoning over perceived or ground-truth spatial codes.""" + from pathlib import Path import os diff --git a/harness/F/__pycache__/__init__.cpython-311.pyc b/harness/F/__pycache__/__init__.cpython-311.pyc index 4086774e00d66b51bc5b96cba900f2ffaced036f..c25716d0288f6e0e9135ae132c453f853e469554 100644 Binary files a/harness/F/__pycache__/__init__.cpython-311.pyc and b/harness/F/__pycache__/__init__.cpython-311.pyc differ diff --git a/harness/F/__pycache__/launch.cpython-311.pyc b/harness/F/__pycache__/launch.cpython-311.pyc index ededb7ef483eb5eca0f4c57756f8cfdadf4aec81..5bc57a758c3511dfc2edf7e0f8ecb6d16ee9efce 100644 Binary files a/harness/F/__pycache__/launch.cpython-311.pyc and b/harness/F/__pycache__/launch.cpython-311.pyc differ diff --git a/harness/F/__pycache__/run.cpython-311.pyc b/harness/F/__pycache__/run.cpython-311.pyc index bbdec75751246d0110c60a383223548797104eb2..980356446ae341f1e841e033af0ae3f9471e6bbc 100644 Binary files a/harness/F/__pycache__/run.cpython-311.pyc and b/harness/F/__pycache__/run.cpython-311.pyc differ diff --git a/harness/F/__pycache__/sweep.cpython-311.pyc b/harness/F/__pycache__/sweep.cpython-311.pyc index 50694437e22d53bdcdb5e3a0d57fa20d2f20b910..7c850f0bc1fabfcda9029c338a31f1b858202320 100644 Binary files a/harness/F/__pycache__/sweep.cpython-311.pyc and b/harness/F/__pycache__/sweep.cpython-311.pyc differ diff --git a/harness/F/launch.py b/harness/F/launch.py index ea52076200ed701672bbacdcb948eb6118512a1a..3e15ca0d663ccafc645321a0c4eba3b79791f893 100644 --- a/harness/F/launch.py +++ b/harness/F/launch.py @@ -1,3 +1,6 @@ """Launch one Harness F symbolic-solver condition over selected scenes.""" + from harness.F.run import main -if __name__ == "__main__": main() + +if __name__ == "__main__": + main() diff --git a/harness/F/run.py b/harness/F/run.py index d88fa48190a7a943a92417c9166dfcb66b428644..3530188c900c0c6ec8876dec03c21dcbd0770d45 100644 --- a/harness/F/run.py +++ b/harness/F/run.py @@ -1,4 +1,5 @@ """Run the existing symbolic solver as first-class Harness F.""" + from __future__ import annotations import argparse import glob @@ -14,18 +15,38 @@ from harness.F import DEFAULT_SOURCE, RESULTS_DIR, SOURCES from symbolic import run as symbolic_run -def results_dir_for(source, spatial_code_format, depth="metric", tracking="tracking", - input_selection="uniform", frame_count=32, results_dir=None): +def results_dir_for( + source, + spatial_code_format, + depth="metric", + tracking="tracking", + input_selection="uniform", + frame_count=32, + results_dir=None, +): if results_dir is not None: return Path(results_dir) if source == "ground truth": return RESULTS_DIR / "ground truth" / spatial_code_format - return (RESULTS_DIR / "perceived" / depth / tracking / input_selection / - str(frame_count) / spatial_code_format) + return ( + RESULTS_DIR + / "perceived" + / depth + / tracking + / input_selection + / str(frame_count) + / spatial_code_format + ) -def select_source(source=DEFAULT_SOURCE, spatial_code_format="explicit", depth="metric", - tracking="tracking", input_selection="uniform", frame_count=32): +def select_source( + source=DEFAULT_SOURCE, + spatial_code_format="explicit", + depth="metric", + tracking="tracking", + input_selection="uniform", + frame_count=32, +): if source not in SOURCES: raise ValueError(f"unknown source {source!r}; expected one of {SOURCES}") if source == "ground truth": @@ -36,18 +57,42 @@ def select_source(source=DEFAULT_SOURCE, spatial_code_format="explicit", depth=" def available_scenes(): - return sorted(Path(path).stem for path in glob.glob(str(Path(symbolic_run.SPATIAL_CODES_DIR) / "*.json"))) + return sorted( + Path(path).stem + for path in glob.glob(str(Path(symbolic_run.SPATIAL_CODES_DIR) / "*.json")) + ) -def run(source=DEFAULT_SOURCE, spatial_code_format="explicit", depth="metric", - tracking="tracking", input_selection="uniform", frame_count=32, scene=None, - scenes=None, results_dir=None, write_results=True, quiet=True): +def run( + source=DEFAULT_SOURCE, + spatial_code_format="explicit", + depth="metric", + tracking="tracking", + input_selection="uniform", + frame_count=32, + scene=None, + scenes=None, + results_dir=None, + write_results=True, + quiet=True, +): if scene is not None and scenes is not None: raise ValueError("scene and scenes cannot both be given") - select_source(source, spatial_code_format, depth, tracking, input_selection, frame_count) - selected = [scene] if scene else list(scenes) if scenes is not None else available_scenes() - root = results_dir_for(source, spatial_code_format, depth, tracking, - input_selection, frame_count, results_dir) + select_source( + source, spatial_code_format, depth, tracking, input_selection, frame_count + ) + selected = ( + [scene] if scene else list(scenes) if scenes is not None else available_scenes() + ) + root = results_dir_for( + source, + spatial_code_format, + depth, + tracking, + input_selection, + frame_count, + results_dir, + ) records = [] for scene_id in selected: per_question, aggregate = symbolic_run.score_scene(scene_id) @@ -55,43 +100,87 @@ def run(source=DEFAULT_SOURCE, spatial_code_format="explicit", depth="metric", if not quiet: symbolic_run._print_scene_report(scene_id, per_question, aggregate, code) if write_results: - symbolic_run.write_scene_results(scene_id, per_question, aggregate, code, root) + symbolic_run.write_scene_results( + scene_id, per_question, aggregate, code, root + ) for pq in per_question: - records.append({ - "model": "symbolic", "source": source, "scene": scene_id, - "dataset": pq.get("dataset"), "question_id": pq["question_id"], - "question_type": pq["question_type"], "question": pq["question"], - "answer_expected": pq["ground_truth"], - "answer_given": "" if pq["engine_answer"] is None else str(pq["engine_answer"]), - "score": pq["score"], - "result_path": str(root / scene_id / f"{pq['question_id']}.json") if write_results else None, - }) + records.append( + { + "model": "symbolic", + "source": source, + "scene": scene_id, + "dataset": pq.get("dataset"), + "question_id": pq["question_id"], + "question_type": pq["question_type"], + "question": pq["question"], + "answer_expected": pq["ground_truth"], + "answer_given": ( + "" if pq["engine_answer"] is None else str(pq["engine_answer"]) + ), + "score": pq["score"], + "result_path": ( + str(root / scene_id / f"{pq['question_id']}.json") + if write_results + else None + ), + } + ) return records def main(): p = argparse.ArgumentParser() p.add_argument("scene", nargs="?") - p.add_argument("--scenes", help="comma-separated scenes; default: every available scene") + p.add_argument( + "--scenes", help="comma-separated scenes; default: every available scene" + ) p.add_argument("--source", choices=SOURCES, default=DEFAULT_SOURCE) - p.add_argument("--spatial-code-format", choices=symbolic_run.SPATIAL_CODE_FORMATS, - default="explicit", dest="spatial_code_format") + p.add_argument( + "--spatial-code-format", + choices=symbolic_run.SPATIAL_CODE_FORMATS, + default="explicit", + dest="spatial_code_format", + ) p.add_argument("--depth", choices=symbolic_run.DEPTH_VARIANTS, default="metric") - p.add_argument("--tracking", choices=symbolic_run.TRACKING_MODES, default="tracking") - p.add_argument("--input-selection", choices=symbolic_run.INPUT_SELECTIONS, - default="uniform", dest="input_selection") + p.add_argument( + "--tracking", choices=symbolic_run.TRACKING_MODES, default="tracking" + ) + p.add_argument( + "--input-selection", + choices=symbolic_run.INPUT_SELECTIONS, + default="uniform", + dest="input_selection", + ) p.add_argument("--frames", type=int, default=32) p.add_argument("--results-dir", default=None) p.add_argument("--no-write", action="store_true") p.add_argument("--verbose", action="store_true") a = p.parse_args() - if a.scene and a.scenes: p.error("scene and --scenes cannot be combined") - if a.frames < 1: p.error("--frames must be positive") - selected = None if not a.scenes else list(dict.fromkeys(x.strip() for x in a.scenes.split(",") if x.strip())) - records = run(a.source, a.spatial_code_format, a.depth, a.tracking, - a.input_selection, a.frames, a.scene, selected, a.results_dir, - not a.no_write, not a.verbose) + if a.scene and a.scenes: + p.error("scene and --scenes cannot be combined") + if a.frames < 1: + p.error("--frames must be positive") + selected = ( + None + if not a.scenes + else list(dict.fromkeys(x.strip() for x in a.scenes.split(",") if x.strip())) + ) + records = run( + a.source, + a.spatial_code_format, + a.depth, + a.tracking, + a.input_selection, + a.frames, + a.scene, + selected, + a.results_dir, + not a.no_write, + not a.verbose, + ) mean = sum(r["score"] for r in records) / len(records) if records else None print(f"{len(records)} questions, mean_score={mean}") -if __name__ == "__main__": main() + +if __name__ == "__main__": + main() diff --git a/harness/F/sweep.py b/harness/F/sweep.py index b93a2f7a7682db274c548455dffa89de08593caf..84579799a15ae2b066b2cfb172a704fc65237021 100644 --- a/harness/F/sweep.py +++ b/harness/F/sweep.py @@ -1,4 +1,5 @@ """Sweep Harness F spatial-code configurations.""" + from __future__ import annotations import argparse from itertools import product @@ -7,14 +8,19 @@ from symbolic import run as symbolic_run def _csv(value, valid): - values = list(valid) if value.lower() == "all" else [x.strip() for x in value.split(",") if x.strip()] + values = ( + list(valid) + if value.lower() == "all" + else [x.strip() for x in value.split(",") if x.strip()] + ) unknown = [x for x in values if x not in valid] - if unknown: raise ValueError(f"unknown values {unknown}; expected {valid} or all") + if unknown: + raise ValueError(f"unknown values {unknown}; expected {valid} or all") return list(dict.fromkeys(values)) def main(): - p=argparse.ArgumentParser() + p = argparse.ArgumentParser() p.add_argument("--sources", default="all") p.add_argument("--spatial-code-formats", default="all") p.add_argument("--depths", default="metric") @@ -23,24 +29,45 @@ def main(): p.add_argument("--frames", default="32") p.add_argument("--scenes", default=None) p.add_argument("--results-dir", default=None) - a=p.parse_args() + a = p.parse_args() try: - sources=_csv(a.sources, harness_run.SOURCES) - formats=_csv(a.spatial_code_formats, symbolic_run.SPATIAL_CODE_FORMATS) - depths=_csv(a.depths, symbolic_run.DEPTH_VARIANTS) - trackings=_csv(a.trackings, symbolic_run.TRACKING_MODES) - selections=_csv(a.input_selections, symbolic_run.INPUT_SELECTIONS) - frames=list(dict.fromkeys(int(x.strip()) for x in a.frames.split(",") if x.strip())) - if not frames or any(x < 1 for x in frames): raise ValueError("frames must be positive") - except ValueError as exc: p.error(str(exc)) - scenes=None if not a.scenes else list(dict.fromkeys(x.strip() for x in a.scenes.split(",") if x.strip())) - for source,fmt in product(sources,formats): - configs=[(None,None,None,None)] if source=="ground truth" else product(depths,trackings,selections,frames) + sources = _csv(a.sources, harness_run.SOURCES) + formats = _csv(a.spatial_code_formats, symbolic_run.SPATIAL_CODE_FORMATS) + depths = _csv(a.depths, symbolic_run.DEPTH_VARIANTS) + trackings = _csv(a.trackings, symbolic_run.TRACKING_MODES) + selections = _csv(a.input_selections, symbolic_run.INPUT_SELECTIONS) + frames = list( + dict.fromkeys(int(x.strip()) for x in a.frames.split(",") if x.strip()) + ) + if not frames or any(x < 1 for x in frames): + raise ValueError("frames must be positive") + except ValueError as exc: + p.error(str(exc)) + scenes = ( + None + if not a.scenes + else list(dict.fromkeys(x.strip() for x in a.scenes.split(",") if x.strip())) + ) + for source, fmt in product(sources, formats): + configs = ( + [(None, None, None, None)] + if source == "ground truth" + else product(depths, trackings, selections, frames) + ) for config in configs: - depth,tracking,selection,count=config - records=harness_run.run(source,fmt,depth or "metric",tracking or "tracking", - selection or "uniform",count or 32,scenes=scenes, - results_dir=a.results_dir) - print(source,fmt,depth,tracking,selection,count,len(records)) + depth, tracking, selection, count = config + records = harness_run.run( + source, + fmt, + depth or "metric", + tracking or "tracking", + selection or "uniform", + count or 32, + scenes=scenes, + results_dir=a.results_dir, + ) + print(source, fmt, depth, tracking, selection, count, len(records)) + -if __name__ == "__main__": main() +if __name__ == "__main__": + main() diff --git a/inference/__init__.py b/inference/__init__.py index 5fafb2fe17095954d312adc89dea3eb3b38068f2..7a4b1885d62df42c460a7d1ab3b2ee6ac0afae00 100644 --- a/inference/__init__.py +++ b/inference/__init__.py @@ -5,7 +5,6 @@ from __future__ import annotations import os from pathlib import Path - FRAMES_PER_VIDEO = int(os.environ.get("VSI_FRAMES_PER_VIDEO", "32")) DATA_ROOT = Path(os.environ.get("VSI_DATA_ROOT", "/root/data")) VSI_ROOT = Path(os.environ.get("VSI_ROOT", DATA_ROOT / "VSI-Bench")) @@ -45,7 +44,9 @@ def video_path(scene, dataset=None): return str(matches[0]) -def model_cache_dir(model, input_selection, frame_count=FRAMES_PER_VIDEO, depth="relative"): +def model_cache_dir( + model, input_selection, frame_count=FRAMES_PER_VIDEO, depth="relative" +): """Return one hardcoded model cache leaf for explicit input dimensions.""" if input_selection not in SAM3_FRAME_SELECTIONS: raise ValueError( @@ -68,9 +69,13 @@ def model_cache_dir(model, input_selection, frame_count=FRAMES_PER_VIDEO, depth= def sam3_cache_dir(tracking, input_selection, frame_count=FRAMES_PER_VIDEO): """Return one SAM3 cache leaf for explicit tracking and input dimensions.""" if tracking not in SAM3_TRACKING_MODES: - raise ValueError(f"unknown tracking mode {tracking!r}; expected {SAM3_TRACKING_MODES}") + raise ValueError( + f"unknown tracking mode {tracking!r}; expected {SAM3_TRACKING_MODES}" + ) if input_selection not in SAM3_FRAME_SELECTIONS: - raise ValueError(f"unknown input selection {input_selection!r}; expected {SAM3_FRAME_SELECTIONS}") + raise ValueError( + f"unknown input selection {input_selection!r}; expected {SAM3_FRAME_SELECTIONS}" + ) if frame_count < 1: raise ValueError("frame count must be positive") return str(CACHE_ROOT / "sam3" / tracking / input_selection / str(frame_count)) @@ -79,6 +84,8 @@ def sam3_cache_dir(tracking, input_selection, frame_count=FRAMES_PER_VIDEO): def parse_sam3_frame_mode(mode): """Split ``-`` into validated cache dimensions.""" if mode not in SAM3_FRAME_MODES: - raise ValueError(f"unknown SAM3 frame mode {mode!r}; expected {SAM3_FRAME_MODES}") + raise ValueError( + f"unknown SAM3 frame mode {mode!r}; expected {SAM3_FRAME_MODES}" + ) selection, tracking = mode.split("-", 1) return selection, tracking diff --git a/inference/__pycache__/__init__.cpython-311.pyc b/inference/__pycache__/__init__.cpython-311.pyc index 4f2fd868bd919d8c63f522e097a8f6b4d8ddb1f3..dc2bd9324c17072f1f65ded59db2b6d7c3ff4c6a 100644 Binary files a/inference/__pycache__/__init__.cpython-311.pyc and b/inference/__pycache__/__init__.cpython-311.pyc differ diff --git a/inference/__pycache__/adapters.cpython-311.pyc b/inference/__pycache__/adapters.cpython-311.pyc index 5c377ac90c056f38e936812c6bc1459bc87bbd10..83b5e95d488a3b2acee731aeb1f60a33e441596d 100644 Binary files a/inference/__pycache__/adapters.cpython-311.pyc and b/inference/__pycache__/adapters.cpython-311.pyc differ diff --git a/inference/__pycache__/launch.cpython-311.pyc b/inference/__pycache__/launch.cpython-311.pyc index dc90071a427594c898a6b19503f2c3674a05e470..be1d5e800be46fb326206d4e7a3edc87ecc48225 100644 Binary files a/inference/__pycache__/launch.cpython-311.pyc and b/inference/__pycache__/launch.cpython-311.pyc differ diff --git a/inference/__pycache__/prompts.cpython-311.pyc b/inference/__pycache__/prompts.cpython-311.pyc index 0bd95857a8517c3e4341441814e385bc7688c3d8..eff0d16f75b72205597090f27cba795ae33765fc 100644 Binary files a/inference/__pycache__/prompts.cpython-311.pyc and b/inference/__pycache__/prompts.cpython-311.pyc differ diff --git a/inference/__pycache__/run.cpython-311.pyc b/inference/__pycache__/run.cpython-311.pyc index 07183bd0612b165807fbdacf87330793ab19dd66..e227ef06bfc98dfd1dc9a0b95b0c53af6ed20c17 100644 Binary files a/inference/__pycache__/run.cpython-311.pyc and b/inference/__pycache__/run.cpython-311.pyc differ diff --git a/inference/adapters.py b/inference/adapters.py index 87b9f74e3a15171e9560a5650ef5284447b45315..dada2ffa44212109488bcedde375c99a9564daf1 100644 --- a/inference/adapters.py +++ b/inference/adapters.py @@ -14,7 +14,6 @@ import numpy as np from inference import prompts as inference_prompts - DATA_ROOT = Path(os.environ.get("VSI_DATA_ROOT", "/root/data")) MODELS_ROOT = Path(os.environ.get("VSI_MODELS_ROOT", "/root/models")) SELECTED_FRAMES_CACHE = Path( @@ -24,9 +23,7 @@ SELECTED_FRAMES_CACHE = Path( / "selected frames", ) ) -DA3_ROOT = Path( - os.environ.get("VSI_DA3_ROOT", MODELS_ROOT / "depth-anything-3") -) +DA3_ROOT = Path(os.environ.get("VSI_DA3_ROOT", MODELS_ROOT / "depth-anything-3")) SAM3_ROOT = Path(os.environ.get("VSI_SAM3_ROOT", MODELS_ROOT / "sam3")) SEGVGGT_ROOT = Path(os.environ.get("VSI_SEGVGGT_ROOT", MODELS_ROOT / "SegVGGT")) SELECTOR_ALGORITHM = os.environ.get("VSI_SELECTOR_ALGORITHM", "5") @@ -222,7 +219,8 @@ def _ssim(reference, candidate, valid_mask=None): covariance = cv2.GaussianBlur(reference * candidate, (11, 11), 1.5) covariance -= mean_product score = ( - (2 * mean_product + c1) * (2 * covariance + c2) + (2 * mean_product + c1) + * (2 * covariance + c2) / ( (mean_reference_sq + mean_candidate_sq + c1) * (variance_reference + variance_candidate + c2) @@ -248,21 +246,31 @@ def _aligned_or_unaligned_ssim(reference, candidate): detector = cv2.ORB_create( nfeatures=500, edgeThreshold=8, patchSize=15, fastThreshold=10 ) - reference_points, reference_descriptors = detector.detectAndCompute(reference_u8, None) - candidate_points, candidate_descriptors = detector.detectAndCompute(candidate_u8, None) + reference_points, reference_descriptors = detector.detectAndCompute( + reference_u8, None + ) + candidate_points, candidate_descriptors = detector.detectAndCompute( + candidate_u8, None + ) if reference_descriptors is None or candidate_descriptors is None: return _ssim(reference, candidate) matcher = cv2.BFMatcher(cv2.NORM_HAMMING) reliable_matches = [] - for neighbors in matcher.knnMatch(candidate_descriptors, reference_descriptors, k=2): + for neighbors in matcher.knnMatch( + candidate_descriptors, reference_descriptors, k=2 + ): if len(neighbors) == 2 and neighbors[0].distance < 0.75 * neighbors[1].distance: reliable_matches.append(neighbors[0]) if len(reliable_matches) < MINIMUM_ALIGNMENT_MATCHES: return _ssim(reference, candidate) - candidate_xy = np.float32([candidate_points[m.queryIdx].pt for m in reliable_matches]) - reference_xy = np.float32([reference_points[m.trainIdx].pt for m in reliable_matches]) + candidate_xy = np.float32( + [candidate_points[m.queryIdx].pt for m in reliable_matches] + ) + reference_xy = np.float32( + [reference_points[m.trainIdx].pt for m in reliable_matches] + ) transform, inliers = cv2.estimateAffinePartial2D( candidate_xy, reference_xy, method=cv2.RANSAC, ransacReprojThreshold=3.0 ) @@ -273,12 +281,20 @@ def _aligned_or_unaligned_ssim(reference, candidate): height, width = reference.shape aligned = cv2.warpAffine( - candidate, transform, (width, height), flags=cv2.INTER_LINEAR, - borderMode=cv2.BORDER_CONSTANT, borderValue=0, + candidate, + transform, + (width, height), + flags=cv2.INTER_LINEAR, + borderMode=cv2.BORDER_CONSTANT, + borderValue=0, ) valid = cv2.warpAffine( - np.ones(candidate.shape, np.uint8), transform, (width, height), - flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, borderValue=0, + np.ones(candidate.shape, np.uint8), + transform, + (width, height), + flags=cv2.INTER_NEAREST, + borderMode=cv2.BORDER_CONSTANT, + borderValue=0, ) if float(np.mean(valid > 0)) < MINIMUM_VALID_OVERLAP_FRACTION: return _ssim(reference, candidate) @@ -326,8 +342,12 @@ def _orb_covisibility_ratio(reference, candidate): detector = cv2.ORB_create( nfeatures=500, edgeThreshold=8, patchSize=15, fastThreshold=10 ) - reference_points, reference_descriptors = detector.detectAndCompute(reference_u8, None) - candidate_points, candidate_descriptors = detector.detectAndCompute(candidate_u8, None) + reference_points, reference_descriptors = detector.detectAndCompute( + reference_u8, None + ) + candidate_points, candidate_descriptors = detector.detectAndCompute( + candidate_u8, None + ) if ( reference_descriptors is None or candidate_descriptors is None @@ -337,14 +357,20 @@ def _orb_covisibility_ratio(reference, candidate): matcher = cv2.BFMatcher(cv2.NORM_HAMMING) reliable_matches = [] - for neighbors in matcher.knnMatch(candidate_descriptors, reference_descriptors, k=2): + for neighbors in matcher.knnMatch( + candidate_descriptors, reference_descriptors, k=2 + ): if len(neighbors) == 2 and neighbors[0].distance < 0.75 * neighbors[1].distance: reliable_matches.append(neighbors[0]) if len(reliable_matches) < MINIMUM_ALIGNMENT_MATCHES: return None - candidate_xy = np.float32([candidate_points[m.queryIdx].pt for m in reliable_matches]) - reference_xy = np.float32([reference_points[m.trainIdx].pt for m in reliable_matches]) + candidate_xy = np.float32( + [candidate_points[m.queryIdx].pt for m in reliable_matches] + ) + reference_xy = np.float32( + [reference_points[m.trainIdx].pt for m in reliable_matches] + ) _, inliers = cv2.estimateAffinePartial2D( candidate_xy, reference_xy, method=cv2.RANSAC, ransacReprojThreshold=3.0 ) @@ -451,8 +477,7 @@ def _collect_usability_filtered_frames(path): if frame["dark_fraction"] < 0.80 and frame["bright_fraction"] < 0.80 and not ( - frame["sharpness"] < 20.0 - and frame["sharpness"] < 0.25 * median_sharpness + frame["sharpness"] < 20.0 and frame["sharpness"] < 0.25 * median_sharpness ) ] return frames, usable_frames @@ -479,7 +504,10 @@ def _select_indices_algorithm_2(path): height, width = grayscale.shape canonical = cv2.resize( grayscale, - (BLUR_CANONICAL_WIDTH, max(1, round(height * BLUR_CANONICAL_WIDTH / width))), + ( + BLUR_CANONICAL_WIDTH, + max(1, round(height * BLUR_CANONICAL_WIDTH / width)), + ), interpolation=cv2.INTER_AREA, ) variance = float(cv2.Laplacian(canonical, cv2.CV_64F).var()) @@ -524,7 +552,10 @@ def _select_indices_algorithm_3(path): height, width = grayscale.shape thumbnail = cv2.resize( grayscale, - (GLITCH_THUMBNAIL_WIDTH, max(1, round(height * GLITCH_THUMBNAIL_WIDTH / width))), + ( + GLITCH_THUMBNAIL_WIDTH, + max(1, round(height * GLITCH_THUMBNAIL_WIDTH / width)), + ), interpolation=cv2.INTER_AREA, ).astype(np.float32) thumbnail /= 255.0 @@ -564,7 +595,10 @@ def _select_indices_algorithm_3(path): continue # A failed adjacent match only counts as corruption evidence if the frame # had enough of its own texture to match reliably in the first place. - if _orb_keypoint_count(frames[i]["thumbnail"]) < GLITCH_MINIMUM_OWN_KEYPOINTS: + if ( + _orb_keypoint_count(frames[i]["thumbnail"]) + < GLITCH_MINIMUM_OWN_KEYPOINTS + ): continue is_glitch[i] = True @@ -656,11 +690,15 @@ def _sample_video_frames(path, frame_count, frame_selection="uniform"): # Selective mode uses every frame retained by the selector. indices = np.asarray(select_video_frame_indices(path), dtype=int) if len(indices) > frame_count: - indices = indices[np.linspace(0, len(indices) - 1, frame_count, dtype=int)] + indices = indices[ + np.linspace(0, len(indices) - 1, frame_count, dtype=int) + ] elif frame_selection == "uniform": total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) if total < frame_count: - raise ValueError(f"{path} has {total} frames; {frame_count} are required") + raise ValueError( + f"{path} has {total} frames; {frame_count} are required" + ) indices = np.linspace(0, total - 1, frame_count, dtype=int) else: raise ValueError( @@ -689,7 +727,9 @@ class InferenceAdapter(ABC): """Load model state once for repeated scene inference.""" @abstractmethod - def run_scene(self, video_path, output_path, frame_count, frame_selection="uniform"): + def run_scene( + self, video_path, output_path, frame_count, frame_selection="uniform" + ): """Run one video and atomically preserve the model's native output.""" @@ -703,9 +743,7 @@ class SegVGGTAdapter(InferenceAdapter): ) def __init__(self, model_root=None, checkpoint=None): - self.model_root = Path( - model_root or SEGVGGT_ROOT - ) + self.model_root = Path(model_root or SEGVGGT_ROOT) self.checkpoint = Path( checkpoint or os.environ.get( @@ -817,10 +855,7 @@ class DepthAnything3Adapter(InferenceAdapter): depth_variant = "relative" def __init__(self, model_root=None, checkpoint=None): - self.model_root = Path( - model_root - or DA3_ROOT - ) + self.model_root = Path(model_root or DA3_ROOT) self.checkpoint = Path( checkpoint or os.environ.get( @@ -905,9 +940,7 @@ class SAM3Adapter(InferenceAdapter): if tracking not in ("tracking", "no tracking"): raise ValueError("tracking must be 'tracking' or 'no tracking'") self.tracking = tracking - self.model_root = Path( - model_root or SAM3_ROOT - ) + self.model_root = Path(model_root or SAM3_ROOT) self.checkpoint = Path( checkpoint or os.environ.get( @@ -1094,9 +1127,7 @@ class SAM3DepthAnything3Adapter(InferenceAdapter): else: self.sam3.run_frames(frames, output_path["sam3"], prompts) if "depth-anything-3" in output_path: - self.depth_anything_3.run_frames( - frames, output_path["depth-anything-3"] - ) + self.depth_anything_3.run_frames(frames, output_path["depth-anything-3"]) _ADAPTERS = { diff --git a/inference/prompts.py b/inference/prompts.py index 240cf9e69d7541123606190eba28fa81a9b8bbb2..83077087f51cf5c47e1788d8f02d135e4ec25612 100644 --- a/inference/prompts.py +++ b/inference/prompts.py @@ -4,29 +4,101 @@ from __future__ import annotations from pathlib import Path - DATASET_OBJECT_PROMPTS = { "arkitscenes": ( - "bathtub", "bed", "chair", "dishwasher", "fireplace", "refrigerator", - "sofa", "stool", "stove", "table", "toilet", "tv", "washer", + "bathtub", + "bed", + "chair", + "dishwasher", + "fireplace", + "refrigerator", + "sofa", + "stool", + "stove", + "table", + "toilet", + "tv", + "washer", ), "scannet": ( - "backpack", "bed", "bookshelf", "chair", "clock", "closet", - "computer mouse", "counter", "door", "fan", "guitar", "keyboard", - "lamp", "mattress", "microwave", "mirror", "monitor", "nightstand", - "oven", "piano", "pillow", "plant", "printer", "radiator", - "refrigerator", "sofa", "table", "telephone", "towel", "trash bin", - "tv", "washing machine", "window", + "backpack", + "bed", + "bookshelf", + "chair", + "clock", + "closet", + "computer mouse", + "counter", + "door", + "fan", + "guitar", + "keyboard", + "lamp", + "mattress", + "microwave", + "mirror", + "monitor", + "nightstand", + "oven", + "piano", + "pillow", + "plant", + "printer", + "radiator", + "refrigerator", + "sofa", + "table", + "telephone", + "towel", + "trash bin", + "tv", + "washing machine", + "window", ), "scannetpp": ( - "basket", "bed", "blanket", "bookshelf", "bowl", "bucket", - "ceiling light", "chair", "clock", "coat hanger", "computer mouse", - "computer tower", "crate", "cup", "cushion", "cutting board", "door", - "exhaust fan", "headphones", "heater", "kettle", "keyboard", "laptop", - "microwave", "monitor", "pan", "paper bag", "pillow", "plant", - "power strip", "printer", "refrigerator", "shoe rack", "shoes", "sofa", - "suitcase", "table", "table lamp", "telephone", "toilet", "trash can", - "tv", "whiteboard", + "basket", + "bed", + "blanket", + "bookshelf", + "bowl", + "bucket", + "ceiling light", + "chair", + "clock", + "coat hanger", + "computer mouse", + "computer tower", + "crate", + "cup", + "cushion", + "cutting board", + "door", + "exhaust fan", + "headphones", + "heater", + "kettle", + "keyboard", + "laptop", + "microwave", + "monitor", + "pan", + "paper bag", + "pillow", + "plant", + "power strip", + "printer", + "refrigerator", + "shoe rack", + "shoes", + "sofa", + "suitcase", + "table", + "table lamp", + "telephone", + "toilet", + "trash can", + "tv", + "whiteboard", ), } diff --git a/inference/run.py b/inference/run.py index 2be8bbe96e0c62125f35bcaccdc8d7042b0263fd..297629b8fd88adfd43c1cf04f260d64b4b7571a8 100644 --- a/inference/run.py +++ b/inference/run.py @@ -50,9 +50,7 @@ def output_path( frame_count=inference_config.FRAMES_PER_VIDEO, ): """Return one path for single-output models; combined models return a mapping.""" - paths = output_paths( - scene, model, frame_selection, tracking, frame_count - ) + paths = output_paths(scene, model, frame_selection, tracking, frame_count) return next(iter(paths.values())) if len(paths) == 1 else paths @@ -75,9 +73,7 @@ def run_scene( if model == "SAM3" else adapters.get_adapter(model) ) - destinations = output_paths( - scene, model, frame_selection, tracking, frame_count - ) + destinations = output_paths(scene, model, frame_selection, tracking, frame_count) pending = ( destinations if rebuild @@ -94,15 +90,11 @@ def run_scene( frame_count = frame_count or inference_config.FRAMES_PER_VIDEO if owns_adapter: adapter.load_model(device or "cuda") - adapter_output = ( - next(iter(pending.values())) if len(destinations) == 1 else pending - ) + adapter_output = next(iter(pending.values())) if len(destinations) == 1 else pending adapter.run_scene( inference_config.video_path(scene), adapter_output, frame_count, frame_selection ) - return "built", output_path( - scene, model, frame_selection, tracking, frame_count - ) + return "built", output_path(scene, model, frame_selection, tracking, frame_count) def main(): diff --git a/symbolic/__pycache__/adapters.cpython-311.pyc b/symbolic/__pycache__/adapters.cpython-311.pyc index 41dc7961d3c0fe4ff0d1fb093c6d6476d9615aea..6a9ad9da2716c2b2cae11431e6aae08986ff43d9 100644 Binary files a/symbolic/__pycache__/adapters.cpython-311.pyc and b/symbolic/__pycache__/adapters.cpython-311.pyc differ diff --git a/symbolic/__pycache__/launch.cpython-311.pyc b/symbolic/__pycache__/launch.cpython-311.pyc index 43f2a9e197d7b247bac3aeb0ea83c92f982637f4..1e0085e182fc27054de32bf9c22138c8a5e1bdee 100644 Binary files a/symbolic/__pycache__/launch.cpython-311.pyc and b/symbolic/__pycache__/launch.cpython-311.pyc differ diff --git a/symbolic/__pycache__/run.cpython-311.pyc b/symbolic/__pycache__/run.cpython-311.pyc index 373cb77a3208d58831ee76243e64724c968eddb4..607d5aaeb5877aca606348c8320c6fb0b1e9d8cc 100644 Binary files a/symbolic/__pycache__/run.cpython-311.pyc and b/symbolic/__pycache__/run.cpython-311.pyc differ diff --git a/symbolic/__pycache__/solver.cpython-311.pyc b/symbolic/__pycache__/solver.cpython-311.pyc index b7ba01743f1f72e1dd26a8c21b1662c885cb3adf..21fe760690e88ffe821390514edcecd6a8b70087 100644 Binary files a/symbolic/__pycache__/solver.cpython-311.pyc and b/symbolic/__pycache__/solver.cpython-311.pyc differ diff --git a/symbolic/adapters.py b/symbolic/adapters.py index c74cbc7a082032ac611c2836008b4f4adea314ac..3c209351d46b0f3583e93b91823bb7309063ff5e 100644 --- a/symbolic/adapters.py +++ b/symbolic/adapters.py @@ -12,7 +12,6 @@ import math import numpy as np from scipy.optimize import lsq_linear - SPATIAL_CODE_FORMATS = ("compact", "explicit") _BOX_KEY = "3D oriented bounding box" _CENTER_KEY = "3D oriented bounding box center coordinates" @@ -63,10 +62,14 @@ def _oriented_box(instance): raise ValueError(f"{_ORIENTATION_KEY} must contain three finite 3D vectors") lengths = np.linalg.norm(orientation, axis=1) if not np.allclose(lengths, 1.0, atol=0.02): - raise ValueError("3D oriented bounding box orientation vectors must have unit length") + raise ValueError( + "3D oriented bounding box orientation vectors must have unit length" + ) orientation = orientation / lengths[:, None] if not np.allclose(orientation @ orientation.T, np.eye(3), atol=0.02): - raise ValueError("3D oriented bounding box orientation vectors must be perpendicular") + raise ValueError( + "3D oriented bounding box orientation vectors must be perpendicular" + ) return center, dimensions, orientation @@ -100,7 +103,9 @@ def oriented_box_distance(first, second): max_iter=200, ) if not result.success: - raise RuntimeError(f"oriented-box distance optimization failed: {result.message}") + raise RuntimeError( + f"oriented-box distance optimization failed: {result.message}" + ) distance = float(np.linalg.norm(matrix @ result.x + center_a - center_b)) return 0.0 if distance < 1e-10 else distance @@ -122,12 +127,16 @@ def _primary_instance_distance_floor(first_instances, second_instances): center_a, dimensions_a, _ = _oriented_box(first_instances[0]) center_b, dimensions_b, _ = _oriented_box(second_instances[0]) center_distance = float(np.linalg.norm(center_a - center_b)) - return max(0.0, center_distance - (float(dimensions_a.max()) + float(dimensions_b.max())) / 2) + return max( + 0.0, + center_distance - (float(dimensions_a.max()) + float(dimensions_b.max())) / 2, + ) def _corrected_class_distance(first_instances, second_instances): """max(min-across-pairs surface distance, primary-instance sphere floor) -- the - table's printed distance value, identical to encoder.geometric._corrected_class_distance.""" + table's printed distance value, identical to encoder.geometric._corrected_class_distance. + """ return max( _class_distance(first_instances, second_instances), _primary_instance_distance_floor(first_instances, second_instances), @@ -235,7 +244,11 @@ def _adapt_compact(code): "room": {"floor area": _floor_area(polygons)}, "closest classes distance meters from": closest, "appearance order": sorted( - classes, key=lambda class_name: (first_visible.get(class_name, math.inf), class_name) + classes, + key=lambda class_name: ( + first_visible.get(class_name, math.inf), + class_name, + ), ), } diff --git a/symbolic/launch.py b/symbolic/launch.py index 183e2d6cfdb3751c7dca443ee5bc01624bf773df..2c0d467a57a629b3eca90b3f26a59acd8aaf10fd 100644 --- a/symbolic/launch.py +++ b/symbolic/launch.py @@ -84,7 +84,8 @@ def run_all(scene_ids=None, quiet=False): """Runs every scene in scene_ids (or every scene with a spatial code on disk, if None) through symbolic_run.score_scene(). Returns (per_scene_results, combined_aggregate) where per_scene_results is {scene_id: (per_question, aggregate)} and combined_aggregate is the - real official vsi_official_eval.py aggregate across every scene's questions together.""" + real official vsi_official_eval.py aggregate across every scene's questions together. + """ import vsi_official_eval as vse scene_ids = scene_ids if scene_ids is not None else scenes_with_spatial_codes() @@ -469,8 +470,8 @@ def _run_cli(args, requested_scene_ids): print(f"\n{'=' * 100}") print( - f"COMBINED AGGREGATE across {len(scenes_with_real_questions)} " - "scene(s) with real " + f"COMBINED AGGREGATE across {len(scenes_with_real_questions)} " + "scene(s) with real " f"questions ({len(scene_ids) - len(scenes_with_real_questions)} scene(s) had a " f"spatial code but no real test.jsonl questions, skipped)" ) @@ -500,9 +501,7 @@ def _run_cli(args, requested_scene_ids): print("=" * 100) print_mca_breakdown(per_scene_results) error_results["_mca_breakdown"] = { - question_type: mca_answer_breakdown( - per_scene_results, question_type - ) + question_type: mca_answer_breakdown(per_scene_results, question_type) for question_type in _MCA_TYPES_WITH_BREAKDOWN } @@ -539,9 +538,7 @@ def _run_cli(args, requested_scene_ids): def main(): ap = argparse.ArgumentParser() - ap.add_argument( - "--depth", required=True, choices=symbolic_run.DEPTH_VARIANTS - ) + ap.add_argument("--depth", required=True, choices=symbolic_run.DEPTH_VARIANTS) ap.add_argument( "--input", required=True, @@ -555,9 +552,7 @@ def main(): default="explicit", dest="spatial_code_format", ) - ap.add_argument( - "--tracking", required=True, choices=symbolic_run.TRACKING_MODES - ) + ap.add_argument("--tracking", required=True, choices=symbolic_run.TRACKING_MODES) ap.add_argument( "--scenes", default="", @@ -587,6 +582,5 @@ def main(): _run_cli(a, requested_scene_ids) - if __name__ == "__main__": main() diff --git a/symbolic/run.py b/symbolic/run.py index a9be262556762ab450deed52ddc89f0b6dfb6907..04756d6eb175a23f3deb274c6a5832f705f84f6a 100644 --- a/symbolic/run.py +++ b/symbolic/run.py @@ -39,7 +39,6 @@ if _HERE not in sys.path: import adapters # noqa: E402 import solver as sym # noqa: E402 - _ROOT = os.path.dirname(_HERE) _OFFICIAL_EVAL = os.environ.get( "SYMBOLIC_OFFICIAL_EVAL", @@ -88,9 +87,7 @@ _AUTO_WORKSPACE = _find_workspace_root(_HERE) def _default_spatial_codes_root(): workspace = os.environ.get("VSI_WORKSPACE_ROOT", "/workspace") - return os.environ.get( - "VSI_CODES", os.path.join(workspace, "data", "spatial codes") - ) + return os.environ.get("VSI_CODES", os.path.join(workspace, "data", "spatial codes")) def _default_test_jsonl(): @@ -100,9 +97,7 @@ def _default_test_jsonl(): def _default_results_dir(): - if _AUTO_WORKSPACE is not None: - return os.path.join(_AUTO_WORKSPACE, "results", "symbolic") - return "/workspace/results/symbolic" + return "/root/results/symbolic" # ========================================================================================== @@ -143,7 +138,9 @@ def _validate_selection(depth, input_selection, tracking, frame_count): f"unknown input selection {input_selection!r}; expected {INPUT_SELECTIONS}" ) if tracking not in TRACKING_MODES: - raise ValueError(f"unknown tracking mode {tracking!r}; expected {TRACKING_MODES}") + raise ValueError( + f"unknown tracking mode {tracking!r}; expected {TRACKING_MODES}" + ) if frame_count < 1: raise ValueError("frame count must be positive") @@ -151,9 +148,7 @@ def _validate_selection(depth, input_selection, tracking, frame_count): def _selection_subdirectory(depth, input_selection, tracking, frame_count): """Return the shared depth/tracking/input/frame-count hierarchy.""" _validate_selection(depth, input_selection, tracking, frame_count) - return os.path.join( - depth, tracking, input_selection, str(frame_count) - ) + return os.path.join(depth, tracking, input_selection, str(frame_count)) def select_spatial_codes( @@ -243,7 +238,12 @@ def fetch_spatial_code(scene_id): def fetch_spatial_code_for( - scene_id, depth, input_selection, tracking, frame_count, spatial_code_format="explicit" + scene_id, + depth, + input_selection, + tracking, + frame_count, + spatial_code_format="explicit", ): """Load and adapt one EXPLICIT scene/dimension spatial code, independent of the current global SPATIAL_CODES_DIR selection -- unlike fetch_spatial_code(), this never mutates @@ -568,7 +568,8 @@ def write_scene_results(scene_id, per_question, aggregate, code, results_dir=Non score for the scene (Qwen's own pipeline keeps its equivalent rollup in a separate analysis/export.py step over the per-question files rather than a file living alongside them -- this one small extra file is the one deliberate convenience difference, since the - symbolic engine has no separate analysis pass of its own). Returns the list of paths written.""" + symbolic engine has no separate analysis pass of its own). Returns the list of paths written. + """ paths = [ write_question_result(scene_id, pq, code, results_dir) for pq in per_question ] @@ -590,7 +591,9 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("scene_id") parser.add_argument("--depth", required=True, choices=DEPTH_VARIANTS) - parser.add_argument("--input", required=True, choices=INPUT_SELECTIONS, dest="input_selection") + parser.add_argument( + "--input", required=True, choices=INPUT_SELECTIONS, dest="input_selection" + ) parser.add_argument("--tracking", required=True, choices=TRACKING_MODES) parser.add_argument("--frames", type=int, default=32) parser.add_argument( @@ -613,7 +616,9 @@ def main(): code = fetch_spatial_code(args.scene_id) _print_scene_report(args.scene_id, per_question, aggregate, code) paths = write_scene_results(args.scene_id, per_question, aggregate, code) - print(f"\n wrote {len(paths)} file(s) to {results_dir_for_selection()}/{args.scene_id}/") + print( + f"\n wrote {len(paths)} file(s) to {results_dir_for_selection()}/{args.scene_id}/" + ) if __name__ == "__main__": diff --git a/symbolic/solver.py b/symbolic/solver.py index b4580a5ab825dc94d12f2277f7dee942af15b890..b709d836872ec47a1594f357f898203667f4fe1b 100644 --- a/symbolic/solver.py +++ b/symbolic/solver.py @@ -47,7 +47,6 @@ import json import math import re - # ========================================================================================== # UNIT PARSING -- every unit-string field in the final spatial code shape ("3.59 meters", # "48.4 square meters") back to a plain float. @@ -186,7 +185,12 @@ def _primary_instance_distance_estimate(code, cls_a, cls_b): from 0.742m to 0.563m (mean MRA score 56.4 -> 62.4).""" obj_a = code.get("objects", {}).get(cls_a) obj_b = code.get("objects", {}).get(cls_b) - if not obj_a or not obj_a.get("instances") or not obj_b or not obj_b.get("instances"): + if ( + not obj_a + or not obj_a.get("instances") + or not obj_b + or not obj_b.get("instances") + ): return None inst_a, inst_b = obj_a["instances"][0], obj_b["instances"][0] pos_a, pos_b = inst_a.get("position"), inst_b.get("position") @@ -194,15 +198,19 @@ def _primary_instance_distance_estimate(code, cls_a, cls_b): if pos_a is None or pos_b is None or dim_a is None or dim_b is None: return None center_distance = ( - (_parse_meters(pos_a["x coordinate"]) - _parse_meters(pos_b["x coordinate"])) ** 2 - + (_parse_meters(pos_a["y coordinate"]) - _parse_meters(pos_b["y coordinate"])) ** 2 + (_parse_meters(pos_a["x coordinate"]) - _parse_meters(pos_b["x coordinate"])) + ** 2 + + (_parse_meters(pos_a["y coordinate"]) - _parse_meters(pos_b["y coordinate"])) + ** 2 + ( _parse_meters(pos_a["height above floor"]) - _parse_meters(pos_b["height above floor"]) ) ** 2 ) ** 0.5 - return max(0.0, center_distance - (_parse_meters(dim_a) / 2 + _parse_meters(dim_b) / 2)) + return max( + 0.0, center_distance - (_parse_meters(dim_a) / 2 + _parse_meters(dim_b) / 2) + ) def _closest_distance_meters(code, cls_a, cls_b): @@ -389,7 +397,11 @@ def answer_object_abs_distance(question, options, code): return None a = _find_class(m.group(1), code) b = _find_class(m.group(2), code) - d = _closest_distance_meters(code, a, b) if a is not None and b is not None else None + d = ( + _closest_distance_meters(code, a, b) + if a is not None and b is not None + else None + ) if d is None: fallback = _room_scale_distance_estimate(code) return round(fallback, 2) if fallback is not None else None @@ -491,7 +503,9 @@ def answer_obj_appearance_order(question, options, code): order = code.get("appearance order", []) order_index = {c: i for i, c in enumerate(order)} - resolved_options = [] # (letter, indices) for every option whose classes ALL resolve + resolved_options = ( + [] + ) # (letter, indices) for every option whose classes ALL resolve for opt in options: letter, _, seq_text = opt.partition(".") names = [n.strip() for n in seq_text.split(",")] @@ -595,7 +609,8 @@ def answer_route_planning(question, options, code): """'beginning at the X facing Y ... 1. Go forward until the Z 2. [please fill in] ...' -> the option letter whose comma-separated turn sequence matches the chained turn classification, re-derived from encoder/geometric.py's answer_route()/_classify_turn() - but reading parsed (x, y) positions from the spatial code instead of raw point clouds.""" + but reading parsed (x, y) positions from the spatial code instead of raw point clouds. + """ if not options: return None m = re.search(r"beginning at the (.+?) (?:and )?facing the (.+?)\.", question) diff --git a/tests/test_A/__pycache__/__init__.cpython-311.pyc b/tests/test_A/__pycache__/__init__.cpython-311.pyc index d55634fd20efff187f3f928badc520a58d2d78dc..fb41e316a71fe9c5410ebfd8a2f50d143a43560c 100644 Binary files a/tests/test_A/__pycache__/__init__.cpython-311.pyc and b/tests/test_A/__pycache__/__init__.cpython-311.pyc differ diff --git a/tests/test_A/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc b/tests/test_A/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc index 987b8d6586d3415d4a1d5218e382c2887dcf6e8d..2f8c33d556408a66017bd97f5c2c4dbf4c552f50 100644 Binary files a/tests/test_A/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc and b/tests/test_A/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_A/__pycache__/conftest.cpython-311.pyc b/tests/test_A/__pycache__/conftest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..730163b92283f4a3abfad64bea01ef19f9692a36 Binary files /dev/null and b/tests/test_A/__pycache__/conftest.cpython-311.pyc differ diff --git a/tests/test_A/__pycache__/test_A.cpython-311-pytest-9.1.1.pyc b/tests/test_A/__pycache__/test_A.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be0dc9b208b3350d7a1d85d5f20f1e8ab6ecb56a Binary files /dev/null and b/tests/test_A/__pycache__/test_A.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_A/__pycache__/test_A.cpython-311.pyc b/tests/test_A/__pycache__/test_A.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95ecb18feb95cfdc4496aa6d6f3f683fc190bc3b Binary files /dev/null and b/tests/test_A/__pycache__/test_A.cpython-311.pyc differ diff --git a/tests/test_A/__pycache__/test_frames.cpython-311-pytest-9.1.1.pyc b/tests/test_A/__pycache__/test_frames.cpython-311-pytest-9.1.1.pyc index 95dff2aeb78ac3ad41ecf41990de2664285ad558..82f39d9559f3a370003616f46804e3c20eaa657d 100644 Binary files a/tests/test_A/__pycache__/test_frames.cpython-311-pytest-9.1.1.pyc and b/tests/test_A/__pycache__/test_frames.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_A/__pycache__/test_frames.cpython-311.pyc b/tests/test_A/__pycache__/test_frames.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cda6ff17fc93fb8346cf611fc67d13aa73317fb5 Binary files /dev/null and b/tests/test_A/__pycache__/test_frames.cpython-311.pyc differ diff --git a/tests/test_A/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc b/tests/test_A/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc index 14ace0c41b4de22e627312685e5f6f3b74fb53d9..5876a083063604d4d3cdf85d52b61b342ced9742 100644 Binary files a/tests/test_A/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc and b/tests/test_A/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_A/__pycache__/test_init.cpython-311.pyc b/tests/test_A/__pycache__/test_init.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b9022b6595ccf109cb59d24543017c3974d545a Binary files /dev/null and b/tests/test_A/__pycache__/test_init.cpython-311.pyc differ diff --git a/tests/test_A/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc b/tests/test_A/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc index 11b09e2f3603cc5acd8dc97b79d38aa93cdef97d..9a1f3b8f8951f02ac0a6f18e8c5df8e1c34478a1 100644 Binary files a/tests/test_A/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc and b/tests/test_A/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_A/__pycache__/test_launch.cpython-311.pyc b/tests/test_A/__pycache__/test_launch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cba741d3364c18e3b73fbaa14778901cbee8c7c Binary files /dev/null and b/tests/test_A/__pycache__/test_launch.cpython-311.pyc differ diff --git a/tests/test_A/__pycache__/test_models.cpython-311-pytest-9.1.1.pyc b/tests/test_A/__pycache__/test_models.cpython-311-pytest-9.1.1.pyc index 97fd51a247775f74a713b1db2fb7aaefa3ff53c8..b078e9413b87b5406093bd4c15af8865a8bdd9e3 100644 Binary files a/tests/test_A/__pycache__/test_models.cpython-311-pytest-9.1.1.pyc and b/tests/test_A/__pycache__/test_models.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_A/__pycache__/test_models.cpython-311.pyc b/tests/test_A/__pycache__/test_models.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a55a04ba5679f4a570d7ecac177b67c7a77a04c3 Binary files /dev/null and b/tests/test_A/__pycache__/test_models.cpython-311.pyc differ diff --git a/tests/test_A/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc b/tests/test_A/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc index 118db3b706ab7783449c2530e11854539289dfea..611eb450f6ffe8b54c80ca581dae526cc3a295a3 100644 Binary files a/tests/test_A/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc and b/tests/test_A/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_A/__pycache__/test_prompts.cpython-311.pyc b/tests/test_A/__pycache__/test_prompts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22a2ee3d893a29a4dd2cd2c8713db28e0106786b Binary files /dev/null and b/tests/test_A/__pycache__/test_prompts.cpython-311.pyc differ diff --git a/tests/test_A/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc b/tests/test_A/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc index fb0f53d61d92d07c4dd975b40717161563abed4e..433552536d50ae4add952d1172468f574979e112 100644 Binary files a/tests/test_A/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc and b/tests/test_A/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_A/__pycache__/test_run.cpython-311.pyc b/tests/test_A/__pycache__/test_run.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93ef436b4a7f9380fb1bff32a56dada6115a90e5 Binary files /dev/null and b/tests/test_A/__pycache__/test_run.cpython-311.pyc differ diff --git a/tests/test_A/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc b/tests/test_A/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc index 9ed873dab61f4349513eef31299ad3abcf029f53..1d226de6367bb6fa8db4d754f99941afbc8809bd 100644 Binary files a/tests/test_A/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc and b/tests/test_A/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_A/__pycache__/test_sweep.cpython-311.pyc b/tests/test_A/__pycache__/test_sweep.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08acf9f4e2d046fe50657eba86257838269601c1 Binary files /dev/null and b/tests/test_A/__pycache__/test_sweep.cpython-311.pyc differ diff --git a/tests/test_A/test_A.py b/tests/test_A/test_A.py new file mode 100644 index 0000000000000000000000000000000000000000..10f68f7b2b1bce3a497769e713368bbe59953e53 --- /dev/null +++ b/tests/test_A/test_A.py @@ -0,0 +1,43 @@ +"""Tests for harness/A/__init__.py -- shared config constants.""" + +from pathlib import Path + +from harness import A + + +def test_generation_protocol_matches_vsibench_yaml(): + # thinking-in-space/lmms_eval/tasks/vsibench/vsibench.yaml generation_kwargs. + assert A.MAX_NEW_TOKENS == 16 + assert A.TEMPERATURE == 0.0 + assert A.DO_SAMPLE is False + + +def test_extended_generation_protocol(): + assert A.EXTENDED_MAX_NEW_TOKENS == 2048 + assert A.EXTENDED_MAX_NEW_TOKENS > A.MAX_NEW_TOKENS + assert isinstance(A.FORCE_ANSWER_PROMPT, str) and A.FORCE_ANSWER_PROMPT.strip() + + +def test_frame_selections_match_inference_vocabulary(): + from inference import SAM3_FRAME_SELECTIONS + + assert A.FRAME_SELECTIONS == SAM3_FRAME_SELECTIONS + + +def test_default_frame_selection_is_a_valid_selection(): + assert A.DEFAULT_FRAME_SELECTION in A.FRAME_SELECTIONS + + +def test_model_paths_cover_every_registered_model(): + assert set(A.MODEL_PATHS) == { + "qwen3.5-4b", + "qwen3.5-2b", + "internvl3.5-4b", + "internvl3.5-2b", + } + for path in A.MODEL_PATHS.values(): + assert path.parent == A.MODELS_ROOT + + +def test_results_dir_defaults_under_root_results(): + assert A.RESULTS_DIR == Path("/root/results/A") diff --git a/tests/test_A/test_frames.py b/tests/test_A/test_frames.py index 3481b0fb2c5d6c9f686ad66215c00eab0c6a6b42..72483e70c8437eb054776910c046d9b4e119356b 100644 --- a/tests/test_A/test_frames.py +++ b/tests/test_A/test_frames.py @@ -36,6 +36,17 @@ def test_sample_frames_returns_pil_images_in_order(tmp_path, monkeypatch): "_sample_video_frames", lambda path, count, selection: (fake_frames, np.array([0.0, 1.0, 2.0])), ) + + class _UnreadableCapture: + def get(self, prop): + return 0.0 + + def release(self): + pass + + monkeypatch.setattr( + frame_sampling.cv2, "VideoCapture", lambda path: _UnreadableCapture() + ) result, timestamps, indices = frame_sampling.sample_frames(str(video), 3, "uniform") assert len(result) == 3 assert np.array(result[0])[0, 0, 0] == 10 diff --git a/tests/test_A/test_launch.py b/tests/test_A/test_launch.py index 97f2c2851a8aadc329bbde326da25a439ffa6d52..a324b60ddafd730667795b914b85b9b9a3dc0952 100644 --- a/tests/test_A/test_launch.py +++ b/tests/test_A/test_launch.py @@ -1,27 +1,47 @@ """Tests for harness/A/launch.py -- multi-GPU scene sharding across workers.""" +import pytest + from harness.A import launch -from harness.A import run as harness_run def test_launcher_imports(): assert callable(launch.main) -def test_scenes_dedups_and_preserves_order(): - rows = harness_run.load_questions() - expected = list(dict.fromkeys(row["scene_name"] for row in rows)) - assert launch.scenes() == expected +def test_scenes_dedups_and_preserves_order(tmp_path, monkeypatch): + manifest = tmp_path / "questions.jsonl" + rows = [ + '{"scene_name": "scene-a"}', + '{"scene_name": "scene-b"}', + '{"scene_name": "scene-a"}', + ] + manifest.write_text("\n".join(rows) + "\n") + monkeypatch.setattr(launch, "JSONL", manifest) + assert launch.scenes() == ["scene-a", "scene-b"] + + +class _FakeRun: + rows = [{"id": 1}, {"id": 2}] + + @staticmethod + def results_dir_for( + model, protocol, frame_selection, frame_count, results_dir=None + ): + return results_dir + + @classmethod + def load_questions(cls, scene=None): + return list(cls.rows) -def test_launch_skips_scene_already_fully_answered(tmp_path, capsys): - scene = "41069025" - rows = harness_run.load_questions(scene=scene) - assert rows, "fixture scene must have real questions in the VSI-Bench manifest" +def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch): + scene = "scene-a" + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) scene_dir = tmp_path / scene scene_dir.mkdir() - for row in rows: + for row in _FakeRun.rows: (scene_dir / f"{row['id']}.json").write_text("{}") launch.launch("qwen3.5-2b", "uniform", 16, [scene], results_dir=tmp_path) @@ -32,25 +52,25 @@ def test_launch_skips_scene_already_fully_answered(tmp_path, capsys): def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): - scene = "41069025" - rows = harness_run.load_questions(scene=scene) + scene = "scene-a" + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) scene_dir = tmp_path / scene scene_dir.mkdir() - for row in rows: + for row in _FakeRun.rows: (scene_dir / f"{row['id']}.json").write_text("{}") - seen_gpus = [] monkeypatch.setattr(launch, "visible_gpus", lambda: []) - def fake_launch_worker_spawn(*args, **kwargs): - seen_gpus.append(True) - # Only assert it treats the scene as pending (doesn't take the all-skipped early # return); actually spawning workers needs a real model/GPU, exercised by the live # harness.A.launch smoke run instead of the unit suite. - monkeypatch.setattr(launch.mp, "get_context", lambda *_: (_ for _ in ()).throw( - RuntimeError("rebuild correctly reached worker dispatch") - )) + monkeypatch.setattr( + launch.mp, + "get_context", + lambda *_: (_ for _ in ()).throw( + RuntimeError("rebuild correctly reached worker dispatch") + ), + ) try: launch.launch( "qwen3.5-2b", "uniform", 16, [scene], results_dir=tmp_path, rebuild=True @@ -59,3 +79,12 @@ def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch) assert "rebuild correctly reached worker dispatch" in str(exc) else: raise AssertionError("expected rebuild to force scene into the pending path") + + +def test_launch_rejects_scene_with_no_questions(monkeypatch, tmp_path): + class EmptyRun(_FakeRun): + rows = [] + + monkeypatch.setattr(launch, "_load_run_module", lambda: EmptyRun) + with pytest.raises(ValueError, match="no questions found"): + launch.launch("qwen3.5-2b", "uniform", 16, ["missing"], results_dir=tmp_path) diff --git a/tests/test_A/test_models.py b/tests/test_A/test_models.py index dab23efc3f75a269dbd29d068eb3149a918da68a..140af5da7797ef25973679b0f8f8bc48a0a368a9 100644 --- a/tests/test_A/test_models.py +++ b/tests/test_A/test_models.py @@ -13,7 +13,10 @@ from harness.A import models as vlm_models def test_all_three_models_are_registered(): assert vlm_models.available_models() == ( - "internvl3.5-2b", "internvl3.5-4b", "qwen3.5-2b", "qwen3.5-4b", + "internvl3.5-2b", + "internvl3.5-4b", + "qwen3.5-2b", + "qwen3.5-4b", ) @@ -25,7 +28,9 @@ def test_get_adapter_binds_the_correct_checkpoint_path(): def test_get_adapter_returns_the_right_class_per_model(): assert isinstance(vlm_models.get_adapter("qwen3.5-2b"), vlm_models.QwenVLAdapter) - assert isinstance(vlm_models.get_adapter("internvl3.5-4b"), vlm_models.InternVLAdapter) + assert isinstance( + vlm_models.get_adapter("internvl3.5-4b"), vlm_models.InternVLAdapter + ) def test_get_adapter_rejects_unknown_model(): diff --git a/tests/test_A/test_run.py b/tests/test_A/test_run.py index 8aa818cc7f936930413dcb149cdb6bbe250e1bcf..4b7077ab4d40508cec51bd608ce9f32a19fc0b19 100644 --- a/tests/test_A/test_run.py +++ b/tests/test_A/test_run.py @@ -112,7 +112,10 @@ def test_results_dir_for_isolates_the_two_protocols(): def test_results_dir_for_honors_explicit_override(tmp_path): - assert harness_run.results_dir_for("qwen3.5-4b", "base", "uniform", 16, tmp_path) == tmp_path + assert ( + harness_run.results_dir_for("qwen3.5-4b", "base", "uniform", 16, tmp_path) + == tmp_path + ) def test_build_record_preserves_every_field_untruncated(): @@ -168,8 +171,14 @@ def test_write_question_result_writes_one_json_file_per_question(tmp_path): def test_build_record_defaults_reasoning_fields_when_not_extended(): 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", _FAKE_FRAME_INFO, + _FAKE_ROW, + "full prompt text", + _FAKE_ANSWER, + "MRA:.5:.95:.05", + 1.0, + "qwen3.5-4b", + "/root/models/qwen3.5-4b", + _FAKE_FRAME_INFO, ) assert record["reasoning_text"] is None assert record["forced"] is False @@ -188,8 +197,14 @@ def test_build_record_carries_reasoning_fields_when_extended(): "forced_input_token_count": 2510, } record = harness_run._build_record( - _FAKE_ROW, "full prompt text", extended_answer, "MRA:.5:.95:.05", 1.0, - "qwen3.5-4b", "/root/models/qwen3.5-4b", _FAKE_FRAME_INFO, + _FAKE_ROW, + "full prompt text", + extended_answer, + "MRA:.5:.95:.05", + 1.0, + "qwen3.5-4b", + "/root/models/qwen3.5-4b", + _FAKE_FRAME_INFO, ) assert record["reasoning_text"] == "long reasoning about the scene" assert record["reasoning_token_count"] == 50 diff --git a/tests/test_A/test_sweep.py b/tests/test_A/test_sweep.py index 7afce873529249b188f4314dce8926470119bd10..ad3c0b8308854149f8478ab92ef6bae28b2b092d 100644 --- a/tests/test_A/test_sweep.py +++ b/tests/test_A/test_sweep.py @@ -7,7 +7,9 @@ from harness.A import sweep def test_parse_csv_choice_splits_and_dedups(): - result = sweep._parse_csv_choice("uniform,selective,uniform", ("uniform", "selective"), "--x") + result = sweep._parse_csv_choice( + "uniform,selective,uniform", ("uniform", "selective"), "--x" + ) assert result == ["uniform", "selective"] @@ -41,13 +43,19 @@ def test_parse_frame_counts_rejects_non_integer(): def test_build_plan_covers_every_combination(): - plan = sweep.build_plan(["qwen3.5-2b", "qwen3.5-4b"], ["uniform", "selective"], [16, 32]) + plan = sweep.build_plan( + ["qwen3.5-2b", "qwen3.5-4b"], ["uniform", "selective"], [16, 32] + ) assert len(plan) == 2 * 2 * 2 assert set(plan) == { - ("qwen3.5-2b", "uniform", 16), ("qwen3.5-2b", "uniform", 32), - ("qwen3.5-2b", "selective", 16), ("qwen3.5-2b", "selective", 32), - ("qwen3.5-4b", "uniform", 16), ("qwen3.5-4b", "uniform", 32), - ("qwen3.5-4b", "selective", 16), ("qwen3.5-4b", "selective", 32), + ("qwen3.5-2b", "uniform", 16), + ("qwen3.5-2b", "uniform", 32), + ("qwen3.5-2b", "selective", 16), + ("qwen3.5-2b", "selective", 32), + ("qwen3.5-4b", "uniform", 16), + ("qwen3.5-4b", "uniform", 32), + ("qwen3.5-4b", "selective", 16), + ("qwen3.5-4b", "selective", 32), } diff --git a/tests/test_B/__pycache__/__init__.cpython-311.pyc b/tests/test_B/__pycache__/__init__.cpython-311.pyc index 269ccf9c4099f9a028f634efb0ced30d71eaf97f..4971ff5ce2e29b3c11bb5fe3585a9e23658a5703 100644 Binary files a/tests/test_B/__pycache__/__init__.cpython-311.pyc and b/tests/test_B/__pycache__/__init__.cpython-311.pyc differ diff --git a/tests/test_B/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc b/tests/test_B/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc index 0cfd54f22d72adf0dccf363006550009d41a3810..2cd8623666ff2250584e5cd5710951a860a5d973 100644 Binary files a/tests/test_B/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc and b/tests/test_B/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_B/__pycache__/conftest.cpython-311.pyc b/tests/test_B/__pycache__/conftest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db9f990ff0b0916439b7e766292de3526162f351 Binary files /dev/null and b/tests/test_B/__pycache__/conftest.cpython-311.pyc differ diff --git a/tests/test_B/__pycache__/test_B.cpython-311-pytest-9.1.1.pyc b/tests/test_B/__pycache__/test_B.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8dc202118b2d56d20db7de97e29979a5ce7023b Binary files /dev/null and b/tests/test_B/__pycache__/test_B.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_B/__pycache__/test_B.cpython-311.pyc b/tests/test_B/__pycache__/test_B.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9125027bb145db64c3dd2ac9b6bd5645c48d8c3a Binary files /dev/null and b/tests/test_B/__pycache__/test_B.cpython-311.pyc differ diff --git a/tests/test_B/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc b/tests/test_B/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc index dba23f4fb9d2c6a36c01b66e1ad64aa165c933d5..eb7976e18524650241fa1f1a96044338c359c40d 100644 Binary files a/tests/test_B/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc and b/tests/test_B/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_B/__pycache__/test_init.cpython-311.pyc b/tests/test_B/__pycache__/test_init.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64de6c7bb078469e14b47ba525b670899f27d16d Binary files /dev/null and b/tests/test_B/__pycache__/test_init.cpython-311.pyc differ diff --git a/tests/test_B/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc b/tests/test_B/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc index d1fa4f120e32de61f3f02481017504752937b966..76c2d702ae5415c006ec84ca7c89131e49b999fc 100644 Binary files a/tests/test_B/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc and b/tests/test_B/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_B/__pycache__/test_launch.cpython-311.pyc b/tests/test_B/__pycache__/test_launch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d100ceacd019b31da1f1013619766f0ff925293 Binary files /dev/null and b/tests/test_B/__pycache__/test_launch.cpython-311.pyc differ diff --git a/tests/test_B/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc b/tests/test_B/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc index fc8075798e8f9bcb6b60e0b82a023857b3df3b30..165b554d0b3514c86778ae0d7c18662fb9998766 100644 Binary files a/tests/test_B/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc and b/tests/test_B/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_B/__pycache__/test_prompts.cpython-311.pyc b/tests/test_B/__pycache__/test_prompts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ba52242916a344a96f72ed8d83e76164284beeb Binary files /dev/null and b/tests/test_B/__pycache__/test_prompts.cpython-311.pyc differ diff --git a/tests/test_B/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc b/tests/test_B/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc index e66f4491581482b6278ffab2685350d16216b57b..8dc35865d3d826ca0b8f65dbfe1c8ffdbb5fba3f 100644 Binary files a/tests/test_B/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc and b/tests/test_B/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_B/__pycache__/test_run.cpython-311.pyc b/tests/test_B/__pycache__/test_run.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1dda01d44ca935cf4d1d33d594af762ede345a4 Binary files /dev/null and b/tests/test_B/__pycache__/test_run.cpython-311.pyc differ diff --git a/tests/test_B/__pycache__/test_spatial_codes.cpython-311-pytest-9.1.1.pyc b/tests/test_B/__pycache__/test_spatial_codes.cpython-311-pytest-9.1.1.pyc index eb5bb1ab2a07cffd78997b2c7b1eeeecc61a62d7..9cf87ef78e7d6fdacbc9611d6f14412fb49fd748 100644 Binary files a/tests/test_B/__pycache__/test_spatial_codes.cpython-311-pytest-9.1.1.pyc and b/tests/test_B/__pycache__/test_spatial_codes.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_B/__pycache__/test_spatial_codes.cpython-311.pyc b/tests/test_B/__pycache__/test_spatial_codes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..195c27b631fea3190f814d77a0eefbaeb43dfb43 Binary files /dev/null and b/tests/test_B/__pycache__/test_spatial_codes.cpython-311.pyc differ diff --git a/tests/test_B/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc b/tests/test_B/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc index 19891b32c606d8370bbdd1f01c930dd4c63501cc..028649b9a8a0c3617fe43cce9bfd3578271ce366 100644 Binary files a/tests/test_B/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc and b/tests/test_B/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_B/__pycache__/test_sweep.cpython-311.pyc b/tests/test_B/__pycache__/test_sweep.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13ba74089a9c994cc8c8ea9f5be084be6cbdc617 Binary files /dev/null and b/tests/test_B/__pycache__/test_sweep.cpython-311.pyc differ diff --git a/tests/test_B/test_B.py b/tests/test_B/test_B.py new file mode 100644 index 0000000000000000000000000000000000000000..bab25bef8f2c231e0e5bd356ed979564baf55e28 --- /dev/null +++ b/tests/test_B/test_B.py @@ -0,0 +1,35 @@ +"""Tests for harness/B/__init__.py -- shared config constants.""" + +from pathlib import Path + +from harness import A, B + + +def test_spatial_code_formats_match_the_two_on_disk_schemas(): + assert B.SPATIAL_CODE_FORMATS == ("explicit", "compact") + assert B.DEFAULT_SPATIAL_CODE_FORMAT in B.SPATIAL_CODE_FORMATS + + +def test_input_selections_match_harness_a_vocabulary(): + assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS + assert B.DEFAULT_INPUT_SELECTION in B.INPUT_SELECTIONS + + +def test_reuses_harness_a_model_paths_and_generation_protocol(): + assert B.MODEL_PATHS is A.MODEL_PATHS + assert B.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS + assert B.DO_SAMPLE == A.DO_SAMPLE + assert B.TEMPERATURE == A.TEMPERATURE + + +def test_results_dir_defaults_under_root_results(): + assert B.RESULTS_DIR == Path("/root/results/B") + + +def test_depth_and_tracking_reuse_encoder_config_vocabulary(): + from encoder.config import DEPTH_VARIANTS, TRACKING_MODES + + assert B.DEPTH_VARIANTS == DEPTH_VARIANTS + assert B.TRACKING_MODES == TRACKING_MODES + assert B.DEFAULT_DEPTH in B.DEPTH_VARIANTS + assert B.DEFAULT_TRACKING in B.TRACKING_MODES diff --git a/tests/test_B/test_launch.py b/tests/test_B/test_launch.py index 68be0bebee397ab08e092252bfc4ec0ee44f8459..598fa4e72abf4cc301473153f1c818df3d694b2f 100644 --- a/tests/test_B/test_launch.py +++ b/tests/test_B/test_launch.py @@ -1,6 +1,7 @@ """Tests for harness/B/launch.py -- multi-GPU scene sharding across workers.""" -from harness.A.run import load_questions as harness_a_load_questions +import pytest + from harness.B import launch @@ -8,17 +9,30 @@ 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" +class _FakeRun: + rows = [{"id": 1}, {"id": 3}] + + @staticmethod + def results_dir_for(*args, **kwargs): + return args[-1] + + @classmethod + def load_questions(cls, scene=None): + return list(cls.rows) + + +def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch): + scene = "scene-b" + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) scene_dir = tmp_path / scene scene_dir.mkdir() - for row in rows: + for row in _FakeRun.rows: (scene_dir / f"{row['id']}.json").write_text("{}") - launch.launch("qwen3.5-2b", "explicit", "selective", 64, [scene], results_dir=tmp_path) + launch.launch( + "qwen3.5-2b", "explicit", "selective", 64, [scene], results_dir=tmp_path + ) output = capsys.readouterr().out assert "skipped" in output @@ -26,24 +40,46 @@ def test_launch_skips_scene_already_fully_answered(tmp_path, capsys): def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): - scene = "13c3e046d7" - rows = harness_a_load_questions(scene=scene) + scene = "scene-b" + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) scene_dir = tmp_path / scene scene_dir.mkdir() - for row in rows: + for row in _FakeRun.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")), + launch.mp, + "get_context", + lambda *_: (_ for _ in ()).throw( + RuntimeError("rebuild correctly reached worker dispatch") + ), ) try: launch.launch( - "qwen3.5-2b", "explicit", "selective", 64, [scene], - results_dir=tmp_path, rebuild=True, + "qwen3.5-2b", + "explicit", + "selective", + 64, + [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_rejects_question_id_filter_that_matches_nothing(monkeypatch, tmp_path): + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) + with pytest.raises(ValueError, match="no questions found"): + launch.launch( + "qwen3.5-2b", + "explicit", + "selective", + 64, + ["scene-b"], + results_dir=tmp_path, + question_ids={999}, + ) diff --git a/tests/test_B/test_prompts.py b/tests/test_B/test_prompts.py index babdc91cef8b0ac1a9cbd26e6d69936807a009f7..ad7945c4d970f71f92ae5db81907af6effecbc75 100644 --- a/tests/test_B/test_prompts.py +++ b/tests/test_B/test_prompts.py @@ -7,7 +7,10 @@ import pytest from harness.A.prompts import MCA_QUESTION_TYPES, NA_QUESTION_TYPES from harness.B import prompts as code_prompts -_CODE = {"objects": {"chair": {"count": 1}}, "room": {"floor area": "10.0 square meters"}} +_CODE = { + "objects": {"chair": {"count": 1}}, + "room": {"floor area": "10.0 square meters"}, +} def test_na_question_prompt_embeds_the_spatial_code_as_text_and_a_post_prompt(): @@ -55,7 +58,11 @@ def test_every_mca_question_type_builds(question_type): def test_default_arguments_reproduce_the_standard_prompt_byte_for_byte(): standard = code_prompts.build_prompt(_CODE, "object_counting", "How many chairs?") explicit_defaults = code_prompts.build_prompt( - _CODE, "object_counting", "How many chairs?", serialization="json", context_line=None + _CODE, + "object_counting", + "How many chairs?", + serialization="json", + context_line=None, ) assert standard == explicit_defaults @@ -82,7 +89,9 @@ def test_yaml_arm_context_line_does_not_claim_json(): def test_paraphrase_context_line_swaps_only_the_first_line(): standard = code_prompts.build_prompt(_CODE, "object_counting", "How many chairs?") paraphrased = code_prompts.build_prompt( - _CODE, "object_counting", "How many chairs?", + _CODE, + "object_counting", + "How many chairs?", context_line=code_prompts.PARAPHRASE_PRE_PROMPT, ) assert standard.split("\n", 1)[1] == paraphrased.split("\n", 1)[1] diff --git a/tests/test_B/test_run.py b/tests/test_B/test_run.py index c6ebf8fe369860c8b8eed5badf520eab7b248226..aaba6c80fc4defbbfc58397aa43225dc9cd0e12c 100644 --- a/tests/test_B/test_run.py +++ b/tests/test_B/test_run.py @@ -55,8 +55,14 @@ def test_results_dir_for_matches_established_dimension_nesting(): "qwen3.5-4b", "extended", "compact", "metric", "tracking", "uniform", 32 ) assert root == ( - B.RESULTS_DIR / "qwen3.5-4b" / "extended" / "compact" / "metric" / "tracking" - / "uniform" / "32" + B.RESULTS_DIR + / "qwen3.5-4b" + / "extended" + / "compact" + / "metric" + / "tracking" + / "uniform" + / "32" ) @@ -72,15 +78,28 @@ def test_results_dir_for_isolates_the_two_protocols(): def test_results_dir_for_honors_explicit_override(tmp_path): root = harness_run.results_dir_for( - "qwen3.5-4b", "base", "explicit", "relative", "no tracking", "selective", 16, tmp_path + "qwen3.5-4b", + "base", + "explicit", + "relative", + "no tracking", + "selective", + 16, + tmp_path, ) assert root == tmp_path def test_build_record_preserves_every_field_untruncated(): 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", _FAKE_CODE_INFO, + _FAKE_ROW, + "full prompt text", + _FAKE_ANSWER, + "MRA:.5:.95:.05", + 1.0, + "qwen3.5-4b", + "/root/models/qwen3.5-4b", + _FAKE_CODE_INFO, ) assert record["question"] == "How many chairs?" assert record["full_prompt"] == "full prompt text" @@ -109,8 +128,15 @@ def test_build_record_preserves_every_field_untruncated(): 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", _FAKE_CODE_INFO, results_dir=tmp_path, + _FAKE_ROW, + "full prompt text", + _FAKE_ANSWER, + "MRA:.5:.95:.05", + 1.0, + "qwen3.5-4b", + "/root/models/qwen3.5-4b", + _FAKE_CODE_INFO, + results_dir=tmp_path, ) assert path == tmp_path / "scene0001_00" / "7.json" on_disk = json.loads(path.read_text()) @@ -129,8 +155,14 @@ def test_build_record_carries_reasoning_fields_when_forced(): "forced_input_token_count": 2510, } record = harness_run._build_record( - _FAKE_ROW, "full prompt text", extended_answer, "MRA:.5:.95:.05", 1.0, - "qwen3.5-4b", "/root/models/qwen3.5-4b", _FAKE_CODE_INFO, + _FAKE_ROW, + "full prompt text", + extended_answer, + "MRA:.5:.95:.05", + 1.0, + "qwen3.5-4b", + "/root/models/qwen3.5-4b", + _FAKE_CODE_INFO, ) assert record["reasoning_text"] == "long reasoning about the spatial code" assert record["forced"] is True @@ -141,7 +173,10 @@ def test_run_strip_schema_legend_removes_only_the_legend(monkeypatch): seen = {} def fake_load(scene_id, depth, input_selection, tracking, frame_count, fmt): - return {"spatial code schema": {"doc": 1}, "objects": {"chair": {"count": 1}}}, "/fake.json" + return { + "spatial code schema": {"doc": 1}, + "objects": {"chair": {"count": 1}}, + }, "/fake.json" class FakeAdapter: model_path = "/fake/model" @@ -149,18 +184,30 @@ def test_run_strip_schema_legend_removes_only_the_legend(monkeypatch): 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": {}, + "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) results = harness_run.run( - "qwen3.5-2b", scene="13c3e046d7", adapter=FakeAdapter(), write_results=False, - limit=1, strip_schema_legend=True, + "qwen3.5-2b", + scene="13c3e046d7", + adapter=FakeAdapter(), + write_results=False, + limit=1, + strip_schema_legend=True, ) assert results assert "spatial code schema" not in seen["prompt"] diff --git a/tests/test_B/test_spatial_codes.py b/tests/test_B/test_spatial_codes.py index c5f57cd986b8fbfdb0c643abd57f557933ff80e6..33be845b2d5b493a2e0f854a203d000d8c730f73 100644 --- a/tests/test_B/test_spatial_codes.py +++ b/tests/test_B/test_spatial_codes.py @@ -9,21 +9,29 @@ from harness.B import spatial_codes def test_load_spatial_code_rejects_unknown_format(): with pytest.raises(ValueError): - spatial_codes.load_spatial_code("scene", "metric", "selective", "tracking", 64, "bogus") + spatial_codes.load_spatial_code( + "scene", "metric", "selective", "tracking", 64, "bogus" + ) def test_load_spatial_code_raises_clearly_when_missing(tmp_path, monkeypatch): monkeypatch.setattr( - spatial_codes, "spatial_code_path", lambda *a, **k: str(tmp_path / "missing.json") + spatial_codes, + "spatial_code_path", + lambda *a, **k: str(tmp_path / "missing.json"), ) with pytest.raises(FileNotFoundError): - spatial_codes.load_spatial_code("scene", "metric", "selective", "tracking", 64, "explicit") + spatial_codes.load_spatial_code( + "scene", "metric", "selective", "tracking", 64, "explicit" + ) def test_load_spatial_code_returns_dict_and_path(tmp_path, monkeypatch): fixture = tmp_path / "13c3e046d7.json" fixture.write_text(json.dumps({"objects": {}, "room": {}})) - monkeypatch.setattr(spatial_codes, "spatial_code_path", lambda *a, **k: str(fixture)) + monkeypatch.setattr( + spatial_codes, "spatial_code_path", lambda *a, **k: str(fixture) + ) code, path = spatial_codes.load_spatial_code( "13c3e046d7", "metric", "selective", "tracking", 64, "compact" ) @@ -31,10 +39,10 @@ def test_load_spatial_code_returns_dict_and_path(tmp_path, monkeypatch): assert path == str(fixture) -def test_load_spatial_code_reads_a_real_on_disk_file(): - code, path = spatial_codes.load_spatial_code( - "13c3e046d7", "metric", "selective", "tracking", 64, "explicit" +def test_spatial_code_path_includes_every_cache_axis(): + path = spatial_codes.spatial_code_path( + "scene-a", "metric", "selective", "tracking", 64, "explicit" + ) + assert path.endswith( + "data/spatial codes/sam3+depth-anything-3/metric/tracking/selective/64/explicit/scene-a.json" ) - assert "spatial code schema" in code - assert "closest classes distance meters from" in code - assert path.endswith("13c3e046d7.json") diff --git a/tests/test_B/test_sweep.py b/tests/test_B/test_sweep.py index deda6af708c86ac7e3ef354177ae285b41ef9dbd..de963023d13132661d9341438acbfb2507041e43 100644 --- a/tests/test_B/test_sweep.py +++ b/tests/test_B/test_sweep.py @@ -8,8 +8,12 @@ from harness.B import sweep def test_build_plan_covers_every_combination(): plan = sweep.build_plan( - ["qwen3.5-2b", "qwen3.5-4b"], ["explicit", "compact"], ["uniform", "selective"], - [16, 32], ["metric"], ["tracking"], + ["qwen3.5-2b", "qwen3.5-4b"], + ["explicit", "compact"], + ["uniform", "selective"], + [16, 32], + ["metric"], + ["tracking"], ) assert len(plan) == 2 * 2 * 2 * 2 assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan @@ -18,8 +22,12 @@ def test_build_plan_covers_every_combination(): def test_build_plan_sweeps_depth_and_tracking_too(): plan = sweep.build_plan( - ["qwen3.5-2b"], ["explicit"], ["uniform"], [16], - ["metric", "relative"], ["tracking", "no tracking"], + ["qwen3.5-2b"], + ["explicit"], + ["uniform"], + [16], + ["metric", "relative"], + ["tracking", "no tracking"], ) assert len(plan) == 4 assert ("qwen3.5-2b", "explicit", "relative", "no tracking", "uniform", 16) in plan @@ -27,22 +35,33 @@ def test_build_plan_sweeps_depth_and_tracking_too(): def test_build_plan_orders_by_frame_count_first(): plan = sweep.build_plan( - ["qwen3.5-2b"], ["explicit"], ["uniform"], [64, 16, 32], ["metric"], ["tracking"] + ["qwen3.5-2b"], + ["explicit"], + ["uniform"], + [64, 16, 32], + ["metric"], + ["tracking"], ) assert [frame_count for *_rest, frame_count in plan] == [16, 32, 64] def test_build_plan_with_all_registered_models(): plan = sweep.build_plan( - list(vlm_models.available_models()), ["explicit"], ["uniform"], [16], - ["metric"], ["tracking"], + list(vlm_models.available_models()), + ["explicit"], + ["uniform"], + [16], + ["metric"], + ["tracking"], ) assert len(plan) == len(vlm_models.available_models()) def test_sweep_parser_rejects_unknown_spatial_code_format(): with pytest.raises(ValueError): - sweep._parse_csv_choice("bogus", ("explicit", "compact"), "--spatial-code-formats") + sweep._parse_csv_choice( + "bogus", ("explicit", "compact"), "--spatial-code-formats" + ) def test_sweep_parser_rejects_unknown_depth(): diff --git a/tests/test_C/__pycache__/__init__.cpython-311.pyc b/tests/test_C/__pycache__/__init__.cpython-311.pyc index 90f888369b088e8829b992a7a4c3c2925f2a24c2..b6f9a9b03950d6880f1b3fdddd159b4b850fe4f5 100644 Binary files a/tests/test_C/__pycache__/__init__.cpython-311.pyc and b/tests/test_C/__pycache__/__init__.cpython-311.pyc differ diff --git a/tests/test_C/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc b/tests/test_C/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc index 2339b66200996c69650ada4edd23c14019893d55..328eb908382af402962cdc7572284cbbea5d0908 100644 Binary files a/tests/test_C/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc and b/tests/test_C/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/__pycache__/conftest.cpython-311.pyc b/tests/test_C/__pycache__/conftest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acc39e0e81aaa01ad9c30f2fbe52e2057dfa7deb Binary files /dev/null and b/tests/test_C/__pycache__/conftest.cpython-311.pyc differ diff --git a/tests/test_C/__pycache__/test_C.cpython-311-pytest-9.1.1.pyc b/tests/test_C/__pycache__/test_C.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45c70e07080b3627492f68ee9b5d192b1451d4aa Binary files /dev/null and b/tests/test_C/__pycache__/test_C.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/__pycache__/test_C.cpython-311.pyc b/tests/test_C/__pycache__/test_C.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0ca54d698f6813864ee5ee12ff35ad893a59ee5 Binary files /dev/null and b/tests/test_C/__pycache__/test_C.cpython-311.pyc differ diff --git a/tests/test_C/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc b/tests/test_C/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc index cd3f2b3afe78ae6589d00a4e6605ad7ed40942e4..9ae8328950761d474609d5ebcdb8440570e98f4b 100644 Binary files a/tests/test_C/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc and b/tests/test_C/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/__pycache__/test_init.cpython-311.pyc b/tests/test_C/__pycache__/test_init.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..234185748d67917034a631bbf0003209d5e79a5b Binary files /dev/null and b/tests/test_C/__pycache__/test_init.cpython-311.pyc differ diff --git a/tests/test_C/__pycache__/test_launch.cpython-311.pyc b/tests/test_C/__pycache__/test_launch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44c5113e7a9d62006b54383b12fbb9d8edfe7b0f Binary files /dev/null and b/tests/test_C/__pycache__/test_launch.cpython-311.pyc differ diff --git a/tests/test_C/__pycache__/test_overlay.cpython-311-pytest-9.1.1.pyc b/tests/test_C/__pycache__/test_overlay.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e09f439f77500d81aa92d3508f9f411e593f986c Binary files /dev/null and b/tests/test_C/__pycache__/test_overlay.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/__pycache__/test_overlay.cpython-311.pyc b/tests/test_C/__pycache__/test_overlay.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06365f8b677248b166b3d31211255156080653a2 Binary files /dev/null and b/tests/test_C/__pycache__/test_overlay.cpython-311.pyc differ diff --git a/tests/test_C/__pycache__/test_overlay_launch.cpython-311-pytest-9.1.1.pyc b/tests/test_C/__pycache__/test_overlay_launch.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f445a81bbaf4d8bbed4cff782891717a0749e02 Binary files /dev/null and b/tests/test_C/__pycache__/test_overlay_launch.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/__pycache__/test_overlay_launch.cpython-311.pyc b/tests/test_C/__pycache__/test_overlay_launch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45d3df93b6cbb3c4f8fd494aa817da38d934c2d2 Binary files /dev/null and b/tests/test_C/__pycache__/test_overlay_launch.cpython-311.pyc differ diff --git a/tests/test_C/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc b/tests/test_C/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc index 07aa683206610112ce1fbf2d852f4686a5af0280..1cd6203358cf6b442100c1373379851bd0679ce7 100644 Binary files a/tests/test_C/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc and b/tests/test_C/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/__pycache__/test_prompts.cpython-311.pyc b/tests/test_C/__pycache__/test_prompts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bc23531b3e4ff3cd8f5e195f6f9646901a9bc2e Binary files /dev/null and b/tests/test_C/__pycache__/test_prompts.cpython-311.pyc differ diff --git a/tests/test_C/__pycache__/test_run.cpython-311.pyc b/tests/test_C/__pycache__/test_run.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b087c5acd485fdefdf90f63b41eeabdd9eef4699 Binary files /dev/null and b/tests/test_C/__pycache__/test_run.cpython-311.pyc differ diff --git a/tests/test_C/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc b/tests/test_C/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc index de4477508da485d2c0628e679b3bfda4fbd3a12e..68b64043903fe9d5024ecc4ad69923d6154ab350 100644 Binary files a/tests/test_C/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc and b/tests/test_C/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/test_launch.py b/tests/test_C/test_launch.py index 358593155f107893bb2ce5717006896169e06a73..68844acf0f75eacc9f28df964570bc06eb5c0a83 100644 --- a/tests/test_C/test_launch.py +++ b/tests/test_C/test_launch.py @@ -1,6 +1,5 @@ """Tests for harness/C/launch.py -- multi-GPU scene sharding across workers.""" -from harness.A.run import load_questions as harness_a_load_questions from harness.C import launch @@ -8,40 +7,94 @@ 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" +class _FakeRun: + rows = [{"id": 1}, {"id": 2}] + + @staticmethod + def results_dir_for(*args, **kwargs): + return args[-1] + + @classmethod + def load_questions(cls, scene=None): + return list(cls.rows) + + +def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch): + scene = "scene-c" + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) scene_dir = tmp_path / scene scene_dir.mkdir() - for row in rows: + for row in _FakeRun.rows: (scene_dir / f"{row['id']}.json").write_text("{}") - launch.launch("qwen3.5-2b", "explicit", "selective", 64, [scene], results_dir=tmp_path) + launch.launch( + "qwen3.5-2b", "explicit", "selective", 64, [scene], results_dir=tmp_path + ) output = capsys.readouterr().out assert "skipped" in output assert "DONE: 1 ok, 0 failed" in output +def test_launch_routes_overlay_to_overlay_result_tree(monkeypatch, capsys, tmp_path): + captured = {} + + root = tmp_path / "unused-results" + scene_dir = root / "scene" + scene_dir.mkdir(parents=True, exist_ok=True) + (scene_dir / "1.json").write_text("{}") + + class FakeRun: + + def results_dir_for(*args, **kwargs): + captured["overlay"] = kwargs.get("overlay") + return root + + def load_questions(scene=None): + return [{"id": 1}] + + monkeypatch.setattr(launch, "_load_run_module", lambda: FakeRun) + + launch.launch( + "qwen3.5-2b", + "explicit", + "uniform", + 32, + ["scene"], + overlay=True, + strip_schema_legend=True, + ) + + assert captured["overlay"] is True + assert "DONE: 1 ok, 0 failed" in capsys.readouterr().out + + def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): - scene = "13c3e046d7" - rows = harness_a_load_questions(scene=scene) + scene = "scene-c" + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) scene_dir = tmp_path / scene scene_dir.mkdir() - for row in rows: + for row in _FakeRun.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")), + launch.mp, + "get_context", + lambda *_: (_ for _ in ()).throw( + RuntimeError("rebuild correctly reached worker dispatch") + ), ) try: launch.launch( - "qwen3.5-2b", "explicit", "selective", 64, [scene], - results_dir=tmp_path, rebuild=True, + "qwen3.5-2b", + "explicit", + "selective", + 64, + [scene], + results_dir=tmp_path, + rebuild=True, ) except RuntimeError as exc: assert "rebuild correctly reached worker dispatch" in str(exc) diff --git a/tests/test_encoder/__pycache__/test_render.cpython-311.pyc b/tests/test_encoder/__pycache__/test_render.cpython-311.pyc index ef22b50b6ba657954dbdc488716a9e3aaba3f39c..562e665ede9f03119027a9e7bbf66ff6363868a2 100644 Binary files a/tests/test_encoder/__pycache__/test_render.cpython-311.pyc and b/tests/test_encoder/__pycache__/test_render.cpython-311.pyc differ diff --git a/tests/test_encoder/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc b/tests/test_encoder/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc index f22dd859049cf8a65931b517931c35d3c9b2d9f0..6fe412500da2cfc47d347619a464ec6beff3841e 100644 Binary files a/tests/test_encoder/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc and b/tests/test_encoder/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_encoder/test_config.py b/tests/test_encoder/test_config.py index 3454074688af531c8ad663f218719563fa31f1e1..439f41ca7cc2a7c9207209adcfbe78e90636e145 100644 --- a/tests/test_encoder/test_config.py +++ b/tests/test_encoder/test_config.py @@ -8,12 +8,12 @@ from encoder import config def test_encoder_paths_mirror_all_dimensions(tmp_path, monkeypatch): monkeypatch.setattr(config, "CACHE_ROOT", tmp_path / "caches") monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "codes") - assert config.cache_file( - "scene", "metric", "uniform", "no tracking", 64 - ).endswith("metric/no tracking/uniform/64/scene.pkl.gz") - assert config.da3_cache_file( - "scene", "relative", "uniform", 32 - ).endswith("depth-anything-3/relative/uniform/32/scene.pkl") + assert config.cache_file("scene", "metric", "uniform", "no tracking", 64).endswith( + "metric/no tracking/uniform/64/scene.pkl.gz" + ) + assert config.da3_cache_file("scene", "relative", "uniform", 32).endswith( + "depth-anything-3/relative/uniform/32/scene.pkl" + ) assert config.spatial_code_path( "scene", "metric", "selective", "tracking", 64 ).endswith("metric/tracking/selective/64/explicit/scene.json") @@ -29,7 +29,9 @@ def test_encoder_paths_reject_unknown_spatial_code_format(): ) -def test_ground_truth_paths_have_no_depth_tracking_input_frames_axis(tmp_path, monkeypatch): +def test_ground_truth_paths_have_no_depth_tracking_input_frames_axis( + tmp_path, monkeypatch +): monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "codes") assert config.ground_truth_spatial_code_path("scene", "explicit").endswith( "codes/ground truth/explicit/scene.json" diff --git a/tests/test_encoder/test_init.py b/tests/test_encoder/test_init.py new file mode 100644 index 0000000000000000000000000000000000000000..e8b95cf73b1554ca88509c5a76ea2c9943627a0c --- /dev/null +++ b/tests/test_encoder/test_init.py @@ -0,0 +1,7 @@ +"""Tests for encoder package importability.""" + +import encoder + + +def test_encoder_package_imports_without_data_or_checkpoints(): + assert encoder.__doc__ == "Spatial-code encoder package." diff --git a/tests/test_encoder/test_run.py b/tests/test_encoder/test_run.py index 2c27865d227485b2c5d0928327f662600cfb35ab..a8ce9d98dfd6433d955cf3d7a3084b914fe9aa70 100644 --- a/tests/test_encoder/test_run.py +++ b/tests/test_encoder/test_run.py @@ -2,5 +2,6 @@ from encoder import run + def test_cache_or_load_exposes_explicit_dimensions(): assert "frame_count" in run.cache_or_load.__code__.co_varnames diff --git a/tests/test_inference/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc b/tests/test_inference/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc index 16241db250347981ee67d308573f6e04321b7fc9..235e0fe7ccc5946382b6388fd3c46fb2c9de5062 100644 Binary files a/tests/test_inference/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc and b/tests/test_inference/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_inference/__pycache__/test_inference.cpython-311-pytest-9.1.1.pyc b/tests/test_inference/__pycache__/test_inference.cpython-311-pytest-9.1.1.pyc index 466345c59824646386407e18578e23e5f60d7b7e..4150dbc41770a7c6fd9579726328dc1c3c0b1c58 100644 Binary files a/tests/test_inference/__pycache__/test_inference.cpython-311-pytest-9.1.1.pyc and b/tests/test_inference/__pycache__/test_inference.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_inference/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc b/tests/test_inference/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0571712ee2d31bbdaba56c47b342214c6417eb9 Binary files /dev/null and b/tests/test_inference/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_inference/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc b/tests/test_inference/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc index 324bfc814d340d5ab6d715b4ac7226cd28e6ffc1..ce3ccb79d6395a2fb01c644202c24e0e564dacd1 100644 Binary files a/tests/test_inference/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc and b/tests/test_inference/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_inference/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc b/tests/test_inference/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb068aa5c7cee82e281c21c4d30f498836575f05 Binary files /dev/null and b/tests/test_inference/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_inference/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc b/tests/test_inference/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc index dc308285fc77b43dcdab356b126a491b6247690b..776ffc5fe832412e598377c5b9e8e8daf16952dd 100644 Binary files a/tests/test_inference/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc and b/tests/test_inference/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_symbolic/__pycache__/test_launch.cpython-311.pyc b/tests/test_symbolic/__pycache__/test_launch.cpython-311.pyc index 093161660e199008634582cc948debdea47b0033..9b8041590ab27d9078b67aac1bedb4dcf66b4de6 100644 Binary files a/tests/test_symbolic/__pycache__/test_launch.cpython-311.pyc and b/tests/test_symbolic/__pycache__/test_launch.cpython-311.pyc differ