File size: 19,181 Bytes
13e95c8 | 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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 | from typing import Optional, Union
import numpy as np
import torch
import torch.nn as nn
import torch.distributed as dist
from scipy.spatial.transform import Rotation
from src.utils.license_register import register_license
from src.utils.model.scatter_utils import scatter
@register_license('odesign2025')
def centre_random_augmentation(
x_input_coords: torch.Tensor,
N_sample: int = 1,
s_trans: float = 1.0,
centre_only: bool = False,
mask: torch.Tensor = None,
eps: float = 1e-12,
dtype: torch.dtype = torch.float32,
) -> torch.Tensor:
"""Implements Algorithm 19 in AF3
Args:
x_input_coords (torch.Tensor): input coords
[..., N_atom, 3]
N_sample (int, optional): the total number of augmentation. Defaults to 1.
s_trans (float, optional): scale factor of trans. Defaults to 1.0.
centre_only (bool, optional): if set true, will only perform centering without applying random translation and rotation.
mask (torch.Tensor, optional): masking for the coords
[..., N_atom]
eps (float, optional): small number used for masked mean
Returns:
torch.Tensor: the Augmentation version of input coords
[..., N_sample, N_atom, 3]
"""
N_atom = x_input_coords.size(-2)
device = x_input_coords.device
# Move to origin [..., N_atom, 3]
# Compute center of coordinates (with optional masking)
if mask is None:
x_center = torch.mean(
input=x_input_coords, dim=-2, keepdim=True
)
else:
x_center = ((x_input_coords * mask.unsqueeze(dim=-1)).sum(dim=-2) / (
mask.sum(dim=-1) + eps
)).unsqueeze(dim=-2)
x_input_coords = x_input_coords - x_center
# Expand to [..., N_sample, N_atom, 3]
x_input_coords = expand_at_dim(x_input_coords, dim=-3, n=N_sample)
if centre_only:
return x_input_coords
# N_augment = batch_size * N_sample
N_augment = torch.numel(x_input_coords[..., 0, 0])
# Generate N_augment (rot, trans) pairs
batch_size_shape = x_input_coords.shape[:-3]
rot_matrix_random = (
uniform_random_rotation(N_sample=N_augment)
.to(device)
.reshape(*batch_size_shape, N_sample, 3, 3)
).detach() # [..., N_sample, 3, 3]
trans_random = s_trans * torch.randn(
size=(*batch_size_shape, N_sample, 3), device=device
) # [..., N_sample, 3]
x_augment_coords = (
rot_vec_mul(
r=expand_at_dim(rot_matrix_random, dim=-3, n=N_atom), t=x_input_coords
)
+ trans_random[..., None, :]
) # [..., N_sample, N_atom, 3]
if mask is not None:
x_augment_coords = x_augment_coords * mask[..., None, :, None]
# Convert to specified dtype for consistency
return (
x_augment_coords.to(dtype),
trans_random.to(dtype),
rot_matrix_random.to(dtype),
x_center.to(dtype)
)
# Comment: Rotation.random is not supported by torch.compile()
@register_license('bytedance2024')
def uniform_random_rotation(N_sample: int = 1) -> torch.Tensor:
"""Generate random rotation matrices with scipy.spatial.transform.Rotation
Args:
N_sample (int, optional): the total number of augmentation. Defaults to 1.
Returns:
torch.Tensor: N_sample rot matrics
[N_sample, 3, 3]
"""
rotation = Rotation.random(num=N_sample)
rot_matrix = torch.from_numpy(rotation.as_matrix()).float() # [N_sample, 3, 3]
return rot_matrix
# this is from openfold.utils.rigid_utils import rot_vec_mul
# precision is added
@register_license('bytedance2024')
def rot_vec_mul(r: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
"""Apply rot matrix to vector
Applies a rotation to a vector. Written out by hand to avoid transfer
to avoid AMP downcasting.
Args:
r (torch.Tensor): the rotation matrices
[..., 3, 3]
t (torch.Tensor): the coordinate tensors
[..., 3]
Returns:
torch.Tensor: the rotated coordinates
"""
if t.dtype != torch.float32:
t = t.to(dtype=torch.float32)
if r.dtype != torch.float32:
r = r.to(dtype=torch.float32)
x, y, z = torch.unbind(input=t, dim=-1)
return torch.stack(
tensors=[
r[..., 0, 0] * x + r[..., 0, 1] * y + r[..., 0, 2] * z,
r[..., 1, 0] * x + r[..., 1, 1] * y + r[..., 1, 2] * z,
r[..., 2, 0] * x + r[..., 2, 1] * y + r[..., 2, 2] * z,
],
dim=-1,
)
# from openfold.utils.tensor_utils.permute_final_dims
# from openfold.utils.tensor_utils.flatten_final_dims
@register_license('bytedance2024')
def permute_final_dims(tensor: torch.Tensor, inds: list[int]) -> torch.Tensor:
"""Permute final dims of tensor
Args:
tensor (torch.Tensor): the input tensor
[...]
inds (List[int]): the dim to permute
Returns:
torch.Tensor: the permuted tensor
"""
zero_index = -1 * len(inds)
first_inds = list(range(len(tensor.shape[:zero_index])))
return tensor.permute(first_inds + [zero_index + i for i in inds])
@register_license('bytedance2024')
def flatten_final_dims(t: torch.Tensor, num_dims: int) -> torch.Tensor:
"""Flatten final dims of tensor
Args:
t (torch.Tensor): the input tensor
[...]
num_dims (int): the number of final dims to flatten
Returns:
torch.Tensor: the flattened tensor
"""
return t.reshape(shape=t.shape[:-num_dims] + (-1,))
@register_license('bytedance2024')
def one_hot(
x: torch.Tensor, lower_bins: torch.Tensor, upper_bins: torch.Tensor
) -> torch.Tensor:
"""Get one hot embedding of x from lower_bins and upper_bins
Args:
x (torch.Tensor): the input x
[...]
lower_bins (torch.Tensor): the lower bounds of bins
[bins]
upper_bins (torch.Tensor): the upper bounds of bins
[bins]
Returns:
torch.Tensor: the one hot embedding of x from v_bins
[..., bins]
"""
dgram = (x[..., None] > lower_bins) * (x[..., None] < upper_bins).float()
return dgram
# this is mostly from openfold.utils.torch_utils import batched_gather
@register_license('bytedance2024')
def batched_gather(
data: torch.Tensor, inds: torch.Tensor, dim: int = 0, no_batch_dims: int = 0
) -> torch.Tensor:
"""Gather data according to indices specify by inds
Args:
data (torch.Tensor): the input data
[..., K, ...]
inds (torch.Tensor): the indices for gathering data
[..., N]
dim (int, optional): along which dimension to gather data by inds (the dim of "K" "N"). Defaults to 0.
no_batch_dims (int, optional): length of dimensions before the "dim" dimension. Defaults to 0.
Returns:
torch.Tensor: gathered data
[..., N, ...]
"""
# for the naive case
if len(inds.shape) == 1 and no_batch_dims == 0 and dim == 0:
return data[inds]
ranges = []
for i, s in enumerate(data.shape[:no_batch_dims]):
r = torch.arange(s)
r = r.view(*(*((1,) * i), -1, *((1,) * (len(inds.shape) - i - 1))))
ranges.append(r)
remaining_dims = [slice(None) for _ in range(len(data.shape) - no_batch_dims)]
remaining_dims[dim - no_batch_dims if dim >= 0 else dim] = inds
ranges.extend(remaining_dims)
return data[ranges]
@register_license('bytedance2024')
def broadcast_token_to_atom(
x_token: torch.Tensor, atom_to_token_idx: torch.Tensor
) -> torch.Tensor:
"""Broadcast token-level embeddings to atom-level embeddings
Args:
x_token (torch.Tensor): token embedding
[..., N_token, d]
atom_to_token_idx (torch.Tensor): map atom idx to token idx
[..., N_atom] or [N_atom]
Returns:
torch.Tensor: atom embedding
[..., N_atom, d]
"""
if len(atom_to_token_idx.shape) == 1:
# shape = [N_atom], easy index
return x_token[..., atom_to_token_idx, :]
else:
assert atom_to_token_idx.shape[:-1] == x_token.shape[:-2]
return batched_gather(
data=x_token,
inds=atom_to_token_idx,
dim=-2,
no_batch_dims=len(x_token.shape[:-2]),
)
@register_license('bytedance2024')
def aggregate_atom_to_token(
x_atom: torch.Tensor,
atom_to_token_idx: torch.Tensor,
n_token: Optional[int] = None,
reduce: str = "mean",
) -> torch.Tensor:
"""Aggregate atom embedding to obtain token embedding
Args:
x_atom (torch.Tensor): atom-level embedding
[..., N_atom, d]
atom_to_token_idx (torch.Tensor): map atom to token idx
[..., N_atom] or [N_atom]
n_token (int, optional): number of tokens in total. Defaults to None.
reduce (str, optional): aggregation method. Defaults to "mean".
Returns:
torch.Tensor: token-level embedding
[..., N_token, d]
"""
# Broadcasting in the given dim.
out = scatter(
src=x_atom, index=atom_to_token_idx, dim=-2, dim_size=n_token, reduce=reduce
)
return out
@register_license('bytedance2024')
def sample_indices(
n: int,
device: torch.device = torch.device("cpu"),
lower_bound=1,
strategy: str = "random",
) -> torch.Tensor:
"""Sample msa indices k from uniform[1,n]
Args:
n (int): the msa num
strategy (str): the strategy to sample msa index, random or topk
Returns:
torch.Tensor: the sampled indices k
"""
assert strategy in ["random", "topk"]
sample_size = torch.randint(low=min(lower_bound, n), high=n + 1, size=(1,)).item()
if strategy == "random":
indices = torch.randperm(n=n, device=device)[:sample_size]
if strategy == "topk":
indices = torch.arange(sample_size, device=device)
return indices
@register_license('bytedance2024')
def sample_msa_feature_dict_random_without_replacement(
feat_dict: dict[str, torch.Tensor],
dim_dict: dict[str, int],
cutoff: int = 512,
lower_bound: int = 1,
strategy: str = "random",
) -> dict[str, torch.Tensor]:
"""Sample a dict of MSA features randomly without replacement.
Args:
feat_dict (dict[str, torch.Tensor]): A dict containing the MSA features.
dim_dict (dict[str, int]): A dict containing the dimensions of the MSA features.
cutoff (int): The maximum number of features to sample.
lower_bound (int): The minimum number of features to sample.
strategy (str): The sampling strategy to use. Can be either "random" or "sequential".
Returns:
dict[str, torch.Tensor]: A dict containing the sampled MSA features.
"""
msa_len = feat_dict["msa"].size(dim=dim_dict["msa"])
indices = sample_indices(
n=msa_len,
device=feat_dict["msa"].device,
lower_bound=lower_bound,
strategy=strategy,
)
if cutoff > 0:
indices = indices[:cutoff]
msa_feat_dict = {
feat_name: torch.index_select(
input=feat_dict[feat_name], dim=dim, index=indices
)
for feat_name, dim in dim_dict.items()
}
return msa_feat_dict
@register_license('bytedance2024')
def expand_at_dim(x: torch.Tensor, dim: int, n: int) -> torch.Tensor:
"""expand a tensor at specific dim by n times
Args:
x (torch.Tensor): input
dim (int): dimension to expand
n (int): expand size
Returns:
torch.Tensor: expanded tensor of shape [..., n, ...]
"""
x = x.unsqueeze(dim=dim)
if dim < 0:
dim = x.dim() + dim
before_shape = x.shape[:dim]
after_shape = x.shape[dim + 1 :]
return x.expand(*before_shape, n, *after_shape)
@register_license('bytedance2024')
def pad_at_dim(
x: torch.Tensor,
dim: int,
pad_length: Union[tuple[int], list[int]],
value: float = 0,
) -> torch.Tensor:
"""pad to input x at dimension dim with length pad_length[0] to the left and and pad_length[1] to the right.
Args:
x (torch.Tensor): input
dim (int): padding dimension
pad_length (Union[Tuple[int], List[int]]): length to pad to the beginning and end.
Returns:
torch.Tensor: padded tensor
"""
n_dim = len(x.shape)
if dim < 0:
dim = n_dim + dim
pad = (pad_length[0], pad_length[1])
if pad == (0, 0):
return x
k = n_dim - (dim + 1)
if k > 0:
pad_skip = (0, 0) * k
pad = (*pad_skip, *pad)
return nn.functional.pad(x, pad=pad, value=value)
@register_license('bytedance2024')
def reshape_at_dim(
x: torch.Tensor, dim: int, target_shape: Union[tuple[int], list[int]]
) -> torch.Tensor:
"""reshape dimension dim of x to target_shape
Args:
x (torch.Tensor): input
dim (int): dimension to reshape
target_shape (Union[Tuple[int], List[int]]): target_shape of dim
Returns:
torch.Tensor: reshaped tensor
"""
n_dim = len(x.shape)
if dim < 0:
dim = n_dim + dim
target_shape = tuple(target_shape)
target_shape = (*x.shape[:dim], *target_shape)
if dim + 1 < n_dim:
target_shape = (*target_shape, *x.shape[dim + 1 :])
return x.reshape(target_shape)
@register_license('bytedance2024')
def move_final_dim_to_dim(x: torch.Tensor, dim: int) -> torch.Tensor:
"""
Move the final dimension of a tensor to a specified dimension.
Args:
x (torch.Tensor): Input tensor.
dim (int): Target dimension to move the final dimension to.
Returns:
torch.Tensor: Tensor with the final dimension moved to the specified dimension.
"""
# permute_final_dims
n_dim = len(x.shape)
if dim < 0:
dim = n_dim + dim
if dim >= n_dim - 1:
return x
new_order = (n_dim - 1,)
if dim > 0:
new_order = tuple(range(dim)) + new_order
if dim < n_dim - 1:
new_order = new_order + tuple(range(dim, n_dim - 1))
return x.permute(new_order)
@register_license('bytedance2024')
def simple_merge_dict_list(dict_list: list[dict]) -> dict:
"""
Merge a list of dictionaries into a single dictionary.
Args:
dict_list (list[dict]): List of dictionaries to merge.
Returns:
dict: Merged dictionary where values are concatenated arrays.
"""
merged_dict = {}
def add(key, value):
merged_dict.setdefault(key, [])
if isinstance(value, (float, int)):
value = np.array([value])
elif isinstance(value, torch.Tensor):
if value.dim() == 0:
value = np.array([value.item()])
else:
value = value.detach().cpu().numpy()
elif isinstance(value, np.ndarray):
pass
else:
raise ValueError(f"Unsupported type for metric data: {type(value)}")
merged_dict[key].append(value)
for x in dict_list:
for k, v in x.items():
add(k, v)
for k, v in merged_dict.items():
merged_dict[k] = np.concatenate(v)
return merged_dict
@register_license('odesign2025')
def reverse_centre_random_augmentation(
x_augment_coords: torch.Tensor,
trans: torch.Tensor,
rot: torch.Tensor,
x_center: torch.Tensor
) -> torch.Tensor:
"""
Reverse the centre random augmentation to recover original coordinates.
This function inverts the transformation applied by centre_random_augmentation
by applying inverse rotation, inverse translation, and restoring the original center.
Args:
x_augment_coords (torch.Tensor): Augmented coordinates to reverse.
Shape: [..., N_sample, N_atom, 3]
trans (torch.Tensor): Translation vector used in augmentation.
Shape: [..., N_sample, 3]
rot (torch.Tensor): Rotation matrix used in augmentation.
Shape: [..., N_sample, 3, 3]
x_center (torch.Tensor): Original center of the coordinates.
Shape: [..., 1, 3] or [..., N_atom, 3]
Returns:
torch.Tensor: Reversed coordinates in original space.
Shape: [..., N_sample, N_atom, 3]
"""
N_atom = x_augment_coords.size(-2)
# Apply inverse translation (subtract the translation vector)
x_reversed = x_augment_coords - trans[..., None, :]
# Apply inverse rotation (transpose of rotation matrix)
x_reversed = rot_vec_mul(
r=expand_at_dim(rot.transpose(-1, -2), dim=-3, n=N_atom),
t=x_reversed
)
# Restore to original center
x_reversed = x_reversed + x_center[..., None, :]
return x_reversed.view_as(x_augment_coords)
@register_license('bytedance2024')
def reverse_transformation(
augmented_coords: torch.Tensor,
trans: torch.Tensor,
rot: torch.Tensor,
center: torch.Tensor
) -> torch.Tensor:
"""
Alternative implementation for reversing coordinate transformation.
This function reverses the augmentation transformation using matrix operations.
Args:
augmented_coords (torch.Tensor): Augmented coordinates.
Shape: [..., N_atom, 3]
trans (torch.Tensor): Translation vector.
Shape: [..., 3]
rot (torch.Tensor): Rotation matrix.
Shape: [..., 3, 3]
center (torch.Tensor): Original center.
Shape: [..., 3]
Returns:
torch.Tensor: Original coordinates.
Shape: [..., N_atom, 3]
"""
coords_no_trans = augmented_coords - trans
inv_rot = rot.transpose(-2, -1)
coords_no_rot = inv_rot @ coords_no_trans.unsqueeze(-1)
coords_no_rot = coords_no_rot.squeeze(-1)
original_coords = coords_no_rot + center
return original_coords
@register_license('bytedance2024')
def count_parameters(model):
total_params = sum(p.numel() for p in model.parameters())
return total_params / 1000.0 / 1000.0
@register_license('bytedance2024')
def is_loss_nan_check(loss: torch.Tensor) -> bool:
"""check the validness of the current loss
Args:
loss: the loss from the model
Returns:
bool: if True, loss is not nan or inf
"""
def is_nan(x):
return torch.isnan(x).any() or torch.isinf(x).any()
def all_reduce_tensor(tensor, op=dist.ReduceOp.SUM):
if dist.is_initialized():
dist.all_reduce(tensor, op=op)
return tensor
nan_flag = torch.tensor(
1.0 if is_nan(loss) else 0.0,
device=loss.device if torch.cuda.is_available() else None,
) # support cpu
# avoid "Watchdog caught collective operation timeout" error
all_reduce_tensor(nan_flag)
if nan_flag.item() > 0.0:
return True
return False
@register_license('odesign2025')
def check_condition_atom_coords(x_denoised, x_gt, condition_mask):
if condition_mask.any():
N_sample = x_denoised.shape[0]
x_gt = x_gt.unsqueeze(dim=0).expand(N_sample, -1, -1)
if (
x_denoised[condition_mask] -
x_gt[condition_mask]
).abs().max() > 5e-3:
raise ValueError("Condition atom coords set error") |