# 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