data_transfer / bbflow_base /scripts /audit_condition_sign_loss.py
hanghang214's picture
Add files using upload-large-folder tool
5b2e6c5 verified
Raw History Blame Contribute Delete
11.8 kB
#!/usr/bin/env python
import argparse
import json
import math
import sys
from pathlib import Path
import mdtraj
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.pdb_dataloader_bbflow import PDBDatasetBBFlow
from bbflow.models.bbflow_module import BBFlowModule
def normalize_csv(csv_path):
df = pd.read_csv(csv_path)
if "folder" not in df.columns:
if "pdb_path" not in df.columns:
raise RuntimeError(f"{csv_path} has neither folder nor pdb_path")
df = df.copy()
df["folder"] = df["pdb_path"].map(lambda x: str(Path(str(x)).parent))
return df
def load_module(ckpt_path, device):
ckpt_path = Path(ckpt_path)
cfg_path = ckpt_path.with_name("config.yaml")
if not cfg_path.exists():
raise FileNotFoundError(f"Missing config next to checkpoint: {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
module = BBFlowModule(cfg)
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
current = module.state_dict()
compatible = {
k: v for k, v in ckpt["state_dict"].items()
if k in current and current[k].shape == v.shape
}
module.load_state_dict(compatible, strict=False)
module.to(device)
module.eval()
return module
def infer_num_frames(row):
for key in ["num_conformations", "num_frames", "n_frames", "traj_num_frames"]:
if key in row and pd.notna(row[key]):
return int(row[key])
name = str(row["name"])
folder = Path(str(row["folder"]))
xtc = folder / f"{name}_R1.xtc"
if not xtc.exists():
raise FileNotFoundError(f"Missing trajectory: {xtc}")
with mdtraj.open(str(xtc)) as handle:
return int(handle.n_frames if hasattr(handle, "n_frames") else len(handle))
def move_item(item, device):
out = {}
for k, v in item.items():
out[k] = v[None].to(device) if torch.is_tensor(v) else v
return out
def mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device):
disps = []
for fid in frame_ids:
item = move_item(dataset[(protein_idx, 0, int(fid))], device)
mask = torch.ones_like(item["trans_equilibrium"][..., 0])
disp = module.latent_encoder.relative_displacement(
item["trans_1"].float(),
item["trans_equilibrium"].float(),
mask,
)
disps.append(disp)
return torch.cat(disps, dim=0).mean(dim=0, keepdim=True)
def coeff_for_frame(module, dataset, protein_idx, frame_id, prior, mean_disp, device):
item = move_item(dataset[(protein_idx, 0, int(frame_id))], device)
cond, coeff = module.latent_encoder.frame_condition_from_projection(
item["trans_1"],
item["trans_equilibrium"],
item["rotmats_equilibrium"],
torch.ones_like(item["trans_equilibrium"][..., 0]),
prior,
mean_disp=mean_disp,
)
return cond, coeff.detach().float()
def rel_l2(a, b):
a = a.detach().float()
b = b.detach().float().to(a.device)
return float(((a - b).norm() / a.norm().clamp_min(1e-8)).detach().cpu())
def cosine(a, b):
a = a.detach().float().reshape(-1)
b = b.detach().float().reshape(-1).to(a.device)
return float(((a * b).sum() / (a.norm().clamp_min(1e-8) * b.norm().clamp_min(1e-8))).detach().cpu())
def sign_flip_fraction(a, b):
a = a.detach().float().reshape(-1)
b = b.detach().float().reshape(-1).to(a.device)
valid = (a.abs() > 1e-8) & (b.abs() > 1e-8)
if valid.sum() == 0:
return float("nan")
return float(((a[valid] * b[valid]) < 0).float().mean().detach().cpu())
def condition_for_coeff(module, prior, coeff, item):
return module.latent_encoder.condition_from_mode_coefficients(
prior["u_global"],
coeff,
item["rotmats_equilibrium"],
torch.ones_like(item["trans_equilibrium"][..., 0]),
extra={
key: prior[key]
for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"]
if key in prior
},
)
def selected_rows_from_matched(matched_csv, dataset):
matched = pd.read_csv(matched_csv)
by_name = {str(name): i for i, name in enumerate(dataset.pdb_names)}
rows = []
for _, r in matched.iterrows():
name = str(r["pdb_name"])
if name not in by_name:
continue
if "frame_a" not in r or "frame_b" not in r:
raise RuntimeError("matched_csv must contain frame_a and frame_b columns")
rows.append((by_name[name], r))
return rows
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_mean_frames", type=int, default=6)
args = ap.parse_args()
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
device = torch.device(args.device if args.device.startswith("cuda") and torch.cuda.is_available() else "cpu")
module = load_module(args.ckpt_path, device)
df = normalize_csv(args.csv_path)
dataset = PDBDatasetBBFlow(csv=df)
matched_rows = selected_rows_from_matched(args.matched_csv, dataset)
print(f"[audit] matched rows loaded: {len(matched_rows)}", flush=True)
rows = []
with torch.no_grad():
for protein_idx, matched in matched_rows:
meta = dataset.csv.iloc[protein_idx]
name = str(meta["name"])
total = infer_num_frames(meta)
# Reconstruct the same mean-disp convention used by earlier diagnostics:
# spread frames across trajectory. This is only for aggregate testing.
frame_grid = sorted(set(np.linspace(0, total - 1, args.num_mean_frames, dtype=int).tolist()))
frame_a = int(matched["frame_a"])
frame_b = int(matched["frame_b"])
for fid in [frame_a, frame_b]:
if fid not in frame_grid:
frame_grid.append(fid)
frame_grid = sorted(set(frame_grid))
eq_item = move_item(dataset[(protein_idx, 0, frame_grid[0])], device)
mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0])
prior, _ = module.latent_encoder.forward_prior(
eq_item["trans_equilibrium"],
eq_item["rotmats_equilibrium"],
eq_item["seq"],
mask,
)
mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_grid, device)
cond_a, coeff_a = coeff_for_frame(module, dataset, protein_idx, frame_a, prior, mean_disp, device)
cond_b, coeff_b = coeff_for_frame(module, dataset, protein_idx, frame_b, prior, mean_disp, device)
# Exact sign-flip audit on condition tensors for coeff_a vs -coeff_a.
cond_pos = condition_for_coeff(module, prior, coeff_a, eq_item)
cond_neg = condition_for_coeff(module, prior, -coeff_a, eq_item)
# Direct a-vs-b condition distance.
even_keys = ["node_cond", "edge_cond", "disp_edge_cond"]
odd_keys = ["disp_node_cond"]
row = {
"pdb_name": name,
"frame_a": frame_a,
"frame_b": frame_b,
"coeff_cos_ab": cosine(coeff_a, coeff_b),
"coeff_sign_flip_frac_ab": sign_flip_fraction(coeff_a, coeff_b),
"coeff_norm_ratio_b_over_a": float((coeff_b.norm() / coeff_a.norm().clamp_min(1e-8)).detach().cpu()),
"a_condition_correct_fraction": float(matched.get("a_condition_correct_fraction", float("nan"))),
"b_condition_correct_fraction": float(matched.get("b_condition_correct_fraction", float("nan"))),
"mean_correct_fraction": float(matched.get("mean_correct_fraction", float("nan"))),
}
for key in even_keys + odd_keys:
row[f"flip_rel_l2_{key}"] = rel_l2(cond_pos[key], cond_neg[key])
row[f"ab_rel_l2_{key}"] = rel_l2(cond_a[key], cond_b[key])
rows.append(row)
print(f"[audit] {name} done", flush=True)
result = pd.DataFrame(rows)
result.to_csv(out_dir / "condition_sign_loss_audit.csv", index=False)
summary = {
"n": int(len(result)),
"coeff_cos_ab_mean": float(result["coeff_cos_ab"].mean()),
"coeff_cos_ab_median": float(result["coeff_cos_ab"].median()),
"coeff_sign_flip_frac_mean": float(result["coeff_sign_flip_frac_ab"].mean()),
"b_correct_mean": float(result["b_condition_correct_fraction"].mean()),
"a_correct_mean": float(result["a_condition_correct_fraction"].mean()),
"mean_correct_mean": float(result["mean_correct_fraction"].mean()),
}
# Static exactness: c vs -c should leave even paths almost unchanged and flip linear path.
for key in ["node_cond", "edge_cond", "disp_edge_cond", "disp_node_cond"]:
summary[f"flip_rel_l2_{key}_mean"] = float(result[f"flip_rel_l2_{key}"].mean())
summary[f"flip_rel_l2_{key}_median"] = float(result[f"flip_rel_l2_{key}"].median())
# Correlations. No per-protein story, only aggregate statistics.
corr_cols = [
"b_condition_correct_fraction",
"a_condition_correct_fraction",
"mean_correct_fraction",
]
for y in corr_cols:
valid = result[["coeff_cos_ab", "coeff_sign_flip_frac_ab", y]].dropna()
if len(valid) >= 3:
summary[f"pearson_coeff_cos_vs_{y}"] = float(valid["coeff_cos_ab"].corr(valid[y], method="pearson"))
summary[f"spearman_coeff_cos_vs_{y}"] = float(valid["coeff_cos_ab"].corr(valid[y], method="spearman"))
summary[f"pearson_signflip_vs_{y}"] = float(valid["coeff_sign_flip_frac_ab"].corr(valid[y], method="pearson"))
summary[f"spearman_signflip_vs_{y}"] = float(valid["coeff_sign_flip_frac_ab"].corr(valid[y], method="spearman"))
# Distribution bins, still aggregate.
bins = [-1.01, -0.5, 0.0, 0.5, 1.01]
labels = ["cos<-0.5", "-0.5<=cos<0", "0<=cos<0.5", "cos>=0.5"]
result["coeff_cos_bin"] = pd.cut(result["coeff_cos_ab"], bins=bins, labels=labels)
grouped = result.groupby("coeff_cos_bin", observed=False).agg(
n=("pdb_name", "count"),
b_correct_mean=("b_condition_correct_fraction", "mean"),
a_correct_mean=("a_condition_correct_fraction", "mean"),
mean_correct=("mean_correct_fraction", "mean"),
signflip_mean=("coeff_sign_flip_frac_ab", "mean"),
).reset_index()
grouped.to_csv(out_dir / "condition_sign_loss_bins.csv", index=False)
(out_dir / "condition_sign_loss_summary.json").write_text(
json.dumps(summary, indent=2, sort_keys=True) + "\n"
)
print("\n=== condition sign-loss summary ===")
print(json.dumps(summary, indent=2, sort_keys=True))
print("\n=== coeff cosine bins ===")
print(grouped.to_string(index=False))
print("\nSaved:", out_dir)
if __name__ == "__main__":
main()