data_transfer / bbflow_base /bbflow /models /bbflow_model.py
hanghang214's picture
Add files using upload-large-folder tool
9e6e56b verified
Raw History Blame Contribute Delete
16.8 kB
# Copyright (c) 2025 Max Planck Institute for Polymer Research
# Copyright (c) 2024 HITS gGmbH
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import numpy as np
import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
from gafl.models import ipa_pytorch
from gafl.data import utils as du
from gafl.models.gafl.pga_utils import embed_frames, EquiLayerNorm
from gafl.models.gafl.cfa import GeometricFrameAttention, Linear, BackboneUpdate
from bbflow.models.embedder import Embedder
from bbflow.models.collective import CollectiveMeasureController
from omegaconf import DictConfig, OmegaConf
from omegaconf.base import ContainerMetadata
# depending on the torch version (higher than 2.6), we need to add the DictConfig and ContainerMetadata to the safe globals:
import torch
import builtins
from typing import Any
from collections import defaultdict
from omegaconf import DictConfig, OmegaConf, ListConfig
from omegaconf.nodes import AnyNode
from omegaconf.base import ContainerMetadata, Metadata
# depending on the torch version (>=2.6), we need to add all types the checkpoint asked for
if hasattr(torch.serialization, "add_safe_globals"):
torch.serialization.add_safe_globals([
(Any, "typing.Any"),
(defaultdict, "collections.defaultdict"),
(DictConfig, "omegaconf.dictconfig.DictConfig"),
(ListConfig, "omegaconf.listconfig.ListConfig"),
(AnyNode, "omegaconf.nodes.AnyNode"),
(ContainerMetadata, "omegaconf.base.ContainerMetadata"),
(Metadata, "omegaconf.base.Metadata"),
(builtins.dict, "builtins.dict"),
(builtins.int, "builtins.int"),
(builtins.list, "builtins.list"),
])
class BBFlowModel(nn.Module):
def __init__(self, model_conf, latent_cfg=None):
super(BBFlowModel, self).__init__()
self._model_conf = model_conf
self._gfa_conf = model_conf.gfa
self.rigids_ang_to_nm = lambda x: x.apply_trans_fn(lambda x: x * du.ANG_TO_NM_SCALE)
self.rigids_nm_to_ang = lambda x: x.apply_trans_fn(lambda x: x * du.NM_TO_ANG_SCALE)
self.embedder = Embedder(model_conf, latent_cfg=latent_cfg)
self.latent_enabled = bool(latent_cfg is not None and getattr(latent_cfg, "enable", False))
self.inject_film = bool(
self.latent_enabled and getattr(latent_cfg, "inject_film", True)
)
self.activation_checkpoint = bool(
latent_cfg is not None and getattr(latent_cfg, "activation_checkpoint", False)
)
self.collective_enabled = bool(
self.latent_enabled and getattr(latent_cfg, "collective_enable", False)
)
if self.collective_enabled:
self.collective_rank = int(getattr(latent_cfg, "collective_rank", 4))
self.collective_controller = CollectiveMeasureController(
rank=self.collective_rank,
hidden_dim=int(getattr(latent_cfg, "collective_hidden_dim", 128)),
output_scale=float(getattr(latent_cfg, "collective_output_scale", 1.0)),
)
else:
self.collective_rank = 0
self.collective_controller = None
# Attention trunk
self.trunk = nn.ModuleDict()
for b in range(self._gfa_conf.num_blocks):
self.trunk[f'gfa_{b}'] = GeometricFrameAttention(self._gfa_conf, geometric_input=bool(b), geometric_output=True)
self.trunk[f'gfa_ln_{b}'] = nn.LayerNorm(self._gfa_conf.c_s)
self.trunk[f'g_ln_{b}'] = EquiLayerNorm()
tfmr_in = self._gfa_conf.c_s
tfmr_layer = nn.TransformerEncoderLayer(
d_model=tfmr_in,
nhead=self._gfa_conf.seq_tfmr_num_heads,
dim_feedforward=tfmr_in,
batch_first=True,
dropout=0.0,
norm_first=False
)
self.trunk[f'seq_tfmr_{b}'] = nn.TransformerEncoder(
tfmr_layer, self._gfa_conf.seq_tfmr_num_layers, enable_nested_tensor=False)
self.trunk[f'post_tfmr_{b}'] = Linear(
tfmr_in, self._gfa_conf.c_s, init="final")
self.trunk[f'node_transition_{b}'] = ipa_pytorch.StructureModuleTransition(
c=self._gfa_conf.c_s)
self.trunk[f'bb_update_{b}'] = BackboneUpdate(
self._gfa_conf.c_s,
self._gfa_conf.no_v_points,
self._gfa_conf.no_heads,)
if b < self._gfa_conf.num_blocks-1:
# No edge update on the last block.
edge_in = self._model_conf.edge_embed_size
self.trunk[f'edge_transition_{b}'] = ipa_pytorch.EdgeTransition(
node_embed_size=self._gfa_conf.c_s,
edge_embed_in=edge_in,
edge_embed_out=self._model_conf.edge_embed_size,
)
if self.inject_film:
self.latent_dim = int(getattr(latent_cfg, "dim", 16))
self.film_cond_dim = int(getattr(latent_cfg, "node_cond_dim", getattr(latent_cfg, "num_modes", self.latent_dim)))
self.film_mlp = nn.Sequential(
nn.Linear(self.film_cond_dim, self._gfa_conf.c_s),
nn.ReLU(),
nn.Linear(self._gfa_conf.c_s, 2 * self._gfa_conf.c_s),
)
nn.init.zeros_(self.film_mlp[-1].weight)
nn.init.zeros_(self.film_mlp[-1].bias)
else:
self.latent_dim = 0
self.film_cond_dim = 0
self.film_mlp = None
def _apply_latent_film(self, node_embed, z):
if not self.inject_film:
return node_embed
if isinstance(z, dict):
cond = z.get("node_cond")
else:
cond = z
if cond is None:
cond = torch.zeros(
node_embed.shape[0],
node_embed.shape[1],
self.film_cond_dim,
device=node_embed.device,
dtype=node_embed.dtype,
)
if cond.dim() == 2:
cond = cond[:, None, :].expand(node_embed.shape[0], node_embed.shape[1], -1)
gamma_beta = self.film_mlp(cond.to(dtype=node_embed.dtype))
gamma, beta = torch.chunk(gamma_beta, 2, dim=-1)
return node_embed * (1.0 + gamma) + beta
def _collective_update(self, input_feats):
if not self.collective_enabled:
return None, None
condition = input_feats.get("z")
if not isinstance(condition, dict):
raise ValueError("CMFM requires a dictionary condition")
required = (
"collective_basis_global",
"collective_target_covariance",
"collective_group_index",
)
missing = [key for key in required if key not in condition]
if missing:
raise ValueError(f"CMFM condition is missing required keys: {missing}")
return self.collective_controller(
input_feats["trans_t"],
input_feats["trans_equilibrium"],
input_feats["res_mask"],
condition["collective_basis_global"],
condition["collective_target_covariance"],
condition["collective_group_index"].long(),
input_feats["t"],
)
def prepare_inference_static(self, batch):
B, N = batch["res_mask"].shape[:2]
return self.embedder.prepare_inference_static({
"B,N": (B, N),
"device": batch["res_mask"].device,
"CA_pos": {
"trans_equilibrium": batch["trans_equilibrium"],
},
"rotmats_equilibrium": batch["rotmats_equilibrium"],
"seq": batch["seq"],
"z": batch.get("z"),
})
def _run_gfa(self, block_idx, node_embed, g, edge_embed, curr_frames, node_mask):
gfa = self.trunk[f'gfa_{block_idx}']
if not (self.training and self.activation_checkpoint and torch.is_grad_enabled()):
return gfa(node_embed, g, edge_embed, curr_frames, node_mask)
if g is None:
def first_gfa_forward(node_embed_, edge_embed_, curr_frames_, node_mask_):
return gfa(
node_embed_, None, edge_embed_, curr_frames_, node_mask_
)
return checkpoint(
first_gfa_forward,
node_embed,
edge_embed,
curr_frames,
node_mask,
use_reentrant=False,
preserve_rng_state=False,
)
def gfa_forward(node_embed_, g_, edge_embed_, curr_frames_, node_mask_):
return gfa(node_embed_, g_, edge_embed_, curr_frames_, node_mask_)
return checkpoint(
gfa_forward,
node_embed,
g,
edge_embed,
curr_frames,
node_mask,
use_reentrant=False,
preserve_rng_state=False,
)
def _run_edge_transition(self, block_idx, node_embed, edge_embed):
edge_transition = self.trunk[f'edge_transition_{block_idx}']
if not (
self.training
and self.activation_checkpoint
and torch.is_grad_enabled()
):
return edge_transition(node_embed, edge_embed)
def edge_forward(node_embed_, edge_embed_):
return edge_transition(node_embed_, edge_embed_)
return checkpoint(
edge_forward,
node_embed,
edge_embed,
use_reentrant=False,
preserve_rng_state=False,
)
def forward_backbone(self, input_feats):
node_mask = input_feats['res_mask']
edge_mask = node_mask[:, None] * node_mask[:, :, None]
continuous_t = input_feats['t']
trans_t = input_feats['trans_t']
rotmats_t = input_feats['rotmats_t']
# Initialize node and edge embeddings
if 'trans_sc' not in input_feats:
trans_sc = torch.zeros_like(trans_t)
else:
trans_sc = input_feats['trans_sc']
B, N = node_mask.shape[:2]
CA_pos = {
"trans_t": trans_t,
"trans_sc": trans_sc,
"trans_equilibrium": input_feats["trans_equilibrium"]
}
embedder_input_feats = {
"B,N": (B, N),
"device": node_mask.device,
"time": continuous_t,
"CA_pos": CA_pos,
"rotmats_equilibrium": input_feats["rotmats_equilibrium"],
"seq": input_feats["seq"],
}
if "dataset_type_onehot" in input_feats:
embedder_input_feats["dataset_type_onehot"] = input_feats["dataset_type_onehot"]
if "z" in input_feats:
embedder_input_feats["z"] = input_feats["z"]
if "_embedder_static" in input_feats:
embedder_input_feats["inference_static"] = input_feats["_embedder_static"]
init_node_embed, init_edge_embed = self.embedder(embedder_input_feats)
# Initial rigids
# curr_frames = embed_frames(rotmats_t, trans_t * du.ANG_TO_NM_SCALE)
curr_rigids = du.create_rigid(rotmats_t, trans_t,)
curr_rigids = self.rigids_ang_to_nm(curr_rigids)
curr_frames = embed_frames(rotmats_t, trans_t * du.ANG_TO_NM_SCALE)
# Main trunk
init_node_embed = init_node_embed * node_mask[..., None]
node_embed = init_node_embed * node_mask[..., None]
edge_embed = init_edge_embed * edge_mask[..., None]
g = None
for b in range(self._gfa_conf.num_blocks):
gfa_embed, g_gfa, gfa_rel = self._run_gfa(
b,
node_embed,
g,
edge_embed,
curr_frames,
node_mask)
gfa_embed *= node_mask[..., None]
gfa_rel = gfa_rel * node_mask[..., None, None]
node_embed = self.trunk[f'gfa_ln_{b}'](node_embed + gfa_embed)
if g is not None:
g = self.trunk[f'g_ln_{b}'](g + g_gfa)
else:
g = self.trunk[f'g_ln_{b}'](g_gfa)
g = g * node_mask[..., None, None]
seq_tfmr_out = self.trunk[f'seq_tfmr_{b}'](
node_embed, src_key_padding_mask=(1 - node_mask).bool())
node_embed = node_embed + self.trunk[f'post_tfmr_{b}'](seq_tfmr_out)
node_embed = self.trunk[f'node_transition_{b}'](node_embed)
node_embed = node_embed * node_mask[..., None]
update_node_embed = node_embed
if b == self._gfa_conf.num_blocks - 1:
update_node_embed = self._apply_latent_film(
node_embed,
input_feats.get("z", None),
)
curr_frames, curr_rigids = self.trunk[f'bb_update_{b}'](
update_node_embed,
g,
gfa_rel,
curr_frames,
curr_rigids,
node_mask[..., None],)
if b < self._gfa_conf.num_blocks-1:
edge_embed = self._run_edge_transition(
b, node_embed, edge_embed)
edge_embed *= edge_mask[..., None]
curr_rigids = self.rigids_nm_to_ang(curr_rigids)
pred_trans = curr_rigids.get_trans()
pred_rotmats = curr_rigids.get_rots().get_rot_mats()
return {
'pred_trans': pred_trans,
'pred_rotmats': pred_rotmats,
}
@classmethod
def _slice_batch_value(cls, value, start, end, batch_size):
if torch.is_tensor(value):
if value.ndim > 0 and value.shape[0] == batch_size:
return value[start:end]
return value
if isinstance(value, dict):
return {
key: cls._slice_batch_value(item, start, end, batch_size)
for key, item in value.items()
}
if isinstance(value, list) and len(value) == batch_size:
return value[start:end]
if isinstance(value, tuple) and len(value) == batch_size:
return value[start:end]
return value
def forward_chunked(self, input_feats, chunk_size, checkpoint_chunks=True):
"""Run the particle-independent backbone in chunks, then couple the full group."""
batch_size = int(input_feats['res_mask'].shape[0])
chunk_size = int(chunk_size)
if chunk_size <= 0:
raise ValueError(f"chunk_size must be positive, got {chunk_size}")
if chunk_size >= batch_size:
return self.forward(input_feats)
chunk_outputs = []
for start in range(0, batch_size, chunk_size):
end = min(start + chunk_size, batch_size)
chunk_input = self._slice_batch_value(
input_feats,
start,
end,
batch_size,
)
if checkpoint_chunks and self.training and torch.is_grad_enabled():
chunk_output = checkpoint(
self.forward_backbone,
chunk_input,
use_reentrant=False,
)
else:
chunk_output = self.forward_backbone(chunk_input)
chunk_outputs.append(chunk_output)
output_keys = tuple(chunk_outputs[0])
if any(tuple(output) != output_keys for output in chunk_outputs[1:]):
raise RuntimeError("backbone chunk outputs do not have matching keys")
backbone_output = {
key: torch.cat([output[key] for output in chunk_outputs], dim=0)
for key in output_keys
}
return self.apply_collective_update(input_feats, backbone_output)
def apply_collective_update(self, input_feats, output):
output = dict(output)
collective_update, collective_coefficients = self._collective_update(input_feats)
if collective_update is None:
return output
output['pred_trans'] = output['pred_trans'] + collective_update.to(
dtype=output['pred_trans'].dtype
)
output['collective_update_global'] = collective_update
output['collective_coefficients_t'] = collective_coefficients
return output
def forward(self, input_feats):
backbone_output = self.forward_backbone(input_feats)
return self.apply_collective_update(input_feats, backbone_output)