diff --git a/harness/A/__init__.py b/harness/A/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eda15f0f1aade5e7a3d291835028aab82388ae0f --- /dev/null +++ b/harness/A/__init__.py @@ -0,0 +1,54 @@ +"""Harness A: uniform/selective frame sampling + direct VLM inference calls. + +Mirrors the frame-selection vocabulary already used by ``inference`` (uniform vs. +selective) and the exact generation protocol VSI-Bench's own harness +(``thinking-in-space/lmms_eval/tasks/vsibench/vsibench.yaml``) evaluates every model +under: greedy decoding (``do_sample=False``, temperature 0) and a hard 16-token output +cap. Model weights live under ``MODELS_ROOT`` next to the other model checkpoints +(``depth-anything-3``, ``sam3``) this workspace already downloads there. +""" + +from __future__ import annotations + +import os +from pathlib import Path + +DATA_ROOT = Path(os.environ.get("VSI_DATA_ROOT", "/root/data")) +MODELS_ROOT = Path(os.environ.get("VSI_MODELS_ROOT", "/root/models")) +VSI_ROOT = Path(os.environ.get("VSI_ROOT", DATA_ROOT / "VSI-Bench")) +JSONL = Path(os.environ.get("VSI_JSONL", VSI_ROOT / "test.jsonl")) +WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent +# One JSON per question, matching the layout results/symbolic/... already uses: +# results/A/////.json +RESULTS_DIR = Path( + os.environ.get("VSI_HARNESS_RESULTS_DIR", WORKSPACE_ROOT / "results" / "A") +) + +# Same two selection strategies and vocabulary as inference.SAM3_FRAME_SELECTIONS: +# "uniform" (evenly spaced indices) or "selective" (the quality/redundancy/motion- +# filtered keyframe selector in inference.adapters, algorithm 5 by default). +FRAME_SELECTIONS = ("uniform", "selective") +DEFAULT_FRAME_SELECTION = "uniform" +FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_FRAMES_PER_VIDEO", "32")) + +# Fixed by the VSI-Bench protocol (vsibench.yaml generation_kwargs) -- not configurable +# per call, since comparing models under different decoding settings would be meaningless. +MAX_NEW_TOKENS = 16 +TEMPERATURE = 0.0 +DO_SAMPLE = False + +# Extended-budget generation (VLMAdapter.answer_extended, harness.B/C's default protocol +# and harness.A's opt-in --extended flag): a much larger first-pass budget for the model +# to work through the input before answering, with a short forced second call only if it +# didn't conclude (hit the budget without emitting an end-of-sequence token) in that +# first pass. The forced call reuses MAX_NEW_TOKENS (16) -- the same short-answer budget +# the base protocol already uses -- since its whole job is to extract one terse answer, +# not to reason further. +EXTENDED_MAX_NEW_TOKENS = 2048 +FORCE_ANSWER_PROMPT = "\nFinal answer:" + +MODEL_PATHS = { + "qwen3.5-4b": MODELS_ROOT / "qwen3.5-4b", + "qwen3.5-2b": MODELS_ROOT / "qwen3.5-2b", + "internvl3.5-4b": MODELS_ROOT / "internvl3.5-4b", +} diff --git a/harness/A/__pycache__/__init__.cpython-311.pyc b/harness/A/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0508ef598573a3b8a81ded2be42df34f68e54e49 Binary files /dev/null and b/harness/A/__pycache__/__init__.cpython-311.pyc differ diff --git a/harness/A/__pycache__/frames.cpython-311.pyc b/harness/A/__pycache__/frames.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..956ea2542fc1803b6e8f93668befaf82200b1ebe Binary files /dev/null and b/harness/A/__pycache__/frames.cpython-311.pyc differ diff --git a/harness/A/__pycache__/launch.cpython-311.pyc b/harness/A/__pycache__/launch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01f55c4c783f264a2eb70841b2704c13850282b9 Binary files /dev/null and b/harness/A/__pycache__/launch.cpython-311.pyc differ diff --git a/harness/A/__pycache__/models.cpython-311.pyc b/harness/A/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac5fc2496c3a63459ddeb9601bc5f4bac17bc1ae Binary files /dev/null and b/harness/A/__pycache__/models.cpython-311.pyc differ diff --git a/harness/A/__pycache__/prompts.cpython-311.pyc b/harness/A/__pycache__/prompts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70b45c83cfd1a386b55eb27782f95f142132cd34 Binary files /dev/null and b/harness/A/__pycache__/prompts.cpython-311.pyc differ diff --git a/harness/A/__pycache__/run.cpython-311.pyc b/harness/A/__pycache__/run.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60361ef4d293a2690a0946904d10d5b391844e2f Binary files /dev/null and b/harness/A/__pycache__/run.cpython-311.pyc differ diff --git a/harness/A/__pycache__/sweep.cpython-311.pyc b/harness/A/__pycache__/sweep.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c44e70d568a5b01c8a19b8562e6cd8fccc243bf Binary files /dev/null and b/harness/A/__pycache__/sweep.cpython-311.pyc differ diff --git a/harness/A/frames.py b/harness/A/frames.py new file mode 100644 index 0000000000000000000000000000000000000000..551ebaf8b79840f7235146e3b00ae2d9b0a89e4a --- /dev/null +++ b/harness/A/frames.py @@ -0,0 +1,54 @@ +"""Uniform / selective frame sampling for direct VLM calls. + +Reuses ``inference.adapters._sample_video_frames`` -- the exact same decoder every +other model adapter in this workspace (DA3, SAM3, SegVGGT) already samples through -- +so "uniform" and "selective" behave identically here and there, and the selective +(smart) keyframe indices share that module's on-disk cache instead of being recomputed. +""" + +from __future__ import annotations + +from pathlib import Path + +import cv2 +from PIL import Image + +from harness.A import FRAME_SELECTIONS +from inference.adapters import _sample_video_frames + + +def sample_frames(video_path, frame_count, frame_selection): + """Return (``frame_count`` RGB frames as PIL images, their video timestamps in + seconds, their raw integer frame indices). + + ``frame_selection="uniform"`` takes evenly spaced indices across the whole video. + ``frame_selection="selective"`` (the "smart" mode) takes the quality/redundancy/ + motion-filtered keyframe indices from ``inference.adapters.select_video_frame_indices``, + downsampled to ``frame_count`` if the selector kept more frames than requested. + Both timestamps and indices are returned (not discarded) so callers can log exactly + which frames of the source video were fed to a model, for full-provenance result + records -- indices are exact (unlike timestamps, which lose precision through the + index/fps conversion _sample_video_frames itself performs). + """ + if frame_selection not in FRAME_SELECTIONS: + raise ValueError( + f"unknown frame selection {frame_selection!r}; expected one of {FRAME_SELECTIONS}" + ) + if frame_count < 1: + raise ValueError("frame_count must be positive") + if not Path(video_path).is_file(): + raise FileNotFoundError(f"video not found: {video_path}") + frames, times = _sample_video_frames(video_path, frame_count, frame_selection) + capture = cv2.VideoCapture(video_path) + try: + fps = capture.get(cv2.CAP_PROP_FPS) or 1.0 + finally: + capture.release() + # Inverse of the exact index/fps conversion _sample_video_frames applies, so this + # recovers the original integer indices without redoing frame selection. + indices = [int(round(float(t) * fps)) for t in times] + return ( + [Image.fromarray(frame) for frame in frames], + [float(t) for t in times], + indices, + ) diff --git a/harness/A/launch.py b/harness/A/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..f16f74cc4689fcc5f8ec2e33358b67ba8965423a --- /dev/null +++ b/harness/A/launch.py @@ -0,0 +1,224 @@ +"""Keep every visible GPU busy with persistent harness-A inference workers. + +Same shape as ``inference/launch.py``: one persistent worker process per visible GPU, +pulling scenes off a shared queue, each loading its model exactly once and reusing it +for every scene it's assigned (via ``run.run(..., adapter=...)``) instead of paying the +load cost per scene. One invocation covers one (model, frame_selection, frame_count) +triple across every requested scene; sweep multiple triples by invoking this once per +triple (a shell loop), exactly how ``inference/launch.py`` is invoked once per mode. +""" + +from __future__ import annotations + +import argparse +import importlib.util +import json +import multiprocessing as mp +import os +from pathlib import Path +import sys +import traceback + +HERE = Path(__file__).resolve().parent +WORKSPACE_ROOT = HERE.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +from harness.A import ( # noqa: E402 + DEFAULT_FRAME_SELECTION, + EXTENDED_MAX_NEW_TOKENS, + FRAME_SELECTIONS, + FRAMES_PER_VIDEO, + JSONL, + MAX_NEW_TOKENS, +) +from harness.A import models as vlm_models # noqa: E402 +from inference.launch import available_cpu_count, visible_gpus # noqa: E402 + + +def _load_run_module(): + spec = importlib.util.spec_from_file_location("_harness_A_run", HERE / "run.py") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return 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)) + + +def _worker( + tasks, results, model, frame_selection, frame_count, 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"): + os.environ[variable] = str(cpu_threads) + import cv2 + + cv2.setNumThreads(cpu_threads) + run = _load_run_module() + adapter = None + load_error = None + try: + adapter = vlm_models.get_adapter(model) + adapter.load_model("cuda:0" if gpu is not None else "cpu") + except Exception: + load_error = traceback.format_exc() + while True: + scene = tasks.get() + if scene is None: + return + if load_error is not None: + results.put((scene, False, load_error)) + continue + try: + answered = run.run( + model, + frame_selection=frame_selection, + frame_count=frame_count, + scene=scene, + results_dir=results_dir, + adapter=adapter, + extended=extended, + reasoning_budget=reasoning_budget, + force_budget=force_budget, + ) + mean_score = ( + sum(r["score"] for r in answered) / len(answered) if answered else None + ) + results.put( + (scene, True, f"{len(answered)} question(s), mean_score={mean_score}") + ) + except Exception: + results.put((scene, False, traceback.format_exc())) + + +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, +): + """Answer every question for ``selected`` scenes, sharded across every visible GPU.""" + condition = f"{model}/{frame_selection}/{frame_count}" + run = _load_run_module() + root = run.results_dir_for(model, 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 answered and not rebuild: + completed += 1 + print(f"[{condition} {completed}/{len(selected)}] {scene}: skipped", flush=True) + else: + pending.append(scene) + if not pending: + print(f"[{condition}] DONE: {len(selected)} ok, 0 failed") + return + + gpus = visible_gpus() + worker_count = min(len(pending), len(gpus) if gpus else 1) + assignments = gpus[:worker_count] if gpus else [None] + cpu_count = available_cpu_count() + cpu_threads = max(1, cpu_count // worker_count) + print( + f"[{condition}] starting {worker_count} persistent worker(s); " + f"GPUs={assignments}; CPU threads/worker={cpu_threads}", + flush=True, + ) + + context = mp.get_context("spawn") + tasks, results = context.Queue(), context.Queue() + for scene in pending: + tasks.put(scene) + for _ in range(worker_count): + tasks.put(None) + workers = [ + context.Process( + target=_worker, + args=( + tasks, results, model, frame_selection, frame_count, results_dir, + gpu, cpu_threads, extended, reasoning_budget, force_budget, + ), + ) + for gpu in assignments + ] + for worker in workers: + worker.start() + failed = [] + for finished in range(1, len(pending) + 1): + scene, ok, detail = results.get() + if not ok: + failed.append(scene) + print( + f"[{condition} {completed + finished}/{len(selected)}] {scene}: " + f"{'done' if ok else 'FAILED'}\n{detail}", + flush=True, + ) + for worker in workers: + worker.join() + print( + f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, " + f"{len(failed)} failed" + ) + if failed: + raise SystemExit(1) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("scene", nargs="?") + parser.add_argument( + "--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, + dest="frame_selection", + ) + parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO) + parser.add_argument("--results-dir", default=None) + parser.add_argument("--rebuild", action="store_true") + parser.add_argument( + "--extended", + action="store_true", + help=( + f"use a {EXTENDED_MAX_NEW_TOKENS}-token reasoning budget instead of the fixed " + f"{MAX_NEW_TOKENS}-token VSI-Bench protocol, with a short forced second call " + "only if the model doesn't conclude within it" + ), + ) + parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) + parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) + args = parser.parse_args() + if args.scene and args.scenes: + parser.error("positional scene and --scenes cannot be used together") + if args.scenes is not None: + selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()] + if not selected: + parser.error("--scenes must contain at least one scene") + selected = list(dict.fromkeys(selected)) + else: + selected = [args.scene] if args.scene else scenes() + if args.frames < 1: + parser.error("--frames must be positive") + if args.reasoning_budget < 1: + parser.error("--reasoning-budget must be positive") + if args.force_budget < 1: + parser.error("--force-budget must be positive") + 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, + ) + + +if __name__ == "__main__": + main() diff --git a/harness/A/models.py b/harness/A/models.py new file mode 100644 index 0000000000000000000000000000000000000000..282c7dd49b51302e9f06604a8323cf26aed3530c --- /dev/null +++ b/harness/A/models.py @@ -0,0 +1,343 @@ +"""Model adapters: load one VLM, answer one (frames, prompt) pair, greedy-decoded. + +Same ``load_model`` / one-call-per-question shape as ``inference.adapters.InferenceAdapter``, +but returning generated text instead of preserving a native raw-feature cache. Every +adapter is forced to the fixed VSI-Bench decoding protocol from ``harness.A`` +(``do_sample=False``, 16 new tokens) -- callers cannot override it, since comparing +models under different decoding settings defeats the point of a shared harness. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from pathlib import Path + +from harness.A import ( + DO_SAMPLE, + EXTENDED_MAX_NEW_TOKENS, + FORCE_ANSWER_PROMPT, + MAX_NEW_TOKENS, + MODEL_PATHS, + TEMPERATURE, +) + + +def _numbered_content(frames, question): + """Interleave "Frame N:" labels with each image, then the question text. + + Numbering frames (not just concatenating raw images) is the documented convention + for multi-image/video prompting with both model families here -- it is the only way + the model can recover frame ORDER, which several VSI-Bench question types + (obj_appearance_order, route_planning) directly depend on. + """ + content = [] + for index, frame in enumerate(frames, start=1): + content.append({"type": "text", "text": f"Frame {index}:"}) + content.append({"type": "image", "image": frame}) + content.append({"type": "text", "text": question}) + return content + + +class VLMAdapter(ABC): + """Common interface implemented by every direct-inference VLM adapter.""" + + def __init__(self, model_path=None): + self.model_path = Path(model_path) + self.model = None + self.processor = None + self.device = None + self.dtype = None + + @abstractmethod + def load_model(self, device="cuda"): + """Load model + processor weights once for repeated ``answer`` calls.""" + + @abstractmethod + def answer(self, frames, question): + """Return a full, untruncated record of one greedy-decoded response. + + Every field a downstream result file needs is produced here, not reconstructed + later: the literal rendered prompt text, both the cleaned and fully raw decoded + response, the actual generated token ids/count, whether the token budget cut the + response off before a natural stop, and the exact generation config used. + """ + + @abstractmethod + 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 + second call -- continuing the exact same generation, not a new turn -- asks for + the final answer directly. Always records the full, untruncated first-pass text + too (``reasoning_text``), even when a forced second call supplies the answer + actually used for scoring. + """ + + def unload(self): + """Free GPU memory so another adapter can be loaded in its place.""" + import torch + + self.model = None + self.processor = None + torch.cuda.empty_cache() + + +class _TransformersVLMAdapter(VLMAdapter): + """Shared load/generate path for HF ``AutoModelForImageTextToText`` checkpoints.""" + + chat_template_kwargs = {} + + def load_model(self, device="cuda"): + import torch + from transformers import AutoModelForImageTextToText, AutoProcessor + + if not self.model_path.is_dir(): + raise FileNotFoundError(f"model not found: {self.model_path}") + self.device = device + self.dtype = torch.bfloat16 + self.processor = AutoProcessor.from_pretrained( + str(self.model_path), trust_remote_code=True + ) + self.model = ( + AutoModelForImageTextToText.from_pretrained( + str(self.model_path), dtype=self.dtype, trust_remote_code=True + ) + .eval() + .to(device) + ) + + def _build_inputs(self, frames, question): + """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, + ) + inputs = self.processor.apply_chat_template( + 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 + # token id, and still shows exactly how much visual input the model actually received. + vision_input_shapes = { + key: list(value.shape) + for key, value in inputs.items() + if key not in ("input_ids", "attention_mask") and hasattr(value, "shape") + } + return prompt_text, inputs, vision_input_shapes + + def _eos_ids(self): + eos_ids = self.model.generation_config.eos_token_id + if eos_ids is None: + eos_ids = self.processor.tokenizer.eos_token_id + return [eos_ids] if isinstance(eos_ids, int) else list(eos_ids or []) + + def _generate(self, inputs, max_new_tokens): + """Run one greedy generate() call. Returns (full sequence, elapsed seconds).""" + import time + + import torch + + 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, + ) + if self.device.startswith("cuda"): + torch.cuda.synchronize() + return generated, time.monotonic() - start + + 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) + ) + 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 + + def _library_versions(self): + import torch + import transformers + + return {"transformers": transformers.__version__, "torch": torch.__version__} + + def answer(self, frames, question): + if self.model is None or self.processor is None: + raise RuntimeError("load_model() must be called before answer()") + prompt_text, inputs, vision_input_shapes = self._build_inputs(frames, question) + input_token_count = int(inputs["input_ids"].shape[1]) + generated, generation_seconds = self._generate(inputs, MAX_NEW_TOKENS) + eos_ids = self._eos_ids() + output_token_ids, hit_token_limit, answer_text, answer_raw = self._decode_new_tokens( + generated, input_token_count, MAX_NEW_TOKENS, eos_ids + ) + + return { + "prompt_text": prompt_text, + "answer_text": answer_text, + "answer_raw": answer_raw, + "input_token_count": input_token_count, + "vision_input_shapes": vision_input_shapes, + "output_token_ids": output_token_ids, + "output_token_count": len(output_token_ids), + "hit_token_limit": hit_token_limit, + "eos_token_ids": eos_ids, + "generation_seconds": generation_seconds, + "device": self.device, + "dtype": str(self.dtype).removeprefix("torch."), + "library_versions": self._library_versions(), + "generation_config": { + "max_new_tokens": MAX_NEW_TOKENS, + "do_sample": DO_SAMPLE, + "temperature": TEMPERATURE, + "top_p": None, + "top_k": None, + **self.chat_template_kwargs, + }, + } + + 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: + raise RuntimeError("load_model() must be called before answer_extended()") + prompt_text, inputs, vision_input_shapes = self._build_inputs(frames, question) + input_token_count = int(inputs["input_ids"].shape[1]) + eos_ids = self._eos_ids() + + 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) + ) + + forced = reasoning_hit_limit + generation_seconds = reasoning_seconds + if forced: + # Continue the SAME generation (not a new chat turn): the model's own partial + # response, plus an explicit instruction to answer now, then a short second + # 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_prompt_ids = self.processor.tokenizer( + FORCE_ANSWER_PROMPT, return_tensors="pt", add_special_tokens=False + )["input_ids"].to(self.device) + continued_ids = torch.cat([generated, force_prompt_ids], dim=1) + continued_mask = torch.ones_like(continued_ids) + added_length = int(continued_ids.shape[1]) - input_token_count + continued_inputs = {} + for key, value in inputs.items(): + if key in ("input_ids", "attention_mask"): + continue + # Per-token multimodal metadata (e.g. Qwen's mm_token_type_ids) is sized to + # the ORIGINAL prompt length and must grow with it; every newly generated + # token (reasoning + the force prompt) is plain text, never an image + # 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:])) + 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 + ) + generation_seconds += forced_seconds + else: + forced_input_token_count = None + output_token_ids, hit_token_limit = reasoning_token_ids, reasoning_hit_limit + answer_text, answer_raw = reasoning_text, reasoning_raw + + return { + "prompt_text": prompt_text, + "answer_text": answer_text, + "answer_raw": answer_raw, + "input_token_count": input_token_count, + "vision_input_shapes": vision_input_shapes, + "output_token_ids": output_token_ids, + "output_token_count": len(output_token_ids), + "hit_token_limit": hit_token_limit, + "eos_token_ids": eos_ids, + "generation_seconds": generation_seconds, + "device": self.device, + "dtype": str(self.dtype).removeprefix("torch."), + "library_versions": self._library_versions(), + "generation_config": { + "max_new_tokens": reasoning_budget, + "force_answer_max_new_tokens": force_budget, + "do_sample": DO_SAMPLE, + "temperature": TEMPERATURE, + "top_p": None, + "top_k": None, + **self.chat_template_kwargs, + }, + "reasoning_text": reasoning_text, + "reasoning_raw": reasoning_raw, + "reasoning_token_ids": reasoning_token_ids, + "reasoning_token_count": len(reasoning_token_ids), + "reasoning_hit_limit": reasoning_hit_limit, + "forced": forced, + "forced_input_token_count": forced_input_token_count, + } + + +class QwenVLAdapter(_TransformersVLMAdapter): + """Qwen3.5 (image-text-to-text): used for both the 4B and 2B checkpoints. + + ``enable_thinking=False`` is required, not optional -- Qwen3.5's chat template + defaults to opening an unclosed ```` block before the answer, which would + consume the entire 16-token budget on reasoning preamble and never emit an answer. + """ + + chat_template_kwargs = {"enable_thinking": False} + + +class InternVLAdapter(_TransformersVLMAdapter): + """InternVL3.5 (image-text-to-text). + + ``crop_to_patches=False`` is required, not optional -- InternVL's default image + processor dynamically tiles EACH image content item into up to ~13 sub-patches at + 448x448, meant for one high-resolution photo. Applied per FRAME (our multi-image + prompting, one item per frame -- see ``_numbered_content``), that explodes the + prompt to ~3300 tokens/frame; just 16 frames already exceeds this checkpoint's + 40960-token context window before generation can even start. Disabling tiling + drops that to ~265 tokens/frame (measured: 16 frames 53401 -> 4251 tokens), + letting every frame count up to 96 fit comfortably. (The "correct" fix -- passing + frames as one native ``{"type": "video"}`` content item, which HF's own video + preprocessor handles at a similarly low per-frame cost without this flag -- hits + an unrelated shape-mismatch bug in this transformers version's InternVL vision + pixel-shuffle path; this is the working equivalent, not a workaround of our own + logic.) + """ + + chat_template_kwargs = {"crop_to_patches": False} + + +_ADAPTERS = { + "qwen3.5-4b": QwenVLAdapter, + "qwen3.5-2b": QwenVLAdapter, + "internvl3.5-4b": InternVLAdapter, +} + + +def available_models(): + """Return registered model names in stable order.""" + return tuple(sorted(_ADAPTERS)) + + +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()}") + return adapter_type(MODEL_PATHS[model]) diff --git a/harness/A/prompts.py b/harness/A/prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..ba7c581faf17d48ede67172a55da6f40ed8393bd --- /dev/null +++ b/harness/A/prompts.py @@ -0,0 +1,47 @@ +"""VSI-Bench prompt construction -- reproduces lmms_eval's own protocol exactly. + +Mirrors ``thinking-in-space/lmms_eval/tasks/vsibench/utils.py::vsibench_doc_to_text`` +and ``vsibench.yaml``'s ``lmms_eval_specific_kwargs.default`` profile verbatim (the +profile every non-API model, including local HF checkpoints, is scored under): the +same question-type split, the same pre/post prompt text, the same "\\n".join layout. +""" + +from __future__ import annotations + +# Verbatim from thinking-in-space/lmms_eval/tasks/vsibench/utils.py. +MCA_QUESTION_TYPES = ( + "object_rel_direction_easy", + "object_rel_direction_medium", + "object_rel_direction_hard", + "object_rel_distance", + "route_planning", + "obj_appearance_order", +) +NA_QUESTION_TYPES = ( + "object_abs_distance", + "object_counting", + "object_size_estimation", + "room_size_estimation", +) + +# vsibench.yaml lmms_eval_specific_kwargs.default. pre_prompt is "" in the yaml, which +# the original doc_to_text treats as falsy and falls back to this text -- so this is +# the pre_prompt every non-API (incl. local HF) model is actually scored under. +PRE_PROMPT = "These are frames of a video." +NA_POST_PROMPT = "Please answer the question using a single word or phrase." +MCA_POST_PROMPT = "Answer with the option's letter from the given choices directly." + + +def build_prompt(question_type, question, options=None): + """Return the exact text prompt lmms_eval would send for one VSI-Bench question.""" + if question_type in NA_QUESTION_TYPES: + return PRE_PROMPT + "\n" + question + "\n" + NA_POST_PROMPT + if question_type in MCA_QUESTION_TYPES: + 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, 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/A/run.py b/harness/A/run.py new file mode 100644 index 0000000000000000000000000000000000000000..af11e58bc7799c684fe0c355f3189ebe6faff8a5 --- /dev/null +++ b/harness/A/run.py @@ -0,0 +1,339 @@ +"""Run one VLM over VSI-Bench questions through harness A's frame sampling + adapters. + +Writes one JSON file per question -- the same one-file-per-question layout +``symbolic/run.py`` uses for the spatial-code pipeline -- with the FULL, untruncated +record: the exact prompt text sent, the cleaned and fully raw decoded response, the +actual output token ids/count, whether the 16-token budget cut generation off before a +natural stop, the exact generation config used, per-question latency, and full +provenance (video path, frame indices/timestamps, device/dtype, library versions). +Nothing here is summarized or truncated for display; printing to stdout is a separate, +lossy convenience only. + +Scoring reuses the real, unmodified official scorer +(``thinking-in-space/lmms_eval/tasks/vsibench/utils.py``), the same convention +``symbolic/run.py`` already follows, so results here are directly comparable to those. +""" + +from __future__ import annotations + +import argparse +import importlib.util +import json +import os +import sys +from pathlib import Path + +WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +import inference as inference_config # noqa: E402 +from harness.A import ( # noqa: E402 + DEFAULT_FRAME_SELECTION, + EXTENDED_MAX_NEW_TOKENS, + FRAME_SELECTIONS, + FRAMES_PER_VIDEO, + JSONL, + MAX_NEW_TOKENS, + RESULTS_DIR, +) +from harness.A import frames as frame_sampling # noqa: E402 +from harness.A import models as vlm_models # noqa: E402 +from harness.A import prompts as vsi_prompts # noqa: E402 + +_OFFICIAL_EVAL = os.environ.get( + "HARNESS_OFFICIAL_EVAL", + "/root/data/thinking-in-space/lmms_eval/tasks/vsibench/utils.py", +) + + +def _load_official_eval(path): + # Loaded under a unique module name (not the bare "utils" symbolic/run.py itself + # uses) so the two never fight over sys.modules["utils"] when both are imported in + # the same process, e.g. across the test suite. + spec = importlib.util.spec_from_file_location("harness_A_vsi_official_eval", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +vsi_official_eval = _load_official_eval(_OFFICIAL_EVAL) + + +def _scalar_score(question_type, score_doc): + """Return (metric_name, value) -- the one numeric metric attached by the scorer.""" + if question_type in vsi_official_eval.MCA_QUESTION_TYPES: + metric_keys = vsi_official_eval.METRICS_FOR_MCA + elif question_type in vsi_official_eval.NA_QUESTION_TYPES: + metric_keys = vsi_official_eval.METRICS_FOR_NA + else: + raise ValueError( + f"unknown question_type {question_type!r}; " + f"expected one of {vsi_official_eval.MCA_QUESTION_TYPES + vsi_official_eval.NA_QUESTION_TYPES}" + ) + (metric_key,) = metric_keys.keys() + return metric_key, score_doc[metric_key] + + +def load_questions(jsonl_path=None, scene=None, scenes=None, limit=None): + """Return VSI-Bench question rows, optionally filtered to one/many scenes / capped.""" + if scene is not None and scenes is not None: + raise ValueError("scene and scenes cannot both be given") + allowed = {scene} if scene is not None else (set(scenes) if scenes is not None else None) + jsonl_path = jsonl_path or JSONL + rows = [] + with open(jsonl_path) as stream: + for line in stream: + row = json.loads(line) + if allowed is not None and row["scene_name"] not in allowed: + continue + rows.append(row) + if limit is not None and len(rows) >= limit: + break + return rows + + +def results_dir_for(model, frame_selection, frame_count, results_dir=None): + """Return the result root isolated by model + frame-selection + frame-count.""" + if results_dir is not None: + return Path(results_dir) + return RESULTS_DIR / model / frame_selection / str(frame_count) + + +def _build_record(row, prompt, answer, metric_name, score, model, model_path, frame_info): + """Assemble one question's full, untruncated result record (nothing summarized).""" + return { + "model": model, + "model_path": str(model_path), + "device": answer["device"], + "dtype": answer["dtype"], + "library_versions": answer["library_versions"], + "condition": f"{frame_info['frame_selection']}:{frame_info['frame_count']}", + "frame_selection": frame_info["frame_selection"], + "frame_count": frame_info["frame_count"], + "video_path": frame_info["video_path"], + "frame_indices": frame_info["frame_indices"], + "frame_timestamps_seconds": frame_info["frame_timestamps"], + "scene": row["scene_name"], + "dataset": row.get("dataset"), + "question_id": row["id"], + "question_type": row["question_type"], + "question": row["question"], + "options": row.get("options"), + "full_prompt": prompt, + "rendered_prompt": answer["prompt_text"], + "answer_expected": row["ground_truth"], + "answer_given": answer["answer_text"], + "answer_raw": answer["answer_raw"], + "input_token_count": answer["input_token_count"], + "vision_input_shapes": answer["vision_input_shapes"], + "output_token_ids": answer["output_token_ids"], + "output_token_count": answer["output_token_count"], + "hit_token_limit": answer["hit_token_limit"], + "eos_token_ids": answer["eos_token_ids"], + "generation_seconds": answer["generation_seconds"], + "generation_config": answer["generation_config"], + "reasoning_text": answer.get("reasoning_text"), + "reasoning_raw": answer.get("reasoning_raw"), + "reasoning_token_ids": answer.get("reasoning_token_ids"), + "reasoning_token_count": answer.get("reasoning_token_count"), + "reasoning_hit_limit": answer.get("reasoning_hit_limit"), + "forced": answer.get("forced", False), + "forced_input_token_count": answer.get("forced_input_token_count"), + "metric": metric_name, + "score": score, + } + + +def write_question_result( + row, prompt, answer, metric_name, score, model, model_path, frame_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, frame_info + ) + root = results_dir_for( + model, frame_info["frame_selection"], frame_info["frame_count"], results_dir + ) + scene_dir = root / record["scene"] + scene_dir.mkdir(parents=True, exist_ok=True) + path = scene_dir / f"{row['id']}.json" + with path.open("w", encoding="utf-8") as stream: + json.dump(record, stream, indent=1) + return path, record + + +def run( + model, + frame_selection=DEFAULT_FRAME_SELECTION, + frame_count=FRAMES_PER_VIDEO, + scene=None, + scenes=None, + limit=None, + device="cuda", + jsonl_path=None, + results_dir=None, + write_results=True, + adapter=None, + extended=False, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, +): + """Answer every matching question with one model, scored via the official scorer. + + Each question's full record is written to its own JSON file as soon as it is + answered (unless ``write_results=False``); the in-memory list returned holds the + same full records for callers that want them without re-reading from disk. + + Pass a pre-loaded ``adapter`` (as ``harness.A.launch``'s persistent per-GPU workers + do) to reuse one already-loaded model across many calls instead of paying the load + cost per call; the caller then owns unloading it. Without one, ``run`` loads and + unloads its own adapter, same as before. + + ``extended=True`` switches from the fixed 16-token VSI-Bench protocol to + ``adapter.answer_extended`` -- a much larger first-pass budget (``reasoning_budget``) + with a short forced second call (``force_budget``) only if the model doesn't + conclude within it. Opt-in per call/CLI invocation, not a change to the default + protocol every other harness.A caller and test still exercises. + """ + rows = load_questions(jsonl_path, scene, scenes, limit) + if not rows: + return [] + owns_adapter = adapter is None + if owns_adapter: + adapter = vlm_models.get_adapter(model) + adapter.load_model(device) + frame_cache = {} + results = [] + try: + for row in rows: + scene_id = row["scene_name"] + if scene_id not in frame_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, frame_selection + ) + frame_cache[scene_id] = { + "video_path": video_path, + "frame_images": frame_images, + "frame_timestamps": frame_timestamps, + "frame_indices": frame_indices, + "frame_selection": frame_selection, + "frame_count": frame_count, + } + cached = frame_cache[scene_id] + prompt = vsi_prompts.build_prompt( + row["question_type"], row["question"], row.get("options") + ) + answer = ( + adapter.answer_extended( + cached["frame_images"], prompt, + reasoning_budget=reasoning_budget, force_budget=force_budget, + ) + if extended + else adapter.answer(cached["frame_images"], prompt) + ) + doc = {"question_type": row["question_type"], "ground_truth": row["ground_truth"]} + score_doc = vsi_official_eval.vsibench_process_results( + doc, [answer["answer_text"]] + )["vsibench_score"] + metric_name, score = _scalar_score(row["question_type"], score_doc) + frame_info = { + "video_path": cached["video_path"], + "frame_timestamps": cached["frame_timestamps"], + "frame_indices": cached["frame_indices"], + "frame_selection": frame_selection, + "frame_count": frame_count, + } + if write_results: + path, record = write_question_result( + row, prompt, answer, metric_name, score, model, adapter.model_path, + frame_info, results_dir, + ) + else: + path = None + record = _build_record( + row, prompt, answer, metric_name, score, model, adapter.model_path, frame_info + ) + record["result_path"] = str(path) if path else None + results.append(record) + finally: + if owns_adapter: + adapter.unload() + return results + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", required=True, choices=vlm_models.available_models()) + parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene") + parser.add_argument( + "--frame-selection", + default=DEFAULT_FRAME_SELECTION, + choices=FRAME_SELECTIONS, + dest="frame_selection", + ) + parser.add_argument("--frames", type=int, default=FRAMES_PER_VIDEO) + parser.add_argument("--limit", type=int, default=None, help="cap the number of questions") + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--results-dir", + default=None, + help="override the default results/A/// root", + ) + parser.add_argument( + "--no-write", + action="store_true", + help="skip writing per-question JSON files; print/score only", + ) + parser.add_argument( + "--extended", + action="store_true", + help=( + f"use a {EXTENDED_MAX_NEW_TOKENS}-token reasoning budget instead of the fixed " + f"{MAX_NEW_TOKENS}-token VSI-Bench protocol, with a short forced second call " + "only if the model doesn't conclude within it" + ), + ) + parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) + parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) + args = parser.parse_args() + if args.frames < 1: + parser.error("--frames must be positive") + if args.reasoning_budget < 1: + parser.error("--reasoning-budget must be positive") + if args.force_budget < 1: + parser.error("--force-budget must be positive") + + results = run( + args.model, + frame_selection=args.frame_selection, + frame_count=args.frames, + scene=args.scene, + limit=args.limit, + device=args.device, + results_dir=args.results_dir, + write_results=not args.no_write, + extended=args.extended, + reasoning_budget=args.reasoning_budget, + force_budget=args.force_budget, + ) + + for result in results: + print( + f"[{result['scene']}#{result['question_id']}] {result['question_type']}: " + f"pred={result['answer_given']!r} gt={result['answer_expected']!r} " + f"score={result['score']} ({result['generation_seconds']:.2f}s) -> " + f"{result['result_path']}" + ) + if results: + mean_score = sum(r["score"] for r in results) / len(results) + total_seconds = sum(r["generation_seconds"] for r in results) + print( + f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, " + f"total generation time={total_seconds:.1f}s" + ) + + +if __name__ == "__main__": + main() diff --git a/harness/A/sweep.py b/harness/A/sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..8b89ed62ead89b9687a74d0a3bad2b12bd52f9ce --- /dev/null +++ b/harness/A/sweep.py @@ -0,0 +1,127 @@ +"""Sweep any set of models x frame-selections x frame-counts, one command. + +Every (model, frame_selection, frame_count) triple in the sweep is run through +``harness.A.launch.launch`` in turn, so each triple individually saturates every +visible GPU (persistent per-GPU workers, one model load per worker, scenes sharded off +a shared queue) before the next triple starts. Triples aren't run concurrently with +each other -- each already uses every GPU on its own, so there is nothing to gain by +overlapping them, and it keeps peak GPU memory bounded to one model at a time. +""" + +from __future__ import annotations + +import argparse +from pathlib import Path +import sys + +HERE = Path(__file__).resolve().parent +WORKSPACE_ROOT = HERE.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +from harness.A import FRAME_SELECTIONS # noqa: E402 +from harness.A import launch as harness_launch # noqa: E402 +from harness.A import models as vlm_models # noqa: E402 + + +def _parse_csv_choice(value, valid, flag): + """Split a comma-separated ``--flag`` value; ``"all"`` expands to every ``valid``.""" + items = [item.strip() for item in value.split(",") if item.strip()] + if not items: + raise ValueError(f"{flag} must name at least one value") + if len(items) == 1 and items[0].lower() == "all": + 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')") + return list(dict.fromkeys(items)) + + +def _parse_frame_counts(value): + items = [item.strip() for item in value.split(",") if item.strip()] + if not items: + raise ValueError("--frames must name at least one frame count") + counts = [] + for item in items: + try: + count = int(item) + except ValueError: + raise ValueError(f"--frames value {item!r} is not an integer") from None + if count < 1: + raise ValueError(f"--frames value {count} must be positive") + counts.append(count) + return list(dict.fromkeys(counts)) + + +def build_plan(models, frame_selections, frame_counts): + """Return every (model, frame_selection, frame_count) triple in the sweep, in a + stable, cheapest-first-ish order (frame count is the dominant cost driver, so + sorting by it surfaces comparable results across every model/selection soonest).""" + return [ + (model, selection, frame_count) + for frame_count in sorted(frame_counts) + for model in models + for selection in frame_selections + ] + + +def sweep(models, frame_selections, frame_counts, selected_scenes, results_dir=None, rebuild=False): + """Run every (model, frame_selection, frame_count) triple across all visible GPUs.""" + plan = build_plan(models, frame_selections, frame_counts) + for index, (model, frame_selection, frame_count) in enumerate(plan, start=1): + print(f"=== sweep {index}/{len(plan)}: {model}/{frame_selection}/{frame_count} ===", flush=True) + harness_launch.launch( + model, frame_selection, frame_count, selected_scenes, + results_dir=results_dir, rebuild=rebuild, + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("scene", nargs="?") + parser.add_argument( + "--scenes", help="comma-separated scenes (cannot be combined with positional scene)" + ) + parser.add_argument( + "--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", + help=f"comma-separated selections (or 'all'); one of {FRAME_SELECTIONS}", + ) + parser.add_argument( + "--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") + args = parser.parse_args() + if args.scene and args.scenes: + parser.error("positional scene and --scenes cannot be used together") + + try: + models = _parse_csv_choice(args.models, vlm_models.available_models(), "--models") + frame_selections = _parse_csv_choice( + args.frame_selections, FRAME_SELECTIONS, "--frame-selections" + ) + frame_counts = _parse_frame_counts(args.frames) + except ValueError as exc: + parser.error(str(exc)) + + if args.scenes is not None: + selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()] + if not selected: + parser.error("--scenes must contain at least one scene") + selected = list(dict.fromkeys(selected)) + else: + 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, + ) + + +if __name__ == "__main__": + main() diff --git a/harness/B/__init__.py b/harness/B/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..66db02b12df9791836e9ae792dd61b380f00e88b --- /dev/null +++ b/harness/B/__init__.py @@ -0,0 +1,42 @@ +"""Harness B: route a scene's on-disk spatial code (explicit or compact) -- as TEXT, +no video frames -- to all three models, for every VSI-Bench question. + +Reuses harness.A's model registry/adapters and fixed generation protocol exactly; only +what is fed to the model differs (spatial-code text instead of frame images). Results +are written in the identical per-question JSON shape harness.A uses, so B's records are +directly comparable to A's -- the frame-provenance fields are simply replaced with +spatial-code provenance fields (see harness.B.run._build_record). +""" + +from __future__ import annotations + +import os +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 + +# Same two on-disk spatial-code schemas encoder/geometric.py can build. +SPATIAL_CODE_FORMATS = ("explicit", "compact") +DEFAULT_SPATIAL_CODE_FORMAT = "explicit" + +# Same vocabulary as inference.SAM3_FRAME_SELECTIONS / harness.A.FRAME_SELECTIONS -- +# which raw video sampling the on-disk spatial code was itself built from. +INPUT_SELECTIONS = ("uniform", "selective") +DEFAULT_INPUT_SELECTION = "uniform" + +# Same depth/tracking vocabulary encoder.config uses to lay out spatial codes on disk -- +# real sweepable axes here too (see sweep.py's --depths/--trackings), not fixed +# constants; DEFAULT_DEPTH/DEFAULT_TRACKING are just the single-value default when a +# caller doesn't ask to sweep them, matching this workspace's shipped production config. +DEFAULT_DEPTH = "metric" +DEFAULT_TRACKING = "tracking" + +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", WORKSPACE_ROOT / "results" / "B") +) diff --git a/harness/B/__pycache__/__init__.cpython-311.pyc b/harness/B/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2afcc42e3c7ca9bc6003e98a7255ef616852388f Binary files /dev/null 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 new file mode 100644 index 0000000000000000000000000000000000000000..9a9e313ab8d6f206f5607fbab66b86e0e2c507db Binary files /dev/null and b/harness/B/__pycache__/launch.cpython-311.pyc differ diff --git a/harness/B/__pycache__/prompts.cpython-311.pyc b/harness/B/__pycache__/prompts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77c713593ab6f127d28df4aab23473d4c0fc5a9f Binary files /dev/null and b/harness/B/__pycache__/prompts.cpython-311.pyc differ diff --git a/harness/B/__pycache__/run.cpython-311.pyc b/harness/B/__pycache__/run.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1277f1ad809cbcb27b4a26f76a436b88fcd34ba Binary files /dev/null and b/harness/B/__pycache__/run.cpython-311.pyc differ diff --git a/harness/B/__pycache__/spatial_codes.cpython-311.pyc b/harness/B/__pycache__/spatial_codes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e87aa44c5ff2823c9092a3cf016d9ebf4807f9e Binary files /dev/null and b/harness/B/__pycache__/spatial_codes.cpython-311.pyc differ diff --git a/harness/B/__pycache__/sweep.cpython-311.pyc b/harness/B/__pycache__/sweep.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c59a5d6c97993337f5e07a3083a9655ce74d5f0a Binary files /dev/null and b/harness/B/__pycache__/sweep.cpython-311.pyc differ diff --git a/harness/B/launch.py b/harness/B/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..ffe9c546944062ec1b89d4bd7150d2172497a50d --- /dev/null +++ b/harness/B/launch.py @@ -0,0 +1,218 @@ +"""Keep every visible GPU busy with persistent harness-B inference workers. + +Same shape as ``harness.A.launch``: one persistent worker process per visible GPU, +pulling scenes off a shared queue, each loading its model exactly once and reusing it +for every scene it's assigned (via ``run.run(..., adapter=...)``). One invocation covers +one (model, spatial_code_format, input_selection, frame_count) quadruple across every +requested scene; sweep multiple quadruples by invoking this once per quadruple (see +harness.B.sweep, or a shell loop). +""" + +from __future__ import annotations + +import argparse +import importlib.util +import multiprocessing as mp +import os +from pathlib import Path +import sys +import traceback + +HERE = Path(__file__).resolve().parent +WORKSPACE_ROOT = HERE.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402 +from harness.A import models as vlm_models # noqa: E402 +from harness.A.launch import scenes # noqa: E402 +from harness.B import ( # noqa: E402 + DEFAULT_DEPTH, + DEFAULT_INPUT_SELECTION, + DEFAULT_SPATIAL_CODE_FORMAT, + DEFAULT_TRACKING, + DEPTH_VARIANTS, + FRAMES_PER_VIDEO, + INPUT_SELECTIONS, + SPATIAL_CODE_FORMATS, + TRACKING_MODES, +) +from inference.launch import available_cpu_count, visible_gpus # noqa: E402 + + +def _load_run_module(): + spec = importlib.util.spec_from_file_location("_harness_B_run", HERE / "run.py") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _worker( + tasks, results, model, spatial_code_format, input_selection, frame_count, depth, tracking, + results_dir, gpu, cpu_threads, 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"): + os.environ[variable] = str(cpu_threads) + run = _load_run_module() + adapter = None + load_error = None + try: + adapter = vlm_models.get_adapter(model) + adapter.load_model("cuda:0" if gpu is not None else "cpu") + except Exception: + load_error = traceback.format_exc() + while True: + scene = tasks.get() + if scene is None: + return + if load_error is not None: + results.put((scene, False, load_error)) + continue + try: + answered = run.run( + model, + spatial_code_format=spatial_code_format, + input_selection=input_selection, + frame_count=frame_count, + depth=depth, + tracking=tracking, + scene=scene, + results_dir=results_dir, + adapter=adapter, + reasoning_budget=reasoning_budget, + force_budget=force_budget, + ) + mean_score = ( + sum(r["score"] for r in answered) / len(answered) if answered else None + ) + results.put( + (scene, True, f"{len(answered)} question(s), mean_score={mean_score}") + ) + except Exception: + results.put((scene, False, traceback.format_exc())) + + +def launch( + model, spatial_code_format, input_selection, frame_count, selected, + depth=DEFAULT_DEPTH, tracking=DEFAULT_TRACKING, results_dir=None, rebuild=False, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, +): + """Answer every question for ``selected`` scenes, sharded across every visible GPU.""" + condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count}" + run = _load_run_module() + root = run.results_dir_for( + model, spatial_code_format, depth, tracking, input_selection, frame_count, results_dir + ) + 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 answered and not rebuild: + completed += 1 + print(f"[{condition} {completed}/{len(selected)}] {scene}: skipped", flush=True) + else: + pending.append(scene) + if not pending: + print(f"[{condition}] DONE: {len(selected)} ok, 0 failed") + return + + gpus = visible_gpus() + worker_count = min(len(pending), len(gpus) if gpus else 1) + assignments = gpus[:worker_count] if gpus else [None] + cpu_count = available_cpu_count() + cpu_threads = max(1, cpu_count // worker_count) + print( + f"[{condition}] starting {worker_count} persistent worker(s); " + f"GPUs={assignments}; CPU threads/worker={cpu_threads}", + flush=True, + ) + + context = mp.get_context("spawn") + tasks, results = context.Queue(), context.Queue() + for scene in pending: + tasks.put(scene) + for _ in range(worker_count): + tasks.put(None) + workers = [ + context.Process( + target=_worker, + args=( + tasks, results, model, spatial_code_format, input_selection, frame_count, + depth, tracking, results_dir, gpu, cpu_threads, reasoning_budget, force_budget, + ), + ) + for gpu in assignments + ] + for worker in workers: + worker.start() + failed = [] + for finished in range(1, len(pending) + 1): + scene, ok, detail = results.get() + if not ok: + failed.append(scene) + print( + f"[{condition} {completed + finished}/{len(selected)}] {scene}: " + f"{'done' if ok else 'FAILED'}\n{detail}", + flush=True, + ) + for worker in workers: + worker.join() + print( + f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, " + f"{len(failed)} failed" + ) + if failed: + raise SystemExit(1) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("scene", nargs="?") + parser.add_argument( + "--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", + ) + parser.add_argument( + "--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("--results-dir", default=None) + parser.add_argument("--rebuild", action="store_true") + parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) + parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) + args = parser.parse_args() + if args.scene and args.scenes: + parser.error("positional scene and --scenes cannot be used together") + if args.scenes is not None: + selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()] + if not selected: + parser.error("--scenes must contain at least one scene") + selected = list(dict.fromkeys(selected)) + else: + selected = [args.scene] if args.scene else scenes() + if args.frames < 1: + parser.error("--frames must be positive") + if args.reasoning_budget < 1: + parser.error("--reasoning-budget must be positive") + if args.force_budget < 1: + parser.error("--force-budget must be positive") + 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, + reasoning_budget=args.reasoning_budget, force_budget=args.force_budget, + ) + + +if __name__ == "__main__": + main() diff --git a/harness/B/prompts.py b/harness/B/prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..88bef56606a1230fa114eaa483d7355551fd7fec --- /dev/null +++ b/harness/B/prompts.py @@ -0,0 +1,55 @@ +"""VSI-Bench prompt construction with a spatial code (as text) instead of video frames. + +Reuses harness.A.prompts's exact question-type split and post-prompts verbatim -- only +the pre-prompt context line changes (there are no frames to describe), and the spatial +code's own JSON text is inserted between that context line and the question. + +CODE_DESCRIPTION deliberately says nothing about where the code came from (not "based on +an analysis of a video", not "ground truth annotation") -- the model is never told +whether it's reading a perceived or ground-truth code, in either harness.B (perceived) +or harness.D (ground truth), which is exactly what makes a B-vs-D comparison a clean +read of perception error alone, not a comparison the model could game by knowing which +condition it's in. +""" + +from __future__ import annotations + +import json + +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 +# compact has per-instance orientation vectors), and this line has to describe both +# without over- or under-claiming either one. The code's own "spatial code schema" key +# is what actually documents every field present in a given call. +# +# CODE_DESCRIPTION is factored out (not just inlined into PRE_PROMPT) so that +# harness.C.prompts and harness.D.prompts can build their own context lines by literally +# reusing this exact string -- guaranteeing the frames-only, code-only, and +# frames+code conditions never drift into differently-worded descriptions of the same +# spatial code, and guaranteeing B and D (perceived vs. ground-truth code, otherwise the +# same condition) get a byte-identical prompt, which would be a real, avoidable wording +# confound between conditions if it ever drifted. +CODE_DESCRIPTION = ( + "a structured JSON description of a room and its objects. The schema included in " + "it explains every field." +) +PRE_PROMPT = "This is a spatial code: " + CODE_DESCRIPTION + + +def build_prompt(spatial_code, question_type, question, options=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.""" + code_text = json.dumps(spatial_code, indent=1) + if question_type in NA_QUESTION_TYPES: + return "\n".join([PRE_PROMPT, code_text, question, NA_POST_PROMPT]) + if question_type in MCA_QUESTION_TYPES: + 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]) + raise ValueError( + f"unknown question_type {question_type!r}; " + f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}" + ) diff --git a/harness/B/run.py b/harness/B/run.py new file mode 100644 index 0000000000000000000000000000000000000000..8e6fc77f5b45acb145311be097bdaaebb9e3678a --- /dev/null +++ b/harness/B/run.py @@ -0,0 +1,281 @@ +"""Run one VLM over VSI-Bench questions through harness B's spatial-code-as-text routing. + +Writes one JSON file per question in the identical shape harness.A uses (same +provenance-heavy, nothing-truncated philosophy) -- the frame-provenance fields are +simply replaced with spatial-code provenance fields (spatial_code_format, +input_selection, frame_count, depth, tracking, spatial_code_path), since B has no +video frames at all. Scoring reuses the same real, unmodified official scorer harness.A +and symbolic/run.py both use. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402 +from harness.A import models as vlm_models # noqa: E402 +from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402 +from harness.B import ( # noqa: E402 + DEFAULT_DEPTH, + DEFAULT_INPUT_SELECTION, + DEFAULT_SPATIAL_CODE_FORMAT, + DEFAULT_TRACKING, + DEPTH_VARIANTS, + FRAMES_PER_VIDEO, + INPUT_SELECTIONS, + RESULTS_DIR, + SPATIAL_CODE_FORMATS, + TRACKING_MODES, +) +from harness.B import prompts as code_prompts # noqa: E402 +from harness.B import spatial_codes # noqa: E402 + + +def results_dir_for( + model, spatial_code_format, depth, tracking, input_selection, frame_count, results_dir=None +): + """Return the result root isolated by model + spatial-code-format + depth + + tracking + input + frames.""" + if results_dir is not None: + return Path(results_dir) + return ( + RESULTS_DIR / model / spatial_code_format / depth / tracking + / input_selection / str(frame_count) + ) + + +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, + "model_path": str(model_path), + "device": answer["device"], + "dtype": answer["dtype"], + "library_versions": answer["library_versions"], + "condition": ( + f"{code_info['spatial_code_format']}:{code_info['depth']}:" + f"{code_info['tracking']}:{code_info['input_selection']}:" + f"{code_info['frame_count']}" + ), + "spatial_code_format": code_info["spatial_code_format"], + "input_selection": code_info["input_selection"], + "frame_count": code_info["frame_count"], + "depth": code_info["depth"], + "tracking": code_info["tracking"], + "spatial_code_path": code_info["spatial_code_path"], + "scene": row["scene_name"], + "dataset": row.get("dataset"), + "question_id": row["id"], + "question_type": row["question_type"], + "question": row["question"], + "options": row.get("options"), + "full_prompt": prompt, + "rendered_prompt": answer["prompt_text"], + "answer_expected": row["ground_truth"], + "answer_given": answer["answer_text"], + "answer_raw": answer["answer_raw"], + "input_token_count": answer["input_token_count"], + "vision_input_shapes": answer["vision_input_shapes"], + "output_token_ids": answer["output_token_ids"], + "output_token_count": answer["output_token_count"], + "hit_token_limit": answer["hit_token_limit"], + "eos_token_ids": answer["eos_token_ids"], + "generation_seconds": answer["generation_seconds"], + "generation_config": answer["generation_config"], + "reasoning_text": answer.get("reasoning_text"), + "reasoning_raw": answer.get("reasoning_raw"), + "reasoning_token_ids": answer.get("reasoning_token_ids"), + "reasoning_token_count": answer.get("reasoning_token_count"), + "reasoning_hit_limit": answer.get("reasoning_hit_limit"), + "forced": answer.get("forced", False), + "forced_input_token_count": answer.get("forced_input_token_count"), + "metric": metric_name, + "score": score, + } + + +def write_question_result( + row, prompt, answer, metric_name, score, model, model_path, 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) + root = results_dir_for( + model, + code_info["spatial_code_format"], + code_info["depth"], + code_info["tracking"], + code_info["input_selection"], + code_info["frame_count"], + results_dir, + ) + scene_dir = root / record["scene"] + scene_dir.mkdir(parents=True, exist_ok=True) + path = scene_dir / f"{row['id']}.json" + with path.open("w", encoding="utf-8") as stream: + json.dump(record, stream, indent=1) + return path, record + + +def run( + model, + spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT, + input_selection=DEFAULT_INPUT_SELECTION, + frame_count=FRAMES_PER_VIDEO, + depth=DEFAULT_DEPTH, + tracking=DEFAULT_TRACKING, + scene=None, + scenes=None, + limit=None, + device="cuda", + jsonl_path=None, + results_dir=None, + write_results=True, + adapter=None, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, +): + """Answer every matching question with one model, given its scene's spatial code as + text (no video frames). Each question's full record is written to its own JSON file + as soon as it is answered (unless ``write_results=False``). + + Uses ``adapter.answer_extended`` (a large ``reasoning_budget`` first pass, with a + short forced second call only if the model doesn't conclude within it) as the + standing default protocol -- not harness.A's fixed 16-token budget -- since working + through a full spatial-code JSON before answering benefits from more room than a + short visual caption does. + + Pass a pre-loaded ``adapter`` (as harness.B.launch's persistent per-GPU workers do) + to reuse one already-loaded model across many calls; the caller then owns unloading + it. Without one, ``run`` loads and unloads its own adapter, same as harness.A. + """ + rows = load_questions(jsonl_path, scene, scenes, limit) + if not rows: + return [] + owns_adapter = adapter is None + if owns_adapter: + adapter = vlm_models.get_adapter(model) + adapter.load_model(device) + code_cache = {} + results = [] + try: + 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, depth, input_selection, tracking, frame_count, spatial_code_format + ) + code_cache[scene_id] = {"code": code, "path": path} + cached = code_cache[scene_id] + prompt = code_prompts.build_prompt( + cached["code"], row["question_type"], row["question"], row.get("options") + ) + answer = adapter.answer_extended( + [], prompt, reasoning_budget=reasoning_budget, force_budget=force_budget + ) + 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 = { + "spatial_code_format": spatial_code_format, + "input_selection": input_selection, + "frame_count": frame_count, + "depth": depth, + "tracking": tracking, + "spatial_code_path": cached["path"], + } + if write_results: + path, record = write_question_result( + 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 + ) + record["result_path"] = str(path) if path else None + results.append(record) + finally: + if owns_adapter: + adapter.unload() + return results + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", required=True, choices=vlm_models.available_models()) + parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene") + parser.add_argument( + "--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", + ) + 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("--device", default="cuda") + parser.add_argument( + "--results-dir", default=None, + help="override the default results/B////// root", + ) + parser.add_argument( + "--no-write", action="store_true", + help="skip writing per-question JSON files; print/score only", + ) + parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) + parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) + args = parser.parse_args() + if args.frames < 1: + parser.error("--frames must be positive") + if args.reasoning_budget < 1: + parser.error("--reasoning-budget must be positive") + if args.force_budget < 1: + parser.error("--force-budget must be positive") + + results = run( + args.model, + spatial_code_format=args.spatial_code_format, + input_selection=args.input_selection, + frame_count=args.frames, + depth=args.depth, + tracking=args.tracking, + scene=args.scene, + limit=args.limit, + device=args.device, + results_dir=args.results_dir, + write_results=not args.no_write, + reasoning_budget=args.reasoning_budget, + force_budget=args.force_budget, + ) + + for result in results: + print( + f"[{result['scene']}#{result['question_id']}] {result['question_type']}: " + f"pred={result['answer_given']!r} gt={result['answer_expected']!r} " + f"score={result['score']} ({result['generation_seconds']:.2f}s) -> " + f"{result['result_path']}" + ) + if results: + mean_score = sum(r["score"] for r in results) / len(results) + total_seconds = sum(r["generation_seconds"] for r in results) + print( + f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}, " + f"total generation time={total_seconds:.1f}s" + ) + + +if __name__ == "__main__": + main() diff --git a/harness/B/spatial_codes.py b/harness/B/spatial_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..aa31256b2d23c5c9032befbca549fed681c7a593 --- /dev/null +++ b/harness/B/spatial_codes.py @@ -0,0 +1,31 @@ +"""Load one scene's on-disk spatial code (explicit or compact) as plain JSON. + +No solver-side adaptation (symbolic.adapters.adapt_spatial_code): the model is shown +literally the same file encoder/geometric.py wrote to disk -- schema legend included -- +not a derived, answer-oriented shape a solver would compute from it. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from encoder.config import spatial_code_path + +from harness.B import SPATIAL_CODE_FORMATS + + +def load_spatial_code(scene, depth, input_selection, tracking, frame_count, spatial_code_format): + """Return (spatial code dict, path it was loaded from).""" + if spatial_code_format not in SPATIAL_CODE_FORMATS: + raise ValueError( + f"unknown spatial-code format {spatial_code_format!r}; " + f"expected one of {SPATIAL_CODE_FORMATS}" + ) + path = spatial_code_path( + scene, depth, input_selection, tracking, frame_count, spatial_code_format + ) + if not Path(path).is_file(): + raise FileNotFoundError(f"no spatial code found for scene {scene!r} at {path}") + with open(path, encoding="utf-8") as stream: + return json.load(stream), path diff --git a/harness/B/sweep.py b/harness/B/sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..a33d4e1521212b1b74dc3154a25f8191589a0730 --- /dev/null +++ b/harness/B/sweep.py @@ -0,0 +1,139 @@ +"""Sweep any set of models x spatial-code-formats x depths x trackings x +input-selections x frame-counts. + +Every (model, spatial_code_format, depth, tracking, input_selection, frame_count) +6-tuple in the sweep is run through ``harness.B.launch.launch`` in turn, so each +combination individually saturates every visible GPU before the next one starts. +Depth/tracking default to this workspace's single shipped production config +(DEFAULT_DEPTH/DEFAULT_TRACKING) when --depths/--trackings aren't given, but are real +sweepable axes like every other dimension here -- pass --depths all / --trackings all +(or an explicit comma list) to sweep them too. +""" + +from __future__ import annotations + +import argparse +from pathlib import Path +import sys + +HERE = Path(__file__).resolve().parent +WORKSPACE_ROOT = HERE.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +from harness.A import models as vlm_models # noqa: E402 +from harness.A.sweep import _parse_csv_choice, _parse_frame_counts # noqa: E402 +from harness.B import ( # noqa: E402 + DEFAULT_DEPTH, + DEFAULT_TRACKING, + DEPTH_VARIANTS, + INPUT_SELECTIONS, + SPATIAL_CODE_FORMATS, + TRACKING_MODES, +) +from harness.B import launch as harness_launch # noqa: E402 + + +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).""" + return [ + (model, spatial_code_format, depth, tracking, input_selection, frame_count) + for frame_count in sorted(frame_counts) + for model in models + for spatial_code_format in spatial_code_formats + for depth in depths + for tracking in trackings + for input_selection in input_selections + ] + + +def sweep( + models, spatial_code_formats, input_selections, frame_counts, selected_scenes, + depths=(DEFAULT_DEPTH,), trackings=(DEFAULT_TRACKING,), results_dir=None, rebuild=False, +): + """Run every sweep combination across all visible GPUs.""" + plan = build_plan(models, spatial_code_formats, input_selections, frame_counts, depths, trackings) + for index, (model, spatial_code_format, depth, tracking, input_selection, frame_count) in enumerate( + plan, start=1 + ): + print( + f"=== sweep {index}/{len(plan)}: " + f"{model}/{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count} ===", + 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, + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("scene", nargs="?") + parser.add_argument( + "--scenes", help="comma-separated scenes (cannot be combined with positional scene)" + ) + parser.add_argument( + "--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", + help=f"comma-separated formats (or 'all'); one of {SPATIAL_CODE_FORMATS}", + ) + parser.add_argument( + "--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, + help=f"comma-separated depths (or 'all'); one of {DEPTH_VARIANTS}", + ) + parser.add_argument( + "--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") + args = parser.parse_args() + if args.scene and args.scenes: + parser.error("positional scene and --scenes cannot be used together") + + try: + 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" + ) + input_selections = _parse_csv_choice( + args.input_selections, INPUT_SELECTIONS, "--input-selections" + ) + depths = _parse_csv_choice(args.depths, DEPTH_VARIANTS, "--depths") + trackings = _parse_csv_choice(args.trackings, TRACKING_MODES, "--trackings") + frame_counts = _parse_frame_counts(args.frames) + except ValueError as exc: + parser.error(str(exc)) + + if args.scenes is not None: + selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()] + if not selected: + parser.error("--scenes must contain at least one scene") + selected = list(dict.fromkeys(selected)) + else: + from harness.A.launch import scenes + + 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, + ) + + +if __name__ == "__main__": + main() diff --git a/harness/C/__pycache__/__init__.cpython-311.pyc b/harness/C/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b23435971a7b72bea7b90a15aefe295b5a8ed2d1 Binary files /dev/null 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 new file mode 100644 index 0000000000000000000000000000000000000000..715df8b6698267d44c321f4a829396f6ead12a95 Binary files /dev/null and b/harness/C/__pycache__/launch.cpython-311.pyc differ diff --git a/harness/C/__pycache__/prompts.cpython-311.pyc b/harness/C/__pycache__/prompts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72faaab90af50af86b28b2a647fb08c4a1f14651 Binary files /dev/null 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 new file mode 100644 index 0000000000000000000000000000000000000000..9d25e58c1f90f25fdfd2da8ac7b38693220b2511 Binary files /dev/null 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 new file mode 100644 index 0000000000000000000000000000000000000000..4e7dbc820b00bd6b30bbe15e3d1dd36eb7e38c45 Binary files /dev/null and b/harness/C/__pycache__/sweep.cpython-311.pyc differ diff --git a/harness/C/launch.py b/harness/C/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..ff3b302919d1c2b64bdfe201c74e24b25c85d5f7 --- /dev/null +++ b/harness/C/launch.py @@ -0,0 +1,221 @@ +"""Keep every visible GPU busy with persistent harness-C inference workers. + +Same shape as ``harness.A.launch`` / ``harness.B.launch``: one persistent worker +process per visible GPU, pulling scenes off a shared queue, each loading its model +exactly once and reusing it for every scene it's assigned (via ``run.run(..., +adapter=...)``). One invocation covers one (model, spatial_code_format, +input_selection, frame_count) quadruple across every requested scene; sweep multiple +quadruples via harness.C.sweep. +""" + +from __future__ import annotations + +import argparse +import importlib.util +import multiprocessing as mp +import os +from pathlib import Path +import sys +import traceback + +HERE = Path(__file__).resolve().parent +WORKSPACE_ROOT = HERE.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402 +from harness.A import models as vlm_models # noqa: E402 +from harness.A.launch import scenes # noqa: E402 +from harness.B import ( # noqa: E402 + DEFAULT_DEPTH, + DEFAULT_INPUT_SELECTION, + DEFAULT_SPATIAL_CODE_FORMAT, + DEFAULT_TRACKING, + DEPTH_VARIANTS, + INPUT_SELECTIONS, + SPATIAL_CODE_FORMATS, + TRACKING_MODES, +) +from harness.C import FRAMES_PER_VIDEO # noqa: E402 +from inference.launch import available_cpu_count, visible_gpus # noqa: E402 + + +def _load_run_module(): + spec = importlib.util.spec_from_file_location("_harness_C_run", HERE / "run.py") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _worker( + tasks, results, model, spatial_code_format, input_selection, frame_count, depth, tracking, + results_dir, gpu, cpu_threads, 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"): + os.environ[variable] = str(cpu_threads) + import cv2 + + cv2.setNumThreads(cpu_threads) + run = _load_run_module() + adapter = None + load_error = None + try: + adapter = vlm_models.get_adapter(model) + adapter.load_model("cuda:0" if gpu is not None else "cpu") + except Exception: + load_error = traceback.format_exc() + while True: + scene = tasks.get() + if scene is None: + return + if load_error is not None: + results.put((scene, False, load_error)) + continue + try: + answered = run.run( + model, + spatial_code_format=spatial_code_format, + input_selection=input_selection, + frame_count=frame_count, + depth=depth, + tracking=tracking, + scene=scene, + results_dir=results_dir, + adapter=adapter, + reasoning_budget=reasoning_budget, + force_budget=force_budget, + ) + mean_score = ( + sum(r["score"] for r in answered) / len(answered) if answered else None + ) + results.put( + (scene, True, f"{len(answered)} question(s), mean_score={mean_score}") + ) + except Exception: + results.put((scene, False, traceback.format_exc())) + + +def launch( + model, spatial_code_format, input_selection, frame_count, selected, + depth=DEFAULT_DEPTH, tracking=DEFAULT_TRACKING, results_dir=None, rebuild=False, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, force_budget=MAX_NEW_TOKENS, +): + """Answer every question for ``selected`` scenes, sharded across every visible GPU.""" + condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/{input_selection}/{frame_count}" + run = _load_run_module() + root = run.results_dir_for( + model, spatial_code_format, depth, tracking, input_selection, frame_count, results_dir + ) + 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 answered and not rebuild: + completed += 1 + print(f"[{condition} {completed}/{len(selected)}] {scene}: skipped", flush=True) + else: + pending.append(scene) + if not pending: + print(f"[{condition}] DONE: {len(selected)} ok, 0 failed") + return + + gpus = visible_gpus() + worker_count = min(len(pending), len(gpus) if gpus else 1) + assignments = gpus[:worker_count] if gpus else [None] + cpu_count = available_cpu_count() + cpu_threads = max(1, cpu_count // worker_count) + print( + f"[{condition}] starting {worker_count} persistent worker(s); " + f"GPUs={assignments}; CPU threads/worker={cpu_threads}", + flush=True, + ) + + context = mp.get_context("spawn") + tasks, results = context.Queue(), context.Queue() + for scene in pending: + tasks.put(scene) + for _ in range(worker_count): + tasks.put(None) + workers = [ + context.Process( + target=_worker, + args=( + tasks, results, model, spatial_code_format, input_selection, frame_count, + depth, tracking, results_dir, gpu, cpu_threads, reasoning_budget, force_budget, + ), + ) + for gpu in assignments + ] + for worker in workers: + worker.start() + failed = [] + for finished in range(1, len(pending) + 1): + scene, ok, detail = results.get() + if not ok: + failed.append(scene) + print( + f"[{condition} {completed + finished}/{len(selected)}] {scene}: " + f"{'done' if ok else 'FAILED'}\n{detail}", + flush=True, + ) + for worker in workers: + worker.join() + print( + f"[{condition}] DONE: {len(pending) - len(failed)} answered, {completed} skipped, " + f"{len(failed)} failed" + ) + if failed: + raise SystemExit(1) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("scene", nargs="?") + parser.add_argument( + "--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", + ) + parser.add_argument( + "--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("--results-dir", default=None) + parser.add_argument("--rebuild", action="store_true") + parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) + parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) + args = parser.parse_args() + if args.scene and args.scenes: + parser.error("positional scene and --scenes cannot be used together") + if args.scenes is not None: + selected = [scene.strip() for scene in args.scenes.split(",") if scene.strip()] + if not selected: + parser.error("--scenes must contain at least one scene") + selected = list(dict.fromkeys(selected)) + else: + selected = [args.scene] if args.scene else scenes() + if args.frames < 1: + parser.error("--frames must be positive") + if args.reasoning_budget < 1: + parser.error("--reasoning-budget must be positive") + if args.force_budget < 1: + parser.error("--force-budget must be positive") + 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, + reasoning_budget=args.reasoning_budget, force_budget=args.force_budget, + ) + + +if __name__ == "__main__": + main() diff --git a/harness/C/prompts.py b/harness/C/prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..45fd5aaad7c54a1078a440449795ed7da9c68ec4 --- /dev/null +++ b/harness/C/prompts.py @@ -0,0 +1,48 @@ +"""Combined video-frames + spatial-code-as-text prompt construction. + +Reuses harness.A.prompts's exact question-type split and post-prompts verbatim. The +returned text becomes the ONE trailing content item passed to +harness.A.models._numbered_content(frames, this_text) -- since that helper already puts +every numbered frame image first and appends a single text block last, the resulting +model input order is exactly: frames (numbered) -> spatial code text -> question. +""" + +from __future__ import annotations + +import json + +from harness.A.prompts import ( + MCA_POST_PROMPT, + MCA_QUESTION_TYPES, + NA_POST_PROMPT, + NA_QUESTION_TYPES, + PRE_PROMPT as FRAMES_PRE_PROMPT, +) +from harness.B.prompts import CODE_DESCRIPTION + +# Built by literally concatenating harness.A's frames sentence with harness.B's spatial +# code sentence (not independently reworded) -- so a reviewer can see the frames-only, +# code-only, and frames+code context lines never describe the same content in different +# words. This is the ONE deliberate difference from B's context line (mentioning frames +# at all); everything describing the spatial code itself is the identical CODE_DESCRIPTION +# string B uses. +PRE_PROMPT = FRAMES_PRE_PROMPT + " Also provided is a spatial code: " + CODE_DESCRIPTION + + +def build_prompt(spatial_code, question_type, question, options=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 + harness.A.models._numbered_content.""" + code_text = json.dumps(spatial_code, indent=1) + if question_type in NA_QUESTION_TYPES: + return "\n".join([PRE_PROMPT, code_text, question, NA_POST_PROMPT]) + if question_type in MCA_QUESTION_TYPES: + 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]) + raise ValueError( + f"unknown question_type {question_type!r}; " + f"expected one of {MCA_QUESTION_TYPES + NA_QUESTION_TYPES}" + ) diff --git a/harness/D/__pycache__/launch.cpython-311.pyc b/harness/D/__pycache__/launch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24b17332ef7daf38a02b63abb88097c3ec1f5984 Binary files /dev/null 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 new file mode 100644 index 0000000000000000000000000000000000000000..39cd56f53f54a90a9072f0ccbc27367e9f53efd0 Binary files /dev/null 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 new file mode 100644 index 0000000000000000000000000000000000000000..51b37d4f0d0e7391984e5beae5e833bf9265b984 Binary files /dev/null and b/harness/D/__pycache__/run.cpython-311.pyc differ diff --git a/harness/D/__pycache__/spatial_codes.cpython-311.pyc b/harness/D/__pycache__/spatial_codes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02b0108e63acfdd145b43530e1725165e65b69a4 Binary files /dev/null and b/harness/D/__pycache__/spatial_codes.cpython-311.pyc differ diff --git a/harness/D/__pycache__/symbolic_eval.cpython-311.pyc b/harness/D/__pycache__/symbolic_eval.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f326452699c000db580f0a3c8cedec6193d5bf74 Binary files /dev/null and b/harness/D/__pycache__/symbolic_eval.cpython-311.pyc differ diff --git a/harness/__pycache__/__init__.cpython-311.pyc b/harness/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6c3c59eb99774a9ceaeea9df34e3657237f0950 Binary files /dev/null and b/harness/__pycache__/__init__.cpython-311.pyc differ diff --git a/tests/test_B/__init__.py b/tests/test_B/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_B/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc b/tests/test_B/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43229c7c644c49c806ab1aa887561552ab41a141 Binary files /dev/null and b/tests/test_B/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_B/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc b/tests/test_B/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26160072cf970718586f0d34ac2c9e8bbb166bfd Binary files /dev/null and b/tests/test_B/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_B/__pycache__/test_spatial_codes.cpython-311-pytest-8.3.5.pyc b/tests/test_B/__pycache__/test_spatial_codes.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0dcf4850ea9d2730f250d47c041d78a5290fc23 Binary files /dev/null and b/tests/test_B/__pycache__/test_spatial_codes.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_B/conftest.py b/tests/test_B/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..cff300cdd89d64dac0aa52d10f2982c6fcbbe74d --- /dev/null +++ b/tests/test_B/conftest.py @@ -0,0 +1,12 @@ +"""Shared import setup for harness.B tests.""" + +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + + +def pytest_configure(config): + config.option.importmode = "importlib" diff --git a/tests/test_B/test_init.py b/tests/test_B/test_init.py new file mode 100644 index 0000000000000000000000000000000000000000..96c5b1ca3c5de979a7b143722d77bfc8b07439f0 --- /dev/null +++ b/tests/test_B/test_init.py @@ -0,0 +1,33 @@ +"""Tests for harness/B/__init__.py -- shared config constants.""" + +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_workspace_results(): + assert B.RESULTS_DIR == B.WORKSPACE_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 new file mode 100644 index 0000000000000000000000000000000000000000..68be0bebee397ab08e092252bfc4ec0ee44f8459 --- /dev/null +++ b/tests/test_B/test_launch.py @@ -0,0 +1,49 @@ +"""Tests for harness/B/launch.py -- multi-GPU scene sharding across workers.""" + +from harness.A.run import load_questions as harness_a_load_questions +from harness.B import launch + + +def test_launcher_imports(): + assert callable(launch.main) + + +def test_launch_skips_scene_already_fully_answered(tmp_path, capsys): + scene = "13c3e046d7" + rows = harness_a_load_questions(scene=scene) + assert rows, "fixture scene must have real questions in the VSI-Bench manifest" + + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + launch.launch("qwen3.5-2b", "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_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): + scene = "13c3e046d7" + rows = harness_a_load_questions(scene=scene) + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + monkeypatch.setattr(launch, "visible_gpus", lambda: []) + monkeypatch.setattr( + launch.mp, "get_context", + lambda *_: (_ for _ in ()).throw(RuntimeError("rebuild correctly reached worker dispatch")), + ) + try: + launch.launch( + "qwen3.5-2b", "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") diff --git a/tests/test_B/test_sweep.py b/tests/test_B/test_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..deda6af708c86ac7e3ef354177ae285b41ef9dbd --- /dev/null +++ b/tests/test_B/test_sweep.py @@ -0,0 +1,55 @@ +"""Tests for harness/B/sweep.py -- multi-config sweep planning.""" + +import pytest + +from harness.A import models as vlm_models +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"], + ) + assert len(plan) == 2 * 2 * 2 * 2 + assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan + assert ("qwen3.5-4b", "compact", "metric", "tracking", "selective", 32) in plan + + +def test_build_plan_sweeps_depth_and_tracking_too(): + plan = sweep.build_plan( + ["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 + + +def test_build_plan_orders_by_frame_count_first(): + plan = sweep.build_plan( + ["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"], + ) + 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") + + +def test_sweep_parser_rejects_unknown_depth(): + with pytest.raises(ValueError): + sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths") + + +def test_sweep_parser_rejects_unknown_tracking(): + with pytest.raises(ValueError): + sweep._parse_csv_choice("bogus", sweep.TRACKING_MODES, "--trackings") diff --git a/tests/test_C/__init__.py b/tests/test_C/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_C/__pycache__/__init__.cpython-311.pyc b/tests/test_C/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fccfaf93789afcde575319124258fe1e289fa7a7 Binary files /dev/null and b/tests/test_C/__pycache__/__init__.cpython-311.pyc differ diff --git a/tests/test_C/__pycache__/conftest.cpython-311-pytest-8.3.5.pyc b/tests/test_C/__pycache__/conftest.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4f9af121318f6dacf1b979d650b8b0ae7827398 Binary files /dev/null and b/tests/test_C/__pycache__/conftest.cpython-311-pytest-8.3.5.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 new file mode 100644 index 0000000000000000000000000000000000000000..7c960a3a8b45a27a345b9d0449b9a952cc7e8b62 Binary files /dev/null and b/tests/test_C/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc b/tests/test_C/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..555ee681e45463a6855cf38c890095f658225738 Binary files /dev/null and b/tests/test_C/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_C/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc b/tests/test_C/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..600df5913b9cba76ba43334e83c1479061721f06 Binary files /dev/null and b/tests/test_C/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc b/tests/test_C/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bcdd34676443b37f950bac7a0cbaa860d044737 Binary files /dev/null and b/tests/test_C/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_C/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc b/tests/test_C/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f90687fbc5c5f4da688813ed77d9e594ac632179 Binary files /dev/null and b/tests/test_C/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/__pycache__/test_sweep.cpython-311-pytest-8.3.5.pyc b/tests/test_C/__pycache__/test_sweep.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be66096481e9525b5c39fe90a63dd8f04d7550d2 Binary files /dev/null and b/tests/test_C/__pycache__/test_sweep.cpython-311-pytest-8.3.5.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 new file mode 100644 index 0000000000000000000000000000000000000000..9113f74eebd51b618b2fd2f2dcfcdfb862924041 Binary files /dev/null and b/tests/test_C/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_C/conftest.py b/tests/test_C/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..3abc76e01c01cd0bfbddf3345cf7422f6c71fe53 --- /dev/null +++ b/tests/test_C/conftest.py @@ -0,0 +1,12 @@ +"""Shared import setup for harness.C tests.""" + +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + + +def pytest_configure(config): + config.option.importmode = "importlib" diff --git a/tests/test_C/test_init.py b/tests/test_C/test_init.py new file mode 100644 index 0000000000000000000000000000000000000000..62629afcda57cbea7408725d50f1f536ffe7bae7 --- /dev/null +++ b/tests/test_C/test_init.py @@ -0,0 +1,25 @@ +"""Tests for harness/C/__init__.py -- shared config constants.""" + +from harness import A, B, C + + +def test_input_selections_are_one_shared_vocabulary_with_a_and_b(): + assert B.INPUT_SELECTIONS == A.FRAME_SELECTIONS + + +def test_reuses_harness_a_model_paths_and_generation_protocol(): + assert C.MODEL_PATHS is A.MODEL_PATHS + assert C.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS + assert C.DO_SAMPLE == A.DO_SAMPLE + assert C.TEMPERATURE == A.TEMPERATURE + + +def test_results_dir_defaults_under_workspace_results(): + assert C.RESULTS_DIR == C.WORKSPACE_ROOT / "results" / "C" + + +def test_depth_and_tracking_reuse_encoder_config_vocabulary(): + from encoder.config import DEPTH_VARIANTS, TRACKING_MODES + + assert C.DEPTH_VARIANTS == DEPTH_VARIANTS + assert C.TRACKING_MODES == TRACKING_MODES diff --git a/tests/test_C/test_launch.py b/tests/test_C/test_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..358593155f107893bb2ce5717006896169e06a73 --- /dev/null +++ b/tests/test_C/test_launch.py @@ -0,0 +1,49 @@ +"""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 + + +def test_launcher_imports(): + assert callable(launch.main) + + +def test_launch_skips_scene_already_fully_answered(tmp_path, capsys): + scene = "13c3e046d7" + rows = harness_a_load_questions(scene=scene) + assert rows, "fixture scene must have real questions in the VSI-Bench manifest" + + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + launch.launch("qwen3.5-2b", "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_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): + scene = "13c3e046d7" + rows = harness_a_load_questions(scene=scene) + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + monkeypatch.setattr(launch, "visible_gpus", lambda: []) + monkeypatch.setattr( + launch.mp, "get_context", + lambda *_: (_ for _ in ()).throw(RuntimeError("rebuild correctly reached worker dispatch")), + ) + try: + launch.launch( + "qwen3.5-2b", "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") diff --git a/tests/test_C/test_prompts.py b/tests/test_C/test_prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..367d7e9fc74a647e2831cea149a9907de1b6e660 --- /dev/null +++ b/tests/test_C/test_prompts.py @@ -0,0 +1,56 @@ +"""Tests for harness/C/prompts.py -- combined frames+spatial-code prompt construction.""" + +import json + +import pytest + +from harness.A.prompts import MCA_QUESTION_TYPES, NA_QUESTION_TYPES +from harness.C import prompts as combined_prompts + +_CODE = {"objects": {"chair": {"count": 1}}, "room": {"floor area": "10.0 square meters"}} + + +def test_pre_prompt_mentions_both_frames_and_spatial_code(): + lowered = combined_prompts.PRE_PROMPT.lower() + assert "frame" in lowered + assert "spatial code" in lowered + + +def test_na_question_prompt_layout_is_context_then_code_then_question_then_post_prompt(): + prompt = combined_prompts.build_prompt(_CODE, "object_counting", "How many chairs?") + context_pos = prompt.find(combined_prompts.PRE_PROMPT) + code_pos = prompt.find(json.dumps(_CODE, indent=1)) + question_pos = prompt.find("How many chairs?") + post_pos = prompt.find(combined_prompts.NA_POST_PROMPT) + assert context_pos == 0 + assert context_pos < code_pos < question_pos < post_pos + + +def test_mca_question_prompt_includes_options_and_post_prompt(): + prompt = combined_prompts.build_prompt( + _CODE, "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"] + ) + assert "Options:\nA. sofa\nB. table" in prompt + assert prompt.endswith(combined_prompts.MCA_POST_PROMPT) + + +def test_mca_question_requires_options(): + with pytest.raises(ValueError): + combined_prompts.build_prompt(_CODE, "route_planning", "Which way?", None) + + +def test_unknown_question_type_rejected(): + with pytest.raises(ValueError): + combined_prompts.build_prompt(_CODE, "not_a_real_type", "?", None) + + +@pytest.mark.parametrize("question_type", NA_QUESTION_TYPES) +def test_every_na_question_type_builds(question_type): + prompt = combined_prompts.build_prompt(_CODE, question_type, "q?") + assert prompt.startswith(combined_prompts.PRE_PROMPT) + + +@pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES) +def test_every_mca_question_type_builds(question_type): + prompt = combined_prompts.build_prompt(_CODE, question_type, "q?", ["A. x", "B. y"]) + assert prompt.startswith(combined_prompts.PRE_PROMPT) diff --git a/tests/test_C/test_run.py b/tests/test_C/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..c31960b86f6706cc4d8e38c3c39ecc761f1bf2a8 --- /dev/null +++ b/tests/test_C/test_run.py @@ -0,0 +1,120 @@ +"""Tests for harness/C/run.py -- result-record shape and result-file writing.""" + +import json + +from harness import C +from harness.C import run as harness_run + +_FAKE_ANSWER = { + "prompt_text": "", + "answer_text": "4", + "answer_raw": "<|im_start|>assistant\n4<|im_end|>", + "input_token_count": 22205, + "vision_input_shapes": {"pixel_values": [76800, 1536], "image_grid_thw": [64, 3]}, + "output_token_ids": [19, 151645], + "output_token_count": 2, + "hit_token_limit": False, + "eos_token_ids": [151645], + "generation_seconds": 5.6, + "device": "cuda", + "dtype": "bfloat16", + "library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"}, + "generation_config": { + "max_new_tokens": 16, + "do_sample": False, + "temperature": 0.0, + "top_p": None, + "top_k": None, + "enable_thinking": False, + }, +} + +_FAKE_ROW = { + "id": 7, + "scene_name": "scene0001_00", + "dataset": "scannet", + "question_type": "object_counting", + "question": "How many chairs?", + "options": None, + "ground_truth": "4", +} + +_FAKE_SOURCE_INFO = { + "spatial_code_format": "explicit", + "input_selection": "selective", + "frame_count": 64, + "depth": "metric", + "tracking": "tracking", + "spatial_code_path": "/workspace/data/spatial codes/.../scene0001_00.json", + "video_path": "/root/data/VSI-Bench/scannet/scene0001_00.mp4", + "frame_indices": [0, 30, 60], + "frame_timestamps": [0.0, 1.0, 2.0], +} + + +def test_results_dir_for_matches_established_dimension_nesting(): + root = harness_run.results_dir_for("qwen3.5-4b", "compact", "metric", "tracking", "uniform", 32) + assert root == ( + C.RESULTS_DIR / "qwen3.5-4b" / "compact" / "metric" / "tracking" / "uniform" / "32" + ) + + +def test_results_dir_for_honors_explicit_override(tmp_path): + root = harness_run.results_dir_for( + "qwen3.5-4b", "explicit", "relative", "no tracking", "selective", 16, tmp_path + ) + assert root == tmp_path + + +def test_build_record_carries_both_frame_and_spatial_code_provenance(): + record = harness_run._build_record( + _FAKE_ROW, "full prompt text", _FAKE_ANSWER, "MRA:.5:.95:.05", 1.0, + "qwen3.5-4b", "/root/models/qwen3.5-4b", _FAKE_SOURCE_INFO, + ) + # Spatial-code provenance (shared with harness.B). + assert record["spatial_code_format"] == "explicit" + assert record["input_selection"] == "selective" + assert record["frame_count"] == 64 + assert record["depth"] == "metric" + assert record["tracking"] == "tracking" + assert record["spatial_code_path"] == _FAKE_SOURCE_INFO["spatial_code_path"] + # Frame provenance (shared with harness.A). + assert record["video_path"] == _FAKE_SOURCE_INFO["video_path"] + assert record["frame_indices"] == [0, 30, 60] + assert record["frame_timestamps_seconds"] == [0.0, 1.0, 2.0] + # Question/answer fields, same shape as A and B. + assert record["question"] == "How many chairs?" + assert record["answer_given"] == "4" + assert record["vision_input_shapes"] == _FAKE_ANSWER["vision_input_shapes"] + assert record["condition"] == "explicit:metric:tracking:selective:64" + assert record["score"] == 1.0 + + +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_SOURCE_INFO, results_dir=tmp_path, + ) + assert path == tmp_path / "scene0001_00" / "7.json" + on_disk = json.loads(path.read_text()) + assert on_disk == record + + +def test_build_record_carries_reasoning_fields_when_forced(): + extended_answer = { + **_FAKE_ANSWER, + "reasoning_text": "long reasoning about the frames and spatial code", + "reasoning_raw": "long reasoning about the frames and spatial code<|im_end|>", + "reasoning_token_ids": list(range(50)), + "reasoning_token_count": 50, + "reasoning_hit_limit": True, + "forced": True, + "forced_input_token_count": 22300, + } + 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_SOURCE_INFO, + ) + assert record["reasoning_text"] == "long reasoning about the frames and spatial code" + assert record["forced"] is True + assert record["forced_input_token_count"] == 22300 diff --git a/tests/test_C/test_sweep.py b/tests/test_C/test_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..e87649c4988eb56674c0ce31ae92face890c1502 --- /dev/null +++ b/tests/test_C/test_sweep.py @@ -0,0 +1,55 @@ +"""Tests for harness/C/sweep.py -- multi-config sweep planning.""" + +import pytest + +from harness.A import models as vlm_models +from harness.C 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"], + ) + assert len(plan) == 2 * 2 * 2 * 2 + assert ("qwen3.5-2b", "explicit", "metric", "tracking", "uniform", 16) in plan + assert ("qwen3.5-4b", "compact", "metric", "tracking", "selective", 32) in plan + + +def test_build_plan_sweeps_depth_and_tracking_too(): + plan = sweep.build_plan( + ["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 + + +def test_build_plan_orders_by_frame_count_first(): + plan = sweep.build_plan( + ["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"], + ) + 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") + + +def test_sweep_parser_rejects_unknown_depth(): + with pytest.raises(ValueError): + sweep._parse_csv_choice("bogus", sweep.DEPTH_VARIANTS, "--depths") + + +def test_sweep_parser_rejects_unknown_tracking(): + with pytest.raises(ValueError): + sweep._parse_csv_choice("bogus", sweep.TRACKING_MODES, "--trackings") diff --git a/tests/test_D/__init__.py b/tests/test_D/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_D/__pycache__/__init__.cpython-311.pyc b/tests/test_D/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe8176ad99e699005a1ce250dcfb381f9c128a0b Binary files /dev/null and b/tests/test_D/__pycache__/__init__.cpython-311.pyc differ diff --git a/tests/test_D/__pycache__/conftest.cpython-311-pytest-8.3.5.pyc b/tests/test_D/__pycache__/conftest.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca3c72ed46b777cec5800cc0dfcc84feda22f013 Binary files /dev/null and b/tests/test_D/__pycache__/conftest.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_D/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc b/tests/test_D/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca3c72ed46b777cec5800cc0dfcc84feda22f013 Binary files /dev/null and b/tests/test_D/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_D/__pycache__/test_init.cpython-311-pytest-8.3.5.pyc b/tests/test_D/__pycache__/test_init.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef71292e8553bd9d3fa714b9e49cb537f55135b9 Binary files /dev/null and b/tests/test_D/__pycache__/test_init.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_D/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc b/tests/test_D/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cd4444f3f86c1bda8ff88efc404d98ef9cd13d0 Binary files /dev/null and b/tests/test_D/__pycache__/test_init.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_D/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc b/tests/test_D/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57de5a1dc451772847e481ffa12a6dcaf75452aa Binary files /dev/null and b/tests/test_D/__pycache__/test_launch.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_D/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc b/tests/test_D/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04716f93c2655aea9092d62a9ae78d52d56eadbc Binary files /dev/null and b/tests/test_D/__pycache__/test_launch.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_D/__pycache__/test_prompts.cpython-311-pytest-8.3.5.pyc b/tests/test_D/__pycache__/test_prompts.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0857221b5e13f0ebafca8030545382c940aa939 Binary files /dev/null and b/tests/test_D/__pycache__/test_prompts.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_D/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc b/tests/test_D/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0857221b5e13f0ebafca8030545382c940aa939 Binary files /dev/null and b/tests/test_D/__pycache__/test_prompts.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc b/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68626dd5511c0f320962ee743d16a1bcd6a26120 Binary files /dev/null and b/tests/test_D/__pycache__/test_run.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_D/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc b/tests/test_D/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24bbc1f7403e05ccaa248955b3f9ccd72b26143d Binary files /dev/null and b/tests/test_D/__pycache__/test_run.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_D/__pycache__/test_spatial_codes.cpython-311-pytest-8.3.5.pyc b/tests/test_D/__pycache__/test_spatial_codes.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cc43dbc7622ae41ed26c5acf9d81e1e50e5d10c Binary files /dev/null and b/tests/test_D/__pycache__/test_spatial_codes.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_D/__pycache__/test_spatial_codes.cpython-311-pytest-9.1.1.pyc b/tests/test_D/__pycache__/test_spatial_codes.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47a790dbece19e7c43e572ac94785b38d71f0f69 Binary files /dev/null and b/tests/test_D/__pycache__/test_spatial_codes.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_D/__pycache__/test_sweep.cpython-311-pytest-8.3.5.pyc b/tests/test_D/__pycache__/test_sweep.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..205bfb0b1d98baaafaa9316d212f3df03fe62c18 Binary files /dev/null and b/tests/test_D/__pycache__/test_sweep.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_D/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc b/tests/test_D/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97caaf258e97e4460febfd9add0a1085965b0962 Binary files /dev/null and b/tests/test_D/__pycache__/test_sweep.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_D/__pycache__/test_symbolic_eval.cpython-311-pytest-8.3.5.pyc b/tests/test_D/__pycache__/test_symbolic_eval.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01cdfb40ed0a0de23c0c98cee0a7b386d6d15235 Binary files /dev/null and b/tests/test_D/__pycache__/test_symbolic_eval.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_D/__pycache__/test_symbolic_eval.cpython-311-pytest-9.1.1.pyc b/tests/test_D/__pycache__/test_symbolic_eval.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8abead35f5e43077ded83e5b4312769f0505096 Binary files /dev/null and b/tests/test_D/__pycache__/test_symbolic_eval.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_D/conftest.py b/tests/test_D/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..82957828bd0e0ea1e9fec107f7951d289425ee1b --- /dev/null +++ b/tests/test_D/conftest.py @@ -0,0 +1,12 @@ +"""Shared import setup for harness.D tests.""" + +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + + +def pytest_configure(config): + config.option.importmode = "importlib" diff --git a/tests/test_D/test_init.py b/tests/test_D/test_init.py new file mode 100644 index 0000000000000000000000000000000000000000..5164a571f95d4a5ad250132d0ed90430297ac338 --- /dev/null +++ b/tests/test_D/test_init.py @@ -0,0 +1,19 @@ +"""Tests for harness/D/__init__.py -- shared config constants.""" + +from harness import A, B, D + + +def test_spatial_code_formats_reuse_harness_b_vocabulary(): + assert D.SPATIAL_CODE_FORMATS == B.SPATIAL_CODE_FORMATS + assert D.DEFAULT_SPATIAL_CODE_FORMAT in D.SPATIAL_CODE_FORMATS + + +def test_reuses_harness_a_model_paths_and_generation_protocol(): + assert D.MODEL_PATHS is A.MODEL_PATHS + assert D.MAX_NEW_TOKENS == A.MAX_NEW_TOKENS + assert D.DO_SAMPLE == A.DO_SAMPLE + assert D.TEMPERATURE == A.TEMPERATURE + + +def test_results_dir_defaults_under_workspace_results(): + assert D.RESULTS_DIR == D.WORKSPACE_ROOT / "results" / "D" diff --git a/tests/test_D/test_launch.py b/tests/test_D/test_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..21e693dd9b89c720443ba5010f452e61b960c491 --- /dev/null +++ b/tests/test_D/test_launch.py @@ -0,0 +1,54 @@ +"""Tests for harness/D/launch.py -- multi-GPU scene sharding across workers.""" + +from harness.A.run import load_questions as harness_a_load_questions +from harness.D import launch + + +def test_launcher_imports(): + assert callable(launch.main) + + +def test_launch_skips_scene_already_fully_answered(tmp_path, capsys): + scene = "13c3e046d7" + rows = harness_a_load_questions(scene=scene) + assert rows, "fixture scene must have real questions in the VSI-Bench manifest" + + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + launch.launch("qwen3.5-2b", "explicit", [scene], results_dir=tmp_path) + + output = capsys.readouterr().out + assert "skipped" in output + assert "DONE: 1 ok, 0 failed" in output + + +def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): + scene = "13c3e046d7" + rows = harness_a_load_questions(scene=scene) + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + monkeypatch.setattr(launch, "visible_gpus", lambda: []) + monkeypatch.setattr( + launch.mp, "get_context", + lambda *_: (_ for _ in ()).throw(RuntimeError("rebuild correctly reached worker dispatch")), + ) + try: + launch.launch("qwen3.5-2b", "explicit", [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_scenes_is_subset_of_vsi_bench_scenes_with_ground_truth_coverage(): + from harness.A.launch import scenes as vsi_scenes + + all_scenes = set(vsi_scenes()) + d_scenes = launch.scenes() + assert set(d_scenes) <= all_scenes diff --git a/tests/test_D/test_prompts.py b/tests/test_D/test_prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..ef5077210824220faea54fb03b941eb30bb2ff36 --- /dev/null +++ b/tests/test_D/test_prompts.py @@ -0,0 +1,52 @@ +"""Tests for harness/D/prompts.py -- ground-truth spatial-code-as-text prompt construction.""" + +import json + +import pytest + +from harness.A.prompts import MCA_QUESTION_TYPES, NA_QUESTION_TYPES +from harness.D import prompts as code_prompts + +_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(): + prompt = code_prompts.build_prompt(_CODE, "object_counting", "How many chairs?") + assert prompt.startswith(code_prompts.PRE_PROMPT) + assert json.dumps(_CODE, indent=1) in prompt + assert prompt.endswith(code_prompts.NA_POST_PROMPT) + + +def test_mca_question_prompt_includes_options_and_matches_harness_a_post_prompt(): + prompt = code_prompts.build_prompt( + _CODE, "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"] + ) + assert "Options:\nA. sofa\nB. table" in prompt + assert prompt.endswith(code_prompts.MCA_POST_PROMPT) + + +def test_mca_question_requires_options(): + with pytest.raises(ValueError): + code_prompts.build_prompt(_CODE, "route_planning", "Which way?", None) + + +def test_unknown_question_type_rejected(): + with pytest.raises(ValueError): + code_prompts.build_prompt(_CODE, "not_a_real_type", "?", None) + + +def test_no_frames_or_video_language_in_pre_prompt(): + assert "frame" not in code_prompts.PRE_PROMPT.lower() + assert "video" not in code_prompts.PRE_PROMPT.lower() + + +@pytest.mark.parametrize("question_type", NA_QUESTION_TYPES) +def test_every_na_question_type_builds(question_type): + prompt = code_prompts.build_prompt(_CODE, question_type, "q?") + assert prompt.startswith(code_prompts.PRE_PROMPT) + + +@pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES) +def test_every_mca_question_type_builds(question_type): + prompt = code_prompts.build_prompt(_CODE, question_type, "q?", ["A. x", "B. y"]) + assert prompt.startswith(code_prompts.PRE_PROMPT) diff --git a/tests/test_D/test_run.py b/tests/test_D/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..df02c80fd50f32fc7432d0577ad866ea8048cc82 --- /dev/null +++ b/tests/test_D/test_run.py @@ -0,0 +1,117 @@ +"""Tests for harness/D/run.py -- result-record shape and result-file writing.""" + +import json + +from harness import D +from harness.D import run as harness_run + +_FAKE_ANSWER = { + "prompt_text": "", + "answer_text": "4", + "answer_raw": "<|im_start|>assistant\n4<|im_end|>", + "input_token_count": 2558, + "vision_input_shapes": {"mm_token_type_ids": [1, 2558]}, + "output_token_ids": [19, 151645], + "output_token_count": 2, + "hit_token_limit": False, + "eos_token_ids": [151645], + "generation_seconds": 0.65, + "device": "cuda", + "dtype": "bfloat16", + "library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"}, + "generation_config": { + "max_new_tokens": 16, + "do_sample": False, + "temperature": 0.0, + "top_p": None, + "top_k": None, + "enable_thinking": False, + }, +} + +_FAKE_ROW = { + "id": 7, + "scene_name": "scene0001_00", + "dataset": "scannet", + "question_type": "object_counting", + "question": "How many chairs?", + "options": None, + "ground_truth": "4", +} + +_FAKE_CODE_INFO = { + "spatial_code_format": "explicit", + "spatial_code_path": "/workspace/data/spatial codes/ground truth/explicit/scene0001_00.json", +} + + +def test_results_dir_for_matches_model_and_format_only(): + root = harness_run.results_dir_for("qwen3.5-4b", "compact") + assert root == D.RESULTS_DIR / "qwen3.5-4b" / "compact" + + +def test_results_dir_for_honors_explicit_override(tmp_path): + root = harness_run.results_dir_for("qwen3.5-4b", "explicit", 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, + ) + assert record["question"] == "How many chairs?" + assert record["full_prompt"] == "full prompt text" + assert record["rendered_prompt"] == _FAKE_ANSWER["prompt_text"] + assert record["answer_given"] == "4" + assert record["spatial_code_format"] == "explicit" + assert record["spatial_code_path"] == _FAKE_CODE_INFO["spatial_code_path"] + # No depth/tracking/input_selection/frame_count -- ground truth has no such axis. + assert record["condition"] == "explicit" + assert "input_selection" not in record + assert "frame_count" not in record + assert "depth" not in record + assert "tracking" not in record + assert record["metric"] == "MRA:.5:.95:.05" + assert record["score"] == 1.0 + assert record["scene"] == "scene0001_00" + assert record["question_id"] == 7 + + +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, + ) + assert path == tmp_path / "scene0001_00" / "7.json" + on_disk = json.loads(path.read_text()) + assert on_disk == record + + +def test_build_record_carries_reasoning_fields_when_forced(): + extended_answer = { + **_FAKE_ANSWER, + "reasoning_text": "long reasoning about the spatial code", + "reasoning_raw": "long reasoning about the spatial code<|im_end|>", + "reasoning_token_ids": list(range(50)), + "reasoning_token_count": 50, + "reasoning_hit_limit": True, + "forced": True, + "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, + ) + assert record["reasoning_text"] == "long reasoning about the spatial code" + assert record["forced"] is True + assert record["forced_input_token_count"] == 2510 + + +def test_build_record_defaults_reasoning_fields_when_absent(): + 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, + ) + assert record["reasoning_token_count"] is None + assert record["forced"] is False diff --git a/tests/test_D/test_spatial_codes.py b/tests/test_D/test_spatial_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..222a89376708db874c1e2c03ca531c779dc975bf --- /dev/null +++ b/tests/test_D/test_spatial_codes.py @@ -0,0 +1,31 @@ +"""Tests for harness/D/spatial_codes.py -- loading on-disk ground-truth spatial codes.""" + +import json + +import pytest + +from harness.D import spatial_codes + + +def test_load_spatial_code_rejects_unknown_format(): + with pytest.raises(ValueError): + spatial_codes.load_spatial_code("scene", "bogus") + + +def test_load_spatial_code_raises_clearly_when_missing(tmp_path, monkeypatch): + monkeypatch.setattr( + spatial_codes, "ground_truth_spatial_code_path", lambda *a, **k: str(tmp_path / "missing.json") + ) + with pytest.raises(FileNotFoundError): + spatial_codes.load_spatial_code("scene", "explicit") + + +def test_load_spatial_code_returns_dict_and_path(tmp_path, monkeypatch): + fixture = tmp_path / "scene1.json" + fixture.write_text(json.dumps({"objects": {}, "room": {}})) + monkeypatch.setattr( + spatial_codes, "ground_truth_spatial_code_path", lambda *a, **k: str(fixture) + ) + code, path = spatial_codes.load_spatial_code("scene1", "compact") + assert code == {"objects": {}, "room": {}} + assert path == str(fixture) diff --git a/tests/test_D/test_sweep.py b/tests/test_D/test_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..6c8e5b1bbb97ad37db8e5cc33104d136a7d7438d --- /dev/null +++ b/tests/test_D/test_sweep.py @@ -0,0 +1,28 @@ +"""Tests for harness/D/sweep.py -- multi-config sweep planning.""" + +from harness.A import models as vlm_models +from harness.D import sweep + + +def test_build_plan_covers_every_combination(): + plan = sweep.build_plan(["qwen3.5-2b", "qwen3.5-4b"], ["explicit", "compact"]) + assert len(plan) == 4 + assert ("qwen3.5-2b", "explicit") in plan + assert ("qwen3.5-4b", "compact") in plan + + +def test_build_plan_with_all_registered_models(): + plan = sweep.build_plan(list(vlm_models.available_models()), ["explicit"]) + assert len(plan) == len(vlm_models.available_models()) + + +def test_default_spatial_code_formats_cover_both_when_not_restricted(): + # This session's execution-design decision: D sweeps both formats by default + # (unlike a hypothetical "winning cell only" design) since ground truth costs + # nothing extra to build across formats. + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--spatial-code-formats", default="all") + args = parser.parse_args([]) + assert args.spatial_code_formats == "all" diff --git a/tests/test_D/test_symbolic_eval.py b/tests/test_D/test_symbolic_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..5b344ae8983ee9ba254600146ae82d6d1c778ef8 --- /dev/null +++ b/tests/test_D/test_symbolic_eval.py @@ -0,0 +1,104 @@ +"""Tests for harness/D/symbolic_eval.py -- symbolic solver run directly on ground-truth +spatial codes, no VLM, written through symbolic.run's own writer into +results/symbolic/ground truth//... (not a separate results/D/... location).""" + +import json + +from harness.D import symbolic_eval + +_FAKE_CODE = { + "spatial code schema": {}, + "objects": { + "chair": [ + { + "3D oriented bounding box": { + "3D oriented bounding box center coordinates": [0, 0, 0.5], + "3D oriented bounding box dimensions": [1, 1, 1], + "3D oriented bounding box orientation unit vectors": [ + [1, 0, 0], [0, 1, 0], [0, 0, 1], + ], + }, + "first visible time": 0.0, + } + ] + }, + "room": {"floor boundary polygons": []}, +} + + +def _fake_load(scene_id, spatial_code_format): + return _FAKE_CODE, f"/fake/{scene_id}.json" + + +def test_run_answers_real_questions_for_a_real_ground_truth_scene(tmp_path, monkeypatch): + scene = "13c3e046d7" + monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load) + + results = symbolic_eval.run( + spatial_code_format="compact", scene=scene, results_dir=tmp_path, + ) + + assert results + for record in results: + assert record["scene"] == scene + assert record["result_path"] is not None + + written = list(tmp_path.rglob("*.json")) + assert len(written) == len(results) + native_record = json.loads(written[0].read_text()) + assert native_record["model"] == "symbolic" + assert native_record["condition"] == "ground truth:compact" + assert native_record["scene"] == scene + + +def test_run_selects_ground_truth_spatial_codes_when_writing(tmp_path, monkeypatch): + scene = "13c3e046d7" + monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load) + called = {"select": False, "format": None} + + def fake_select(spatial_code_format): + called["select"] = True + called["format"] = spatial_code_format + + monkeypatch.setattr(symbolic_eval.symbolic_run, "select_ground_truth_spatial_codes", fake_select) + + symbolic_eval.run(spatial_code_format="explicit", scene=scene, results_dir=tmp_path) + + assert called["select"] is True + assert called["format"] == "explicit" + + +def test_run_does_not_write_when_write_results_is_false(tmp_path, monkeypatch): + scene = "13c3e046d7" + monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load) + called = {"select": False} + monkeypatch.setattr( + symbolic_eval.symbolic_run, "select_ground_truth_spatial_codes", + lambda *a, **k: called.__setitem__("select", True), + ) + + results = symbolic_eval.run( + spatial_code_format="compact", scene=scene, results_dir=tmp_path, write_results=False, + ) + + assert called["select"] is False + assert results + for record in results: + assert record["result_path"] is None + assert list(tmp_path.rglob("*.json")) == [] + + +def test_run_forwards_results_dir_to_symbolic_writer(tmp_path, monkeypatch): + scene = "13c3e046d7" + monkeypatch.setattr(symbolic_eval.spatial_codes, "load_spatial_code", _fake_load) + seen = {} + + def fake_write(scene_id, pq, code, results_dir=None): + seen["results_dir"] = results_dir + return tmp_path / "fake.json" + + monkeypatch.setattr(symbolic_eval.symbolic_run, "write_question_result", fake_write) + + symbolic_eval.run(spatial_code_format="compact", scene=scene, results_dir=tmp_path) + + assert seen["results_dir"] == tmp_path diff --git a/tests/test_analysis/__init__.py b/tests/test_analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_analysis/__pycache__/__init__.cpython-311.pyc b/tests/test_analysis/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b67a5944c648766efe8953e028a028b335ec8b71 Binary files /dev/null and b/tests/test_analysis/__pycache__/__init__.cpython-311.pyc differ diff --git a/tests/test_analysis/__pycache__/conftest.cpython-311-pytest-8.3.5.pyc b/tests/test_analysis/__pycache__/conftest.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c41fd01eaa9214c6b1e0c9541c4c372d68cd0a43 Binary files /dev/null and b/tests/test_analysis/__pycache__/conftest.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_analysis/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc b/tests/test_analysis/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c41fd01eaa9214c6b1e0c9541c4c372d68cd0a43 Binary files /dev/null and b/tests/test_analysis/__pycache__/conftest.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_analysis/__pycache__/test_aggregate.cpython-311-pytest-8.3.5.pyc b/tests/test_analysis/__pycache__/test_aggregate.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c00f87676c071254fbf2238c7afbc3a0f8df6c74 Binary files /dev/null and b/tests/test_analysis/__pycache__/test_aggregate.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_analysis/__pycache__/test_aggregate.cpython-311-pytest-9.1.1.pyc b/tests/test_analysis/__pycache__/test_aggregate.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c00f87676c071254fbf2238c7afbc3a0f8df6c74 Binary files /dev/null and b/tests/test_analysis/__pycache__/test_aggregate.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_analysis/__pycache__/test_compare.cpython-311-pytest-8.3.5.pyc b/tests/test_analysis/__pycache__/test_compare.cpython-311-pytest-8.3.5.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cc14607fb2604e50c631f496a2832d4b653efa8 Binary files /dev/null and b/tests/test_analysis/__pycache__/test_compare.cpython-311-pytest-8.3.5.pyc differ diff --git a/tests/test_analysis/__pycache__/test_compare.cpython-311-pytest-9.1.1.pyc b/tests/test_analysis/__pycache__/test_compare.cpython-311-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1ee26177e22f8c31fd9d87024a960d909899fdf Binary files /dev/null and b/tests/test_analysis/__pycache__/test_compare.cpython-311-pytest-9.1.1.pyc differ diff --git a/tests/test_analysis/conftest.py b/tests/test_analysis/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..29a9f396dde007ccbdfbafa84d847b8c7fb7803c --- /dev/null +++ b/tests/test_analysis/conftest.py @@ -0,0 +1,12 @@ +"""Shared import setup for harness.analysis tests.""" + +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + + +def pytest_configure(config): + config.option.importmode = "importlib" diff --git a/tests/test_analysis/test_aggregate.py b/tests/test_analysis/test_aggregate.py new file mode 100644 index 0000000000000000000000000000000000000000..07a64e63048c5989edf5db48a1d5726f321aa8fc --- /dev/null +++ b/tests/test_analysis/test_aggregate.py @@ -0,0 +1,165 @@ +"""Tests for analysis/aggregate.py -- per-category scores + stats, shared across A/B/C.""" + +import json + +from analysis import aggregate as harness_analysis + + +def _record( + model="qwen3.5-2b", condition="uniform:16", question_type="object_counting", + answer_expected="4", metric="MRA:.5:.95:.05", score=1.0, generation_seconds=1.0, + input_token_count=100, output_token_count=4, hit_token_limit=False, + reasoning_token_count=None, forced=None, +): + return { + "model": model, + "condition": condition, + "question_type": question_type, + "answer_expected": answer_expected, + "metric": metric, + "score": score, + "generation_seconds": generation_seconds, + "input_token_count": input_token_count, + "output_token_count": output_token_count, + "hit_token_limit": hit_token_limit, + "reasoning_token_count": reasoning_token_count, + "forced": forced, + } + + +def test_results_dirs_cover_all_four_harnesses(): + assert set(harness_analysis.RESULTS_DIRS) == {"A", "B", "C", "D"} + from harness.A import RESULTS_DIR as a_dir + from harness.B import RESULTS_DIR as b_dir + from harness.C import RESULTS_DIR as c_dir + from harness.D import RESULTS_DIR as d_dir + + assert harness_analysis.RESULTS_DIRS["A"] == a_dir + assert harness_analysis.RESULTS_DIRS["B"] == b_dir + assert harness_analysis.RESULTS_DIRS["C"] == c_dir + assert harness_analysis.RESULTS_DIRS["D"] == d_dir + + +def test_iter_records_reads_every_json_under_results_dir(tmp_path): + scene_dir = tmp_path / "qwen3.5-2b" / "uniform" / "16" / "scene0001_00" + scene_dir.mkdir(parents=True) + (scene_dir / "0.json").write_text(json.dumps(_record())) + (scene_dir / "1.json").write_text(json.dumps(_record(question_type="object_size_estimation"))) + records = list(harness_analysis.iter_records(tmp_path)) + assert len(records) == 2 + + +def test_iter_records_returns_empty_for_missing_dir(tmp_path): + assert list(harness_analysis.iter_records(tmp_path / "does-not-exist")) == [] + + +def test_condition_key_groups_by_model_and_condition(): + key = harness_analysis._condition_key(_record(model="qwen3.5-4b", condition="selective:64")) + assert key == "qwen3.5-4b/selective:64" + + +def test_aggregate_groups_by_model_and_condition(): + records = [ + _record(model="qwen3.5-2b", condition="uniform:16"), + _record(model="qwen3.5-2b", condition="uniform:16", question_type="object_size_estimation"), + _record(model="qwen3.5-4b", condition="uniform:16"), + ] + aggregated = harness_analysis.aggregate(records) + assert set(aggregated) == {"qwen3.5-2b/uniform:16", "qwen3.5-4b/uniform:16"} + assert aggregated["qwen3.5-2b/uniform:16"]["count"] == 2 + assert aggregated["qwen3.5-4b/uniform:16"]["count"] == 1 + + +def test_aggregate_computes_official_scores_via_the_real_scorer(): + records = [_record(score=1.0), _record(score=0.0, question_type="object_size_estimation")] + aggregated = harness_analysis.aggregate(records) + official = aggregated["qwen3.5-2b/uniform:16"]["official"] + assert official["object_counting_MRA:.5:.95:.05"] == 100.0 + assert official["object_size_estimation_MRA:.5:.95:.05"] == 0.0 + assert official["overall"] == 50.0 + + +def test_aggregate_computes_latency_and_token_stats(): + records = [ + _record(generation_seconds=1.0, input_token_count=100, output_token_count=4), + _record(generation_seconds=3.0, input_token_count=200, output_token_count=8), + ] + aggregated = harness_analysis.aggregate(records) + stats = aggregated["qwen3.5-2b/uniform:16"] + assert stats["generation_seconds"]["mean"] == 2.0 + assert stats["generation_seconds"]["total"] == 4.0 + assert stats["input_token_count"]["mean"] == 150.0 + assert stats["output_token_count"]["mean"] == 6.0 + + +def test_aggregate_computes_hit_token_limit_rate(): + records = [ + _record(hit_token_limit=True), _record(hit_token_limit=True), _record(hit_token_limit=False), + ] + aggregated = harness_analysis.aggregate(records) + assert aggregated["qwen3.5-2b/uniform:16"]["hit_token_limit_rate"] == 2 / 3 + + +def test_aggregate_omits_forced_stats_when_no_records_used_extended(): + aggregated = harness_analysis.aggregate([_record()]) + assert "forced_rate" not in aggregated["qwen3.5-2b/uniform:16"] + + +def test_aggregate_includes_forced_stats_for_extended_records(): + records = [ + _record(reasoning_token_count=50, forced=True), + _record(reasoning_token_count=10, forced=False), + ] + aggregated = harness_analysis.aggregate(records) + stats = aggregated["qwen3.5-2b/uniform:16"] + assert stats["forced_rate"] == 0.5 + assert stats["reasoning_token_count"]["mean"] == 30.0 + + +def test_aggregate_returns_empty_dict_for_no_records(): + assert harness_analysis.aggregate([]) == {} + + +def test_flatten_rows_splits_key_and_includes_official_and_summary_columns(): + records = [_record(model="qwen3.5-2b", condition="uniform:16")] + aggregated = harness_analysis.aggregate(records) + rows = harness_analysis.flatten_rows(aggregated) + assert len(rows) == 1 + row = rows[0] + assert row["model"] == "qwen3.5-2b" + assert row["condition"] == "uniform:16" + assert row["count"] == 1 + assert row["official_overall"] == 100.0 + assert row["generation_seconds_mean"] == 1.0 + assert row["hit_token_limit_rate"] == 0.0 + assert "forced_rate" not in row + + +def test_flatten_rows_includes_forced_columns_for_extended_records(): + records = [_record(reasoning_token_count=50, forced=True)] + aggregated = harness_analysis.aggregate(records) + row = harness_analysis.flatten_rows(aggregated)[0] + assert row["forced_rate"] == 1.0 + assert row["reasoning_token_count_mean"] == 50.0 + + +def test_write_csv_round_trips_through_a_real_file(tmp_path): + import csv + + records = [ + _record(model="qwen3.5-2b", condition="uniform:16"), + _record(model="qwen3.5-4b", condition="uniform:16", reasoning_token_count=20, forced=False), + ] + aggregated = harness_analysis.aggregate(records) + csv_path = tmp_path / "out.csv" + harness_analysis.write_csv(aggregated, csv_path) + + with csv_path.open(encoding="utf-8") as stream: + rows = list(csv.DictReader(stream)) + assert len(rows) == 2 + assert {row["model"] for row in rows} == {"qwen3.5-2b", "qwen3.5-4b"} + qwen2b_row = next(row for row in rows if row["model"] == "qwen3.5-2b") + assert qwen2b_row["official_overall"] == "100.0" + assert qwen2b_row["forced_rate"] == "" + qwen4b_row = next(row for row in rows if row["model"] == "qwen3.5-4b") + assert qwen4b_row["forced_rate"] == "0.0" diff --git a/tests/test_analysis/test_compare.py b/tests/test_analysis/test_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..cdfb3005f7370f2b03c1281f1fb3c539e0cadeae --- /dev/null +++ b/tests/test_analysis/test_compare.py @@ -0,0 +1,144 @@ +"""Tests for analysis/compare.py -- cross-harness A vs B vs C comparison.""" + +from analysis import compare as analysis_compare +from analysis.aggregate import RESULTS_DIRS + + +def test_parse_a_key_splits_model_selection_frame_count(): + assert analysis_compare._parse_a_key("qwen3.5-2b/uniform:16") == ( + "qwen3.5-2b", "uniform", "16" + ) + + +def test_parse_bc_key_splits_model_format_selection_frame_count(): + assert analysis_compare._parse_bc_key("qwen3.5-2b/explicit:selective:64") == ( + "qwen3.5-2b", "explicit", "selective", "64" + ) + + +def _fake_iter_records(results_dir): + return [{"dir": str(results_dir)}] + + +def _fake_aggregate_factory(by_dir): + def fake_aggregate(records): + return by_dir.get(records[0]["dir"], {}) + + return fake_aggregate + + +def test_compare_joins_a_b_c_on_shared_dimensions(monkeypatch): + monkeypatch.setattr(analysis_compare, "iter_records", _fake_iter_records) + monkeypatch.setattr( + analysis_compare, + "aggregate", + _fake_aggregate_factory( + { + str(RESULTS_DIRS["A"]): { + "qwen3.5-2b/selective:64": {"official": {"overall": 47.5}}, + }, + str(RESULTS_DIRS["B"]): { + "qwen3.5-2b/explicit:selective:64": {"official": {"overall": 20.0}}, + }, + str(RESULTS_DIRS["C"]): { + "qwen3.5-2b/explicit:selective:64": {"official": {"overall": 60.0}}, + }, + } + ), + ) + + rows = analysis_compare.compare() + key = ("qwen3.5-2b", "selective", "64") + assert rows[key]["A"] == 47.5 + assert rows[key]["B"]["explicit"] == 20.0 + assert rows[key]["C"]["explicit"] == 60.0 + + +def test_compare_leaves_missing_combinations_absent(monkeypatch): + monkeypatch.setattr(analysis_compare, "iter_records", _fake_iter_records) + monkeypatch.setattr( + analysis_compare, + "aggregate", + _fake_aggregate_factory( + { + str(RESULTS_DIRS["A"]): { + "qwen3.5-2b/uniform:8": {"official": {"overall": 40.0}}, + }, + } + ), + ) + + rows = analysis_compare.compare() + key = ("qwen3.5-2b", "uniform", "8") + assert rows[key]["A"] == 40.0 + assert rows[key]["B"] == {} + assert rows[key]["C"] == {} + + +def test_compare_uses_explicit_results_dirs_when_given(monkeypatch): + seen = [] + + def recording_iter_records(results_dir): + seen.append(str(results_dir)) + return [{"dir": str(results_dir)}] + + monkeypatch.setattr(analysis_compare, "iter_records", recording_iter_records) + monkeypatch.setattr(analysis_compare, "aggregate", lambda records: {}) + + analysis_compare.compare( + a_results_dir="/tmp/custom-a", + b_results_dir="/tmp/custom-b", + c_results_dir="/tmp/custom-c", + ) + assert seen == ["/tmp/custom-a", "/tmp/custom-b", "/tmp/custom-c"] + + +def test_format_score_handles_none(): + assert analysis_compare._format_score(None) == "-" + assert analysis_compare._format_score(47.5) == "47.50" + + +def test_flatten_rows_produces_per_format_columns(): + rows = { + ("qwen3.5-2b", "selective", "64"): { + "A": 47.5, + "B": {"explicit": 20.0, "compact": 22.0}, + "C": {"explicit": 60.0}, + }, + } + flat = analysis_compare.flatten_rows(rows) + assert len(flat) == 1 + row = flat[0] + assert row["model"] == "qwen3.5-2b" + assert row["selection"] == "selective" + assert row["frames"] == "64" + assert row["A"] == 47.5 + assert row["B_explicit"] == 20.0 + assert row["B_compact"] == 22.0 + assert row["C_explicit"] == 60.0 + assert row["C_compact"] is None + + +def test_write_csv_round_trips_through_a_real_file(tmp_path): + import csv + + rows = { + ("qwen3.5-2b", "selective", "64"): { + "A": 47.5, + "B": {"explicit": 20.0}, + "C": {"explicit": 60.0}, + }, + ("qwen3.5-4b", "uniform", "16"): {"A": 30.0, "B": {}, "C": {}}, + } + csv_path = tmp_path / "compare.csv" + analysis_compare.write_csv(rows, csv_path) + + with csv_path.open(encoding="utf-8") as stream: + read_rows = list(csv.DictReader(stream)) + assert len(read_rows) == 2 + row_2b = next(r for r in read_rows if r["model"] == "qwen3.5-2b") + assert row_2b["A"] == "47.5" + assert row_2b["B_explicit"] == "20.0" + assert row_2b["C_explicit"] == "60.0" + row_4b = next(r for r in read_rows if r["model"] == "qwen3.5-4b") + assert row_4b["B_explicit"] == ""