File size: 15,239 Bytes
5b2e6c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/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()