File size: 11,525 Bytes
9e6e56b | 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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | # Copyright (c) 2025 Max Planck Institute for Polymer Research
# Copyright (c) 2024 HITS gGmbH
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
import numpy as np
from scipy.spatial.transform import Rotation
import os
import contextlib
from scipy.optimize import linear_sum_assignment
from sklearn.metrics import pairwise_distances
from tqdm.auto import tqdm
import pandas as pd
import logging
from torch.utils.data.distributed import dist
from gafl.data import so3_utils
from gafl.data import utils as du
from gafl.data import all_atom
from gafl.data.interpolant import (
Interpolant,
_centered_gaussian,
_uniform_so3,
_trans_diffuse_mask,
_rots_diffuse_mask
)
class InterpolantBBFlow(Interpolant):
def __init__(self, cfg):
self._cfg = cfg
self._rots_cfg = cfg.rots
self._trans_cfg = cfg.trans
self._sample_cfg = cfg.sampling
self._rot_distribution = self._rots_cfg.distribution
self._igso3 = None
self._log = logging.getLogger(__name__)
super().__init__(cfg)
def _fp32_linalg_context(self):
device_type = getattr(getattr(self, "_device", None), "type", None)
if device_type == "cuda":
return torch.autocast(device_type="cuda", enabled=False)
return contextlib.nullcontext()
def _intra_batch_ot(self, trans_1, trans_0, t, res_mask):
B, N = trans_0.shape[:2]
if self._cfg.batch_ot == "intra_permute":
trans_0_ordered = torch.zeros_like(trans_0)
for b in range(B):
cost_matrix_x = pairwise_distances(
trans_1[b].numpy(force=True),
trans_0[b].numpy(force=True)
)
cost_matrix = cost_matrix_x #+ cost_matrix_r
_, col_ind = linear_sum_assignment(cost_matrix)
aligned_0, _, _ = du.batch_align_structures(
trans_0[b].clone()[col_ind].unsqueeze(0),
trans_1[b].unsqueeze(0)
)
trans_0_ordered[b] = aligned_0[0]
return trans_0_ordered
else:
trans_0, trans_1, _ = du.batch_align_structures(
trans_0, trans_1, mask=res_mask
)
return trans_0
def _corrupt_trans(self, trans_1, trans_0, t, res_mask):
if self._cfg.batch_ot == "inter":
trans_0 = self._batch_ot(trans_0, trans_1, res_mask)
elif self._cfg.batch_ot in ["intra", "intra_permute"]:
trans_0 = self._intra_batch_ot(trans_1, trans_0, t, res_mask)
elif self._cfg.batch_ot == "none":
pass
else:
raise ValueError(f'Unknown batch ot type {self._cfg.batch_ot}')
trans_t = (1 - t[..., None]) * trans_0 + t[..., None] * trans_1
trans_t = _trans_diffuse_mask(trans_t, trans_1, res_mask)
return trans_t * res_mask[..., None]
def _corrupt_rotmats(self, rotmats_1, rotmats_0, t, res_mask):
rotmats_t = so3_utils.geodesic_t(t[..., None], rotmats_1, rotmats_0)
identity = torch.eye(3, device=self._device)
rotmats_t = (
rotmats_t * res_mask[..., None, None]
+ identity[None, None] * (1 - res_mask[..., None, None])
)
return _rots_diffuse_mask(rotmats_t, rotmats_1, res_mask)
def corrupt_batch(self, batch, t=None):
noisy_batch = dict(batch)
trans_equilibrium = batch["trans_equilibrium"].float()
rotmats_equilibrium = batch["rotmats_equilibrium"].float()
B, N = trans_equilibrium.shape[:2]
with self._fp32_linalg_context():
trans_0, rotmats_0 = self.sample_from_prior(
B, N,
trans_equilibrium,
rotmats_equilibrium,
)
if t is None:
# [B, 1]
t = self.sample_t(B)[:, None]
t = t.float()
# [B, N, 3]
trans_1 = batch['trans_1'].float() # Angstrom
# [B, N, 3, 3]
rotmats_1 = batch['rotmats_1'].float()
# [B, N]
res_mask = batch['res_mask'].float()
# Apply corruptions
trans_t = self._corrupt_trans(trans_1, trans_0, t, res_mask)
rotmats_t = self._corrupt_rotmats(rotmats_1, rotmats_0, t, res_mask)
noisy_batch['t'] = t
noisy_batch['trans_t'] = trans_t
noisy_batch['rotmats_t'] = rotmats_t
return noisy_batch
def _pure_noise_prior(self, num_batch, num_res, rotmats_1):
trans_nm_0 = _centered_gaussian(num_batch, num_res, self._device)
trans_0 = trans_nm_0 * du.NM_TO_ANG_SCALE
trans_0 *= self.noise_scale
# make the noise blob larger the longer the protein is:
if self.noise_res_scaling_power > 0:
trans_0 *= (trans_0.shape[1] / 128.)**self.noise_res_scaling_power
if self._rot_distribution == 'uniform':
rotmats_0 = _uniform_so3(num_batch, num_res, self._device)
elif self._rot_distribution == 'igso3':
noisy_rotmats = self.igso3.sample(
torch.tensor([1.5]),
num_batch*num_res
).to(self._device)
noisy_rotmats = noisy_rotmats.reshape(num_batch, num_res, 3, 3)
rotmats_0 = torch.einsum("...ij,...jk->...ik", rotmats_1, noisy_rotmats)
else:
raise ValueError(f'Unknown SO(3) distribution {self._rot_distribution}')
return trans_0, rotmats_0
def _conditional_prior(self, num_batch, num_res, trans_equilibrium, rotmats_equilibrium):
res_mask = torch.ones(num_batch, num_res, device=self._device)
trans_equilibrium = trans_equilibrium.float()
rotmats_equilibrium = rotmats_equilibrium.float()
trans_0, rotmats_0 = self._pure_noise_prior(num_batch, num_res, rotmats_equilibrium)
trans_0 = self._corrupt_trans(
trans_equilibrium,
trans_0,
self._cfg.prior_conditional.gamma_trans * torch.ones(num_batch, 1, device=self._device, dtype=torch.float32),
res_mask
)
rotmats_0 = self._corrupt_rotmats(
rotmats_equilibrium,
rotmats_0,
self._cfg.prior_conditional.gamma_rots * torch.ones(num_batch, 1, device=self._device, dtype=torch.float32),
res_mask
)
return trans_0, rotmats_0
def sample_from_prior(
self,
num_batch,
num_res,
trans_equilibrium,
rotmats_equilibrium,
):
prior_type = self._cfg.prior
if prior_type == 'conditional':
with self._fp32_linalg_context():
return self._conditional_prior(
num_batch, num_res, trans_equilibrium, rotmats_equilibrium
)
elif prior_type == 'pure_noise':
return self._pure_noise_prior(num_batch, num_res, rotmats_equilibrium)
else:
raise ValueError(f'Unknown prior type {prior_type}')
def sample(
self,
num_batch,
num_res,
model,
trans_equilibrium,
rotmats_equilibrium,
seq,
z=None,
return_trajectory=True,
cache_static_features=True,
):
res_mask = torch.ones(num_batch, num_res, device=self._device)
# Set-up initial prior samples
trans_0, rotmats_0 = self.sample_from_prior(
num_batch, num_res, trans_equilibrium, rotmats_equilibrium
)
batch = {
"res_mask": res_mask,
"trans_equilibrium": trans_equilibrium,
"rotmats_equilibrium": rotmats_equilibrium,
"seq": seq,
}
if z is not None:
batch["z"] = z
if cache_static_features and hasattr(model, "prepare_inference_static"):
batch["_embedder_static"] = model.prepare_inference_static(batch)
# Set-up time
ts = torch.linspace(
self._cfg.min_t, 1.0, self._sample_cfg.num_timesteps)
t_1 = ts[0]
prot_traj = [(trans_0, rotmats_0)] if return_trajectory else None
clean_traj = []
trans_current, rotmats_current = trans_0, rotmats_0
if self._cfg.use_tqdm:
# Only a progress-bar label, but dist.get_rank() raises outright when no
# process group exists -- which is the case for single-device inference,
# where Lightning never initialises one. Sampling has no other reason to
# need distributed state, so fall back to 0 rather than making a one-GPU
# run impossible.
rank = dist.get_rank() if dist.is_available() and dist.is_initialized() else 0
iterator = tqdm(
ts[1:],
leave=False,
desc=f'Sampl. {num_batch} states, len {num_res}, rank {rank} - timesteps'
)
else:
iterator = ts[1:]
for t_2 in iterator:
# Run model.
trans_t_1, rotmats_t_1 = trans_current, rotmats_current
t = torch.ones((num_batch, 1), device=self._device) * t_1
batch['trans_t'] = trans_t_1
batch['rotmats_t'] = rotmats_t_1
batch['t'] = t
with torch.no_grad():
model_out = model(batch)
# Process model output.
pred_trans_1 = model_out['pred_trans']
pred_rotmats_1 = model_out['pred_rotmats']
if return_trajectory:
clean_traj.append(
(pred_trans_1.detach().cpu(), pred_rotmats_1.detach().cpu())
)
if self._cfg.self_condition:
batch['trans_sc'] = pred_trans_1
d_t = t_2 - t_1
# Take reverse step
trans_t_2 = self._trans_euler_step(
d_t, t_1, pred_trans_1, trans_t_1)
rotmats_t_2 = self._rots_euler_step(
d_t, t_1, pred_rotmats_1, rotmats_t_1)
trans_current, rotmats_current = trans_t_2, rotmats_t_2
if return_trajectory:
prot_traj.append((trans_t_2, rotmats_t_2))
t_1 = t_2
t_1 = ts[-1]
trans_t_1, rotmats_t_1 = trans_current, rotmats_current
t = torch.ones((num_batch, 1), device=self._device) * t_1
batch['trans_t'] = trans_t_1
batch['rotmats_t'] = rotmats_t_1
batch['t'] = t
with torch.no_grad():
model_out = model(batch)
# Process model output.
pred_trans_1 = model_out['pred_trans']
pred_rotmats_1 = model_out['pred_rotmats']
if return_trajectory:
clean_traj.append(
(pred_trans_1.detach().cpu(), pred_rotmats_1.detach().cpu())
)
prot_traj.append((pred_trans_1, pred_rotmats_1))
else:
# Keep the historical return structure, but materialize only the
# final state that inference actually writes.
prot_traj = [(pred_trans_1, pred_rotmats_1)]
clean_traj = [(pred_trans_1, pred_rotmats_1)]
# Convert trajectories to atom37.
atom37_traj = all_atom.transrot_to_atom37(prot_traj, res_mask)
clean_atom37_traj = all_atom.transrot_to_atom37(clean_traj, res_mask)
return atom37_traj, clean_atom37_traj, clean_traj
|