File size: 8,890 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#!/usr/bin/env python
"""Measure condition sensitivity at the final BBFlow coordinate-update input.



This script is diagnostic-only. It does not modify model source files, checkpoint

weights, or training configuration. It compares three counterfactual conditions

at the sampler's initial noisy state:



1. directional_all_zero: zero disp_node_cond and disp_edge_cond;

2. node_cond_zero_all_paths: zero node_cond everywhere;

3. node_cond_zero_film_only: keep initial node injection but zero node_cond only

   inside the final-block FiLM call.

"""
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.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)
    checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False)
    current_state = module.state_dict()
    compatible_state = {
        key: value
        for key, value in checkpoint["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, {
        "loaded": len(compatible_state),
        "missing": len(missing),
        "unexpected": len(unexpected),
    }


def select_item(dataset, 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 in csv: {pdb_name}")


def clone_condition(condition):
    return {
        key: value.clone() if torch.is_tensor(value) else copy.deepcopy(value)
        for key, value in condition.items()
    }


def zero_condition_keys(condition, keys):
    out = clone_condition(condition)
    for key in keys:
        if key in out and torch.is_tensor(out[key]):
            out[key] = torch.zeros_like(out[key])
    return out


def relative_mean_abs_delta(reference, changed):
    denominator = reference.detach().float().abs().mean().clamp_min(1e-8)
    return float(
        (
            (reference.detach().float() - changed.detach().float()).abs().mean()
            / denominator
        )
        .cpu()
        .item()
    )


def run_model_and_capture_final_update(model, batch, condition, zero_node_cond_in_film=False):
    """Return final bb_update input and pred_trans for one counterfactual forward."""
    captured = {}
    last_block_index = model._gfa_conf.num_blocks - 1
    last_bb_update = model.trunk[f"bb_update_{last_block_index}"]

    def capture_final_update(_module, args):
        captured["final_update_node_embed"] = args[0].detach().clone()

    handle = last_bb_update.register_forward_pre_hook(capture_final_update)
    original_apply_film = model._apply_latent_film

    if zero_node_cond_in_film:
        def apply_film_with_zero_node_cond(node_embed, z):
            if isinstance(z, dict):
                z = dict(z)
                z["node_cond"] = torch.zeros_like(z["node_cond"])
            elif torch.is_tensor(z):
                z = torch.zeros_like(z)
            return original_apply_film(node_embed, z)

        model._apply_latent_film = apply_film_with_zero_node_cond

    try:
        call_batch = dict(batch)
        call_batch["z"] = condition
        with torch.no_grad():
            output = model(call_batch)
    finally:
        model._apply_latent_film = original_apply_film
        handle.remove()

    return {
        "final_update_node_embed": captured["final_update_node_embed"],
        "pred_trans": output["pred_trans"].detach().clone(),
    }


def measure_protein(module, dataset, pdb_name, device):
    item = select_item(dataset, 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]
    res_mask = torch.ones(1, num_res, device=device)

    trans_t, rotmats_t = module.interpolant.sample_from_prior(
        1, num_res, trans_eq, rotmats_eq
    )
    batch = {
        "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,
        ),
    }

    with torch.no_grad():
        condition = module.latent_encoder.sample_prior_z(
            trans_eq, rotmats_eq, seq, res_mask
        )

    reference = run_model_and_capture_final_update(module.model, batch, condition)
    variants = {
        "directional_all_zero": (
            zero_condition_keys(condition, ["disp_node_cond", "disp_edge_cond"]),
            False,
        ),
        "node_cond_zero_all_paths": (
            zero_condition_keys(condition, ["node_cond"]),
            False,
        ),
        "node_cond_zero_film_only": (condition, True),
    }

    result = {
        "pdb_name": str(item["pdb_name"]),
        "num_res": int(num_res),
        "t": float(module.interpolant._cfg.min_t),
    }
    for label, (variant_condition, film_only) in variants.items():
        changed = run_model_and_capture_final_update(
            module.model,
            batch,
            variant_condition,
            zero_node_cond_in_film=film_only,
        )
        result[f"{label}_final_update_rel_delta"] = relative_mean_abs_delta(
            reference["final_update_node_embed"],
            changed["final_update_node_embed"],
        )
        result[f"{label}_pred_trans_rel_delta"] = relative_mean_abs_delta(
            reference["pred_trans"],
            changed["pred_trans"],
        )
    return result


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--ckpt_path", required=True)
    parser.add_argument("--csv_path", required=True)
    parser.add_argument("--pdb_names", default="6o2vA,7eadA,6uofA")
    parser.add_argument("--device", default="cuda")
    parser.add_argument("--seed", type=int, default=20260626)
    parser.add_argument("--out_path", default="")
    args = parser.parse_args()

    torch.manual_seed(args.seed)
    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)
    module.interpolant.set_device(device)

    df = pd.read_csv(args.csv_path)
    dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf)
    pdb_names = [name.strip() for name in args.pdb_names.split(",") if name.strip()]
    per_protein = [measure_protein(module, dataset, name, device) for name in pdb_names]

    metric_keys = [key for key in per_protein[0] if key.endswith("_rel_delta")]
    summary = {
        "ckpt_path": str(args.ckpt_path),
        "load_info": load_info,
        "measurement": (
            "Relative mean-absolute counterfactual change at the sampler initial "
            "noise state. final_update is captured by a pre-hook immediately before "
            "the final bb_update module."
        ),
        "per_protein": per_protein,
        "mean_over_proteins": {
            key: float(np.mean([row[key] for row in per_protein]))
            for key in metric_keys
        },
    }
    text = json.dumps(summary, indent=2, sort_keys=True)
    print(text)
    if args.out_path:
        out_path = Path(args.out_path)
        out_path.parent.mkdir(parents=True, exist_ok=True)
        out_path.write_text(text + "\n")


if __name__ == "__main__":
    main()