diff --git a/README.md b/README.md index e70c9bceeeb98017ae9602e1c9c490c4aced202f..59c4ec8b4e2883cd3d41b435b0cd5bf574a73052 100644 --- a/README.md +++ b/README.md @@ -256,12 +256,12 @@ Files: ### Harness C: Frames Plus Spatial Code ```bash -python -m harness.C.run --model qwen3.5-4b --depth metric --tracking tracking --input-selection uniform --frames 32 --spatial-code-source frames --spatial-code-input-selection selective --spatial-code-frames 64 --scene SCENE -python -m harness.C.launch --model qwen3.5-4b --depth metric --tracking tracking --input-selection uniform --frames 32 --spatial-code-source frames --spatial-code-input-selection selective --spatial-code-frames 64 -python -m harness.C.sweep --models all --depths metric --trackings tracking --input-selections uniform --frames 32 --spatial-code-sources frames --spatial-code-input-selections selective --spatial-code-frames 64 -python -m harness.C.run --model qwen3.5-4b --depth metric --tracking tracking --input-selection uniform --frames 32 --spatial-code-source video --scene SCENE -python -m harness.C.launch --model qwen3.5-4b --depth metric --tracking tracking --input-selection uniform --frames 32 --spatial-code-source video -python -m harness.C.sweep --models all --depths metric --trackings tracking --input-selections uniform --frames 32 --spatial-code-sources video +python -m harness.C.run --model qwen3.5-4b --depth metric --tracking tracking --input-selection uniform --frames 32 --scene SCENE +python -m harness.C.launch --model qwen3.5-4b --depth metric --tracking tracking --input-selection uniform --frames 32 +python -m harness.C.sweep --models all --depths metric --trackings tracking --input-selections uniform --frames 32 +python -m harness.C.run --model qwen3.5-4b --depth metric --tracking tracking --video --scene SCENE +python -m harness.C.launch --model qwen3.5-4b --depth metric --tracking tracking --video +python -m harness.C.sweep --models all --depths metric --trackings tracking --video ``` Files: @@ -270,7 +270,7 @@ Files: - `harness/C/prompts.py`: combined frames + code prompt construction - `harness/C/run.py`: one model/config/scene - `harness/C/launch.py`: persistent GPU workers for one config -- `harness/C/sweep.py`: grid over independent visual-input and spatial-code-input axes +- `harness/C/sweep.py`: grid over model/depth/tracking/input/frame axes ### Harness F: Symbolic Solver As A Harness diff --git a/analysis/D_reports.py b/analysis/D_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..79ae89f877a33c73d38bd3b7e5f42a105f32eb06 --- /dev/null +++ b/analysis/D_reports.py @@ -0,0 +1,34 @@ +"""Generate the high-level within-D report.""" + +import argparse +from pathlib import Path +from analysis.letters_reports import generate_letter + +LETTER = "D" + + +def generate( + results_dir, + protocols=(), + output_dir=None, + spatial_codes_dir=None, + profile_path=None, +): + return generate_letter( + LETTER, results_dir, protocols, output_dir, spatial_codes_dir, profile_path + ) + + +def main(): + p = argparse.ArgumentParser(description="Generate the high-level within-D report.") + p.add_argument("--results-dir", default="/root/results/D") + p.add_argument("--protocol", action="append", default=[]) + p.add_argument("--output-dir", default="/workspace/reports") + p.add_argument("--spatial-codes-dir", default=None) + a = p.parse_args() + result = generate(a.results_dir, a.protocol, a.output_dir, a.spatial_codes_dir) + print(f"wrote {result['path']}") + + +if __name__ == "__main__": + main() diff --git a/analysis/letters_reports.py.orig b/analysis/letters_reports.py.orig new file mode 100644 index 0000000000000000000000000000000000000000..5aaddcb688bb79bbd13a0bfef081b4bb13d9b6e3 --- /dev/null +++ b/analysis/letters_reports.py.orig @@ -0,0 +1,574 @@ +"""Comprehensive, matched A/B/C result analysis. + +Reports coverage, score, question-type and dataset breakdowns, response/prompt/token +lengths, latency, limit/forced rates, spatial-code size for B/C, score relationships, +and pairwise deltas on exact question intersections. Stored per-question scores are +used directly; ``mean_score`` is not the category-weighted official VSI overall. +""" +from __future__ import annotations + +import argparse +import json +import math +import statistics +import random +from collections import Counter, defaultdict +from itertools import combinations +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +DEFAULT_DIRS = {h: ROOT / "results" / h for h in "ABC"} +NUMERIC_FIELDS = ( + "input_token_count", "output_token_count", "reasoning_token_count", + "generation_seconds", "forced_input_token_count", +) +TEXT_FIELDS = ( + "answer_given", "answer_raw", "reasoning_text", "full_prompt", "rendered_prompt", +) + + +def iter_records(directory): + root = Path(directory) + if not root.is_dir(): + return + for path in sorted(root.rglob("*.json")): + try: + with path.open(encoding="utf-8") as stream: + record = json.load(stream) + except (OSError, json.JSONDecodeError): + continue + if isinstance(record, dict) and "question_id" in record and "condition" in record: + yield record + + +def protocol_selected(protocol, selectors): + if protocol is None: + return not selectors + return not selectors or any( + protocol == item or ("/" not in item and protocol.startswith(item + "/")) + for item in selectors + ) + + +def cell_identity(harness, record): + protocol = record.get("protocol") or record["condition"].split(":", 1)[0] + selection = record.get("frame_selection", record.get("input_selection")) + common = { + "harness": harness, "model": record.get("model"), "protocol": protocol, + "selection": selection, "frames": str(record.get("frame_count")), + } + if harness in ("B", "C"): + common.update({ + "format": record.get("spatial_code_format"), "depth": record.get("depth"), + "tracking": record.get("tracking"), + }) + return tuple(sorted(common.items())) + + +def identity_dict(identity): + return dict(identity) + + +def cell_label(identity): + d = identity_dict(identity) + parts = [d["harness"], d.get("model"), d.get("protocol"), d.get("selection"), d.get("frames")] + if d["harness"] in ("B", "C"): + parts += [d.get("format"), d.get("depth"), d.get("tracking")] + return "/".join("?" if value is None else str(value) for value in parts) + + +def comparison_key(identity): + d = identity_dict(identity) + return d.get("model"), d.get("protocol"), d.get("selection"), d.get("frames") + + +def _numbers(records, getter): + out = [] + for record in records: + value = getter(record) + if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value): + out.append(float(value)) + return out + + +def numeric_summary(values): + values = sorted(values) + if not values: + return None + def percentile(p): + position = (len(values) - 1) * p + low, high = math.floor(position), math.ceil(position) + if low == high: + return values[low] + return values[low] + (values[high] - values[low]) * (position - low) + return { + "n": len(values), "mean": statistics.mean(values), "median": statistics.median(values), + "min": values[0], "p25": percentile(.25), "p75": percentile(.75), "max": values[-1], + "stdev": statistics.stdev(values) if len(values) > 1 else 0.0, + } + + +def pearson(xs, ys): + pairs = [(float(x), float(y)) for x, y in zip(xs, ys) + if isinstance(x, (int, float)) and isinstance(y, (int, float)) + and not isinstance(x, bool) and not isinstance(y, bool) + and math.isfinite(x) and math.isfinite(y)] + if len(pairs) < 2: + return None + x, y = zip(*pairs); mx, my = statistics.mean(x), statistics.mean(y) + dx, dy = [v - mx for v in x], [v - my for v in y] + denom = math.sqrt(sum(v*v for v in dx) * sum(v*v for v in dy)) + return sum(a*b for a, b in zip(dx, dy)) / denom if denom else None + + +def spatial_code_bytes(record, cache): + path = record.get("spatial_code_path") + if not path: + return None + if path not in cache: + try: + cache[path] = Path(path).stat().st_size + except OSError: + cache[path] = None + return cache[path] + + +def breakdown(records, field): + groups = defaultdict(list) + for record in records: + groups[str(record.get(field) or "")].append(record) + return { + name: { + "count": len(group), + "mean_score": numeric_summary(_numbers(group, lambda r: r.get("score")))["mean"] + if _numbers(group, lambda r: r.get("score")) else None, + "scenes": len({r.get("scene") for r in group}), + } + for name, group in sorted(groups.items()) + } + + +def summarize_cell(records, code_cache): + scores = _numbers(records, lambda r: r.get("score")) + numeric = {field: numeric_summary(_numbers(records, lambda r, f=field: r.get(f))) + for field in NUMERIC_FIELDS} + text = {field + "_chars": numeric_summary(_numbers( + records, lambda r, f=field: len(r[f]) if isinstance(r.get(f), str) else None + )) for field in TEXT_FIELDS} + code_sizes = _numbers(records, lambda r: spatial_code_bytes(r, code_cache)) + relationships = {} + measures = { + **{field: lambda r, f=field: r.get(f) for field in NUMERIC_FIELDS}, + **{field + "_chars": lambda r, f=field: len(r[f]) if isinstance(r.get(f), str) else None + for field in TEXT_FIELDS}, + "spatial_code_bytes": lambda r: spatial_code_bytes(r, code_cache), + } + for name, getter in measures.items(): + pairs = [(r.get("score"), getter(r)) for r in records] + relationships["score_vs_" + name] = pearson( + [p[1] for p in pairs], [p[0] for p in pairs] + ) + return { + "questions": len(records), "unique_question_ids": len({r["question_id"] for r in records}), + "scenes": len({r.get("scene") for r in records}), + "mean_score": statistics.mean(scores) if scores else None, + "score_distribution": numeric_summary(scores), + "question_types": breakdown(records, "question_type"), + "datasets": breakdown(records, "dataset"), + "numeric": numeric, "text_lengths": text, + "rates": { + "hit_token_limit": statistics.mean(bool(r.get("hit_token_limit")) for r in records) if records else None, + "reasoning_hit_limit": statistics.mean(bool(r.get("reasoning_hit_limit")) for r in records) if records else None, + "forced": statistics.mean(bool(r.get("forced")) for r in records) if records else None, + "scored": len(scores) / len(records) if records else None, + }, + "spatial_codes": { + "records_with_path": sum(bool(r.get("spatial_code_path")) for r in records), + "unique_paths": len({r.get("spatial_code_path") for r in records if r.get("spatial_code_path")}), + "readable_file_bytes": numeric_summary(code_sizes), + }, + "relationships": relationships, + } + + +def paired_breakdown(x, y, common, field): + groups = defaultdict(list) + for qid in common: + name = str(x[qid].get(field) or y[qid].get(field) or "") + groups[name].append(y[qid].get("score") - x[qid].get("score")) + return {name: {"count": len(vals), "mean_delta": statistics.mean(vals)} + for name, vals in sorted(groups.items()) if vals} + + +def _scene_bootstrap(x, y, common, iterations=1000, seed=0): + by_scene=defaultdict(list) + for qid in common: + by_scene[str(x[qid].get("scene") or y[qid].get("scene") or "")].append( + y[qid]["score"]-x[qid]["score"] + ) + if not by_scene: + return {"scenes":0,"iterations":iterations,"ci_low":None,"ci_high":None,"p_value":None} + scenes=sorted(by_scene); rng=random.Random(seed); draws=[] + for _ in range(iterations): + values=[] + for _ in scenes: values.extend(by_scene[rng.choice(scenes)]) + draws.append(statistics.mean(values)) + draws.sort(); low=int(.025*iterations); high=min(iterations-1,int(.975*iterations)) + below=sum(v<=0 for v in draws)/iterations; above=sum(v>=0 for v in draws)/iterations + return {"scenes":len(scenes),"iterations":iterations,"seed":seed,"confidence":.95, + "ci_low":draws[low],"ci_high":draws[high], + "p_value":max(1/iterations,min(1.0,2*min(below,above)))} + +def paired_report(x_records, y_records): + x = {r["question_id"]: r for r in x_records if isinstance(r.get("score"), (int, float))} + y = {r["question_id"]: r for r in y_records if isinstance(r.get("score"), (int, float))} + common = sorted(set(x) & set(y)) + deltas = [y[q]["score"] - x[q]["score"] for q in common] + solved_x={q for q in common if x[q]["score"]>=1.0}; solved_y={q for q in common if y[q]["score"]>=1.0} + union=solved_x|solved_y + telemetry = {} + for field in NUMERIC_FIELDS: + vals = [y[q].get(field) - x[q].get(field) for q in common + if isinstance(x[q].get(field), (int, float)) and isinstance(y[q].get(field), (int, float))] + telemetry[field + "_delta"] = numeric_summary(vals) + return { + "common_questions": len(common), "x_full_questions": len(x), "y_full_questions": len(y), + "mean_score_delta_y_minus_x": statistics.mean(deltas) if deltas else None, + "score_delta_distribution": numeric_summary(deltas), + "wins_y": sum(d > 0 for d in deltas), "ties": sum(d == 0 for d in deltas), + "wins_x": sum(d < 0 for d in deltas), + "scene_clustered_bootstrap": _scene_bootstrap(x,y,common), + "solved_overlap": {"x":len(solved_x),"y":len(solved_y),"both":len(solved_x&solved_y), + "only_x":len(solved_x-solved_y),"only_y":len(solved_y-solved_x), + "jaccard":len(solved_x&solved_y)/len(union) if union else None}, + "by_question_type": paired_breakdown(x, y, common, "question_type"), + "by_dataset": paired_breakdown(x, y, common, "dataset"), + "telemetry_deltas": telemetry, + } + + +def analyze(directories=None, protocols=()): + directories = directories or DEFAULT_DIRS + cells = defaultdict(list) + for harness, directory in directories.items(): + for record in iter_records(directory): + protocol = record.get("protocol") or record["condition"].split(":", 1)[0] + if protocol_selected(protocol, protocols): + cells[cell_identity(harness, record)].append(record) + code_cache = {} + report = {"cells": {}, "comparison_groups": {}} + for identity, records in cells.items(): + report["cells"][cell_label(identity)] = { + "identity": identity_dict(identity), "summary": summarize_cell(records, code_cache) + } + grouped = defaultdict(list) + for identity in cells: + grouped[comparison_key(identity)].append(identity) + for key, identities in grouped.items(): + name = "/".join("?" if v is None else str(v) for v in key) + pairs = {} + for first, second in combinations(sorted(identities, key=cell_label), 2): + pairs[cell_label(first) + " -> " + cell_label(second)] = paired_report(cells[first], cells[second]) + id_sets = [{r["question_id"] for r in cells[i]} for i in identities] + report["comparison_groups"][name] = { + "cells": [cell_label(i) for i in identities], + "all_cell_common_questions": len(set.intersection(*id_sets)) if id_sets else 0, + "pairwise": pairs, + } + return report + + +def main(): + parser = argparse.ArgumentParser() + for harness in "abc": + parser.add_argument(f"--{harness}-results-dir", default=None) + parser.add_argument("--protocol", action="append", default=[], + help="repeatable; family 'truncated' includes truncated/") + parser.add_argument( + "--output-dir", default=str(ROOT / "reports"), + help="report directory (default: workspace/reports)", + ) + parser.add_argument( + "--json-out", default=None, + help="override the JSON report path (default: /comprehensive.json)", + ) + args = parser.parse_args() + dirs = {h.upper(): Path(getattr(args, f"{h}_results_dir") or DEFAULT_DIRS[h.upper()]) for h in "abc"} + report = analyze(dirs, args.protocol) + text = json.dumps(report, indent=1) + output_path = Path(args.json_out) if args.json_out else Path(args.output_dir) / "comprehensive.json" + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(text + "\n", encoding="utf-8") + print(f"wrote {output_path}") + + + +# --- Modular profile-driven interface (v2) --- +from datetime import datetime, timezone + +# Built-in, versioned harness profiles. +PROFILE_VERSION = 1 +BUILTINS = { + "A":{"letter":"A","kind":"vlm","input_source":"frames","axes":["model","protocol","selection","frames"],"capabilities":["tokens","latency","reasoning","frames"]}, + "B":{"letter":"B","kind":"vlm","input_source":"perceived","axes":["model","protocol","format","depth","tracking","selection","frames"],"capabilities":["tokens","latency","reasoning","spatial_code"]}, + "C":{"letter":"C","kind":"vlm","input_source":"frames_perceived","axes":["model","protocol","format","depth","tracking","selection","frames"],"capabilities":["tokens","latency","reasoning","frames","spatial_code"]}, + "D":{"letter":"D","kind":"vlm","input_source":"ground_truth","axes":["model","protocol","format"],"capabilities":["tokens","latency","reasoning","spatial_code"]}, + "F":{"letter":"F","kind":"solver","input_source":"dynamic","axes":["source","depth","tracking","selection","frames","format","spatial_code_model"],"capabilities":["spatial_code","solver"]}, +} +def validate_profile(profile): + p=dict(profile); letter=str(p.get("letter","")).upper() + if len(letter)!=1 or not letter.isalpha(): raise ValueError("profile letter must be one alphabetic character") + if letter=="E": raise ValueError("E is explicitly excluded") + p["letter"]=letter; p.setdefault("kind","generic"); p.setdefault("input_source","unknown"); p.setdefault("axes",["model","protocol"]); p.setdefault("capabilities",[]); p["profile_version"]=PROFILE_VERSION + return p +def load_profile(letter,path=None): + letter=letter.upper() + if letter=="E": raise ValueError("E is explicitly excluded") + if path: + p=json.loads(Path(path).read_text()); p.setdefault("letter",letter) + if p["letter"].upper()!=letter: raise ValueError(f"profile letter mismatch for {letter}") + return validate_profile(p) + return validate_profile(BUILTINS.get(letter,{"letter":letter,"kind":"generic","input_source":"unknown","axes":["model","protocol","format","depth","tracking","selection","frames"]})) + +ANALYSIS_VERSION = 2 + +def discover_records(letter, directory, profile, protocols=(), spatial_codes_dir=None): + root=Path(directory); records=[]; warnings=[] + if not root.is_dir(): return records,[{"code":"missing_directory","path":str(root)}] + for path in sorted(root.rglob("*.json")): + if path.name.startswith("_"): continue + try: record=json.loads(path.read_text(encoding="utf-8")) + except (OSError,json.JSONDecodeError) as exc: + warnings.append({"code":"unreadable_json","path":str(path),"detail":str(exc)}); continue + if not isinstance(record,dict) or record.get("question_id") is None or record.get("score") is None: + warnings.append({"code":"not_question_record","path":str(path)}); continue + record=dict(record); record["_result_path"]=str(path); record["_relative_path"]=path.relative_to(root).parts + record=_normalize_record(letter,record,profile) + code_path=record.get("spatial_code_path") + if code_path and not Path(code_path).is_file() and spatial_codes_dir: + marker="spatial codes/" + suffix=str(code_path).split(marker,1)[-1] if marker in str(code_path) else None + candidate=Path(spatial_codes_dir)/suffix if suffix else None + if candidate and candidate.is_file(): record["spatial_code_path"]=str(candidate) + else: warnings.append({"code":"unresolved_spatial_code_path","path":str(path),"recorded_path":str(code_path)}) + if letter!="F" and not protocol_selected(record.get("protocol"),protocols): continue + records.append(record) + return records,warnings + +def _normalize_record(letter,r,profile): + r["format"]=r.get("spatial_code_format") or r.get("format") + r["selection"]=r.get("frame_selection") or r.get("input_selection") or r.get("input") + r["frames"]=r.get("frame_count") or r.get("number_of_frames") + if not r.get("protocol") and r.get("condition") and letter!="F": r["protocol"]=r["condition"].split(":",1)[0] + if letter=="F": + parts=list(r.get("_relative_path",())) + top=parts[0].lower() if parts else "" + if top in ("ground truth","ground_truth"): + r.update(source="ground_truth",depth=None,tracking=None,selection=None,frames=None) + r["format"]=r.get("format") or (parts[1] if len(parts)>1 else None) + else: + r["source"]="perceived" + offset=1 + if top=="perceived": r["depth"]=r.get("depth") or (parts[1] if len(parts)>1 else None); offset=2 + elif top in ("metric","relative"): r["depth"]=r.get("depth") or top + r["tracking"]=r.get("tracking") or (parts[offset] if len(parts)>offset else None) + r["selection"]=r.get("selection") or (parts[offset+1] if len(parts)>offset+1 else None) + r["frames"]=r.get("frames") or (parts[offset+2] if len(parts)>offset+2 else None) + candidate=parts[offset+3] if len(parts)>offset+3 else None + if candidate and not candidate.startswith("scene") and len(candidate)!=10: r["format"]=r.get("format") or candidate + r["spatial_code_model"]=r.get("spatial_code_model") + r["protocol"]=None + return r + +def modular_identity(letter,record,profile): + values={"harness":letter} + for axis in profile["axes"]: values[axis]=str(record.get(axis)) if record.get(axis) is not None else None + return tuple(sorted(values.items())) + +def modular_label(identity): + d=dict(identity); return "/".join([d.pop("harness")]+[f"{k}={v or '?'}" for k,v in sorted(d.items())]) + +def _controlled(first,second,profile): + a,b=dict(first),dict(second); diffs=[axis for axis in profile["axes"] if a.get(axis)!=b.get(axis)] + return len(diffs)==1,diffs + +def _compatible(a,b,profiles): + x,y=dict(a),dict(b); lx,ly=x["harness"],y["harness"] + warnings=[] + if lx==ly: return False,[],["same_harness"] + # F source semantics. + f=x if lx=="F" else y if ly=="F" else None; other=y if lx=="F" else x + if f: + expected="ground_truth" if other["harness"]=="D" else "perceived" if other["harness"] in ("B","C") else None + if expected and f.get("source")!=expected: return False,[],["incompatible_F_source"] + shared=[] + for axis in ("model","format","depth","tracking","selection","frames"): + av,bv=x.get(axis),y.get(axis) + if axis=="model" and f: continue + if av is not None and bv is not None: + if av!=bv: return False,[],[f"conflicting_{axis}"] + shared.append(axis) + else: warnings.append(f"unmatched_{axis}") + if not f and x.get("protocol") is not None and y.get("protocol") is not None: + if x["protocol"]!=y["protocol"]: return False,[],["conflicting_protocol"] + shared.append("protocol") + return True,shared,warnings + +def analyze_modular(cells, profiles, protocols=(), requested_pairs=(), spatial_codes_dir=None): + all_cells=defaultdict(list); warnings={}; sources={} + for letter,directory in cells.items(): + recs,warns=discover_records(letter,directory,profiles[letter],protocols,spatial_codes_dir); warnings[letter]=warns; sources[letter]=str(directory) + for r in recs: all_cells[modular_identity(letter,r,profiles[letter])].append(r) + cache={}; per={letter:{"manifest":{"analysis_version":ANALYSIS_VERSION,"profile_version":PROFILE_VERSION,"generated_at":datetime.now(timezone.utc).isoformat(),"letter":letter,"profile":profiles[letter],"source":sources[letter],"protocols":list(protocols)},"cells":{},"within_harness_comparisons":{},"integrity_warnings":warnings[letter]} for letter in cells} + for ident,recs in all_cells.items(): per[dict(ident)["harness"]]["cells"][modular_label(ident)]={"identity":dict(ident),"summary":summarize_cell(recs,cache)} + for letter in cells: + ids=[i for i in all_cells if dict(i)["harness"]==letter] + for a,b in combinations(ids,2): + ok,diffs=_controlled(a,b,profiles[letter]) + if ok: per[letter]["within_harness_comparisons"][modular_label(a)+" -> "+modular_label(b)]={"varied_axis":diffs[0],**paired_report(all_cells[a],all_cells[b])} + allowed={tuple(sorted(p)) for p in requested_pairs} + cross={} + ids=list(all_cells) + for a,b in combinations(ids,2): + letters=tuple(sorted((dict(a)["harness"],dict(b)["harness"]))) + if letters[0]==letters[1] or (allowed and letters not in allowed): continue + ok,shared,warns=_compatible(a,b,profiles) + if ok: cross[modular_label(a)+" -> "+modular_label(b)]={"letters":letters,"shared_axes":shared,"alignment_warnings":warns,**paired_report(all_cells[a],all_cells[b])} + manifest={"analysis_version":ANALYSIS_VERSION,"profile_version":PROFILE_VERSION,"generated_at":datetime.now(timezone.utc).isoformat(),"letters":sorted(cells),"sources":sources,"protocols":list(protocols),"requested_pairs":[":".join(p) for p in requested_pairs]} + return per,{"manifest":manifest,"cross_harness_comparisons":cross,"harness_summaries":{l:{"cell_count":len(per[l]["cells"]),"warning_count":len(per[l]["integrity_warnings"])} for l in per}} + +def parse_assignment(value,option): + if "=" not in value: raise argparse.ArgumentTypeError(f"{option} must be LETTER=PATH") + letter,path=value.split("=",1); letter=letter.upper() + if len(letter)!=1 or not letter.isalpha() or letter=="E": raise argparse.ArgumentTypeError("letter must be one alphabetic character other than E") + return letter,path + +def export_reports(per,combined,output_dir): + out=Path(output_dir); out.mkdir(parents=True,exist_ok=True); paths=[] + for letter,report in sorted(per.items()): + path=out/f"{letter}_report.json"; path.write_text(json.dumps(report,indent=1)+"\n"); paths.append(path) + if len(per) > 1: + name="".join(sorted(per))+"_report.json" + path=out/name + path.write_text(json.dumps(combined,indent=1)+"\n") + paths.append(path) + return paths + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument("--cell",action="append",default=[],help="repeatable LETTER=PATH; E is excluded") + parser.add_argument("--profile",action="append",default=[],help="optional LETTER=profile.json") + parser.add_argument("--compare",action="append",default=[],help="optional pair restriction, e.g. A:B") + parser.add_argument("--protocol",action="append",default=[],help="repeatable; truncated includes truncated/") + parser.add_argument("--output-dir",default=str(ROOT/"reports")) + parser.add_argument("--spatial-codes-dir",default=None,help="optional local root used to rebase stale recorded code paths") + for h in "abc": parser.add_argument(f"--{h}-results-dir",default=None,help=argparse.SUPPRESS) + args=parser.parse_args(); cells=dict(parse_assignment(v,"--cell") for v in args.cell) + for h in "abc": + value=getattr(args,f"{h}_results_dir") + if value: cells[h.upper()]=value + if not cells: parser.error("provide at least one --cell LETTER=PATH") + profile_paths=dict(parse_assignment(v,"--profile") for v in args.profile) + profiles={letter:load_profile(letter,profile_paths.get(letter)) for letter in cells} + pairs=[] + for value in args.compare: + bits=[x.upper() for x in value.split(":")] + if len(bits)!=2 or any(x not in cells for x in bits): parser.error(f"invalid --compare {value}") + pairs.append(tuple(bits)) + per,combined=analyze_modular(cells,profiles,args.protocol,pairs,args.spatial_codes_dir) + for path in export_reports(per,combined,args.output_dir): print(f"wrote {path}") + + +# Consolidated analysis helpers formerly split across stats/solvability/sufficiency/audits. +def _official_scores(records): + records=list(records) + try: + import importlib.util, os + path=os.environ.get("HARNESS_OFFICIAL_EVAL","/root/data/thinking-in-space/lmms_eval/tasks/vsibench/utils.py") + spec=importlib.util.spec_from_file_location("analysis_vsi_official_eval",path) + module=importlib.util.module_from_spec(spec); spec.loader.exec_module(module) + docs=[{"question_type":r["question_type"],"ground_truth":r.get("answer_expected"),r["metric"]:r["score"]} for r in records] + return module.vsibench_aggregate_results(docs) + except (OSError,ImportError,AttributeError,TypeError): + scores=[r.get("score") for r in records if isinstance(r.get("score"),(int,float))] + return {"overall":statistics.mean(scores)*100 if scores else None,"scoring_mode":"stored_per_question_mean_fallback"} + +def holm_bonferroni(p_values): + ordered=sorted(p_values.items(),key=lambda item:item[1]); total=len(ordered); out={}; running=0.0 + for rank,(name,p) in enumerate(ordered): + running=max(running,min(1.0,(total-rank)*p)); out[name]=running + return out + +def solved_set_overlap(cells,threshold=1.0): + maps={name:{r["question_id"]:r.get("score") for r in records} for name,records in cells.items()} + common=set.intersection(*(set(m) for m in maps.values())) if maps else set(); solved={n:{q for q in common if v[q] is not None and v[q]>=threshold} for n,v in maps.items()} + pairs={} + for a,b in combinations(sorted(solved),2): + union=solved[a]|solved[b]; pairs[f"{a}|{b}"]={"jaccard":len(solved[a]&solved[b])/len(union) if union else None,"both":len(solved[a]&solved[b]),f"only_{a}":len(solved[a]-solved[b]),f"only_{b}":len(solved[b]-solved[a])} + return {"questions":len(common),"solved":{n:len(v) for n,v in solved.items()},"pairs":pairs} + +def sufficiency_decomposition(vlm_records,solver_records,threshold=1.0,exclude=()): + cert={r["question_id"]:r.get("score") is not None and r["score"]>=threshold for r in solver_records}; buckets={"certified":[],"uncertified":[]} + for r in vlm_records: + if r.get("question_type") in set(exclude) or r.get("question_id") not in cert: continue + buckets["certified" if cert[r["question_id"]] else "uncertified"].append(r.get("score")) + def summary(vals): + valid=[v for v in vals if isinstance(v,(int,float))]; correct=sum(v>=threshold for v in valid) + return {"count":len(vals),"mean_score":statistics.mean(valid) if valid else None,"vlm_correct":correct,"vlm_wrong":len(vals)-correct} + return {name:summary(vals) for name,vals in buckets.items()} + +def solver_depth_table(records): + try: from symbolic import adapters,solver + except ImportError: return {"status":"unavailable","reason":"symbolic solver imports unavailable"} + cache={}; buckets=defaultdict(list) + for r in records: + path=r.get("spatial_code_path") + if not path: continue + try: + if path not in cache: cache[path]=adapters.adapt_spatial_code(json.loads(Path(path).read_text())) + solver.answer(r["question_type"],r["question"],r.get("options"),cache[path]); depth=solver.LAST_ANSWER_OPS.get("total") + except (OSError,KeyError,ValueError): continue + if depth is not None and isinstance(r.get("score"),(int,float)): buckets["0-2" if depth<=2 else "3-8" if depth<=8 else "9-20" if depth<=20 else "21-inf"].append((depth,r["score"])) + return {k:{"count":len(v),"mean_depth":statistics.mean(x for x,_ in v),"mean_score":statistics.mean(y for _,y in v)} for k,v in buckets.items()} + +_NUMBER_RE=__import__('re').compile(r"[-+]?\d+(?:\.\d+)?") +def deterministic_cot_audit(records,tolerance=.01): + def nums(value): return [float(x) for x in _NUMBER_RE.findall(str(value or ''))] + audits=[]; cache={} + for r in records: + reasoning=r.get("reasoning_text"); path=r.get("spatial_code_path") + if not reasoning or not path: continue + try: + if path not in cache: cache[path]=nums(Path(path).read_text()) + except OSError: continue + sources=cache[path]+nums(r.get("question"))+sum((nums(x) for x in r.get("options") or []),[]); cited=nums(reasoning) + fabricated=[v for v in cited if not (abs(v)<=12 and v.is_integer()) and not any(abs(v-x)<=tolerance*max(1,abs(x)) for x in sources)] + audits.append({"question_id":r["question_id"],"score":r.get("score"),"cited":len(cited),"fabricated":len(fabricated)}) + wrong=[a for a in audits if a["score"] is not None and a["score"]<1]; bad=[a for a in wrong if a["fabricated"]] + return {"audited":len(audits),"wrong":len(wrong),"wrong_with_fabrication":len(bad),"fabrication_share_of_wrong":len(bad)/len(wrong) if wrong else None} + +def generate_letter(letter,results_dir,protocols=(),output_dir=None,spatial_codes_dir=None,profile_path=None): + letter=letter.upper(); profile=load_profile(letter,profile_path) + per,combined=analyze_modular({letter:Path(results_dir)},{letter:profile},protocols,(),spatial_codes_dir) + paths=export_reports(per,combined,output_dir or ROOT/'reports') + return {"report":per[letter],"path":paths[0]} + +def generate(cells,protocols=(),comparisons=(),output_dir=None,profile_paths=None,spatial_codes_dir=None): + normalized={str(k).upper():Path(v) for k,v in cells.items()} + if 'E' in normalized: raise ValueError('E is explicitly excluded') + profile_paths={str(k).upper():v for k,v in (profile_paths or {}).items()}; profiles={l:load_profile(l,profile_paths.get(l)) for l in normalized}; pairs=[] + for pair in comparisons: + pair=tuple(x.upper() for x in (pair.split(':') if isinstance(pair,str) else pair)) + if len(pair)!=2 or any(x not in normalized for x in pair): raise ValueError(f'invalid comparison {pair}') + pairs.append(pair) + per,combined=analyze_modular(normalized,profiles,protocols,pairs,spatial_codes_dir); paths=export_reports(per,combined,output_dir or ROOT/'reports') + return {"letter_reports":per,"combined_report":combined,"paths":paths} + +def main(): + parser=argparse.ArgumentParser(description='Generate arbitrary mixed letter reports; E is excluded.') + parser.add_argument('--cell',action='append',required=True); parser.add_argument('--profile',action='append',default=[]); parser.add_argument('--compare',action='append',default=[]); parser.add_argument('--protocol',action='append',default=[]); parser.add_argument('--output-dir',default=str(ROOT/'reports')); parser.add_argument('--spatial-codes-dir',default=None) + args=parser.parse_args(); cells=dict(parse_assignment(v,'--cell') for v in args.cell); profiles=dict(parse_assignment(v,'--profile') for v in args.profile) + try: result=generate(cells,args.protocol,args.compare,args.output_dir,profiles,args.spatial_codes_dir) + except ValueError as exc: parser.error(str(exc)) + for path in result['paths']: print(f'wrote {path}') +if __name__=='__main__': main() diff --git a/data/.vsi-environment.sh b/data/.vsi-environment.sh new file mode 100644 index 0000000000000000000000000000000000000000..c9ceb9a63a67391f0f71539afc2158f28867d4fd --- /dev/null +++ b/data/.vsi-environment.sh @@ -0,0 +1,17 @@ +# Generated by setup.sh. +# Source this before running inference or the encoder. +export VSI_WORKSPACE_ROOT=/workspace +export VSI_DATA_ROOT=/root/data +export VSI_ROOT=/root/data/VSI-Bench +export VSI_CACHE_ROOT=/root/data/caches +export VSI_CODES=/workspace/data/spatial\ codes +export VSI_MODELS_ROOT=/root/models +export VSI_THINKING_IN_SPACE_ROOT=/root/data/thinking-in-space +export VSI_SELECTED_FRAMES_CACHE=/root/data/caches/selected\ frames +export VSI_DA3_ROOT=/root/models/depth-anything-3 +export VSI_DA3_METRIC_CHECKPOINT=/root/models/depth-anything-3/checkpoints/DA3NESTED-GIANT-LARGE-1.1 +export VSI_SAM3_ROOT=/root/models/sam3 +export VSI_SEGVGGT_ROOT=/root/models/SegVGGT +export VIRTUAL_ENV=/root/.venv +export PATH=/root/.venv/bin:$PATH +export PYTHONPATH=/workspace${PYTHONPATH:+:$PYTHONPATH} diff --git a/data/caches/depth-anything-3.tar.zst b/data/caches/depth-anything-3.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..535b8a66211f19317052ea43071201e3d9094ecb --- /dev/null +++ b/data/caches/depth-anything-3.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e7cb06cb9cc25f35e30cf03dc1a2d975fd1cdb657d83cee375377acefe182ce +size 58480215103 diff --git a/data/caches/depth-anything-3/depth-anything-3-metric-frames.zip b/data/caches/depth-anything-3/depth-anything-3-metric-frames.zip new file mode 100644 index 0000000000000000000000000000000000000000..2a3c81f838de76d963ce6763fa7dfe1eac3a4cdf --- /dev/null +++ b/data/caches/depth-anything-3/depth-anything-3-metric-frames.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d369f754a9349d54cbeb19c20d665f18651902d337fec8e844a5decbc2d4085b +size 54026425128 diff --git a/data/caches/depth-anything-3/depth-anything-3-metric-video.zip b/data/caches/depth-anything-3/depth-anything-3-metric-video.zip new file mode 100644 index 0000000000000000000000000000000000000000..39322b60c76e19e8f2d3790a71841fa52ef45559 --- /dev/null +++ b/data/caches/depth-anything-3/depth-anything-3-metric-video.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bdfc1ef085232e1644c3535b6e5f8117abe53648f97b12db9b6cafa439ada11 +size 60332885871 diff --git a/data/caches/depth-anything-3/depth-anything-3-relative-frames.zip b/data/caches/depth-anything-3/depth-anything-3-relative-frames.zip new file mode 100644 index 0000000000000000000000000000000000000000..09abf9d3317111d4f52e1bedcbd2d71e49b1371f --- /dev/null +++ b/data/caches/depth-anything-3/depth-anything-3-relative-frames.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7399a487380320f863c9f331588aa37845f1b0d00f08674dedf930d0a4919baa +size 4828585754 diff --git a/data/caches/overlay-frames.tar.zst b/data/caches/overlay-frames.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..7e68f18a430060881d6809059b5fb02104eb4912 --- /dev/null +++ b/data/caches/overlay-frames.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b25b608bc8b7c85e5d10ade1514932e7ef6d9ef9b16a4cd7522cd55b91af1d9 +size 560766155 diff --git a/data/caches/sam3/.gitkeep b/data/caches/sam3/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/data/caches/sam3/.gitkeep @@ -0,0 +1 @@ + diff --git a/data/caches/sam3/sam3-no-tracking-video.zip b/data/caches/sam3/sam3-no-tracking-video.zip new file mode 100644 index 0000000000000000000000000000000000000000..4525c7bfcc45887a14d7d4266d10581228d16975 --- /dev/null +++ b/data/caches/sam3/sam3-no-tracking-video.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc17d884ef1ef1e456a84444d9d0e9cccb8c94d99afc338ecde9b9f653b4be30 +size 326509595 diff --git a/data/caches/sam3/sam3-tracking-frames.zip b/data/caches/sam3/sam3-tracking-frames.zip new file mode 100644 index 0000000000000000000000000000000000000000..1113c44ea195e1283c566f546a674fa46b38bcb4 --- /dev/null +++ b/data/caches/sam3/sam3-tracking-frames.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6138e6115d1723365f7bbd44295b966d1b006ef7b78684a59634d238730c7bb +size 27961117522 diff --git a/data/caches/segvggt.tar.zst b/data/caches/segvggt.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..c172789a679ff60f83e5524c39e6af64bf27aa9c --- /dev/null +++ b/data/caches/segvggt.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f1eb474058433186ba10f5b8c756ca21635a7cd4eb567bd88fe404378d4d520 +size 40228959795 diff --git a/data/caches/selected-frames.tar.zst b/data/caches/selected-frames.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..f00f701ff40bf0bed10c5fa519f59e3b732b7aec --- /dev/null +++ b/data/caches/selected-frames.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8036112e912a68325ad6447d5d3aadf40d0308fb2cdbe7d005986f1268b4d371 +size 169891 diff --git a/data/spatial-codes.tar.zst b/data/spatial-codes.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..1beeb961bfa19acfbabc499ff1d0648bf83b29e0 --- /dev/null +++ b/data/spatial-codes.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3c1a6e3613c2c6525d7220c32738d18f1ecdaad52174b476382fc4e0fee8046 +size 7774580 diff --git a/encoder/ground_truth.py b/encoder/ground_truth.py new file mode 100644 index 0000000000000000000000000000000000000000..47ca9967cff599cb6f0ea0ae24ced261148286a9 --- /dev/null +++ b/encoder/ground_truth.py @@ -0,0 +1,280 @@ +"""Ground-truth spatial codes: the same compact/explicit schemas encoder/geometric.py +produces from the perception pipeline (SAM3 + Depth Anything 3), but built directly from +the dataset's own annotated 3D object boxes and room size instead -- perfect geometry, +zero perception error, for isolating "does the VLM's spatial reasoning improve when the +input geometry is exactly right" from "is the encoder's perception good enough." + +Sourced from thinking-in-space's meta_info (the same ground truth thinking-in-space's own +official VSI-Bench scorer trains/evaluates against): per-scene `object_bbox` (each +instance's centroid/axesLengths/normalizedAxes -- a full 3D oriented box) and `room_size` +(the room's true floor area). Two things meta_info does NOT carry, because they are +properties of a specific camera walkthrough rather than of the scene's static geometry: + +- Room SHAPE (only the scalar area is annotated): represented as a single axis-aligned + square floor polygon of exactly that area, centered at the scene's own `room_center` -- + the honest floor-shape representation the data supports, matching real area exactly + under the same shoelace derivation compact/explicit already use, without inventing a + boundary the annotations don't contain. +- Per-object "first visible time" (when a class first appears on camera -- inherently a + property of the video, not the 3D scan): there is no such ground truth for the average + object, but VSI-Bench's own `obj_appearance_order` questions DO carry genuine human + ground truth ordering for the specific classes they ask about. Every appearance-order + question for a scene contributes a same-scene ordering constraint (see + _appearance_order_ranks); classes never covered by any such question for that scene + get "first visible time": null (no fabricated number) and sort after every timed class + in "appearance order". + +Coordinate convention: thinking-in-space's meta_info coordinates are already gravity- +aligned per-scene (z is up; verified empirically -- `room_center` z is tightly clustered +near a small non-negative range across every scannet scene, unlike x/y, and ARKitScenes' +axis-locked object boxes carry an exact [0, 0, 1] orientation row), so -- unlike the real +encoder pipeline, which must estimate gravity from a noisy reconstructed point cloud -- +ground truth's own x, y, z pass straight through as the compact schema's own (x, y, +height above floor) room frame; only a floor reference (z of the annotations' own lowest +point) needs to be established. +""" + +from __future__ import annotations + +import json +from functools import lru_cache +from pathlib import Path + +import numpy as np + +from encoder import config +from encoder.geometric import ( + COMPACT_SPATIAL_CODE_SCHEMA, + _compact_room_floor_area, + _explicit_from_compact, + _rounded_list, + dump_spatial_code, +) + +META_INFO_DIR = Path(config.DATA_ROOT) / "thinking-in-space" / "data" / "meta_info" +META_INFO_DATASETS = ("scannet", "arkitscenes", "scannetpp") + + +@lru_cache(maxsize=1) +def load_meta_info(): + """Return {scene: record} merged across every dataset's meta_info file, each record + carrying its own "dataset" key (scannet / arkitscenes / scannetpp).""" + merged = {} + for dataset in META_INFO_DATASETS: + path = META_INFO_DIR / f"{dataset}_meta_info_val.json" + with open(path, encoding="utf-8") as stream: + records = json.load(stream) + for scene, record in records.items(): + merged[str(scene)] = {**record, "dataset": dataset} + return merged + + +@lru_cache(maxsize=1) +def _appearance_order_ranks_by_scene(): + """Return {scene: {class_name: rank}} decoded from every real + ``obj_appearance_order`` question's ground_truth answer in test.jsonl -- a DAG of + "class X appears no later than class Y" edges per scene, topologically ranked (DFS, + back-edges from any inconsistent question ignored rather than raising, since a rank + is still useful even if two annotators' four-item orderings can't be perfectly + reconciled). Classes never named by any appearance-order question for that scene are + simply absent from the returned mapping. + """ + edges_by_scene = {} + with open(config.JSONL, encoding="utf-8") as stream: + for line in stream: + question = json.loads(line) + if question.get("question_type") != "obj_appearance_order": + continue + scene = str(question["scene_name"]) + index = ord(question["ground_truth"]) - ord("A") + option = question["options"][index] + classes = [name.strip() for name in option.split(".", 1)[1].split(",")] + edges = edges_by_scene.setdefault(scene, {}) + for earlier, later in zip(classes, classes[1:]): + edges.setdefault(earlier, set()).add(later) + + ranks_by_scene = {} + for scene, edges in edges_by_scene.items(): + nodes = set(edges) | { + node for successors in edges.values() for node in successors + } + order = [] + visited, in_progress = set(), set() + + def visit(node): + if node in visited or node in in_progress: + return + in_progress.add(node) + for successor in sorted(edges.get(node, ())): + visit(successor) + in_progress.discard(node) + visited.add(node) + order.append(node) + + for node in sorted(nodes): + visit(node) + order.reverse() + ranks_by_scene[scene] = {name: rank for rank, name in enumerate(order)} + return ranks_by_scene + + +def _floor_level(object_bbox): + """Return the lowest z any annotated object's oriented box reaches: the support of + each box along -z, i.e. centroid_z minus the box's half-extent projected onto z + (sum of half-dimension * |axis . z| across all three axes -- the true lowest corner + of a tilted box, not just its centroid).""" + lowest = [] + for instances in object_bbox.values(): + for instance in instances: + centroid_z = float(instance["centroid"][2]) + dims = np.asarray(instance["axesLengths"], np.float64) + axes = np.asarray(instance["normalizedAxes"], np.float64).reshape(3, 3) + axes = axes / np.linalg.norm(axes, axis=1, keepdims=True) + half_extent_z = float(np.sum(dims / 2 * np.abs(axes[:, 2]))) + lowest.append(centroid_z - half_extent_z) + return min(lowest) if lowest else 0.0 + + +def _gt_oriented_box(instance, floor_level): + """Return one compact "3D oriented bounding box" dict straight from a meta_info + object_bbox instance -- centroid/axesLengths/normalizedAxes pass through as this + dataset's own gravity-aligned x, y, z (see module docstring), only re-based so the + third component is height above this scene's own floor reference.""" + centroid = np.asarray(instance["centroid"], np.float64) + dims = np.asarray(instance["axesLengths"], np.float64) + axes = np.asarray(instance["normalizedAxes"], np.float64).reshape(3, 3) + axes = axes / np.linalg.norm(axes, axis=1, keepdims=True) + center = [float(centroid[0]), float(centroid[1]), float(centroid[2]) - floor_level] + return { + "3D oriented bounding box center coordinates": _rounded_list(center), + "3D oriented bounding box dimensions": _rounded_list(dims.tolist()), + "3D oriented bounding box orientation unit vectors": [ + _rounded_list(row.tolist()) for row in axes + ], + } + + +def _gt_floor_boundary_polygons(room_size, room_center): + """A single axis-aligned square of exactly area ``room_size`` centered at + ``room_center``'s (x, y) -- the floor-SHAPE stand-in the annotations actually + support (see module docstring); no holes, since meta_info carries no boundary + detail to place one from.""" + half_side = float(np.sqrt(max(room_size, 0.0))) / 2 + cx, cy = float(room_center[0]), float(room_center[1]) + corners = [ + [cx - half_side, cy - half_side], + [cx + half_side, cy - half_side], + [cx + half_side, cy + half_side], + [cx - half_side, cy + half_side], + ] + return [ + { + "outer boundary coordinates": [_rounded_list(corner) for corner in corners], + "interior hole boundary coordinates": [], + } + ] + + +def build_compact_ground_truth_spatial_code(scene): + """Build the compact spatial code for ``scene`` directly from its dataset annotation + (meta_info), in the exact COMPACT_SPATIAL_CODE_SCHEMA shape/legend build_compact_ + spatial_code() produces from the perception pipeline.""" + meta = load_meta_info() + if scene not in meta: + raise KeyError(f"no meta_info ground truth for scene {scene!r}") + record = meta[scene] + object_bbox = record["object_bbox"] + floor_level = _floor_level(object_bbox) + ranks = _appearance_order_ranks_by_scene().get(scene, {}) + + objects = {} + for class_name, instances in object_bbox.items(): + rank = ranks.get(class_name) + objects[class_name] = [ + { + "3D oriented bounding box": _gt_oriented_box(instance, floor_level), + "first visible time": float(rank) if rank is not None else None, + } + for instance in instances + ] + + return { + "objects": objects, + "room": { + "floor boundary polygons": _gt_floor_boundary_polygons( + record["room_size"], record["room_center"] + ) + }, + } + + +def build_explicit_ground_truth_spatial_code(scene): + """Build the explicit spatial code for ``scene`` as the exact same strict derivation + of a compact code that build_explicit_spatial_code() uses for encoder-built codes, + applied to build_compact_ground_truth_spatial_code()'s output instead.""" + compact_code = build_compact_ground_truth_spatial_code(scene) + code, _floor_area = _explicit_from_compact(compact_code) + return code + + +def build_ground_truth_spatial_code(scene, spatial_code_format="explicit"): + """Dispatch to the compact or explicit ground-truth builder, mirroring + encoder.geometric.build_spatial_code's format switch.""" + if spatial_code_format == "compact": + return build_compact_ground_truth_spatial_code(scene) + if spatial_code_format == "explicit": + return build_explicit_ground_truth_spatial_code(scene) + raise ValueError( + f"unknown spatial-code format {spatial_code_format!r}; expected 'compact' or 'explicit'" + ) + + +def build_and_write(scene, spatial_code_format="explicit"): + """Build one scene's ground-truth spatial code and write it to its on-disk path + (encoder.config.ground_truth_spatial_code_path), creating parent directories as + needed. Returns the path written.""" + code = build_ground_truth_spatial_code(scene, spatial_code_format) + path = config.ground_truth_spatial_code_path(scene, spatial_code_format) + Path(path).parent.mkdir(parents=True, exist_ok=True) + dump_spatial_code(code, path) + return path + + +def scenes(): + """Every scene meta_info has ground truth for (a superset of every scene any + perception-built spatial code could ever cover, since this needs no SAM3/DA3 cache). + """ + return sorted(load_meta_info()) + + +def build_all(spatial_code_formats=("explicit", "compact"), scene_list=None): + """Build and write ground-truth spatial codes for every scene (or ``scene_list``) + in both formats by default. Returns the list of paths written.""" + written = [] + for scene in scene_list if scene_list is not None else scenes(): + for spatial_code_format in spatial_code_formats: + written.append(build_and_write(scene, spatial_code_format)) + return written + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--scenes", help="comma-separated scenes (default: every scene)" + ) + parser.add_argument( + "--formats", + default="explicit,compact", + help="comma-separated spatial-code formats", + ) + args = parser.parse_args() + scene_list = ( + [scene.strip() for scene in args.scenes.split(",") if scene.strip()] + if args.scenes + else None + ) + formats = tuple(fmt.strip() for fmt in args.formats.split(",") if fmt.strip()) + paths = build_all(formats, scene_list) + print(f"wrote {len(paths)} ground-truth spatial codes") diff --git a/harness/C/__init__.py b/harness/C/__init__.py index 0f1edc658d0e30f6a7070baac2e77ac53ad701bb..225c426043559503eb946b55206f09b769a43c60 100644 --- a/harness/C/__init__.py +++ b/harness/C/__init__.py @@ -1,7 +1,17 @@ -"""Harness C supplies both visual input and explicit spatial code to the model. +"""Harness C: route BOTH a scene's video frames AND its on-disk spatial code (explicit +explicit) to all three models, for every VSI-Bench question. -The visual input (sampled frames or video) and spatial-code source (frame-derived or -video-derived) are configured independently. Changing one never changes the other. +Frames and spatial code are sourced from the exact same (depth, tracking, +input_selection, frame_count) config -- the same parameters drive both +harness.A.frames.sample_frames() and harness.B.spatial_codes.load_spatial_code(), so the +spatial code shown to the model is guaranteed to have been built from sampling the same +video the same way the frames themselves are sampled here; they can never mismatch. + +Reuses harness.A's model registry/adapters and fixed generation protocol exactly, and +harness.B's spatial-code loading and format/input-selection vocabulary. Results are +written in the identical per-question JSON shape harness.A and harness.B use, with both +harnesses' provenance fields present (frame provenance from A, spatial-code provenance +from B) since C uses both kinds of input. """ from __future__ import annotations @@ -33,5 +43,5 @@ assert INPUT_SELECTIONS == FRAME_SELECTIONS # one shared vocabulary drives both FRAMES_PER_VIDEO = int(os.environ.get("VSI_HARNESS_C_FRAMES_PER_VIDEO", "32")) # One JSON per question, matching harness.A/B's layout: -# results/C//explicit///code/.../visual/...//.json +# results/C////////.json RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_C_RESULTS_DIR", "/root/results/C")) diff --git a/harness/C/launch.py b/harness/C/launch.py index e8998442509cd30f408d7db9754d7a229ab41e79..f3e7eef1ffbd8c8b906c4e66746aba6832c22a8a 100644 --- a/harness/C/launch.py +++ b/harness/C/launch.py @@ -56,9 +56,6 @@ def _worker( input_selection, frame_count, video, - spatial_code_source, - spatial_code_input_selection, - spatial_code_frame_count, depth, tracking, results_dir, @@ -97,9 +94,6 @@ def _worker( input_selection=input_selection, frame_count=frame_count, video=video, - spatial_code_source=spatial_code_source, - spatial_code_input_selection=spatial_code_input_selection, - spatial_code_frame_count=spatial_code_frame_count, depth=depth, tracking=tracking, scene=scene, @@ -126,9 +120,6 @@ def launch( frame_count, selected, video=False, - spatial_code_source="frames", - spatial_code_input_selection=DEFAULT_INPUT_SELECTION, - spatial_code_frame_count=FRAMES_PER_VIDEO, depth=DEFAULT_DEPTH, tracking=DEFAULT_TRACKING, results_dir=None, @@ -144,17 +135,7 @@ def launch( elif frame_count is None or frame_count < 1: raise ValueError("frame_count must be positive in frames mode") mode = "video" if video else f"{input_selection}/{frame_count}" - if spatial_code_source == "video": - code_input_selection, code_frame_count, code_mode = "video", None, "video" - elif spatial_code_source == "frames": - if spatial_code_frame_count is None or spatial_code_frame_count < 1: - raise ValueError("spatial_code_frame_count must be positive") - code_input_selection = spatial_code_input_selection - code_frame_count = spatial_code_frame_count - code_mode = f"{code_input_selection}/{code_frame_count}" - else: - raise ValueError("spatial_code_source must be frames or video") - condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/code-{code_mode}/visual-{mode}" + condition = f"{model}/{spatial_code_format}/{depth}/{tracking}/{mode}" run = _load_run_module() root = run.results_dir_for( model, @@ -164,9 +145,6 @@ def launch( tracking, input_selection, frame_count, - spatial_code_source, - code_input_selection, - code_frame_count, results_dir, ) pending = [] @@ -218,9 +196,6 @@ def launch( input_selection, frame_count, video, - spatial_code_source, - code_input_selection, - code_frame_count, depth, tracking, results_dir, @@ -272,9 +247,6 @@ def main(): input_mode = parser.add_mutually_exclusive_group(required=True) input_mode.add_argument("--frames", type=int) input_mode.add_argument("--video", action="store_true") - parser.add_argument("--spatial-code-source", required=True, choices=("frames", "video")) - parser.add_argument("--spatial-code-input-selection", choices=INPUT_SELECTIONS) - parser.add_argument("--spatial-code-frames", type=int) 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) @@ -309,14 +281,6 @@ def main(): parser.error("--input-selection is required with --frames") if args.frames < 1: parser.error("--frames must be positive") - if args.spatial_code_source == "video": - if args.spatial_code_input_selection is not None or args.spatial_code_frames is not None: - parser.error("spatial-code frame flags cannot be used with --spatial-code-source video") - else: - if args.spatial_code_input_selection is None or args.spatial_code_frames is None: - parser.error("--spatial-code-input-selection and --spatial-code-frames are required with --spatial-code-source frames") - if args.spatial_code_frames < 1: - parser.error("--spatial-code-frames must be positive") resolve_protocol_budgets(parser, args) launch( args.model, @@ -325,9 +289,6 @@ def main(): args.frames, selected, video=args.video, - spatial_code_source=args.spatial_code_source, - spatial_code_input_selection=args.spatial_code_input_selection, - spatial_code_frame_count=args.spatial_code_frames, depth=args.depth, tracking=args.tracking, results_dir=args.results_dir, diff --git a/harness/C/overlay.py b/harness/C/overlay.py new file mode 100644 index 0000000000000000000000000000000000000000..13e3168e40957eb44ed7048f9d51ad03e481957b --- /dev/null +++ b/harness/C/overlay.py @@ -0,0 +1,391 @@ +"""Set-of-Marks overlay for the strong correspondence arm (harness C) -- sourced +PURELY from SAM3's own raw per-frame output. No 3D math anywhere in this module. + +Gives frames and spatial code a SHARED instance namespace with 1:1 correspondence +guaranteed BY CONSTRUCTION: every explicit-code instance gets an id ("bed 1", +"chair 2", ...), and that id is stamped in EXACTLY the frames SAM3's own tracker +reported that instance's masklet(s) present in, at EXACTLY the bounding box SAM3's +own tracker reported for it there. There is no camera projection, no floor-basis +inversion, no depth buffer, no occlusion heuristic anywhere in this pipeline -- an +instance is drawn iff SAM3's raw cache says it's in this frame, at the box SAM3's +raw cache says it's at. Any placement error, missing detection, or wrong-frame +presence is therefore attributable to SAM3 (or the SAM3->code consolidation +encoder.geometric already performs, verified separately), never to this module's +own math, since this module doesn't do any. + +Provenance (which raw SAM3 masklet id(s) a final code instance came from) is +recovered via encoder.geometric.instance_source_track_ids(), which exposes the +"oids" field build_compact_spatial_code()'s own consolidation pipeline threads +through internally but never emits in the on-disk schema (adding it there would +change every harness's prompt -- this module is the only consumer). +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +from PIL import Image, ImageDraw, ImageFont + +# Markers are drawn on a layer rendered at _SUPERSAMPLE x the frame's own resolution, +# then downsampled with LANCZOS before compositing -- this is what makes the box +# edges and glyph strokes look crisp/anti-aliased rather than jagged, WITHOUT the +# marker's rendered footprint on the final frame growing (that footprint is set by +# _FONT_SIZE below, sized for the frame's OWN resolution). +_SUPERSAMPLE = 3 +_FONT_SIZE = 15 +_MARKER_RADIUS = 5 +_MAX_NUDGES = 12 + +# A scalable font, not PIL's tiny fixed-size default bitmap font -- labels need to be +# legible to a human reviewer (and to the model) at typical VSI-Bench frame resolution. +# DejaVuSans-Bold ships inside every Pillow install (PIL/fonts/), so this never depends +# on the host having a system font installed. +try: + _LABEL_FONT = ImageFont.truetype( + str(Path(ImageFont.__file__).parent / "fonts" / "DejaVuSans-Bold.ttf"), + _FONT_SIZE * _SUPERSAMPLE, + ) +except OSError: + _LABEL_FONT = ImageFont.load_default(size=_FONT_SIZE * _SUPERSAMPLE) + +WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +from encoder import config as encoder_config # noqa: E402 +from encoder import geometric as gm # noqa: E402 +from encoder import run as perceive # noqa: E402 + + +def _parse_meters(value): + return float(str(value).split()[0]) + + +def _boxes_overlap(a, b): + return a[0] < b[2] and a[2] > b[0] and a[1] < b[3] and a[3] > b[1] + + +def _place_label_box(anchor_x, anchor_y, width, height, placed, frame_h, step): + """Return ((left, top, right, bottom), was_nudged) for one label, greedily moved + vertically away from every box already in ``placed`` (deterministic: labels are + tried in the caller's fixed order, so a given code always nudges the same way). + ``was_nudged`` is False only for attempt 0 (the label's natural, un-collided + position) -- the caller uses it to draw a leader line ONLY when the label actually + moved away from its marker, instead of drawing one, unconditionally, that's too + short to see for every other label. Alternates below/above the anchor in + increasing steps so a crowded cluster fans out symmetrically instead of drifting + off in one direction; stops at ``_MAX_NUDGES`` attempts and returns the last-tried + box rather than looping forever -- a residual overlap in a dense cluster is a + real, visible property of that cluster, not something to hide by trying + indefinitely.""" + for attempt in range(_MAX_NUDGES): + direction = 1 if attempt % 2 == 0 else -1 + offset = direction * step * ((attempt + 1) // 2) + top = anchor_y + offset + box = (anchor_x, top, anchor_x + width, top + height) + if ( + 0 <= box[1] + and box[3] <= frame_h + and not any(_boxes_overlap(box, p) for p in placed) + ): + return box, attempt > 0 + return box, True + + +def instance_ids(explicit_code): + """Return a copy of an explicit code whose instances each carry an + '"instance id": " "' field (1-based, in the code's own list order -- + the same numbering label_positions() and stamp_frames() use). Input not mutated.""" + code = dict(explicit_code) + objects = {} + for class_name, rendered in code.get("objects", {}).items(): + instances = [ + {**instance, "instance id": f"{class_name} {index}"} + for index, instance in enumerate(rendered.get("instances", []), 1) + ] + objects[class_name] = {**rendered, "instances": instances} + code["objects"] = objects + return code + + +def label_positions(explicit_code): + """Return [(label, floor_x, floor_y, height_above_floor, longest_dimension)] for + every instance, labeled identically to instance_ids(). NOT used by stamp_frames + (which sources positions from SAM3's own raw boxes, not the code's stored 3D + position) -- kept as a standalone utility for auditing the code's own claimed + geometry against a scene (e.g. checking a suspect instance's stored height).""" + out = [] + for class_name, rendered in explicit_code.get("objects", {}).items(): + for index, instance in enumerate(rendered.get("instances", []), 1): + position = instance["position"] + out.append( + ( + f"{class_name} {index}", + _parse_meters(position["x coordinate"]), + _parse_meters(position["y coordinate"]), + _parse_meters(position["height above floor"]), + _parse_meters(instance["longest dimension"]), + ) + ) + return out + + +def _load_raw_sam3_boxes(scene_id, input_selection, tracking, frame_count): + """Return {class_name: {frame_index: {masklet_id: (x, y, w, h) normalized [0,1]}}} + read directly from the native SAM3 tracking cache -- the same file + encoder.run.cache_or_load() itself reads, parsed here with NO further processing + (no masking, no merging, no geometry): exactly what SAM3's own tracker reported, + per frame, per masklet.""" + import torch + + path = encoder_config.sam3_cache_file( + scene_id, input_selection, tracking, frame_count + ) + if not Path(path).is_file(): + raise FileNotFoundError( + f"no raw SAM3 cache found for scene {scene_id!r} at {path} -- the strong " + "correspondence arm needs the scene's SAM3 perception cache on disk" + ) + raw = torch.load(path, map_location="cpu", weights_only=False) + out = {} + for class_name, class_data in raw.items(): + stream = class_data.get("stream", []) if isinstance(class_data, dict) else [] + frames = {} + for entry in stream: + outputs = entry.get("outputs", {}) + obj_ids = outputs.get("out_obj_ids", []) + boxes = outputs.get("out_boxes_xywh", []) + frames[int(entry["frame_index"])] = { + int(oid): tuple(float(v) for v in box) + for oid, box in zip(obj_ids, boxes) + } + out[str(class_name)] = frames + return out + + +def overlay_frame_cache_dir(scene_id, depth, input_selection, tracking, frame_count): + """Return the on-disk cache directory for one scene's stamped overlay frames -- + same axes as the spatial code path (depth still matters here even though box + POSITIONS never touch it: instance_source_track_ids's provenance mapping, which + decides which raw SAM3 id becomes "chair 1" vs "chair 3", is computed via + room_gravity on the depth-specific geometry cache). Format is always explicit + (the only format the correspondence arms support), so it isn't part of the path.""" + return ( + encoder_config.CACHE_ROOT + / "overlay-frames" + / depth + / tracking + / input_selection + / str(frame_count) + / scene_id + ) + + +def overlay_spatial_code_path(scene_id, depth, input_selection, tracking, frame_count): + """Return the durable overlay-code JSON path for one scene/config. + + Overlay codes are stored under the configured spatial-code root's top-level + ``overlay`` directory so an overlay run has a browsable code artifact matching + the stamped frames, instead of only an in-memory prompt transform. + """ + encoder_config._validate_dimensions(depth, input_selection, tracking, frame_count) + return ( + encoder_config.CODES_ROOT + / "overlay" + / encoder_config.MODEL + / depth + / tracking + / input_selection + / str(frame_count) + / "explicit" + / f"{scene_id}.json" + ) + + +def load_or_create_overlay_code( + explicit_code, scene_id, depth, input_selection, tracking, frame_count +): + """Load an existing overlay code, or create and save it from ``explicit_code``. + + The saved code is exactly ``instance_ids(explicit_code)``. Existing files are + trusted as the durable artifact for that scene/config and are not rewritten. + Returns ``(code, path)``. + """ + path = overlay_spatial_code_path( + scene_id, depth, input_selection, tracking, frame_count + ) + if path.is_file(): + return json.loads(path.read_text(encoding="utf-8")), str(path) + code = instance_ids(explicit_code) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(code, indent=1) + "\n", encoding="utf-8") + return code, str(path) + + +def _load_cached_frames(cache_dir, frame_count): + """Return (stamped_frame_copies, per_frame_visible_labels) if a complete cache + exists at ``cache_dir`` (every frame PNG plus the labels sidecar present), else + None. A partial cache (e.g. an interrupted pre-generation run) is treated as + absent -- regenerated in full, never silently served incomplete.""" + labels_path = cache_dir / "labels.json" + if not labels_path.is_file(): + return None + frame_paths = [cache_dir / f"{i}.png" for i in range(frame_count)] + if not all(path.is_file() for path in frame_paths): + return None + images = [Image.open(path).convert("RGB") for path in frame_paths] + visible = json.loads(labels_path.read_text()) + return images, visible + + +def _save_cached_frames(cache_dir, stamped, visible): + cache_dir.mkdir(parents=True, exist_ok=True) + for i, image in enumerate(stamped): + image.save(cache_dir / f"{i}.png") + (cache_dir / "labels.json").write_text(json.dumps(visible)) + + +def stamp_frames( + frame_images, + explicit_code, + scene_id, + depth, + input_selection, + tracking, + frame_count, + use_cache=True, +): + """Return (stamped_frame_copies, per_frame_visible_labels). For every code + instance, looks up which raw SAM3 masklet id(s) it consolidated from + (encoder.geometric.instance_source_track_ids) and, per frame, whether SAM3's own + tracker reported any of those ids present -- if so, stamps SAM3's own reported box + for it, verbatim. An instance is absent from a frame's output iff SAM3's raw + tracker never reported it there; there is no other reason. Input images are + never mutated. + + ``use_cache=True`` (default) reads/writes a persistent on-disk cache under + overlay_frame_cache_dir() -- the same stamping is otherwise recomputed from + scratch on every call (once per scene per model per run), and the result is + scene-only (never model- or question-dependent), so caching it once and reusing + it across every model/run that touches this scene/config is a pure speed win. + Pass False to force a fresh computation (e.g. after a code or overlay-logic + change, before the cache is known to be stale and worth clearing).""" + cache_dir = overlay_frame_cache_dir( + scene_id, depth, input_selection, tracking, frame_count + ) + if use_cache: + cached = _load_cached_frames(cache_dir, frame_count) + if cached is not None: + return cached + geometry, _how = perceive.cache_or_load( + scene_id, depth, input_selection, tracking, frame_count, False + ) + provenance = gm.instance_source_track_ids(geometry) + raw_boxes = _load_raw_sam3_boxes(scene_id, input_selection, tracking, frame_count) + + labels = [] + for class_name, rendered in explicit_code.get("objects", {}).items(): + oid_lists = provenance.get(class_name, []) + for index, _instance in enumerate(rendered.get("instances", []), 1): + oids = oid_lists[index - 1] if index - 1 < len(oid_lists) else [] + labels.append((f"{class_name} {index}", class_name, oids)) + + stamped, visible = [], [] + for frame_index, image in enumerate(frame_images): + image = image.convert("RGB") + # Markers are drawn on a transparent layer at _SUPERSAMPLE x resolution, THEN + # downsampled with LANCZOS and alpha-composited onto the (unscaled, un-blurred) + # frame -- crisp anti-aliased edges on the marker itself, no change to the + # underlying photo's own resolution or the marker's on-frame footprint. + hi_res_size = (image.size[0] * _SUPERSAMPLE, image.size[1] * _SUPERSAMPLE) + overlay_layer = Image.new("RGBA", hi_res_size, (0, 0, 0, 0)) + draw = ImageDraw.Draw(overlay_layer) + marker_r = _MARKER_RADIUS * _SUPERSAMPLE + placed_boxes = [] + frame_labels = [] + for label, class_name, oids in labels: + frame_detections = raw_boxes.get(class_name, {}).get(frame_index, {}) + box = next( + (frame_detections[oid] for oid in oids if oid in frame_detections), None + ) + if box is None: + continue # SAM3's own tracker did not report this instance in this frame + nx, ny, nw, nh = box # normalized [0,1] -- SAM3's own box, verbatim + bx0, by0 = nx * hi_res_size[0], ny * hi_res_size[1] + bw, bh = nw * hi_res_size[0], nh * hi_res_size[1] + draw.rectangle( + [bx0, by0, bx0 + bw, by0 + bh], + outline="red", + width=max(2, _SUPERSAMPLE), + ) + px, py = bx0 + bw / 2, by0 + bh / 2 + draw.ellipse( + [px - marker_r, py - marker_r, px + marker_r, py + marker_r], + outline="red", + width=max(2, _SUPERSAMPLE), + ) + # Flip the label to the opposite side of the marker whenever its default + # placement would run off the frame -- a label clipped at the image edge is + # unreadable to both a human reviewer and the model. + text_width = draw.textlength(label, font=_LABEL_FONT) + text_height = _FONT_SIZE * _SUPERSAMPLE * 1.3 + gap = 8 * _SUPERSAMPLE + text_x = ( + px - gap - text_width + if px + gap + text_width > hi_res_size[0] + else px + gap + ) + anchor_y = ( + py + 4 * _SUPERSAMPLE + if py - 10 * _SUPERSAMPLE < 0 + else py - 10 * _SUPERSAMPLE + ) + # Nudge this label's box away from every label already placed in this + # frame -- a crowded cluster fans its labels out instead of stacking them + # into an unreadable smear (see _place_label_box's docstring). + label_box, was_nudged = _place_label_box( + text_x, + anchor_y, + text_width, + text_height, + placed_boxes, + hi_res_size[1], + step=text_height + 2 * _SUPERSAMPLE, + ) + placed_boxes.append(label_box) + if was_nudged: + # A leader line from the marker to its (moved) label -- needed because + # dense clusters (several instances detected close together) can leave + # an unconnected dot cluster reading as unowned "random circles" once + # collision avoidance fans their labels apart. Only drawn when nudging + # actually happened -- a label already next to its own dot doesn't + # need one, and it would be invisible under the marker anyway. + anchor_x = label_box[2] if text_x < px else label_box[0] + anchor_y_mid = (label_box[1] + label_box[3]) / 2 + draw.line( + [(px, py), (anchor_x, anchor_y_mid)], + fill=(255, 70, 55, 210), + width=max(2, _SUPERSAMPLE), + ) + # A thin dark stroke (not a solid fill box) keeps the label legible + # against any background without blotting out the photo underneath it. + draw.text( + (label_box[0], label_box[1]), + label, + font=_LABEL_FONT, + fill="#ff4030", + stroke_width=max(2, _SUPERSAMPLE), + stroke_fill=(0, 0, 0, 235), + ) + frame_labels.append(label) + overlay_layer = overlay_layer.resize(image.size, Image.LANCZOS) + composited = Image.alpha_composite( + image.convert("RGBA"), overlay_layer + ).convert("RGB") + stamped.append(composited) + visible.append(frame_labels) + if use_cache: + _save_cached_frames(cache_dir, stamped, visible) + return stamped, visible diff --git a/harness/C/overlay_launch.py b/harness/C/overlay_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..261f90a77ab05be6fde6dd5d31c37732bf3d9906 --- /dev/null +++ b/harness/C/overlay_launch.py @@ -0,0 +1,202 @@ +"""Pre-generate the strong correspondence arm's stamped-frame cache for many scenes +at once (harness.C.overlay.overlay_frame_cache_dir/stamp_frames). + +Stamping is scene-only (never model- or question-dependent), so pre-populating the +cache once here means every later --overlay-ids run, for every model, reuses these +same files instead of recomputing the identical stamping from scratch each time -- +and the cached PNGs are themselves a durable, browsable record of what every scene's +overlay actually looks like, independent of any particular model run. + +Usage: + python -m harness.C.overlay_launch --depth metric --tracking tracking \\ + --input uniform --frames 32 + Pre-generates every scene with BOTH an explicit spatial code AND a SAM3 + perception cache for this config -- skips scenes already cached and scenes + missing either dependency (reported, not silently dropped). + + python -m harness.C.overlay_launch --depth metric --tracking tracking \\ + --input uniform --frames 32 --scenes 42444976,45b0dac5e3 + Restrict to specific scenes. + + python -m harness.C.overlay_launch ... --rebuild + Recompute even scenes whose cache already exists (e.g. after an overlay.py + rendering change). +""" + +from __future__ import annotations + +import argparse +import multiprocessing as mp +import os +import sys +import traceback +from pathlib import Path + +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.launch import scenes as all_scenes # noqa: E402 +from harness.A import frames as frame_sampling # noqa: E402 +from harness.B import spatial_codes # noqa: E402 +from harness.C import overlay # noqa: E402 +import inference as inference_config # noqa: E402 + + +def _available_cpu_count(): + configured = os.environ.get("VSI_CPU_WORKERS") + if configured is not None: + count = int(configured) + if count < 1: + raise ValueError("VSI_CPU_WORKERS must be positive") + return count + try: + return max(1, len(os.sched_getaffinity(0))) + except AttributeError: + return max(1, os.cpu_count() or 1) + + +def _has_dependencies(scene, depth, input_selection, tracking, frame_count): + """True iff this scene has both an explicit spatial code AND a raw SAM3 cache + for this config -- both are required to stamp its frames.""" + try: + spatial_codes.load_spatial_code( + scene, depth, input_selection, tracking, frame_count, "explicit" + ) + except FileNotFoundError: + return False + from encoder import config as encoder_config + + return Path( + encoder_config.sam3_cache_file(scene, input_selection, tracking, frame_count) + ).is_file() + + +def _generate_one(args): + scene, depth, input_selection, tracking, frame_count = args + try: + code, _path = spatial_codes.load_spatial_code( + scene, depth, input_selection, tracking, frame_count, "explicit" + ) + video_path = inference_config.video_path(scene, None) + frame_images, _ts, _idx = frame_sampling.sample_frames( + video_path, frame_count, input_selection + ) + overlay.stamp_frames( + frame_images, + code, + scene, + depth, + input_selection, + tracking, + frame_count, + use_cache=True, + ) + overlay.load_or_create_overlay_code( + code, scene, depth, input_selection, tracking, frame_count + ) + return scene, True, None + except Exception: + return scene, False, traceback.format_exc() + + +def launch( + depth, input_selection, tracking, frame_count, selected, rebuild=False, workers=0 +): + """Pre-generate the overlay-frame cache for every scene in ``selected`` that has + both required dependencies. Returns (succeeded, failed, skipped_missing_deps) + scene-name lists.""" + eligible, missing = [], [] + for scene in selected: + if _has_dependencies(scene, depth, input_selection, tracking, frame_count): + eligible.append(scene) + else: + missing.append(scene) + if missing: + print( + f"[overlay-launch] {len(missing)} scene(s) missing a code or SAM3 cache, skipped:" + ) + print(f" {missing}") + + if not rebuild: + pending = [] + for scene in eligible: + cache_dir = overlay.overlay_frame_cache_dir( + scene, depth, input_selection, tracking, frame_count + ) + code_path = overlay.overlay_spatial_code_path( + scene, depth, input_selection, tracking, frame_count + ) + if ( + overlay._load_cached_frames(cache_dir, frame_count) is not None + and code_path.is_file() + ): + continue + pending.append(scene) + skipped = len(eligible) - len(pending) + if skipped: + print(f"[overlay-launch] {skipped} scene(s) already cached, skipped") + else: + pending = eligible + + if not pending: + print( + f"[overlay-launch] DONE: 0 generated, {len(eligible) - len(pending)} skipped" + ) + return [], [], missing + + worker_count = workers if workers > 0 else _available_cpu_count() + worker_count = min(worker_count, len(pending)) + print( + f"[overlay-launch] generating {len(pending)} scene(s) with {worker_count} worker(s)" + ) + tasks = [ + (scene, depth, input_selection, tracking, frame_count) for scene in pending + ] + with mp.get_context("spawn").Pool(worker_count) as pool: + results = pool.map(_generate_one, tasks) + + succeeded = [scene for scene, ok, _ in results if ok] + failed = [(scene, detail) for scene, ok, detail in results if not ok] + for scene, detail in failed: + print(f"[overlay-launch] FAILED {scene}:\n{detail}") + print( + f"[overlay-launch] DONE: {len(succeeded)} generated, {len(failed)} failed, " + f"{len(eligible) - len(pending)} already cached" + ) + return succeeded, failed, missing + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--depth", required=True) + parser.add_argument("--tracking", required=True) + parser.add_argument("--input", required=True, dest="input_selection") + parser.add_argument("--frames", type=int, required=True) + parser.add_argument( + "--scenes", default=None, help="comma-separated scenes (default: all)" + ) + parser.add_argument("--rebuild", action="store_true") + parser.add_argument("--workers", type=int, default=0, help="0 = all available CPUs") + args = parser.parse_args() + selected = ( + [s.strip() for s in args.scenes.split(",") if s.strip()] + if args.scenes + else all_scenes() + ) + _succeeded, failed, _missing = launch( + args.depth, + args.input_selection, + args.tracking, + args.frames, + selected, + rebuild=args.rebuild, + workers=args.workers, + ) + if failed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/harness/C/run.py b/harness/C/run.py index 2bf1dc131d8170ee0f9d3729bf9640e70f74bbd0..e3cc84ed699991f3f26bc87fcb4ca503dce4cb6d 100644 --- a/harness/C/run.py +++ b/harness/C/run.py @@ -51,9 +51,6 @@ def results_dir_for( tracking, input_selection, frame_count, - spatial_code_source="frames", - spatial_code_input_selection=DEFAULT_INPUT_SELECTION, - spatial_code_frame_count=FRAMES_PER_VIDEO, results_dir=None, ): """Return the result root isolated by model + protocol + fixed explicit spatial code + @@ -63,9 +60,9 @@ def results_dir_for( if results_dir is not None: return Path(results_dir) root = RESULTS_DIR / model / spatial_code_format / depth / tracking - visual = Path("visual") / ("video" if input_selection == "video" else f"frames/{input_selection}/{frame_count}") - code = Path("code") / ("video" if spatial_code_source == "video" else f"frames/{spatial_code_input_selection}/{spatial_code_frame_count}") - return root / code / visual + if input_selection == "video": + return root / "video" + return root / input_selection / str(frame_count) def _build_record( @@ -81,22 +78,17 @@ def _build_record( "condition": ( f"{source_info['protocol']}:{source_info['spatial_code_format']}:" f"{source_info['depth']}:{source_info['tracking']}:" - f"code-{source_info['spatial_code_source']}" - + ("" if source_info["spatial_code_source"] == "video" else - f"-{source_info['spatial_code_input_selection']}" - f"-{source_info['spatial_code_frame_count']}") - + f":visual-{source_info['input_selection']}" - + ("" if source_info["input_selection"] == "video" else - f"-{source_info['frame_count']}") + + ( + "video" + if source_info["input_selection"] == "video" + else f"{source_info['input_selection']}:{source_info['frame_count']}" + ) ), "protocol": source_info["protocol"], "question_group": question_group(row["question_type"]), "spatial_code_format": source_info["spatial_code_format"], "input_selection": source_info["input_selection"], "frame_count": source_info["frame_count"], - "spatial_code_source": source_info["spatial_code_source"], - "spatial_code_input_selection": source_info["spatial_code_input_selection"], - "spatial_code_frame_count": source_info["spatial_code_frame_count"], "depth": source_info["depth"], "tracking": source_info["tracking"], "spatial_code_path": source_info["spatial_code_path"], @@ -157,9 +149,6 @@ def write_question_result( source_info["tracking"], source_info["input_selection"], source_info["frame_count"], - source_info["spatial_code_source"], - source_info["spatial_code_input_selection"], - source_info["spatial_code_frame_count"], results_dir, ) scene_dir = root / record["scene"] @@ -176,9 +165,6 @@ def run( input_selection=DEFAULT_INPUT_SELECTION, frame_count=FRAMES_PER_VIDEO, video=False, - spatial_code_source="frames", - spatial_code_input_selection=DEFAULT_INPUT_SELECTION, - spatial_code_frame_count=FRAMES_PER_VIDEO, depth=DEFAULT_DEPTH, tracking=DEFAULT_TRACKING, scene=None, @@ -214,15 +200,6 @@ def run( frame_count = None elif frame_count is None or frame_count < 1: raise ValueError("frame_count must be positive in frames mode") - if spatial_code_source == "video": - code_input_selection, code_frame_count = "video", None - elif spatial_code_source == "frames": - if spatial_code_frame_count is None or spatial_code_frame_count < 1: - raise ValueError("spatial_code_frame_count must be positive") - code_input_selection = spatial_code_input_selection - code_frame_count = spatial_code_frame_count - else: - raise ValueError("spatial_code_source must be frames or video") if spatial_code_format != "explicit": raise ValueError("Harness C supports explicit spatial codes only") protocol = "mixed" @@ -234,9 +211,6 @@ def run( tracking, input_selection, frame_count, - spatial_code_source, - code_input_selection, - code_frame_count, results_dir, ) rows = load_questions(jsonl_path, scene, scenes, limit) @@ -267,9 +241,9 @@ def run( code, code_path = spatial_codes.load_spatial_code( scene_id, depth, - code_input_selection, + input_selection, tracking, - code_frame_count, + frame_count, spatial_code_format, ) source_cache[scene_id] = { @@ -313,9 +287,6 @@ def run( "spatial_code_format": spatial_code_format, "input_selection": input_selection, "frame_count": frame_count, - "spatial_code_source": spatial_code_source, - "spatial_code_input_selection": code_input_selection, - "spatial_code_frame_count": code_frame_count, "depth": depth, "tracking": tracking, "spatial_code_path": cached["spatial_code_path"], @@ -368,9 +339,6 @@ def main(): input_mode = parser.add_mutually_exclusive_group(required=True) input_mode.add_argument("--frames", type=int) input_mode.add_argument("--video", action="store_true") - parser.add_argument("--spatial-code-source", required=True, choices=("frames", "video")) - parser.add_argument("--spatial-code-input-selection", choices=INPUT_SELECTIONS) - parser.add_argument("--spatial-code-frames", type=int) parser.add_argument("--depth", default=DEFAULT_DEPTH, choices=DEPTH_VARIANTS) parser.add_argument("--tracking", default=DEFAULT_TRACKING, choices=TRACKING_MODES) parser.add_argument( @@ -409,14 +377,6 @@ def main(): parser.error("--input-selection is required with --frames") if args.frames < 1: parser.error("--frames must be positive") - if args.spatial_code_source == "video": - if args.spatial_code_input_selection is not None or args.spatial_code_frames is not None: - parser.error("spatial-code frame flags cannot be used with --spatial-code-source video") - else: - if args.spatial_code_input_selection is None or args.spatial_code_frames is None: - parser.error("--spatial-code-input-selection and --spatial-code-frames are required with --spatial-code-source frames") - if args.spatial_code_frames < 1: - parser.error("--spatial-code-frames must be positive") resolve_protocol_budgets(parser, args) results = run( args.model, @@ -424,9 +384,6 @@ def main(): input_selection=args.input_selection, frame_count=args.frames, video=args.video, - spatial_code_source=args.spatial_code_source, - spatial_code_input_selection=args.spatial_code_input_selection, - spatial_code_frame_count=args.spatial_code_frames, depth=args.depth, tracking=args.tracking, scene=args.scene, diff --git a/harness/C/sweep.py b/harness/C/sweep.py index 35b7a0f7ac5e34ccc42b751e1e231352a2854a8a..0052baac74793cda091ecfb1e583274f8bc574a8 100644 --- a/harness/C/sweep.py +++ b/harness/C/sweep.py @@ -27,7 +27,6 @@ from harness.A import EXTENDED_MAX_NEW_TOKENS # noqa: E402 from harness.A.sweep import _parse_csv_choice, _parse_frame_counts # noqa: E402 from harness.B import ( # noqa: E402 DEFAULT_DEPTH, - DEFAULT_INPUT_SELECTION, DEFAULT_SPATIAL_CODE_FORMAT, DEFAULT_TRACKING, DEPTH_VARIANTS, @@ -38,131 +37,163 @@ from harness.C import launch as harness_launch # noqa: E402 def build_plan( - models, spatial_code_formats, input_selections, frame_counts, depths, trackings, - spatial_code_sources, spatial_code_input_selections, spatial_code_frame_counts, + models, spatial_code_formats, input_selections, frame_counts, depths, trackings ): - """Return every independent visual-input x spatial-code-input combination.""" - code_configs = [] - for source in spatial_code_sources: - if source == "video": - code_configs.append(("video", "video", None)) - else: - code_configs.extend( - ("frames", selection, count) - for count in sorted(spatial_code_frame_counts) - for selection in spatial_code_input_selections - ) + """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, fmt, depth, tracking, selection, count, - code_source, code_selection, code_count) - for count in frame_counts + (model, spatial_code_format, depth, tracking, input_selection, frame_count) + for frame_count in sorted(frame_counts) for model in models - for fmt in spatial_code_formats + for spatial_code_format in spatial_code_formats for depth in depths for tracking in trackings - for selection in input_selections - for code_source, code_selection, code_count in code_configs + for input_selection in input_selections ] def sweep( - models, spatial_code_formats, input_selections, frame_counts, selected_scenes, - video=False, depths=(DEFAULT_DEPTH,), trackings=(DEFAULT_TRACKING,), - spatial_code_sources=("frames",), - spatial_code_input_selections=(DEFAULT_INPUT_SELECTION,), - spatial_code_frame_counts=(32,), results_dir=None, rebuild=False, - extended=True, reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + models, + spatial_code_formats, + input_selections, + frame_counts, + selected_scenes, + video=False, + depths=(DEFAULT_DEPTH,), + trackings=(DEFAULT_TRACKING,), + results_dir=None, + rebuild=False, + extended=True, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, ): - """Run every independent visual-input x spatial-code-input combination.""" + """Run every sweep combination across all visible GPUs.""" plan = build_plan( - models, spatial_code_formats, input_selections, frame_counts, depths, trackings, - spatial_code_sources, spatial_code_input_selections, spatial_code_frame_counts, + models, spatial_code_formats, input_selections, frame_counts, depths, trackings ) - for index, config in enumerate(plan, start=1): - (model, fmt, depth, tracking, selection, count, - code_source, code_selection, code_count) = config - visual_mode = "video" if video else f"{selection}/{count}" - code_mode = "video" if code_source == "video" else f"{code_selection}/{code_count}" - print(f"=== sweep {index}/{len(plan)}: {model}/{fmt}/{depth}/{tracking}/" - f"code-{code_mode}/visual-{visual_mode} ===", flush=True) + for index, ( + model, + spatial_code_format, + depth, + tracking, + input_selection, + frame_count, + ) in enumerate(plan, start=1): + print( + f"=== sweep {index}/{len(plan)}: {model}/" + f"{spatial_code_format}/{depth}/{tracking}/" + + ("video" if video else f"{input_selection}/{frame_count}") + + " ===", + flush=True, + ) harness_launch.launch( - model, fmt, selection, count, selected_scenes, video=video, - spatial_code_source=code_source, - spatial_code_input_selection=code_selection, - spatial_code_frame_count=code_count, - depth=depth, tracking=tracking, results_dir=results_dir, - rebuild=rebuild, extended=extended, reasoning_budget=reasoning_budget, + model, + spatial_code_format, + input_selection, + frame_count, + selected_scenes, + video=video, + depth=depth, + tracking=tracking, + results_dir=results_dir, + rebuild=rebuild, + extended=extended, + reasoning_budget=reasoning_budget, ) + def main(): parser = argparse.ArgumentParser() parser.add_argument("scene", nargs="?") - parser.add_argument("--scenes", help="comma-separated scenes") - parser.add_argument("--models", required=True) - parser.add_argument("--input-selections", dest="input_selections") - visual = parser.add_mutually_exclusive_group(required=True) - visual.add_argument("--frames", help="comma-separated visual frame counts") - visual.add_argument("--video", action="store_true") - parser.add_argument("--spatial-code-sources", required=True) - parser.add_argument("--spatial-code-input-selections") - parser.add_argument("--spatial-code-frames") - parser.add_argument("--depths", default=DEFAULT_DEPTH) - parser.add_argument("--trackings", default=DEFAULT_TRACKING) - parser.add_argument("--results-dir") + 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( + "--input-selections", + required=False, + dest="input_selections", + help=f"comma-separated selections (or 'all'); one of {INPUT_SELECTIONS}", + ) + input_mode = parser.add_mutually_exclusive_group(required=True) + input_mode.add_argument( + "--frames", help="comma-separated frame counts, e.g. 16,32,64" + ) + input_mode.add_argument("--video", action="store_true") + 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") - parser.add_argument("--reasoning-budget", type=int, default=None, - help="thinking questions only") + parser.add_argument( + "--reasoning-budget", + type=int, + default=None, + dest="reasoning_budget", + help="thinking-protocol first-pass budget (the calibrated value from " + "preregistration.md, e.g. 512)", + ) args = parser.parse_args() resolve_protocol_budgets(parser, 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") + models = _parse_csv_choice( + args.models, vlm_models.available_models(), "--models" + ) + spatial_code_formats = (DEFAULT_SPATIAL_CODE_FORMAT,) if args.video: if args.input_selections is not None: raise ValueError("--input-selections cannot be used with --video") - selections, counts = ["video"], [None] + input_selections = ["video"] + frame_counts = [None] else: if args.input_selections is None: raise ValueError("--input-selections is required with --frames") - selections = _parse_csv_choice(args.input_selections, INPUT_SELECTIONS, - "--input-selections") - counts = _parse_frame_counts(args.frames) - code_sources = _parse_csv_choice(args.spatial_code_sources, - ("frames", "video"), - "--spatial-code-sources") - if "frames" in code_sources: - if (args.spatial_code_input_selections is None or - args.spatial_code_frames is None): - raise ValueError("spatial-code selections and frame counts are required " - "when frame-derived codes are included") - code_selections = _parse_csv_choice( - args.spatial_code_input_selections, INPUT_SELECTIONS, - "--spatial-code-input-selections") - code_counts = _parse_frame_counts(args.spatial_code_frames) - else: - if (args.spatial_code_input_selections is not None or - args.spatial_code_frames is not None): - raise ValueError("spatial-code frame flags cannot be used with video-only codes") - code_selections, code_counts = [], [] + input_selections = _parse_csv_choice( + args.input_selections, INPUT_SELECTIONS, "--input-selections" + ) + frame_counts = _parse_frame_counts(args.frames) depths = _parse_csv_choice(args.depths, DEPTH_VARIANTS, "--depths") trackings = _parse_csv_choice(args.trackings, TRACKING_MODES, "--trackings") except ValueError as exc: parser.error(str(exc)) + if args.scenes is not None: - selected = list(dict.fromkeys(x.strip() for x in args.scenes.split(",") if x.strip())) + 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, (DEFAULT_SPATIAL_CODE_FORMAT,), selections, counts, selected, - video=args.video, depths=depths, trackings=trackings, - spatial_code_sources=code_sources, - spatial_code_input_selections=code_selections, - spatial_code_frame_counts=code_counts, - results_dir=args.results_dir, rebuild=args.rebuild, + models, + spatial_code_formats, + input_selections, + frame_counts, + selected, + video=args.video, + depths=depths, + trackings=trackings, + results_dir=args.results_dir, + rebuild=args.rebuild, + extended=True, reasoning_budget=args.reasoning_budget, ) diff --git a/harness/D/__init__.py b/harness/D/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6043adb3af8a64d22fb7467c176d474fce2d58d6 --- /dev/null +++ b/harness/D/__init__.py @@ -0,0 +1,42 @@ +"""Harness D: harness.B's spatial-code-as-text routing, but the spatial code is the +GROUND-TRUTH one (encoder.ground_truth -- built from the dataset's own 3D annotations, +zero perception error) instead of the SAM3+DA3-perceived one B reads off disk. + +Ground truth has no depth/tracking/input-selection/frame-count axis at all (it is built +once per scene directly from annotations, not from any particular video-frame sampling +run) -- so D only sweeps model x spatial_code_format, both formats, mirroring exactly +the (model, format) grid harness.B actually swept at its one frozen (selection, frames) +config. Deliberately NOT narrowed to just B's winning format: ground-truth codes cost +nothing extra to build across formats (no encoder GPU pass at all), so running both +formats is free relative to running one, and it is the only way to see whether a +format's real-vs-perfect-perception ranking flips. + +Results are written in the identical per-question JSON shape harness.A/B/C use, so D's +records are directly comparable and drop straight into analysis.aggregate/analysis.compare +alongside every other harness. harness.D.symbolic_eval additionally answers every +question with the real symbolic solver run directly against the ground-truth code (no +VLM at all) -- the perfect-information ceiling -- written through symbolic.run's own +writer into results/symbolic/ground truth//, the same results family every +other symbolic-solver result already lives in, not a separate results/D/... location. +""" + +from __future__ import annotations + +import os +from pathlib import Path + +from harness.A import ( + DO_SAMPLE, + JSONL, + MAX_NEW_TOKENS, + MODEL_PATHS, + TEMPERATURE, + WORKSPACE_ROOT, +) +from harness.B import SPATIAL_CODE_FORMATS + +DEFAULT_SPATIAL_CODE_FORMAT = "explicit" + +# One JSON per question, matching harness.B's layout minus the axes ground truth doesn't +# have: results/D//code////.json +RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_D_RESULTS_DIR", "/root/results/D")) diff --git a/harness/D/launch.py b/harness/D/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..ae88e93d987251c517351f2d95ca91f2fd62c699 --- /dev/null +++ b/harness/D/launch.py @@ -0,0 +1,340 @@ +"""Keep every visible GPU busy with persistent harness-D inference workers. + +Same shape as ``harness.B.launch``, minus the depth/tracking/input-selection/frame-count +axes ground truth doesn't have: 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) pair across every requested scene; sweep multiple pairs by +invoking this once per pair (see harness.D.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 encoder.ground_truth import scenes as ground_truth_scenes # noqa: E402 +from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402 +from harness.A import models as vlm_models # noqa: E402 +from harness.B import ( + DEFAULT_INPUT_SELECTION, + FRAMES_PER_VIDEO, + INPUT_SELECTIONS, +) # noqa: E402 +from harness.D import DEFAULT_SPATIAL_CODE_FORMAT, SPATIAL_CODE_FORMATS # 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_D_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, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, + frames, + frame_selection, + frame_count, + raw_budget, + thinking, +): + 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) + if thinking and not adapter.set_thinking(True): + raise ValueError(f"{model} has no native thinking mode to enable") + 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, + scene=scene, + results_dir=results_dir, + adapter=adapter, + extended=extended, + reasoning_budget=reasoning_budget, + force_budget=force_budget, + frames=frames, + frame_selection=frame_selection, + frame_count=frame_count, + raw_budget=raw_budget, + thinking=thinking, + ) + 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, + selected, + results_dir=None, + rebuild=False, + extended=True, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, + frames=False, + frame_selection=DEFAULT_INPUT_SELECTION, + frame_count=FRAMES_PER_VIDEO, + raw_budget=None, + thinking=False, +): + """Answer every question for ``selected`` scenes, sharded across every visible GPU. + + ``raw_budget`` (mutually exclusive with ``extended``) runs the raw-budget arm: + base-protocol mechanics at this token cap, under its own truncated/ path + segment -- see harness.D.run.run.""" + if extended and raw_budget is not None: + raise ValueError("extended and raw_budget are mutually exclusive") + protocol = ( + f"{reasoning_budget}" + if extended + else f"truncated/{raw_budget}" if raw_budget is not None else "base" + ) + condition = f"{model}/{protocol}/{spatial_code_format}" + if frames: + condition += f"/frames/{frame_selection}/{frame_count}" + run = _load_run_module() + root = run.results_dir_for( + model, + protocol, + spatial_code_format, + results_dir, + frames=frames, + frame_selection=frame_selection, + frame_count=frame_count, + ) + pending = [] + completed = 0 + for scene in selected: + rows = run.load_questions(scene=scene) + if not rows: + raise ValueError( + f"no questions found for scene {scene!r}; check the manifest/scene selection" + ) + answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows) + if answered and not rebuild: + completed += 1 + print( + f"[{condition} {completed}/{len(selected)}] {scene}: skipped", + flush=True, + ) + 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, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, + frames, + frame_selection, + frame_count, + raw_budget, + thinking, + ), + ) + 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 scenes(): + """Every scene that both has a real VSI-Bench question AND ground-truth annotation + coverage -- i.e. every scene harness.A/B/C could ever be run on (all of them have GT, + since encoder.ground_truth covers the full 288-scene meta_info set, a superset of any + perception-built spatial code's coverage).""" + from harness.A.launch import scenes as vsi_scenes + + ground_truth = set(ground_truth_scenes()) + return [scene for scene in vsi_scenes() if scene in ground_truth] + + +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("--results-dir", default=None) + parser.add_argument("--rebuild", action="store_true") + parser.add_argument( + "--base-protocol", + action="store_true", + help="run harness.A's exact fixed 16-token protocol instead of the extended default", + ) + parser.add_argument( + "--with-frames", + action="store_true", + dest="frames", + help="frames+ground-truth-code arm: also sample and show the scene's raw video " + "frames alongside the ground-truth code (default sampling: uniform, 32 frames -- " + "the frozen Step-1 config)", + ) + parser.add_argument( + "--frame-selection", + default=DEFAULT_INPUT_SELECTION, + choices=INPUT_SELECTIONS, + dest="frame_selection", + help="only used with --with-frames", + ) + parser.add_argument( + "--frames-per-video", + type=int, + default=FRAMES_PER_VIDEO, + dest="frame_count", + help="only used with --with-frames", + ) + parser.add_argument( + "--thinking", + action="store_true", + help="enable the model's native thinking mode where supported; errors on models without the switch", + ) + parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) + parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) + parser.add_argument( + "--truncated-budget", + type=int, + default=None, + help="raw-budget arm: base-protocol mechanics (single generation, no forced " + "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive " + "with --base-protocol)", + ) + 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.reasoning_budget < 1: + parser.error("--reasoning-budget must be positive") + if args.force_budget < 1: + parser.error("--force-budget must be positive") + if args.frame_count < 1: + parser.error("--frames-per-video must be positive") + if args.truncated_budget is not None and args.truncated_budget < 1: + parser.error("--truncated-budget must be positive") + if args.base_protocol and args.truncated_budget is not None: + parser.error("--base-protocol and --truncated-budget are mutually exclusive") + launch( + args.model, + args.spatial_code_format, + selected, + results_dir=args.results_dir, + rebuild=args.rebuild, + extended=not args.base_protocol and args.truncated_budget is None, + frames=args.frames, + frame_selection=args.frame_selection, + frame_count=args.frame_count, + thinking=args.thinking, + reasoning_budget=args.reasoning_budget, + force_budget=args.force_budget, + raw_budget=args.truncated_budget, + ) + + +if __name__ == "__main__": + main() diff --git a/harness/D/prompts.py b/harness/D/prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..2babc677077aa4be23a33a0c093fe8f0ea3b9d02 --- /dev/null +++ b/harness/D/prompts.py @@ -0,0 +1,9 @@ +"""Ground-truth spatial-code prompt construction. + +Ground-truth and perceived code use the same v2 prompt text; only the loaded code file +differs. +""" + +from __future__ import annotations + +from harness.B.prompts import build_prompt diff --git a/harness/D/run.py b/harness/D/run.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b3fa2ef614d462a121effeabe6db2d58d2f75f --- /dev/null +++ b/harness/D/run.py @@ -0,0 +1,457 @@ +"""Run one VLM over VSI-Bench questions through harness D's ground-truth-spatial-code- +as-text routing. + +Writes one JSON file per question in the identical shape harness.A/B/C use -- the +frame-provenance fields are replaced with spatial-code provenance fields +(spatial_code_format, spatial_code_path), since D has no video frames and no depth/ +tracking/input-selection/frame-count axis at all (ground truth is built once per scene +straight from dataset annotations). Scoring reuses the same real, unmodified official +scorer every harness uses. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +import inference as inference_config # noqa: E402 +from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402 +from harness.A import frames as frame_sampling # noqa: E402 +from harness.A import models as vlm_models # noqa: E402 +from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402 +from harness.B import ( + DEFAULT_INPUT_SELECTION, + FRAMES_PER_VIDEO, + INPUT_SELECTIONS, +) # noqa: E402 +from harness.C import prompts as combined_prompts # noqa: E402 +from harness.D import ( + DEFAULT_SPATIAL_CODE_FORMAT, + RESULTS_DIR, + SPATIAL_CODE_FORMATS, +) # noqa: E402 +from harness.D import prompts as code_prompts # noqa: E402 +from harness.D import spatial_codes # noqa: E402 + + +def results_dir_for( + model, + protocol, + spatial_code_format, + results_dir=None, + frames=False, + frame_selection=DEFAULT_INPUT_SELECTION, + frame_count=FRAMES_PER_VIDEO, +): + """Return the result root isolated by model + protocol + spatial-code-format. + ``protocol`` is "base" (16-token) or "" (e.g. "512") -- a real path segment, so records from different protocols OR + different reasoning budgets can never collide on disk. + + ``frames=True`` (the frames+ground-truth-code arm) selects the sibling + "code + frames" branch and appends "/" -- video frames have no bearing on which ground-truth + code gets loaded (ground truth has no depth/tracking/input-selection axis at all; + see harness/D/__init__.py), but they DO change what the model sees, so this arm's + records must never share a path with the text-only condition's.""" + if results_dir is not None: + return Path(results_dir) + root = ( + RESULTS_DIR + / model + / ("code + frames" if frames else "code") + / protocol + / spatial_code_format + ) + if frames: + root = root / frame_selection / str(frame_count) + return root + + +def _build_record( + row, prompt, answer, metric_name, score, model, model_path, code_info +): + """Assemble one question's full, untruncated result record (nothing summarized). + + ``code_info`` carries frame provenance (``video_path``, ``frame_indices``, + ``frame_timestamps``) only for the frames+ground-truth-code arm; all three are None + on the standard text-only condition, matching how harness.A/B/D's other optional + fields (``reasoning_text`` etc.) are present-but-null rather than absent.""" + condition = f"{code_info['protocol']}:{code_info['spatial_code_format']}" + if code_info.get("frames"): + condition += ( + f":frames:{code_info['frame_selection']}:{code_info['frame_count']}" + ) + return { + "model": model, + "model_path": str(model_path), + "device": answer["device"], + "dtype": answer["dtype"], + "library_versions": answer["library_versions"], + "condition": condition, + "protocol": code_info["protocol"], + "spatial_code_format": code_info["spatial_code_format"], + "spatial_code_path": code_info["spatial_code_path"], + "frames": code_info.get("frames", False), + "frame_selection": code_info.get("frame_selection"), + "frame_count": code_info.get("frame_count"), + "video_path": code_info.get("video_path"), + "frame_indices": code_info.get("frame_indices"), + "frame_timestamps_seconds": code_info.get("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, + 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["protocol"], + code_info["spatial_code_format"], + results_dir, + frames=code_info.get("frames", False), + frame_selection=code_info.get("frame_selection", DEFAULT_INPUT_SELECTION), + frame_count=code_info.get("frame_count", FRAMES_PER_VIDEO), + ) + 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, + scene=None, + scenes=None, + limit=None, + device="cuda", + jsonl_path=None, + results_dir=None, + write_results=True, + adapter=None, + thinking=False, + extended=True, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, + code_transform=None, + frames=False, + frame_selection=DEFAULT_INPUT_SELECTION, + frame_count=FRAMES_PER_VIDEO, + raw_budget=None, +): + """Answer every matching question with one model, given its scene's GROUND-TRUTH + spatial code as text. Each question's full record is written to its own JSON file + as soon as it is answered (unless ``write_results=False``). + + ``frames=True`` runs the frames+ground-truth-code arm: the scene's raw video is + ALSO sampled (``frame_selection``/``frame_count``, harness.A.frames.sample_frames -- + the same sampling every harness uses; ground truth has no depth/tracking axis for + frames to be sourced "from", so there is nothing for this to mismatch against) and + shown alongside the ground-truth code, with harness.C's frames+code context line + (byte-identical composition rule: harness.A's frame sentence + harness.B's code + sentence, the same CODE_DESCRIPTION D's own text-only line already uses). This is + the ground-truth counterpart of harness C -- C answers with frames + a PERCEIVED + code; this is frames + the PERFECT code -- which harness C itself cannot produce, + since its spatial-code loader is perception-only. The default ``frame_selection``/ + ``frame_count`` match the frozen Step-1 config (uniform, 32) so a default frames=True + call needs no extra flags to land on the same sampling every other harness uses. + + Uses ``adapter.answer_extended`` as the standing default protocol, same as + harness.B -- working through a full spatial-code JSON before answering benefits + from more room than a short visual caption does. ``extended=False`` runs + harness.A's exact fixed 16-token base protocol instead (plain ``adapter.answer``). + + ``raw_budget`` (mutually exclusive with ``extended``) runs the raw-budget arm -- + same mechanism as ``extended=False`` (single generation, no forced rescue) but at + this token cap instead of the hardcoded 16, under its own "truncated/" + protocol path segment (mirrors harness.B/C's identical arm) so it can never collide + with either the extended or the base-protocol condition on disk. + + ``code_transform``, when given, is called as ``code_transform(code, scene_id, + spatial_code_format)`` on each freshly loaded code and its return value is what + the prompt is built from -- the hook the corruption module (README Theme 8) uses + to run corrupted codes through this EXACT prompt/adapter path instead of a + duplicated one. ``None`` (the default) leaves behavior byte-identical to before. + + Pass a pre-loaded ``adapter`` (as harness.D.launch's persistent per-GPU workers do) + to reuse one already-loaded model across many calls; the caller then owns unloading + it. Without one, ``run`` loads and unloads its own adapter, same as harness.A/B. + """ + if extended and raw_budget is not None: + raise ValueError("extended and raw_budget are mutually exclusive") + 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) + if thinking and not adapter.set_thinking(True): + raise ValueError(f"{model} has no native thinking mode to enable") + 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, spatial_code_format + ) + if code_transform is not None: + code = code_transform(code, scene_id, spatial_code_format) + entry = {"code": code, "path": path} + if frames: + video_path = inference_config.video_path( + scene_id, row.get("dataset") + ) + frame_images, frame_timestamps, frame_indices = ( + frame_sampling.sample_frames( + video_path, frame_count, frame_selection + ) + ) + entry.update( + video_path=video_path, + frame_images=frame_images, + frame_timestamps=frame_timestamps, + frame_indices=frame_indices, + ) + code_cache[scene_id] = entry + cached = code_cache[scene_id] + prompt_builder = combined_prompts.build_prompt if frames else code_prompts.build_prompt + prompt = prompt_builder( + cached["code"], + row["question_type"], + row["question"], + row.get("options"), + ) + answer = ( + adapter.answer_extended( + cached["frame_images"] if frames else [], + prompt, + reasoning_budget=reasoning_budget, + force_budget=force_budget, + ) + if extended + else adapter.answer( + cached["frame_images"] if frames else [], + prompt, + max_new_tokens=raw_budget, + ) + ) + doc = { + "question_type": row["question_type"], + "ground_truth": row["ground_truth"], + } + score_doc = vsi_official_eval.vsibench_process_results( + doc, [answer["answer_text"]] + )["vsibench_score"] + metric_name, score = _scalar_score(row["question_type"], score_doc) + code_info = { + "protocol": ( + f"{reasoning_budget}" + if extended + else f"truncated/{raw_budget}" if raw_budget is not None else "base" + ), + "spatial_code_format": spatial_code_format, + "spatial_code_path": cached["path"], + "frames": frames, + "frame_selection": frame_selection if frames else None, + "frame_count": frame_count if frames else None, + "video_path": cached.get("video_path"), + "frame_indices": cached.get("frame_indices"), + "frame_timestamps": cached.get("frame_timestamps"), + } + 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( + "--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/D//// root", + ) + parser.add_argument( + "--no-write", + action="store_true", + help="skip writing per-question JSON files; print/score only", + ) + parser.add_argument( + "--base-protocol", + action="store_true", + help="run harness.A's exact fixed 16-token protocol (plain answer()) instead of " + "the extended 2048-token default", + ) + parser.add_argument( + "--with-frames", + action="store_true", + dest="frames", + help="frames+ground-truth-code arm: also sample and show the scene's raw video " + "frames alongside the ground-truth code (default sampling: uniform, 32 frames -- " + "the frozen Step-1 config)", + ) + parser.add_argument( + "--frame-selection", + default=DEFAULT_INPUT_SELECTION, + choices=INPUT_SELECTIONS, + dest="frame_selection", + help="only used with --with-frames", + ) + parser.add_argument( + "--frames-per-video", + type=int, + default=FRAMES_PER_VIDEO, + dest="frame_count", + help="only used with --with-frames", + ) + parser.add_argument( + "--thinking", + action="store_true", + help="enable the model's native thinking mode where supported; errors on models without the switch", + ) + parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) + parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) + parser.add_argument( + "--truncated-budget", + type=int, + default=None, + help="raw-budget arm: base-protocol mechanics (single generation, no forced " + "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive " + "with --base-protocol)", + ) + args = parser.parse_args() + if args.reasoning_budget < 1: + parser.error("--reasoning-budget must be positive") + if args.force_budget < 1: + parser.error("--force-budget must be positive") + if args.frame_count < 1: + parser.error("--frames-per-video must be positive") + if args.truncated_budget is not None and args.truncated_budget < 1: + parser.error("--truncated-budget must be positive") + if args.base_protocol and args.truncated_budget is not None: + parser.error("--base-protocol and --truncated-budget are mutually exclusive") + + results = run( + args.model, + spatial_code_format=args.spatial_code_format, + scene=args.scene, + limit=args.limit, + device=args.device, + results_dir=args.results_dir, + write_results=not args.no_write, + extended=not args.base_protocol and args.truncated_budget is None, + thinking=args.thinking, + reasoning_budget=args.reasoning_budget, + force_budget=args.force_budget, + frames=args.frames, + frame_selection=args.frame_selection, + frame_count=args.frame_count, + raw_budget=args.truncated_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/D/spatial_codes.py b/harness/D/spatial_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233a5523d68ce5c228df77bbbc7ecfb99fd0352 --- /dev/null +++ b/harness/D/spatial_codes.py @@ -0,0 +1,32 @@ +"""Load one scene's GROUND-TRUTH spatial code (explicit or compact) as plain JSON. + +Same "no solver-side adaptation" philosophy as harness.B.spatial_codes: the model is +shown literally the same file encoder.ground_truth 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 ground_truth_spatial_code_path + +from harness.D import SPATIAL_CODE_FORMATS + + +def load_spatial_code(scene, 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 = ground_truth_spatial_code_path(scene, spatial_code_format) + if not Path(path).is_file(): + raise FileNotFoundError( + f"no ground-truth spatial code found for scene {scene!r} at {path} -- " + "run `python -m encoder.ground_truth` to build it" + ) + with open(path, encoding="utf-8") as stream: + return json.load(stream), path diff --git a/harness/D/sweep.py b/harness/D/sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..9868ec76fef13a0a181d2b396943d05dad5f1954 --- /dev/null +++ b/harness/D/sweep.py @@ -0,0 +1,204 @@ +"""Sweep any set of models x spatial-code-formats over ground-truth spatial codes. + +Every (model, spatial_code_format) pair in the sweep is run through +``harness.D.launch.launch`` in turn, so each pair individually saturates every visible +GPU before the next one starts. No depth/tracking/input-selection/frame-count axes -- +ground truth has none of those (see harness/D/__init__.py) -- so by design this sweeps +BOTH spatial_code_formats for every model rather than picking one winning format, per +this session's execution-design decision: ground-truth codes cost nothing extra to build +across formats (no GPU encoder pass at all), so the marginal cost of covering both is +just the extra VLM inference calls, and seeing whether a format's real-vs-perfect +ranking flips is exactly the kind of thing this phase exists to check. +""" + +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 import EXTENDED_MAX_NEW_TOKENS # noqa: E402 +from harness.A.sweep import _parse_csv_choice # noqa: E402 +from harness.B import ( + DEFAULT_INPUT_SELECTION, + FRAMES_PER_VIDEO, + INPUT_SELECTIONS, + SPATIAL_CODE_FORMATS, +) # noqa: E402 +from harness.D import launch as harness_launch # noqa: E402 + + +def build_plan(models, spatial_code_formats): + """Return every (model, spatial_code_format) pair in the sweep.""" + return [ + (model, spatial_code_format) + for model in models + for spatial_code_format in spatial_code_formats + ] + + +def sweep( + models, + spatial_code_formats, + selected_scenes, + results_dir=None, + rebuild=False, + thinking=False, + extended=True, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + frames=False, + frame_selection=DEFAULT_INPUT_SELECTION, + frame_count=FRAMES_PER_VIDEO, + raw_budget=None, +): + """Run every (model, spatial_code_format) pair across all visible GPUs.""" + plan = build_plan(models, spatial_code_formats) + protocol = ( + f"{reasoning_budget}" + if extended + else f"truncated/{raw_budget}" if raw_budget is not None else "base" + ) + for index, (model, spatial_code_format) in enumerate(plan, start=1): + print( + f"=== sweep {index}/{len(plan)}: {model}/{protocol}/{spatial_code_format}" + + (f"/frames/{frame_selection}/{frame_count}" if frames else "") + + " ===", + flush=True, + ) + harness_launch.launch( + model, + spatial_code_format, + selected_scenes, + results_dir=results_dir, + rebuild=rebuild, + thinking=thinking, + extended=extended, + reasoning_budget=reasoning_budget, + frames=frames, + frame_selection=frame_selection, + frame_count=frame_count, + raw_budget=raw_budget, + ) + + +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", + default="all", + dest="spatial_code_formats", + help=f"comma-separated formats (or 'all'); one of {SPATIAL_CODE_FORMATS}", + ) + parser.add_argument("--results-dir", default=None) + parser.add_argument("--rebuild", action="store_true") + parser.add_argument( + "--base-protocol", + action="store_true", + help="run the whole sweep under harness.A's exact fixed 16-token protocol " + "instead of the extended default", + ) + parser.add_argument( + "--thinking", + action="store_true", + help="enable the model's native thinking mode where supported; errors on models without the switch", + ) + parser.add_argument( + "--reasoning-budget", + type=int, + default=EXTENDED_MAX_NEW_TOKENS, + dest="reasoning_budget", + help="extended-protocol first-pass budget (the calibrated value from " + "analysis/preregistration.md, e.g. 512)", + ) + parser.add_argument( + "--with-frames", + action="store_true", + dest="frames", + help="frames+ground-truth-code arm: also sample and show the scene's raw video " + "frames alongside the ground-truth code (default sampling: uniform, 32 frames -- " + "the frozen Step-1 config)", + ) + parser.add_argument( + "--frame-selection", + default=DEFAULT_INPUT_SELECTION, + choices=INPUT_SELECTIONS, + dest="frame_selection", + help="only used with --with-frames", + ) + parser.add_argument( + "--frames-per-video", + type=int, + default=FRAMES_PER_VIDEO, + dest="frame_count", + help="only used with --with-frames", + ) + parser.add_argument( + "--truncated-budget", + type=int, + default=None, + help="raw-budget arm: base-protocol mechanics (single generation, no forced " + "rescue) at this token cap instead of the hardcoded 16 (mutually exclusive " + "with --base-protocol)", + ) + args = parser.parse_args() + if args.scene and args.scenes: + parser.error("positional scene and --scenes cannot be used together") + if args.frame_count < 1: + parser.error("--frames-per-video must be positive") + if args.truncated_budget is not None and args.truncated_budget < 1: + parser.error("--truncated-budget must be positive") + if args.base_protocol and args.truncated_budget is not None: + parser.error("--base-protocol and --truncated-budget are mutually exclusive") + + 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" + ) + 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, + spatial_code_formats, + selected, + results_dir=args.results_dir, + rebuild=args.rebuild, + thinking=args.thinking, + extended=not args.base_protocol and args.truncated_budget is None, + reasoning_budget=args.reasoning_budget, + frames=args.frames, + frame_selection=args.frame_selection, + frame_count=args.frame_count, + raw_budget=args.truncated_budget, + ) + + +if __name__ == "__main__": + main() diff --git a/harness/D/symbolic_eval.py b/harness/D/symbolic_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..aa206a14618d3631517e25e35e655265c9390cbb --- /dev/null +++ b/harness/D/symbolic_eval.py @@ -0,0 +1,152 @@ +"""Run the real symbolic solver directly against ground-truth spatial codes -- no VLM at +all -- the perfect-information ceiling: perfect geometry AND perfect (deterministic, +formula-driven) reasoning over it. + +Reuses symbolic/solver.py and symbolic/adapters.py completely unmodified (the same +solver harness.D.run's VLM path is being compared against use for scoring, and +symbolic/run.py itself uses for the encoder-perceived spatial codes) -- this module only +supplies ground-truth-sourced input instead of a perception-pipeline-sourced one. + +Results are written through symbolic.run's own writer, in symbolic's own native record +shape, landing in the SAME results family every other symbolic-solver result already +lives in: results/symbolic/ground truth///.json -- not a +separate results/D/... location -- since this IS a symbolic-solver run, just against +ground-truth input instead of a perception-pipeline selection +(symbolic.run.select_ground_truth_spatial_codes). +""" + +from __future__ import annotations + +import argparse +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.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402 +from harness.D import DEFAULT_SPATIAL_CODE_FORMAT, SPATIAL_CODE_FORMATS # noqa: E402 +from harness.D import spatial_codes # noqa: E402 +from symbolic import adapters, solver # noqa: E402 +from symbolic import run as symbolic_run # noqa: E402 + + +def run( + spatial_code_format=DEFAULT_SPATIAL_CODE_FORMAT, + scene=None, + scenes=None, + limit=None, + jsonl_path=None, + results_dir=None, + write_results=True, +): + """Answer every matching question with the real symbolic solver, given each + question's scene's GROUND-TRUTH spatial code. Writes symbolic's own native-shape + record (results/symbolic/ground truth//...) when ``write_results``.""" + rows = load_questions(jsonl_path, scene, scenes, limit) + if not rows: + return [] + if write_results: + symbolic_run.select_ground_truth_spatial_codes(spatial_code_format) + code_cache = {} + results = [] + for row in rows: + scene_id = row["scene_name"] + if scene_id not in code_cache: + code, path = spatial_codes.load_spatial_code(scene_id, spatial_code_format) + code_cache[scene_id] = { + "adapted": adapters.adapt_spatial_code(code), + "path": path, + } + cached = code_cache[scene_id] + answer = solver.answer( + row["question_type"], row["question"], row["options"], cached["adapted"] + ) + pred_str = "" if answer is None else str(answer) + doc = { + "question_type": row["question_type"], + "ground_truth": row["ground_truth"], + } + score_doc = vsi_official_eval.vsibench_process_results(doc, [pred_str])[ + "vsibench_score" + ] + _metric_name, score = _scalar_score(row["question_type"], score_doc) + record = { + "scene": scene_id, + "dataset": row.get("dataset"), + "question_id": row["id"], + "question_type": row["question_type"], + "question": row["question"], + "answer_expected": row["ground_truth"], + "answer_given": pred_str, + "score": score, + } + if write_results: + pq = { + "question_id": row["id"], + "dataset": row.get("dataset"), + "question_type": row["question_type"], + "question": row["question"], + "options": row.get("options"), + "engine_answer": answer, + "ground_truth": row["ground_truth"], + "score": score, + } + path = symbolic_run.write_question_result( + scene_id, pq, cached["adapted"], results_dir=results_dir + ) + record["result_path"] = str(path) + else: + record["result_path"] = None + results.append(record) + return results + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("scene", nargs="?") + parser.add_argument("--scenes", help="comma-separated scenes") + parser.add_argument( + "--spatial-code-format", + default=DEFAULT_SPATIAL_CODE_FORMAT, + choices=SPATIAL_CODE_FORMATS, + dest="spatial_code_format", + ) + parser.add_argument("--limit", type=int, default=None) + parser.add_argument( + "--results-dir", + default=None, + help="override the default results/symbolic/ground truth/ root", + ) + parser.add_argument("--no-write", action="store_true") + args = parser.parse_args() + if args.scene and args.scenes: + parser.error("positional scene and --scenes cannot be used together") + selected = None + if args.scenes: + selected = list( + dict.fromkeys(s.strip() for s in args.scenes.split(",") if s.strip()) + ) + + results = run( + spatial_code_format=args.spatial_code_format, + scene=args.scene, + scenes=selected, + limit=args.limit, + results_dir=args.results_dir, + write_results=not args.no_write, + ) + 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['result_path']}" + ) + if results: + mean_score = sum(r["score"] for r in results) / len(results) + print(f"\n{len(results)} questions, mean vsibench_score={mean_score:.4f}") + + +if __name__ == "__main__": + main() diff --git a/harness/E/__init__.py b/harness/E/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d33b2e6ae03fe3cbfea57f3cee1df04f2de811e2 --- /dev/null +++ b/harness/E/__init__.py @@ -0,0 +1,31 @@ +"""Harness E: the BLIND floor -- question (and options) only, no video frames, no +spatial code, no scene information of any kind. + +VSI-Bench's own paper shows blind LLMs beat chance on several categories through pure +priors (typical room sizes, typical object sizes), so a question-only floor is what +separates "the model used the geometry it was given" from "the prompt shifted its +priors." Every harness A/B/C/D delta is only interpretable against this floor. + +Reuses harness.A's models, generation protocols (base 16-token by default, --extended +opt-in, exactly like harness.A), question-type split, and post-prompts. Results are +written in the identical per-question record shape as every other harness: +results/E////.json. +""" + +from __future__ import annotations + +import os +from pathlib import Path + +from harness.A import ( + DO_SAMPLE, + JSONL, + MAX_NEW_TOKENS, + MODEL_PATHS, + PROTOCOLS, + TEMPERATURE, + WORKSPACE_ROOT, +) + +# One JSON per question: results/E////.json +RESULTS_DIR = Path(os.environ.get("VSI_HARNESS_E_RESULTS_DIR", "/root/results/E")) diff --git a/harness/E/launch.py b/harness/E/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..72f5be92b6b8dc0dcd12f5f8f96c212daeea6161 --- /dev/null +++ b/harness/E/launch.py @@ -0,0 +1,234 @@ +"""Keep every visible GPU busy with persistent harness-E (blind floor) 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, protocol) pair across every requested scene. +""" + +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 inference.launch import available_cpu_count, visible_gpus # noqa: E402 + + +def _load_run_module(): + spec = importlib.util.spec_from_file_location("_harness_E_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, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, + thinking, +): + 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) + if thinking and not adapter.set_thinking(True): + raise ValueError(f"{model} has no native thinking mode to enable") + 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, + scene=scene, + results_dir=results_dir, + adapter=adapter, + extended=extended, + reasoning_budget=reasoning_budget, + force_budget=force_budget, + thinking=thinking, + ) + 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, + selected, + results_dir=None, + rebuild=False, + extended=False, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, + thinking=False, +): + """Answer every question for ``selected`` scenes, sharded across every visible GPU.""" + protocol = f"{reasoning_budget}" if extended else "base" + condition = f"{model}/{protocol}" + run = _load_run_module() + root = run.results_dir_for(model, protocol, results_dir) + pending = [] + completed = 0 + for scene in selected: + rows = run.load_questions(scene=scene) + if not rows: + raise ValueError( + f"no questions found for scene {scene!r}; check the manifest/scene selection" + ) + answered = all((root / scene / f"{row['id']}.json").is_file() for row in rows) + if answered and not rebuild: + completed += 1 + print( + f"[{condition} {completed}/{len(selected)}] {scene}: skipped", + flush=True, + ) + 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, + results_dir, + gpu, + cpu_threads, + extended, + reasoning_budget, + force_budget, + thinking, + ), + ) + 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("--results-dir", default=None) + parser.add_argument("--rebuild", action="store_true") + parser.add_argument( + "--extended", + action="store_true", + help="use the extended 2048-token protocol instead of the fixed 16-token default", + ) + parser.add_argument( + "--thinking", + action="store_true", + help="enable the model's native thinking mode where supported; errors on models without the switch", + ) + 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.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, + selected, + results_dir=args.results_dir, + rebuild=args.rebuild, + extended=args.extended, + thinking=args.thinking, + reasoning_budget=args.reasoning_budget, + force_budget=args.force_budget, + ) + + +if __name__ == "__main__": + main() diff --git a/harness/E/prompts.py b/harness/E/prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..774e40944b53b4eb2d43a11f8288140dde0c6c71 --- /dev/null +++ b/harness/E/prompts.py @@ -0,0 +1,36 @@ +"""VSI-Bench prompt construction with NO scene input at all -- the blind floor. + +Reuses harness.A.prompts's question-type split and final-answer constraints. There +is deliberately NO context line: there are no frames and no spatial code to describe, +and inventing one ("answer from your general knowledge") would itself be an +uncontrolled prompt manipulation. The prompt is exactly the question (and options) +plus the same post-prompt every other harness uses for that question type. +""" + +from __future__ import annotations + +from harness.A.prompts import ( + MCA_POST_PROMPT, + MCA_QUESTION_TYPES, + NA_POST_PROMPT, + NA_QUESTION_TYPES, + STEP_BY_STEP_REASONING_PROMPT, +) + + +def build_prompt(question_type, question, options=None): + """Return the blind text prompt: the question, options (for MCA types), and the + same VSI-Bench post-prompt harness.A uses for the same question_type.""" + if question_type in NA_QUESTION_TYPES: + return "\n".join([question, STEP_BY_STEP_REASONING_PROMPT, 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( + [question, options_block, STEP_BY_STEP_REASONING_PROMPT, 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/E/run.py b/harness/E/run.py new file mode 100644 index 0000000000000000000000000000000000000000..d59bacc441b272fb46ed18cc96635bf97b1999a1 --- /dev/null +++ b/harness/E/run.py @@ -0,0 +1,262 @@ +"""Run one VLM over VSI-Bench questions completely blind -- question text only. + +Writes one JSON file per question in the identical shape harness.A/B/C/D use -- with no +frame or spatial-code provenance fields at all, since E receives no scene input of any +kind. Scoring reuses the same real, unmodified official scorer every harness uses. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent +if str(WORKSPACE_ROOT) not in sys.path: + sys.path.insert(0, str(WORKSPACE_ROOT)) + +from harness.A import EXTENDED_MAX_NEW_TOKENS, MAX_NEW_TOKENS # noqa: E402 +from harness.A import models as vlm_models # noqa: E402 +from harness.A.run import _scalar_score, load_questions, vsi_official_eval # noqa: E402 +from harness.E import RESULTS_DIR # noqa: E402 +from harness.E import prompts as blind_prompts # noqa: E402 + + +def results_dir_for(model, protocol, results_dir=None): + """Return the result root isolated by model + protocol. ``protocol`` is "base" + (16-token) or "extended" (2048-token) -- a real path segment, so the two protocols' + records can never collide on disk.""" + if results_dir is not None: + return Path(results_dir) + return RESULTS_DIR / model / protocol + + +def _build_record(row, prompt, answer, metric_name, score, model, model_path, protocol): + """Assemble one question's full, untruncated result record (nothing summarized).""" + return { + "model": model, + "model_path": str(model_path), + "device": answer["device"], + "dtype": answer["dtype"], + "library_versions": answer["library_versions"], + "condition": protocol, + "protocol": protocol, + "scene": row["scene_name"], + "dataset": row.get("dataset"), + "question_id": row["id"], + "question_type": row["question_type"], + "question": row["question"], + "options": row.get("options"), + "full_prompt": prompt, + "rendered_prompt": answer["prompt_text"], + "answer_expected": row["ground_truth"], + "answer_given": answer["answer_text"], + "answer_raw": answer["answer_raw"], + "input_token_count": answer["input_token_count"], + "vision_input_shapes": answer["vision_input_shapes"], + "output_token_ids": answer["output_token_ids"], + "output_token_count": answer["output_token_count"], + "hit_token_limit": answer["hit_token_limit"], + "eos_token_ids": answer["eos_token_ids"], + "generation_seconds": answer["generation_seconds"], + "generation_config": answer["generation_config"], + "reasoning_text": answer.get("reasoning_text"), + "reasoning_raw": answer.get("reasoning_raw"), + "reasoning_token_ids": answer.get("reasoning_token_ids"), + "reasoning_token_count": answer.get("reasoning_token_count"), + "reasoning_hit_limit": answer.get("reasoning_hit_limit"), + "forced": answer.get("forced", False), + "forced_input_token_count": answer.get("forced_input_token_count"), + "metric": metric_name, + "score": score, + } + + +def write_question_result( + row, + prompt, + answer, + metric_name, + score, + model, + model_path, + protocol, + results_dir=None, +): + """Write one question's full, untruncated result record. Return (path, record).""" + record = _build_record( + row, prompt, answer, metric_name, score, model, model_path, protocol + ) + root = results_dir_for(model, protocol, results_dir) + scene_dir = root / record["scene"] + scene_dir.mkdir(parents=True, exist_ok=True) + path = scene_dir / f"{row['id']}.json" + with path.open("w", encoding="utf-8") as stream: + json.dump(record, stream, indent=1) + return path, record + + +def run( + model, + scene=None, + scenes=None, + limit=None, + device="cuda", + jsonl_path=None, + results_dir=None, + write_results=True, + adapter=None, + thinking=False, + extended=False, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, + force_budget=MAX_NEW_TOKENS, +): + """Answer every matching question with one model, completely blind (question text + only, no frames, no spatial code). Each question's full record is written to its + own JSON file as soon as it is answered (unless ``write_results=False``). + + Base 16-token protocol by default, exactly like harness.A; ``extended=True`` + switches to the same ``answer_extended`` protocol every other harness supports. + + Pass a pre-loaded ``adapter`` (as harness.E.launch's persistent per-GPU workers do) + to reuse one already-loaded model across many calls; the caller then owns unloading + it. Without one, ``run`` loads and unloads its own adapter, same as harness.A. + """ + rows = load_questions(jsonl_path, scene, scenes, limit) + if not rows: + return [] + owns_adapter = adapter is None + if owns_adapter: + adapter = vlm_models.get_adapter(model) + if thinking and not adapter.set_thinking(True): + raise ValueError(f"{model} has no native thinking mode to enable") + adapter.load_model(device) + protocol = f"{reasoning_budget}" if extended else "base" + results = [] + try: + for row in rows: + prompt = blind_prompts.build_prompt( + row["question_type"], row["question"], row.get("options") + ) + answer = ( + adapter.answer_extended( + [], + prompt, + reasoning_budget=reasoning_budget, + force_budget=force_budget, + ) + if extended + else adapter.answer([], prompt) + ) + doc = { + "question_type": row["question_type"], + "ground_truth": row["ground_truth"], + } + score_doc = vsi_official_eval.vsibench_process_results( + doc, [answer["answer_text"]] + )["vsibench_score"] + metric_name, score = _scalar_score(row["question_type"], score_doc) + if write_results: + path, record = write_question_result( + row, + prompt, + answer, + metric_name, + score, + model, + adapter.model_path, + protocol, + results_dir, + ) + else: + path = None + record = _build_record( + row, + prompt, + answer, + metric_name, + score, + model, + adapter.model_path, + protocol, + ) + record["result_path"] = str(path) if path else None + results.append(record) + finally: + if owns_adapter: + adapter.unload() + return results + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", required=True, choices=vlm_models.available_models()) + parser.add_argument("--scene", default=None, help="restrict to one VSI-Bench scene") + parser.add_argument( + "--limit", type=int, default=None, help="cap the number of questions" + ) + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--results-dir", + default=None, + help="override the default results/E// root", + ) + parser.add_argument( + "--no-write", + action="store_true", + help="skip writing per-question JSON files; print/score only", + ) + parser.add_argument( + "--extended", + action="store_true", + help=( + f"use a {EXTENDED_MAX_NEW_TOKENS}-token reasoning budget instead of the fixed " + f"{MAX_NEW_TOKENS}-token VSI-Bench protocol, with a short forced second call " + "only if the model doesn't conclude within it" + ), + ) + parser.add_argument( + "--thinking", + action="store_true", + help="enable the model's native thinking mode where supported; errors on models without the switch", + ) + parser.add_argument("--reasoning-budget", type=int, default=EXTENDED_MAX_NEW_TOKENS) + parser.add_argument("--force-budget", type=int, default=MAX_NEW_TOKENS) + args = parser.parse_args() + if args.reasoning_budget < 1: + parser.error("--reasoning-budget must be positive") + if args.force_budget < 1: + parser.error("--force-budget must be positive") + + results = run( + args.model, + scene=args.scene, + limit=args.limit, + device=args.device, + results_dir=args.results_dir, + write_results=not args.no_write, + extended=args.extended, + thinking=args.thinking, + 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/E/sweep.py b/harness/E/sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..4951da8034383ac6d5fe4b7831cea53d78c44926 --- /dev/null +++ b/harness/E/sweep.py @@ -0,0 +1,115 @@ +"""Sweep any set of models over the blind floor (question-only, no scene input). + +Every model in the sweep is run through ``harness.E.launch.launch`` in turn, so each +model individually saturates every visible GPU before the next one starts. The only +other axis is the generation protocol (--extended), matching harness.A's flag. +""" + +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 EXTENDED_MAX_NEW_TOKENS # noqa: E402 +from harness.A import models as vlm_models # noqa: E402 +from harness.A.sweep import _parse_csv_choice # noqa: E402 +from harness.E import launch as harness_launch # noqa: E402 + + +def sweep( + models, + selected_scenes, + results_dir=None, + rebuild=False, + thinking=False, + extended=False, + reasoning_budget=EXTENDED_MAX_NEW_TOKENS, +): + """Run every model across all visible GPUs.""" + protocol = "extended" if extended else "base" + for index, model in enumerate(models, start=1): + print(f"=== sweep {index}/{len(models)}: {model}/{protocol} ===", flush=True) + harness_launch.launch( + model, + selected_scenes, + results_dir=results_dir, + rebuild=rebuild, + thinking=thinking, + extended=extended, + reasoning_budget=reasoning_budget, + ) + + +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("--results-dir", default=None) + parser.add_argument("--rebuild", action="store_true") + parser.add_argument( + "--extended", + action="store_true", + help="run the whole sweep under the extended protocol instead of the fixed " + "16-token default", + ) + parser.add_argument( + "--thinking", + action="store_true", + help="enable the model's native thinking mode where supported; errors on models without the switch", + ) + parser.add_argument( + "--reasoning-budget", + type=int, + default=EXTENDED_MAX_NEW_TOKENS, + dest="reasoning_budget", + help="extended-protocol first-pass budget (the calibrated value from " + "analysis/preregistration.md, e.g. 512)", + ) + 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" + ) + 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, + selected, + results_dir=args.results_dir, + rebuild=args.rebuild, + thinking=args.thinking, + extended=args.extended, + reasoning_budget=args.reasoning_budget, + ) + + +if __name__ == "__main__": + main() diff --git a/tests/test_C/test_overlay.py b/tests/test_C/test_overlay.py new file mode 100644 index 0000000000000000000000000000000000000000..f087058a643d116cd69ea1b72d2cc6cfb457af28 --- /dev/null +++ b/tests/test_C/test_overlay.py @@ -0,0 +1,209 @@ +"""Tests for harness/C/overlay.py -- overlay labels, cache, and stamping.""" + +import json +from pathlib import Path + +import pytest +from PIL import Image + +from harness.C import overlay + +_EXPLICIT_CODE = { + "objects": { + "chair": { + "instances": [ + { + "position": { + "x coordinate": "1.5 m", + "y coordinate": "-2 m", + "height above floor": "0.25 m", + }, + "longest dimension": "0.80 m", + } + ] + }, + "table": { + "instances": [ + { + "position": { + "x coordinate": "3 m", + "y coordinate": "4 m", + "height above floor": "0 m", + }, + "longest dimension": "1.20 m", + } + ] + }, + } +} + + +def test_instance_ids_adds_stable_one_based_labels_without_mutating_input(): + original = {"objects": {"chair": {"instances": [{"position": {}}]}}} + + labeled = overlay.instance_ids(original) + + assert labeled["objects"]["chair"]["instances"][0]["instance id"] == "chair 1" + assert "instance id" not in original["objects"]["chair"]["instances"][0] + + +def test_overlay_spatial_code_path_lives_under_overlay_root(monkeypatch, tmp_path): + monkeypatch.setattr( + overlay.encoder_config, "CODES_ROOT", tmp_path / "data" / "spatial codes" + ) + monkeypatch.setattr(overlay.encoder_config, "MODEL", "sam3+depth-anything-3") + + path = overlay.overlay_spatial_code_path( + "scene", "metric", "uniform", "tracking", 32 + ) + + assert path == ( + tmp_path + / "data" + / "spatial codes" + / "overlay" + / "sam3+depth-anything-3" + / "metric" + / "tracking" + / "uniform" + / "32" + / "explicit" + / "scene.json" + ) + + +def test_load_or_create_overlay_code_saves_missing_file(monkeypatch, tmp_path): + monkeypatch.setattr(overlay.encoder_config, "CODES_ROOT", tmp_path / "codes") + monkeypatch.setattr(overlay.encoder_config, "MODEL", "model") + + code, path = overlay.load_or_create_overlay_code( + _EXPLICIT_CODE, "scene", "metric", "uniform", "tracking", 32 + ) + + path = Path(path) + assert path.is_file() + assert json.loads(path.read_text()) == code + assert code["objects"]["chair"]["instances"][0]["instance id"] == "chair 1" + + +def test_load_or_create_overlay_code_reuses_existing_file(monkeypatch, tmp_path): + monkeypatch.setattr(overlay.encoder_config, "CODES_ROOT", tmp_path / "codes") + monkeypatch.setattr(overlay.encoder_config, "MODEL", "model") + path = overlay.overlay_spatial_code_path( + "scene", "metric", "uniform", "tracking", 32 + ) + path.parent.mkdir(parents=True) + existing = {"objects": {"saved": {"instances": []}}, "sentinel": True} + path.write_text(json.dumps(existing)) + + code, returned = overlay.load_or_create_overlay_code( + _EXPLICIT_CODE, "scene", "metric", "uniform", "tracking", 32 + ) + + assert returned == str(path) + assert code == existing + assert json.loads(path.read_text()) == existing + + +def test_label_positions_parse_meter_strings_in_code_order(): + assert overlay.label_positions(_EXPLICIT_CODE) == [ + ("chair 1", 1.5, -2.0, 0.25, 0.8), + ("table 1", 3.0, 4.0, 0.0, 1.2), + ] + + +def test_load_cached_frames_requires_complete_png_set_and_labels(tmp_path): + assert overlay._load_cached_frames(tmp_path, 2) is None + (tmp_path / "labels.json").write_text(json.dumps([["chair 1"], []])) + Image.new("RGB", (4, 4), "white").save(tmp_path / "0.png") + assert overlay._load_cached_frames(tmp_path, 2) is None + + Image.new("RGB", (4, 4), "black").save(tmp_path / "1.png") + images, visible = overlay._load_cached_frames(tmp_path, 2) + + assert [image.mode for image in images] == ["RGB", "RGB"] + assert visible == [["chair 1"], []] + + +def test_save_cached_frames_writes_pngs_and_labels(tmp_path): + frames = [Image.new("RGB", (2, 2), color) for color in ("white", "black")] + + overlay._save_cached_frames(tmp_path, frames, [["a"], ["b"]]) + + assert (tmp_path / "0.png").is_file() + assert (tmp_path / "1.png").is_file() + assert json.loads((tmp_path / "labels.json").read_text()) == [["a"], ["b"]] + + +def test_stamp_frames_uses_raw_sam3_boxes_and_does_not_mutate_inputs( + monkeypatch, tmp_path +): + monkeypatch.setattr( + overlay, "overlay_frame_cache_dir", lambda *args: tmp_path / "cache" + ) + monkeypatch.setattr( + overlay.perceive, + "cache_or_load", + lambda *args: ({"geometry": "fake"}, "cache"), + ) + monkeypatch.setattr( + overlay.gm, + "instance_source_track_ids", + lambda geometry: {"chair": [[10]], "table": [[20]]}, + ) + monkeypatch.setattr( + overlay, + "_load_raw_sam3_boxes", + lambda *args: { + "chair": {0: {10: (0.10, 0.10, 0.30, 0.30)}}, + "table": {1: {20: (0.50, 0.50, 0.25, 0.25)}}, + }, + ) + frames = [Image.new("RGB", (40, 40), "white"), Image.new("RGB", (40, 40), "white")] + before = frames[0].copy() + + stamped, visible = overlay.stamp_frames( + frames, + _EXPLICIT_CODE, + "scene", + "metric", + "uniform", + "tracking", + 2, + use_cache=True, + ) + + assert visible == [["chair 1"], ["table 1"]] + assert stamped[0].getpixel((8, 8)) != before.getpixel((8, 8)) + assert frames[0].tobytes() == before.tobytes() + cached = overlay._load_cached_frames(tmp_path / "cache", 2) + assert cached is not None + assert cached[1] == visible + + +def test_stamp_frames_serves_complete_cache_without_loading_dependencies( + monkeypatch, tmp_path +): + cache_dir = tmp_path / "cache" + overlay._save_cached_frames( + cache_dir, [Image.new("RGB", (2, 2), "red")], [["cached"]] + ) + monkeypatch.setattr(overlay, "overlay_frame_cache_dir", lambda *args: cache_dir) + monkeypatch.setattr( + overlay.perceive, + "cache_or_load", + lambda *args: pytest.fail("cache hit should not touch perception"), + ) + + stamped, visible = overlay.stamp_frames( + [Image.new("RGB", (2, 2), "white")], + {}, + "scene", + "metric", + "uniform", + "tracking", + 1, + ) + + assert visible == [["cached"]] + assert stamped[0].getpixel((0, 0)) == (255, 0, 0) diff --git a/tests/test_C/test_overlay_launch.py b/tests/test_C/test_overlay_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8ab35c47b74a51b9650679fd5368be8b2e3933 --- /dev/null +++ b/tests/test_C/test_overlay_launch.py @@ -0,0 +1,144 @@ +"""Tests for harness/C/overlay_launch.py -- cache pregeneration orchestration.""" + +import pytest + +from harness.C import overlay_launch + + +def test_available_cpu_count_honors_positive_environment(monkeypatch): + monkeypatch.setenv("VSI_CPU_WORKERS", "3") + assert overlay_launch._available_cpu_count() == 3 + monkeypatch.setenv("VSI_CPU_WORKERS", "0") + with pytest.raises(ValueError, match="positive"): + overlay_launch._available_cpu_count() + + +def test_has_dependencies_requires_spatial_code_and_sam3_cache(monkeypatch, tmp_path): + cache = tmp_path / "sam3.pt" + monkeypatch.setattr( + overlay_launch.spatial_codes, + "load_spatial_code", + lambda *args: ({"objects": {}}, "code.json"), + ) + monkeypatch.setattr( + "encoder.config.sam3_cache_file", + lambda *args: cache, + ) + + assert ( + overlay_launch._has_dependencies("scene", "metric", "uniform", "tracking", 32) + is False + ) + cache.write_text("cache") + assert ( + overlay_launch._has_dependencies("scene", "metric", "uniform", "tracking", 32) + is True + ) + + +def test_has_dependencies_treats_missing_code_as_ineligible(monkeypatch): + def missing(*args): + raise FileNotFoundError("missing code") + + monkeypatch.setattr(overlay_launch.spatial_codes, "load_spatial_code", missing) + assert ( + overlay_launch._has_dependencies("scene", "metric", "uniform", "tracking", 32) + is False + ) + + +def test_launch_skips_missing_and_already_cached_without_pool( + monkeypatch, tmp_path, capsys +): + monkeypatch.setattr( + overlay_launch, + "_has_dependencies", + lambda scene, *args: scene != "missing", + ) + monkeypatch.setattr( + overlay_launch.overlay, + "overlay_frame_cache_dir", + lambda scene, *args: tmp_path / scene, + ) + monkeypatch.setattr( + overlay_launch.overlay, + "_load_cached_frames", + lambda cache_dir, frame_count: ( + ([object()], [[]]) if cache_dir.name == "cached" else None + ), + ) + monkeypatch.setattr( + overlay_launch.overlay, + "overlay_spatial_code_path", + lambda scene, *args: tmp_path / scene / "overlay-code.json", + ) + (tmp_path / "cached").mkdir() + (tmp_path / "cached" / "overlay-code.json").write_text("{}") + monkeypatch.setattr( + overlay_launch.mp, + "get_context", + lambda *_: pytest.fail("no pending scenes should avoid multiprocessing"), + ) + + succeeded, failed, missing = overlay_launch.launch( + "metric", "uniform", "tracking", 32, ["missing", "cached"] + ) + + assert succeeded == [] + assert failed == [] + assert missing == ["missing"] + output = capsys.readouterr().out + assert "missing a code or SAM3 cache" in output + assert "already cached" in output + + +def test_launch_does_not_skip_frames_cache_when_overlay_code_is_missing( + monkeypatch, tmp_path +): + monkeypatch.setattr(overlay_launch, "_has_dependencies", lambda scene, *args: True) + monkeypatch.setattr( + overlay_launch.overlay, + "overlay_frame_cache_dir", + lambda scene, *args: tmp_path / scene, + ) + monkeypatch.setattr( + overlay_launch.overlay, + "_load_cached_frames", + lambda cache_dir, frame_count: ([object()], [[]]), + ) + monkeypatch.setattr( + overlay_launch.overlay, + "overlay_spatial_code_path", + lambda scene, *args: tmp_path / scene / "missing-overlay-code.json", + ) + + calls = [] + + class FakePool: + def __init__(self, workers): + self.workers = workers + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def map(self, fn, tasks): + calls.extend(tasks) + return [(task[0], True, None) for task in tasks] + + class FakeContext: + def Pool(self, workers): + return FakePool(workers) + + monkeypatch.setattr(overlay_launch.mp, "get_context", lambda *_: FakeContext()) + + succeeded, failed, missing = overlay_launch.launch( + "metric", "uniform", "tracking", 32, ["frames_only"], workers=1 + ) + + assert calls == [("frames_only", "metric", "uniform", "tracking", 32)] + assert succeeded == ["frames_only"] + assert failed == [] + assert missing == [] 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/conftest.py b/tests/test_D/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..14a3272bdddc53337bcd1ed07dc1a360035d3bdc --- /dev/null +++ b/tests/test_D/conftest.py @@ -0,0 +1,45 @@ +"""Shared, self-contained import setup for harness.D tests.""" + +import os +from pathlib import Path +import sys +import tempfile +import types + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +# D imports the official VSI scorer eagerly. Provide a tiny interface-compatible scorer +# and manifest so unit tests do not depend on /root/data being mounted. +_FIXTURES = Path(tempfile.mkdtemp(prefix="test_D_")) +_SCORER = _FIXTURES / "utils.py" +_SCORER.write_text( + 'MCA_QUESTION_TYPES = ("object_rel_direction_easy", "object_rel_direction_medium", "object_rel_direction_hard", "object_rel_distance", "route_planning", "obj_appearance_order")\n' + 'NA_QUESTION_TYPES = ("object_abs_distance", "object_counting", "object_size_estimation", "room_size_estimation")\n' + 'METRICS_FOR_MCA = {"exact_match": None}\n' + 'METRICS_FOR_NA = {"MRA:.5:.95:.05": None}\n' + "def vsibench_process_results(doc, results):\n" + ' metric = "exact_match" if doc["question_type"] in MCA_QUESTION_TYPES else "MRA:.5:.95:.05"\n' + ' score = float(str(results[0]).strip() == str(doc["ground_truth"]).strip())\n' + ' return {"vsibench_score": {metric: score}}\n' +) +_MANIFEST = _FIXTURES / "test.jsonl" +_MANIFEST.write_text( + '{"id": 7, "scene_name": "13c3e046d7", "dataset": "scannet", "question_type": "object_counting", "question": "How many chairs?", "options": null, "ground_truth": "1"}\n' +) +os.environ["HARNESS_OFFICIAL_EVAL"] = str(_SCORER) +os.environ["SYMBOLIC_OFFICIAL_EVAL"] = str(_SCORER) +sys.path.insert(0, str(_FIXTURES)) +os.environ["VSI_JSONL"] = str(_MANIFEST) + +# OpenCV is only needed when the optional frame arm actually decodes a video. Frame +# unit tests monkeypatch that boundary and never call this placeholder. +if "cv2" not in sys.modules: + cv2 = types.ModuleType("cv2") + cv2.CAP_PROP_FPS = 5 + sys.modules["cv2"] = cv2 + + +def pytest_configure(config): + config.option.importmode = "importlib" diff --git a/tests/test_D/test_D.py b/tests/test_D/test_D.py new file mode 100644 index 0000000000000000000000000000000000000000..9989e0c2371219f148e0b57e9c1e0c7c5542d5c4 --- /dev/null +++ b/tests/test_D/test_D.py @@ -0,0 +1,21 @@ +"""Tests for harness/D/__init__.py -- shared config constants.""" + +from pathlib import Path + +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_root_results(): + assert D.RESULTS_DIR == Path("/root/results/D") 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..08f7a5419a82b2e2be3378a1cc2dbf910f863ff8 --- /dev/null +++ b/tests/test_D/test_launch.py @@ -0,0 +1,67 @@ +"""Tests for harness/D/launch.py -- multi-GPU scene sharding across workers.""" + +from harness.D import launch + + +def test_launcher_imports(): + assert callable(launch.main) + + +class _FakeRun: + rows = [{"id": 2}, {"id": 5}] + + @staticmethod + def results_dir_for(*args, **kwargs): + return args[3] + + @classmethod + def load_questions(cls, scene=None): + return list(cls.rows) + + +def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch): + scene = "scene-d" + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) + + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in _FakeRun.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 = "scene-d" + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in _FakeRun.rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + monkeypatch.setattr(launch, "visible_gpus", lambda: []) + monkeypatch.setattr( + launch.mp, + "get_context", + lambda *_: (_ for _ in ()).throw( + RuntimeError("rebuild correctly reached worker dispatch") + ), + ) + 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(monkeypatch): + monkeypatch.setattr("harness.A.launch.scenes", lambda: ["a", "b", "c"]) + monkeypatch.setattr(launch, "ground_truth_scenes", lambda: ["b", "c", "z"]) + assert launch.scenes() == ["b", "c"] diff --git a/tests/test_D/test_prompts.py b/tests/test_D/test_prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..53ac352315b71bd29d86dc1bf39345149d0cc08b --- /dev/null +++ b/tests/test_D/test_prompts.py @@ -0,0 +1,55 @@ +"""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..5b958de017e2594e13a06954fd9703a340ce3f77 --- /dev/null +++ b/tests/test_D/test_run.py @@ -0,0 +1,246 @@ +"""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 = { + "protocol": "extended", + "spatial_code_format": "explicit", + "spatial_code_path": "/workspace/data/spatial codes/ground truth/explicit/scene0001_00.json", +} + + +def test_results_dir_for_matches_model_protocol_and_format_only(): + root = harness_run.results_dir_for("qwen3.5-4b", "extended", "compact") + assert root == D.RESULTS_DIR / "qwen3.5-4b" / "code" / "extended" / "compact" + + +def test_results_dir_for_isolates_frames_and_truncated_budget_arms(): + root = harness_run.results_dir_for( + "qwen3.5-4b", + "truncated/64", + "explicit", + frames=True, + frame_selection="uniform", + frame_count=32, + ) + assert root == ( + D.RESULTS_DIR + / "qwen3.5-4b" + / "code + frames" + / "truncated" + / "64" + / "explicit" + / "uniform" + / "32" + ) + + +def test_build_record_describes_frames_plus_ground_truth_condition(): + code_info = { + **_FAKE_CODE_INFO, + "protocol": "512", + "frames": True, + "frame_selection": "uniform", + "frame_count": 32, + "video_path": "/fake/scene.mp4", + "frame_indices": [0, 30], + "frame_timestamps": [0.0, 1.0], + } + 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", + code_info, + ) + assert record["condition"] == "512:explicit:frames:uniform:32" + assert record["frames"] is True + assert record["video_path"] == "/fake/scene.mp4" + assert record["frame_indices"] == [0, 30] + assert record["frame_timestamps_seconds"] == [0.0, 1.0] + + +def test_results_dir_for_honors_explicit_override(tmp_path): + root = harness_run.results_dir_for("qwen3.5-4b", "base", "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 -- ground truth has no such axis. frames/ + # frame_selection/frame_count/video_path/frame_indices/frame_timestamps_seconds DO + # exist on every record (the frames+ground-truth-code arm's fields), null here since + # _FAKE_CODE_INFO has no "frames" key -- same present-but-null pattern as + # reasoning_text on a base-protocol record. + assert record["condition"] == "extended:explicit" + assert record["protocol"] == "extended" + assert record["frames"] is False + assert record["frame_selection"] is None + assert record["frame_count"] is None + assert record["video_path"] is None + assert "input_selection" 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 + + +def test_run_code_transform_hook_replaces_the_loaded_code(monkeypatch, tmp_path): + """The corruption module's entry point: the hook's return value is what the + prompt is built from, and passing no hook keeps behavior identical.""" + scene = "13c3e046d7" + seen = {} + + def fake_load(scene_id, spatial_code_format): + return {"objects": {"chair": {"count": 1}}}, f"/fake/{scene_id}.json" + + class FakeAdapter: + model_path = "/fake/model" + + def answer_extended(self, frames, prompt, **kwargs): + seen["prompt"] = prompt + return { + "prompt_text": prompt, + "answer_text": "1", + "answer_raw": "1", + "input_token_count": 1, + "vision_input_shapes": {}, + "output_token_ids": [1], + "output_token_count": 1, + "hit_token_limit": False, + "eos_token_ids": [1], + "generation_seconds": 0.0, + "device": "cpu", + "dtype": "float32", + "library_versions": {}, + "generation_config": {}, + } + + monkeypatch.setattr(harness_run.spatial_codes, "load_spatial_code", fake_load) + replacement = {"objects": {"table": {"count": 9}}} + results = harness_run.run( + "qwen3.5-2b", + scene=scene, + adapter=FakeAdapter(), + write_results=False, + limit=1, + code_transform=lambda code, scene_id, fmt: replacement, + ) + assert results + assert '"table"' in seen["prompt"] + assert '"chair"' not in seen["prompt"] diff --git a/tests/test_D/test_spatial_codes.py b/tests/test_D/test_spatial_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..7bfe4b9759c034727417933f4d25e97c96c4e15a --- /dev/null +++ b/tests/test_D/test_spatial_codes.py @@ -0,0 +1,33 @@ +"""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..39e8c19b0c05bfe224c2d413a67a20c70b210358 --- /dev/null +++ b/tests/test_D/test_symbolic_eval.py @@ -0,0 +1,116 @@ +"""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_E/__init__.py b/tests/test_E/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_E/conftest.py b/tests/test_E/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..8a801f94b60da603c80287f186e31c5d32012e99 --- /dev/null +++ b/tests/test_E/conftest.py @@ -0,0 +1,12 @@ +"""Shared import setup for this test package.""" + +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_E/test_E.py b/tests/test_E/test_E.py new file mode 100644 index 0000000000000000000000000000000000000000..3656a84bdfd3a36926b95730ad130fa769650a9b --- /dev/null +++ b/tests/test_E/test_E.py @@ -0,0 +1,20 @@ +"""Tests for harness/E package configuration.""" + +import importlib +from pathlib import Path + +from harness import E + + +def test_blind_floor_reuses_harness_a_public_config(): + assert E.PROTOCOLS == ("base", "extended") + assert "qwen3.5-2b" in E.MODEL_PATHS + assert E.RESULTS_DIR == Path("/root/results/E") + + +def test_results_dir_can_be_overridden_by_environment(monkeypatch, tmp_path): + monkeypatch.setenv("VSI_HARNESS_E_RESULTS_DIR", str(tmp_path / "E")) + reloaded = importlib.reload(E) + assert reloaded.RESULTS_DIR == tmp_path / "E" + monkeypatch.delenv("VSI_HARNESS_E_RESULTS_DIR") + importlib.reload(E) diff --git a/tests/test_E/test_launch.py b/tests/test_E/test_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..8879c92358f669bf9bd6d3e81bd77cc5299dd2da --- /dev/null +++ b/tests/test_E/test_launch.py @@ -0,0 +1,66 @@ +"""Tests for harness/E/launch.py -- multi-GPU scene sharding for the blind floor.""" + +from harness.E import launch + + +def test_launcher_imports(): + assert callable(launch.main) + + +class _FakeRun: + rows = [{"id": 4}, {"id": 9}] + + @staticmethod + def results_dir_for(model, protocol, results_dir=None): + return results_dir + + @classmethod + def load_questions(cls, scene=None): + return list(cls.rows) + + +def test_launch_skips_scene_already_fully_answered(tmp_path, capsys, monkeypatch): + scene = "scene-e" + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) + + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in _FakeRun.rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + launch.launch("qwen3.5-2b", [scene], results_dir=tmp_path) + + output = capsys.readouterr().out + assert "skipped" in output + assert "DONE: 1 ok, 0 failed" in output + + +def test_launch_rebuild_forces_pending_even_when_answered(tmp_path, monkeypatch): + scene = "scene-e" + monkeypatch.setattr(launch, "_load_run_module", lambda: _FakeRun) + scene_dir = tmp_path / scene + scene_dir.mkdir() + for row in _FakeRun.rows: + (scene_dir / f"{row['id']}.json").write_text("{}") + + monkeypatch.setattr(launch, "visible_gpus", lambda: []) + monkeypatch.setattr( + launch.mp, + "get_context", + lambda *_: (_ for _ in ()).throw( + RuntimeError("rebuild correctly reached worker dispatch") + ), + ) + try: + launch.launch("qwen3.5-2b", [scene], results_dir=tmp_path, rebuild=True) + except RuntimeError as exc: + assert "rebuild correctly reached worker dispatch" in str(exc) + else: + raise AssertionError("expected rebuild to force scene into the pending path") + + +def test_launch_protocols_use_separate_result_roots(): + run = launch._load_run_module() + base = run.results_dir_for("qwen3.5-2b", "base") + extended = run.results_dir_for("qwen3.5-2b", "extended") + assert base != extended diff --git a/tests/test_E/test_prompts.py b/tests/test_E/test_prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..41570afc460258064e85f423d6ec42294562c43d --- /dev/null +++ b/tests/test_E/test_prompts.py @@ -0,0 +1,48 @@ +"""Tests for harness/E/prompts.py -- blind question-only prompt construction.""" + +import pytest + +from harness.A.prompts import MCA_QUESTION_TYPES, NA_QUESTION_TYPES +from harness.E import prompts as blind_prompts + + +def test_na_question_prompt_is_question_plus_post_prompt_only(): + prompt = blind_prompts.build_prompt("object_counting", "How many chairs?") + assert prompt == "How many chairs?\n" + blind_prompts.NA_POST_PROMPT + + +def test_mca_question_prompt_includes_options_and_post_prompt(): + prompt = blind_prompts.build_prompt( + "object_rel_distance", "Which is closest?", ["A. sofa", "B. table"] + ) + assert "Options:\nA. sofa\nB. table" in prompt + assert prompt.endswith(blind_prompts.MCA_POST_PROMPT) + + +def test_no_scene_language_anywhere(): + # Blind means blind: no context line claiming frames, video, or a spatial code. + prompt = blind_prompts.build_prompt("object_counting", "How many chairs?") + lowered = prompt.lower() + assert "frame" not in lowered + assert "video" not in lowered + assert "spatial code" not in lowered + + +def test_mca_question_requires_options(): + with pytest.raises(ValueError): + blind_prompts.build_prompt("route_planning", "Which way?", None) + + +def test_unknown_question_type_rejected(): + with pytest.raises(ValueError): + blind_prompts.build_prompt("not_a_real_type", "?", None) + + +@pytest.mark.parametrize("question_type", NA_QUESTION_TYPES) +def test_every_na_question_type_builds(question_type): + assert blind_prompts.build_prompt(question_type, "q?") + + +@pytest.mark.parametrize("question_type", MCA_QUESTION_TYPES) +def test_every_mca_question_type_builds(question_type): + assert blind_prompts.build_prompt(question_type, "q?", ["A. x", "B. y"]) diff --git a/tests/test_E/test_run.py b/tests/test_E/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..8452b467d423715a3c6ad703eb39aea760bb87b3 --- /dev/null +++ b/tests/test_E/test_run.py @@ -0,0 +1,97 @@ +"""Tests for harness/E/run.py -- result-record shape and result-file writing.""" + +import json + +from harness import E +from harness.E import run as harness_run + +_FAKE_ANSWER = { + "prompt_text": "", + "answer_text": "4", + "answer_raw": "<|im_start|>assistant\n4<|im_end|>", + "input_token_count": 42, + "vision_input_shapes": {}, + "output_token_ids": [19, 151645], + "output_token_count": 2, + "hit_token_limit": False, + "eos_token_ids": [151645], + "generation_seconds": 0.2, + "device": "cuda", + "dtype": "bfloat16", + "library_versions": {"transformers": "5.14.1", "torch": "2.13.0+cu130"}, + "generation_config": { + "max_new_tokens": 16, + "do_sample": False, + "temperature": 0.0, + "top_p": None, + "top_k": None, + "enable_thinking": False, + }, +} + +_FAKE_ROW = { + "id": 7, + "scene_name": "scene0001_00", + "dataset": "scannet", + "question_type": "object_counting", + "question": "How many chairs?", + "options": None, + "ground_truth": "4", +} + + +def test_results_dir_for_matches_model_and_protocol_only(): + root = harness_run.results_dir_for("qwen3.5-4b", "base") + assert root == E.RESULTS_DIR / "qwen3.5-4b" / "base" + + +def test_results_dir_for_isolates_the_two_protocols(): + assert harness_run.results_dir_for( + "qwen3.5-4b", "base" + ) != harness_run.results_dir_for("qwen3.5-4b", "extended") + + +def test_results_dir_for_honors_explicit_override(tmp_path): + assert harness_run.results_dir_for("qwen3.5-4b", "base", tmp_path) == tmp_path + + +def test_build_record_has_no_scene_input_provenance(): + record = harness_run._build_record( + _FAKE_ROW, + "full prompt text", + _FAKE_ANSWER, + "MRA:.5:.95:.05", + 1.0, + "qwen3.5-4b", + "/root/models/qwen3.5-4b", + "base", + ) + assert record["condition"] == "base" + assert record["protocol"] == "base" + assert record["question"] == "How many chairs?" + assert record["answer_given"] == "4" + assert record["metric"] == "MRA:.5:.95:.05" + assert record["score"] == 1.0 + # Blind: no frame or spatial-code provenance of any kind. + assert "frame_selection" not in record + assert "video_path" not in record + assert "frame_indices" not in record + assert "spatial_code_format" not in record + assert "spatial_code_path" not in record + + +def test_write_question_result_writes_one_json_file_per_question(tmp_path): + path, record = harness_run.write_question_result( + _FAKE_ROW, + "full prompt text", + _FAKE_ANSWER, + "MRA:.5:.95:.05", + 1.0, + "qwen3.5-4b", + "/root/models/qwen3.5-4b", + "base", + results_dir=tmp_path, + ) + assert path == tmp_path / "scene0001_00" / "7.json" + on_disk = json.loads(path.read_text()) + assert on_disk == record diff --git a/tests/test_E/test_sweep.py b/tests/test_E/test_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..14ea803121f66e56d137c3378e939a1f9514139b --- /dev/null +++ b/tests/test_E/test_sweep.py @@ -0,0 +1,40 @@ +"""Tests for harness/E/sweep.py -- per-model blind-floor sweeping.""" + +import pytest + +from harness.E import sweep + + +def test_sweep_imports(): + assert callable(sweep.main) + + +def test_sweep_runs_every_model_through_launch(monkeypatch): + launched = [] + monkeypatch.setattr( + sweep.harness_launch, + "launch", + lambda model, scenes, **kwargs: launched.append( + (model, kwargs.get("extended")) + ), + ) + sweep.sweep(["qwen3.5-2b", "qwen3.5-4b"], ["scene_a"], extended=True) + assert launched == [("qwen3.5-2b", True), ("qwen3.5-4b", True)] + + +def test_sweep_defaults_to_base_protocol(monkeypatch): + launched = [] + monkeypatch.setattr( + sweep.harness_launch, + "launch", + lambda model, scenes, **kwargs: launched.append(kwargs.get("extended")), + ) + sweep.sweep(["qwen3.5-2b"], ["scene_a"]) + assert launched == [False] + + +def test_sweep_parser_rejects_unknown_model(monkeypatch, capsys): + monkeypatch.setattr("sys.argv", ["sweep", "--models", "not-a-model"]) + with pytest.raises(SystemExit): + sweep.main() + assert "unknown" in capsys.readouterr().err diff --git a/tests/test_analysis/test_D_reports.py b/tests/test_analysis/test_D_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..6fd57e3dadf66c863bee1cabf963e4c02b925dc1 --- /dev/null +++ b/tests/test_analysis/test_D_reports.py @@ -0,0 +1,13 @@ +from tests.test_analysis.conftest import ReportTestCase, vlm +from analysis import D_reports + + +class TestDReports(ReportTestCase): + def test_D_report_is_ground_truth_code_report(self): + result = D_reports.generate( + self.directory("D", [vlm("D")]), ["base"], self.root / "reports" + ) + self.assertEqual(result["path"].name, "D_report.json") + self.assertEqual( + result["report"]["manifest"]["profile"]["input_source"], "ground_truth" + ) diff --git a/tests/test_calibration/__init__.py b/tests/test_calibration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_calibration/conftest.py b/tests/test_calibration/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..8a801f94b60da603c80287f186e31c5d32012e99 --- /dev/null +++ b/tests/test_calibration/conftest.py @@ -0,0 +1,12 @@ +"""Shared import setup for this test package.""" + +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_calibration/test_calibration.py b/tests/test_calibration/test_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..0f8fa86b6a7f93f7661ae8fb9965fda2e4ec4b44 --- /dev/null +++ b/tests/test_calibration/test_calibration.py @@ -0,0 +1,18 @@ +"""Tests for calibration package configuration.""" + +import importlib +from pathlib import Path + +import calibration + + +def test_results_dir_defaults_to_root_results(): + assert calibration.RESULTS_DIR == Path("/root/results/calibration") + + +def test_results_dir_can_be_overridden_by_environment(monkeypatch, tmp_path): + monkeypatch.setenv("VSI_CALIBRATION_RESULTS_DIR", str(tmp_path / "calibration")) + reloaded = importlib.reload(calibration) + assert reloaded.RESULTS_DIR == tmp_path / "calibration" + monkeypatch.delenv("VSI_CALIBRATION_RESULTS_DIR") + importlib.reload(calibration) diff --git a/tests/test_calibration/test_report.py b/tests/test_calibration/test_report.py new file mode 100644 index 0000000000000000000000000000000000000000..63f7a89adeb3de1a5691b4eca3a4f787486eb1ce --- /dev/null +++ b/tests/test_calibration/test_report.py @@ -0,0 +1,140 @@ +"""Tests for calibration/report.py -- budget stats and the recommendation rule.""" + +import json + +from calibration import report as calibration_report + + +def _record(question_id, score, forced=False, reasoning_tokens=100, seconds=1.0): + return { + "question_id": question_id, + "question_type": "object_counting", + "answer_expected": "4", + "metric": "MRA:.5:.95:.05", + "score": score, + "forced": forced, + "reasoning_token_count": reasoning_tokens, + "generation_seconds": seconds, + } + + +def test_cell_stats_counts_forced_and_natural_lengths(): + stats = calibration_report.cell_stats( + [ + _record(1, 1.0, forced=False, reasoning_tokens=50), + _record(2, 0.0, forced=True, reasoning_tokens=512), + ] + ) + assert stats["count"] == 2 + assert stats["forced_rate"] == 0.5 + # Forced records are excluded from the natural-stop length mean. + assert stats["natural_reasoning_tokens_mean"] == 50 + + +def test_report_scores_only_the_shared_question_intersection(): + grid = { + "m": { + 256: {1: _record(1, 0.0), 2: _record(2, 1.0)}, + 512: {1: _record(1, 1.0)}, # never answered q2 + } + } + result = calibration_report.report(grid) + assert result["m"]["questions"] == 1 + assert result["m"]["budgets"][256]["count"] == 1 + + +def test_recommendation_picks_smallest_saturated_low_forced_budget(): + grid = { + "m": { + 256: {1: _record(1, 0.0, forced=True)}, + 512: {1: _record(1, 1.0, forced=False)}, + 2048: {1: _record(1, 1.0, forced=False)}, + } + } + result = calibration_report.report(grid, tolerance=1.0, max_forced_rate=0.15) + assert result["m"]["recommended"] == 512 + + +def test_recommendation_rejects_high_forced_rate_even_at_best_accuracy(): + grid = { + "m": { + 256: {1: _record(1, 1.0, forced=True)}, # accurate but 100% forced + 1024: {1: _record(1, 1.0, forced=False)}, + } + } + result = calibration_report.report(grid, max_forced_rate=0.15) + assert result["m"]["recommended"] == 1024 + + +def test_load_grid_reads_the_full_config_layout(tmp_path): + cell = ( + tmp_path + / "qwen3.5-2b" + / "explicit" + / "metric" + / "tracking" + / "selective" + / "64" + / "512" + / "scene_a" + ) + cell.mkdir(parents=True) + (cell / "7.json").write_text(json.dumps(_record(7, 1.0))) + grid = calibration_report.load_grid(tmp_path) + assert grid == { + "qwen3.5-2b/explicit/metric/tracking/selective/64": { + "512": {7: json.loads((cell / "7.json").read_text())} + } + } + + +def test_load_grid_does_not_mistake_frame_count_dirs_for_budgets(tmp_path): + # The "64" frame-count level is numeric too -- only the budget leaf (whose + # children are scene folders with JSONs) may be treated as a budget. + cell = ( + tmp_path + / "qwen3.5-2b" + / "explicit" + / "metric" + / "tracking" + / "selective" + / "64" + / "512" + / "scene_a" + ) + cell.mkdir(parents=True) + (cell / "7.json").write_text(json.dumps(_record(7, 1.0))) + grid = calibration_report.load_grid(tmp_path) + assert list(grid) == ["qwen3.5-2b/explicit/metric/tracking/selective/64"] + assert list(grid["qwen3.5-2b/explicit/metric/tracking/selective/64"]) == ["512"] + + +def test_load_grid_includes_variant_budget_directories(tmp_path): + cell = ( + tmp_path + / "qwen3.5-2b" + / "explicit" + / "metric" + / "tracking" + / "selective" + / "64" + / "512-prose-legend" + / "scene_a" + ) + cell.mkdir(parents=True) + (cell / "7.json").write_text(json.dumps(_record(7, 1.0))) + grid = calibration_report.load_grid(tmp_path) + assert list(grid["qwen3.5-2b/explicit/metric/tracking/selective/64"]) == [ + "512-prose-legend" + ] + + +def test_variant_rows_are_never_recommended(): + grid = { + "m": { + "512": {1: _record(1, 0.5)}, + "512-prose-legend": {1: _record(1, 1.0)}, + } + } + result = calibration_report.report(grid) + assert result["m"]["recommended"] == "512" diff --git a/tests/test_calibration/test_run.py b/tests/test_calibration/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..66087deeeb524fc8d8e1a2d80577eaae36ab2d73 --- /dev/null +++ b/tests/test_calibration/test_run.py @@ -0,0 +1,130 @@ +"""Tests for calibration/run.py -- operator-specified budget-grid orchestration.""" + +import pytest + +from calibration import run as calibration_run + + +def test_results_dir_isolates_every_pilot_axis(): + base = ("qwen3.5-4b", "explicit", "metric", "tracking", "selective", 32, 512) + variants = {calibration_run.results_dir_for(*base)} + for index, value in [ + (0, "qwen3.5-2b"), + (1, "compact"), + (2, "relative"), + (3, "no tracking"), + (4, "uniform"), + (5, 64), + (6, 1024), + ]: + changed = list(base) + changed[index] = value + variants.add(calibration_run.results_dir_for(*changed)) + assert len(variants) == 8 + + +def test_build_plan_orders_cheapest_budget_first(): + plan = calibration_run.build_plan(["m1", "m2"], [2048, 256]) + assert plan == [("m1", 256), ("m2", 256), ("m1", 2048), ("m2", 2048)] + + +def test_scenes_for_derives_scenes_and_rejects_unknown_ids(monkeypatch): + rows = [ + {"id": 1, "scene_name": "scene_a"}, + {"id": 2, "scene_name": "scene_b"}, + {"id": 3, "scene_name": "scene_a"}, + ] + monkeypatch.setattr(calibration_run, "load_questions", lambda: list(rows)) + assert calibration_run.scenes_for({1, 2, 3}) == ["scene_a", "scene_b"] + with pytest.raises(ValueError): + calibration_run.scenes_for({1, 999}) + + +def test_run_grid_passes_budget_questions_and_isolated_dir(monkeypatch): + launched = [] + monkeypatch.setattr(calibration_run, "scenes_for", lambda ids: ["scene_a"]) + monkeypatch.setattr( + calibration_run.harness_b_launch, + "launch", + lambda model, fmt, sel, frames, scenes, **kwargs: launched.append( + ( + model, + fmt, + kwargs["reasoning_budget"], + str(kwargs["results_dir"]), + kwargs["question_ids"], + scenes, + ) + ), + ) + calibration_run.run_grid( + ["qwen3.5-2b"], + [256, 512], + [1, 2], + "compact", + "metric", + "tracking", + "selective", + 64, + ) + assert [(m, f, b) for m, f, b, _, _, _ in launched] == [ + ("qwen3.5-2b", "compact", 256), + ("qwen3.5-2b", "compact", 512), + ] + assert launched[0][3] != launched[1][3] + assert launched[0][4] == {1, 2} + assert launched[0][5] == ["scene_a"] + + +def test_cli_requires_exactly_one_question_source(monkeypatch, capsys): + monkeypatch.setattr( + "sys.argv", + [ + "run", + "--models", + "qwen3.5-2b", + "--budgets", + "256", + "--spatial-code-format", + "explicit", + "--depth", + "metric", + "--tracking", + "tracking", + "--input-selection", + "selective", + "--frames", + "32", + ], + ) + with pytest.raises(SystemExit): + calibration_run.main() + assert "exactly one of" in capsys.readouterr().err + + +def test_cli_rejects_nonpositive_budget(monkeypatch, capsys): + monkeypatch.setattr( + "sys.argv", + [ + "run", + "--models", + "qwen3.5-2b", + "--budgets", + "0", + "--questions", + "1", + "--spatial-code-format", + "explicit", + "--depth", + "metric", + "--tracking", + "tracking", + "--input-selection", + "selective", + "--frames", + "32", + ], + ) + with pytest.raises(SystemExit): + calibration_run.main() + assert "must be positive" in capsys.readouterr().err diff --git a/tests/test_corruption/__init__.py b/tests/test_corruption/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_corruption/conftest.py b/tests/test_corruption/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..8a801f94b60da603c80287f186e31c5d32012e99 --- /dev/null +++ b/tests/test_corruption/conftest.py @@ -0,0 +1,12 @@ +"""Shared import setup for this test package.""" + +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_corruption/test_chimera.py b/tests/test_corruption/test_chimera.py new file mode 100644 index 0000000000000000000000000000000000000000..6cab03969a07548dd79096173bc70a44cc6128f0 --- /dev/null +++ b/tests/test_corruption/test_chimera.py @@ -0,0 +1,96 @@ +"""Tests for corruption/chimera.py -- hybrid codes and the single-object probe.""" + +import random + +from corruption import chimera + + +def _instance(x, y, dims=(1.0, 1.0, 1.0), time=0.0): + return { + "3D oriented bounding box": { + "3D oriented bounding box center coordinates": [x, y, 0.5], + "3D oriented bounding box dimensions": list(dims), + "3D oriented bounding box orientation unit vectors": [ + [1.0, 0.0, 0.0], + [0.0, 0.0, 1.0], + [0.0, -1.0, 0.0], + ], + }, + "first visible time": time, + } + + +def _code(objects): + return { + "spatial code schema": {}, + "objects": objects, + "room": {"floor boundary polygons": []}, + } + + +def test_gt_inventory_keeps_gt_counts_but_takes_perceived_boxes(): + gt = _code({"chair": [_instance(0.0, 0.0), _instance(5.0, 5.0)]}) + perceived = _code({"chair": [_instance(0.3, 0.1, dims=(9.0, 9.0, 9.0))]}) + hybrid, coverage = chimera.gt_inventory_perceived_geometry(gt, perceived) + # GT count preserved (2 chairs), nearest GT instance got the perceived box. + assert len(hybrid["objects"]["chair"]) == 2 + assert coverage == {"instances": 2, "swapped": 1} + boxes = [ + item["3D oriented bounding box"]["3D oriented bounding box dimensions"] + for item in hybrid["objects"]["chair"] + ] + assert [9.0, 9.0, 9.0] in boxes + + +def test_perceived_inventory_keeps_perceived_counts_but_takes_gt_boxes(): + gt = _code({"chair": [_instance(0.0, 0.0, dims=(2.0, 2.0, 2.0))]}) + perceived = _code( + { + "chair": [_instance(0.4, 0.0), _instance(8.0, 8.0)], + "ghost": [_instance(1.0, 1.0)], + } + ) + hybrid, coverage = chimera.perceived_inventory_gt_geometry(gt, perceived) + # Perceived inventory preserved: 2 chairs + the hallucinated "ghost" class. + assert len(hybrid["objects"]["chair"]) == 2 + assert "ghost" in hybrid["objects"] + assert coverage["swapped"] == 1 # only one GT chair box available to give out + boxes = [ + item["3D oriented bounding box"]["3D oriented bounding box dimensions"] + for item in hybrid["objects"]["chair"] + ] + assert [2.0, 2.0, 2.0] in boxes + + +def test_chimeras_do_not_mutate_inputs(): + gt = _code({"chair": [_instance(0.0, 0.0)]}) + perceived = _code({"chair": [_instance(1.0, 1.0)]}) + frozen_gt, frozen_perceived = str(gt), str(perceived) + chimera.gt_inventory_perceived_geometry(gt, perceived) + chimera.perceived_inventory_gt_geometry(gt, perceived) + assert str(gt) == frozen_gt + assert str(perceived) == frozen_perceived + + +def test_perturb_single_object_changes_exactly_one_instance(): + code = _code( + { + "chair": [_instance(0.0, 0.0), _instance(5.0, 5.0)], + "table": [_instance(2.0, 2.0)], + } + ) + out, info = chimera.perturb_single_object(code, random.Random(0)) + changed = 0 + for name in code["objects"]: + for before, after in zip(code["objects"][name], out["objects"][name]): + if before != after: + changed += 1 + assert changed == 1 + assert info["class"] in code["objects"] + + +def test_perturb_single_object_empty_code_is_a_noop(): + code = _code({}) + out, info = chimera.perturb_single_object(code, random.Random(0)) + assert out == code + assert info is None diff --git a/tests/test_corruption/test_corruption.py b/tests/test_corruption/test_corruption.py new file mode 100644 index 0000000000000000000000000000000000000000..55573a76f5e670440ec7182c5b89deb5af998d94 --- /dev/null +++ b/tests/test_corruption/test_corruption.py @@ -0,0 +1,19 @@ +"""Tests for corruption package configuration.""" + +import importlib +from pathlib import Path + +import corruption + + +def test_corruption_defaults_are_explicit(): + assert corruption.RESULTS_DIR == Path("/root/results/corruption") + assert corruption.SAMPLE_SEED == 20260725 + + +def test_results_dir_can_be_overridden_by_environment(monkeypatch, tmp_path): + monkeypatch.setenv("VSI_CORRUPTION_RESULTS_DIR", str(tmp_path / "corruption")) + reloaded = importlib.reload(corruption) + assert reloaded.RESULTS_DIR == tmp_path / "corruption" + monkeypatch.delenv("VSI_CORRUPTION_RESULTS_DIR") + importlib.reload(corruption) diff --git a/tests/test_corruption/test_empirical.py b/tests/test_corruption/test_empirical.py new file mode 100644 index 0000000000000000000000000000000000000000..b8526352da1210c304cd6ba81a358790f115441f --- /dev/null +++ b/tests/test_corruption/test_empirical.py @@ -0,0 +1,96 @@ +"""Tests for corruption/empirical.py -- measured residuals and empirical noise.""" + +import random + +from corruption import empirical + + +def _instance(x, y, dims=(1.0, 1.0, 1.0)): + return { + "3D oriented bounding box": { + "3D oriented bounding box center coordinates": [x, y, 0.5], + "3D oriented bounding box dimensions": list(dims), + "3D oriented bounding box orientation unit vectors": [ + [1.0, 0.0, 0.0], + [0.0, 0.0, 1.0], + [0.0, -1.0, 0.0], + ], + }, + "first visible time": 0.0, + } + + +def _code(objects): + return { + "spatial code schema": {}, + "objects": objects, + "room": {"floor boundary polygons": []}, + } + + +def test_measure_residuals_matches_missed_and_hallucinated(): + gt = _code({"chair": [_instance(0.0, 0.0), _instance(5.0, 5.0)]}) + perceived = _code( + {"chair": [_instance(0.5, 0.0)], "phantom": [_instance(9.0, 9.0)]} + ) + residuals = empirical.measure_residuals([(perceived, gt)]) + assert residuals["matched"] == 1 + assert residuals["missed"] == 1 # second GT chair unmatched + assert residuals["hallucinated"] == 1 # the phantom class + assert residuals["miss_rate"] == 0.5 + assert residuals["position_residuals"] == [[0.5, 0.0, 0.0]] + + +def test_measure_residuals_dimension_ratios(): + gt = _code({"chair": [_instance(0.0, 0.0, dims=(2.0, 2.0, 2.0))]}) + perceived = _code({"chair": [_instance(0.0, 0.0, dims=(1.0, 3.0, 2.0))]}) + residuals = empirical.measure_residuals([(perceived, gt)]) + assert residuals["dimension_ratios"] == [[0.5, 1.5, 1.0]] + + +def test_empirical_noise_at_zero_scale_is_identity(): + code = _code({"chair": [_instance(1.0, 1.0)]}) + residuals = { + "position_residuals": [[0.5, 0.5, 0.0]], + "dimension_ratios": [[2.0, 2.0, 2.0]], + "matched": 1, + "missed": 1, + "hallucinated": 1, + "miss_rate": 0.5, + "hallucination_rate": 0.5, + } + out = empirical.empirical_noise(code, residuals, random.Random(0), scale=0.0) + assert out == code + + +def test_empirical_noise_applies_sampled_residuals(): + code = _code({"chair": [_instance(1.0, 1.0)]}) + residuals = { + "position_residuals": [[0.5, -0.5, 0.0]], + "dimension_ratios": [[2.0, 1.0, 1.0]], + "matched": 1, + "missed": 0, + "hallucinated": 0, + "miss_rate": 0.0, + "hallucination_rate": 0.0, + } + out = empirical.empirical_noise(code, residuals, random.Random(0), scale=1.0) + box = out["objects"]["chair"][0]["3D oriented bounding box"] + assert box["3D oriented bounding box center coordinates"] == [1.5, 0.5, 0.5] + assert box["3D oriented bounding box dimensions"] == [2.0, 1.0, 1.0] + + +def test_empirical_noise_is_reproducible(): + code = _code({"chair": [_instance(1.0, 1.0), _instance(3.0, 3.0)]}) + residuals = { + "position_residuals": [[0.5, 0.0, 0.0], [-0.2, 0.1, 0.0]], + "dimension_ratios": [[1.1, 0.9, 1.0]], + "matched": 2, + "missed": 1, + "hallucinated": 1, + "miss_rate": 0.3, + "hallucination_rate": 0.3, + } + first = empirical.empirical_noise(code, residuals, random.Random(7)) + second = empirical.empirical_noise(code, residuals, random.Random(7)) + assert first == second diff --git a/tests/test_corruption/test_launch.py b/tests/test_corruption/test_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..4bba8040e41bf38050f554ac2db568b814715e9d --- /dev/null +++ b/tests/test_corruption/test_launch.py @@ -0,0 +1,68 @@ +"""Tests for corruption/launch.py -- grid looping over conditions.""" + +import pytest + +from corruption import launch + + +def test_launch_imports(): + assert callable(launch.main) + + +def test_launch_rejects_unknown_transform(monkeypatch, capsys): + monkeypatch.setattr( + "sys.argv", + [ + "launch", + "--transforms", + "not-a-transform", + "--magnitudes", + "0.5", + "--arm", + "solver", + ], + ) + with pytest.raises(SystemExit): + launch.main() + assert "unknown transform" in capsys.readouterr().err + + +def test_launch_vlm_arm_requires_models(monkeypatch, capsys): + monkeypatch.setattr( + "sys.argv", + ["launch", "--transforms", "translate", "--magnitudes", "10", "--arm", "vlm"], + ) + with pytest.raises(SystemExit): + launch.main() + assert "requires --models" in capsys.readouterr().err + + +def test_launch_runs_the_full_grid_through_run_solver(monkeypatch): + conditions = [] + monkeypatch.setattr( + launch, + "run_solver", + lambda transform, magnitude, fmt, **kwargs: conditions.append( + (transform, magnitude) + ) + or [], + ) + monkeypatch.setattr( + "sys.argv", + [ + "launch", + "--arm", + "solver", + "--transforms", + "translate,rotate-z", + "--magnitudes", + "10,90", + ], + ) + launch.main() + assert conditions == [ + ("translate", 10.0), + ("translate", 90.0), + ("rotate-z", 10.0), + ("rotate-z", 90.0), + ] diff --git a/tests/test_corruption/test_run.py b/tests/test_corruption/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..cefe176074934ca4f277145341195a5536504835 --- /dev/null +++ b/tests/test_corruption/test_run.py @@ -0,0 +1,220 @@ +"""Tests for corruption/run.py -- condition orchestration, determinism, and certification.""" + +import copy + +import pytest + +from corruption import run as corruption_run +from encoder.geometric import _explicit_from_compact + +_SCENE = "13c3e046d7" +_OTHER_SCENE = "09c1414f1b" + + +def _box(x, y, z=0.5, dims=(1.0, 1.0, 1.0)): + return { + "3D oriented bounding box center coordinates": [x, y, z], + "3D oriented bounding box dimensions": list(dims), + "3D oriented bounding box orientation unit vectors": [ + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + ], + } + + +def _compact(offset=0.0): + return { + "spatial code schema": {}, + "objects": { + "chair": [ + { + "3D oriented bounding box": _box(offset, 0.0), + "first visible time": 0.0, + } + ], + "table": [ + { + "3D oriented bounding box": _box(offset + 3.0, 0.0), + "first visible time": 1.0, + } + ], + }, + "room": { + "floor boundary polygons": [ + { + "outer boundary coordinates": [ + [-2.0, -2.0], + [5.0, -2.0], + [5.0, 2.0], + [-2.0, 2.0], + ], + "interior hole boundary coordinates": [], + } + ] + }, + } + + +@pytest.fixture(autouse=True) +def self_contained_ground_truth(monkeypatch): + codes = {_SCENE: _compact(), _OTHER_SCENE: _compact(offset=10.0)} + + def load_compact(scene): + return copy.deepcopy(codes[scene]) + + def load_spatial_code(scene, spatial_code_format): + compact = load_compact(scene) + if spatial_code_format == "compact": + return compact, f"/fixture/{scene}.json" + if spatial_code_format == "explicit": + explicit, _floor_area = _explicit_from_compact(compact) + return explicit, f"/fixture/{scene}.json" + raise ValueError(spatial_code_format) + + monkeypatch.setattr(corruption_run, "load_ground_truth_compact", load_compact) + monkeypatch.setattr( + corruption_run.gt_spatial_codes, "load_spatial_code", load_spatial_code + ) + + +def test_seed_is_deterministic_and_condition_specific(): + first = corruption_run._seed_for(_SCENE, "position-jitter", 0.25) + second = corruption_run._seed_for(_SCENE, "position-jitter", 0.25) + different = corruption_run._seed_for(_SCENE, "position-jitter", 0.5) + assert first == second + assert first != different + + +def test_corrupted_code_is_reproducible(): + first = corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "compact") + second = corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "compact") + assert first == second + + +def test_corrupted_explicit_is_derived_from_the_corrupted_compact(): + compact = corruption_run.corrupted_code(_SCENE, "position-jitter", 0.25, "compact") + explicit = corruption_run.corrupted_code( + _SCENE, "position-jitter", 0.25, "explicit" + ) + # Same corruption seed -> the explicit code's per-class counts must match the + # corrupted compact's own instance counts (consistency-by-construction). + for class_name, items in compact["objects"].items(): + assert explicit["objects"][class_name]["count"] == len(items) + + +def test_wrong_scene_returns_the_substitute_scenes_code(): + substituted = corruption_run.corrupted_code( + _SCENE, "wrong-scene", 0, "compact", wrong_scene=_OTHER_SCENE + ) + own = corruption_run.load_ground_truth_compact(_SCENE) + other = corruption_run.load_ground_truth_compact(_OTHER_SCENE) + assert substituted == other + assert substituted != own + + +def test_wrong_scene_requires_a_substitute(): + with pytest.raises(ValueError): + corruption_run.corrupted_code(_SCENE, "wrong-scene", 0, "compact") + + +def test_chimera_requires_perceived_config(): + with pytest.raises(ValueError): + corruption_run.corrupted_code(_SCENE, "chimera-gt-inventory", 0, "compact") + + +def test_empirical_requires_residuals(): + with pytest.raises(ValueError): + corruption_run.corrupted_code(_SCENE, "empirical", 1.0, "compact") + + +def test_unknown_transform_rejected(): + with pytest.raises(ValueError): + corruption_run.corrupted_code(_SCENE, "not-a-transform", 1.0, "compact") + + +def test_results_dir_for_isolates_every_axis(): + a = corruption_run.results_dir_for("vlm", "position-jitter", 0.25, "qwen3.5-4b") + b = corruption_run.results_dir_for("vlm", "position-jitter", 0.5, "qwen3.5-4b") + c = corruption_run.results_dir_for("solver", "position-jitter", 0.25, "symbolic") + assert len({a, b, c}) == 3 + + +def test_certify_rejects_non_invariance_transforms(): + with pytest.raises(ValueError): + corruption_run.certify_invariant(_SCENE, "position-jitter", 0.25) + + +def test_certify_translate_passes_on_a_real_scene(): + assert corruption_run.certify_invariant(_SCENE, "translate", 10.0) is True + + +def test_run_solver_answers_and_writes_records(tmp_path): + results = corruption_run.run_solver( + "position-jitter", 0.0, scenes=[_SCENE], results_dir=tmp_path + ) + assert results + for record in results: + assert record["model"] == "symbolic" + assert record["transform"] == "position-jitter" + assert record["scene"] == _SCENE + assert (tmp_path / _SCENE / f"{record['question_id']}.json").is_file() + + +def test_run_solver_zero_magnitude_jitter_matches_clean_ground_truth(): + # position-jitter at 0.0 is geometrically the identity, so the solver must score + # exactly what it scores on the clean ground-truth code. + from harness.D import symbolic_eval + + corrupted = corruption_run.run_solver( + "position-jitter", 0.0, scenes=[_SCENE], write_results=False + ) + clean = symbolic_eval.run( + spatial_code_format="explicit", scene=_SCENE, write_results=False + ) + corrupted_scores = {r["question_id"]: r["score"] for r in corrupted} + clean_scores = {r["question_id"]: r["score"] for r in clean} + assert corrupted_scores == clean_scores + + +def test_run_solver_respects_the_question_sample(tmp_path): + all_results = corruption_run.run_solver( + "position-jitter", 0.0, scenes=[_SCENE], write_results=False + ) + keep = {all_results[0]["question_id"]} + sampled = corruption_run.run_solver( + "position-jitter", 0.0, scenes=[_SCENE], question_ids=keep, write_results=False + ) + assert [r["question_id"] for r in sampled] == list(keep) + + +def test_make_code_transform_ignores_the_loaded_code(): + hook = corruption_run.make_code_transform("position-jitter", 0.25) + out = hook({"not": "used"}, _SCENE, "compact") + assert out == corruption_run.corrupted_code( + _SCENE, "position-jitter", 0.25, "compact" + ) + + +def test_single_object_info_is_deterministic_and_recomputable(): + first = corruption_run.single_object_info(_SCENE, 0) + second = corruption_run.single_object_info(_SCENE, 0) + assert first == second + assert "class" in first and "instance" in first + + +def test_single_object_solver_run_writes_perturbation_sidecar(tmp_path): + corruption_run.run_solver("single-object", 0, scenes=[_SCENE], results_dir=tmp_path) + sidecar = tmp_path / _SCENE / "_perturbation.json" + assert sidecar.is_file() + import json + + info = json.loads(sidecar.read_text()) + assert info == corruption_run.single_object_info(_SCENE, 0) + + +def test_non_probe_runs_write_no_sidecar(tmp_path): + corruption_run.run_solver( + "position-jitter", 0.0, scenes=[_SCENE], results_dir=tmp_path + ) + assert not (tmp_path / _SCENE / "_perturbation.json").exists() diff --git a/tests/test_corruption/test_sample.py b/tests/test_corruption/test_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..848798e3df29196319e8c19c86cf3a856165ca0a --- /dev/null +++ b/tests/test_corruption/test_sample.py @@ -0,0 +1,72 @@ +"""Tests for corruption/sample.py -- the pre-registered question sampler.""" + +from corruption import sample as corruption_sample + + +def _rows(monkeypatch, rows): + monkeypatch.setattr(corruption_sample, "load_questions", lambda: list(rows)) + + +def test_budget_key_pools_direction_subtypes(): + assert ( + corruption_sample._budget_key("object_rel_direction_easy") + == "object_rel_direction" + ) + assert ( + corruption_sample._budget_key("object_rel_direction_hard") + == "object_rel_direction" + ) + assert corruption_sample._budget_key("object_counting") == "object_counting" + + +def test_draw_sample_is_deterministic_for_the_frozen_seed(monkeypatch): + rows = [ + {"id": i, "scene_name": f"scene{i % 5}", "question_type": "object_counting"} + for i in range(50) + ] + _rows(monkeypatch, rows) + scenes = {f"scene{i}" for i in range(5)} + first = corruption_sample.draw_sample(scenes, budgets={"object_counting": 10}) + second = corruption_sample.draw_sample(scenes, budgets={"object_counting": 10}) + assert first == second + assert len(first) == 10 + + +def test_draw_sample_spreads_across_scenes_round_robin(monkeypatch): + # 5 scenes x 10 questions each; a 5-question budget must touch 5 DISTINCT scenes. + rows = [ + { + "id": scene * 100 + i, + "scene_name": f"scene{scene}", + "question_type": "object_counting", + } + for scene in range(5) + for i in range(10) + ] + _rows(monkeypatch, rows) + scenes = {f"scene{i}" for i in range(5)} + sampled = corruption_sample.draw_sample(scenes, budgets={"object_counting": 5}) + assert len({qid // 100 for qid in sampled}) == 5 + + +def test_draw_sample_excludes_unlisted_categories_and_scenes(monkeypatch): + rows = [ + {"id": 1, "scene_name": "scene_in", "question_type": "object_counting"}, + {"id": 2, "scene_name": "scene_in", "question_type": "obj_appearance_order"}, + {"id": 3, "scene_name": "scene_out", "question_type": "object_counting"}, + ] + _rows(monkeypatch, rows) + sampled = corruption_sample.draw_sample( + {"scene_in"}, budgets={"object_counting": 10} + ) + assert sampled == [1] + + +def test_draw_sample_budget_caps_the_draw(monkeypatch): + rows = [ + {"id": i, "scene_name": "scene0", "question_type": "object_counting"} + for i in range(100) + ] + _rows(monkeypatch, rows) + sampled = corruption_sample.draw_sample({"scene0"}, budgets={"object_counting": 7}) + assert len(sampled) == 7 diff --git a/tests/test_corruption/test_transforms.py b/tests/test_corruption/test_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..6c9a0280d77967bf4b6f72d835160b1fc9c07650 --- /dev/null +++ b/tests/test_corruption/test_transforms.py @@ -0,0 +1,178 @@ +"""Tests for corruption/transforms.py -- noise and invariance transform families.""" + +import math +import random + +from corruption import transforms + + +def _compact(classes=("chair", "table"), instances_per_class=2): + objects = {} + for class_index, name in enumerate(classes): + items = [] + for index in range(instances_per_class): + items.append( + { + "3D oriented bounding box": { + "3D oriented bounding box center coordinates": [ + float(class_index), + float(index), + 0.5, + ], + "3D oriented bounding box dimensions": [1.0, 2.0, 0.5], + "3D oriented bounding box orientation unit vectors": [ + [1.0, 0.0, 0.0], + [0.0, 0.0, 1.0], + [0.0, -1.0, 0.0], + ], + }, + "first visible time": float(index), + } + ) + objects[name] = items + return { + "spatial code schema": {}, + "objects": objects, + "room": { + "floor boundary polygons": [ + { + "outer boundary coordinates": [ + [0.0, 0.0], + [4.0, 0.0], + [4.0, 4.0], + [0.0, 4.0], + ] + } + ] + }, + } + + +def test_transforms_never_mutate_the_input(): + code = _compact() + frozen = str(code) + for name, transform in transforms.TRANSFORMS.items(): + transform(code, 0.5, random.Random(0)) + assert str(code) == frozen, f"{name} mutated its input" + + +def test_position_jitter_moves_centers_and_nothing_else(): + code = _compact() + out = transforms.position_jitter(code, 0.5, random.Random(0)) + before = code["objects"]["chair"][0]["3D oriented bounding box"] + after = out["objects"]["chair"][0]["3D oriented bounding box"] + assert before["3D oriented bounding box center coordinates"] != ( + after["3D oriented bounding box center coordinates"] + ) + assert before["3D oriented bounding box dimensions"] == ( + after["3D oriented bounding box dimensions"] + ) + + +def test_position_jitter_zero_sigma_is_identity_geometry(): + code = _compact() + out = transforms.position_jitter(code, 0.0, random.Random(0)) + assert out == code + + +def test_dimension_noise_never_collapses_a_dimension(): + code = _compact() + out = transforms.dimension_noise(code, 5.0, random.Random(0)) + for _name, instance in transforms._instances(out): + for value in instance["3D oriented bounding box"][ + "3D oriented bounding box dimensions" + ]: + assert value > 0.0 + + +def test_drop_objects_removes_emptied_classes_entirely(): + code = _compact() + out = transforms.drop_objects(code, 1.0, random.Random(0)) + assert out["objects"] == {} + + +def test_drop_objects_zero_fraction_drops_nothing(): + code = _compact() + out = transforms.drop_objects(code, 0.0, random.Random(0)) + assert out == code + + +def test_hallucinate_objects_only_ever_adds(): + code = _compact() + out = transforms.hallucinate_objects(code, 1.0, random.Random(0)) + for name in code["objects"]: + assert len(out["objects"][name]) == 2 * len(code["objects"][name]) + + +def test_class_swap_keeps_geometry_but_relabels(): + code = _compact() + out = transforms.class_swap(code, 1.0, random.Random(0)) + # Same set of class names, same total geometry, but at least one class's items moved. + assert sorted(out["objects"]) == sorted(code["objects"]) + assert any( + out["objects"][name] != code["objects"][name] for name in code["objects"] + ) + + +def test_translate_shifts_centers_and_polygons_together(): + code = _compact() + out = transforms.translate(code, 10.0) + center = out["objects"]["chair"][0]["3D oriented bounding box"][ + "3D oriented bounding box center coordinates" + ] + assert center[:2] == [10.0, 10.0] + assert center[2] == 0.5 # height untouched + assert out["room"]["floor boundary polygons"][0]["outer boundary coordinates"][ + 0 + ] == [10.0, 10.0] + + +def test_rotate_z_preserves_pairwise_distances(): + code = _compact() + out = transforms.rotate_z(code, 90.0) + + def centers(c): + return [ + instance["3D oriented bounding box"][ + "3D oriented bounding box center coordinates" + ] + for _name, instance in transforms._instances(c) + ] + + before, after = centers(code), centers(out) + for i in range(len(before)): + for j in range(i + 1, len(before)): + assert ( + math.dist(before[i], before[j]) + == round(math.dist(after[i], after[j]), 10) + or abs(math.dist(before[i], before[j]) - math.dist(after[i], after[j])) + < 0.05 + ) + + +def test_reorder_changes_only_order(): + code = _compact(classes=("a", "b", "c", "d")) + out = transforms.reorder(code, None, random.Random(3)) + assert sorted(out["objects"]) == sorted(code["objects"]) + for name in code["objects"]: + assert sorted(map(str, out["objects"][name])) == sorted( + map(str, code["objects"][name]) + ) + + +def test_round_precision_rounds_every_geometry_value(): + code = _compact() + code["objects"]["chair"][0]["3D oriented bounding box"][ + "3D oriented bounding box center coordinates" + ] = [0.123456, 1.987654, 0.5] + out = transforms.round_precision(code, 1) + assert out["objects"]["chair"][0]["3D oriented bounding box"][ + "3D oriented bounding box center coordinates" + ] == [0.1, 2.0, 0.5] + + +def test_seeded_transforms_are_reproducible(): + code = _compact() + first = transforms.position_jitter(code, 0.3, random.Random(42)) + second = transforms.position_jitter(code, 0.3, random.Random(42)) + assert first == second diff --git a/tests/test_encoder/test_ground_truth.py b/tests/test_encoder/test_ground_truth.py new file mode 100644 index 0000000000000000000000000000000000000000..a0608f0210c06fbcfd541b4a882b592cd3fb7d85 --- /dev/null +++ b/tests/test_encoder/test_ground_truth.py @@ -0,0 +1,327 @@ +"""Tests for encoder/ground_truth.py -- spatial codes built from dataset annotations.""" + +import json +import math + +import numpy as np +import pytest + +from encoder import config, geometric +from encoder import ground_truth as gt + +IDENTITY_AXES = [1, 0, 0, 0, 1, 0, 0, 0, 1] + + +def _instance(centroid, dims, axes=None): + return { + "centroid": list(centroid), + "axesLengths": list(dims), + "normalizedAxes": list(axes if axes is not None else IDENTITY_AXES), + } + + +def _write_meta_info(tmp_path, scannet=None, arkitscenes=None, scannetpp=None): + meta_dir = tmp_path / "thinking-in-space" / "data" / "meta_info" + meta_dir.mkdir(parents=True) + for dataset, records in ( + ("scannet", scannet or {}), + ("arkitscenes", arkitscenes or {}), + ("scannetpp", scannetpp or {}), + ): + with open(meta_dir / f"{dataset}_meta_info_val.json", "w") as stream: + json.dump(records, stream) + return meta_dir + + +@pytest.fixture(autouse=True) +def _clear_ground_truth_caches(): + gt.load_meta_info.cache_clear() + gt._appearance_order_ranks_by_scene.cache_clear() + yield + gt.load_meta_info.cache_clear() + gt._appearance_order_ranks_by_scene.cache_clear() + + +def test_load_meta_info_merges_all_three_datasets_and_tags_dataset( + tmp_path, monkeypatch +): + _write_meta_info( + tmp_path, + scannet={"scene0001_00": {"room_size": 10.0, "object_bbox": {}}}, + arkitscenes={"41000000": {"room_size": 12.0, "object_bbox": {}}}, + scannetpp={"abc123": {"room_size": 14.0, "object_bbox": {}}}, + ) + monkeypatch.setattr( + gt, "META_INFO_DIR", tmp_path / "thinking-in-space" / "data" / "meta_info" + ) + merged = gt.load_meta_info() + assert merged["scene0001_00"]["dataset"] == "scannet" + assert merged["41000000"]["dataset"] == "arkitscenes" + assert merged["abc123"]["dataset"] == "scannetpp" + + +def test_floor_level_is_the_lowest_box_support_across_every_instance(): + object_bbox = { + "chair": [_instance([0, 0, 1.0], [1, 1, 0.4])], # spans z in [0.8, 1.2] + "table": [_instance([0, 0, 0.5], [1, 1, 1.0])], # spans z in [0.0, 1.0] + } + # table reaches lower (0.0) than chair (0.8) -> floor_level should be 0.0 + assert gt._floor_level(object_bbox) == pytest.approx(0.0) + + +def test_floor_level_accounts_for_tilted_box_support(): + # a box tilted 45 degrees around x has a lower support than its centroid_z - half_z + # would suggest if you ignored orientation. + axes = [ + [1, 0, 0], + [0, math.cos(math.pi / 4), math.sin(math.pi / 4)], + [0, -math.sin(math.pi / 4), math.cos(math.pi / 4)], + ] + flat_axes = [v for row in axes for v in row] + object_bbox = {"box": [_instance([0, 0, 1.0], [1, 2, 2], axes=flat_axes)]} + half_extent_z = ( + (1 / 2) * abs(0) + + (2 / 2) * abs(math.sin(math.pi / 4)) + + (2 / 2) * abs(math.cos(math.pi / 4)) + ) + assert gt._floor_level(object_bbox) == pytest.approx(1.0 - half_extent_z) + + +def test_floor_level_defaults_to_zero_for_empty_scene(): + assert gt._floor_level({}) == 0.0 + + +def test_gt_oriented_box_rebases_height_above_floor_and_passes_xy_through(): + instance = _instance([1.234, -2.345, 3.456], [1.0, 2.0, 3.0]) + box = gt._gt_oriented_box(instance, floor_level=1.0) + center = box["3D oriented bounding box center coordinates"] + assert center == [1.23, -2.35, 2.46] + assert box["3D oriented bounding box dimensions"] == [1.0, 2.0, 3.0] + assert box["3D oriented bounding box orientation unit vectors"] == [ + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + ] + + +def test_gt_oriented_box_renormalizes_orientation_vectors(): + axes = [2, 0, 0, 0, 2, 0, 0, 0, 2] # not unit length + instance = _instance([0, 0, 0], [1, 1, 1], axes=axes) + box = gt._gt_oriented_box(instance, floor_level=0.0) + for row in box["3D oriented bounding box orientation unit vectors"]: + assert np.linalg.norm(row) == pytest.approx(1.0) + + +def test_gt_floor_boundary_polygon_area_matches_room_size(): + polygons = gt._gt_floor_boundary_polygons( + room_size=16.0, room_center=[3.0, -2.0, 0.0] + ) + assert len(polygons) == 1 + area = geometric._compact_polygon_area(polygons[0]["outer boundary coordinates"]) + assert area == pytest.approx(16.0, abs=0.01) + assert polygons[0]["interior hole boundary coordinates"] == [] + + +def test_appearance_order_ranks_topological_across_multiple_questions( + tmp_path, monkeypatch +): + jsonl_path = tmp_path / "test.jsonl" + questions = [ + { + "scene_name": "scene1", + "question_type": "obj_appearance_order", + "ground_truth": "A", + "options": ["A. chair, table, lamp", "B. lamp, table, chair"], + }, + { + "scene_name": "scene1", + "question_type": "obj_appearance_order", + "ground_truth": "A", + "options": ["A. table, sofa", "B. sofa, table"], + }, + { + "scene_name": "scene2", + "question_type": "object_counting", + "ground_truth": "3", + "options": None, + }, + ] + with open(jsonl_path, "w") as stream: + for question in questions: + stream.write(json.dumps(question) + "\n") + monkeypatch.setattr(config, "JSONL", jsonl_path) + + ranks = gt._appearance_order_ranks_by_scene() + assert "scene2" not in ranks + scene1 = ranks["scene1"] + assert scene1["chair"] < scene1["table"] < scene1["lamp"] + assert scene1["table"] < scene1["sofa"] + + +def test_build_compact_ground_truth_spatial_code_uses_ranks_and_nulls_unranked( + tmp_path, monkeypatch +): + _write_meta_info( + tmp_path, + scannet={ + "scene1": { + "room_size": 9.0, + "room_center": [0.0, 0.0, 0.0], + "object_bbox": { + "chair": [_instance([0, 0, 0.5], [1, 1, 1])], + "lamp": [_instance([1, 1, 0.5], [0.2, 0.2, 0.2])], + }, + } + }, + ) + monkeypatch.setattr( + gt, "META_INFO_DIR", tmp_path / "thinking-in-space" / "data" / "meta_info" + ) + jsonl_path = tmp_path / "test.jsonl" + with open(jsonl_path, "w") as stream: + stream.write( + json.dumps( + { + "scene_name": "scene1", + "question_type": "obj_appearance_order", + "ground_truth": "A", + "options": ["A. chair, lamp"], + } + ) + + "\n" + ) + monkeypatch.setattr(config, "JSONL", jsonl_path) + + code = gt.build_compact_ground_truth_spatial_code("scene1") + assert code["spatial code schema"] is geometric.COMPACT_SPATIAL_CODE_SCHEMA + assert code["objects"]["chair"][0]["first visible time"] == 0.0 + assert code["objects"]["lamp"][0]["first visible time"] == 1.0 + + +def test_build_compact_ground_truth_spatial_code_nulls_untimed_classes( + tmp_path, monkeypatch +): + _write_meta_info( + tmp_path, + scannet={ + "scene1": { + "room_size": 9.0, + "room_center": [0.0, 0.0, 0.0], + "object_bbox": {"chair": [_instance([0, 0, 0.5], [1, 1, 1])]}, + } + }, + ) + monkeypatch.setattr( + gt, "META_INFO_DIR", tmp_path / "thinking-in-space" / "data" / "meta_info" + ) + monkeypatch.setattr(config, "JSONL", tmp_path / "empty.jsonl") + (tmp_path / "empty.jsonl").write_text("") + + code = gt.build_compact_ground_truth_spatial_code("scene1") + assert code["objects"]["chair"][0]["first visible time"] is None + + +def test_build_compact_ground_truth_spatial_code_raises_for_unknown_scene( + tmp_path, monkeypatch +): + _write_meta_info(tmp_path) + monkeypatch.setattr( + gt, "META_INFO_DIR", tmp_path / "thinking-in-space" / "data" / "meta_info" + ) + monkeypatch.setattr(config, "JSONL", tmp_path / "empty.jsonl") + (tmp_path / "empty.jsonl").write_text("") + with pytest.raises(KeyError): + gt.build_compact_ground_truth_spatial_code("nonexistent") + + +def test_build_explicit_ground_truth_spatial_code_is_derived_from_compact(monkeypatch): + compact_code = { + "spatial code schema": geometric.COMPACT_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": []}, + } + monkeypatch.setattr( + gt, "build_compact_ground_truth_spatial_code", lambda scene: compact_code + ) + explicit_code = gt.build_explicit_ground_truth_spatial_code("scene1") + assert ( + explicit_code["spatial code schema"] is geometric.EXPLICIT_SPATIAL_CODE_SCHEMA + ) + assert explicit_code["objects"]["chair"]["count"] == 1 + assert explicit_code["appearance order"] == ["chair"] + + +def test_build_ground_truth_spatial_code_dispatches_by_format(monkeypatch): + monkeypatch.setattr( + gt, "build_compact_ground_truth_spatial_code", lambda scene: "compact-code" + ) + monkeypatch.setattr( + gt, "build_explicit_ground_truth_spatial_code", lambda scene: "explicit-code" + ) + assert gt.build_ground_truth_spatial_code("scene1", "compact") == "compact-code" + assert gt.build_ground_truth_spatial_code("scene1", "explicit") == "explicit-code" + + +def test_build_ground_truth_spatial_code_rejects_unknown_format(): + with pytest.raises(ValueError, match="unknown spatial-code format"): + gt.build_ground_truth_spatial_code("scene1", "unknown") + + +def test_build_and_write_writes_to_the_ground_truth_path(tmp_path, monkeypatch): + monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "codes") + monkeypatch.setattr( + gt, "build_ground_truth_spatial_code", lambda scene, fmt: {"objects": {}} + ) + path = gt.build_and_write("scene1", "explicit") + assert path.endswith("codes/ground truth/explicit/scene1.json") + assert json.loads(open(path).read()) == {"objects": {}} + + +def test_scenes_returns_sorted_meta_info_keys(tmp_path, monkeypatch): + _write_meta_info( + tmp_path, + scannet={"scene0002_00": {}, "scene0001_00": {}}, + arkitscenes={"41000000": {}}, + ) + monkeypatch.setattr( + gt, "META_INFO_DIR", tmp_path / "thinking-in-space" / "data" / "meta_info" + ) + assert gt.scenes() == ["41000000", "scene0001_00", "scene0002_00"] + + +def test_build_all_writes_every_scene_and_format(tmp_path, monkeypatch): + monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "codes") + monkeypatch.setattr(gt, "scenes", lambda: ["scene1", "scene2"]) + monkeypatch.setattr( + gt, "build_ground_truth_spatial_code", lambda scene, fmt: {"objects": {}} + ) + written = gt.build_all() + assert len(written) == 4 + assert (tmp_path / "codes" / "ground truth" / "explicit" / "scene1.json").exists() + assert (tmp_path / "codes" / "ground truth" / "compact" / "scene2.json").exists() + + +def test_build_all_respects_explicit_scene_list_and_formats(tmp_path, monkeypatch): + monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "codes") + monkeypatch.setattr( + gt, "build_ground_truth_spatial_code", lambda scene, fmt: {"objects": {}} + ) + written = gt.build_all(spatial_code_formats=("compact",), scene_list=["scene9"]) + assert written == [ + str(tmp_path / "codes" / "ground truth" / "compact" / "scene9.json") + ]