| """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 os |
| 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: Path("/root/results") / h for h in "ABCE"} |
| 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(0.25), |
| "p75": percentile(0.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 "<missing>")].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 |
| ), |
| "reasoning_present": ( |
| statistics.mean( |
| bool(r.get("reasoning_text") or r.get("reasoning_raw")) |
| 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 "<missing>") |
| 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 "<missing>")].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(0.025 * iterations) |
| high = min(iterations - 1, int(0.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": 0.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; select base or thinking protocol families", |
| ) |
| 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: <output-dir>/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}") |
|
|
|
|
| |
|
|
| |
| 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"], |
| }, |
| "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") |
| 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 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 "" |
| 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 = x if lx == "F" else y if ly == "F" else None |
| other = y if lx == "F" else x |
| if f: |
| expected = "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 _generated_at(): |
| return os.environ.get("VSI_ANALYSIS_GENERATED_AT", "reproducible") |
|
|
|
|
| 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": _generated_at(), |
| "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": _generated_at(), |
| "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 == "D": |
| raise argparse.ArgumentTypeError( |
| "letter must be one alphabetic character other than D" |
| ) |
| 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; D is removed", |
| ) |
| 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; select base or thinking protocol families", |
| ) |
| 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 "abce": |
| 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 "abce": |
| 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}") |
|
|
|
|
| |
| 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=0.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()} |
| 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; D is removed." |
| ) |
| 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() |
|
|