Download bbflow_base/scripts/audit_condition_forward_paths.py from hanghang214/data_transfer: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/audit_condition_forward_paths.py
- Command line
-
hf download hf://datasets/hanghang214/data_transfer/bbflow_base/scripts/audit_condition_forward_paths.py
-
curl -L -o audit_condition_forward_paths.py https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/audit_condition_forward_paths.py
16.5 kB
| #!/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() | |