Download bbflow_base/scripts/check_foundation_compatibility.py from hanghang214/data_transfer: direct link, hf CLI and curl.
- Browser
- Download file 8.13 kB
-
https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/check_foundation_compatibility.py
- Command line
-
hf download hf://datasets/hanghang214/data_transfer/bbflow_base/scripts/check_foundation_compatibility.py
-
curl -L -o check_foundation_compatibility.py https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/check_foundation_compatibility.py
8.13 kB
| import argparse | |
| import copy | |
| import json | |
| from pathlib import Path | |
| import torch | |
| from hydra import compose, initialize_config_dir | |
| from omegaconf import OmegaConf | |
| from bbflow.data.pdb_dataloader_bbflow import PdbDataModuleBBFlow | |
| from bbflow.models.bbflow_module import BBFlowModule | |
| from bbflow.models.embedder import Embedder | |
| from bbflow.models.bbflow_model import BBFlowModel | |
| def _dim_summary(cfg): | |
| e = cfg.model.embed | |
| node_dim = int(e.time_embed_dim) + int(e.length_embed_dim) | |
| if e.embed_aatype: | |
| node_dim += int(e.aatype_embed_dim) | |
| edge_dim = 2 * int(e.time_embed_dim) | |
| edge_dim += 2 * int(cfg.model.node_embed_size) | |
| edge_dim += int(e.num_bins_distance) | |
| if e.embed_distogram: | |
| edge_dim += int(e.num_bins_distance) | |
| if e.embed_self_conditioning: | |
| edge_dim += int(e.num_bins_distance) | |
| if e.embed_direction: | |
| edge_dim += 3 | |
| index_type = getattr(e, "index_embed_type", None) | |
| if index_type == "full": | |
| node_dim += int(e.index_embed_dim) | |
| edge_dim += int(e.index_embed_dim) | |
| elif index_type == "neighbor": | |
| edge_dim += 1 | |
| return { | |
| "time_embed_dim": int(e.time_embed_dim), | |
| "aatype_embed_dim": int(e.aatype_embed_dim), | |
| "embed_direction": bool(e.embed_direction), | |
| "node_dim": node_dim, | |
| "edge_dim": edge_dim, | |
| } | |
| def _load_ckpt_state(ckpt_path): | |
| ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=True) | |
| state = ckpt["state_dict"] | |
| return {k.replace("model.", ""): v for k, v in state.items()} | |
| def _compatible_report(model, ckpt_state): | |
| current = model.state_dict() | |
| loaded = [] | |
| skipped = [] | |
| for key, value in ckpt_state.items(): | |
| if key in current and current[key].shape == value.shape: | |
| loaded.append(key) | |
| elif key in current: | |
| skipped.append({ | |
| "key": key, | |
| "ckpt_shape": list(value.shape), | |
| "model_shape": list(current[key].shape), | |
| }) | |
| return {"loaded": len(loaded), "skipped": skipped} | |
| def _make_embedder_inputs(batch): | |
| node_mask = batch["res_mask"] | |
| trans_t = batch["trans_t"] | |
| trans_sc = batch.get("trans_sc", torch.zeros_like(trans_t)) | |
| bsz, num_res = node_mask.shape[:2] | |
| return { | |
| "B,N": (bsz, num_res), | |
| "device": node_mask.device, | |
| "time": batch["t"], | |
| "CA_pos": { | |
| "trans_t": trans_t, | |
| "trans_sc": trans_sc, | |
| "trans_equilibrium": batch["trans_equilibrium"], | |
| }, | |
| "rotmats_equilibrium": batch["rotmats_equilibrium"], | |
| "seq": batch["seq"], | |
| "z": batch.get("z"), | |
| } | |
| def _move_to_device(batch, device): | |
| return {k: v.to(device) if torch.is_tensor(v) else v for k, v in batch.items()} | |
| def _adapter_zero_report(model): | |
| report = {} | |
| embedder = model.embedder | |
| for name in ["z_node_adapter", "z_edge_adapter", "disp_node_adapter", "disp_edge_adapter"]: | |
| module = getattr(embedder, name, None) | |
| if module is None: | |
| report[name] = None | |
| continue | |
| last = module[-1] | |
| report[name] = { | |
| "weight_abs_max": float(last.weight.detach().abs().max().cpu().item()), | |
| "bias_abs_max": float(last.bias.detach().abs().max().cpu().item()), | |
| } | |
| film = getattr(model, "film_mlp", None) | |
| if film is not None: | |
| last = film[-1] | |
| report["film_mlp"] = { | |
| "weight_abs_max": float(last.weight.detach().abs().max().cpu().item()), | |
| "bias_abs_max": float(last.bias.detach().abs().max().cpu().item()), | |
| } | |
| else: | |
| report["film_mlp"] = None | |
| return report | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--ckpt_path", required=True) | |
| parser.add_argument("--official_config_path", default=None) | |
| parser.add_argument("--device", default="cpu") | |
| parser.add_argument("--run_batch_checks", action="store_true") | |
| parser.add_argument("--output", default=None) | |
| parser.add_argument("--override", action="append", default=[]) | |
| args = parser.parse_args() | |
| repo_root = Path(__file__).resolve().parents[1] | |
| with initialize_config_dir(version_base=None, config_dir=str(repo_root / "configs")): | |
| cfg = compose(config_name="train", overrides=args.override) | |
| OmegaConf.set_struct(cfg, False) | |
| cfg.experiment.use_wandb = False | |
| cfg.experiment.num_devices = 1 | |
| cfg.latent.enable = True | |
| cfg.latent.inject_embedder = True | |
| cfg.latent.inject_film = True | |
| cfg.data.loader.num_workers = 0 | |
| report = { | |
| "current_config_dims": _dim_summary(cfg), | |
| "official_config_dims": None, | |
| "official_config_matches_current": None, | |
| "compatibility": None, | |
| "adapter_zero_init": None, | |
| "initial_equivalence": None, | |
| "prior_scope": { | |
| "prior_uses_model_embed_config": False, | |
| "prior_input_dim": 50, | |
| "note": "LatentEncoder prior features are defined in bbflow.models.latent and do not read cfg.model.embed time/aatype/embed_direction.", | |
| }, | |
| } | |
| if args.official_config_path is not None and Path(args.official_config_path).exists(): | |
| official_cfg = OmegaConf.load(args.official_config_path) | |
| report["official_config_dims"] = _dim_summary(official_cfg) | |
| report["official_config_matches_current"] = report["official_config_dims"] == report["current_config_dims"] | |
| module = BBFlowModule(cfg) | |
| ckpt_state = _load_ckpt_state(args.ckpt_path) | |
| report["compatibility"] = _compatible_report(module.model, ckpt_state) | |
| report["adapter_zero_init"] = _adapter_zero_report(module.model) | |
| baseline_model = BBFlowModel(cfg.model, latent_cfg=None).eval() | |
| latent_model = BBFlowModel(cfg.model, latent_cfg=cfg.latent).eval() | |
| latent_model.load_state_dict(copy.deepcopy(baseline_model.state_dict()), strict=False) | |
| device = torch.device(args.device if (args.device == "cpu" or torch.cuda.is_available()) else "cpu") | |
| baseline_model.to(device) | |
| latent_model.to(device) | |
| if args.run_batch_checks: | |
| datamodule = PdbDataModuleBBFlow(cfg.data, training_cfg=cfg.experiment.training, latent_cfg=cfg.latent) | |
| datamodule.setup("fit") | |
| batch = next(iter(datamodule.train_dataloader(rank=0, num_replicas=1))) | |
| batch = _move_to_device(batch, device) | |
| module.interpolant.set_device(device) | |
| noisy = module.interpolant.corrupt_batch(batch) | |
| noisy = _move_to_device(noisy, device) | |
| bsz, num_res = noisy["res_mask"].shape[:2] | |
| num_modes = int(cfg.latent.num_modes) | |
| z = { | |
| "node_cond": torch.randn(bsz, num_res, num_modes, device=device), | |
| "edge_cond": torch.randn(bsz, num_res, num_res, num_modes, device=device), | |
| } | |
| noisy_z = dict(noisy) | |
| noisy_z["z"] = z | |
| with torch.no_grad(): | |
| out_base = baseline_model(noisy) | |
| out_latent = latent_model(noisy_z) | |
| embed_base = baseline_model.embedder(_make_embedder_inputs(noisy)) | |
| embed_latent = latent_model.embedder(_make_embedder_inputs(noisy_z)) | |
| report["initial_equivalence"] = { | |
| "pred_trans_max_abs_diff": float((out_base["pred_trans"] - out_latent["pred_trans"]).abs().max().cpu().item()), | |
| "pred_rotmats_max_abs_diff": float((out_base["pred_rotmats"] - out_latent["pred_rotmats"]).abs().max().cpu().item()), | |
| "node_embed_max_abs_diff": float((embed_base[0] - embed_latent[0]).abs().max().cpu().item()), | |
| "edge_embed_max_abs_diff": float((embed_base[1] - embed_latent[1]).abs().max().cpu().item()), | |
| } | |
| text = json.dumps(report, indent=2, ensure_ascii=False) | |
| print(text) | |
| if args.output is not None: | |
| out = Path(args.output) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| out.write_text(text + "\n") | |
| if __name__ == "__main__": | |
| main() |