"""Fast diffusion conditioning for the captured AlphaFold3 shape.""" from __future__ import annotations import math import torch import torch.nn as nn import triton import triton.language as tl from ..L1.layer_norm import LayerNorm from ..L1.linear import Linear from .alphafold3_input_embedder import relpos_complex from .alphafold3_swiglu_transition import SwiGLUTransition __targets__ = ["DiffusionConditioning"] @triton.jit def _pair_input_ln(z, residue_index, scale, out, BLOCK: tl.constexpr): row = tl.program_id(0) col = tl.arange(0, BLOCK) i = row // 16 j = row - i * 16 z_col = tl.minimum(col, 127) z_val = tl.load(z + row * 128 + z_col, mask=col < 128, other=0.0) rcol = col - 128 # relpos_complex layout: residue, token, same-entity, chain. ri = tl.load(residue_index + i).to(tl.float32) rj = tl.load(residue_index + j).to(tl.float32) residue_delta = (ri - rj).to(tl.bfloat16).to(tl.float32) rel_pos_idx = (residue_delta + 32.0).to(tl.bfloat16).to(tl.float32) rel_pos_idx = tl.maximum(0.0, tl.minimum(64.0, rel_pos_idx)) rel_pos = (rcol.to(tl.float32) < rel_pos_idx) & (rcol >= 0) & (rcol < 66) token_idx = tl.where(ri == rj, (i - j + 32).to(tl.float32), 65.0) rel_token = (rcol - 66 < token_idx) & (rcol >= 66) & (rcol < 132) same_entity = rcol == 132 rel_chain = (rcol >= 133) & (rcol < 135) rel = (rel_pos | rel_token | same_entity | rel_chain).to(tl.float32) valid = col < 267 x = tl.where(col < 128, z_val, rel).to(tl.float32) x = tl.where(valid, x, 0.0) mean = tl.sum(x, axis=0) / 267.0 centered = tl.where(valid, x - mean, 0.0) var = tl.sum(centered * centered, axis=0) / 267.0 y = (x - mean) * tl.rsqrt(var + 1.0e-5) s = tl.load(scale + col, mask=valid, other=0.0).to(tl.float32) tl.store(out + row * 267 + col, y * s, mask=valid) @triton.jit def _single_input_ln(trunk, inp, scale, out, BLOCK: tl.constexpr): row = tl.program_id(0) col = tl.arange(0, BLOCK) tc = tl.minimum(col, 383) ic = tl.maximum(0, tl.minimum(col - 384, 448)) a = tl.load(trunk + row * 384 + tc, mask=col < 384, other=0.0) b = tl.load(inp + row * 449 + ic, mask=(col >= 384) & (col < 833), other=0.0) valid = col < 833 x = tl.where(col < 384, a, b).to(tl.float32) x = tl.where(valid, x, 0.0) mean = tl.sum(x, axis=0) / 833.0 centered = tl.where(valid, x - mean, 0.0) var = tl.sum(centered * centered, axis=0) / 833.0 y = (x - mean) * tl.rsqrt(var + 1.0e-5) s = tl.load(scale + col, mask=valid, other=0.0).to(tl.float32) tl.store(out + row * 833 + col, y * s, mask=valid) @triton.jit def _matmul( x, weight, out, M: tl.constexpr, N: tl.constexpr, K: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, ): pm = tl.program_id(0) pn = tl.program_id(1) rows = pm * BM + tl.arange(0, BM) cols = pn * BN + tl.arange(0, BN) acc = tl.zeros((BM, BN), tl.float32) for k0 in range(0, K, BK): ks = k0 + tl.arange(0, BK) a = tl.load( x + rows[:, None] * K + ks[None, :], mask=(rows[:, None] < M) & (ks[None, :] < K), other=0.0, ) b = tl.load( weight + cols[:, None] * K + ks[None, :], mask=(cols[:, None] < N) & (ks[None, :] < K), other=0.0, ) acc += tl.dot(a, tl.trans(b)) tl.store( out + rows[:, None] * N + cols[None, :], acc, mask=(rows[:, None] < M) & (cols[None, :] < N), ) @triton.jit def _transition_in( x, scale, wa, wb, hidden, M: tl.constexpr, C: tl.constexpr, H: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, BC: tl.constexpr, ): pm = tl.program_id(0) pn = tl.program_id(1) rows = pm * BM + tl.arange(0, BM) hcols = pn * BN + tl.arange(0, BN) all_c = tl.arange(0, BC) xv = tl.load( x + rows[:, None] * C + all_c[None, :], mask=(rows[:, None] < M) & (all_c[None, :] < C), other=0.0, ).to(tl.float32) mean = tl.sum(xv, axis=1) / C centered = tl.where(all_c[None, :] < C, xv - mean[:, None], 0.0) var = tl.sum(centered * centered, axis=1) / C rstd = tl.rsqrt(var + 1.0e-5) acc_a = tl.zeros((BM, BN), tl.float32) acc_b = tl.zeros((BM, BN), tl.float32) for k0 in range(0, C, BK): ks = k0 + tl.arange(0, BK) v = tl.load( x + rows[:, None] * C + ks[None, :], mask=(rows[:, None] < M) & (ks[None, :] < C), other=0.0, ).to(tl.float32) s = tl.load(scale + ks, mask=ks < C, other=0.0).to(tl.float32) norm = ((v - mean[:, None]) * rstd[:, None] * s[None, :]).to(tl.bfloat16) a = tl.load( wa + hcols[:, None] * C + ks[None, :], mask=(hcols[:, None] < H) & (ks[None, :] < C), other=0.0, ) b = tl.load( wb + hcols[:, None] * C + ks[None, :], mask=(hcols[:, None] < H) & (ks[None, :] < C), other=0.0, ) acc_a += tl.dot(norm, tl.trans(a)) acc_b += tl.dot(norm, tl.trans(b)) av = acc_a.to(tl.bfloat16).to(tl.float32) bv = acc_b.to(tl.bfloat16).to(tl.float32) silu = (av * tl.sigmoid(av)).to(tl.bfloat16).to(tl.float32) result = (silu * bv).to(tl.bfloat16) tl.store( hidden + rows[:, None] * H + hcols[None, :], result, mask=(rows[:, None] < M) & (hcols[None, :] < H), ) @triton.jit def _transition_out( hidden, weight, residual, token_mask, out, M: tl.constexpr, C: tl.constexpr, H: tl.constexpr, MASK_KIND: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, ): pm = tl.program_id(0) pn = tl.program_id(1) rows = pm * BM + tl.arange(0, BM) cols = pn * BN + tl.arange(0, BN) acc = tl.zeros((BM, BN), tl.float32) for k0 in range(0, H, BK): ks = k0 + tl.arange(0, BK) a = tl.load( hidden + rows[:, None] * H + ks[None, :], mask=(rows[:, None] < M) & (ks[None, :] < H), other=0.0, ) b = tl.load( weight + cols[:, None] * H + ks[None, :], mask=(cols[:, None] < C) & (ks[None, :] < H), other=0.0, ) acc += tl.dot(a, tl.trans(b)) if MASK_KIND == 1: mask = tl.load(token_mask + rows, mask=rows < M, other=0.0) else: i = rows // 16 j = rows - i * 16 mi = tl.load(token_mask + i, mask=rows < M, other=0.0) mj = tl.load(token_mask + j, mask=rows < M, other=0.0) mask = (mi * mj).to(tl.bfloat16) projected = acc.to(tl.bfloat16) projected = (projected * mask[:, None]).to(tl.bfloat16) old = tl.load( residual + rows[:, None] * C + cols[None, :], mask=(rows[:, None] < M) & (cols[None, :] < C), other=0.0, ) result = (old + projected).to(tl.bfloat16) tl.store( out + rows[:, None] * C + cols[None, :], result, mask=(rows[:, None] < M) & (cols[None, :] < C), ) @triton.jit def _noise_add(emb_ptr, ln_scale, weight, si, BN: tl.constexpr): pn = tl.program_id(0) cols = pn * BN + tl.arange(0, BN) ks = tl.arange(0, 256) emb = tl.load(emb_ptr + ks).to(tl.float32) mean = tl.sum(emb, axis=0) / 256.0 centered = emb - mean var = tl.sum(centered * centered, axis=0) / 256.0 scale = tl.load(ln_scale + ks).to(tl.float32) norm = (centered * tl.rsqrt(var + 1.0e-5) * scale).to(tl.bfloat16) ww = tl.load( weight + cols[:, None] * 256 + ks[None, :], mask=cols[:, None] < 384, other=0.0, ) projected = tl.dot(norm[None, :], tl.trans(ww)).to(tl.bfloat16) rows = tl.arange(0, 16) old = tl.load( si + rows[:, None] * 384 + cols[None, :], mask=cols[None, :] < 384, other=0.0, ) tl.store( si + rows[:, None] * 384 + cols[None, :], (old + projected).to(tl.bfloat16), mask=cols[None, :] < 384, ) class FourierEmbedding(nn.Module): def __init__(self, c: int = 256, seed: int = 42): super().__init__() self.c = c generator = torch.Generator() generator.manual_seed(seed) self.register_buffer("w", torch.randn(c, generator=generator)) self.register_buffer("b", torch.randn(c, generator=generator)) def forward(self, t: torch.Tensor) -> torch.Tensor: return torch.cos(2 * math.pi * (t * self.w + self.b)) class DiffusionConditioning(nn.Module): def __init__( self, c_s: int = 384, c_z: int = 128, c_s_input: int = 449, sigma_data: float = 16.0, relpos_k: int = 32, max_relative_chain: int = 2, c_fourier_emb: int = 256, seed_fourier_emb: int = 42, ): super().__init__() self.c_s = c_s self.c_z = c_z self.c_s_input = c_s_input self.c_fourier_emb = c_fourier_emb self.sigma_data = sigma_data self.relpos_k = relpos_k self.max_relative_chain = max_relative_chain relpos_dims = 2 * (2 * relpos_k + 2) + 2 * max_relative_chain + 3 self.layer_norm_z = LayerNorm(relpos_dims + c_z, create_offset=False) self.linear_z = Linear(relpos_dims + c_z, c_z, bias=False) self.transition_z = nn.ModuleList( [SwiGLUTransition(c_in=c_z, n=2) for _ in range(2)] ) self.layer_norm_s = LayerNorm(c_s + c_s_input, create_offset=False) self.linear_s = Linear(c_s + c_s_input, c_s, bias=False) self.fourier_emb = FourierEmbedding(c=c_fourier_emb, seed=seed_fourier_emb) self.layer_norm_n = LayerNorm(c_fourier_emb, create_offset=False) self.linear_n = Linear(c_fourier_emb, c_s, bias=False) self.transition_s = nn.ModuleList( [SwiGLUTransition(c_in=c_s, n=2) for _ in range(2)] ) def _can_use_fast_path( self, batch, t, si_input, si_trunk, zij_trunk, use_conditioning, ): return ( use_conditioning and t.is_cuda and t.dtype == torch.bfloat16 and t.numel() == 1 and si_input.shape == (1, 16, 449) and si_trunk.shape == (1, 16, 384) and zij_trunk.shape == (1, 16, 16, 128) and "asym_id" in batch and batch.get("token_mask") is not None and self.c_s == 384 and self.c_z == 128 and self.c_s_input == 449 and self.c_fourier_emb == 256 and self.relpos_k == 32 and self.max_relative_chain == 2 and self.sigma_data == 16.0 ) def _fast_forward(self, batch, t, si_input, si_trunk, zij_trunk): z_norm = torch.empty((256, 267), device=zij_trunk.device, dtype=torch.bfloat16) _pair_input_ln[(256,)]( zij_trunk, batch["residue_index"], self.layer_norm_z.weight, z_norm, BLOCK=512, num_warps=4, ) zij = torch.empty((256, 128), device=zij_trunk.device, dtype=torch.bfloat16) _matmul[(4, 2)]( z_norm, self.linear_z.weight, zij, M=256, N=128, K=267, BM=64, BN=64, BK=32, num_warps=8, ) s_norm = torch.empty((16, 833), device=si_input.device, dtype=torch.bfloat16) _single_input_ln[(16,)]( si_trunk, si_input, self.layer_norm_s.weight, s_norm, BLOCK=1024, num_warps=8, ) si = torch.empty((16, 384), device=si_input.device, dtype=torch.bfloat16) _matmul[(1, 3)]( s_norm, self.linear_s.weight, si, M=16, N=384, K=833, BM=16, BN=128, BK=32, num_warps=8, ) n = 0.25 * torch.log(t / self.sigma_data) n_emb = self.fourier_emb(n.unsqueeze(-1)) _noise_add[(6,)]( n_emb, self.layer_norm_n.weight, self.linear_n.weight, si, BN=64, num_warps=4, ) token_mask = batch["token_mask"] for layer in self.transition_z: hidden = torch.empty((256, 256), device=zij.device, dtype=torch.bfloat16) _transition_in[(8, 4)]( zij, layer.layer_norm.weight, layer.swiglu.linear_a.weight, layer.swiglu.linear_b.weight, hidden, M=256, C=128, H=256, BM=32, BN=64, BK=32, BC=128, num_warps=8, ) next_z = torch.empty_like(zij) _transition_out[(4, 2)]( hidden, layer.linear_out.weight, zij, token_mask, next_z, M=256, C=128, H=256, MASK_KIND=2, BM=64, BN=64, BK=32, num_warps=8, ) zij = next_z for layer in self.transition_s: hidden = torch.empty((16, 768), device=si.device, dtype=torch.bfloat16) _transition_in[(2, 24)]( si, layer.layer_norm.weight, layer.swiglu.linear_a.weight, layer.swiglu.linear_b.weight, hidden, M=16, C=384, H=768, BM=8, BN=32, BK=32, BC=512, num_warps=4, ) next_s = torch.empty_like(si) _transition_out[(1, 3)]( hidden, layer.linear_out.weight, si, token_mask, next_s, M=16, C=384, H=768, MASK_KIND=1, BM=16, BN=128, BK=32, num_warps=8, ) si = next_s return si.reshape(1, 16, 384), zij.reshape(1, 16, 16, 128) def _reference_forward( self, batch, t, si_input, si_trunk, zij_trunk, use_conditioning, ): if use_conditioning: if "asym_id" in batch: relpos_zij = relpos_complex( batch=batch, max_relative_idx=self.relpos_k, max_relative_chain=self.max_relative_chain, ).to(dtype=zij_trunk.dtype) else: relpos_dim = self.linear_z.weight.shape[-1] - self.c_z relpos_zij = zij_trunk.new_zeros( zij_trunk.shape[:-1] + (relpos_dim,) ) zij = self.linear_z(self.layer_norm_z(torch.cat([zij_trunk, relpos_zij], -1))) si = self.linear_s(self.layer_norm_s(torch.cat([si_trunk, si_input], -1))) else: zij = zij_trunk.new_zeros(zij_trunk.shape) si = si_trunk.new_zeros(si_trunk.shape[:-1] + (self.c_s,)) n = 0.25 * torch.log(t / self.sigma_data) n_emb = self.fourier_emb(n.unsqueeze(-1) if n.dim() == 0 else n) si = si + self.linear_n(self.layer_norm_n(n_emb)).unsqueeze(-2) token_mask = batch.get("token_mask") pair_mask = ( token_mask[..., :, None] * token_mask[..., None, :] if token_mask is not None else None ) for layer in self.transition_z: zij = zij + layer(zij, mask=pair_mask) for layer in self.transition_s: si = si + layer(si, mask=token_mask) return si, zij def forward( self, batch: dict, t: torch.Tensor, si_input: torch.Tensor, si_trunk: torch.Tensor, zij_trunk: torch.Tensor, use_conditioning: bool, chunk_size: int | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: if self._can_use_fast_path( batch, t, si_input, si_trunk, zij_trunk, use_conditioning ): return self._fast_forward(batch, t, si_input, si_trunk, zij_trunk) return self._reference_forward( batch, t, si_input, si_trunk, zij_trunk, use_conditioning )