OutOfSightOutOfPlace / code /lib /evaluate_hidden_state.py
Giulio Trovato
Upload OutOfSightOutOfPlace
c6a1af0 verified
Raw History Blame Contribute Delete
21.5 kB
#!/usr/bin/env python3
"""JEPA tensor/masking contracts. No renderer or semantic model result is implied.
The CLI currently runs contract checks and checkpoint inspection. Image-dataset
evaluation will be enabled after the two-ball renderer and ROI are validated.
All model factories use pretrained=False: this program never downloads weights.
"""
import argparse
from dataclasses import asdict
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import torch
import torch.nn.functional as F
from hidden_state import FramePlan, content_hash, write_new_json
def add_official_repo(repo):
repo = Path(repo).resolve()
if not (repo / "src/models/vision_transformer.py").is_file():
raise ValueError(f"Missing official V-JEPA repository: {repo}")
if "src" in sys.modules:
module_file = getattr(sys.modules["src"], "__file__", None)
if module_file and not Path(module_file).resolve().is_relative_to(repo):
raise ValueError("A different package named src is already imported")
sys.path.insert(0, str(repo))
def cleaned_weights(weights):
result = {}
for original, value in weights.items():
key = original
while key.startswith(("module.", "backbone.")):
key = key.split(".", 1)[1]
if key in result:
raise ValueError(f"Checkpoint key collision after removing wrappers: {key}")
result[key] = value
return result
def checked_load(module, weights, allowed_unused=()):
weights = cleaned_weights(weights)
missing = set(module.state_dict()) - set(weights)
unexpected = set(weights) - set(module.state_dict())
if missing or unexpected - set(allowed_unused):
raise ValueError(f"Weight mismatch: missing={sorted(missing)}, unexpected={sorted(unexpected)}")
filtered = {key: value for key, value in weights.items() if key not in unexpected}
module.load_state_dict(filtered, strict=True, assign=True)
module.requires_grad_(False).eval()
return {"loaded_tensors": len(filtered), "ignored_legacy_keys": sorted(unexpected)}
class PredictiveInterface:
"""Image-only context path, explicit future queries, separate target path."""
def __init__(self, encoder, predictor, plan, target_encoder=None, mask_index=1):
self.encoder = encoder.eval().requires_grad_(False)
self.predictor = predictor.eval().requires_grad_(False)
self.target_encoder = target_encoder
if target_encoder is not None:
target_encoder.eval().requires_grad_(False)
self.plan = plan
self.mask_index = mask_index
projection = encoder.patch_embed.proj
expected = (plan.tubelet_size, plan.patch_size, plan.patch_size)
if (tuple(projection.kernel_size) != expected or tuple(projection.stride) != expected
or tuple(projection.padding) != (0, 0, 0) or tuple(projection.dilation) != (1, 1, 1)):
raise ValueError("Patch embedding overlaps token boundaries or differs from the frame plan")
if (predictor.img_height, predictor.img_width, predictor.num_frames) != (
plan.input_size, plan.input_size, plan.sample_frames
):
raise ValueError("Predictor positional grid differs from the frame plan")
if not 0 <= mask_index < predictor.num_mask_tokens:
raise ValueError("Mask-token index must be explicit and in range")
self.output_width = predictor.predictor_proj.out_features
def _validate_video(self, video, frames):
expected = (3, frames, self.plan.input_size, self.plan.input_size)
if video.ndim != 5 or tuple(video.shape[1:]) != expected:
raise ValueError(f"Expected B×{expected}, got {tuple(video.shape)}")
if not torch.is_floating_point(video) or not torch.isfinite(video).all():
raise ValueError("Video must be finite, preprocessed floating-point RGB")
def masks(self, batch, device):
context = torch.arange(self.plan.context_tokens, device=device).expand(batch, -1)
future = torch.arange(self.plan.context_tokens, self.plan.total_tokens, device=device).expand(batch, -1)
return context, future
@torch.inference_mode()
def _encode_masked_full_video(self, video):
"""Low-level path used to verify native pre-attention mask invariance."""
self._validate_video(video, self.plan.sample_frames)
context, _ = self.masks(video.shape[0], video.device)
features = self.encoder(video, masks=context)
if not isinstance(features, torch.Tensor) or features.shape[:2] != context.shape:
raise ValueError("Unexpected context feature interface; hierarchical outputs need an explicit adapter")
return features
@torch.inference_mode()
def encode_context(self, prefix):
"""Only observed frames are accepted: candidate endings cannot enter here."""
self._validate_video(prefix, self.plan.context_frames)
future = prefix.new_zeros((prefix.shape[0], 3,
self.plan.sample_frames - self.plan.context_frames,
self.plan.input_size, self.plan.input_size))
return self._encode_masked_full_video(torch.cat((prefix, future), dim=2))
@torch.inference_mode()
def predict_future(self, context_features):
if context_features.ndim != 3 or context_features.shape[1] != self.plan.context_tokens:
raise ValueError("Unexpected context tensor shape")
context, future = self.masks(context_features.shape[0], context_features.device)
result = self.predictor(context_features, context, future, mask_index=self.mask_index)
# V-JEPA 2.1 returns predicted-future and predicted-context tensors.
prediction = result[0] if isinstance(result, tuple) else result
expected = (context_features.shape[0], self.plan.future_tokens, self.output_width)
if tuple(prediction.shape) != expected:
raise ValueError(f"Unexpected predictor output: {tuple(prediction.shape)} != {expected}")
return prediction
@torch.inference_mode()
def encode_candidate_targets(self, common_prefix, candidate_suffixes):
"""One history-independent prefix, reused for every candidate code."""
if self.target_encoder is None:
raise ValueError("A compatible trained target encoder is required for visual energy scoring")
self._validate_video(common_prefix, self.plan.context_frames)
if common_prefix.shape[0] != 1:
raise ValueError("Target codebook accepts exactly one shared canonical prefix")
self._validate_video(candidate_suffixes, self.plan.sample_frames - self.plan.context_frames)
all_targets = []
for suffix in candidate_suffixes:
video = torch.cat((common_prefix, suffix.unsqueeze(0)), dim=2)
targets = self.target_encoder(video)
if not isinstance(targets, torch.Tensor) or targets.ndim != 3:
raise ValueError("Target model needs an explicit hierarchical-output adapter")
if targets.shape[1:] != (self.plan.total_tokens, self.output_width):
raise ValueError("Target tokens/width do not match the trained predictor target space")
targets = F.layer_norm(targets.float(), (targets.shape[-1],), eps=1e-5)
all_targets.append(targets[:, self.plan.context_tokens:, :])
return torch.cat(all_targets)
def score_candidates(self, predictions, targets, spatial_indices):
"""L1 score with an explicitly supplied fixed, candidate-independent ROI."""
expected = (self.plan.future_tokens, self.output_width)
if predictions.ndim != 3 or targets.ndim != 3:
raise ValueError("Predictions and targets must be batch×tokens×features")
if tuple(predictions.shape[1:]) != expected or tuple(targets.shape[1:]) != expected:
raise ValueError("Prediction and target dimensions differ; do not project/truncate to fit")
if not spatial_indices or len(set(spatial_indices)) != len(spatial_indices):
raise ValueError("ROI must contain a nonempty set of unique spatial token indices")
if any(type(i) is not int or not 0 <= i < self.plan.spatial_tokens for i in spatial_indices):
raise ValueError("Spatial ROI index outside grid")
if not torch.isfinite(predictions).all() or not torch.isfinite(targets).all():
raise ValueError("Nonfinite features cannot be scored")
start = (self.plan.score_start_frame - self.plan.context_frames) // self.plan.tubelet_size
end = (self.plan.score_end_frame - self.plan.context_frames) // self.plan.tubelet_size
positions = torch.tensor([t * self.plan.spatial_tokens + s
for t in range(start, end) for s in spatial_indices],
device=predictions.device)
pred = predictions.index_select(1, positions).float()
target = targets.index_select(1, positions).float()
# Loop over candidates to avoid materializing B×K×tokens×width.
return torch.stack([(pred - candidate.unsqueeze(0)).abs().mean(dim=(1, 2))
for candidate in target], dim=1)
def source_provenance(repo):
repo = Path(repo)
paths = ["src/hub/backbones.py", "src/models/vision_transformer.py",
"src/models/predictor.py", "src/models/utils/patch_embed.py",
"src/models/utils/modules.py", "src/masks/utils.py",
"app/vjepa_2_1/models/vision_transformer.py",
"app/vjepa_2_1/models/predictor.py",
"app/vjepa_2_1/models/utils/modules.py"]
commit = subprocess.run(["git", "-C", str(repo), "rev-parse", "HEAD"],
text=True, capture_output=True, check=True, timeout=30).stdout.strip()
return {"repo_commit": commit,
"source_sha256": {p: content_hash(repo / p) for p in paths},
"automatic_hub_downloads": False}
def inspect_checkpoint(path):
state = torch.load(path, map_location="cpu", mmap=True, weights_only=True)
sections = {}
for name in ("encoder", "ema_encoder", "target_encoder", "predictor"):
if name not in state:
continue
weights = cleaned_weights(state[name])
keys = ("patch_embed.proj.weight", "predictor_embed.weight", "predictor_proj.weight")
sections[name] = {"tensors": len(weights),
"key_shapes": {key: list(weights[key].shape) for key in keys if key in weights}}
return {"path": str(Path(path).resolve()), "bytes": Path(path).stat().st_size,
"sha256": content_hash(path), "top_level_keys": list(state), "sections": sections}
def tiny_interface(repo, device):
add_official_repo(repo)
from src.models.vision_transformer import VisionTransformer
from src.models.predictor import VisionTransformerPredictor
plan = FramePlan(sample_frames=8, context_frames=4, score_start_frame=6,
score_end_frame=8, input_size=32)
encoder = VisionTransformer(img_size=(32, 32), num_frames=8, patch_size=16,
tubelet_size=2, embed_dim=96, depth=2, num_heads=4,
use_rope=True, use_sdpa=True).to(device)
predictor = VisionTransformerPredictor(img_size=(32, 32), num_frames=8,
patch_size=16, tubelet_size=2, embed_dim=96,
predictor_embed_dim=48, depth=2, num_heads=4,
use_rope=True, use_mask_tokens=True,
num_mask_tokens=2).to(device)
return PredictiveInterface(encoder, predictor, plan, target_encoder=encoder)
def load_pretrained_interface(repo, checkpoint, family, device, frames=8):
add_official_repo(repo)
from src.hub.backbones import vjepa2_vit_large, vjepa2_1_vit_base_384
state = torch.load(checkpoint, map_location="cpu", weights_only=True, mmap=True)
if family == "vjepa2":
encoder, predictor = vjepa2_vit_large(pretrained=False, num_frames=frames)
context_key, size = "target_encoder", 256
target_encoder = encoder
allowed_encoder, allowed_predictor = ("pos_embed",), ("predictor_pos_embed",)
elif family == "vjepa2.1-b":
encoder, predictor = vjepa2_1_vit_base_384(pretrained=False, num_frames=frames)
context_key, size = "ema_encoder", 384
target_encoder = None # Student width 768 is NOT the trained 1664-wide target.
allowed_encoder = allowed_predictor = ()
else:
raise ValueError(f"Unsupported family: {family}")
loading = {
"context_key": context_key,
"encoder": checked_load(encoder, state[context_key], allowed_encoder),
"predictor": checked_load(predictor, state["predictor"], allowed_predictor),
}
del state
encoder.to(device)
predictor.to(device)
if frames == 64:
plan = FramePlan(sample_frames=64, context_frames=52, score_start_frame=60,
score_end_frame=64, input_size=size)
elif frames == 8:
plan = FramePlan(sample_frames=8, context_frames=4, score_start_frame=6,
score_end_frame=8, input_size=size)
else:
raise ValueError("Contract checks support eight-frame smoke or the 64-frame pilot plan")
return PredictiveInterface(encoder, predictor, plan, target_encoder), loading
@torch.inference_mode()
def run_contract_checks(interface):
"""Check leakage, sensitivity, shape errors, and target ordering on noise."""
plan = interface.plan
device = next(interface.encoder.parameters()).device
video = torch.randn((1, 3, plan.sample_frames, plan.input_size, plan.input_size), device=device)
altered_future = video.clone()
altered_future[:, :, plan.context_frames:] = 2 * torch.randn_like(altered_future[:, :, plan.context_frames:]) + 3
observed = video[:, :, :plan.context_frames].clone()
context = interface._encode_masked_full_video(video)
alternate_context = interface._encode_masked_full_video(altered_future)
prediction = interface.predict_future(context)
alternate_prediction = interface.predict_future(alternate_context)
torch.testing.assert_close(context, alternate_context, rtol=0, atol=1e-6)
torch.testing.assert_close(prediction, alternate_prediction, rtol=0, atol=1e-6)
torch.testing.assert_close(context, interface.encode_context(observed), rtol=0, atol=1e-6)
changed_past = observed.clone()
changed_past[:, :, :2] = 3 * torch.randn_like(changed_past[:, :, :2])
changed_prediction = interface.predict_future(interface.encode_context(changed_past))
past_effect = float((prediction - changed_prediction).abs().max())
if past_effect <= 1e-6:
raise AssertionError("Predictor is insensitive to changed observed frames; invariant output is insufficient")
# Deliberately wrong comparator: encoding future first must be detected.
leaky_a = interface.encoder(video)[:, :plan.context_tokens]
leaky_b = interface.encoder(altered_future)[:, :plan.context_tokens]
leaky_effect = float((leaky_a - leaky_b).abs().max())
if leaky_effect <= 1e-6:
raise AssertionError("Leakage negative control was not detected")
try:
interface.encode_context(video)
except ValueError:
rejected_full_video = True
else:
raise AssertionError("Context API accepted a clip containing future frames")
result = {
"status": "passed",
"scope": "synthetic-noise software contract, not a perceptual or hidden-state result",
"frame_plan": asdict(plan),
"context_shape": list(context.shape),
"prediction_shape": list(prediction.shape),
"future_context_max_abs_difference": float((context - alternate_context).abs().max()),
"future_prediction_max_abs_difference": float((prediction - alternate_prediction).abs().max()),
"observed_past_prediction_max_abs_difference": past_effect,
"deliberately_leaky_encoder_max_abs_difference": leaky_effect,
"context_api_rejects_full_video": rejected_full_video,
"compatible_target_encoder_available": interface.target_encoder is not None,
}
if interface.target_encoder is not None:
suffixes = torch.randn((4, 3, plan.sample_frames-plan.context_frames,
plan.input_size, plan.input_size), device=device)
canonical = torch.zeros_like(observed)
targets = interface.encode_candidate_targets(canonical, suffixes)
roi = list(range(plan.spatial_tokens)) # Full frame is explicit, diagnostic only.
energies = interface.score_candidates(prediction, targets, roi)
order = torch.tensor([2, 0, 3, 1], device=device)
permuted = interface.score_candidates(prediction, targets[order], roi)
torch.testing.assert_close(permuted, energies[:, order], rtol=0, atol=1e-7)
try:
interface.score_candidates(prediction, targets[:, :, :-1], roi)
except ValueError:
pass
else:
raise AssertionError("Scoring accepted mismatched latent widths")
result.update(target_shape=list(targets.shape), energy_shape=list(energies.shape),
candidate_permutation_invariance=True, mismatched_width_rejected=True)
else:
try:
interface.encode_candidate_targets(observed, video[:, :, plan.context_frames:])
except ValueError:
result["scoring_without_teacher_rejected"] = True
else:
raise AssertionError("Distilled student was used as its own target")
result["visual_energy_scoring_status"] = "blocked_until_matching_teacher_is_available"
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--mode", choices=("tiny-contract", "inspect-checkpoint", "pretrained-contract"), required=True)
parser.add_argument("--repo", type=Path, default=Path(".local/vjepa2"))
parser.add_argument("--checkpoint", type=Path)
parser.add_argument("--family", choices=("vjepa2", "vjepa2.1-b"), default="vjepa2")
parser.add_argument("--device", choices=("cpu", "cuda"), default="cpu")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--threads", type=int, default=2)
parser.add_argument("--frames", type=int, choices=(8, 64), default=8)
args = parser.parse_args()
if args.output.exists():
parser.error("Refusing to overwrite an existing result")
if args.mode != "tiny-contract" and (args.checkpoint is None or not args.checkpoint.is_file()):
parser.error("An existing local checkpoint is required; downloads are never automatic")
if args.mode == "pretrained-contract" and (args.device != "cuda" or not os.environ.get("SLURM_JOB_ID")
or os.environ.get("SLURM_JOB_PARTITION") != "bulk"):
parser.error("Run pretrained contracts in a bulk Slurm GPU allocation")
if args.device == "cuda" and not torch.cuda.is_available():
parser.error("CUDA is unavailable")
torch.set_num_threads(args.threads)
torch.manual_seed(20261016)
torch.set_float32_matmul_precision("highest")
started = time.monotonic()
result = {"created_utc": datetime.now(timezone.utc).isoformat(),
"torch_version": torch.__version__, "mode": args.mode,
"device": args.device, "slurm_job_id": os.environ.get("SLURM_JOB_ID"),
"provenance": source_provenance(args.repo),
"implementation_sha256": {name: content_hash(Path(__file__).parent / name)
for name in ("evaluate_hidden_state.py", "hidden_state.py")}}
if args.mode == "inspect-checkpoint":
result["checkpoint"] = inspect_checkpoint(args.checkpoint)
else:
if args.mode == "tiny-contract":
interface = tiny_interface(args.repo, args.device)
result["weights"] = "random; official classes with reduced dimensions"
else:
print("Running reduced official-model contract before loading pretrained weights", flush=True)
tiny = tiny_interface(args.repo, args.device)
result["tiny_checks"] = run_contract_checks(tiny)
del tiny
print("Loading existing pretrained weights with explicit tensor checks", flush=True)
interface, loading = load_pretrained_interface(args.repo, args.checkpoint, args.family, args.device, args.frames)
result["loading"] = loading
result["checkpoint"] = inspect_checkpoint(args.checkpoint)
print("Running context/future/target contract checks", flush=True)
result["checks"] = run_contract_checks(interface)
result["elapsed_seconds"] = time.monotonic() - started
if args.device == "cuda":
result["gpu"] = torch.cuda.get_device_name()
result["peak_allocated_vram_bytes"] = torch.cuda.max_memory_allocated()
write_new_json(args.output, result)
print(json.dumps({"output": str(args.output), "status": result.get("checks", {}).get("status", "inspected"),
"elapsed_seconds": result["elapsed_seconds"]}), flush=True)
if __name__ == "__main__":
main()