#!/usr/bin/env python """ Stage-1 GATE metric: held-out displacement-reconstruction error of the predicted motion subspace U = f(X_eq), with the full diagnostic protocol needed before concluding anything from a single number: 1. SAME-GATE train-split eval (apples-to-apples vs the held-out number; the live training loop's mode_recon_rel_error uses different batching/masking and is NOT directly comparable to this script's per-protein full-MD-frame eval -- see HANDOFF discussion). 2. ALL-EPOCH sweep on held-out (checks for overfitting-with-training / picks the best checkpoint by validation instead of just reading the last one). 3. random / untrained U baselines, so a bare rel_error number has a floor to compare against: random = a random orthonormal K-dim subspace (no network, no X_eq dependence at all); untrained = a freshly-initialized LatentEncoder (same architecture/K, never trained) run on the real X_eq. 1 - r^2 (r = rel_error) is the fraction of MD displacement ENERGY explained by the K-dim subspace (Pythagorean identity for an orthogonal/ridge-lstsq projection). Report r AND 1-r^2 -- r alone overstates how bad/good a number is. NO-LEAKAGE CONTRACT --csv_path is REQUIRED (no default). This script never reads any other split's CSV and never touches the training dataloader. USAGE # single checkpoint, trained U, one split: python scripts/eval_held_out_mode_recon.py --run_dir RUN --csv_path CSV \ --cache_path CACHE --frames_per_protein 20 # all epochs, held-out, to see over/under-fitting across training: python scripts/eval_held_out_mode_recon.py --run_dir RUN --csv_path VAL_CSV \ --cache_path CACHE --all_epochs # random / untrained baselines (checkpoint choice is irrelevant for these # except --run_dir's config.yaml is used to build a same-K fresh encoder): python scripts/eval_held_out_mode_recon.py --run_dir RUN --csv_path VAL_CSV \ --cache_path CACHE --baseline random python scripts/eval_held_out_mode_recon.py --run_dir RUN --csv_path VAL_CSV \ --cache_path CACHE --baseline untrained """ import argparse import glob import os import sys import numpy as np import torch import mdtraj import pandas as pd from omegaconf import OmegaConf sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from bbflow.data.utils import frames_from_pdb, backbone_to_frames from bbflow.models.bbflow_module import BBFlowModule from bbflow.models.latent import LatentEncoder def pdb_name_variants(name): variants = {name} if "_" in name: variants.add(name.replace("_", "")) elif len(name) == 5: variants.add(f"{name[:4]}_{name[4]}") return variants def load_mean_disp_cache(cache_path): cache = torch.load(cache_path, map_location="cpu", weights_only=False) targets = cache["motion_targets"] if isinstance(cache, dict) and "motion_targets" in cache else cache out = {} for key, value in targets.items(): if "oracle_mean_disp" not in value: continue md = torch.as_tensor(value["oracle_mean_disp"], dtype=torch.float32) for name in pdb_name_variants(str(key)): out[name] = md return out def list_epoch_checkpoints(run_dir): return sorted(glob.glob(os.path.join(run_dir, "epoch:*.ckpt"))) def pick_checkpoint(run_dir, ckpt_name=None): if ckpt_name: return os.path.join(run_dir, ckpt_name) candidates = list_epoch_checkpoints(run_dir) if candidates: return candidates[-1] last = os.path.join(run_dir, "last.ckpt") if os.path.exists(last): return last raise FileNotFoundError(f"No epoch:*.ckpt or last.ckpt found in {run_dir}") def build_module(run_dir, device, ckpt_path=None): """Build BBFlowModule from run_dir's config.yaml. If ckpt_path is given, load its weights (the 'trained' condition). If None, leave the module at its from-scratch random init (the 'untrained' baseline: same architecture/K, never saw a gradient step).""" cfg_path = os.path.join(run_dir, "config.yaml") cfg = OmegaConf.load(cfg_path) module = BBFlowModule(cfg) if ckpt_path is not None: ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) state_dict = ckpt["state_dict"] if "state_dict" in ckpt else ckpt current_state = module.state_dict() compatible = { k: v for k, v in state_dict.items() if k in current_state and current_state[k].shape == v.shape } missing = len(current_state) - len(compatible) print(f"[load] {os.path.basename(ckpt_path)}: matched {len(compatible)}/{len(current_state)} " f"tensors ({missing} unmatched -- should be ~0 for a same-config checkpoint)") module.load_state_dict(compatible, strict=False) module.eval() module.to(device) return module def reload_checkpoint_(module, ckpt_path): """In-place weight swap for the all-epoch sweep -- avoids rebuilding the module (and re-reading config.yaml) 15 times.""" ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) state_dict = ckpt["state_dict"] if "state_dict" in ckpt else ckpt current_state = module.state_dict() compatible = { k: v for k, v in state_dict.items() if k in current_state and current_state[k].shape == v.shape } module.load_state_dict(compatible, strict=False) module.eval() def random_orthonormal_modes(N, K, device): """A random K-dim linear subspace of the full 3N-dim displacement space, via QR on a Gaussian matrix. Independent of X_eq and of any network -- the floor baseline: if trained-U barely beats this, U carries ~no learned information.""" g = torch.randn(N * 3, K, device=device) q, _ = torch.linalg.qr(g) # [3N, K], orthonormal columns return q.reshape(N, 3, K).permute(0, 2, 1) # -> [N, K, 3], matches u_global layout def sample_frame_indices(traj_path, n_frames): with mdtraj.open(traj_path) as f: total = len(f) if total <= 0: return [] n = min(n_frames, total) return np.linspace(0, total - 1, n, dtype=int).tolist() def load_md_frame_trans(traj_path, eq_path, frame_idx, seq_letters): conf = mdtraj.load_frame(traj_path, frame_idx, top=eq_path) N_atoms = conf.xyz[0, conf.top.select("name N"), :] * 10 CA_atoms = conf.xyz[0, conf.top.select("name CA"), :] * 10 C_atoms = conf.xyz[0, conf.top.select("name C"), :] * 10 data = backbone_to_frames(N_atoms, CA_atoms, C_atoms, seq_letters) return data["trans"] # [N, 3] def load_protein_cache(csv_path, mean_disp_cache, frames_per_protein, max_proteins, device, random_seed=None): """Load MD frames / eq structure / mean_disp ONCE per protein. Reused across every checkpoint/epoch/baseline evaluated against this CSV -- an all-epoch sweep does NOT re-read MD trajectories per epoch.""" csv = pd.read_csv(csv_path) if max_proteins: # NOTE: .iloc[:max_proteins] takes the CSV's first N rows, not a random # sample. If the CSV has any ordering (by length, difficulty, source...) # that subsets non-representatively. Pass random_seed to draw a real # random sample instead when comparing against a held-out split. if random_seed is not None: csv = csv.sample(n=min(max_proteins, len(csv)), random_state=random_seed) else: csv = csv.iloc[:max_proteins] proteins, skipped = [], [] for _, row in csv.iterrows(): name = row["name"] # Two CSV schemas exist: train (name, folder, pdb_path, ...) and # validation/test (name, pdb_path only). dirname(pdb_path) == folder in # both (verified against a train-CSV row). if "pdb_path" in row and pd.notna(row.get("pdb_path")): eq_path = row["pdb_path"] folder = os.path.dirname(eq_path) else: folder = row["folder"] eq_path = os.path.join(folder, f"{name}.pdb") traj_path = os.path.join(folder, f"{name}_R1.xtc") if not os.path.exists(traj_path): skipped.append((name, f"missing trajectory: {traj_path}")) continue mean_disp = None for variant in pdb_name_variants(name): if variant in mean_disp_cache: mean_disp = mean_disp_cache[variant] break if mean_disp is None: skipped.append((name, "no oracle_mean_disp in cache")) continue frame_idxs = sample_frame_indices(traj_path, frames_per_protein) if not frame_idxs: skipped.append((name, f"empty trajectory: {traj_path}")) continue trans_eq, rotmats_eq, seq_onehot, _ = frames_from_pdb(eq_path) seq_letters = list(mdtraj.load(eq_path).top.to_fasta()[0]) trans_1 = torch.stack( [load_md_frame_trans(traj_path, eq_path, i, seq_letters) for i in frame_idxs], dim=0 ).to(device) # [B, N, 3] proteins.append({ "name": name, "N": trans_eq.shape[0], "trans_eq": trans_eq.to(device), "rotmats_eq": rotmats_eq.to(device), "seq_onehot": seq_onehot.to(device), "trans_1": trans_1, "mean_disp": mean_disp.to(device), }) return proteins, skipped def eval_cache(host_encoder, proteins, device, baseline, source_module=None, num_modes=None): """host_encoder: a LatentEncoder instance used for the projection math (frame_condition_from_projection) -- its ridge/detach hyperparameters, NOT necessarily the source of u_global. baseline: 'trained' (u_global from source_module.latent_encoder, i.e. the loaded checkpoint), 'untrained' (u_global from host_encoder itself, freshly initialized, never loaded any checkpoint), 'random' (u_global = random orthonormal subspace, no network at all).""" per_protein = [] for p in proteins: B = p["trans_1"].shape[0] N = p["N"] res_mask_1 = torch.ones(1, N, device=device) with torch.no_grad(): if baseline == "random": u1 = random_orthonormal_modes(N, num_modes, device)[None] # [1,N,K,3] else: src = source_module.latent_encoder if baseline == "trained" else host_encoder prior_condition_1, _ = src.forward_prior( p["trans_eq"][None], p["rotmats_eq"][None], p["seq_onehot"][None], res_mask_1 ) u1 = prior_condition_1["u_global"] u_b = LatentEncoder.repeat_condition({"u_global": u1}, B)["u_global"] trans_eq_b = p["trans_eq"][None].expand(B, -1, -1) rotmats_eq_b = p["rotmats_eq"][None].expand(B, -1, -1, -1) res_mask_b = torch.ones(B, N, device=device) condition, _ = host_encoder.frame_condition_from_projection( p["trans_1"], trans_eq_b, rotmats_eq_b, res_mask_b, {"u_global": u_b}, mean_disp=p["mean_disp"], ) rel_error = condition["projection_recon_rel_error"].detach().cpu().numpy() per_protein.append((p["name"], float(np.mean(rel_error)))) return per_protein def report(per_protein, label): if not per_protein: print(f"[gate] {label}: NO proteins evaluated.") return values = np.array([v for _, v in per_protein]) energy = 1.0 - values ** 2 print(f"[gate] {label}") print(f" rel_error mean={values.mean():.4f} median={np.median(values):.4f}") print(f" energy(1-r^2) mean={energy.mean():.4f} median={np.median(energy):.4f} " f"(fraction of MD displacement variance explained)") worst = sorted(per_protein, key=lambda x: -x[1])[:5] print(f" worst5 = {worst}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--run_dir", required=True) ap.add_argument("--ckpt_name", default=None, help="single-checkpoint mode: default latest epoch:*.ckpt") ap.add_argument("--all_epochs", action="store_true", help="sweep every epoch:*.ckpt in run_dir") ap.add_argument("--baseline", choices=["trained", "untrained", "random"], default="trained") ap.add_argument("--csv_path", required=True, help="EXACT split to evaluate. Never pass a mix of splits.") ap.add_argument("--cache_path", required=True, help="motion-target cache with oracle_mean_disp") ap.add_argument("--frames_per_protein", type=int, default=20) ap.add_argument("--max_proteins", type=int, default=None) ap.add_argument("--random_seed", type=int, default=None, help="if set with --max_proteins, draw a RANDOM sample of that many " "rows instead of the CSV's first N (default .iloc[:N] is order-biased)") ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") args = ap.parse_args() split_name = os.path.basename(args.csv_path) print(f"[gate] split file: {args.csv_path} baseline={args.baseline}") mean_disp_cache = load_mean_disp_cache(args.cache_path) proteins, skipped = load_protein_cache( args.csv_path, mean_disp_cache, args.frames_per_protein, args.max_proteins, args.device, random_seed=args.random_seed, ) print(f"[gate] loaded {len(proteins)} proteins, skipped {len(skipped)}") for name, err in skipped: print(f" SKIP {name}: {err}") if not proteins: print("[gate] nothing to evaluate.") return cfg = OmegaConf.load(os.path.join(args.run_dir, "config.yaml")) num_modes = int(cfg.latent.num_modes) if args.baseline == "random": host = LatentEncoder(cfg.latent).to(args.device).eval() per_protein = eval_cache(host, proteins, args.device, "random", num_modes=num_modes) report(per_protein, f"{split_name} K={num_modes} baseline=random") return if args.baseline == "untrained": host = LatentEncoder(cfg.latent).to(args.device).eval() per_protein = eval_cache(host, proteins, args.device, "untrained") report(per_protein, f"{split_name} K={num_modes} baseline=untrained") return # baseline == "trained" if args.all_epochs: ckpts = list_epoch_checkpoints(args.run_dir) if not ckpts: print(f"[gate] no epoch:*.ckpt found in {args.run_dir}") return module = build_module(args.run_dir, args.device, ckpt_path=ckpts[0]) for ckpt_path in ckpts: reload_checkpoint_(module, ckpt_path) per_protein = eval_cache(module.latent_encoder, proteins, args.device, "trained", source_module=module) epoch_tag = os.path.basename(ckpt_path) report(per_protein, f"{split_name} {epoch_tag}") else: ckpt_path = pick_checkpoint(args.run_dir, args.ckpt_name) module = build_module(args.run_dir, args.device, ckpt_path=ckpt_path) per_protein = eval_cache(module.latent_encoder, proteins, args.device, "trained", source_module=module) report(per_protein, f"{split_name} {os.path.basename(ckpt_path)}") if __name__ == "__main__": main()