Download bbflow_base/scripts/diagnose_injection_amplitude.py from hanghang214/data_transfer: direct link, hf CLI and curl.
- Browser
- Download file 7.97 kB
-
https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/diagnose_injection_amplitude.py
- Command line
-
hf download hf://datasets/hanghang214/data_transfer/bbflow_base/scripts/diagnose_injection_amplitude.py
-
curl -L -o diagnose_injection_amplitude.py https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/diagnose_injection_amplitude.py
7.97 kB
| #!/usr/bin/env python | |
| """Diagnose whether latent condition adapters grew and inject nontrivial amplitude.""" | |
| import argparse | |
| 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.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb | |
| from bbflow.models.bbflow_module import BBFlowModule | |
| 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 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 | |
| module = BBFlowModule(cfg) | |
| ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) | |
| current_state = module.state_dict() | |
| compatible_state = { | |
| key: value for key, value in ckpt["state_dict"].items() | |
| if key in current_state and current_state[key].shape == value.shape | |
| } | |
| missing, unexpected = module.load_state_dict(compatible_state, strict=False) | |
| module.to(device) | |
| module.eval() | |
| return module, cfg, {"loaded": len(compatible_state), "missing": len(missing), "unexpected": len(unexpected)} | |
| def select_item(dataset, pdb_name): | |
| if pdb_name: | |
| for idx, name in enumerate(dataset.pdb_names): | |
| if str(name) == pdb_name: | |
| return dataset[idx] | |
| raise ValueError(f"pdb_name not found: {pdb_name}") | |
| return dataset[0] | |
| def last_linear_stats(module): | |
| if module is None: | |
| return None | |
| last = module[-1] | |
| return { | |
| "weight_norm": float(last.weight.detach().float().norm().cpu().item()), | |
| "weight_abs_mean": float(last.weight.detach().float().abs().mean().cpu().item()), | |
| "weight_abs_max": float(last.weight.detach().float().abs().max().cpu().item()), | |
| "bias_norm": float(last.bias.detach().float().norm().cpu().item()) if last.bias is not None else 0.0, | |
| "bias_abs_mean": float(last.bias.detach().float().abs().mean().cpu().item()) if last.bias is not None else 0.0, | |
| "bias_abs_max": float(last.bias.detach().float().abs().max().cpu().item()) if last.bias is not None else 0.0, | |
| } | |
| def mean_abs(tensor): | |
| return float(tensor.detach().float().abs().mean().cpu().item()) | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--ckpt_path", required=True) | |
| parser.add_argument("--csv_path", required=True) | |
| parser.add_argument("--pdb_name", default="") | |
| parser.add_argument("--device", default="cuda") | |
| parser.add_argument("--out_path", default="") | |
| args = parser.parse_args() | |
| device = torch.device(args.device if (args.device == "cpu" or torch.cuda.is_available()) else "cpu") | |
| module, cfg, load_info = load_module(args.ckpt_path, device) | |
| module.interpolant.set_device(device) | |
| df = pd.read_csv(args.csv_path) | |
| dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) | |
| item = select_item(dataset, args.pdb_name) | |
| trans_eq = item["trans_equilibrium"][None].to(device) | |
| rotmats_eq = item["rotmats_equilibrium"][None].to(device) | |
| seq = item["seq"][None].to(device) | |
| num_res = trans_eq.shape[1] | |
| batch = { | |
| "trans_equilibrium": trans_eq, | |
| "rotmats_equilibrium": rotmats_eq, | |
| "seq": seq, | |
| "res_mask": torch.ones(1, num_res, device=device), | |
| "pdb_name": [str(item["pdb_name"])], | |
| } | |
| # This is an injection-site diagnostic, not a training-loss diagnostic. | |
| # PDBDatasetBBFlowFromPdb only provides the equilibrium structure, not MD | |
| # targets (trans_1/rotmats_1), so build a minimal model-forward batch by | |
| # using the equilibrium frame as the current frame. The embedder injection | |
| # amplitudes are measured at the exact node/edge embedding site. | |
| noisy_batch = dict(batch) | |
| noisy_batch["trans_t"] = trans_eq.clone() | |
| noisy_batch["rotmats_t"] = rotmats_eq.clone() | |
| noisy_batch["t"] = torch.full((1, 1), 0.5, device=device, dtype=trans_eq.dtype) | |
| with torch.no_grad(): | |
| condition = module.latent_encoder.sample_prior_z( | |
| noisy_batch["trans_equilibrium"], | |
| noisy_batch["rotmats_equilibrium"], | |
| noisy_batch["seq"], | |
| noisy_batch["res_mask"], | |
| ) | |
| noisy_batch["z"] = condition | |
| captures = {} | |
| handles = [] | |
| def capture(name): | |
| def hook(_mod, _inp, out): | |
| captures[name] = out.detach() | |
| return hook | |
| embedder = module.model.embedder | |
| for name, submodule in [ | |
| ("node_base", embedder.node_embedding), | |
| ("edge_base_flat", embedder.edge_embedding), | |
| ("z_node_adapter", embedder.z_node_adapter), | |
| ("z_edge_adapter", embedder.z_edge_adapter), | |
| ("disp_node_adapter", embedder.disp_node_adapter), | |
| ("disp_edge_adapter", embedder.disp_edge_adapter), | |
| ]: | |
| if submodule is not None: | |
| handles.append(submodule.register_forward_hook(capture(name))) | |
| with torch.no_grad(): | |
| _ = module.model(noisy_batch) | |
| for handle in handles: | |
| handle.remove() | |
| node_base = captures.get("node_base") | |
| edge_base_flat = captures.get("edge_base_flat") | |
| out = { | |
| "ckpt_path": str(args.ckpt_path), | |
| "pdb_name": str(item["pdb_name"]), | |
| "num_res": int(num_res), | |
| "load_info": load_info, | |
| "condition_shapes": { | |
| key: list(value.shape) for key, value in condition.items() if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"} | |
| }, | |
| "last_layer_stats": { | |
| "z_node_adapter": last_linear_stats(embedder.z_node_adapter), | |
| "z_edge_adapter": last_linear_stats(embedder.z_edge_adapter), | |
| "disp_node_adapter": last_linear_stats(embedder.disp_node_adapter), | |
| "disp_edge_adapter": last_linear_stats(embedder.disp_edge_adapter), | |
| }, | |
| "injection_amplitude": {}, | |
| } | |
| if node_base is not None: | |
| node_base_abs = mean_abs(node_base) | |
| out["injection_amplitude"]["node_base_abs_mean"] = node_base_abs | |
| for key in ["z_node_adapter", "disp_node_adapter"]: | |
| if key in captures: | |
| amp = mean_abs(captures[key]) | |
| out["injection_amplitude"][f"{key}_out_abs_mean"] = amp | |
| out["injection_amplitude"][f"{key}_out_over_node_base"] = amp / max(node_base_abs, 1e-12) | |
| if edge_base_flat is not None: | |
| edge_base_abs = mean_abs(edge_base_flat) | |
| out["injection_amplitude"]["edge_base_abs_mean"] = edge_base_abs | |
| for key in ["z_edge_adapter", "disp_edge_adapter"]: | |
| if key in captures: | |
| amp = mean_abs(captures[key]) | |
| out["injection_amplitude"][f"{key}_out_abs_mean"] = amp | |
| out["injection_amplitude"][f"{key}_out_over_edge_base"] = amp / max(edge_base_abs, 1e-12) | |
| text = json.dumps(out, indent=2, sort_keys=True) | |
| print(text) | |
| if args.out_path: | |
| Path(args.out_path).parent.mkdir(parents=True, exist_ok=True) | |
| Path(args.out_path).write_text(text + "\n") | |
| if __name__ == "__main__": | |
| main() | |