File size: 16,520 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 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | #!/usr/bin/env python
"""Forward audit for signed vs unsigned latent-condition paths.
Diagnostic only: no training, no source mutation, no checkpoint mutation.
This script uses matched frame pairs and measures, on the same forward batch:
* unsigned adapter outputs vs signed adapter outputs;
* cosine between unsigned and signed adapter outputs after projection;
* FiLM gamma/beta amplitudes, separated;
* c -> -c effects versus c_a -> c_b effects at final update and pred_trans.
"""
import argparse
import copy
import json
from pathlib import Path
import sys
import numpy as np
import pandas as pd
import torch
from omegaconf import OmegaConf
REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
from bbflow.data.interpolant_bbflow import InterpolantBBFlow
from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow
from bbflow.models.bbflow_module import BBFlowModule
from scripts.diagnose_condition_interface import (
frame_indices_for_row,
mean_disp_from_frames,
move_item_to_device,
build_cstar_condition,
)
def load_module(ckpt_path, device, num_timesteps=None):
ckpt_path = Path(ckpt_path)
cfg_path = ckpt_path.with_name("config.yaml")
if not cfg_path.exists():
raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}")
infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml")
ckpt_cfg = OmegaConf.load(cfg_path)
OmegaConf.set_struct(infer_cfg, False)
OmegaConf.set_struct(ckpt_cfg, False)
cfg = OmegaConf.merge(infer_cfg, ckpt_cfg)
cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior
cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional
cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot
cfg.inference.interpolant.use_tqdm = False
cfg.model.embed = ckpt_cfg.model.embed
if num_timesteps is not None:
cfg.inference.interpolant.rots.num_timesteps = int(num_timesteps)
cfg.inference.interpolant.trans.num_timesteps = int(num_timesteps)
module = BBFlowModule(cfg)
checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False)
current = module.state_dict()
compatible = {
key: value
for key, value in checkpoint["state_dict"].items()
if key in current and current[key].shape == value.shape
}
missing, unexpected = module.load_state_dict(compatible, strict=False)
module.to(device)
module.eval()
interpolant = InterpolantBBFlow(cfg.inference.interpolant)
interpolant.set_device(device)
module.interpolant = interpolant
return module, {
"loaded": len(compatible),
"missing": len(missing),
"unexpected": len(unexpected),
}
def normalize_csv(df):
df = df.copy()
if "name" not in df.columns and "pdb_name" in df.columns:
df["name"] = df["pdb_name"]
if "folder" not in df.columns and "pdb_path" in df.columns:
df["folder"] = df["pdb_path"].map(lambda p: str(Path(str(p)).parent))
return df
def clone_condition(condition):
return {
key: value.clone() if torch.is_tensor(value) else copy.deepcopy(value)
for key, value in condition.items()
}
def condition_from_coeff(module, prior, coeff, rotmats_eq, res_mask):
extra = {
key: prior[key]
for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"]
if key in prior
}
return module.latent_encoder.condition_from_mode_coefficients(
prior["u_global"],
coeff,
rotmats_eq,
res_mask,
extra=extra,
include_statistics=False,
)
def masked_mean_abs(tensor, mask=None, edge=False):
x = tensor.detach().float().abs()
if mask is None:
return float(x.mean().cpu().item())
m = mask.float()
if edge:
m = m[:, :, None] * m[:, None, :]
while m.dim() < x.dim():
m = m[..., None]
else:
while m.dim() < x.dim():
m = m[..., None]
return float(((x * m).sum() / m.sum().clamp_min(1.0)).cpu().item())
def rms(tensor, mask=None, edge=False):
x = tensor.detach().float().square()
if mask is None:
return float(x.mean().sqrt().cpu().item())
m = mask.float()
if edge:
m = m[:, :, None] * m[:, None, :]
while m.dim() < x.dim():
m = m[..., None]
else:
while m.dim() < x.dim():
m = m[..., None]
return float(((x * m).sum() / m.sum().clamp_min(1.0)).sqrt().cpu().item())
def flat_cosine(a, b, mask=None, edge=False):
aa = a.detach().float()
bb = b.detach().float().to(device=aa.device)
if mask is not None:
m = mask.float()
if edge:
m = m[:, :, None] * m[:, None, :]
while m.dim() < aa.dim():
m = m[..., None]
else:
while m.dim() < aa.dim():
m = m[..., None]
aa = aa * m
bb = bb * m
aa = aa.reshape(-1)
bb = bb.reshape(-1)
denom = aa.norm().clamp_min(1e-8) * bb.norm().clamp_min(1e-8)
return float((aa * bb).sum().div(denom).cpu().item())
def rel_delta(reference, changed, mask=None, edge=False):
denom = masked_mean_abs(reference, mask=mask, edge=edge)
delta = masked_mean_abs(changed - reference, mask=mask, edge=edge)
return float(delta / max(denom, 1e-8))
def adapter_outputs(module, condition):
embedder = module.model.embedder
return {
"z_node": embedder.z_node_adapter(condition["node_cond"]),
"disp_node": embedder.disp_node_adapter(condition["disp_node_cond"]),
"z_edge": embedder.z_edge_adapter(condition["edge_cond"]),
"disp_edge": embedder.disp_edge_adapter(condition["disp_edge_cond"]),
}
def film_outputs(module, condition):
model = module.model
if not getattr(model, "inject_film", False):
return None
cond = condition["node_cond"]
gamma_beta = model.film_mlp(cond)
gamma, beta = torch.chunk(gamma_beta, 2, dim=-1)
return {"gamma": gamma, "beta": beta}
def build_forward_batch(module, item, condition, seed):
device = item["trans_equilibrium"].device
trans_eq = item["trans_equilibrium"]
rotmats_eq = item["rotmats_equilibrium"]
seq = item["seq"]
res_mask = torch.ones_like(trans_eq[..., 0])
_, num_res = trans_eq.shape[:2]
torch.manual_seed(int(seed))
np.random.seed(int(seed) % (2**32 - 1))
trans_t, rotmats_t = module.interpolant.sample_from_prior(
1, int(num_res), trans_eq, rotmats_eq
)
return {
"res_mask": res_mask,
"trans_equilibrium": trans_eq,
"rotmats_equilibrium": rotmats_eq,
"seq": seq,
"trans_t": trans_t,
"rotmats_t": rotmats_t,
"t": torch.full(
(1, 1),
module.interpolant._cfg.min_t,
device=device,
dtype=trans_eq.dtype,
),
"z": condition,
}
def run_model_capture(module, base_batch, condition):
captured = {}
model = module.model
last_block = model._gfa_conf.num_blocks - 1
last_update = model.trunk[f"bb_update_{last_block}"]
def pre_hook(_mod, args):
captured["final_update_node_embed"] = args[0].detach().clone()
handle = last_update.register_forward_pre_hook(pre_hook)
batch = dict(base_batch)
batch["z"] = condition
try:
with torch.no_grad():
out = model(batch)
finally:
handle.remove()
return {
"final_update_node_embed": captured["final_update_node_embed"],
"pred_trans": out["pred_trans"].detach().clone(),
}
def summarize_rows(df, value_cols):
out = {}
for col in value_cols:
vals = pd.to_numeric(df[col], errors="coerce").replace([np.inf, -np.inf], np.nan).dropna()
if len(vals) == 0:
continue
out[col] = {
"n": int(len(vals)),
"mean": float(vals.mean()),
"median": float(vals.median()),
"min": float(vals.min()),
"max": float(vals.max()),
}
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt_path", required=True)
ap.add_argument("--csv_path", required=True)
ap.add_argument("--matched_csv", required=True)
ap.add_argument("--out_dir", required=True)
ap.add_argument("--device", default="cuda")
ap.add_argument("--num_frames", type=int, default=6)
ap.add_argument("--seed", type=int, default=20260712)
ap.add_argument("--num_timesteps", type=int, default=20)
args = ap.parse_args()
device = torch.device(args.device if (args.device == "cpu" or torch.cuda.is_available()) else "cpu")
module, load_info = load_module(args.ckpt_path, device, args.num_timesteps)
df = normalize_csv(pd.read_csv(args.csv_path))
matched = pd.read_csv(args.matched_csv)
dataset = PDBDatasetBBFlow(df)
by_name = {str(name): idx for idx, name in enumerate(dataset.pdb_names)}
rows = []
for row_idx, matched_row in matched.iterrows():
name = str(matched_row["pdb_name"])
if name not in by_name:
raise ValueError(f"pdb_name from matched_csv not found in csv_path: {name}")
protein_idx = by_name[name]
csv_row = dataset.csv.iloc[protein_idx]
frame_ids = frame_indices_for_row(csv_row, args.num_frames)
a_id = int(matched_row["frame_a"])
b_id = int(matched_row["frame_b"])
item_a = move_item_to_device(dataset[(protein_idx, 0, a_id)], device)
item_b = move_item_to_device(dataset[(protein_idx, 0, b_id)], device)
res_mask = torch.ones_like(item_a["trans_equilibrium"][..., 0])
with torch.no_grad():
prior, _ = module.latent_encoder.forward_prior(
item_a["trans_equilibrium"],
item_a["rotmats_equilibrium"],
item_a["seq"],
res_mask,
)
mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device)
cond_a, coeff_a = build_cstar_condition(module, item_a, prior, mean_disp=mean_disp)
cond_b, coeff_b = build_cstar_condition(module, item_b, prior, mean_disp=mean_disp)
cond_neg_a = condition_from_coeff(
module,
prior,
-coeff_a,
item_a["rotmats_equilibrium"],
res_mask,
)
adapters_a = adapter_outputs(module, cond_a)
film_a = film_outputs(module, cond_a)
film_neg_a = film_outputs(module, cond_neg_a)
film_b = film_outputs(module, cond_b)
base_batch = build_forward_batch(module, item_a, cond_a, args.seed + int(row_idx))
forward_a = run_model_capture(module, base_batch, cond_a)
forward_neg_a = run_model_capture(module, base_batch, cond_neg_a)
forward_b = run_model_capture(module, base_batch, cond_b)
record = {
"pdb_name": name,
"frame_a": a_id,
"frame_b": b_id,
"frame_gap": abs(b_id - a_id),
"num_res": int(item_a["trans_equilibrium"].shape[1]),
"coeff_cos_ab": flat_cosine(coeff_a, coeff_b),
"coeff_signflip_frac_ab": float(((coeff_a * coeff_b) < 0).float().mean().detach().cpu().item()),
"node_unsigned_abs": masked_mean_abs(adapters_a["z_node"], res_mask),
"node_signed_abs": masked_mean_abs(adapters_a["disp_node"], res_mask),
"node_signed_over_unsigned": masked_mean_abs(adapters_a["disp_node"], res_mask) / max(masked_mean_abs(adapters_a["z_node"], res_mask), 1e-8),
"node_adapter_cosine": flat_cosine(adapters_a["z_node"], adapters_a["disp_node"], res_mask),
"edge_unsigned_abs": masked_mean_abs(adapters_a["z_edge"], res_mask, edge=True),
"edge_signed_abs": masked_mean_abs(adapters_a["disp_edge"], res_mask, edge=True),
"edge_signed_over_unsigned": masked_mean_abs(adapters_a["disp_edge"], res_mask, edge=True) / max(masked_mean_abs(adapters_a["z_edge"], res_mask, edge=True), 1e-8),
"edge_adapter_cosine": flat_cosine(adapters_a["z_edge"], adapters_a["disp_edge"], res_mask, edge=True),
"final_embed_rel_delta_signflip": rel_delta(
forward_a["final_update_node_embed"], forward_neg_a["final_update_node_embed"], res_mask
),
"final_embed_rel_delta_ab": rel_delta(
forward_a["final_update_node_embed"], forward_b["final_update_node_embed"], res_mask
),
"pred_trans_rel_delta_signflip": rel_delta(forward_a["pred_trans"], forward_neg_a["pred_trans"], res_mask),
"pred_trans_rel_delta_ab": rel_delta(forward_a["pred_trans"], forward_b["pred_trans"], res_mask),
"pred_trans_signflip_over_ab": rel_delta(forward_a["pred_trans"], forward_neg_a["pred_trans"], res_mask) / max(rel_delta(forward_a["pred_trans"], forward_b["pred_trans"], res_mask), 1e-8),
"final_embed_signflip_over_ab": rel_delta(forward_a["final_update_node_embed"], forward_neg_a["final_update_node_embed"], res_mask) / max(rel_delta(forward_a["final_update_node_embed"], forward_b["final_update_node_embed"], res_mask), 1e-8),
}
if film_a is not None:
for key in ["gamma", "beta"]:
record[f"film_{key}_abs"] = masked_mean_abs(film_a[key], res_mask)
record[f"film_{key}_rms"] = rms(film_a[key], res_mask)
record[f"film_{key}_rel_delta_signflip"] = rel_delta(film_a[key], film_neg_a[key], res_mask)
record[f"film_{key}_rel_delta_ab"] = rel_delta(film_a[key], film_b[key], res_mask)
rows.append(record)
result = pd.DataFrame(rows)
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
result.to_csv(out_dir / "condition_forward_audit_rows.csv", index=False)
value_cols = [
"node_unsigned_abs",
"node_signed_abs",
"node_signed_over_unsigned",
"node_adapter_cosine",
"edge_unsigned_abs",
"edge_signed_abs",
"edge_signed_over_unsigned",
"edge_adapter_cosine",
"film_gamma_abs",
"film_gamma_rms",
"film_gamma_rel_delta_signflip",
"film_gamma_rel_delta_ab",
"film_beta_abs",
"film_beta_rms",
"film_beta_rel_delta_signflip",
"film_beta_rel_delta_ab",
"final_embed_rel_delta_signflip",
"final_embed_rel_delta_ab",
"final_embed_signflip_over_ab",
"pred_trans_rel_delta_signflip",
"pred_trans_rel_delta_ab",
"pred_trans_signflip_over_ab",
]
value_cols = [c for c in value_cols if c in result.columns]
summary = {
"load_info": load_info,
"n": int(len(result)),
"ckpt_path": str(args.ckpt_path),
"matched_csv": str(args.matched_csv),
"metrics": summarize_rows(result, value_cols),
}
(out_dir / "condition_forward_audit_summary.json").write_text(
json.dumps(summary, indent=2),
encoding="utf-8",
)
compact_cols = [
"node_signed_over_unsigned",
"node_adapter_cosine",
"edge_signed_over_unsigned",
"edge_adapter_cosine",
"film_gamma_abs",
"film_beta_abs",
"film_gamma_rel_delta_signflip",
"film_gamma_rel_delta_ab",
"film_beta_rel_delta_signflip",
"film_beta_rel_delta_ab",
"final_embed_signflip_over_ab",
"pred_trans_signflip_over_ab",
]
compact_cols = [c for c in compact_cols if c in result.columns]
compact = result[compact_cols].agg(["mean", "median", "min", "max"]).T
compact.to_csv(out_dir / "condition_forward_audit_compact.csv")
print("===== forward audit compact =====")
print(compact.to_string())
print("\n===== key interpretation helpers =====")
print(json.dumps({
"n": int(len(result)),
"film_unsigned_expected": "film_*_rel_delta_signflip should be 0 or near 0 because FiLM sees node_cond=|c|",
"signflip_vs_ab": "ratios near 1 mean c->-c changes output as much as switching to c_b; ratios far below 1 mean sign direction is weak",
"adapter_cosine": "high positive cosine means signed and unsigned adapter outputs are aligned/redundant after projection",
}, indent=2))
print("\nSaved:", out_dir)
if __name__ == "__main__":
main()
|