File size: 16,194 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 | # Copyright 2024 ByteDance and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from typing import Optional
import torch
import torch.nn as nn
from src.model.modules.embedders import FourierEmbedding, RelativePositionEncoding
from src.model.modules.primitives import LinearNoBias, Transition
from src.model.modules.transformer import (
AtomAttentionDecoder,
AtomAttentionEncoder,
DiffusionTransformer,
)
from src.utils.model.misc import expand_at_dim
from src.utils.openfold_local.model.primitives import LayerNorm
from src.utils.openfold_local.utils.checkpointing import get_checkpoint_fn
from src.api.model_interface import (
PairFormerOutput,
DiffusionInput,
)
logger = logging.getLogger(__name__)
class DiffusionConditioning(nn.Module):
"""
Implements Algorithm 21 in AF3
"""
def __init__(
self,
sigma_data: float = 16.0,
c_z: int = 128,
c_s: int = 384,
c_s_inputs: int = 449,
c_noise_embedding: int = 256,
) -> None:
"""
Args:
sigma_data (torch.float, optional): the standard deviation of the data. Defaults to 16.0.
c_z (int, optional): hidden dim [for pair embedding]. Defaults to 128.
c_s (int, optional): hidden dim [for single embedding]. Defaults to 384.
c_s_inputs (int, optional): input embedding dim from InputEmbedder. Defaults to 449.
c_noise_embedding (int, optional): noise embedding dim. Defaults to 256.
"""
super(DiffusionConditioning, self).__init__()
self.sigma_data = sigma_data
self.c_z = c_z
self.c_s = c_s
self.c_s_inputs = c_s_inputs
# Line1-Line3:
self.relpe = RelativePositionEncoding(c_z=c_z)
self.layernorm_z = LayerNorm(2 * self.c_z, create_offset=False)
self.linear_no_bias_z = LinearNoBias(
in_features=2 * self.c_z, out_features=self.c_z, precision=torch.float32
)
# Line3-Line5:
self.transition_z1 = Transition(c_in=self.c_z, n=2)
self.transition_z2 = Transition(c_in=self.c_z, n=2)
# Line6-Line7
self.layernorm_s = LayerNorm(self.c_s + self.c_s_inputs, create_offset=False)
self.linear_no_bias_s = LinearNoBias(
in_features=self.c_s + self.c_s_inputs,
out_features=self.c_s,
precision=torch.float32,
)
# Line8-Line9
self.fourier_embedding = FourierEmbedding(c=c_noise_embedding)
self.layernorm_n = LayerNorm(c_noise_embedding, create_offset=False)
self.linear_no_bias_n = LinearNoBias(
in_features=c_noise_embedding,
out_features=self.c_s,
precision=torch.float32,
)
# Line10-Line12
self.transition_s1 = Transition(c_in=self.c_s, n=2)
self.transition_s2 = Transition(c_in=self.c_s, n=2)
logger.info(f"Diffusion module sigma_data: {self.sigma_data}")
def forward(
self,
t_hat_noise_level: torch.Tensor,
input_data: DiffusionInput,
s_inputs: torch.Tensor,
s_trunk: torch.Tensor,
z_trunk: torch.Tensor,
inplace_safe: bool = False,
use_conditioning: bool = True,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Args:
t_hat_noise_level (torch.Tensor): the noise level
[..., N_sample]
input_feature_dict (dict[str, Union[torch.Tensor, int, float, dict]]): input meta feature dict
s_inputs (torch.Tensor): single embedding from InputFeatureEmbedder
[..., N_tokens, c_s_inputs]
s_trunk (torch.Tensor): single feature embedding from PairFormer (Alg17)
[..., N_tokens, c_s]
z_trunk (torch.Tensor): pair feature embedding from PairFormer (Alg17)
[..., N_tokens, N_tokens, c_z]
inplace_safe (bool): Whether it is safe to use inplace operations.
use_conditioning (bool): Whether to drop the s/z embeddings.
Returns:
tuple[torch.Tensor, torch.Tensor]: embeddings s and z
- s (torch.Tensor): [..., N_sample, N_tokens, c_s]
- z (torch.Tensor): [..., N_tokens, N_tokens, c_z]
"""
if not use_conditioning:
if inplace_safe:
s_trunk *= 0
z_trunk *= 0
else:
s_trunk = 0 * s_trunk
z_trunk = 0 * z_trunk
# Pair conditioning
pair_z = torch.cat(
tensors=[z_trunk, self.relpe(input_data)], dim=-1
) # [..., N_tokens, N_tokens, 2*c_z]
pair_z = self.linear_no_bias_z(self.layernorm_z(pair_z))
if inplace_safe:
pair_z += self.transition_z1(pair_z)
pair_z += self.transition_z2(pair_z)
else:
pair_z = pair_z + self.transition_z1(pair_z)
pair_z = pair_z + self.transition_z2(pair_z)
# Single conditioning
single_s = torch.cat(
tensors=[s_trunk, s_inputs], dim=-1
) # [..., N_tokens, c_s + c_s_inputs]
single_s = self.linear_no_bias_s(self.layernorm_s(single_s))
noise_n = self.fourier_embedding(
t_hat_noise_level=torch.log(input=t_hat_noise_level / self.sigma_data) / 4
).to(
single_s.dtype
) # [..., N_sample, c_in]
single_s = single_s.unsqueeze(dim=-3) + self.linear_no_bias_n(
self.layernorm_n(noise_n)
).unsqueeze(
dim=-2
) # [..., N_sample, N_tokens, c_s]
if inplace_safe:
single_s += self.transition_s1(single_s)
single_s += self.transition_s2(single_s)
else:
single_s = single_s + self.transition_s1(single_s)
single_s = single_s + self.transition_s2(single_s)
if not self.training and pair_z.shape[-2] > 2000:
torch.cuda.empty_cache()
return single_s, pair_z
class DiffusionModule(nn.Module):
"""
Implements Algorithm 20 in AF3
"""
def __init__(
self,
sigma_data: float = 16.0,
c_atom: int = 128,
c_atompair: int = 16,
c_token: int = 768,
c_s: int = 384,
c_z: int = 128,
c_s_inputs: int = 449,
atom_encoder: dict[str, int] = {"n_blocks": 3, "n_heads": 4},
transformer: dict[str, int] = {
"n_blocks": 24,
"n_heads": 16,
"drop_path_rate": 0,
},
atom_decoder: dict[str, int] = {"n_blocks": 3, "n_heads": 4},
blocks_per_ckpt: Optional[int] = None,
use_fine_grained_checkpoint: bool = False,
) -> None:
"""
Args:
sigma_data (torch.float, optional): the standard deviation of the data. Defaults to 16.0.
c_atom (int, optional): embedding dim for atom feature. Defaults to 128.
c_atompair (int, optional): embedding dim for atompair feature. Defaults to 16.
c_token (int, optional): feature channel of token (single a). Defaults to 768.
c_s (int, optional): hidden dim [for single embedding]. Defaults to 384.
c_z (int, optional): hidden dim [for pair embedding]. Defaults to 128.
c_s_inputs (int, optional): hidden dim [for single input embedding]. Defaults to 449.
atom_encoder (dict[str, int], optional): configs in AtomAttentionEncoder. Defaults to {"n_blocks": 3, "n_heads": 4}.
transformer (dict[str, int], optional): configs in DiffusionTransformer. Defaults to {"n_blocks": 24, "n_heads": 16}.
atom_decoder (dict[str, int], optional): configs in AtomAttentionDecoder. Defaults to {"n_blocks": 3, "n_heads": 4}.
blocks_per_ckpt: number of atom_encoder/transformer/atom_decoder blocks in each activation checkpoint
Size of each chunk. A higher value corresponds to fewer
checkpoints, and trades memory for speed. If None, no checkpointing is performed.
use_fine_grained_checkpoint: whether use fine-gained checkpoint for finetuning stage 2
only effective if blocks_per_ckpt is not None.
"""
super(DiffusionModule, self).__init__()
self.sigma_data = sigma_data
self.c_atom = c_atom
self.c_atompair = c_atompair
self.c_token = c_token
self.c_s_inputs = c_s_inputs
self.c_s = c_s
self.c_z = c_z
# Grad checkpoint setting
self.blocks_per_ckpt = blocks_per_ckpt
self.use_fine_grained_checkpoint = use_fine_grained_checkpoint
self.diffusion_conditioning = DiffusionConditioning(
sigma_data=self.sigma_data, c_z=c_z, c_s=c_s, c_s_inputs=c_s_inputs
)
self.atom_attention_encoder = AtomAttentionEncoder(
**atom_encoder,
c_atom=c_atom,
c_atompair=c_atompair,
c_token=c_token,
has_coords=True,
c_s=c_s,
c_z=c_z,
blocks_per_ckpt=blocks_per_ckpt,
)
# Alg20: line4
self.layernorm_s = LayerNorm(c_s, create_offset=False)
self.linear_no_bias_s = LinearNoBias(
in_features=c_s,
out_features=c_token,
precision=torch.float32,
initializer="zeros",
)
self.diffusion_transformer = DiffusionTransformer(
**transformer,
c_a=c_token,
c_s=c_s,
c_z=c_z,
blocks_per_ckpt=blocks_per_ckpt,
)
self.layernorm_a = LayerNorm(c_token, create_offset=False)
self.atom_attention_decoder = AtomAttentionDecoder(
**atom_decoder,
c_token=c_token,
c_atom=c_atom,
c_atompair=c_atompair,
blocks_per_ckpt=blocks_per_ckpt,
)
def forward(
self,
x_noisy: torch.Tensor,
t_hat_noise_level: torch.Tensor,
input_data: DiffusionInput,
input_embedding: PairFormerOutput,
inplace_safe: bool = False,
chunk_size: Optional[int] = None,
use_conditioning: bool = True,
) -> torch.Tensor:
"""The raw network to be trained.
As in EDM equation (7), this is F_theta(c_in * x, c_noise(sigma)).
Here, c_noise(sigma) is computed in Conditioning module.
Args:
x_noisy (torch.Tensor): scaled x_noisy (i.e., c_in * x)
[..., N_sample, N_atom, 3]
t_hat_noise_level (torch.Tensor): the noise level, as well as the time step t
[..., N_sample]
input_data : input feature
input_embedding contains:
s_inputs (torch.Tensor): single embedding from InputFeatureEmbedder
[..., N_tokens, c_s_inputs]
s_trunk (torch.Tensor): single feature embedding from PairFormer (Alg17)
[..., N_tokens, c_s]
z_trunk (torch.Tensor): pair feature embedding from PairFormer (Alg17)
[..., N_tokens, N_tokens, c_z]
inplace_safe (bool): Whether it is safe to use inplace operations. Defaults to False.
chunk_size (Optional[int]): Chunk size for memory-efficient operations. Defaults to None.
use_conditioning (bool): Whether to drop the s/z embeddings in DiffusionConditioning.
Returns:
torch.Tensor: coordinates update
[..., N_sample, N_atom, 3]
"""
N_sample = x_noisy.size(-3)
assert t_hat_noise_level.size(-1) == N_sample
s_inputs, s_trunk, z_trunk = input_embedding.get_embedding()
blocks_per_ckpt = self.blocks_per_ckpt
if not torch.is_grad_enabled():
blocks_per_ckpt = None
# Conditioning, shared across difference samples
# Diffusion_conditioning consumes 7-8G when token num is 768,
# use checkpoint here if blocks_per_ckpt is not None.
if blocks_per_ckpt:
checkpoint_fn = get_checkpoint_fn()
s_single, z_pair = checkpoint_fn(
self.diffusion_conditioning,
t_hat_noise_level,
input_data,
s_inputs,
s_trunk,
z_trunk,
inplace_safe,
use_conditioning,
)
else:
s_single, z_pair = self.diffusion_conditioning(
t_hat_noise_level=t_hat_noise_level,
input_data=input_data,
s_inputs=s_inputs,
s_trunk=s_trunk,
z_trunk=z_trunk,
inplace_safe=inplace_safe,
use_conditioning=use_conditioning,
) # [..., N_sample, N_token, c_s], [..., N_token, N_token, c_z]
# Expand embeddings to match N_sample
s_trunk = expand_at_dim(
s_trunk, dim=-3, n=N_sample
) # [..., N_sample, N_token, c_s]
z_pair = expand_at_dim(
z_pair, dim=-4, n=N_sample
) # [..., N_sample, N_token, N_token, c_z]
# Fine-grained checkpoint for finetuning stage 2 (token num: 768) for avoiding OOM
if blocks_per_ckpt and self.use_fine_grained_checkpoint:
checkpoint_fn = get_checkpoint_fn()
a_token, q_skip, c_skip, p_skip = checkpoint_fn(
self.atom_attention_encoder,
input_data,
x_noisy,
s_trunk,
z_pair,
inplace_safe,
chunk_size,
)
else:
# Sequence-local Atom Attention and aggregation to coarse-grained tokens
a_token, q_skip, c_skip, p_skip = self.atom_attention_encoder(
input_data=input_data,
r_l=x_noisy,
s=s_trunk,
z=z_pair,
inplace_safe=inplace_safe,
chunk_size=chunk_size,
)
# Upcast
a_token = a_token.to(dtype=torch.float32)
# Full self-attention on token level.
if inplace_safe:
a_token += self.linear_no_bias_s(
self.layernorm_s(s_single)
) # [..., N_sample, N_token, c_token]
else:
a_token = a_token + self.linear_no_bias_s(
self.layernorm_s(s_single)
) # [..., N_sample, N_token, c_token]
a_token = self.diffusion_transformer(
a=a_token.to(dtype=torch.float32), # Upcast all inputs
s=s_single.to(dtype=torch.float32),
z=z_pair.to(dtype=torch.float32),
inplace_safe=inplace_safe,
chunk_size=chunk_size,
)
a_token = self.layernorm_a(a_token)
# Fine-grained checkpoint for finetuning stage 2 (token num: 768) for avoiding OOM
if blocks_per_ckpt and self.use_fine_grained_checkpoint:
checkpoint_fn = get_checkpoint_fn()
x_update = checkpoint_fn(
self.atom_attention_decoder,
input_data,
a_token,
q_skip,
c_skip,
p_skip,
inplace_safe,
chunk_size,
)
else:
# Broadcast token activations to atoms and run Sequence-local Atom Attention
x_update = self.atom_attention_decoder(
input_data=input_data,
a=a_token,
q_skip=q_skip,
c_skip=c_skip,
p_skip=p_skip,
inplace_safe=inplace_safe,
chunk_size=chunk_size,
)
return x_update
|