Download code/lib/evaluate_selective_pilot.py from GiulioTrovato/OutOfSightOutOfPlace: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/datasets/GiulioTrovato/OutOfSightOutOfPlace/resolve/main/code/lib/evaluate_selective_pilot.py
- Command line
-
hf download hf://datasets/GiulioTrovato/OutOfSightOutOfPlace/code/lib/evaluate_selective_pilot.py
-
curl -L -o evaluate_selective_pilot.py https://huggingface.co/datasets/GiulioTrovato/OutOfSightOutOfPlace/resolve/main/code/lib/evaluate_selective_pilot.py
12 kB
| #!/usr/bin/env python3 | |
| """Exploratory two-block scoring, visibility controls, and measured profiling.""" | |
| import argparse | |
| from contextlib import nullcontext | |
| from dataclasses import replace | |
| from datetime import datetime, timezone | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import time | |
| import numpy as np | |
| from PIL import Image | |
| import torch | |
| from evaluate_hidden_state import PredictiveInterface, add_official_repo, load_pretrained_interface, source_provenance | |
| from hidden_state import State, content_hash, score_matrix, write_new_json | |
| class ObservedSubset(PredictiveInterface): | |
| """Drop selected past tubelets before attention, retaining absolute positions.""" | |
| def __init__(self, interface, ids): | |
| self.__dict__ = interface.__dict__.copy() | |
| self.kept_ids = ids | |
| if not ids or len(ids) != len(set(ids)) or any(i < 0 or i >= self.plan.context_tokens for i in ids): | |
| raise ValueError("Subset must contain unique observed-token indices") | |
| def masks(self, batch, device): | |
| context = torch.tensor(self.kept_ids, device=device).expand(batch, -1) | |
| future = torch.arange(self.plan.context_tokens, self.plan.total_tokens, device=device).expand(batch, -1) | |
| return context, future | |
| def predict_future(self, context_features): | |
| if context_features.shape[1] != len(self.kept_ids): | |
| raise ValueError("Subset context feature count mismatch") | |
| context, future = self.masks(context_features.shape[0], context_features.device) | |
| result = self.predictor(context_features, context, future, mask_index=self.mask_index) | |
| if tuple(result.shape) != (context_features.shape[0], self.plan.future_tokens, self.output_width): | |
| raise ValueError("Subset predictor output contract failed") | |
| return result | |
| def load_frames(root, paths): | |
| images = [] | |
| for path in paths: | |
| with Image.open(root / path) as image: | |
| image = image.convert("RGB") | |
| if image.size != (256, 256): | |
| raise ValueError("Expected the packaged official 256-pixel crop") | |
| images.append(np.array(image)) | |
| array = np.stack(images) | |
| digest = hashlib.sha256(array.tobytes()).hexdigest() | |
| value = torch.from_numpy(array.copy()).float().permute(3, 0, 1, 2).unsqueeze(0) / 255 | |
| mean = value.new_tensor([0.485, 0.456, 0.406])[None, :, None, None, None] | |
| std = value.new_tensor([0.229, 0.224, 0.225])[None, :, None, None, None] | |
| return ((value - mean) / std).cuda(), digest | |
| def fixed_roi(regions): | |
| tokens = set() | |
| for x0, y0, x1, y1 in regions: | |
| left, top = max(0, x0*292/512 - 18), max(0, y0*292/512 - 18) | |
| right, bottom = min(256, x1*292/512 - 18), min(256, y1*292/512 - 18) | |
| for y in range(16): | |
| for x in range(16): | |
| if 16*x < right and 16*(x+1) > left and 16*y < bottom and 16*(y+1) > top: | |
| tokens.add(y*16+x) | |
| if not tokens: | |
| raise ValueError("Empty fixed all-cup ROI") | |
| return sorted(tokens) | |
| def precision_context(name): | |
| return torch.autocast("cuda", dtype=torch.bfloat16) if name == "bfloat16" else nullcontext() | |
| def profile_operation(operation, precision, count=50): | |
| with precision_context(precision): | |
| for _ in range(5): | |
| operation() | |
| torch.cuda.synchronize() | |
| values = [] | |
| for _ in range(count): | |
| torch.cuda.synchronize(); started = time.perf_counter() | |
| operation(); torch.cuda.synchronize() | |
| values.append(time.perf_counter() - started) | |
| return {"warmup_calls": 5, "measured_calls": count, "seconds": values, | |
| "mean_seconds": float(np.mean(values)), "median_seconds": float(np.median(values)), | |
| "p90_seconds": float(np.percentile(values, 90))} | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--views", type=Path, required=True) | |
| parser.add_argument("--repo", type=Path, default=Path(".local/vjepa2")) | |
| parser.add_argument("--checkpoint", type=Path, default=Path(".local/models/vitl.pt")) | |
| parser.add_argument("--output", type=Path, required=True) | |
| parser.add_argument("--profile", action="store_true") | |
| args = parser.parse_args() | |
| if os.environ.get("SLURM_JOB_PARTITION") != "bulk" or not torch.cuda.is_available(): | |
| parser.error("Run in a bulk GPU allocation") | |
| if args.output.exists(): | |
| parser.error("Refusing to overwrite a pilot result") | |
| add_official_repo(args.repo) | |
| from evals.hub.preprocessor import vjepa2_preprocessor | |
| preprocessor = vjepa2_preprocessor(crop_size=256) | |
| args.output.mkdir(parents=True) | |
| torch.set_num_threads(4); torch.manual_seed(20261016) | |
| torch.set_float32_matmul_precision("highest") | |
| started = time.monotonic() | |
| interface, loading = load_pretrained_interface(args.repo, args.checkpoint, "vjepa2", "cuda", frames=64) | |
| package = json.loads((args.views / "model-view-manifest.json").read_text()) | |
| if len(package["blocks"]) != 2: | |
| raise ValueError("This first evaluation is restricted to two validated scene blocks") | |
| results = [] | |
| profiles = {} | |
| for block_index, item in enumerate(package["blocks"]): | |
| block = item["block"] | |
| roi = fixed_roi(item["fixed_cup_regions_master_pixels"]) | |
| canonical, canonical_hash = load_frames(args.views, [item["canonical_frame"]] * 52) | |
| suffix_tensors, suffix_hashes = [], [] | |
| for candidate in block["candidates"]: | |
| tensor, digest = load_frames(args.views, item["candidates"][candidate["candidate_id"]]) | |
| suffix_tensors.append(tensor); suffix_hashes.append(digest) | |
| suffixes = torch.cat(suffix_tensors) | |
| prefixes, input_hashes = [], [] | |
| for history in block["histories"]: | |
| value, digest = load_frames(args.views, item["histories"][history["history_id"]]) | |
| prefixes.append(value); input_hashes.append(digest) | |
| if block_index == 0: | |
| # Check the exported PNG crop against the genuine model preprocessor. | |
| rendered = json.loads((Path(item["render_directory"]) / "render-manifest.json").read_text()) | |
| history_id = block["histories"][0]["history_id"] | |
| first_key = rendered["histories"][history_id][0]["key"] | |
| with Image.open(Path(item["render_directory"]) / rendered["pool"][first_key]["rgb"]) as image: | |
| reference = preprocessor([image.convert("RGB")])[0] | |
| torch.testing.assert_close(prefixes[0][0, :, :1].cpu(), reference, rtol=0, atol=1e-6) | |
| profiles["official_preprocessor_match"] = True | |
| block_results = {"block_id": block["block_id"], "history_input_rgb_sha256": input_hashes, | |
| "candidate_suffix_rgb_sha256": suffix_hashes, "canonical_rgb_sha256": canonical_hash, | |
| "fixed_spatial_token_indices": roi, "readouts": {}} | |
| modes = {"full": list(range(6656)), "early_only": list(range(6*256)), | |
| "event_only": list(range(7*256, 16*256)), "last_only": list(range(25*256, 26*256))} | |
| for precision in ("float32", "bfloat16"): | |
| with precision_context(precision): | |
| targets = interface.encode_candidate_targets(canonical, suffixes) | |
| for mode, ids in modes.items(): | |
| readout = ObservedSubset(interface, ids) | |
| predictions = torch.cat([readout.predict_future(readout.encode_context(prefix)) for prefix in prefixes]) | |
| energies = interface.score_candidates(predictions, targets, roi).cpu().tolist() | |
| metrics = score_matrix(block, energies) | |
| if mode in {"early_only", "event_only"} and metrics["joint_accuracy"] > .5 + 1e-9: | |
| raise AssertionError("Information-limited control exceeds its proven ceiling") | |
| if mode == "last_only" and abs(metrics["joint_accuracy"] - .25) > 1e-9: | |
| raise AssertionError("Identical covered observation did not give balanced chance accuracy") | |
| block_results["readouts"][f"{precision}/{mode}"] = { | |
| "metrics": metrics, "energies": energies, "context_tokens": len(ids), | |
| "full_frame_energies": interface.score_candidates(predictions, targets, list(range(256))).cpu().tolist()} | |
| visible_predictions = torch.cat([interface.predict_future(interface.encode_context(prefix[:, :, :1].expand(-1,-1,52,-1,-1).contiguous())) | |
| for prefix in prefixes]) | |
| visible_block = dict(block, histories=[dict(h, events=[]) for h in block["histories"]]) | |
| visible_energies = interface.score_candidates(visible_predictions, targets, roi).cpu().tolist() | |
| block_results["readouts"][f"{precision}/visible_stationary_control"] = { | |
| "scope": "Synthetic constant-visible context; correct state is initial state, not the later removal state", | |
| "metrics": score_matrix(visible_block, visible_energies), "energies": visible_energies} | |
| print(json.dumps({"block": block_index+1,"precision": precision, | |
| "full_joint": block_results['readouts'][f'{precision}/full']['metrics']['joint_accuracy'], | |
| "visible_joint": block_results['readouts'][f'{precision}/visible_stationary_control']['metrics']['joint_accuracy']}),flush=True) | |
| if args.profile and block_index == 0: | |
| for precision in ("float32", "bfloat16"): | |
| profiles[precision] = { | |
| "context_and_predictor": profile_operation(lambda: interface.predict_future(interface.encode_context(prefixes[0])), precision), | |
| "single_candidate_target": profile_operation(lambda: interface.encode_candidate_targets(canonical, suffixes[:1]), precision), | |
| } | |
| write_new_json(args.output / f"profile-{precision}.json", profiles[precision]) | |
| write_new_json(args.output / f"block-{block_index+1}.json", block_results) | |
| results.append(block_results) | |
| agreement = [] | |
| for result in results: | |
| for mode in (*modes, "visible_stationary_control"): | |
| fp = result["readouts"][f"float32/{mode}"]["energies"] | |
| bf = result["readouts"][f"bfloat16/{mode}"]["energies"] | |
| agreement.append({"block_id": result["block_id"], "mode": mode, | |
| "top1_agreement_count": int(sum(np.argmin(a)==np.argmin(b) for a,b in zip(fp,bf))), | |
| "histories": 4, "maximum_energy_difference": float(np.max(np.abs(np.array(fp)-np.array(bf))))}) | |
| summary = {"status": "completed_exploratory_two_block_check", "created_utc": datetime.now(timezone.utc).isoformat(), | |
| "independent_scene_blocks": 2, "human_visibility_gate": "pending", | |
| "scope": "readout and stimulus pilot; not a population-performance or memory claim", | |
| "loading": loading, "provenance": source_provenance(args.repo), | |
| "implementation_sha256": {name: content_hash(Path(__file__).parent/name) for name in ( | |
| "evaluate_selective_pilot.py","evaluate_hidden_state.py","hidden_state.py")}, | |
| "checkpoint_sha256": content_hash(args.checkpoint), "view_manifest_sha256": content_hash(args.views/"model-view-manifest.json"), | |
| "precision_agreement": agreement, "profiles": profiles, | |
| "elapsed_seconds": time.monotonic()-started, "gpu": torch.cuda.get_device_name(), | |
| "peak_allocated_vram_bytes": torch.cuda.max_memory_allocated()} | |
| write_new_json(args.output/"summary.json", summary) | |
| print(json.dumps({"output": str(args.output), "status": summary["status"], "elapsed_seconds": summary["elapsed_seconds"]}),flush=True) | |
| if __name__ == "__main__": | |
| main() | |