File size: 8,125 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
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()