Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- model/esm/esmfold/v1/__init__.py +0 -0
- model/esm/esmfold/v1/esmfold.py +364 -0
- model/esm/esmfold/v1/tri_self_attn_block.py +160 -0
- model/esm/esmfold/v1/trunk.py +245 -0
- model/esm/inverse_folding/gvp_modules.py +475 -0
- model/esm/inverse_folding/gvp_transformer.py +140 -0
- model/protenix/__init__.py +0 -0
- model/protenix/layer_norm/__init__.py +1 -0
- model/protenix/layer_norm/kernel/compat.h +9 -0
- model/protenix/layer_norm/kernel/layer_norm_cuda.cpp +179 -0
- model/protenix/layer_norm/kernel/layer_norm_cuda_kernel.cu +599 -0
- model/protenix/layer_norm/kernel/type_shim.h +231 -0
- model/protenix/layer_norm/layer_norm.py +198 -0
- model/protenix/layer_norm/torch_ext_compile.py +41 -0
- scripts/check_import_boundaries.py +67 -0
- scripts/download_weights.sh +65 -0
- scripts/esm2_infer_fairscale_fsdp_cpu_offloading.py +65 -0
- scripts/extract.py +149 -0
- scripts/fold.py +214 -0
- scripts/infer.sh +45 -0
- scripts/inverse_folding/sample_sequences.py +134 -0
- scripts/inverse_folding/score_log_likelihoods.py +140 -0
- scripts/variant_prediction/predict.py +265 -0
- tests/test_import_boundaries.py +47 -0
- weight/README.md +11 -0
- weight/esm-main/.flake8 +10 -0
- weight/esm-main/.git-blame-ignore-revs +2 -0
- weight/esm-main/.github/ISSUE_TEMPLATE/bug.md +27 -0
- weight/esm-main/.gitignore +31 -0
- weight/esm-main/CODE_OF_CONDUCT.rst +6 -0
- weight/esm-main/CONTRIBUTING.md +31 -0
- weight/esm-main/LICENSE +21 -0
- weight/esm-main/README.md +795 -0
- weight/esm-main/__pycache__/hubconf.cpython-311.pyc +0 -0
- weight/esm-main/environment.yml +36 -0
- weight/esm-main/esm/__init__.py +12 -0
- weight/esm-main/esm/__pycache__/__init__.cpython-311.pyc +0 -0
- weight/esm-main/esm/__pycache__/axial_attention.cpython-311.pyc +0 -0
- weight/esm-main/esm/__pycache__/constants.cpython-311.pyc +0 -0
- weight/esm-main/esm/__pycache__/data.cpython-311.pyc +0 -0
- weight/esm-main/esm/__pycache__/modules.cpython-311.pyc +0 -0
- weight/esm-main/esm/__pycache__/multihead_attention.cpython-311.pyc +0 -0
- weight/esm-main/esm/__pycache__/pretrained.cpython-311.pyc +0 -0
- weight/esm-main/esm/__pycache__/rotary_embedding.cpython-311.pyc +0 -0
- weight/esm-main/esm/__pycache__/version.cpython-311.pyc +0 -0
- weight/esm-main/esm/axial_attention.py +239 -0
- weight/esm-main/esm/constants.py +10 -0
- weight/esm-main/esm/data.py +493 -0
- weight/esm-main/esm/esmfold/v1/__init__.py +0 -0
- weight/esm-main/esm/esmfold/v1/categorical_mixture.py +43 -0
model/esm/esmfold/v1/__init__.py
ADDED
|
File without changes
|
model/esm/esmfold/v1/esmfold.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
import typing as T
|
| 6 |
+
from dataclasses import dataclass, field
|
| 7 |
+
from functools import partial
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from torch import nn
|
| 12 |
+
from torch.nn import LayerNorm
|
| 13 |
+
|
| 14 |
+
import model.esm as esm
|
| 15 |
+
from model.esm import Alphabet
|
| 16 |
+
from model.esm.esmfold.v1.categorical_mixture import categorical_lddt
|
| 17 |
+
from model.esm.esmfold.v1.misc import (
|
| 18 |
+
batch_encode_sequences,
|
| 19 |
+
collate_dense_tensors,
|
| 20 |
+
output_to_pdb,
|
| 21 |
+
)
|
| 22 |
+
from model.esm.esmfold.v1.trunk import FoldingTrunk, FoldingTrunkConfig
|
| 23 |
+
from onescience.datapipes.openfold.data_transforms import make_atom14_masks
|
| 24 |
+
from onescience.utils.openfold.np import residue_constants
|
| 25 |
+
from onescience.utils.openfold.loss import compute_predicted_aligned_error, compute_tm
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class ESMFoldConfig:
|
| 30 |
+
trunk: T.Any = field(default_factory=FoldingTrunkConfig)
|
| 31 |
+
lddt_head_hid_dim: int = 128
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
load_fn = esm.pretrained.load_model_and_alphabet
|
| 35 |
+
esm_registry = {
|
| 36 |
+
"esm2_8M": partial(load_fn, "esm2_t6_8M_UR50D_500K"),
|
| 37 |
+
"esm2_8M_270K": esm.pretrained.esm2_t6_8M_UR50D,
|
| 38 |
+
"esm2_35M": partial(load_fn, "esm2_t12_35M_UR50D_500K"),
|
| 39 |
+
"esm2_35M_270K": esm.pretrained.esm2_t12_35M_UR50D,
|
| 40 |
+
"esm2_150M": partial(load_fn, "esm2_t30_150M_UR50D_500K"),
|
| 41 |
+
"esm2_150M_270K": partial(load_fn, "esm2_t30_150M_UR50D_270K"),
|
| 42 |
+
"esm2_650M": esm.pretrained.esm2_t33_650M_UR50D,
|
| 43 |
+
"esm2_650M_270K": partial(load_fn, "esm2_t33_650M_270K_UR50D"),
|
| 44 |
+
"esm2_3B": esm.pretrained.esm2_t36_3B_UR50D,
|
| 45 |
+
"esm2_3B_270K": partial(load_fn, "esm2_t36_3B_UR50D_500K"),
|
| 46 |
+
"esm2_15B": esm.pretrained.esm2_t48_15B_UR50D,
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class ESMFold(nn.Module):
|
| 51 |
+
def __init__(self, esmfold_config=None, **kwargs):
|
| 52 |
+
super().__init__()
|
| 53 |
+
|
| 54 |
+
self.cfg = esmfold_config if esmfold_config else ESMFoldConfig(**kwargs)
|
| 55 |
+
cfg = self.cfg
|
| 56 |
+
|
| 57 |
+
self.distogram_bins = 64
|
| 58 |
+
|
| 59 |
+
self.esm, self.esm_dict = esm_registry.get(cfg.esm_type)()
|
| 60 |
+
|
| 61 |
+
self.esm.requires_grad_(False)
|
| 62 |
+
self.esm.half()
|
| 63 |
+
|
| 64 |
+
self.esm_feats = self.esm.embed_dim
|
| 65 |
+
self.esm_attns = self.esm.num_layers * self.esm.attention_heads
|
| 66 |
+
self.register_buffer("af2_to_esm", ESMFold._af2_to_esm(self.esm_dict))
|
| 67 |
+
self.esm_s_combine = nn.Parameter(torch.zeros(self.esm.num_layers + 1))
|
| 68 |
+
|
| 69 |
+
c_s = cfg.trunk.sequence_state_dim
|
| 70 |
+
c_z = cfg.trunk.pairwise_state_dim
|
| 71 |
+
|
| 72 |
+
self.esm_s_mlp = nn.Sequential(
|
| 73 |
+
LayerNorm(self.esm_feats),
|
| 74 |
+
nn.Linear(self.esm_feats, c_s),
|
| 75 |
+
nn.ReLU(),
|
| 76 |
+
nn.Linear(c_s, c_s),
|
| 77 |
+
)
|
| 78 |
+
if cfg.use_esm_attn_map:
|
| 79 |
+
self.esm_z_mlp = nn.Sequential(
|
| 80 |
+
LayerNorm(self.esm_attns),
|
| 81 |
+
nn.Linear(self.esm_attns, c_z),
|
| 82 |
+
nn.ReLU(),
|
| 83 |
+
nn.Linear(c_z, c_z),
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# 0 is padding, N is unknown residues, N + 1 is mask.
|
| 87 |
+
self.n_tokens_embed = residue_constants.restype_num + 3
|
| 88 |
+
self.pad_idx = 0
|
| 89 |
+
self.unk_idx = self.n_tokens_embed - 2
|
| 90 |
+
self.mask_idx = self.n_tokens_embed - 1
|
| 91 |
+
self.embedding = nn.Embedding(self.n_tokens_embed, c_s, padding_idx=0)
|
| 92 |
+
|
| 93 |
+
self.trunk = FoldingTrunk(**cfg.trunk)
|
| 94 |
+
|
| 95 |
+
self.distogram_head = nn.Linear(c_z, self.distogram_bins)
|
| 96 |
+
self.ptm_head = nn.Linear(c_z, self.distogram_bins)
|
| 97 |
+
self.lm_head = nn.Linear(c_s, self.n_tokens_embed)
|
| 98 |
+
self.lddt_bins = 50
|
| 99 |
+
self.lddt_head = nn.Sequential(
|
| 100 |
+
nn.LayerNorm(cfg.trunk.structure_module.c_s),
|
| 101 |
+
nn.Linear(cfg.trunk.structure_module.c_s, cfg.lddt_head_hid_dim),
|
| 102 |
+
nn.Linear(cfg.lddt_head_hid_dim, cfg.lddt_head_hid_dim),
|
| 103 |
+
nn.Linear(cfg.lddt_head_hid_dim, 37 * self.lddt_bins),
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
@staticmethod
|
| 107 |
+
def _af2_to_esm(d: Alphabet):
|
| 108 |
+
# Remember that t is shifted from residue_constants by 1 (0 is padding).
|
| 109 |
+
esm_reorder = [d.padding_idx] + [
|
| 110 |
+
d.get_idx(v) for v in residue_constants.restypes_with_x
|
| 111 |
+
]
|
| 112 |
+
return torch.tensor(esm_reorder)
|
| 113 |
+
|
| 114 |
+
def _af2_idx_to_esm_idx(self, aa, mask):
|
| 115 |
+
aa = (aa + 1).masked_fill(mask != 1, 0)
|
| 116 |
+
return self.af2_to_esm[aa]
|
| 117 |
+
|
| 118 |
+
def _compute_language_model_representations(
|
| 119 |
+
self, esmaa: torch.Tensor
|
| 120 |
+
) -> torch.Tensor:
|
| 121 |
+
"""Adds bos/eos tokens for the language model, since the structure module doesn't use these."""
|
| 122 |
+
batch_size = esmaa.size(0)
|
| 123 |
+
|
| 124 |
+
bosi, eosi = self.esm_dict.cls_idx, self.esm_dict.eos_idx
|
| 125 |
+
bos = esmaa.new_full((batch_size, 1), bosi)
|
| 126 |
+
eos = esmaa.new_full((batch_size, 1), self.esm_dict.padding_idx)
|
| 127 |
+
esmaa = torch.cat([bos, esmaa, eos], dim=1)
|
| 128 |
+
# Use the first padding index as eos during inference.
|
| 129 |
+
esmaa[range(batch_size), (esmaa != 1).sum(1)] = eosi
|
| 130 |
+
|
| 131 |
+
res = self.esm(
|
| 132 |
+
esmaa,
|
| 133 |
+
repr_layers=range(self.esm.num_layers + 1),
|
| 134 |
+
need_head_weights=self.cfg.use_esm_attn_map,
|
| 135 |
+
)
|
| 136 |
+
esm_s = torch.stack(
|
| 137 |
+
[v for _, v in sorted(res["representations"].items())], dim=2
|
| 138 |
+
)
|
| 139 |
+
esm_s = esm_s[:, 1:-1] # B, L, nLayers, C
|
| 140 |
+
esm_z = (
|
| 141 |
+
res["attentions"].permute(0, 4, 3, 1, 2).flatten(3, 4)[:, 1:-1, 1:-1, :]
|
| 142 |
+
if self.cfg.use_esm_attn_map
|
| 143 |
+
else None
|
| 144 |
+
)
|
| 145 |
+
return esm_s, esm_z
|
| 146 |
+
|
| 147 |
+
def _mask_inputs_to_esm(self, esmaa, pattern):
|
| 148 |
+
new_esmaa = esmaa.clone()
|
| 149 |
+
new_esmaa[pattern == 1] = self.esm_dict.mask_idx
|
| 150 |
+
return new_esmaa
|
| 151 |
+
|
| 152 |
+
def forward(
|
| 153 |
+
self,
|
| 154 |
+
aa: torch.Tensor,
|
| 155 |
+
mask: T.Optional[torch.Tensor] = None,
|
| 156 |
+
residx: T.Optional[torch.Tensor] = None,
|
| 157 |
+
masking_pattern: T.Optional[torch.Tensor] = None,
|
| 158 |
+
num_recycles: T.Optional[int] = None,
|
| 159 |
+
):
|
| 160 |
+
"""Runs a forward pass given input tokens. Use `model.infer` to
|
| 161 |
+
run inference from a sequence.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
aa (torch.Tensor): Tensor containing indices corresponding to amino acids. Indices match
|
| 165 |
+
onescience.utils.openfold.np.residue_constants.restype_order_with_x.
|
| 166 |
+
mask (torch.Tensor): Binary tensor with 1 meaning position is unmasked and 0 meaning position is masked.
|
| 167 |
+
residx (torch.Tensor): Residue indices of amino acids. Will assume contiguous if not provided.
|
| 168 |
+
masking_pattern (torch.Tensor): Optional masking to pass to the input. Binary tensor of the same size
|
| 169 |
+
as `aa`. Positions with 1 will be masked. ESMFold sometimes produces different samples when
|
| 170 |
+
different masks are provided.
|
| 171 |
+
num_recycles (int): How many recycle iterations to perform. If None, defaults to training max
|
| 172 |
+
recycles, which is 3.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
if mask is None:
|
| 176 |
+
mask = torch.ones_like(aa)
|
| 177 |
+
|
| 178 |
+
B = aa.shape[0]
|
| 179 |
+
L = aa.shape[1]
|
| 180 |
+
device = aa.device
|
| 181 |
+
|
| 182 |
+
if residx is None:
|
| 183 |
+
residx = torch.arange(L, device=device).expand_as(aa)
|
| 184 |
+
|
| 185 |
+
# === ESM ===
|
| 186 |
+
esmaa = self._af2_idx_to_esm_idx(aa, mask)
|
| 187 |
+
|
| 188 |
+
if masking_pattern is not None:
|
| 189 |
+
esmaa = self._mask_inputs_to_esm(esmaa, masking_pattern)
|
| 190 |
+
|
| 191 |
+
esm_s, esm_z = self._compute_language_model_representations(esmaa)
|
| 192 |
+
|
| 193 |
+
# Convert esm_s to the precision used by the trunk and
|
| 194 |
+
# the structure module. These tensors may be a lower precision if, for example,
|
| 195 |
+
# we're running the language model in fp16 precision.
|
| 196 |
+
esm_s = esm_s.to(self.esm_s_combine.dtype)
|
| 197 |
+
esm_s = esm_s.detach()
|
| 198 |
+
|
| 199 |
+
# === preprocessing ===
|
| 200 |
+
esm_s = (self.esm_s_combine.softmax(0).unsqueeze(0) @ esm_s).squeeze(2)
|
| 201 |
+
|
| 202 |
+
s_s_0 = self.esm_s_mlp(esm_s)
|
| 203 |
+
if self.cfg.use_esm_attn_map:
|
| 204 |
+
esm_z = esm_z.to(self.esm_s_combine.dtype)
|
| 205 |
+
esm_z = esm_z.detach()
|
| 206 |
+
s_z_0 = self.esm_z_mlp(esm_z)
|
| 207 |
+
else:
|
| 208 |
+
s_z_0 = s_s_0.new_zeros(B, L, L, self.cfg.trunk.pairwise_state_dim)
|
| 209 |
+
|
| 210 |
+
s_s_0 += self.embedding(aa)
|
| 211 |
+
|
| 212 |
+
structure: dict = self.trunk(
|
| 213 |
+
s_s_0, s_z_0, aa, residx, mask, no_recycles=num_recycles
|
| 214 |
+
)
|
| 215 |
+
# Documenting what we expect:
|
| 216 |
+
structure = {
|
| 217 |
+
k: v
|
| 218 |
+
for k, v in structure.items()
|
| 219 |
+
if k
|
| 220 |
+
in [
|
| 221 |
+
"s_z",
|
| 222 |
+
"s_s",
|
| 223 |
+
"frames",
|
| 224 |
+
"sidechain_frames",
|
| 225 |
+
"unnormalized_angles",
|
| 226 |
+
"angles",
|
| 227 |
+
"positions",
|
| 228 |
+
"states",
|
| 229 |
+
]
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
disto_logits = self.distogram_head(structure["s_z"])
|
| 233 |
+
disto_logits = (disto_logits + disto_logits.transpose(1, 2)) / 2
|
| 234 |
+
structure["distogram_logits"] = disto_logits
|
| 235 |
+
|
| 236 |
+
lm_logits = self.lm_head(structure["s_s"])
|
| 237 |
+
structure["lm_logits"] = lm_logits
|
| 238 |
+
|
| 239 |
+
structure["aatype"] = aa
|
| 240 |
+
make_atom14_masks(structure)
|
| 241 |
+
|
| 242 |
+
for k in [
|
| 243 |
+
"atom14_atom_exists",
|
| 244 |
+
"atom37_atom_exists",
|
| 245 |
+
]:
|
| 246 |
+
structure[k] *= mask.unsqueeze(-1)
|
| 247 |
+
structure["residue_index"] = residx
|
| 248 |
+
|
| 249 |
+
lddt_head = self.lddt_head(structure["states"]).reshape(
|
| 250 |
+
structure["states"].shape[0], B, L, -1, self.lddt_bins
|
| 251 |
+
)
|
| 252 |
+
structure["lddt_head"] = lddt_head
|
| 253 |
+
plddt = categorical_lddt(lddt_head[-1], bins=self.lddt_bins)
|
| 254 |
+
structure["plddt"] = (
|
| 255 |
+
100 * plddt
|
| 256 |
+
) # we predict plDDT between 0 and 1, scale to be between 0 and 100.
|
| 257 |
+
|
| 258 |
+
ptm_logits = self.ptm_head(structure["s_z"])
|
| 259 |
+
|
| 260 |
+
seqlen = mask.type(torch.int64).sum(1)
|
| 261 |
+
structure["ptm_logits"] = ptm_logits
|
| 262 |
+
structure["ptm"] = torch.stack(
|
| 263 |
+
[
|
| 264 |
+
compute_tm(
|
| 265 |
+
batch_ptm_logits[None, :sl, :sl],
|
| 266 |
+
max_bins=31,
|
| 267 |
+
no_bins=self.distogram_bins,
|
| 268 |
+
)
|
| 269 |
+
for batch_ptm_logits, sl in zip(ptm_logits, seqlen)
|
| 270 |
+
]
|
| 271 |
+
)
|
| 272 |
+
structure.update(
|
| 273 |
+
compute_predicted_aligned_error(
|
| 274 |
+
ptm_logits, max_bin=31, no_bins=self.distogram_bins
|
| 275 |
+
)
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
return structure
|
| 279 |
+
|
| 280 |
+
@torch.no_grad()
|
| 281 |
+
def infer(
|
| 282 |
+
self,
|
| 283 |
+
sequences: T.Union[str, T.List[str]],
|
| 284 |
+
residx=None,
|
| 285 |
+
masking_pattern: T.Optional[torch.Tensor] = None,
|
| 286 |
+
num_recycles: T.Optional[int] = None,
|
| 287 |
+
residue_index_offset: T.Optional[int] = 512,
|
| 288 |
+
chain_linker: T.Optional[str] = "G" * 25,
|
| 289 |
+
):
|
| 290 |
+
"""Runs a forward pass given input sequences.
|
| 291 |
+
|
| 292 |
+
Args:
|
| 293 |
+
sequences (Union[str, List[str]]): A list of sequences to make predictions for. Multimers can also be passed in,
|
| 294 |
+
each chain should be separated by a ':' token (e.g. "<chain1>:<chain2>:<chain3>").
|
| 295 |
+
residx (torch.Tensor): Residue indices of amino acids. Will assume contiguous if not provided.
|
| 296 |
+
masking_pattern (torch.Tensor): Optional masking to pass to the input. Binary tensor of the same size
|
| 297 |
+
as `aa`. Positions with 1 will be masked. ESMFold sometimes produces different samples when
|
| 298 |
+
different masks are provided.
|
| 299 |
+
num_recycles (int): How many recycle iterations to perform. If None, defaults to training max
|
| 300 |
+
recycles (cfg.trunk.max_recycles), which is 4.
|
| 301 |
+
residue_index_offset (int): Residue index separation between chains if predicting a multimer. Has no effect on
|
| 302 |
+
single chain predictions. Default: 512.
|
| 303 |
+
chain_linker (str): Linker to use between chains if predicting a multimer. Has no effect on single chain
|
| 304 |
+
predictions. Default: length-25 poly-G ("G" * 25).
|
| 305 |
+
"""
|
| 306 |
+
if isinstance(sequences, str):
|
| 307 |
+
sequences = [sequences]
|
| 308 |
+
|
| 309 |
+
aatype, mask, _residx, linker_mask, chain_index = batch_encode_sequences(
|
| 310 |
+
sequences, residue_index_offset, chain_linker
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
if residx is None:
|
| 314 |
+
residx = _residx
|
| 315 |
+
elif not isinstance(residx, torch.Tensor):
|
| 316 |
+
residx = collate_dense_tensors(residx)
|
| 317 |
+
|
| 318 |
+
aatype, mask, residx, linker_mask = map(
|
| 319 |
+
lambda x: x.to(self.device), (aatype, mask, residx, linker_mask)
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
output = self.forward(
|
| 323 |
+
aatype,
|
| 324 |
+
mask=mask,
|
| 325 |
+
residx=residx,
|
| 326 |
+
masking_pattern=masking_pattern,
|
| 327 |
+
num_recycles=num_recycles,
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
output["atom37_atom_exists"] = output[
|
| 331 |
+
"atom37_atom_exists"
|
| 332 |
+
] * linker_mask.unsqueeze(2)
|
| 333 |
+
|
| 334 |
+
output["mean_plddt"] = (output["plddt"] * output["atom37_atom_exists"]).sum(
|
| 335 |
+
dim=(1, 2)
|
| 336 |
+
) / output["atom37_atom_exists"].sum(dim=(1, 2))
|
| 337 |
+
output["chain_index"] = chain_index
|
| 338 |
+
|
| 339 |
+
return output
|
| 340 |
+
|
| 341 |
+
def output_to_pdb(self, output: T.Dict) -> T.List[str]:
|
| 342 |
+
"""Returns the pbd (file) string from the model given the model output."""
|
| 343 |
+
return output_to_pdb(output)
|
| 344 |
+
|
| 345 |
+
def infer_pdbs(self, seqs: T.List[str], *args, **kwargs) -> T.List[str]:
|
| 346 |
+
"""Returns list of pdb (files) strings from the model given a list of input sequences."""
|
| 347 |
+
output = self.infer(seqs, *args, **kwargs)
|
| 348 |
+
return self.output_to_pdb(output)
|
| 349 |
+
|
| 350 |
+
def infer_pdb(self, sequence: str, *args, **kwargs) -> str:
|
| 351 |
+
"""Returns the pdb (file) string from the model given an input sequence."""
|
| 352 |
+
return self.infer_pdbs([sequence], *args, **kwargs)[0]
|
| 353 |
+
|
| 354 |
+
def set_chunk_size(self, chunk_size: T.Optional[int]):
|
| 355 |
+
# This parameter means the axial attention will be computed
|
| 356 |
+
# in a chunked manner. This should make the memory used more or less O(L) instead of O(L^2).
|
| 357 |
+
# It's equivalent to running a for loop over chunks of the dimension we're iterative over,
|
| 358 |
+
# where the chunk_size is the size of the chunks, so 128 would mean to parse 128-lengthed chunks.
|
| 359 |
+
# Setting the value to None will return to default behavior, disable chunking.
|
| 360 |
+
self.trunk.set_chunk_size(chunk_size)
|
| 361 |
+
|
| 362 |
+
@property
|
| 363 |
+
def device(self):
|
| 364 |
+
return self.esm_s_combine.device
|
model/esm/esmfold/v1/tri_self_attn_block.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
import torch
|
| 6 |
+
from model.openfold.triangular_attention import (
|
| 7 |
+
TriangleAttentionEndingNode,
|
| 8 |
+
TriangleAttentionStartingNode,
|
| 9 |
+
)
|
| 10 |
+
from model.openfold.triangular_multiplicative_update import (
|
| 11 |
+
TriangleMultiplicationIncoming,
|
| 12 |
+
TriangleMultiplicationOutgoing,
|
| 13 |
+
)
|
| 14 |
+
from torch import nn
|
| 15 |
+
|
| 16 |
+
from model.esm.esmfold.v1.misc import (
|
| 17 |
+
Attention,
|
| 18 |
+
Dropout,
|
| 19 |
+
PairToSequence,
|
| 20 |
+
ResidueMLP,
|
| 21 |
+
SequenceToPair,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TriangularSelfAttentionBlock(nn.Module):
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
sequence_state_dim,
|
| 29 |
+
pairwise_state_dim,
|
| 30 |
+
sequence_head_width,
|
| 31 |
+
pairwise_head_width,
|
| 32 |
+
dropout=0,
|
| 33 |
+
**__kwargs,
|
| 34 |
+
):
|
| 35 |
+
super().__init__()
|
| 36 |
+
|
| 37 |
+
assert sequence_state_dim % sequence_head_width == 0
|
| 38 |
+
assert pairwise_state_dim % pairwise_head_width == 0
|
| 39 |
+
sequence_num_heads = sequence_state_dim // sequence_head_width
|
| 40 |
+
pairwise_num_heads = pairwise_state_dim // pairwise_head_width
|
| 41 |
+
assert sequence_state_dim == sequence_num_heads * sequence_head_width
|
| 42 |
+
assert pairwise_state_dim == pairwise_num_heads * pairwise_head_width
|
| 43 |
+
assert pairwise_state_dim % 2 == 0
|
| 44 |
+
|
| 45 |
+
self.sequence_state_dim = sequence_state_dim
|
| 46 |
+
self.pairwise_state_dim = pairwise_state_dim
|
| 47 |
+
|
| 48 |
+
self.layernorm_1 = nn.LayerNorm(sequence_state_dim)
|
| 49 |
+
|
| 50 |
+
self.sequence_to_pair = SequenceToPair(
|
| 51 |
+
sequence_state_dim, pairwise_state_dim // 2, pairwise_state_dim
|
| 52 |
+
)
|
| 53 |
+
self.pair_to_sequence = PairToSequence(pairwise_state_dim, sequence_num_heads)
|
| 54 |
+
|
| 55 |
+
self.seq_attention = Attention(
|
| 56 |
+
sequence_state_dim, sequence_num_heads, sequence_head_width, gated=True
|
| 57 |
+
)
|
| 58 |
+
self.tri_mul_out = TriangleMultiplicationOutgoing(
|
| 59 |
+
pairwise_state_dim,
|
| 60 |
+
pairwise_state_dim,
|
| 61 |
+
)
|
| 62 |
+
self.tri_mul_in = TriangleMultiplicationIncoming(
|
| 63 |
+
pairwise_state_dim,
|
| 64 |
+
pairwise_state_dim,
|
| 65 |
+
)
|
| 66 |
+
self.tri_att_start = TriangleAttentionStartingNode(
|
| 67 |
+
pairwise_state_dim,
|
| 68 |
+
pairwise_head_width,
|
| 69 |
+
pairwise_num_heads,
|
| 70 |
+
inf=1e9,
|
| 71 |
+
) # type: ignore
|
| 72 |
+
self.tri_att_end = TriangleAttentionEndingNode(
|
| 73 |
+
pairwise_state_dim,
|
| 74 |
+
pairwise_head_width,
|
| 75 |
+
pairwise_num_heads,
|
| 76 |
+
inf=1e9,
|
| 77 |
+
) # type: ignore
|
| 78 |
+
|
| 79 |
+
self.mlp_seq = ResidueMLP(sequence_state_dim, 4 * sequence_state_dim, dropout=dropout)
|
| 80 |
+
self.mlp_pair = ResidueMLP(pairwise_state_dim, 4 * pairwise_state_dim, dropout=dropout)
|
| 81 |
+
|
| 82 |
+
assert dropout < 0.4
|
| 83 |
+
self.drop = nn.Dropout(dropout)
|
| 84 |
+
self.row_drop = Dropout(dropout * 2, 2)
|
| 85 |
+
self.col_drop = Dropout(dropout * 2, 1)
|
| 86 |
+
|
| 87 |
+
torch.nn.init.zeros_(self.tri_mul_in.linear_z.weight)
|
| 88 |
+
torch.nn.init.zeros_(self.tri_mul_in.linear_z.bias)
|
| 89 |
+
torch.nn.init.zeros_(self.tri_mul_out.linear_z.weight)
|
| 90 |
+
torch.nn.init.zeros_(self.tri_mul_out.linear_z.bias)
|
| 91 |
+
torch.nn.init.zeros_(self.tri_att_start.mha.linear_o.weight)
|
| 92 |
+
torch.nn.init.zeros_(self.tri_att_start.mha.linear_o.bias)
|
| 93 |
+
torch.nn.init.zeros_(self.tri_att_end.mha.linear_o.weight)
|
| 94 |
+
torch.nn.init.zeros_(self.tri_att_end.mha.linear_o.bias)
|
| 95 |
+
|
| 96 |
+
torch.nn.init.zeros_(self.sequence_to_pair.o_proj.weight)
|
| 97 |
+
torch.nn.init.zeros_(self.sequence_to_pair.o_proj.bias)
|
| 98 |
+
torch.nn.init.zeros_(self.pair_to_sequence.linear.weight)
|
| 99 |
+
torch.nn.init.zeros_(self.seq_attention.o_proj.weight)
|
| 100 |
+
torch.nn.init.zeros_(self.seq_attention.o_proj.bias)
|
| 101 |
+
torch.nn.init.zeros_(self.mlp_seq.mlp[-2].weight)
|
| 102 |
+
torch.nn.init.zeros_(self.mlp_seq.mlp[-2].bias)
|
| 103 |
+
torch.nn.init.zeros_(self.mlp_pair.mlp[-2].weight)
|
| 104 |
+
torch.nn.init.zeros_(self.mlp_pair.mlp[-2].bias)
|
| 105 |
+
|
| 106 |
+
def forward(self, sequence_state, pairwise_state, mask=None, chunk_size=None, **__kwargs):
|
| 107 |
+
"""
|
| 108 |
+
Inputs:
|
| 109 |
+
sequence_state: B x L x sequence_state_dim
|
| 110 |
+
pairwise_state: B x L x L x pairwise_state_dim
|
| 111 |
+
mask: B x L boolean tensor of valid positions
|
| 112 |
+
|
| 113 |
+
Output:
|
| 114 |
+
sequence_state: B x L x sequence_state_dim
|
| 115 |
+
pairwise_state: B x L x L x pairwise_state_dim
|
| 116 |
+
"""
|
| 117 |
+
assert len(sequence_state.shape) == 3
|
| 118 |
+
assert len(pairwise_state.shape) == 4
|
| 119 |
+
if mask is not None:
|
| 120 |
+
assert len(mask.shape) == 2
|
| 121 |
+
|
| 122 |
+
batch_dim, seq_dim, sequence_state_dim = sequence_state.shape
|
| 123 |
+
pairwise_state_dim = pairwise_state.shape[3]
|
| 124 |
+
assert sequence_state_dim == self.sequence_state_dim
|
| 125 |
+
assert pairwise_state_dim == self.pairwise_state_dim
|
| 126 |
+
assert batch_dim == pairwise_state.shape[0]
|
| 127 |
+
assert seq_dim == pairwise_state.shape[1]
|
| 128 |
+
assert seq_dim == pairwise_state.shape[2]
|
| 129 |
+
|
| 130 |
+
# Update sequence state
|
| 131 |
+
bias = self.pair_to_sequence(pairwise_state)
|
| 132 |
+
|
| 133 |
+
# Self attention with bias + mlp.
|
| 134 |
+
y = self.layernorm_1(sequence_state)
|
| 135 |
+
y, _ = self.seq_attention(y, mask=mask, bias=bias)
|
| 136 |
+
sequence_state = sequence_state + self.drop(y)
|
| 137 |
+
sequence_state = self.mlp_seq(sequence_state)
|
| 138 |
+
|
| 139 |
+
# Update pairwise state
|
| 140 |
+
pairwise_state = pairwise_state + self.sequence_to_pair(sequence_state)
|
| 141 |
+
|
| 142 |
+
# Axial attention with triangular bias.
|
| 143 |
+
tri_mask = mask.unsqueeze(2) * mask.unsqueeze(1) if mask is not None else None
|
| 144 |
+
pairwise_state = pairwise_state + self.row_drop(
|
| 145 |
+
self.tri_mul_out(pairwise_state, mask=tri_mask)
|
| 146 |
+
)
|
| 147 |
+
pairwise_state = pairwise_state + self.col_drop(
|
| 148 |
+
self.tri_mul_in(pairwise_state, mask=tri_mask)
|
| 149 |
+
)
|
| 150 |
+
pairwise_state = pairwise_state + self.row_drop(
|
| 151 |
+
self.tri_att_start(pairwise_state, mask=tri_mask, chunk_size=chunk_size)
|
| 152 |
+
)
|
| 153 |
+
pairwise_state = pairwise_state + self.col_drop(
|
| 154 |
+
self.tri_att_end(pairwise_state, mask=tri_mask, chunk_size=chunk_size)
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# MLP over pairs.
|
| 158 |
+
pairwise_state = self.mlp_pair(pairwise_state)
|
| 159 |
+
|
| 160 |
+
return sequence_state, pairwise_state
|
model/esm/esmfold/v1/trunk.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
import typing as T
|
| 6 |
+
from contextlib import ExitStack
|
| 7 |
+
# from dataclasses import dataclass
|
| 8 |
+
from dataclasses import dataclass, field
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
from model.openfold.structure_module import StructureModule
|
| 13 |
+
|
| 14 |
+
from model.esm.esmfold.v1.tri_self_attn_block import TriangularSelfAttentionBlock
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class StructureModuleConfig:
|
| 19 |
+
c_s: int = 384
|
| 20 |
+
c_z: int = 128
|
| 21 |
+
c_ipa: int = 16
|
| 22 |
+
c_resnet: int = 128
|
| 23 |
+
no_heads_ipa: int = 12
|
| 24 |
+
no_qk_points: int = 4
|
| 25 |
+
no_v_points: int = 8
|
| 26 |
+
dropout_rate: float = 0.1
|
| 27 |
+
no_blocks: int = 8
|
| 28 |
+
no_transition_layers: int = 1
|
| 29 |
+
no_resnet_blocks: int = 2
|
| 30 |
+
no_angles: int = 7
|
| 31 |
+
trans_scale_factor: int = 10
|
| 32 |
+
epsilon: float = 1e-8
|
| 33 |
+
inf: float = 1e5
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass
|
| 37 |
+
class FoldingTrunkConfig:
|
| 38 |
+
_name: str = "FoldingTrunkConfig"
|
| 39 |
+
num_blocks: int = 48
|
| 40 |
+
sequence_state_dim: int = 1024
|
| 41 |
+
pairwise_state_dim: int = 128
|
| 42 |
+
sequence_head_width: int = 32
|
| 43 |
+
pairwise_head_width: int = 32
|
| 44 |
+
position_bins: int = 32
|
| 45 |
+
dropout: float = 0
|
| 46 |
+
layer_drop: float = 0
|
| 47 |
+
cpu_grad_checkpoint: bool = False
|
| 48 |
+
|
| 49 |
+
max_recycles: int = 4
|
| 50 |
+
chunk_size: T.Optional[int] = None
|
| 51 |
+
|
| 52 |
+
# structure_module: StructureModuleConfig = StructureModuleConfig()
|
| 53 |
+
structure_module: StructureModuleConfig = field(default_factory=StructureModuleConfig)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_axial_mask(mask):
|
| 57 |
+
"""
|
| 58 |
+
Helper to convert B x L mask of valid positions to axial mask used
|
| 59 |
+
in row column attentions.
|
| 60 |
+
|
| 61 |
+
Input:
|
| 62 |
+
mask: B x L tensor of booleans
|
| 63 |
+
|
| 64 |
+
Output:
|
| 65 |
+
mask: B x L x L tensor of booleans
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
if mask is None:
|
| 69 |
+
return None
|
| 70 |
+
assert len(mask.shape) == 2
|
| 71 |
+
batch_dim, seq_dim = mask.shape
|
| 72 |
+
m = mask.unsqueeze(1).expand(batch_dim, seq_dim, seq_dim)
|
| 73 |
+
m = m.reshape(batch_dim * seq_dim, seq_dim)
|
| 74 |
+
return m
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class RelativePosition(nn.Module):
|
| 78 |
+
def __init__(self, bins, pairwise_state_dim):
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.bins = bins
|
| 81 |
+
|
| 82 |
+
# Note an additional offset is used so that the 0th position
|
| 83 |
+
# is reserved for masked pairs.
|
| 84 |
+
self.embedding = torch.nn.Embedding(2 * bins + 2, pairwise_state_dim)
|
| 85 |
+
|
| 86 |
+
def forward(self, residue_index, mask=None):
|
| 87 |
+
"""
|
| 88 |
+
Input:
|
| 89 |
+
residue_index: B x L tensor of indices (dytpe=torch.long)
|
| 90 |
+
mask: B x L tensor of booleans
|
| 91 |
+
|
| 92 |
+
Output:
|
| 93 |
+
pairwise_state: B x L x L x pairwise_state_dim tensor of embeddings
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
assert residue_index.dtype == torch.long
|
| 97 |
+
if mask is not None:
|
| 98 |
+
assert residue_index.shape == mask.shape
|
| 99 |
+
|
| 100 |
+
diff = residue_index[:, None, :] - residue_index[:, :, None]
|
| 101 |
+
diff = diff.clamp(-self.bins, self.bins)
|
| 102 |
+
diff = diff + self.bins + 1 # Add 1 to adjust for padding index.
|
| 103 |
+
|
| 104 |
+
if mask is not None:
|
| 105 |
+
mask = mask[:, None, :] * mask[:, :, None]
|
| 106 |
+
diff[mask == False] = 0
|
| 107 |
+
|
| 108 |
+
output = self.embedding(diff)
|
| 109 |
+
return output
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class FoldingTrunk(nn.Module):
|
| 113 |
+
def __init__(self, **kwargs):
|
| 114 |
+
super().__init__()
|
| 115 |
+
self.cfg = FoldingTrunkConfig(**kwargs)
|
| 116 |
+
assert self.cfg.max_recycles > 0
|
| 117 |
+
|
| 118 |
+
c_s = self.cfg.sequence_state_dim
|
| 119 |
+
c_z = self.cfg.pairwise_state_dim
|
| 120 |
+
|
| 121 |
+
assert c_s % self.cfg.sequence_head_width == 0
|
| 122 |
+
assert c_z % self.cfg.pairwise_head_width == 0
|
| 123 |
+
block = TriangularSelfAttentionBlock
|
| 124 |
+
|
| 125 |
+
self.pairwise_positional_embedding = RelativePosition(self.cfg.position_bins, c_z)
|
| 126 |
+
|
| 127 |
+
self.blocks = nn.ModuleList(
|
| 128 |
+
[
|
| 129 |
+
block(
|
| 130 |
+
sequence_state_dim=c_s,
|
| 131 |
+
pairwise_state_dim=c_z,
|
| 132 |
+
sequence_head_width=self.cfg.sequence_head_width,
|
| 133 |
+
pairwise_head_width=self.cfg.pairwise_head_width,
|
| 134 |
+
dropout=self.cfg.dropout,
|
| 135 |
+
)
|
| 136 |
+
for i in range(self.cfg.num_blocks)
|
| 137 |
+
]
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
self.recycle_bins = 15
|
| 141 |
+
self.recycle_s_norm = nn.LayerNorm(c_s)
|
| 142 |
+
self.recycle_z_norm = nn.LayerNorm(c_z)
|
| 143 |
+
self.recycle_disto = nn.Embedding(self.recycle_bins, c_z)
|
| 144 |
+
self.recycle_disto.weight[0].detach().zero_()
|
| 145 |
+
|
| 146 |
+
self.structure_module = StructureModule(**self.cfg.structure_module) # type: ignore
|
| 147 |
+
self.trunk2sm_s = nn.Linear(c_s, self.structure_module.c_s)
|
| 148 |
+
self.trunk2sm_z = nn.Linear(c_z, self.structure_module.c_z)
|
| 149 |
+
|
| 150 |
+
self.chunk_size = self.cfg.chunk_size
|
| 151 |
+
|
| 152 |
+
def set_chunk_size(self, chunk_size):
|
| 153 |
+
# This parameter means the axial attention will be computed
|
| 154 |
+
# in a chunked manner. This should make the memory used more or less O(L) instead of O(L^2).
|
| 155 |
+
# It's equivalent to running a for loop over chunks of the dimension we're iterative over,
|
| 156 |
+
# where the chunk_size is the size of the chunks, so 128 would mean to parse 128-lengthed chunks.
|
| 157 |
+
self.chunk_size = chunk_size
|
| 158 |
+
|
| 159 |
+
def forward(self, seq_feats, pair_feats, true_aa, residx, mask, no_recycles: T.Optional[int] = None):
|
| 160 |
+
"""
|
| 161 |
+
Inputs:
|
| 162 |
+
seq_feats: B x L x C tensor of sequence features
|
| 163 |
+
pair_feats: B x L x L x C tensor of pair features
|
| 164 |
+
residx: B x L long tensor giving the position in the sequence
|
| 165 |
+
mask: B x L boolean tensor indicating valid residues
|
| 166 |
+
|
| 167 |
+
Output:
|
| 168 |
+
predicted_structure: B x L x (num_atoms_per_residue * 3) tensor wrapped in a Coordinates object
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
device = seq_feats.device
|
| 172 |
+
s_s_0 = seq_feats
|
| 173 |
+
s_z_0 = pair_feats
|
| 174 |
+
|
| 175 |
+
if no_recycles is None:
|
| 176 |
+
no_recycles = self.cfg.max_recycles
|
| 177 |
+
else:
|
| 178 |
+
assert no_recycles >= 0, "Number of recycles must not be negative."
|
| 179 |
+
no_recycles += 1 # First 'recycle' is just the standard forward pass through the model.
|
| 180 |
+
|
| 181 |
+
def trunk_iter(s, z, residx, mask):
|
| 182 |
+
z = z + self.pairwise_positional_embedding(residx, mask=mask)
|
| 183 |
+
|
| 184 |
+
for block in self.blocks:
|
| 185 |
+
s, z = block(s, z, mask=mask, residue_index=residx, chunk_size=self.chunk_size)
|
| 186 |
+
return s, z
|
| 187 |
+
|
| 188 |
+
s_s = s_s_0
|
| 189 |
+
s_z = s_z_0
|
| 190 |
+
recycle_s = torch.zeros_like(s_s)
|
| 191 |
+
recycle_z = torch.zeros_like(s_z)
|
| 192 |
+
recycle_bins = torch.zeros(*s_z.shape[:-1], device=device, dtype=torch.int64)
|
| 193 |
+
|
| 194 |
+
assert no_recycles > 0
|
| 195 |
+
for recycle_idx in range(no_recycles):
|
| 196 |
+
with ExitStack() if recycle_idx == no_recycles - 1 else torch.no_grad():
|
| 197 |
+
# === Recycling ===
|
| 198 |
+
recycle_s = self.recycle_s_norm(recycle_s.detach())
|
| 199 |
+
recycle_z = self.recycle_z_norm(recycle_z.detach())
|
| 200 |
+
recycle_z += self.recycle_disto(recycle_bins.detach())
|
| 201 |
+
|
| 202 |
+
s_s, s_z = trunk_iter(s_s_0 + recycle_s, s_z_0 + recycle_z, residx, mask)
|
| 203 |
+
|
| 204 |
+
# === Structure module ===
|
| 205 |
+
structure = self.structure_module(
|
| 206 |
+
{"single": self.trunk2sm_s(s_s), "pair": self.trunk2sm_z(s_z)},
|
| 207 |
+
true_aa,
|
| 208 |
+
mask.float(),
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
recycle_s = s_s
|
| 212 |
+
recycle_z = s_z
|
| 213 |
+
# Distogram needs the N, CA, C coordinates, and bin constants same as alphafold.
|
| 214 |
+
recycle_bins = FoldingTrunk.distogram(
|
| 215 |
+
structure["positions"][-1][:, :, :3],
|
| 216 |
+
3.375,
|
| 217 |
+
21.375,
|
| 218 |
+
self.recycle_bins,
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
assert isinstance(structure, dict) # type: ignore
|
| 222 |
+
structure["s_s"] = s_s
|
| 223 |
+
structure["s_z"] = s_z
|
| 224 |
+
|
| 225 |
+
return structure
|
| 226 |
+
|
| 227 |
+
@staticmethod
|
| 228 |
+
def distogram(coords, min_bin, max_bin, num_bins):
|
| 229 |
+
# Coords are [... L x 3 x 3], where it's [N, CA, C] x 3 coordinates.
|
| 230 |
+
boundaries = torch.linspace(
|
| 231 |
+
min_bin,
|
| 232 |
+
max_bin,
|
| 233 |
+
num_bins - 1,
|
| 234 |
+
device=coords.device,
|
| 235 |
+
)
|
| 236 |
+
boundaries = boundaries**2
|
| 237 |
+
N, CA, C = [x.squeeze(-2) for x in coords.chunk(3, dim=-2)]
|
| 238 |
+
# Infer CB coordinates.
|
| 239 |
+
b = CA - N
|
| 240 |
+
c = C - CA
|
| 241 |
+
a = b.cross(c, dim=-1)
|
| 242 |
+
CB = -0.58273431 * a + 0.56802827 * b - 0.54067466 * c + CA
|
| 243 |
+
dists = (CB[..., None, :, :] - CB[..., :, None, :]).pow(2).sum(dim=-1, keepdims=True)
|
| 244 |
+
bins = torch.sum(dists > boundaries, dim=-1) # [..., L, L]
|
| 245 |
+
return bins
|
model/esm/inverse_folding/gvp_modules.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contents of this file are from the open source code for
|
| 2 |
+
#
|
| 3 |
+
# Jing, B., Eismann, S., Suriana, P., Townshend, R. J. L., & Dror, R. (2020).
|
| 4 |
+
# Learning from Protein Structure with Geometric Vector Perceptrons. In
|
| 5 |
+
# International Conference on Learning Representations.
|
| 6 |
+
#
|
| 7 |
+
# MIT License
|
| 8 |
+
#
|
| 9 |
+
# Copyright (c) 2020 Bowen Jing, Stephan Eismann, Patricia Suriana, Raphael Townshend, Ron Dror
|
| 10 |
+
#
|
| 11 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 12 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 13 |
+
# in the Software without restriction, including without limitation the rights
|
| 14 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 15 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 16 |
+
# furnished to do so, subject to the following conditions:
|
| 17 |
+
#
|
| 18 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 19 |
+
# copies or substantial portions of the Software.
|
| 20 |
+
#
|
| 21 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 22 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 23 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 24 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 25 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 26 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 27 |
+
# SOFTWARE.
|
| 28 |
+
|
| 29 |
+
import typing as T
|
| 30 |
+
import torch
|
| 31 |
+
from torch import nn
|
| 32 |
+
import torch.nn.functional as F
|
| 33 |
+
from torch_geometric.nn import MessagePassing
|
| 34 |
+
|
| 35 |
+
def tuple_size(tp):
|
| 36 |
+
return tuple([0 if a is None else a.size() for a in tp])
|
| 37 |
+
|
| 38 |
+
def tuple_sum(tp1, tp2):
|
| 39 |
+
s1, v1 = tp1
|
| 40 |
+
s2, v2 = tp2
|
| 41 |
+
if v2 is None and v2 is None:
|
| 42 |
+
return (s1 + s2, None)
|
| 43 |
+
return (s1 + s2, v1 + v2)
|
| 44 |
+
|
| 45 |
+
def tuple_cat(*args, dim=-1):
|
| 46 |
+
'''
|
| 47 |
+
Concatenates any number of tuples (s, V) elementwise.
|
| 48 |
+
|
| 49 |
+
:param dim: dimension along which to concatenate when viewed
|
| 50 |
+
as the `dim` index for the scalar-channel tensors.
|
| 51 |
+
This means that `dim=-1` will be applied as
|
| 52 |
+
`dim=-2` for the vector-channel tensors.
|
| 53 |
+
'''
|
| 54 |
+
dim %= len(args[0][0].shape)
|
| 55 |
+
s_args, v_args = list(zip(*args))
|
| 56 |
+
return torch.cat(s_args, dim=dim), torch.cat(v_args, dim=dim)
|
| 57 |
+
|
| 58 |
+
def tuple_index(x, idx):
|
| 59 |
+
'''
|
| 60 |
+
Indexes into a tuple (s, V) along the first dimension.
|
| 61 |
+
|
| 62 |
+
:param idx: any object which can be used to index into a `torch.Tensor`
|
| 63 |
+
'''
|
| 64 |
+
return x[0][idx], x[1][idx]
|
| 65 |
+
|
| 66 |
+
def randn(n, dims, device="cpu"):
|
| 67 |
+
'''
|
| 68 |
+
Returns random tuples (s, V) drawn elementwise from a normal distribution.
|
| 69 |
+
|
| 70 |
+
:param n: number of data points
|
| 71 |
+
:param dims: tuple of dimensions (n_scalar, n_vector)
|
| 72 |
+
|
| 73 |
+
:return: (s, V) with s.shape = (n, n_scalar) and
|
| 74 |
+
V.shape = (n, n_vector, 3)
|
| 75 |
+
'''
|
| 76 |
+
return torch.randn(n, dims[0], device=device), \
|
| 77 |
+
torch.randn(n, dims[1], 3, device=device)
|
| 78 |
+
|
| 79 |
+
def _norm_no_nan(x, axis=-1, keepdims=False, eps=1e-8, sqrt=True):
|
| 80 |
+
'''
|
| 81 |
+
L2 norm of tensor clamped above a minimum value `eps`.
|
| 82 |
+
|
| 83 |
+
:param sqrt: if `False`, returns the square of the L2 norm
|
| 84 |
+
'''
|
| 85 |
+
# clamp is slow
|
| 86 |
+
# out = torch.clamp(torch.sum(torch.square(x), axis, keepdims), min=eps)
|
| 87 |
+
out = torch.sum(torch.square(x), axis, keepdims) + eps
|
| 88 |
+
return torch.sqrt(out) if sqrt else out
|
| 89 |
+
|
| 90 |
+
def _split(x, nv):
|
| 91 |
+
'''
|
| 92 |
+
Splits a merged representation of (s, V) back into a tuple.
|
| 93 |
+
Should be used only with `_merge(s, V)` and only if the tuple
|
| 94 |
+
representation cannot be used.
|
| 95 |
+
|
| 96 |
+
:param x: the `torch.Tensor` returned from `_merge`
|
| 97 |
+
:param nv: the number of vector channels in the input to `_merge`
|
| 98 |
+
'''
|
| 99 |
+
v = torch.reshape(x[..., -3*nv:], x.shape[:-1] + (nv, 3))
|
| 100 |
+
s = x[..., :-3*nv]
|
| 101 |
+
return s, v
|
| 102 |
+
|
| 103 |
+
def _merge(s, v):
|
| 104 |
+
'''
|
| 105 |
+
Merges a tuple (s, V) into a single `torch.Tensor`, where the
|
| 106 |
+
vector channels are flattened and appended to the scalar channels.
|
| 107 |
+
Should be used only if the tuple representation cannot be used.
|
| 108 |
+
Use `_split(x, nv)` to reverse.
|
| 109 |
+
'''
|
| 110 |
+
v = torch.reshape(v, v.shape[:-2] + (3*v.shape[-2],))
|
| 111 |
+
return torch.cat([s, v], -1)
|
| 112 |
+
|
| 113 |
+
class GVP(nn.Module):
|
| 114 |
+
'''
|
| 115 |
+
Geometric Vector Perceptron. See manuscript and README.md
|
| 116 |
+
for more details.
|
| 117 |
+
|
| 118 |
+
:param in_dims: tuple (n_scalar, n_vector)
|
| 119 |
+
:param out_dims: tuple (n_scalar, n_vector)
|
| 120 |
+
:param h_dim: intermediate number of vector channels, optional
|
| 121 |
+
:param activations: tuple of functions (scalar_act, vector_act)
|
| 122 |
+
:param tuple_io: whether to keep accepting tuple inputs and outputs when vi
|
| 123 |
+
or vo = 0
|
| 124 |
+
'''
|
| 125 |
+
def __init__(self, in_dims, out_dims, h_dim=None, vector_gate=False,
|
| 126 |
+
activations=(F.relu, torch.sigmoid), tuple_io=True,
|
| 127 |
+
eps=1e-8):
|
| 128 |
+
super(GVP, self).__init__()
|
| 129 |
+
self.si, self.vi = in_dims
|
| 130 |
+
self.so, self.vo = out_dims
|
| 131 |
+
self.tuple_io = tuple_io
|
| 132 |
+
if self.vi:
|
| 133 |
+
self.h_dim = h_dim or max(self.vi, self.vo)
|
| 134 |
+
self.wh = nn.Linear(self.vi, self.h_dim, bias=False)
|
| 135 |
+
self.ws = nn.Linear(self.h_dim + self.si, self.so)
|
| 136 |
+
if self.vo:
|
| 137 |
+
self.wv = nn.Linear(self.h_dim, self.vo, bias=False)
|
| 138 |
+
if vector_gate:
|
| 139 |
+
self.wg = nn.Linear(self.so, self.vo)
|
| 140 |
+
else:
|
| 141 |
+
self.ws = nn.Linear(self.si, self.so)
|
| 142 |
+
|
| 143 |
+
self.vector_gate = vector_gate
|
| 144 |
+
self.scalar_act, self.vector_act = activations
|
| 145 |
+
self.eps = eps
|
| 146 |
+
|
| 147 |
+
def forward(self, x):
|
| 148 |
+
'''
|
| 149 |
+
:param x: tuple (s, V) of `torch.Tensor`,
|
| 150 |
+
or (if vectors_in is 0), a single `torch.Tensor`
|
| 151 |
+
:return: tuple (s, V) of `torch.Tensor`,
|
| 152 |
+
or (if vectors_out is 0), a single `torch.Tensor`
|
| 153 |
+
'''
|
| 154 |
+
if self.vi:
|
| 155 |
+
s, v = x
|
| 156 |
+
v = torch.transpose(v, -1, -2)
|
| 157 |
+
vh = self.wh(v)
|
| 158 |
+
vn = _norm_no_nan(vh, axis=-2, eps=self.eps)
|
| 159 |
+
s = self.ws(torch.cat([s, vn], -1))
|
| 160 |
+
if self.scalar_act:
|
| 161 |
+
s = self.scalar_act(s)
|
| 162 |
+
if self.vo:
|
| 163 |
+
v = self.wv(vh)
|
| 164 |
+
v = torch.transpose(v, -1, -2)
|
| 165 |
+
if self.vector_gate:
|
| 166 |
+
g = self.wg(s).unsqueeze(-1)
|
| 167 |
+
else:
|
| 168 |
+
g = _norm_no_nan(v, axis=-1, keepdims=True, eps=self.eps)
|
| 169 |
+
if self.vector_act:
|
| 170 |
+
g = self.vector_act(g)
|
| 171 |
+
v = v * g
|
| 172 |
+
else:
|
| 173 |
+
if self.tuple_io:
|
| 174 |
+
assert x[1] is None
|
| 175 |
+
x = x[0]
|
| 176 |
+
s = self.ws(x)
|
| 177 |
+
if self.scalar_act:
|
| 178 |
+
s = self.scalar_act(s)
|
| 179 |
+
if self.vo:
|
| 180 |
+
v = torch.zeros(list(s.shape)[:-1] + [self.vo, 3],
|
| 181 |
+
device=s.device)
|
| 182 |
+
|
| 183 |
+
if self.vo:
|
| 184 |
+
return (s, v)
|
| 185 |
+
elif self.tuple_io:
|
| 186 |
+
return (s, None)
|
| 187 |
+
else:
|
| 188 |
+
return s
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class _VDropout(nn.Module):
|
| 192 |
+
'''
|
| 193 |
+
Vector channel dropout where the elements of each
|
| 194 |
+
vector channel are dropped together.
|
| 195 |
+
'''
|
| 196 |
+
def __init__(self, drop_rate):
|
| 197 |
+
super(_VDropout, self).__init__()
|
| 198 |
+
self.drop_rate = drop_rate
|
| 199 |
+
|
| 200 |
+
def forward(self, x):
|
| 201 |
+
'''
|
| 202 |
+
:param x: `torch.Tensor` corresponding to vector channels
|
| 203 |
+
'''
|
| 204 |
+
if x is None:
|
| 205 |
+
return None
|
| 206 |
+
device = x.device
|
| 207 |
+
if not self.training:
|
| 208 |
+
return x
|
| 209 |
+
mask = torch.bernoulli(
|
| 210 |
+
(1 - self.drop_rate) * torch.ones(x.shape[:-1], device=device)
|
| 211 |
+
).unsqueeze(-1)
|
| 212 |
+
x = mask * x / (1 - self.drop_rate)
|
| 213 |
+
return x
|
| 214 |
+
|
| 215 |
+
class Dropout(nn.Module):
|
| 216 |
+
'''
|
| 217 |
+
Combined dropout for tuples (s, V).
|
| 218 |
+
Takes tuples (s, V) as input and as output.
|
| 219 |
+
'''
|
| 220 |
+
def __init__(self, drop_rate):
|
| 221 |
+
super(Dropout, self).__init__()
|
| 222 |
+
self.sdropout = nn.Dropout(drop_rate)
|
| 223 |
+
self.vdropout = _VDropout(drop_rate)
|
| 224 |
+
|
| 225 |
+
def forward(self, x):
|
| 226 |
+
'''
|
| 227 |
+
:param x: tuple (s, V) of `torch.Tensor`,
|
| 228 |
+
or single `torch.Tensor`
|
| 229 |
+
(will be assumed to be scalar channels)
|
| 230 |
+
'''
|
| 231 |
+
if type(x) is torch.Tensor:
|
| 232 |
+
return self.sdropout(x)
|
| 233 |
+
s, v = x
|
| 234 |
+
return self.sdropout(s), self.vdropout(v)
|
| 235 |
+
|
| 236 |
+
class LayerNorm(nn.Module):
|
| 237 |
+
'''
|
| 238 |
+
Combined LayerNorm for tuples (s, V).
|
| 239 |
+
Takes tuples (s, V) as input and as output.
|
| 240 |
+
'''
|
| 241 |
+
def __init__(self, dims, tuple_io=True, eps=1e-8):
|
| 242 |
+
super(LayerNorm, self).__init__()
|
| 243 |
+
self.tuple_io = tuple_io
|
| 244 |
+
self.s, self.v = dims
|
| 245 |
+
self.scalar_norm = nn.LayerNorm(self.s)
|
| 246 |
+
self.eps = eps
|
| 247 |
+
|
| 248 |
+
def forward(self, x):
|
| 249 |
+
'''
|
| 250 |
+
:param x: tuple (s, V) of `torch.Tensor`,
|
| 251 |
+
or single `torch.Tensor`
|
| 252 |
+
(will be assumed to be scalar channels)
|
| 253 |
+
'''
|
| 254 |
+
if not self.v:
|
| 255 |
+
if self.tuple_io:
|
| 256 |
+
return self.scalar_norm(x[0]), None
|
| 257 |
+
return self.scalar_norm(x)
|
| 258 |
+
s, v = x
|
| 259 |
+
vn = _norm_no_nan(v, axis=-1, keepdims=True, sqrt=False, eps=self.eps)
|
| 260 |
+
nonzero_mask = (vn > 2 * self.eps)
|
| 261 |
+
vn = torch.sum(vn * nonzero_mask, dim=-2, keepdim=True
|
| 262 |
+
) / (self.eps + torch.sum(nonzero_mask, dim=-2, keepdim=True))
|
| 263 |
+
vn = torch.sqrt(vn + self.eps)
|
| 264 |
+
v = nonzero_mask * (v / vn)
|
| 265 |
+
return self.scalar_norm(s), v
|
| 266 |
+
|
| 267 |
+
class GVPConv(MessagePassing):
|
| 268 |
+
'''
|
| 269 |
+
Graph convolution / message passing with Geometric Vector Perceptrons.
|
| 270 |
+
Takes in a graph with node and edge embeddings,
|
| 271 |
+
and returns new node embeddings.
|
| 272 |
+
|
| 273 |
+
This does NOT do residual updates and pointwise feedforward layers
|
| 274 |
+
---see `GVPConvLayer`.
|
| 275 |
+
|
| 276 |
+
:param in_dims: input node embedding dimensions (n_scalar, n_vector)
|
| 277 |
+
:param out_dims: output node embedding dimensions (n_scalar, n_vector)
|
| 278 |
+
:param edge_dims: input edge embedding dimensions (n_scalar, n_vector)
|
| 279 |
+
:param n_layers: number of GVPs in the message function
|
| 280 |
+
:param module_list: preconstructed message function, overrides n_layers
|
| 281 |
+
:param aggr: should be "add" if some incoming edges are masked, as in
|
| 282 |
+
a masked autoregressive decoder architecture
|
| 283 |
+
'''
|
| 284 |
+
def __init__(self, in_dims, out_dims, edge_dims, n_layers=3,
|
| 285 |
+
vector_gate=False, module_list=None, aggr="mean", eps=1e-8,
|
| 286 |
+
activations=(F.relu, torch.sigmoid)):
|
| 287 |
+
super(GVPConv, self).__init__(aggr=aggr)
|
| 288 |
+
self.eps = eps
|
| 289 |
+
self.si, self.vi = in_dims
|
| 290 |
+
self.so, self.vo = out_dims
|
| 291 |
+
self.se, self.ve = edge_dims
|
| 292 |
+
|
| 293 |
+
module_list = module_list or []
|
| 294 |
+
if not module_list:
|
| 295 |
+
if n_layers == 1:
|
| 296 |
+
module_list.append(
|
| 297 |
+
GVP((2*self.si + self.se, 2*self.vi + self.ve),
|
| 298 |
+
(self.so, self.vo), activations=(None, None)))
|
| 299 |
+
else:
|
| 300 |
+
module_list.append(
|
| 301 |
+
GVP((2*self.si + self.se, 2*self.vi + self.ve), out_dims,
|
| 302 |
+
vector_gate=vector_gate, activations=activations)
|
| 303 |
+
)
|
| 304 |
+
for i in range(n_layers - 2):
|
| 305 |
+
module_list.append(GVP(out_dims, out_dims,
|
| 306 |
+
vector_gate=vector_gate))
|
| 307 |
+
module_list.append(GVP(out_dims, out_dims,
|
| 308 |
+
activations=(None, None)))
|
| 309 |
+
self.message_func = nn.Sequential(*module_list)
|
| 310 |
+
|
| 311 |
+
def forward(self, x, edge_index, edge_attr):
|
| 312 |
+
'''
|
| 313 |
+
:param x: tuple (s, V) of `torch.Tensor`
|
| 314 |
+
:param edge_index: array of shape [2, n_edges]
|
| 315 |
+
:param edge_attr: tuple (s, V) of `torch.Tensor`
|
| 316 |
+
'''
|
| 317 |
+
x_s, x_v = x
|
| 318 |
+
message = self.propagate(edge_index,
|
| 319 |
+
s=x_s, v=x_v.reshape(x_v.shape[0], 3*x_v.shape[1]),
|
| 320 |
+
edge_attr=edge_attr)
|
| 321 |
+
return _split(message, self.vo)
|
| 322 |
+
|
| 323 |
+
def message(self, s_i, v_i, s_j, v_j, edge_attr):
|
| 324 |
+
v_j = v_j.view(v_j.shape[0], v_j.shape[1]//3, 3)
|
| 325 |
+
v_i = v_i.view(v_i.shape[0], v_i.shape[1]//3, 3)
|
| 326 |
+
message = tuple_cat((s_j, v_j), edge_attr, (s_i, v_i))
|
| 327 |
+
message = self.message_func(message)
|
| 328 |
+
return _merge(*message)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class GVPConvLayer(nn.Module):
|
| 332 |
+
'''
|
| 333 |
+
Full graph convolution / message passing layer with
|
| 334 |
+
Geometric Vector Perceptrons. Residually updates node embeddings with
|
| 335 |
+
aggregated incoming messages, applies a pointwise feedforward
|
| 336 |
+
network to node embeddings, and returns updated node embeddings.
|
| 337 |
+
|
| 338 |
+
To only compute the aggregated messages, see `GVPConv`.
|
| 339 |
+
|
| 340 |
+
:param node_dims: node embedding dimensions (n_scalar, n_vector)
|
| 341 |
+
:param edge_dims: input edge embedding dimensions (n_scalar, n_vector)
|
| 342 |
+
:param n_message: number of GVPs to use in message function
|
| 343 |
+
:param n_feedforward: number of GVPs to use in feedforward function
|
| 344 |
+
:param drop_rate: drop probability in all dropout layers
|
| 345 |
+
:param autoregressive: if `True`, this `GVPConvLayer` will be used
|
| 346 |
+
with a different set of input node embeddings for messages
|
| 347 |
+
where src >= dst
|
| 348 |
+
'''
|
| 349 |
+
def __init__(self, node_dims, edge_dims, vector_gate=False,
|
| 350 |
+
n_message=3, n_feedforward=2, drop_rate=.1,
|
| 351 |
+
autoregressive=False, attention_heads=0,
|
| 352 |
+
conv_activations=(F.relu, torch.sigmoid),
|
| 353 |
+
n_edge_gvps=0, layernorm=True, eps=1e-8):
|
| 354 |
+
|
| 355 |
+
super(GVPConvLayer, self).__init__()
|
| 356 |
+
if attention_heads == 0:
|
| 357 |
+
self.conv = GVPConv(
|
| 358 |
+
node_dims, node_dims, edge_dims, n_layers=n_message,
|
| 359 |
+
vector_gate=vector_gate,
|
| 360 |
+
aggr="add" if autoregressive else "mean",
|
| 361 |
+
activations=conv_activations,
|
| 362 |
+
eps=eps,
|
| 363 |
+
)
|
| 364 |
+
else:
|
| 365 |
+
raise NotImplementedError
|
| 366 |
+
if layernorm:
|
| 367 |
+
self.norm = nn.ModuleList([LayerNorm(node_dims, eps=eps) for _ in range(2)])
|
| 368 |
+
else:
|
| 369 |
+
self.norm = nn.ModuleList([nn.Identity() for _ in range(2)])
|
| 370 |
+
self.dropout = nn.ModuleList([Dropout(drop_rate) for _ in range(2)])
|
| 371 |
+
|
| 372 |
+
ff_func = []
|
| 373 |
+
if n_feedforward == 1:
|
| 374 |
+
ff_func.append(GVP(node_dims, node_dims, activations=(None, None)))
|
| 375 |
+
else:
|
| 376 |
+
hid_dims = 4*node_dims[0], 2*node_dims[1]
|
| 377 |
+
ff_func.append(GVP(node_dims, hid_dims, vector_gate=vector_gate))
|
| 378 |
+
for i in range(n_feedforward-2):
|
| 379 |
+
ff_func.append(GVP(hid_dims, hid_dims, vector_gate=vector_gate))
|
| 380 |
+
ff_func.append(GVP(hid_dims, node_dims, activations=(None, None)))
|
| 381 |
+
self.ff_func = nn.Sequential(*ff_func)
|
| 382 |
+
|
| 383 |
+
self.edge_message_func = None
|
| 384 |
+
if n_edge_gvps > 0:
|
| 385 |
+
si, vi = node_dims
|
| 386 |
+
se, ve = edge_dims
|
| 387 |
+
module_list = [
|
| 388 |
+
GVP((2*si + se, 2*vi + ve), edge_dims, vector_gate=vector_gate)
|
| 389 |
+
]
|
| 390 |
+
for i in range(n_edge_gvps - 2):
|
| 391 |
+
module_list.append(GVP(edge_dims, edge_dims,
|
| 392 |
+
vector_gate=vector_gate))
|
| 393 |
+
if n_edge_gvps > 1:
|
| 394 |
+
module_list.append(GVP(edge_dims, edge_dims,
|
| 395 |
+
activations=(None, None)))
|
| 396 |
+
self.edge_message_func = nn.Sequential(*module_list)
|
| 397 |
+
if layernorm:
|
| 398 |
+
self.edge_norm = LayerNorm(edge_dims, eps=eps)
|
| 399 |
+
else:
|
| 400 |
+
self.edge_norm = nn.Identity()
|
| 401 |
+
self.edge_dropout = Dropout(drop_rate)
|
| 402 |
+
|
| 403 |
+
def forward(self, x, edge_index, edge_attr,
|
| 404 |
+
autoregressive_x=None, node_mask=None):
|
| 405 |
+
'''
|
| 406 |
+
:param x: tuple (s, V) of `torch.Tensor`
|
| 407 |
+
:param edge_index: array of shape [2, n_edges]
|
| 408 |
+
:param edge_attr: tuple (s, V) of `torch.Tensor`
|
| 409 |
+
:param autoregressive_x: tuple (s, V) of `torch.Tensor`.
|
| 410 |
+
If not `None`, will be used as srcqq node embeddings
|
| 411 |
+
for forming messages where src >= dst. The corrent node
|
| 412 |
+
embeddings `x` will still be the base of the update and the
|
| 413 |
+
pointwise feedforward.
|
| 414 |
+
:param node_mask: array of type `bool` to index into the first
|
| 415 |
+
dim of node embeddings (s, V). If not `None`, only
|
| 416 |
+
these nodes will be updated.
|
| 417 |
+
'''
|
| 418 |
+
if self.edge_message_func:
|
| 419 |
+
src, dst = edge_index
|
| 420 |
+
if autoregressive_x is None:
|
| 421 |
+
x_src = x[0][src], x[1][src]
|
| 422 |
+
else:
|
| 423 |
+
mask = (src < dst).unsqueeze(-1)
|
| 424 |
+
x_src = (
|
| 425 |
+
torch.where(mask, x[0][src], autoregressive_x[0][src]),
|
| 426 |
+
torch.where(mask.unsqueeze(-1), x[1][src],
|
| 427 |
+
autoregressive_x[1][src])
|
| 428 |
+
)
|
| 429 |
+
x_dst = x[0][dst], x[1][dst]
|
| 430 |
+
x_edge = (
|
| 431 |
+
torch.cat([x_src[0], edge_attr[0], x_dst[0]], dim=-1),
|
| 432 |
+
torch.cat([x_src[1], edge_attr[1], x_dst[1]], dim=-2)
|
| 433 |
+
)
|
| 434 |
+
edge_attr_dh = self.edge_message_func(x_edge)
|
| 435 |
+
edge_attr = self.edge_norm(tuple_sum(edge_attr,
|
| 436 |
+
self.edge_dropout(edge_attr_dh)))
|
| 437 |
+
|
| 438 |
+
if autoregressive_x is not None:
|
| 439 |
+
# Guarding this import here to remove the dependency on torch_scatter, since this isn't used
|
| 440 |
+
# in ESM-IF1
|
| 441 |
+
from torch_scatter import scatter_add
|
| 442 |
+
src, dst = edge_index
|
| 443 |
+
mask = src < dst
|
| 444 |
+
edge_index_forward = edge_index[:, mask]
|
| 445 |
+
edge_index_backward = edge_index[:, ~mask]
|
| 446 |
+
edge_attr_forward = tuple_index(edge_attr, mask)
|
| 447 |
+
edge_attr_backward = tuple_index(edge_attr, ~mask)
|
| 448 |
+
|
| 449 |
+
dh = tuple_sum(
|
| 450 |
+
self.conv(x, edge_index_forward, edge_attr_forward),
|
| 451 |
+
self.conv(autoregressive_x, edge_index_backward, edge_attr_backward)
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
count = scatter_add(torch.ones_like(dst), dst,
|
| 455 |
+
dim_size=dh[0].size(0)).clamp(min=1).unsqueeze(-1)
|
| 456 |
+
|
| 457 |
+
dh = dh[0] / count, dh[1] / count.unsqueeze(-1)
|
| 458 |
+
|
| 459 |
+
else:
|
| 460 |
+
dh = self.conv(x, edge_index, edge_attr)
|
| 461 |
+
|
| 462 |
+
if node_mask is not None:
|
| 463 |
+
x_ = x
|
| 464 |
+
x, dh = tuple_index(x, node_mask), tuple_index(dh, node_mask)
|
| 465 |
+
|
| 466 |
+
x = self.norm[0](tuple_sum(x, self.dropout[0](dh)))
|
| 467 |
+
|
| 468 |
+
dh = self.ff_func(x)
|
| 469 |
+
x = self.norm[1](tuple_sum(x, self.dropout[1](dh)))
|
| 470 |
+
|
| 471 |
+
if node_mask is not None:
|
| 472 |
+
x_[0][node_mask], x_[1][node_mask] = x[0], x[1]
|
| 473 |
+
x = x_
|
| 474 |
+
|
| 475 |
+
return x, edge_attr
|
model/esm/inverse_folding/gvp_transformer.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from typing import Any, Dict, List, Optional, Tuple, NamedTuple
|
| 8 |
+
import torch
|
| 9 |
+
from torch import nn
|
| 10 |
+
from torch import Tensor
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from scipy.spatial import transform
|
| 13 |
+
|
| 14 |
+
from onescience.datapipes.esm import Alphabet
|
| 15 |
+
|
| 16 |
+
from .features import DihedralFeatures
|
| 17 |
+
from .gvp_encoder import GVPEncoder
|
| 18 |
+
from .gvp_utils import unflatten_graph
|
| 19 |
+
from .gvp_transformer_encoder import GVPTransformerEncoder
|
| 20 |
+
from .transformer_decoder import TransformerDecoder
|
| 21 |
+
from .util import rotate, CoordBatchConverter
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class GVPTransformerModel(nn.Module):
|
| 25 |
+
"""
|
| 26 |
+
GVP-Transformer inverse folding model.
|
| 27 |
+
|
| 28 |
+
Architecture: Geometric GVP-GNN as initial layers, followed by
|
| 29 |
+
sequence-to-sequence Transformer encoder and decoder.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, args, alphabet):
|
| 33 |
+
super().__init__()
|
| 34 |
+
encoder_embed_tokens = self.build_embedding(
|
| 35 |
+
args, alphabet, args.encoder_embed_dim,
|
| 36 |
+
)
|
| 37 |
+
decoder_embed_tokens = self.build_embedding(
|
| 38 |
+
args, alphabet, args.decoder_embed_dim,
|
| 39 |
+
)
|
| 40 |
+
encoder = self.build_encoder(args, alphabet, encoder_embed_tokens)
|
| 41 |
+
decoder = self.build_decoder(args, alphabet, decoder_embed_tokens)
|
| 42 |
+
self.args = args
|
| 43 |
+
self.encoder = encoder
|
| 44 |
+
self.decoder = decoder
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def build_encoder(cls, args, src_dict, embed_tokens):
|
| 48 |
+
encoder = GVPTransformerEncoder(args, src_dict, embed_tokens)
|
| 49 |
+
return encoder
|
| 50 |
+
|
| 51 |
+
@classmethod
|
| 52 |
+
def build_decoder(cls, args, tgt_dict, embed_tokens):
|
| 53 |
+
decoder = TransformerDecoder(
|
| 54 |
+
args,
|
| 55 |
+
tgt_dict,
|
| 56 |
+
embed_tokens,
|
| 57 |
+
)
|
| 58 |
+
return decoder
|
| 59 |
+
|
| 60 |
+
@classmethod
|
| 61 |
+
def build_embedding(cls, args, dictionary, embed_dim):
|
| 62 |
+
num_embeddings = len(dictionary)
|
| 63 |
+
padding_idx = dictionary.padding_idx
|
| 64 |
+
emb = nn.Embedding(num_embeddings, embed_dim, padding_idx)
|
| 65 |
+
nn.init.normal_(emb.weight, mean=0, std=embed_dim ** -0.5)
|
| 66 |
+
nn.init.constant_(emb.weight[padding_idx], 0)
|
| 67 |
+
return emb
|
| 68 |
+
|
| 69 |
+
def forward(
|
| 70 |
+
self,
|
| 71 |
+
coords,
|
| 72 |
+
padding_mask,
|
| 73 |
+
confidence,
|
| 74 |
+
prev_output_tokens,
|
| 75 |
+
return_all_hiddens: bool = False,
|
| 76 |
+
features_only: bool = False,
|
| 77 |
+
):
|
| 78 |
+
encoder_out = self.encoder(coords, padding_mask, confidence,
|
| 79 |
+
return_all_hiddens=return_all_hiddens)
|
| 80 |
+
logits, extra = self.decoder(
|
| 81 |
+
prev_output_tokens,
|
| 82 |
+
encoder_out=encoder_out,
|
| 83 |
+
features_only=features_only,
|
| 84 |
+
return_all_hiddens=return_all_hiddens,
|
| 85 |
+
)
|
| 86 |
+
return logits, extra
|
| 87 |
+
|
| 88 |
+
def sample(self, coords, partial_seq=None, temperature=1.0, confidence=None, device=None):
|
| 89 |
+
"""
|
| 90 |
+
Samples sequences based on multinomial sampling (no beam search).
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
coords: L x 3 x 3 list representing one backbone
|
| 94 |
+
partial_seq: Optional, partial sequence with mask tokens if part of
|
| 95 |
+
the sequence is known
|
| 96 |
+
temperature: sampling temperature, use low temperature for higher
|
| 97 |
+
sequence recovery and high temperature for higher diversity
|
| 98 |
+
confidence: optional length L list of confidence scores for coordinates
|
| 99 |
+
"""
|
| 100 |
+
L = len(coords)
|
| 101 |
+
# Convert to batch format
|
| 102 |
+
batch_converter = CoordBatchConverter(self.decoder.dictionary)
|
| 103 |
+
batch_coords, confidence, _, _, padding_mask = (
|
| 104 |
+
batch_converter([(coords, confidence, None)], device=device)
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# Start with prepend token
|
| 108 |
+
mask_idx = self.decoder.dictionary.get_idx('<mask>')
|
| 109 |
+
sampled_tokens = torch.full((1, 1+L), mask_idx, dtype=int)
|
| 110 |
+
sampled_tokens[0, 0] = self.decoder.dictionary.get_idx('<cath>')
|
| 111 |
+
if partial_seq is not None:
|
| 112 |
+
for i, c in enumerate(partial_seq):
|
| 113 |
+
sampled_tokens[0, i+1] = self.decoder.dictionary.get_idx(c)
|
| 114 |
+
|
| 115 |
+
# Save incremental states for faster sampling
|
| 116 |
+
incremental_state = dict()
|
| 117 |
+
|
| 118 |
+
# Run encoder only once
|
| 119 |
+
encoder_out = self.encoder(batch_coords, padding_mask, confidence)
|
| 120 |
+
|
| 121 |
+
# Make sure all tensors are on the same device if a GPU is present
|
| 122 |
+
if device:
|
| 123 |
+
sampled_tokens = sampled_tokens.to(device)
|
| 124 |
+
|
| 125 |
+
# Decode one token at a time
|
| 126 |
+
for i in range(1, L+1):
|
| 127 |
+
logits, _ = self.decoder(
|
| 128 |
+
sampled_tokens[:, :i],
|
| 129 |
+
encoder_out,
|
| 130 |
+
incremental_state=incremental_state,
|
| 131 |
+
)
|
| 132 |
+
logits = logits[0].transpose(0, 1)
|
| 133 |
+
logits /= temperature
|
| 134 |
+
probs = F.softmax(logits, dim=-1)
|
| 135 |
+
if sampled_tokens[0, i] == mask_idx:
|
| 136 |
+
sampled_tokens[:, i] = torch.multinomial(probs, 1).squeeze(-1)
|
| 137 |
+
sampled_seq = sampled_tokens[0, 1:]
|
| 138 |
+
|
| 139 |
+
# Convert back to string via lookup
|
| 140 |
+
return ''.join([self.decoder.dictionary.get_tok(a) for a in sampled_seq])
|
model/protenix/__init__.py
ADDED
|
File without changes
|
model/protenix/layer_norm/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .layer_norm import FusedLayerNorm
|
model/protenix/layer_norm/kernel/compat.h
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#ifndef TORCH_CHECK
|
| 2 |
+
#define TORCH_CHECK AT_CHECK
|
| 3 |
+
#endif
|
| 4 |
+
|
| 5 |
+
#ifdef VERSION_GE_1_3
|
| 6 |
+
#define DATA_PTR data_ptr
|
| 7 |
+
#else
|
| 8 |
+
#define DATA_PTR data
|
| 9 |
+
#endif
|
model/protenix/layer_norm/kernel/layer_norm_cuda.cpp
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2021- HPC-AI Technology Inc.
|
| 2 |
+
//
|
| 3 |
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
// you may not use this file except in compliance with the License.
|
| 5 |
+
// You may obtain a copy of the License at
|
| 6 |
+
//
|
| 7 |
+
// http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
//
|
| 9 |
+
// Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
// See the License for the specific language governing permissions and
|
| 13 |
+
|
| 14 |
+
#include <torch/extension.h>
|
| 15 |
+
#include <c10/cuda/CUDAGuard.h>
|
| 16 |
+
|
| 17 |
+
#include <cassert>
|
| 18 |
+
#include <vector>
|
| 19 |
+
#include <functional>
|
| 20 |
+
|
| 21 |
+
#include "compat.h"
|
| 22 |
+
|
| 23 |
+
void compute_n1_n2(at::Tensor input, at::IntArrayRef normalized_shape, int& n1, int& n2) {
|
| 24 |
+
int idiff = input.ndimension() - normalized_shape.size();
|
| 25 |
+
n2 = 1;
|
| 26 |
+
for (int i = 0; i < (int)normalized_shape.size(); ++i) {
|
| 27 |
+
assert(input.sizes()[i + idiff] == normalized_shape[i]);
|
| 28 |
+
n2 *= normalized_shape[i];
|
| 29 |
+
}
|
| 30 |
+
n1 = 1;
|
| 31 |
+
for (int i = 0; i < idiff; ++i) {
|
| 32 |
+
n1 *= input.sizes()[i];
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
void check_args(at::Tensor input, at::IntArrayRef normalized_shape, int& n1, int& n2) {
|
| 37 |
+
int64_t normalized_ndim = normalized_shape.size();
|
| 38 |
+
|
| 39 |
+
if (normalized_ndim < 1) {
|
| 40 |
+
std::stringstream ss;
|
| 41 |
+
ss << "Expected normalized_shape to be at least 1-dimensional, i.e., "
|
| 42 |
+
<< "containing at least one element, but got normalized_shape=" << normalized_shape;
|
| 43 |
+
throw std::runtime_error(ss.str());
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
auto input_shape = input.sizes();
|
| 47 |
+
auto input_ndim = input.dim();
|
| 48 |
+
|
| 49 |
+
if (input_ndim < normalized_ndim ||
|
| 50 |
+
!input_shape.slice(input_ndim - normalized_ndim).equals(normalized_shape)) {
|
| 51 |
+
std::stringstream ss;
|
| 52 |
+
ss << "Given normalized_shape=" << normalized_shape << ", expected input with shape [*";
|
| 53 |
+
for (auto size : normalized_shape) {
|
| 54 |
+
ss << ", " << size;
|
| 55 |
+
}
|
| 56 |
+
ss << "], but got input of size" << input_shape;
|
| 57 |
+
throw std::runtime_error(ss.str());
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
compute_n1_n2(input, normalized_shape, n1, n2);
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
void cuda_layer_norm(at::Tensor* output, at::Tensor* mean, at::Tensor* invvar, at::Tensor* input,
|
| 64 |
+
int n1, int n2, at::IntArrayRef normalized_shape, at::Tensor* gamma,
|
| 65 |
+
at::Tensor* beta, double epsilon);
|
| 66 |
+
|
| 67 |
+
#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
|
| 68 |
+
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
|
| 69 |
+
#define CHECK_INPUT(x) \
|
| 70 |
+
CHECK_CUDA(x); \
|
| 71 |
+
CHECK_CONTIGUOUS(x)
|
| 72 |
+
|
| 73 |
+
std::vector<at::Tensor> layer_norm_affine(at::Tensor input, at::IntArrayRef normalized_shape,
|
| 74 |
+
at::Tensor *gamma, at::Tensor *beta, double epsilon) {
|
| 75 |
+
CHECK_INPUT(input);
|
| 76 |
+
// CHECK_INPUT((*gamma));
|
| 77 |
+
// CHECK_INPUT((*beta));
|
| 78 |
+
int n1, n2;
|
| 79 |
+
check_args(input, normalized_shape, n1, n2);
|
| 80 |
+
|
| 81 |
+
const at::cuda::OptionalCUDAGuard device_guard(device_of(input));
|
| 82 |
+
|
| 83 |
+
at::Tensor output = at::empty_like(input, input.options().dtype(input.scalar_type()));
|
| 84 |
+
at::Tensor mean = at::empty({n1}, input.options().dtype(at::ScalarType::Float));
|
| 85 |
+
at::Tensor invvar = at::empty_like(mean);
|
| 86 |
+
|
| 87 |
+
cuda_layer_norm(&output, &mean, &invvar, &input, n1, n2, normalized_shape, gamma, beta, epsilon);
|
| 88 |
+
|
| 89 |
+
return {output, mean, invvar};
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
void cuda_layer_norm_gradient(at::Tensor* dout, at::Tensor* mean, at::Tensor* invvar,
|
| 93 |
+
at::Tensor* input, int n1, int n2, at::IntArrayRef normalized_shape,
|
| 94 |
+
at::Tensor* gamma, at::Tensor* beta, double epsilon,
|
| 95 |
+
at::Tensor* grad_input, at::Tensor* grad_gamma,
|
| 96 |
+
at::Tensor* grad_beta);
|
| 97 |
+
|
| 98 |
+
std::vector<at::Tensor> layer_norm_gradient_affine(at::Tensor dout, at::Tensor mean,
|
| 99 |
+
at::Tensor invvar, at::Tensor input,
|
| 100 |
+
at::IntArrayRef normalized_shape,
|
| 101 |
+
at::Tensor* gamma, at::Tensor* beta,
|
| 102 |
+
double epsilon) {
|
| 103 |
+
CHECK_INPUT(dout);
|
| 104 |
+
CHECK_INPUT(mean);
|
| 105 |
+
CHECK_INPUT(invvar);
|
| 106 |
+
CHECK_INPUT(input);
|
| 107 |
+
int n1, n2;
|
| 108 |
+
check_args(input, normalized_shape, n1, n2);
|
| 109 |
+
|
| 110 |
+
const at::cuda::OptionalCUDAGuard device_guard(device_of(input));
|
| 111 |
+
|
| 112 |
+
at::Tensor grad_input = at::empty_like(input);
|
| 113 |
+
|
| 114 |
+
at::Tensor grad_gamma;
|
| 115 |
+
at::Tensor grad_beta;
|
| 116 |
+
if (gamma != NULL)
|
| 117 |
+
grad_gamma = at::empty_like(*gamma);
|
| 118 |
+
if (beta != NULL)
|
| 119 |
+
grad_beta = at::empty_like(*beta);
|
| 120 |
+
|
| 121 |
+
if (gamma != NULL) {
|
| 122 |
+
if(beta != NULL) {
|
| 123 |
+
cuda_layer_norm_gradient(&dout, &mean, &invvar, &input, n1, n2, normalized_shape, gamma, beta,
|
| 124 |
+
epsilon, &grad_input, &grad_gamma, &grad_beta);
|
| 125 |
+
} else {
|
| 126 |
+
cuda_layer_norm_gradient(&dout, &mean, &invvar, &input, n1, n2, normalized_shape, gamma, beta,
|
| 127 |
+
epsilon, &grad_input, &grad_gamma, NULL);
|
| 128 |
+
}
|
| 129 |
+
} else {
|
| 130 |
+
if(beta != NULL) {
|
| 131 |
+
cuda_layer_norm_gradient(&dout, &mean, &invvar, &input, n1, n2, normalized_shape, gamma, beta,
|
| 132 |
+
epsilon, &grad_input, NULL, &grad_beta);
|
| 133 |
+
} else {
|
| 134 |
+
cuda_layer_norm_gradient(&dout, &mean, &invvar, &input, n1, n2, normalized_shape, gamma, beta,
|
| 135 |
+
epsilon, &grad_input, NULL, NULL);
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
return {grad_input, grad_gamma, grad_beta};
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 143 |
+
m.def("forward_none_affine", [](at::Tensor input, at::IntArrayRef normalized_shape, double epsilon) {
|
| 144 |
+
return layer_norm_affine(input, normalized_shape, NULL, NULL, epsilon);
|
| 145 |
+
}, "LayerNorm forward (CUDA)");
|
| 146 |
+
|
| 147 |
+
m.def("forward_with_bias_affine", [](at::Tensor input, at::IntArrayRef normalized_shape, at::Tensor *beta, double epsilon) {
|
| 148 |
+
return layer_norm_affine(input, normalized_shape, NULL, beta, epsilon);
|
| 149 |
+
}, "LayerNorm forward (CUDA)");
|
| 150 |
+
|
| 151 |
+
m.def("forward_with_weight_affine", [](at::Tensor input, at::IntArrayRef normalized_shape, at::Tensor *gamma, double epsilon) {
|
| 152 |
+
return layer_norm_affine(input, normalized_shape, gamma, NULL, epsilon);
|
| 153 |
+
}, "LayerNorm forward (CUDA)");
|
| 154 |
+
|
| 155 |
+
m.def("forward_with_both_affine", [](at::Tensor input, at::IntArrayRef normalized_shape, at::Tensor *gamma, at::Tensor *beta, double epsilon) {
|
| 156 |
+
return layer_norm_affine(input, normalized_shape, gamma, beta, epsilon);
|
| 157 |
+
}, "LayerNorm forward (CUDA)");
|
| 158 |
+
|
| 159 |
+
m.def("backward_none_affine", [](at::Tensor dout, at::Tensor mean, at::Tensor invvar, at::Tensor input,
|
| 160 |
+
at::IntArrayRef normalized_shape, double epsilon) {
|
| 161 |
+
return layer_norm_gradient_affine(dout, mean, invvar, input, normalized_shape, NULL, NULL, epsilon);
|
| 162 |
+
|
| 163 |
+
}, "LayerNorm backward (CUDA)");
|
| 164 |
+
|
| 165 |
+
m.def("backward_with_bias_affine", [](at::Tensor dout, at::Tensor mean, at::Tensor invvar, at::Tensor input,
|
| 166 |
+
at::IntArrayRef normalized_shape, at::Tensor *beta, double epsilon) {
|
| 167 |
+
return layer_norm_gradient_affine(dout, mean, invvar, input, normalized_shape, NULL, beta, epsilon);
|
| 168 |
+
}, "LayerNorm backward (CUDA)");
|
| 169 |
+
|
| 170 |
+
m.def("backward_with_weight_affine", [](at::Tensor dout, at::Tensor mean, at::Tensor invvar, at::Tensor input,
|
| 171 |
+
at::IntArrayRef normalized_shape, at::Tensor *gamma, double epsilon) {
|
| 172 |
+
return layer_norm_gradient_affine(dout, mean, invvar, input, normalized_shape, gamma, NULL, epsilon);
|
| 173 |
+
}, "LayerNorm backward (CUDA)");
|
| 174 |
+
|
| 175 |
+
m.def("backward_with_both_affine", [](at::Tensor dout, at::Tensor mean, at::Tensor invvar, at::Tensor input,
|
| 176 |
+
at::IntArrayRef normalized_shape, at::Tensor *gamma, at::Tensor *beta, double epsilon) {
|
| 177 |
+
return layer_norm_gradient_affine(dout, mean, invvar, input, normalized_shape, gamma, beta, epsilon);
|
| 178 |
+
}, "LayerNorm backward (CUDA)");
|
| 179 |
+
}
|
model/protenix/layer_norm/kernel/layer_norm_cuda_kernel.cu
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <cooperative_groups.h>
|
| 2 |
+
#include <cuda.h>
|
| 3 |
+
#include <cuda_runtime.h>
|
| 4 |
+
#include <torch/extension.h>
|
| 5 |
+
#include <iostream>
|
| 6 |
+
|
| 7 |
+
#include <THC/THCDeviceUtils.cuh>
|
| 8 |
+
|
| 9 |
+
#include "ATen/ATen.h"
|
| 10 |
+
#include "ATen/AccumulateType.h"
|
| 11 |
+
#include "ATen/cuda/CUDAContext.h"
|
| 12 |
+
#include "compat.h"
|
| 13 |
+
#include "type_shim.h"
|
| 14 |
+
|
| 15 |
+
#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
|
| 16 |
+
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
|
| 17 |
+
#define CHECK_INPUT(x) \
|
| 18 |
+
CHECK_CUDA(x); \
|
| 19 |
+
CHECK_CONTIGUOUS(x)
|
| 20 |
+
|
| 21 |
+
#define WarpNum 8
|
| 22 |
+
#define WarpSize 32
|
| 23 |
+
#define BlockSzie WarpNum*WarpSize
|
| 24 |
+
|
| 25 |
+
inline __device__ void WelfordOnline(float val, float* mean, float* m2, float* count) {
|
| 26 |
+
*count += 1;
|
| 27 |
+
float delta1 = val - *mean;
|
| 28 |
+
*mean += delta1 / (*count);
|
| 29 |
+
float delta2 = val - *mean;
|
| 30 |
+
*m2 += delta1 * delta2;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
inline __device__ void WelfordOnline(float b_mean, float b_m2, float b_count, float* mean,
|
| 34 |
+
float* m2, float* count) {
|
| 35 |
+
if (b_count == 0) {
|
| 36 |
+
return;
|
| 37 |
+
}
|
| 38 |
+
float new_count = *count + b_count;
|
| 39 |
+
float nb_n = b_count / new_count;
|
| 40 |
+
float delta = b_mean - *mean;
|
| 41 |
+
*mean += delta * nb_n;
|
| 42 |
+
*m2 += b_m2 + delta * delta * (*count) * nb_n;
|
| 43 |
+
*count = new_count;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
__inline__ __device__ void WelfordWarpAllReduce(float thread_mean, float thread_m2,
|
| 47 |
+
float thread_count, float* mean, float* m2,
|
| 48 |
+
float* count) {
|
| 49 |
+
*mean = thread_mean;
|
| 50 |
+
*m2 = thread_m2;
|
| 51 |
+
*count = thread_count;
|
| 52 |
+
for (int mask = 1; mask < 32; mask *= 2) {
|
| 53 |
+
float b_mean = __shfl_down_sync(0xffffffff, *mean, mask);
|
| 54 |
+
float b_m2 = __shfl_down_sync(0xffffffff, *m2, mask);
|
| 55 |
+
float b_count = __shfl_down_sync(0xffffffff, *count, mask);
|
| 56 |
+
WelfordOnline(b_mean, b_m2, b_count, mean, m2, count);
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
*mean = __shfl_sync(0xffffffff, *mean, 0, 32);
|
| 60 |
+
*m2 = __shfl_sync(0xffffffff, *m2, 0, 32);
|
| 61 |
+
*count = __shfl_sync(0xffffffff, *count, 0, 32);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
extern __shared__ float shared_data[];
|
| 65 |
+
template <typename T>
|
| 66 |
+
__global__ void LayerNormForward(T* input, T* output, T* gamma, T* beta, float* mean,
|
| 67 |
+
float* invvar, int rows, int cols, double epsilon) {
|
| 68 |
+
int warp_id = threadIdx.x / WarpSize;
|
| 69 |
+
int lane_id = threadIdx.x % WarpSize;
|
| 70 |
+
int row_offset = blockIdx.x * WarpNum + warp_id;
|
| 71 |
+
|
| 72 |
+
T* shared_data_warp = (T*)shared_data + warp_id*cols;
|
| 73 |
+
|
| 74 |
+
if (row_offset < rows) {
|
| 75 |
+
T* row_input = input + (long long)(row_offset) * (long long)(cols); // Starting point for input data
|
| 76 |
+
T* row_output = output + (long long)(row_offset) * (long long)(cols); // Starting point for output data
|
| 77 |
+
|
| 78 |
+
float thread_mean = 0.f;
|
| 79 |
+
float thread_m2 = 0.f;
|
| 80 |
+
float thread_count = 0.f;
|
| 81 |
+
|
| 82 |
+
float warp_mean;
|
| 83 |
+
float warp_m2;
|
| 84 |
+
float warp_count;
|
| 85 |
+
// load data to shared memory
|
| 86 |
+
#pragma unroll
|
| 87 |
+
for(int idx = lane_id; idx < cols; idx += WarpSize) {
|
| 88 |
+
shared_data_warp[idx] = row_input[idx];
|
| 89 |
+
WelfordOnline(static_cast<float>(shared_data_warp[idx]), &thread_mean, &thread_m2, &thread_count);
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
WelfordWarpAllReduce(thread_mean, thread_m2, thread_count, &warp_mean, &warp_m2,
|
| 93 |
+
&warp_count);
|
| 94 |
+
|
| 95 |
+
float row_mean = warp_mean;
|
| 96 |
+
float row_variance = max(warp_m2 / warp_count, 0.f);
|
| 97 |
+
float row_inv_var = rsqrt(row_variance + epsilon);
|
| 98 |
+
if (lane_id == 0) {
|
| 99 |
+
mean[row_offset] = row_mean;
|
| 100 |
+
invvar[row_offset] = row_inv_var;
|
| 101 |
+
}
|
| 102 |
+
int process_type = (gamma != NULL)*2 + (beta != NULL);
|
| 103 |
+
if (process_type == 0) {
|
| 104 |
+
#pragma unroll
|
| 105 |
+
for(int idx = lane_id; idx < cols; idx += WarpSize)
|
| 106 |
+
row_output[idx] = static_cast<T>((static_cast<float>(shared_data_warp[idx]) - row_mean) * row_inv_var);
|
| 107 |
+
} else if (process_type == 1) {
|
| 108 |
+
#pragma unroll
|
| 109 |
+
for(int idx = lane_id; idx < cols; idx += WarpSize)
|
| 110 |
+
row_output[idx] = static_cast<T>((static_cast<float>(shared_data_warp[idx]) - row_mean) * row_inv_var + beta[idx]);
|
| 111 |
+
} else if(process_type == 2) {
|
| 112 |
+
#pragma unroll
|
| 113 |
+
for(int idx = lane_id; idx < cols; idx += WarpSize)
|
| 114 |
+
row_output[idx] = static_cast<T>((static_cast<float>(shared_data_warp[idx]) - row_mean) * row_inv_var * gamma[idx]);
|
| 115 |
+
} else {
|
| 116 |
+
#pragma unroll
|
| 117 |
+
for(int idx = lane_id; idx < cols; idx += WarpSize)
|
| 118 |
+
row_output[idx] = static_cast<T>((static_cast<float>(shared_data_warp[idx]) - row_mean) * row_inv_var * gamma[idx] + beta[idx]);
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
void cuda_layer_norm(at::Tensor* output, at::Tensor* mean, at::Tensor* invvar, at::Tensor* input,
|
| 124 |
+
int rows, int cols, at::IntArrayRef normalized_shape, at::Tensor* gamma,
|
| 125 |
+
at::Tensor* beta, double epsilon) {
|
| 126 |
+
int grid = (rows + WarpNum - 1) / WarpNum; // each warp process one line
|
| 127 |
+
dim3 block(BlockSzie);
|
| 128 |
+
// add shared memory size
|
| 129 |
+
if (output->dtype() == torch::kFloat32) {
|
| 130 |
+
int shared_meory_size = WarpNum*sizeof(float)*cols;
|
| 131 |
+
LayerNormForward<float><<<grid, block, shared_meory_size>>>(
|
| 132 |
+
(float*)input->data_ptr(), (float*)output->data_ptr(),
|
| 133 |
+
gamma != NULL ? (float*)gamma->data_ptr() : NULL, beta != NULL ? (float*)beta->data_ptr() : NULL,
|
| 134 |
+
(float*)mean->data_ptr(), (float*)invvar->data_ptr(), rows, cols, epsilon);
|
| 135 |
+
} else if (output->dtype() == torch::kFloat16) {
|
| 136 |
+
int shared_meory_size = WarpNum*sizeof(at::Half)*cols;
|
| 137 |
+
LayerNormForward<at::Half><<<grid, block, shared_meory_size>>>(
|
| 138 |
+
(at::Half*)input->data_ptr(), (at::Half*)output->data_ptr(),
|
| 139 |
+
gamma != NULL ? (at::Half*)gamma->data_ptr() : NULL, beta != NULL ? (at::Half*)beta->data_ptr() : NULL,
|
| 140 |
+
(float*)mean->data_ptr(), (float*)invvar->data_ptr(), rows, cols, epsilon);
|
| 141 |
+
} else if (output->dtype() == torch::kBFloat16) {
|
| 142 |
+
int shared_meory_size = WarpNum*sizeof(at::BFloat16)*cols;
|
| 143 |
+
LayerNormForward<at::BFloat16><<<grid, block, shared_meory_size>>>(
|
| 144 |
+
(at::BFloat16*)input->data_ptr(), (at::BFloat16*)output->data_ptr(),
|
| 145 |
+
gamma != NULL ? (at::BFloat16*)gamma->data_ptr() : NULL, beta != NULL ? (at::BFloat16*)beta->data_ptr() : NULL,
|
| 146 |
+
(float*)mean->data_ptr(), (float*)invvar->data_ptr(), rows, cols, epsilon);
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
template <typename T>
|
| 151 |
+
struct SharedMemory;
|
| 152 |
+
|
| 153 |
+
template <>
|
| 154 |
+
struct SharedMemory<float> {
|
| 155 |
+
__device__ float* getPointer() {
|
| 156 |
+
extern __shared__ float s_float[];
|
| 157 |
+
return s_float;
|
| 158 |
+
}
|
| 159 |
+
};
|
| 160 |
+
|
| 161 |
+
template<typename T>
|
| 162 |
+
__inline__ __device__ T WarpReduce(T val) {
|
| 163 |
+
for (int mask = 16; mask > 0; mask /= 2) { val += __shfl_xor_sync(0xffffffff, val, mask); }
|
| 164 |
+
return val;
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
constexpr int tile_size = 32;
|
| 168 |
+
constexpr int num_per_block = 4;
|
| 169 |
+
constexpr int block_dim_x = 32;
|
| 170 |
+
constexpr int block_dim_y = 32 / num_per_block;
|
| 171 |
+
|
| 172 |
+
template <typename T, typename V>
|
| 173 |
+
__global__ void LayerNormParamGradStep1(int rows, int cols, const V* __restrict__ dy,
|
| 174 |
+
const T* __restrict__ x, const float* __restrict__ mean,
|
| 175 |
+
const float* __restrict__ inv_var,
|
| 176 |
+
float* __restrict__ tmp_gamma_diff, float* __restrict__ tmp_beta_diff) {
|
| 177 |
+
__shared__ float dgamma[32][33];
|
| 178 |
+
__shared__ float dbeta[32][33];
|
| 179 |
+
float dgamma_sum[num_per_block];
|
| 180 |
+
float dbeta_sum[num_per_block];
|
| 181 |
+
#pragma unroll
|
| 182 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 183 |
+
dgamma_sum[index] = 0;
|
| 184 |
+
dbeta_sum[index] = 0;
|
| 185 |
+
}
|
| 186 |
+
const int col_id = blockIdx.x * blockDim.x + threadIdx.x;
|
| 187 |
+
if (col_id < cols) {
|
| 188 |
+
for (int i = blockIdx.y * tile_size + threadIdx.y; i < rows; i += tile_size * gridDim.y) {
|
| 189 |
+
#pragma unroll
|
| 190 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 191 |
+
int row_id = i + index * blockDim.y;
|
| 192 |
+
if (row_id < rows) {
|
| 193 |
+
int offset = row_id * cols + col_id;
|
| 194 |
+
const float dy_val = static_cast<float>(dy[offset]);
|
| 195 |
+
const float x_val = static_cast<float>(x[offset]);
|
| 196 |
+
const float mean_val = mean[row_id];
|
| 197 |
+
const float inv_var_val = inv_var[row_id];
|
| 198 |
+
dgamma_sum[index] += dy_val * (x_val - mean_val) * inv_var_val;
|
| 199 |
+
dbeta_sum[index] += dy_val;
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
#pragma unroll
|
| 205 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 206 |
+
dgamma[index * blockDim.y + threadIdx.y][threadIdx.x] = dgamma_sum[index];
|
| 207 |
+
dbeta[index * blockDim.y + threadIdx.y][threadIdx.x] = dbeta_sum[index];
|
| 208 |
+
}
|
| 209 |
+
__syncthreads();
|
| 210 |
+
#pragma unroll
|
| 211 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 212 |
+
const int col_id = blockIdx.x * blockDim.x + threadIdx.y + index * blockDim.y;
|
| 213 |
+
if (col_id < cols) {
|
| 214 |
+
float gamma_sum = dgamma[threadIdx.x][threadIdx.y + index * blockDim.y];
|
| 215 |
+
float beta_sum = dbeta[threadIdx.x][threadIdx.y + index * blockDim.y];
|
| 216 |
+
float global_dgamma = WarpReduce<float>(gamma_sum);
|
| 217 |
+
float global_dbeta = WarpReduce<float>(beta_sum);
|
| 218 |
+
if (threadIdx.x == 0) {
|
| 219 |
+
const int offset = blockIdx.y * cols + col_id;
|
| 220 |
+
tmp_gamma_diff[offset] = global_dgamma;
|
| 221 |
+
tmp_beta_diff[offset] = global_dbeta;
|
| 222 |
+
}
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
template <typename T, typename V>
|
| 228 |
+
__global__ void LayerNormGammaGradStep1(int rows, int cols, const V* __restrict__ dy,
|
| 229 |
+
const T* __restrict__ x, const float* __restrict__ mean,
|
| 230 |
+
const float* __restrict__ inv_var, float* __restrict__ tmp_gamma_diff) {
|
| 231 |
+
__shared__ float dgamma[32][33];
|
| 232 |
+
float dgamma_sum[num_per_block];
|
| 233 |
+
#pragma unroll
|
| 234 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 235 |
+
dgamma_sum[index] = 0;
|
| 236 |
+
}
|
| 237 |
+
const int col_id = blockIdx.x * blockDim.x + threadIdx.x;
|
| 238 |
+
if (col_id < cols) {
|
| 239 |
+
for (int i = blockIdx.y * tile_size + threadIdx.y; i < rows; i += tile_size * gridDim.y) {
|
| 240 |
+
#pragma unroll
|
| 241 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 242 |
+
int row_id = i + index * blockDim.y;
|
| 243 |
+
if (row_id < rows) {
|
| 244 |
+
int offset = row_id * cols + col_id;
|
| 245 |
+
const float dy_val = static_cast<float>(dy[offset]);
|
| 246 |
+
const float x_val = static_cast<float>(x[offset]);
|
| 247 |
+
const float mean_val = mean[row_id];
|
| 248 |
+
const float inv_var_val = inv_var[row_id];
|
| 249 |
+
dgamma_sum[index] += dy_val * (x_val - mean_val) * inv_var_val;
|
| 250 |
+
}
|
| 251 |
+
}
|
| 252 |
+
}
|
| 253 |
+
}
|
| 254 |
+
#pragma unroll
|
| 255 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 256 |
+
dgamma[index * blockDim.y + threadIdx.y][threadIdx.x] = dgamma_sum[index];
|
| 257 |
+
}
|
| 258 |
+
__syncthreads();
|
| 259 |
+
#pragma unroll
|
| 260 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 261 |
+
const int col_id = blockIdx.x * blockDim.x + threadIdx.y + index * blockDim.y;
|
| 262 |
+
if (col_id < cols) {
|
| 263 |
+
float gamma_sum = dgamma[threadIdx.x][threadIdx.y + index * blockDim.y];
|
| 264 |
+
float global_dgamma = WarpReduce<float>(gamma_sum);
|
| 265 |
+
if (threadIdx.x == 0) {
|
| 266 |
+
const int offset = blockIdx.y * cols + col_id;
|
| 267 |
+
tmp_gamma_diff[offset] = global_dgamma;
|
| 268 |
+
}
|
| 269 |
+
}
|
| 270 |
+
}
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
template <typename T, typename V>
|
| 274 |
+
__global__ void LayerNormBetaGradStep1(int rows, int cols, const V* __restrict__ dy,
|
| 275 |
+
const T* __restrict__ x, const float* __restrict__ mean,
|
| 276 |
+
const float* __restrict__ inv_var, float* __restrict__ tmp_beta_diff) {
|
| 277 |
+
__shared__ float dbeta[32][33];
|
| 278 |
+
float dbeta_sum[num_per_block];
|
| 279 |
+
#pragma unroll
|
| 280 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 281 |
+
dbeta_sum[index] = 0;
|
| 282 |
+
}
|
| 283 |
+
const int col_id = blockIdx.x * blockDim.x + threadIdx.x;
|
| 284 |
+
if (col_id < cols) {
|
| 285 |
+
for (int i = blockIdx.y * tile_size + threadIdx.y; i < rows; i += tile_size * gridDim.y) {
|
| 286 |
+
#pragma unroll
|
| 287 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 288 |
+
int row_id = i + index * blockDim.y;
|
| 289 |
+
if (row_id < rows) {
|
| 290 |
+
int offset = row_id * cols + col_id;
|
| 291 |
+
const float dy_val = static_cast<float>(dy[offset]);
|
| 292 |
+
dbeta_sum[index] += dy_val;
|
| 293 |
+
}
|
| 294 |
+
}
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
#pragma unroll
|
| 298 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 299 |
+
dbeta[index * blockDim.y + threadIdx.y][threadIdx.x] = dbeta_sum[index];
|
| 300 |
+
}
|
| 301 |
+
__syncthreads();
|
| 302 |
+
#pragma unroll
|
| 303 |
+
for (int index = 0; index < num_per_block; ++index) {
|
| 304 |
+
const int col_id = blockIdx.x * blockDim.x + threadIdx.y + index * blockDim.y;
|
| 305 |
+
if (col_id < cols) {
|
| 306 |
+
float beta_sum = dbeta[threadIdx.x][threadIdx.y + index * blockDim.y];
|
| 307 |
+
float global_dbeta = WarpReduce<float>(beta_sum);
|
| 308 |
+
if (threadIdx.x == 0) {
|
| 309 |
+
const int offset = blockIdx.y * cols + col_id;
|
| 310 |
+
tmp_beta_diff[offset] = global_dbeta;
|
| 311 |
+
}
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
template <typename V>
|
| 317 |
+
__global__ void LayerNormParamGradStep2(const float* part_grad_gamma, const float* part_grad_beta,
|
| 318 |
+
const int part_size, const int n1, const int n2,
|
| 319 |
+
V* grad_gamma, V* grad_beta) {
|
| 320 |
+
// sum partial gradients for gamma and beta
|
| 321 |
+
SharedMemory<float> shared;
|
| 322 |
+
float* buf = shared.getPointer();
|
| 323 |
+
int i2 = blockIdx.x * blockDim.x + threadIdx.x;
|
| 324 |
+
if (i2 < n2) {
|
| 325 |
+
// each warp does sequential reductions until reduced part_size is num_warps
|
| 326 |
+
// int num_warp_reductions = part_size / blockDim.y;
|
| 327 |
+
float sum_gamma = float(0);
|
| 328 |
+
float sum_beta = float(0);
|
| 329 |
+
const float* part_grad_gamma_ptr = part_grad_gamma + i2;
|
| 330 |
+
const float* part_grad_beta_ptr = part_grad_beta + i2;
|
| 331 |
+
for (int row_idx = threadIdx.y; row_idx < part_size; row_idx += blockDim.y) {
|
| 332 |
+
sum_gamma += part_grad_gamma_ptr[row_idx * n2];
|
| 333 |
+
sum_beta += part_grad_beta_ptr[row_idx * n2];
|
| 334 |
+
}
|
| 335 |
+
// inter-warp reductions
|
| 336 |
+
const int nbsize3 = blockDim.x * blockDim.y / 2;
|
| 337 |
+
for (int offset = blockDim.y / 2; offset >= 1; offset /= 2) {
|
| 338 |
+
// top half write to shared memory
|
| 339 |
+
if (threadIdx.y >= offset && threadIdx.y < 2 * offset) {
|
| 340 |
+
const int write_idx = (threadIdx.y - offset) * blockDim.x + threadIdx.x;
|
| 341 |
+
buf[write_idx] = sum_gamma;
|
| 342 |
+
buf[write_idx + nbsize3] = sum_beta;
|
| 343 |
+
}
|
| 344 |
+
__syncthreads();
|
| 345 |
+
// bottom half sums
|
| 346 |
+
if (threadIdx.y < offset) {
|
| 347 |
+
const int read_idx = threadIdx.y * blockDim.x + threadIdx.x;
|
| 348 |
+
sum_gamma += buf[read_idx];
|
| 349 |
+
sum_beta += buf[read_idx + nbsize3];
|
| 350 |
+
}
|
| 351 |
+
__syncthreads();
|
| 352 |
+
}
|
| 353 |
+
// write out fully summed gradients
|
| 354 |
+
if (threadIdx.y == 0) {
|
| 355 |
+
grad_gamma[i2] = sum_gamma;
|
| 356 |
+
grad_beta[i2] = sum_beta;
|
| 357 |
+
}
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
template <typename V>
|
| 362 |
+
__global__ void LayerNormGammaGradStep2(const float* part_grad_gamma, const int part_size, const int n1, const int n2, V* grad_gamma) {
|
| 363 |
+
// sum partial gradients for gamma and beta
|
| 364 |
+
SharedMemory<float> shared;
|
| 365 |
+
float* buf = shared.getPointer();
|
| 366 |
+
int i2 = blockIdx.x * blockDim.x + threadIdx.x;
|
| 367 |
+
if (i2 < n2) {
|
| 368 |
+
// each warp does sequential reductions until reduced part_size is num_warps
|
| 369 |
+
// int num_warp_reductions = part_size / blockDim.y;
|
| 370 |
+
float sum_gamma = float(0);
|
| 371 |
+
const float* part_grad_gamma_ptr = part_grad_gamma + i2;
|
| 372 |
+
for (int row_idx = threadIdx.y; row_idx < part_size; row_idx += blockDim.y) {
|
| 373 |
+
sum_gamma += part_grad_gamma_ptr[row_idx * n2];
|
| 374 |
+
}
|
| 375 |
+
// inter-warp reductions
|
| 376 |
+
for (int offset = blockDim.y / 2; offset >= 1; offset /= 2) {
|
| 377 |
+
// top half write to shared memory
|
| 378 |
+
if (threadIdx.y >= offset && threadIdx.y < 2 * offset) {
|
| 379 |
+
const int write_idx = (threadIdx.y - offset) * blockDim.x + threadIdx.x;
|
| 380 |
+
buf[write_idx] = sum_gamma;
|
| 381 |
+
}
|
| 382 |
+
__syncthreads();
|
| 383 |
+
// bottom half sums
|
| 384 |
+
if (threadIdx.y < offset) {
|
| 385 |
+
const int read_idx = threadIdx.y * blockDim.x + threadIdx.x;
|
| 386 |
+
sum_gamma += buf[read_idx];
|
| 387 |
+
}
|
| 388 |
+
__syncthreads();
|
| 389 |
+
}
|
| 390 |
+
// write out fully summed gradients
|
| 391 |
+
if (threadIdx.y == 0) {
|
| 392 |
+
grad_gamma[i2] = sum_gamma;
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
template <typename V>
|
| 398 |
+
__global__ void LayerNormBetaGradStep2(const float* part_grad_beta, const int part_size, const int n1, const int n2, V* grad_beta) {
|
| 399 |
+
// sum partial gradients for gamma and beta
|
| 400 |
+
SharedMemory<float> shared;
|
| 401 |
+
float* buf = shared.getPointer();
|
| 402 |
+
int i2 = blockIdx.x * blockDim.x + threadIdx.x;
|
| 403 |
+
if (i2 < n2) {
|
| 404 |
+
// each warp does sequential reductions until reduced part_size is num_warps
|
| 405 |
+
// int num_warp_reductions = part_size / blockDim.y;
|
| 406 |
+
float sum_beta = float(0);
|
| 407 |
+
const float* part_grad_beta_ptr = part_grad_beta + i2;
|
| 408 |
+
for (int row_idx = threadIdx.y; row_idx < part_size; row_idx += blockDim.y) {
|
| 409 |
+
sum_beta += part_grad_beta_ptr[row_idx * n2];
|
| 410 |
+
}
|
| 411 |
+
// inter-warp reductions
|
| 412 |
+
for (int offset = blockDim.y / 2; offset >= 1; offset /= 2) {
|
| 413 |
+
// top half write to shared memory
|
| 414 |
+
if (threadIdx.y >= offset && threadIdx.y < 2 * offset) {
|
| 415 |
+
const int write_idx = (threadIdx.y - offset) * blockDim.x + threadIdx.x;
|
| 416 |
+
buf[write_idx] = sum_beta;
|
| 417 |
+
}
|
| 418 |
+
__syncthreads();
|
| 419 |
+
// bottom half sums
|
| 420 |
+
if (threadIdx.y < offset) {
|
| 421 |
+
const int read_idx = threadIdx.y * blockDim.x + threadIdx.x;
|
| 422 |
+
sum_beta += buf[read_idx];
|
| 423 |
+
}
|
| 424 |
+
__syncthreads();
|
| 425 |
+
}
|
| 426 |
+
// write out fully summed gradients
|
| 427 |
+
if (threadIdx.y == 0) {
|
| 428 |
+
grad_beta[i2] = sum_beta;
|
| 429 |
+
}
|
| 430 |
+
}
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
template <typename T, typename V>
|
| 434 |
+
__global__ void LayerNormInputGrad(const V* __restrict__ dout, const T* __restrict__ input,
|
| 435 |
+
const int rows, const int cols, const float* __restrict__ mean,
|
| 436 |
+
const float* __restrict__ invvar, float epsilon, const V* gamma,
|
| 437 |
+
T* grad_input) {
|
| 438 |
+
int WarpPerBlock = blockDim.x / WarpSize;
|
| 439 |
+
int thread_idx = threadIdx.x;
|
| 440 |
+
int warp_idx = thread_idx / WarpSize;
|
| 441 |
+
int lane_idx = thread_idx % WarpSize;
|
| 442 |
+
|
| 443 |
+
float* shared_dout = shared_data + warp_idx*cols;
|
| 444 |
+
float* shared_input = shared_data + WarpPerBlock*cols + warp_idx*cols;
|
| 445 |
+
float* shared_gamma = shared_data + 2*WarpPerBlock*cols;
|
| 446 |
+
int row_stride = gridDim.x*WarpPerBlock;
|
| 447 |
+
for(int row = blockIdx.x*WarpPerBlock+warp_idx; row < rows; row += row_stride) {
|
| 448 |
+
float mean_r = mean[row];
|
| 449 |
+
float invvar_r = invvar[row];
|
| 450 |
+
// load dout, input and gamma
|
| 451 |
+
long long data_offset = (long long)(row) * cols;
|
| 452 |
+
const V* dout_r = dout + data_offset;
|
| 453 |
+
const T* input_r = input + data_offset;
|
| 454 |
+
T* grad_input_r = grad_input + data_offset;
|
| 455 |
+
#pragma unroll
|
| 456 |
+
for(int col = lane_idx; col < cols; col += WarpSize) {
|
| 457 |
+
shared_dout[col] = float(dout_r[col]);
|
| 458 |
+
shared_input[col] = float(input_r[col]);
|
| 459 |
+
}
|
| 460 |
+
if(warp_idx == 0) {
|
| 461 |
+
#pragma unroll
|
| 462 |
+
for(int col = lane_idx; col < cols; col += WarpSize) {
|
| 463 |
+
shared_gamma[col] = gamma != NULL ? float(gamma[col]) : 1.0f;
|
| 464 |
+
}
|
| 465 |
+
}
|
| 466 |
+
__syncthreads();
|
| 467 |
+
|
| 468 |
+
float gamma_dout = 0.0;
|
| 469 |
+
float gamma_dout_input_mean = 0.0;
|
| 470 |
+
// reduction, gamma*dout and gamma*dout*(input-mean)
|
| 471 |
+
#pragma unroll
|
| 472 |
+
for(int col = lane_idx; col < cols; col += WarpSize) {
|
| 473 |
+
float temp = shared_gamma[col] * shared_dout[col];
|
| 474 |
+
gamma_dout += temp;
|
| 475 |
+
gamma_dout_input_mean += temp * (shared_input[col] - mean_r);
|
| 476 |
+
}
|
| 477 |
+
float global_gamma_dout = WarpReduce<float>(gamma_dout);
|
| 478 |
+
float global_gamma_dout_input_mean = WarpReduce<float>(gamma_dout_input_mean);
|
| 479 |
+
|
| 480 |
+
float part3_temp_value = global_gamma_dout_input_mean * invvar_r * invvar_r * invvar_r / cols;
|
| 481 |
+
float part2 = global_gamma_dout * invvar_r / cols;
|
| 482 |
+
#pragma unroll
|
| 483 |
+
for(int col = lane_idx; col < cols; col += WarpSize) {
|
| 484 |
+
float part1 = shared_gamma[col] * shared_dout[col] * invvar_r;
|
| 485 |
+
float part3 = (shared_input[col] - mean_r) * part3_temp_value;
|
| 486 |
+
grad_input_r[col] = part1 - part2 - part3;
|
| 487 |
+
}
|
| 488 |
+
}
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
template <typename T, typename V>
|
| 492 |
+
int GetGirdDimY(const int64_t num_instances, const int64_t norm_size) {
|
| 493 |
+
const int grid_dim_x = (norm_size + tile_size - 1) / tile_size;
|
| 494 |
+
const int max_grid_dim_y = (num_instances + tile_size - 1) / tile_size;
|
| 495 |
+
const int block_size = block_dim_x * block_dim_y;
|
| 496 |
+
int max_active_blocks = 0;
|
| 497 |
+
cudaOccupancyMaxActiveBlocksPerMultiprocessor(
|
| 498 |
+
&max_active_blocks, LayerNormParamGradStep1<T, V>, block_size, 0);
|
| 499 |
+
int waves = 1;
|
| 500 |
+
int dev;
|
| 501 |
+
cudaGetDevice(&dev);
|
| 502 |
+
int sm_count;
|
| 503 |
+
cudaDeviceGetAttribute(&sm_count, cudaDevAttrMultiProcessorCount, dev);
|
| 504 |
+
int num_blocks = max_active_blocks * sm_count * waves;
|
| 505 |
+
int grid_dim_y = std::min(max_grid_dim_y, static_cast<int>(num_blocks / grid_dim_x));
|
| 506 |
+
return std::max(grid_dim_y, 1);
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
template <typename T, typename V>
|
| 510 |
+
void HostLayerNormGradient(const V* dout, const float* mean, const float* invvar, at::Tensor* input, int n1,
|
| 511 |
+
int n2, const V* gamma, const V* beta, double epsilon, T* grad_input,
|
| 512 |
+
V* grad_gamma, V* grad_beta) {
|
| 513 |
+
auto stream = at::cuda::getCurrentCUDAStream().stream();
|
| 514 |
+
|
| 515 |
+
if (gamma != NULL && beta != NULL) {
|
| 516 |
+
// compute grad_gamma(j) and grad_beta(j)
|
| 517 |
+
const int part_size = GetGirdDimY<T, V>(n1, n2);
|
| 518 |
+
const int grid_dim_x = (n2 + tile_size - 1) / tile_size;
|
| 519 |
+
const int grid_dim_y = part_size;
|
| 520 |
+
|
| 521 |
+
at::Tensor part_grad_gamma = at::empty({part_size, n2}, input->options().dtype(at::ScalarType::Float));
|
| 522 |
+
at::Tensor part_grad_beta = at::empty_like(part_grad_gamma);
|
| 523 |
+
LayerNormParamGradStep1<T, V><<<dim3(grid_dim_x, grid_dim_y), dim3(32, 32 / num_per_block)>>>(
|
| 524 |
+
n1, n2, dout, input->DATA_PTR<T>(), mean, invvar, part_grad_gamma.DATA_PTR<float>(), part_grad_beta.DATA_PTR<float>()
|
| 525 |
+
);
|
| 526 |
+
|
| 527 |
+
const dim3 threads3(32, 8, 1);
|
| 528 |
+
const dim3 blocks3((n2 + 32 - 1) / 32, 1, 1);
|
| 529 |
+
const int nshared3 = threads3.x * threads3.y * sizeof(float);
|
| 530 |
+
LayerNormParamGradStep2<<<blocks3, threads3, nshared3, stream>>>(
|
| 531 |
+
part_grad_gamma.DATA_PTR<float>(), part_grad_beta.DATA_PTR<float>(), part_size, n1, n2,
|
| 532 |
+
grad_gamma, grad_beta);
|
| 533 |
+
} else if (gamma != NULL && beta == NULL) {
|
| 534 |
+
// compute grad_gamma(j) and grad_beta(j)
|
| 535 |
+
const int part_size = GetGirdDimY<T, V>(n1, n2);
|
| 536 |
+
const int grid_dim_x = (n2 + tile_size - 1) / tile_size;
|
| 537 |
+
const int grid_dim_y = part_size;
|
| 538 |
+
|
| 539 |
+
at::Tensor part_grad_gamma = at::empty({part_size, n2}, input->options().dtype(at::ScalarType::Float));
|
| 540 |
+
LayerNormGammaGradStep1<T, V><<<dim3(grid_dim_x, grid_dim_y), dim3(32, 32 / num_per_block)>>>(
|
| 541 |
+
n1, n2, dout, input->DATA_PTR<T>(), mean, invvar, part_grad_gamma.DATA_PTR<float>());
|
| 542 |
+
|
| 543 |
+
const dim3 threads3(32, 8, 1);
|
| 544 |
+
const dim3 blocks3((n2 + 32 - 1) / 32, 1, 1);
|
| 545 |
+
const int nshared3 = threads3.x * threads3.y * sizeof(float);
|
| 546 |
+
LayerNormGammaGradStep2<<<blocks3, threads3, nshared3, stream>>>(
|
| 547 |
+
part_grad_gamma.DATA_PTR<float>(), part_size, n1, n2, grad_gamma);
|
| 548 |
+
} else if (gamma == NULL && beta!= NULL) {
|
| 549 |
+
// compute grad_gamma(j) and grad_beta(j)
|
| 550 |
+
const int part_size = GetGirdDimY<T, V>(n1, n2);
|
| 551 |
+
const int grid_dim_x = (n2 + tile_size - 1) / tile_size;
|
| 552 |
+
const int grid_dim_y = part_size;
|
| 553 |
+
|
| 554 |
+
at::Tensor part_grad_beta = at::empty({part_size, n2}, input->options().dtype(at::ScalarType::Float));
|
| 555 |
+
LayerNormBetaGradStep1<T, V><<<dim3(grid_dim_x, grid_dim_y), dim3(32, 32 / num_per_block)>>>(
|
| 556 |
+
n1, n2, dout, input->DATA_PTR<T>(), mean, invvar, part_grad_beta.DATA_PTR<float>()
|
| 557 |
+
);
|
| 558 |
+
|
| 559 |
+
const dim3 threads3(32, 8, 1);
|
| 560 |
+
const dim3 blocks3((n2 + 32 - 1) / 32, 1, 1);
|
| 561 |
+
const int nshared3 = threads3.x * threads3.y * sizeof(float);
|
| 562 |
+
LayerNormBetaGradStep2<<<blocks3, threads3, nshared3, stream>>>(
|
| 563 |
+
part_grad_beta.DATA_PTR<float>(), part_size, n1, n2, grad_beta);
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
const uint64_t maxGridY = at::cuda::getCurrentDeviceProperties()->maxGridSize[1];
|
| 567 |
+
#define BlockDim 128
|
| 568 |
+
int WarpNumPerBlock = BlockDim / WarpSize;
|
| 569 |
+
const dim3 threads1(BlockDim);
|
| 570 |
+
int nshared = sizeof(float)*n2*(WarpNumPerBlock*2 + 1);
|
| 571 |
+
|
| 572 |
+
int max_active_blocks = 0;
|
| 573 |
+
cudaOccupancyMaxActiveBlocksPerMultiprocessor(
|
| 574 |
+
&max_active_blocks, LayerNormInputGrad<T, V>, BlockDim, nshared);
|
| 575 |
+
int dev;
|
| 576 |
+
cudaGetDevice(&dev);
|
| 577 |
+
int sm_count;
|
| 578 |
+
cudaDeviceGetAttribute(&sm_count, cudaDevAttrMultiProcessorCount, dev);
|
| 579 |
+
|
| 580 |
+
const dim3 blocks1(std::min((uint64_t)((n1 + WarpNumPerBlock - 1)/WarpNumPerBlock), (uint64_t)(max_active_blocks * sm_count)));
|
| 581 |
+
LayerNormInputGrad<<<blocks1, threads1, nshared>>>(dout, input->DATA_PTR<T>(), n1, n2, mean, invvar, float(epsilon), gamma, grad_input);
|
| 582 |
+
}
|
| 583 |
+
|
| 584 |
+
void cuda_layer_norm_gradient(at::Tensor* dout, at::Tensor* mean, at::Tensor* invvar,
|
| 585 |
+
at::Tensor* input, int n1, int n2, at::IntArrayRef normalized_shape,
|
| 586 |
+
at::Tensor* gamma, at::Tensor* beta, double epsilon,
|
| 587 |
+
at::Tensor* grad_input, at::Tensor* grad_gamma,
|
| 588 |
+
at::Tensor* grad_beta) {
|
| 589 |
+
using namespace at;
|
| 590 |
+
DISPATCH_FLOAT_HALF_AND_BFLOAT_INOUT_TYPES(
|
| 591 |
+
input->scalar_type(), dout->scalar_type(), "cuda_layer_norm_gradient_kernel",
|
| 592 |
+
HostLayerNormGradient(dout->DATA_PTR<scalar_t_out>(), mean->DATA_PTR<float>(),
|
| 593 |
+
invvar->DATA_PTR<float>(), input, n1, n2,
|
| 594 |
+
gamma != NULL ? gamma->DATA_PTR<scalar_t_out>() : NULL,
|
| 595 |
+
beta != NULL ? beta->DATA_PTR<scalar_t_out>() : NULL, epsilon,
|
| 596 |
+
grad_input->DATA_PTR<scalar_t_in>(),
|
| 597 |
+
gamma != NULL ? grad_gamma->DATA_PTR<scalar_t_out>() : NULL,
|
| 598 |
+
beta != NULL ? grad_beta->DATA_PTR<scalar_t_out>() : NULL);)
|
| 599 |
+
}
|
model/protenix/layer_norm/kernel/type_shim.h
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <ATen/ATen.h>
|
| 2 |
+
|
| 3 |
+
#include "compat.h"
|
| 4 |
+
|
| 5 |
+
#define DISPATCH_HALF_AND_BFLOAT(TYPE, NAME, ...) \
|
| 6 |
+
switch (TYPE) { \
|
| 7 |
+
case at::ScalarType::Half: { \
|
| 8 |
+
using scalar_t = at::Half; \
|
| 9 |
+
__VA_ARGS__; \
|
| 10 |
+
break; \
|
| 11 |
+
} \
|
| 12 |
+
case at::ScalarType::BFloat16: { \
|
| 13 |
+
using scalar_t = at::BFloat16; \
|
| 14 |
+
__VA_ARGS__; \
|
| 15 |
+
break; \
|
| 16 |
+
} \
|
| 17 |
+
default: \
|
| 18 |
+
AT_ERROR(#NAME, " not implemented for '", toString(TYPE), "'"); \
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
#define DISPATCH_FLOAT_HALF_AND_BFLOAT_INOUT_TYPES(TYPEIN, TYPEOUT, NAME, ...) \
|
| 22 |
+
switch (TYPEIN) { \
|
| 23 |
+
case at::ScalarType::Float: { \
|
| 24 |
+
using scalar_t_in = float; \
|
| 25 |
+
switch (TYPEOUT) { \
|
| 26 |
+
case at::ScalarType::Float: { \
|
| 27 |
+
using scalar_t_out = float; \
|
| 28 |
+
__VA_ARGS__; \
|
| 29 |
+
break; \
|
| 30 |
+
} \
|
| 31 |
+
case at::ScalarType::Half: { \
|
| 32 |
+
using scalar_t_out = at::Half; \
|
| 33 |
+
__VA_ARGS__; \
|
| 34 |
+
break; \
|
| 35 |
+
} \
|
| 36 |
+
case at::ScalarType::BFloat16: { \
|
| 37 |
+
using scalar_t_out = at::BFloat16; \
|
| 38 |
+
__VA_ARGS__; \
|
| 39 |
+
break; \
|
| 40 |
+
} \
|
| 41 |
+
default: \
|
| 42 |
+
AT_ERROR(#NAME, " not implemented for '", toString(TYPEOUT), "'"); \
|
| 43 |
+
} \
|
| 44 |
+
break; \
|
| 45 |
+
} \
|
| 46 |
+
case at::ScalarType::Half: { \
|
| 47 |
+
using scalar_t_in = at::Half; \
|
| 48 |
+
using scalar_t_out = at::Half; \
|
| 49 |
+
__VA_ARGS__; \
|
| 50 |
+
break; \
|
| 51 |
+
} \
|
| 52 |
+
case at::ScalarType::BFloat16: { \
|
| 53 |
+
using scalar_t_in = at::BFloat16; \
|
| 54 |
+
using scalar_t_out = at::BFloat16; \
|
| 55 |
+
__VA_ARGS__; \
|
| 56 |
+
break; \
|
| 57 |
+
} \
|
| 58 |
+
default: \
|
| 59 |
+
AT_ERROR(#NAME, " not implemented for '", toString(TYPEIN), "'"); \
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
// Forward/backward compatiblity hack around
|
| 63 |
+
// https://github.com/pytorch/pytorch/commit/3aeb78079bcd68282fe9117088e138b77318e288
|
| 64 |
+
// pending more future-proof guidance from upstream.
|
| 65 |
+
// struct TypeShim
|
| 66 |
+
// {
|
| 67 |
+
// const at::Type& payload;
|
| 68 |
+
// TypeShim(const at::Type& type) : payload(type) {}
|
| 69 |
+
// // Enable trivial conversion to a const at::Type& for pre-3aeb78
|
| 70 |
+
// operator const at::Type&(){ return payload; };
|
| 71 |
+
// // Enable dispatch switch statements to take *this directly for post-3aeb78
|
| 72 |
+
// //operator at::ScalarType(){ return payload.; };
|
| 73 |
+
// };
|
| 74 |
+
|
| 75 |
+
#define DISPATCH_FLOAT_AND_HALF(TYPE, LEVEL, NAME, ...) \
|
| 76 |
+
switch (TYPE) { \
|
| 77 |
+
case at::ScalarType::Float: { \
|
| 78 |
+
using scalar_t_##LEVEL = float; \
|
| 79 |
+
__VA_ARGS__; \
|
| 80 |
+
break; \
|
| 81 |
+
} \
|
| 82 |
+
case at::ScalarType::Half: { \
|
| 83 |
+
using scalar_t_##LEVEL = at::Half; \
|
| 84 |
+
__VA_ARGS__; \
|
| 85 |
+
break; \
|
| 86 |
+
} \
|
| 87 |
+
default: \
|
| 88 |
+
AT_ERROR(#NAME, " not implemented for '", toString(TYPE), "'"); \
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
#define DISPATCH_FLOAT_HALF_AND_BYTE(TYPE, LEVEL, NAME, ...) \
|
| 92 |
+
switch (TYPE) { \
|
| 93 |
+
case at::ScalarType::Float: { \
|
| 94 |
+
using scalar_t_##LEVEL = float; \
|
| 95 |
+
__VA_ARGS__; \
|
| 96 |
+
break; \
|
| 97 |
+
} \
|
| 98 |
+
case at::ScalarType::Half: { \
|
| 99 |
+
using scalar_t_##LEVEL = at::Half; \
|
| 100 |
+
__VA_ARGS__; \
|
| 101 |
+
break; \
|
| 102 |
+
} \
|
| 103 |
+
case at::ScalarType::Byte: { \
|
| 104 |
+
using scalar_t_##LEVEL = uint8_t; \
|
| 105 |
+
__VA_ARGS__; \
|
| 106 |
+
break; \
|
| 107 |
+
} \
|
| 108 |
+
default: \
|
| 109 |
+
AT_ERROR(#NAME, " not implemented for '", toString(TYPE), "'"); \
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
#define DISPATCH_DOUBLE_FLOAT_AND_HALF(TYPE, LEVEL, NAME, ...) \
|
| 113 |
+
switch (TYPE) { \
|
| 114 |
+
case at::ScalarType::Double: { \
|
| 115 |
+
using scalar_t_##LEVEL = double; \
|
| 116 |
+
__VA_ARGS__; \
|
| 117 |
+
break; \
|
| 118 |
+
} \
|
| 119 |
+
case at::ScalarType::Float: { \
|
| 120 |
+
using scalar_t_##LEVEL = float; \
|
| 121 |
+
__VA_ARGS__; \
|
| 122 |
+
break; \
|
| 123 |
+
} \
|
| 124 |
+
case at::ScalarType::Half: { \
|
| 125 |
+
using scalar_t_##LEVEL = at::Half; \
|
| 126 |
+
__VA_ARGS__; \
|
| 127 |
+
break; \
|
| 128 |
+
} \
|
| 129 |
+
default: \
|
| 130 |
+
AT_ERROR(#NAME, " not implemented for '", toString(TYPE), "'"); \
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
#define DISPATCH_DOUBLE_AND_FLOAT(TYPE, LEVEL, NAME, ...) \
|
| 134 |
+
switch (TYPE) { \
|
| 135 |
+
case at::ScalarType::Double: { \
|
| 136 |
+
using scalar_t_##LEVEL = double; \
|
| 137 |
+
__VA_ARGS__; \
|
| 138 |
+
break; \
|
| 139 |
+
} \
|
| 140 |
+
case at::ScalarType::Float: { \
|
| 141 |
+
using scalar_t_##LEVEL = float; \
|
| 142 |
+
__VA_ARGS__; \
|
| 143 |
+
break; \
|
| 144 |
+
} \
|
| 145 |
+
default: \
|
| 146 |
+
AT_ERROR(#NAME, " not implemented for '", toString(TYPE), "'"); \
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
template <typename T>
|
| 150 |
+
__device__ __forceinline__ T
|
| 151 |
+
reduce_block_into_lanes(T *x, T val, int lanes = 1,
|
| 152 |
+
bool share_result = false) // lanes is intended to be <= 32.
|
| 153 |
+
{
|
| 154 |
+
int tid = threadIdx.x + threadIdx.y * blockDim.x;
|
| 155 |
+
int blockSize = blockDim.x * blockDim.y; // blockSize is intended to be a multiple of 32.
|
| 156 |
+
|
| 157 |
+
if (blockSize >= 64) {
|
| 158 |
+
x[tid] = val;
|
| 159 |
+
__syncthreads();
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
#pragma unroll
|
| 163 |
+
for (int i = (blockSize >> 1); i >= 64; i >>= 1) {
|
| 164 |
+
if (tid < i) x[tid] = x[tid] + x[tid + i];
|
| 165 |
+
__syncthreads();
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
T final;
|
| 169 |
+
|
| 170 |
+
if (tid < 32) {
|
| 171 |
+
if (blockSize >= 64)
|
| 172 |
+
final = x[tid] + x[tid + 32];
|
| 173 |
+
else
|
| 174 |
+
final = val;
|
| 175 |
+
// __SYNCWARP();
|
| 176 |
+
|
| 177 |
+
#pragma unroll
|
| 178 |
+
for (int i = 16; i >= lanes; i >>= 1)
|
| 179 |
+
final = final + __shfl_down_sync(0xffffffff, final, i);
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
if (share_result) {
|
| 183 |
+
if (tid < lanes) x[tid] = final; // EpilogueOp
|
| 184 |
+
// Make sure the smem result is visible to all warps.
|
| 185 |
+
__syncthreads();
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
return final;
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
template <typename T>
|
| 192 |
+
__device__ __forceinline__ T
|
| 193 |
+
reduce_block_into_lanes_max_op(T *x, T val, int lanes = 1,
|
| 194 |
+
bool share_result = false) // lanes is intended to be <= 32.
|
| 195 |
+
{
|
| 196 |
+
int tid = threadIdx.x + threadIdx.y * blockDim.x;
|
| 197 |
+
int blockSize = blockDim.x * blockDim.y; // blockSize is intended to be a multiple of 32.
|
| 198 |
+
|
| 199 |
+
if (blockSize >= 64) {
|
| 200 |
+
x[tid] = val;
|
| 201 |
+
__syncthreads();
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
#pragma unroll
|
| 205 |
+
for (int i = (blockSize >> 1); i >= 64; i >>= 1) {
|
| 206 |
+
if (tid < i) x[tid] = fmaxf(fabsf(x[tid]), fabsf(x[tid + i]));
|
| 207 |
+
__syncthreads();
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
T final;
|
| 211 |
+
|
| 212 |
+
if (tid < 32) {
|
| 213 |
+
if (blockSize >= 64)
|
| 214 |
+
final = fmaxf(fabsf(x[tid]), fabsf(x[tid + 32]));
|
| 215 |
+
else
|
| 216 |
+
final = val;
|
| 217 |
+
// __SYNCWARP();
|
| 218 |
+
|
| 219 |
+
#pragma unroll
|
| 220 |
+
for (int i = 16; i >= lanes; i >>= 1)
|
| 221 |
+
final = fmaxf(fabsf(final), fabsf(__shfl_down_sync(0xffffffff, final, i)));
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
if (share_result) {
|
| 225 |
+
if (tid < lanes) x[tid] = final; // EpilogueOp
|
| 226 |
+
// Make sure the smem result is visible to all warps.
|
| 227 |
+
__syncthreads();
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
return final;
|
| 231 |
+
}
|
model/protenix/layer_norm/layer_norm.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
import numbers
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch.nn.parameter import Parameter
|
| 9 |
+
|
| 10 |
+
sys.path.append(os.path.dirname(__file__))
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
fastfold_layer_norm_cuda = importlib.import_module("fastfold_layer_norm_cuda")
|
| 14 |
+
except ImportError:
|
| 15 |
+
from model.protenix.layer_norm.torch_ext_compile import compile
|
| 16 |
+
|
| 17 |
+
current_dir = os.path.dirname(__file__)
|
| 18 |
+
fastfold_layer_norm_cuda = compile(
|
| 19 |
+
name="fastfold_layer_norm_cuda",
|
| 20 |
+
sources=[
|
| 21 |
+
os.path.join(f"{current_dir}/kernel", file)
|
| 22 |
+
for file in ["layer_norm_cuda.cpp", "layer_norm_cuda_kernel.cu"]
|
| 23 |
+
],
|
| 24 |
+
extra_include_paths=[f"{current_dir}/kernel"],
|
| 25 |
+
build_directory=current_dir,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class FusedLayerNormAffineFunction(torch.autograd.Function):
|
| 30 |
+
|
| 31 |
+
@staticmethod
|
| 32 |
+
def forward(ctx, input, weight, bias, normalized_shape, eps):
|
| 33 |
+
d = input.dtype
|
| 34 |
+
|
| 35 |
+
ctx.normalized_shape = normalized_shape
|
| 36 |
+
ctx.eps = eps
|
| 37 |
+
input_ = input.contiguous()
|
| 38 |
+
|
| 39 |
+
if weight is None:
|
| 40 |
+
if bias is None:
|
| 41 |
+
output, mean, invvar = fastfold_layer_norm_cuda.forward_none_affine(
|
| 42 |
+
input_, ctx.normalized_shape, ctx.eps
|
| 43 |
+
)
|
| 44 |
+
else:
|
| 45 |
+
output, mean, invvar = (
|
| 46 |
+
fastfold_layer_norm_cuda.forward_with_bias_affine(
|
| 47 |
+
input_, ctx.normalized_shape, bias.to(d), ctx.eps
|
| 48 |
+
)
|
| 49 |
+
)
|
| 50 |
+
else:
|
| 51 |
+
if bias is None:
|
| 52 |
+
output, mean, invvar = (
|
| 53 |
+
fastfold_layer_norm_cuda.forward_with_weight_affine(
|
| 54 |
+
input_, ctx.normalized_shape, weight.to(d), ctx.eps
|
| 55 |
+
)
|
| 56 |
+
)
|
| 57 |
+
else:
|
| 58 |
+
output, mean, invvar = (
|
| 59 |
+
fastfold_layer_norm_cuda.forward_with_both_affine(
|
| 60 |
+
input_, ctx.normalized_shape, weight.to(d), bias.to(d), ctx.eps
|
| 61 |
+
)
|
| 62 |
+
)
|
| 63 |
+
ctx.save_for_backward(input_, weight, bias, mean, invvar)
|
| 64 |
+
return output
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def backward(ctx, grad_output):
|
| 68 |
+
d = grad_output.dtype
|
| 69 |
+
input_, weight_, bias_, mean, invvar = ctx.saved_tensors
|
| 70 |
+
grad_input = grad_weight = grad_bias = None
|
| 71 |
+
|
| 72 |
+
if weight_ is None:
|
| 73 |
+
if bias_ is None:
|
| 74 |
+
grad_input, grad_weight, grad_bias = (
|
| 75 |
+
fastfold_layer_norm_cuda.backward_none_affine(
|
| 76 |
+
grad_output.contiguous(),
|
| 77 |
+
mean,
|
| 78 |
+
invvar,
|
| 79 |
+
input_,
|
| 80 |
+
ctx.normalized_shape,
|
| 81 |
+
ctx.eps,
|
| 82 |
+
)
|
| 83 |
+
)
|
| 84 |
+
else:
|
| 85 |
+
grad_input, grad_weight, grad_bias = (
|
| 86 |
+
fastfold_layer_norm_cuda.backward_with_bias_affine(
|
| 87 |
+
grad_output.contiguous(),
|
| 88 |
+
mean,
|
| 89 |
+
invvar,
|
| 90 |
+
input_,
|
| 91 |
+
ctx.normalized_shape,
|
| 92 |
+
bias_.to(dtype=d),
|
| 93 |
+
ctx.eps,
|
| 94 |
+
)
|
| 95 |
+
)
|
| 96 |
+
else:
|
| 97 |
+
if bias_ is None:
|
| 98 |
+
grad_input, grad_weight, grad_bias = (
|
| 99 |
+
fastfold_layer_norm_cuda.backward_with_weight_affine(
|
| 100 |
+
grad_output.contiguous(),
|
| 101 |
+
mean,
|
| 102 |
+
invvar,
|
| 103 |
+
input_,
|
| 104 |
+
ctx.normalized_shape,
|
| 105 |
+
weight_.to(dtype=d),
|
| 106 |
+
ctx.eps,
|
| 107 |
+
)
|
| 108 |
+
)
|
| 109 |
+
else:
|
| 110 |
+
grad_input, grad_weight, grad_bias = (
|
| 111 |
+
fastfold_layer_norm_cuda.backward_with_both_affine(
|
| 112 |
+
grad_output.contiguous(),
|
| 113 |
+
mean,
|
| 114 |
+
invvar,
|
| 115 |
+
input_,
|
| 116 |
+
ctx.normalized_shape,
|
| 117 |
+
weight_.to(dtype=d),
|
| 118 |
+
bias_.to(dtype=d),
|
| 119 |
+
ctx.eps,
|
| 120 |
+
)
|
| 121 |
+
)
|
| 122 |
+
return (
|
| 123 |
+
grad_input,
|
| 124 |
+
None if weight_ is None else grad_weight,
|
| 125 |
+
None if bias_ is None else grad_bias,
|
| 126 |
+
None,
|
| 127 |
+
None,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class FusedLayerNorm(torch.nn.Module):
|
| 132 |
+
|
| 133 |
+
def __init__(
|
| 134 |
+
self,
|
| 135 |
+
normalized_shape,
|
| 136 |
+
create_scale=True,
|
| 137 |
+
create_offset=True,
|
| 138 |
+
eps=1e-5,
|
| 139 |
+
):
|
| 140 |
+
"""
|
| 141 |
+
Args:
|
| 142 |
+
normalized_shape (int or list or torch.Size) input shape from an expected input of size
|
| 143 |
+
create_scale (bool) If set to False, the layer will not learn an additive weight, Default: True
|
| 144 |
+
create_offset (bool) If set to False, the layer will not learn an additive bias, Default: True
|
| 145 |
+
eps (float) a value added to the denominator for numerical stability. Default: 1e-5
|
| 146 |
+
"""
|
| 147 |
+
super(FusedLayerNorm, self).__init__()
|
| 148 |
+
|
| 149 |
+
if isinstance(normalized_shape, numbers.Integral):
|
| 150 |
+
normalized_shape = (normalized_shape,)
|
| 151 |
+
self.normalized_shape = torch.Size(normalized_shape)
|
| 152 |
+
self.eps = eps
|
| 153 |
+
if create_scale:
|
| 154 |
+
self.weight = Parameter(torch.ones(*normalized_shape))
|
| 155 |
+
else:
|
| 156 |
+
self.weight = None
|
| 157 |
+
|
| 158 |
+
if create_offset:
|
| 159 |
+
self.bias = Parameter(torch.zeros(*normalized_shape))
|
| 160 |
+
else:
|
| 161 |
+
self.bias = None
|
| 162 |
+
|
| 163 |
+
self.reset_parameters()
|
| 164 |
+
|
| 165 |
+
def reset_parameters(self):
|
| 166 |
+
if self.weight is not None:
|
| 167 |
+
torch.nn.init.ones_(self.weight)
|
| 168 |
+
if self.bias is not None:
|
| 169 |
+
torch.nn.init.zeros_(self.bias)
|
| 170 |
+
|
| 171 |
+
def forward(self, input):
|
| 172 |
+
return FusedLayerNormAffineFunction.apply(
|
| 173 |
+
input, self.weight, self.bias, self.normalized_shape, self.eps
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
if __name__ == "__main__":
|
| 178 |
+
dtype = torch.float32
|
| 179 |
+
data = torch.rand(10, 10).cuda().to(dtype=dtype)
|
| 180 |
+
data1 = data * 1
|
| 181 |
+
data.requires_grad = True
|
| 182 |
+
data1.requires_grad = True
|
| 183 |
+
layer_norm = (
|
| 184 |
+
FusedLayerNorm(10, create_scale=True, create_offset=True).cuda().to(dtype=dtype)
|
| 185 |
+
)
|
| 186 |
+
layer_norm_torch = torch.nn.LayerNorm(10).cuda().to(dtype=dtype)
|
| 187 |
+
out = layer_norm(data)
|
| 188 |
+
out1 = layer_norm_torch(data1)
|
| 189 |
+
# print(out - out1)
|
| 190 |
+
loss = out.sum()
|
| 191 |
+
loss.backward()
|
| 192 |
+
loss1 = out1.sum()
|
| 193 |
+
loss1.backward()
|
| 194 |
+
print(data.grad - data1.grad)
|
| 195 |
+
print(layer_norm.weight.grad - layer_norm_torch.weight.grad)
|
| 196 |
+
print(layer_norm.bias.grad - layer_norm_torch.bias.grad)
|
| 197 |
+
print(layer_norm.weight.grad, layer_norm.bias.grad)
|
| 198 |
+
|
model/protenix/layer_norm/torch_ext_compile.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from torch.utils.cpp_extension import load
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def compile(name, sources, extra_include_paths, build_directory):
|
| 7 |
+
os.environ["TORCH_CUDA_ARCH_LIST"] = "7.0;8.0"
|
| 8 |
+
return load(
|
| 9 |
+
name=name,
|
| 10 |
+
sources=sources,
|
| 11 |
+
extra_include_paths=extra_include_paths,
|
| 12 |
+
extra_cflags=[
|
| 13 |
+
"-O3",
|
| 14 |
+
"-DVERSION_GE_1_1",
|
| 15 |
+
"-DVERSION_GE_1_3",
|
| 16 |
+
"-DVERSION_GE_1_5",
|
| 17 |
+
],
|
| 18 |
+
extra_cuda_cflags=[
|
| 19 |
+
"-O3",
|
| 20 |
+
"--use_fast_math",
|
| 21 |
+
"-DVERSION_GE_1_1",
|
| 22 |
+
"-DVERSION_GE_1_3",
|
| 23 |
+
"-DVERSION_GE_1_5",
|
| 24 |
+
"-std=c++17",
|
| 25 |
+
"-maxrregcount=50",
|
| 26 |
+
"-U__CUDA_NO_HALF_OPERATORS__",
|
| 27 |
+
"-U__CUDA_NO_HALF_CONVERSIONS__",
|
| 28 |
+
"--expt-relaxed-constexpr",
|
| 29 |
+
"--expt-extended-lambda",
|
| 30 |
+
"-gencode",
|
| 31 |
+
"arch=compute_70,code=sm_70",
|
| 32 |
+
"-gencode",
|
| 33 |
+
"arch=compute_80,code=sm_80",
|
| 34 |
+
"-gencode",
|
| 35 |
+
"arch=compute_86,code=sm_86",
|
| 36 |
+
"-gencode",
|
| 37 |
+
"arch=compute_90,code=sm_90",
|
| 38 |
+
],
|
| 39 |
+
verbose=True,
|
| 40 |
+
build_directory=build_directory,
|
| 41 |
+
)
|
scripts/check_import_boundaries.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 7 |
+
MODEL_ROOT = PROJECT_ROOT / "model"
|
| 8 |
+
SCRIPT_ROOT = PROJECT_ROOT / "scripts"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _python_files(root: Path):
|
| 12 |
+
return [path for path in root.rglob("*.py") if "__pycache__" not in path.parts]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _check_no_onescience_models_imports():
|
| 16 |
+
offenders = []
|
| 17 |
+
for path in _python_files(MODEL_ROOT):
|
| 18 |
+
text = path.read_text(encoding="utf-8")
|
| 19 |
+
if "onescience.models." in text:
|
| 20 |
+
offenders.append(str(path.relative_to(PROJECT_ROOT)))
|
| 21 |
+
return offenders
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _check_no_legacy_imports():
|
| 25 |
+
pattern = re.compile(
|
| 26 |
+
r"^\s*(from\s+(esm|openfold)(\.|\s)|import\s+(esm|openfold)(\.|\s|$))",
|
| 27 |
+
re.MULTILINE,
|
| 28 |
+
)
|
| 29 |
+
offenders = []
|
| 30 |
+
for root in (MODEL_ROOT, SCRIPT_ROOT):
|
| 31 |
+
for path in _python_files(root):
|
| 32 |
+
text = path.read_text(encoding="utf-8")
|
| 33 |
+
if pattern.search(text):
|
| 34 |
+
offenders.append(str(path.relative_to(PROJECT_ROOT)))
|
| 35 |
+
return offenders
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _check_script_bootstrap():
|
| 39 |
+
offenders = []
|
| 40 |
+
for path in _python_files(SCRIPT_ROOT):
|
| 41 |
+
text = path.read_text(encoding="utf-8")
|
| 42 |
+
if "model.esm" in text and '_PROJECT_ROOT / "model"' not in text:
|
| 43 |
+
offenders.append(str(path.relative_to(PROJECT_ROOT)))
|
| 44 |
+
return offenders
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main():
|
| 48 |
+
checks = {
|
| 49 |
+
"onescience.models imports": _check_no_onescience_models_imports(),
|
| 50 |
+
"legacy esm/openfold imports": _check_no_legacy_imports(),
|
| 51 |
+
"script project-root bootstrap": _check_script_bootstrap(),
|
| 52 |
+
}
|
| 53 |
+
failed = {name: offenders for name, offenders in checks.items() if offenders}
|
| 54 |
+
if failed:
|
| 55 |
+
for name, offenders in failed.items():
|
| 56 |
+
print(f"{name}:")
|
| 57 |
+
for offender in offenders:
|
| 58 |
+
print(f" {offender}")
|
| 59 |
+
return 1
|
| 60 |
+
|
| 61 |
+
print("Import boundary checks passed")
|
| 62 |
+
return 0
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
if __name__ == "__main__":
|
| 66 |
+
sys.exit(main())
|
| 67 |
+
|
scripts/download_weights.sh
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 3 |
+
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# Usage: bash scripts/download_weights.sh /path/to/weights/
|
| 8 |
+
# Re-run the command to continue downloading incomplete files.
|
| 9 |
+
echo "$0"
|
| 10 |
+
run_dir=$(readlink -f "$(dirname "$0")") ;
|
| 11 |
+
|
| 12 |
+
if [[ "$(which aria2c)" == "" ]]; then
|
| 13 |
+
echo "aria2c is required for downloading!"
|
| 14 |
+
exit 1
|
| 15 |
+
fi
|
| 16 |
+
|
| 17 |
+
for _sh_exec in /bin/sh bash zsh; do
|
| 18 |
+
# Only bash and zsh are tested.
|
| 19 |
+
_sh_exec=$(which ${_sh_exec})
|
| 20 |
+
if [[ "$(${_sh_exec} --version)" =~ "bash" || "$(${_sh_exec} --version)" =~ "zsh" ]]; then
|
| 21 |
+
echo "$(which ${_sh_exec})";
|
| 22 |
+
break
|
| 23 |
+
fi
|
| 24 |
+
done
|
| 25 |
+
|
| 26 |
+
model_pth=$1
|
| 27 |
+
if [[ "$model_pth" == "" ]]; then
|
| 28 |
+
model_pth=$PWD
|
| 29 |
+
fi
|
| 30 |
+
|
| 31 |
+
mkdir -p "$model_pth/checkpoints"
|
| 32 |
+
|
| 33 |
+
pushd "$model_pth/checkpoints"
|
| 34 |
+
cat "$run_dir/../docs/UPSTREAM_README.md" | grep -e '^|' | grep -e 'fair-esm/models' | tr -d '|' | \
|
| 35 |
+
awk 'BEGIN{print "set -e"};
|
| 36 |
+
{
|
| 37 |
+
# read urls starts with https
|
| 38 |
+
split($0,arr,"https");
|
| 39 |
+
url="https"arr[2];
|
| 40 |
+
|
| 41 |
+
# remove blank spaces after url string
|
| 42 |
+
split(url,url_arr," ")
|
| 43 |
+
url=url_arr[1]
|
| 44 |
+
|
| 45 |
+
# guessing regression pt url
|
| 46 |
+
url_regression=url;
|
| 47 |
+
sub("models","regression",url_regression);
|
| 48 |
+
sub(".pt","-contact-regression.pt",url_regression);
|
| 49 |
+
|
| 50 |
+
# downloading weight
|
| 51 |
+
url_basename_idx=split(url,url_arr,"/")
|
| 52 |
+
url_basename=url_arr[url_basename_idx]
|
| 53 |
+
print "if [[ ! -f "url_basename" || -f "url_basename".aria2 ]];then echo Download not complete: "url_basename";aria2c -x 10 "url";else echo Download complete: "url_basename";fi"
|
| 54 |
+
|
| 55 |
+
# downloading regression, if not existing and through an error, we just ignore it.
|
| 56 |
+
url_regression_basename_idx=split(url_regression,url_arr,"/")
|
| 57 |
+
url_regression_basename=url_arr[url_regression_basename_idx]
|
| 58 |
+
print "if [[ ! -f "url_regression_basename" || -f "url_regression_basename".aria2 ]];then echo Download not complete: "url_regression_basename";aria2c -x 10 "url_regression" 2>/dev/null || echo Never mind. "url_regression_basename" may not exist. ;else echo Download complete: "url_regression_basename";fi"
|
| 59 |
+
|
| 60 |
+
}' | $_sh_exec
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
echo "Your model directory is located at \`$(readlink -f "${model_pth}")\`."
|
| 64 |
+
|
| 65 |
+
popd
|
scripts/esm2_infer_fairscale_fsdp_cpu_offloading.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
_PROJECT_FILE = Path(__file__).resolve()
|
| 5 |
+
for _PROJECT_ROOT in _PROJECT_FILE.parents:
|
| 6 |
+
if (_PROJECT_ROOT / "model").is_dir():
|
| 7 |
+
if str(_PROJECT_ROOT) not in sys.path:
|
| 8 |
+
sys.path.insert(0, str(_PROJECT_ROOT))
|
| 9 |
+
break
|
| 10 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 11 |
+
|
| 12 |
+
# This source code is licensed under the MIT license found in the
|
| 13 |
+
# LICENSE file in the root directory of this source tree.
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from fairscale.nn.data_parallel import FullyShardedDataParallel as FSDP
|
| 17 |
+
from fairscale.nn.wrap import enable_wrap, wrap
|
| 18 |
+
|
| 19 |
+
import model.esm as esm
|
| 20 |
+
|
| 21 |
+
# init the distributed world with world_size 1
|
| 22 |
+
url = "tcp://localhost:23456"
|
| 23 |
+
torch.distributed.init_process_group(backend="nccl", init_method=url, world_size=1, rank=0)
|
| 24 |
+
|
| 25 |
+
# download model data from the hub
|
| 26 |
+
model_name = "esm2_t48_15B_UR50D"
|
| 27 |
+
model_data, regression_data = esm.pretrained._download_model_and_regression_data(model_name)
|
| 28 |
+
|
| 29 |
+
# initialize the model with FSDP wrapper
|
| 30 |
+
fsdp_params = dict(
|
| 31 |
+
mixed_precision=True,
|
| 32 |
+
flatten_parameters=True,
|
| 33 |
+
state_dict_device=torch.device("cpu"), # reduce GPU mem usage
|
| 34 |
+
cpu_offload=True, # enable cpu offloading
|
| 35 |
+
)
|
| 36 |
+
with enable_wrap(wrapper_cls=FSDP, **fsdp_params):
|
| 37 |
+
model, vocab = esm.pretrained.load_model_and_alphabet_core(
|
| 38 |
+
model_name, model_data, regression_data
|
| 39 |
+
)
|
| 40 |
+
batch_converter = vocab.get_batch_converter()
|
| 41 |
+
model.eval()
|
| 42 |
+
|
| 43 |
+
# Wrap each layer in FSDP separately
|
| 44 |
+
for name, child in model.named_children():
|
| 45 |
+
if name == "layers":
|
| 46 |
+
for layer_name, layer in child.named_children():
|
| 47 |
+
wrapped_layer = wrap(layer)
|
| 48 |
+
setattr(child, layer_name, wrapped_layer)
|
| 49 |
+
model = wrap(model)
|
| 50 |
+
|
| 51 |
+
data = [
|
| 52 |
+
("protein1", "MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLAGG"),
|
| 53 |
+
("protein2", "KALTARQQEVFDLIRDHISQTGMPPTRAEIAQRLGFRSPNAAEEHLKALARKGVIEIVSGASRGIRLLQEE"),
|
| 54 |
+
(
|
| 55 |
+
"protein2 with mask",
|
| 56 |
+
"KALTARQQEVFDLIRD<mask>ISQTGMPPTRAEIAQRLGFRSPNAAEEHLKALARKGVIEIVSGASRGIRLLQEE",
|
| 57 |
+
),
|
| 58 |
+
("protein3", "K A <mask> I S Q"),
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
batch_labels, batch_strs, batch_tokens = batch_converter(data)
|
| 62 |
+
batch_tokens = batch_tokens.cuda()
|
| 63 |
+
with torch.no_grad():
|
| 64 |
+
results = model(batch_tokens, repr_layers=[48], return_contacts=True)
|
| 65 |
+
print(results)
|
scripts/extract.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3 -u
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
_PROJECT_FILE = Path(__file__).resolve()
|
| 6 |
+
for _PROJECT_ROOT in _PROJECT_FILE.parents:
|
| 7 |
+
if (_PROJECT_ROOT / "model").is_dir():
|
| 8 |
+
if str(_PROJECT_ROOT) not in sys.path:
|
| 9 |
+
sys.path.insert(0, str(_PROJECT_ROOT))
|
| 10 |
+
break
|
| 11 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 12 |
+
#
|
| 13 |
+
# This source code is licensed under the MIT license found in the
|
| 14 |
+
# LICENSE file in the root directory of this source tree.
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import pathlib
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from model.esm import Alphabet, FastaBatchedDataset, ProteinBertModel, pretrained, MSATransformer
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def create_parser():
|
| 25 |
+
parser = argparse.ArgumentParser(
|
| 26 |
+
description="Extract per-token representations and model outputs for sequences in a FASTA file" # noqa
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"model_location",
|
| 31 |
+
type=str,
|
| 32 |
+
help="PyTorch model file OR name of pretrained model to download (see README for models)",
|
| 33 |
+
)
|
| 34 |
+
parser.add_argument(
|
| 35 |
+
"fasta_file",
|
| 36 |
+
type=pathlib.Path,
|
| 37 |
+
help="FASTA file on which to extract representations",
|
| 38 |
+
)
|
| 39 |
+
parser.add_argument(
|
| 40 |
+
"output_dir",
|
| 41 |
+
type=pathlib.Path,
|
| 42 |
+
help="output directory for extracted representations",
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
parser.add_argument("--toks_per_batch", type=int, default=4096, help="maximum batch size")
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--repr_layers",
|
| 48 |
+
type=int,
|
| 49 |
+
default=[-1],
|
| 50 |
+
nargs="+",
|
| 51 |
+
help="layers indices from which to extract representations (0 to num_layers, inclusive)",
|
| 52 |
+
)
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
"--include",
|
| 55 |
+
type=str,
|
| 56 |
+
nargs="+",
|
| 57 |
+
choices=["mean", "per_tok", "bos", "contacts"],
|
| 58 |
+
help="specify which representations to return",
|
| 59 |
+
required=True,
|
| 60 |
+
)
|
| 61 |
+
parser.add_argument(
|
| 62 |
+
"--truncation_seq_length",
|
| 63 |
+
type=int,
|
| 64 |
+
default=1022,
|
| 65 |
+
help="truncate sequences longer than the given value",
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
parser.add_argument("--nogpu", action="store_true", help="Do not use GPU even if available")
|
| 69 |
+
return parser
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def run(args):
|
| 73 |
+
model, alphabet = pretrained.load_model_and_alphabet(args.model_location)
|
| 74 |
+
model.eval()
|
| 75 |
+
if isinstance(model, MSATransformer):
|
| 76 |
+
raise ValueError(
|
| 77 |
+
"This script currently does not handle models with MSA input (MSA Transformer)."
|
| 78 |
+
)
|
| 79 |
+
if torch.cuda.is_available() and not args.nogpu:
|
| 80 |
+
model = model.cuda()
|
| 81 |
+
print("Transferred model to GPU")
|
| 82 |
+
|
| 83 |
+
dataset = FastaBatchedDataset.from_file(args.fasta_file)
|
| 84 |
+
batches = dataset.get_batch_indices(args.toks_per_batch, extra_toks_per_seq=1)
|
| 85 |
+
data_loader = torch.utils.data.DataLoader(
|
| 86 |
+
dataset, collate_fn=alphabet.get_batch_converter(args.truncation_seq_length), batch_sampler=batches
|
| 87 |
+
)
|
| 88 |
+
print(f"Read {args.fasta_file} with {len(dataset)} sequences")
|
| 89 |
+
|
| 90 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 91 |
+
return_contacts = "contacts" in args.include
|
| 92 |
+
|
| 93 |
+
assert all(-(model.num_layers + 1) <= i <= model.num_layers for i in args.repr_layers)
|
| 94 |
+
repr_layers = [(i + model.num_layers + 1) % (model.num_layers + 1) for i in args.repr_layers]
|
| 95 |
+
|
| 96 |
+
with torch.no_grad():
|
| 97 |
+
for batch_idx, (labels, strs, toks) in enumerate(data_loader):
|
| 98 |
+
print(
|
| 99 |
+
f"Processing {batch_idx + 1} of {len(batches)} batches ({toks.size(0)} sequences)"
|
| 100 |
+
)
|
| 101 |
+
if torch.cuda.is_available() and not args.nogpu:
|
| 102 |
+
toks = toks.to(device="cuda", non_blocking=True)
|
| 103 |
+
|
| 104 |
+
out = model(toks, repr_layers=repr_layers, return_contacts=return_contacts)
|
| 105 |
+
|
| 106 |
+
logits = out["logits"].to(device="cpu")
|
| 107 |
+
representations = {
|
| 108 |
+
layer: t.to(device="cpu") for layer, t in out["representations"].items()
|
| 109 |
+
}
|
| 110 |
+
if return_contacts:
|
| 111 |
+
contacts = out["contacts"].to(device="cpu")
|
| 112 |
+
|
| 113 |
+
for i, label in enumerate(labels):
|
| 114 |
+
args.output_file = args.output_dir / f"{label}.pt"
|
| 115 |
+
args.output_file.parent.mkdir(parents=True, exist_ok=True)
|
| 116 |
+
result = {"label": label}
|
| 117 |
+
truncate_len = min(args.truncation_seq_length, len(strs[i]))
|
| 118 |
+
# Call clone on tensors to ensure tensors are not views into a larger representation
|
| 119 |
+
# See https://github.com/pytorch/pytorch/issues/1995
|
| 120 |
+
if "per_tok" in args.include:
|
| 121 |
+
result["representations"] = {
|
| 122 |
+
layer: t[i, 1 : truncate_len + 1].clone()
|
| 123 |
+
for layer, t in representations.items()
|
| 124 |
+
}
|
| 125 |
+
if "mean" in args.include:
|
| 126 |
+
result["mean_representations"] = {
|
| 127 |
+
layer: t[i, 1 : truncate_len + 1].mean(0).clone()
|
| 128 |
+
for layer, t in representations.items()
|
| 129 |
+
}
|
| 130 |
+
if "bos" in args.include:
|
| 131 |
+
result["bos_representations"] = {
|
| 132 |
+
layer: t[i, 0].clone() for layer, t in representations.items()
|
| 133 |
+
}
|
| 134 |
+
if return_contacts:
|
| 135 |
+
result["contacts"] = contacts[i, : truncate_len, : truncate_len].clone()
|
| 136 |
+
|
| 137 |
+
torch.save(
|
| 138 |
+
result,
|
| 139 |
+
args.output_file,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def main():
|
| 144 |
+
parser = create_parser()
|
| 145 |
+
args = parser.parse_args()
|
| 146 |
+
run(args)
|
| 147 |
+
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
main()
|
scripts/fold.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
_PROJECT_FILE = Path(__file__).resolve()
|
| 5 |
+
for _PROJECT_ROOT in _PROJECT_FILE.parents:
|
| 6 |
+
if (_PROJECT_ROOT / "model").is_dir():
|
| 7 |
+
if str(_PROJECT_ROOT) not in sys.path:
|
| 8 |
+
sys.path.insert(0, str(_PROJECT_ROOT))
|
| 9 |
+
break
|
| 10 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 11 |
+
|
| 12 |
+
# This source code is licensed under the MIT license found in the
|
| 13 |
+
# LICENSE file in the root directory of this source tree.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
import sys,os
|
| 18 |
+
import argparse
|
| 19 |
+
import logging
|
| 20 |
+
import sys
|
| 21 |
+
import typing as T
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from timeit import default_timer as timer
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
import model.esm as esm
|
| 28 |
+
from onescience.datapipes.esm import read_fasta
|
| 29 |
+
|
| 30 |
+
logger = logging.getLogger()
|
| 31 |
+
logger.setLevel(logging.INFO)
|
| 32 |
+
|
| 33 |
+
formatter = logging.Formatter(
|
| 34 |
+
"%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
| 35 |
+
datefmt="%y/%m/%d %H:%M:%S",
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
console_handler = logging.StreamHandler(sys.stdout)
|
| 39 |
+
console_handler.setLevel(logging.INFO)
|
| 40 |
+
console_handler.setFormatter(formatter)
|
| 41 |
+
logger.addHandler(console_handler)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
PathLike = T.Union[str, Path]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def enable_cpu_offloading(model):
|
| 48 |
+
from torch.distributed.fsdp import CPUOffload, FullyShardedDataParallel
|
| 49 |
+
from torch.distributed.fsdp.wrap import enable_wrap, wrap
|
| 50 |
+
|
| 51 |
+
torch.distributed.init_process_group(
|
| 52 |
+
backend="nccl", init_method="tcp://localhost:9999", world_size=1, rank=0
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
wrapper_kwargs = dict(cpu_offload=CPUOffload(offload_params=True))
|
| 56 |
+
|
| 57 |
+
with enable_wrap(wrapper_cls=FullyShardedDataParallel, **wrapper_kwargs):
|
| 58 |
+
for layer_name, layer in model.layers.named_children():
|
| 59 |
+
wrapped_layer = wrap(layer)
|
| 60 |
+
setattr(model.layers, layer_name, wrapped_layer)
|
| 61 |
+
model = wrap(model)
|
| 62 |
+
|
| 63 |
+
return model
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def init_model_on_gpu_with_cpu_offloading(model):
|
| 67 |
+
model = model.eval()
|
| 68 |
+
model_esm = enable_cpu_offloading(model.esm)
|
| 69 |
+
del model.esm
|
| 70 |
+
model.cuda()
|
| 71 |
+
model.esm = model_esm
|
| 72 |
+
return model
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def create_batched_sequence_datasest(
|
| 76 |
+
sequences: T.List[T.Tuple[str, str]], max_tokens_per_batch: int = 1024
|
| 77 |
+
) -> T.Generator[T.Tuple[T.List[str], T.List[str]], None, None]:
|
| 78 |
+
|
| 79 |
+
batch_headers, batch_sequences, num_tokens = [], [], 0
|
| 80 |
+
for header, seq in sequences:
|
| 81 |
+
if (len(seq) + num_tokens > max_tokens_per_batch) and num_tokens > 0:
|
| 82 |
+
yield batch_headers, batch_sequences
|
| 83 |
+
batch_headers, batch_sequences, num_tokens = [], [], 0
|
| 84 |
+
batch_headers.append(header)
|
| 85 |
+
batch_sequences.append(seq)
|
| 86 |
+
num_tokens += len(seq)
|
| 87 |
+
|
| 88 |
+
yield batch_headers, batch_sequences
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def create_parser():
|
| 92 |
+
parser = argparse.ArgumentParser()
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"-i",
|
| 95 |
+
"--fasta",
|
| 96 |
+
help="Path to input FASTA file",
|
| 97 |
+
type=Path,
|
| 98 |
+
required=True,
|
| 99 |
+
)
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"-o", "--pdb", help="Path to output PDB directory", type=Path, required=True
|
| 102 |
+
)
|
| 103 |
+
parser.add_argument(
|
| 104 |
+
"-m", "--model-dir", help="Parent path to Pretrained ESM data directory. ", type=Path, default=None
|
| 105 |
+
)
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
"--num-recycles",
|
| 108 |
+
type=int,
|
| 109 |
+
default=None,
|
| 110 |
+
help="Number of recycles to run. Defaults to number used in training (4).",
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--max-tokens-per-batch",
|
| 114 |
+
type=int,
|
| 115 |
+
default=1024,
|
| 116 |
+
help="Maximum number of tokens per gpu forward-pass. This will group shorter sequences together "
|
| 117 |
+
"for batched prediction. Lowering this can help with out of memory issues, if these occur on "
|
| 118 |
+
"short sequences.",
|
| 119 |
+
)
|
| 120 |
+
parser.add_argument(
|
| 121 |
+
"--chunk-size",
|
| 122 |
+
type=int,
|
| 123 |
+
default=None,
|
| 124 |
+
help="Chunks axial attention computation to reduce memory usage from O(L^2) to O(L). "
|
| 125 |
+
"Equivalent to running a for loop over chunks of of each dimension. Lower values will "
|
| 126 |
+
"result in lower memory usage at the cost of speed. Recommended values: 128, 64, 32. "
|
| 127 |
+
"Default: None.",
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument("--cpu-only", help="CPU only", action="store_true")
|
| 130 |
+
parser.add_argument("--cpu-offload", help="Enable CPU offloading", action="store_true")
|
| 131 |
+
return parser
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def run(args):
|
| 135 |
+
if not args.fasta.exists():
|
| 136 |
+
raise FileNotFoundError(args.fasta)
|
| 137 |
+
|
| 138 |
+
args.pdb.mkdir(exist_ok=True)
|
| 139 |
+
|
| 140 |
+
# Read fasta and sort sequences by length
|
| 141 |
+
logger.info(f"Reading sequences from {args.fasta}")
|
| 142 |
+
all_sequences = sorted(read_fasta(args.fasta), key=lambda header_seq: len(header_seq[1]))
|
| 143 |
+
logger.info(f"Loaded {len(all_sequences)} sequences from {args.fasta}")
|
| 144 |
+
|
| 145 |
+
logger.info("Loading model")
|
| 146 |
+
|
| 147 |
+
# Use pre-downloaded ESM weights from model_pth.
|
| 148 |
+
if args.model_dir is not None:
|
| 149 |
+
# if pretrained model path is available
|
| 150 |
+
torch.hub.set_dir(args.model_dir)
|
| 151 |
+
|
| 152 |
+
model = esm.pretrained.esmfold_v1()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
model = model.eval()
|
| 156 |
+
model.set_chunk_size(args.chunk_size)
|
| 157 |
+
|
| 158 |
+
if args.cpu_only:
|
| 159 |
+
model.esm.float() # convert to fp32 as ESM-2 in fp16 is not supported on CPU
|
| 160 |
+
model.cpu()
|
| 161 |
+
elif args.cpu_offload:
|
| 162 |
+
model = init_model_on_gpu_with_cpu_offloading(model)
|
| 163 |
+
else:
|
| 164 |
+
model.cuda()
|
| 165 |
+
logger.info("Starting Predictions")
|
| 166 |
+
batched_sequences = create_batched_sequence_datasest(all_sequences, args.max_tokens_per_batch)
|
| 167 |
+
|
| 168 |
+
num_completed = 0
|
| 169 |
+
num_sequences = len(all_sequences)
|
| 170 |
+
for headers, sequences in batched_sequences:
|
| 171 |
+
start = timer()
|
| 172 |
+
try:
|
| 173 |
+
output = model.infer(sequences, num_recycles=args.num_recycles)
|
| 174 |
+
except RuntimeError as e:
|
| 175 |
+
if e.args[0].startswith("CUDA out of memory"):
|
| 176 |
+
if len(sequences) > 1:
|
| 177 |
+
logger.info(
|
| 178 |
+
f"Failed (CUDA out of memory) to predict batch of size {len(sequences)}. "
|
| 179 |
+
"Try lowering `--max-tokens-per-batch`."
|
| 180 |
+
)
|
| 181 |
+
else:
|
| 182 |
+
logger.info(
|
| 183 |
+
f"Failed (CUDA out of memory) on sequence {headers[0]} of length {len(sequences[0])}."
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
continue
|
| 187 |
+
raise
|
| 188 |
+
|
| 189 |
+
output = {key: value.cpu() for key, value in output.items()}
|
| 190 |
+
pdbs = model.output_to_pdb(output)
|
| 191 |
+
tottime = timer() - start
|
| 192 |
+
time_string = f"{tottime / len(headers):0.1f}s"
|
| 193 |
+
if len(sequences) > 1:
|
| 194 |
+
time_string = time_string + f" (amortized, batch size {len(sequences)})"
|
| 195 |
+
for header, seq, pdb_string, mean_plddt, ptm in zip(
|
| 196 |
+
headers, sequences, pdbs, output["mean_plddt"], output["ptm"]
|
| 197 |
+
):
|
| 198 |
+
output_file = args.pdb / f"{header}.pdb"
|
| 199 |
+
output_file.write_text(pdb_string)
|
| 200 |
+
num_completed += 1
|
| 201 |
+
logger.info(
|
| 202 |
+
f"Predicted structure for {header} with length {len(seq)}, pLDDT {mean_plddt:0.1f}, "
|
| 203 |
+
f"pTM {ptm:0.3f} in {time_string}. "
|
| 204 |
+
f"{num_completed} / {num_sequences} completed."
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def main():
|
| 209 |
+
parser = create_parser()
|
| 210 |
+
args = parser.parse_args()
|
| 211 |
+
run(args)
|
| 212 |
+
|
| 213 |
+
if __name__ == "__main__":
|
| 214 |
+
main()
|
scripts/infer.sh
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 5 |
+
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
| 6 |
+
cd "${PROJECT_ROOT}"
|
| 7 |
+
|
| 8 |
+
ESM_WEIGHT_DIR="${ESM_WEIGHT_DIR:-${PROJECT_ROOT}/weight}"
|
| 9 |
+
ESM_OUTPUT_DIR="${ESM_OUTPUT_DIR:-${PROJECT_ROOT}/outputs}"
|
| 10 |
+
ESM_FASTA="${ESM_FASTA:-${PROJECT_ROOT}/data/fasta/few_proteins.fasta}"
|
| 11 |
+
ESM2_8M_WEIGHT="${ESM2_8M_WEIGHT:-${ESM_WEIGHT_DIR}/esm2_t6_8M_UR50D.pt}"
|
| 12 |
+
|
| 13 |
+
mkdir -p "${ESM_OUTPUT_DIR}"
|
| 14 |
+
|
| 15 |
+
if [[ ! -f "${ESM2_8M_WEIGHT}" ]]; then
|
| 16 |
+
echo "Missing ${ESM2_8M_WEIGHT}"
|
| 17 |
+
echo "Run: bash scripts/download_weights.sh ${ESM_WEIGHT_DIR}"
|
| 18 |
+
exit 1
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
python scripts/extract.py \
|
| 22 |
+
"${ESM2_8M_WEIGHT}" \
|
| 23 |
+
"${ESM_FASTA}" \
|
| 24 |
+
"${ESM_OUTPUT_DIR}/embeddings" \
|
| 25 |
+
--include mean per_tok \
|
| 26 |
+
--repr_layers 6
|
| 27 |
+
|
| 28 |
+
if [[ "${RUN_ESMFOLD:-0}" == "1" ]]; then
|
| 29 |
+
python scripts/fold.py \
|
| 30 |
+
-i "${ESM_FASTA}" \
|
| 31 |
+
-o "${ESM_OUTPUT_DIR}/pdb" \
|
| 32 |
+
--model-dir "${ESM_WEIGHT_DIR}" \
|
| 33 |
+
--cpu-only
|
| 34 |
+
fi
|
| 35 |
+
|
| 36 |
+
if [[ "${RUN_VARIANT_PREDICTION:-0}" == "1" ]]; then
|
| 37 |
+
python scripts/variant_prediction/predict.py \
|
| 38 |
+
--model-location "${ESM_WEIGHT_DIR}/esm1v_t33_650M_UR90S_1.pt" \
|
| 39 |
+
--sequence "${ESM_VARIANT_SEQUENCE:?Set ESM_VARIANT_SEQUENCE}" \
|
| 40 |
+
--dms-input data/variant_prediction/BLAT_ECOLX_Ranganathan2015.csv \
|
| 41 |
+
--mutation-col mutant \
|
| 42 |
+
--dms-output "${ESM_OUTPUT_DIR}/variant_prediction.csv" \
|
| 43 |
+
--offset-idx 24 \
|
| 44 |
+
--scoring-strategy wt-marginals
|
| 45 |
+
fi
|
scripts/inverse_folding/sample_sequences.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
_PROJECT_FILE = Path(__file__).resolve()
|
| 5 |
+
for _PROJECT_ROOT in _PROJECT_FILE.parents:
|
| 6 |
+
if (_PROJECT_ROOT / "model").is_dir():
|
| 7 |
+
if str(_PROJECT_ROOT) not in sys.path:
|
| 8 |
+
sys.path.insert(0, str(_PROJECT_ROOT))
|
| 9 |
+
break
|
| 10 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 11 |
+
#
|
| 12 |
+
# This source code is licensed under the MIT license found in the
|
| 13 |
+
# LICENSE file in the root directory of this source tree.
|
| 14 |
+
#
|
| 15 |
+
# Sample sequences based on a given structure (multinomial sampling, no beam search).
|
| 16 |
+
#
|
| 17 |
+
# usage: sample_sequences.py [-h] [--chain CHAIN] [--temperature TEMPERATURE]
|
| 18 |
+
# [--outpath OUTPATH] [--num-samples NUM_SAMPLES] pdbfile
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import numpy as np
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
import model.esm as esm
|
| 26 |
+
import model.esm.inverse_folding
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def sample_seq_singlechain(model, alphabet, args):
|
| 30 |
+
if torch.cuda.is_available() and not args.nogpu:
|
| 31 |
+
model = model.cuda()
|
| 32 |
+
print("Transferred model to GPU")
|
| 33 |
+
device = next(model.parameters()).device
|
| 34 |
+
coords, native_seq = esm.inverse_folding.util.load_coords(args.pdbfile, args.chain)
|
| 35 |
+
print('Native sequence loaded from structure file:')
|
| 36 |
+
print(native_seq)
|
| 37 |
+
|
| 38 |
+
print(f'Saving sampled sequences to {args.outpath}.')
|
| 39 |
+
|
| 40 |
+
Path(args.outpath).parent.mkdir(parents=True, exist_ok=True)
|
| 41 |
+
with open(args.outpath, 'w') as f:
|
| 42 |
+
for i in range(args.num_samples):
|
| 43 |
+
print(f'\nSampling.. ({i+1} of {args.num_samples})')
|
| 44 |
+
sampled_seq = model.sample(coords, temperature=args.temperature, device=device)
|
| 45 |
+
print('Sampled sequence:')
|
| 46 |
+
print(sampled_seq)
|
| 47 |
+
f.write(f'>sampled_seq_{i+1}\n')
|
| 48 |
+
f.write(sampled_seq + '\n')
|
| 49 |
+
|
| 50 |
+
recovery = np.mean([(a==b) for a, b in zip(native_seq, sampled_seq)])
|
| 51 |
+
print('Sequence recovery:', recovery)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def sample_seq_multichain(model, alphabet, args):
|
| 55 |
+
if torch.cuda.is_available() and not args.nogpu:
|
| 56 |
+
model = model.cuda()
|
| 57 |
+
print("Transferred model to GPU")
|
| 58 |
+
structure = esm.inverse_folding.util.load_structure(args.pdbfile)
|
| 59 |
+
coords, native_seqs = esm.inverse_folding.multichain_util.extract_coords_from_complex(structure)
|
| 60 |
+
target_chain_id = args.chain
|
| 61 |
+
native_seq = native_seqs[target_chain_id]
|
| 62 |
+
print('Native sequence loaded from structure file:')
|
| 63 |
+
print(native_seq)
|
| 64 |
+
print('\n')
|
| 65 |
+
|
| 66 |
+
print(f'Saving sampled sequences to {args.outpath}.')
|
| 67 |
+
|
| 68 |
+
Path(args.outpath).parent.mkdir(parents=True, exist_ok=True)
|
| 69 |
+
with open(args.outpath, 'w') as f:
|
| 70 |
+
for i in range(args.num_samples):
|
| 71 |
+
print(f'\nSampling.. ({i+1} of {args.num_samples})')
|
| 72 |
+
sampled_seq = esm.inverse_folding.multichain_util.sample_sequence_in_complex(
|
| 73 |
+
model, coords, target_chain_id, temperature=args.temperature)
|
| 74 |
+
print('Sampled sequence:')
|
| 75 |
+
print(sampled_seq)
|
| 76 |
+
f.write(f'>sampled_seq_{i+1}\n')
|
| 77 |
+
f.write(sampled_seq + '\n')
|
| 78 |
+
|
| 79 |
+
recovery = np.mean([(a==b) for a, b in zip(native_seq, sampled_seq)])
|
| 80 |
+
print('Sequence recovery:', recovery)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def main():
|
| 84 |
+
parser = argparse.ArgumentParser(
|
| 85 |
+
description='Sample sequences based on a given structure.'
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
'pdbfile', type=str,
|
| 89 |
+
help='input filepath, either .pdb or .cif',
|
| 90 |
+
)
|
| 91 |
+
parser.add_argument(
|
| 92 |
+
'--chain', type=str,
|
| 93 |
+
help='chain id for the chain of interest', default=None,
|
| 94 |
+
)
|
| 95 |
+
parser.add_argument(
|
| 96 |
+
'--temperature', type=float,
|
| 97 |
+
help='temperature for sampling, higher for more diversity',
|
| 98 |
+
default=1.,
|
| 99 |
+
)
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
'--outpath', type=str,
|
| 102 |
+
help='output filepath for saving sampled sequences',
|
| 103 |
+
default='output/sampled_seqs.fasta',
|
| 104 |
+
)
|
| 105 |
+
parser.add_argument(
|
| 106 |
+
'--num-samples', type=int,
|
| 107 |
+
help='number of sequences to sample',
|
| 108 |
+
default=1,
|
| 109 |
+
)
|
| 110 |
+
parser.set_defaults(multichain_backbone=False)
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
'--multichain-backbone', action='store_true',
|
| 113 |
+
help='use the backbones of all chains in the input for conditioning'
|
| 114 |
+
)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
'--singlechain-backbone', dest='multichain_backbone',
|
| 117 |
+
action='store_false',
|
| 118 |
+
help='use the backbone of only target chain in the input for conditioning'
|
| 119 |
+
)
|
| 120 |
+
parser.add_argument("--nogpu", action="store_true", help="Do not use GPU even if available")
|
| 121 |
+
|
| 122 |
+
args = parser.parse_args()
|
| 123 |
+
|
| 124 |
+
model, alphabet = esm.pretrained.esm_if1_gvp4_t16_142M_UR50()
|
| 125 |
+
model = model.eval()
|
| 126 |
+
|
| 127 |
+
if args.multichain_backbone:
|
| 128 |
+
sample_seq_multichain(model, alphabet, args)
|
| 129 |
+
else:
|
| 130 |
+
sample_seq_singlechain(model, alphabet, args)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
if __name__ == '__main__':
|
| 134 |
+
main()
|
scripts/inverse_folding/score_log_likelihoods.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
_PROJECT_FILE = Path(__file__).resolve()
|
| 5 |
+
for _PROJECT_ROOT in _PROJECT_FILE.parents:
|
| 6 |
+
if (_PROJECT_ROOT / "model").is_dir():
|
| 7 |
+
if str(_PROJECT_ROOT) not in sys.path:
|
| 8 |
+
sys.path.insert(0, str(_PROJECT_ROOT))
|
| 9 |
+
break
|
| 10 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 11 |
+
#
|
| 12 |
+
# This source code is licensed under the MIT license found in the
|
| 13 |
+
# LICENSE file in the root directory of this source tree.
|
| 14 |
+
#
|
| 15 |
+
# Scores sequences based on a given structure.
|
| 16 |
+
#
|
| 17 |
+
# usage:
|
| 18 |
+
# score_log_likelihoods.py [-h] [--outpath OUTPATH] [--chain CHAIN] pdbfile seqfile
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
from biotite.sequence.io.fasta import FastaFile, get_sequences
|
| 22 |
+
import numpy as np
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn.functional as F
|
| 26 |
+
from tqdm import tqdm
|
| 27 |
+
|
| 28 |
+
import model.esm as esm
|
| 29 |
+
import model.esm.inverse_folding
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def score_singlechain_backbone(model, alphabet, args):
|
| 33 |
+
if torch.cuda.is_available() and not args.nogpu:
|
| 34 |
+
model = model.cuda()
|
| 35 |
+
print("Transferred model to GPU")
|
| 36 |
+
coords, native_seq = esm.inverse_folding.util.load_coords(args.pdbfile, args.chain)
|
| 37 |
+
print('Native sequence loaded from structure file:')
|
| 38 |
+
print(native_seq)
|
| 39 |
+
print('\n')
|
| 40 |
+
|
| 41 |
+
ll, _ = esm.inverse_folding.util.score_sequence(
|
| 42 |
+
model, alphabet, coords, native_seq)
|
| 43 |
+
print('Native sequence')
|
| 44 |
+
print(f'Log likelihood: {ll:.2f}')
|
| 45 |
+
print(f'Perplexity: {np.exp(-ll):.2f}')
|
| 46 |
+
|
| 47 |
+
print('\nScoring variant sequences from sequence file..\n')
|
| 48 |
+
infile = FastaFile()
|
| 49 |
+
infile.read(args.seqfile)
|
| 50 |
+
seqs = get_sequences(infile)
|
| 51 |
+
Path(args.outpath).parent.mkdir(parents=True, exist_ok=True)
|
| 52 |
+
with open(args.outpath, 'w') as fout:
|
| 53 |
+
fout.write('seqid,log_likelihood\n')
|
| 54 |
+
for header, seq in tqdm(seqs.items()):
|
| 55 |
+
ll, _ = esm.inverse_folding.util.score_sequence(
|
| 56 |
+
model, alphabet, coords, str(seq))
|
| 57 |
+
fout.write(header + ',' + str(ll) + '\n')
|
| 58 |
+
print(f'Results saved to {args.outpath}')
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def score_multichain_backbone(model, alphabet, args):
|
| 62 |
+
if torch.cuda.is_available() and not args.nogpu:
|
| 63 |
+
model = model.cuda()
|
| 64 |
+
print("Transferred model to GPU")
|
| 65 |
+
structure = esm.inverse_folding.util.load_structure(args.pdbfile)
|
| 66 |
+
coords, native_seqs = esm.inverse_folding.multichain_util.extract_coords_from_complex(structure)
|
| 67 |
+
target_chain_id = args.chain
|
| 68 |
+
native_seq = native_seqs[target_chain_id]
|
| 69 |
+
print('Native sequence loaded from structure file:')
|
| 70 |
+
print(native_seq)
|
| 71 |
+
print('\n')
|
| 72 |
+
|
| 73 |
+
ll, _ = esm.inverse_folding.multichain_util.score_sequence_in_complex(
|
| 74 |
+
model, alphabet, coords, target_chain_id, native_seq)
|
| 75 |
+
print('Native sequence')
|
| 76 |
+
print(f'Log likelihood: {ll:.2f}')
|
| 77 |
+
print(f'Perplexity: {np.exp(-ll):.2f}')
|
| 78 |
+
|
| 79 |
+
print('\nScoring variant sequences from sequence file..\n')
|
| 80 |
+
infile = FastaFile()
|
| 81 |
+
infile.read(args.seqfile)
|
| 82 |
+
seqs = get_sequences(infile)
|
| 83 |
+
Path(args.outpath).parent.mkdir(parents=True, exist_ok=True)
|
| 84 |
+
with open(args.outpath, 'w') as fout:
|
| 85 |
+
fout.write('seqid,log_likelihood\n')
|
| 86 |
+
for header, seq in tqdm(seqs.items()):
|
| 87 |
+
ll, _ = esm.inverse_folding.multichain_util.score_sequence_in_complex(
|
| 88 |
+
model, alphabet, coords, target_chain_id, str(seq))
|
| 89 |
+
fout.write(header + ',' + str(ll) + '\n')
|
| 90 |
+
print(f'Results saved to {args.outpath}')
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def main():
|
| 94 |
+
parser = argparse.ArgumentParser(
|
| 95 |
+
description='Score sequences based on a given structure.'
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument(
|
| 98 |
+
'pdbfile', type=str,
|
| 99 |
+
help='input filepath, either .pdb or .cif',
|
| 100 |
+
)
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
'seqfile', type=str,
|
| 103 |
+
help='input filepath for variant sequences in a .fasta file',
|
| 104 |
+
)
|
| 105 |
+
parser.add_argument(
|
| 106 |
+
'--outpath', type=str,
|
| 107 |
+
help='output filepath for scores of variant sequences',
|
| 108 |
+
default='output/sequence_scores.csv',
|
| 109 |
+
)
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
'--chain', type=str,
|
| 112 |
+
help='chain id for the chain of interest', default='A',
|
| 113 |
+
)
|
| 114 |
+
parser.set_defaults(multichain_backbone=False)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
'--multichain-backbone', action='store_true',
|
| 117 |
+
help='use the backbones of all chains in the input for conditioning'
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
'--singlechain-backbone', dest='multichain_backbone',
|
| 121 |
+
action='store_false',
|
| 122 |
+
help='use the backbone of only target chain in the input for conditioning'
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
parser.add_argument("--nogpu", action="store_true", help="Do not use GPU even if available")
|
| 126 |
+
|
| 127 |
+
args = parser.parse_args()
|
| 128 |
+
|
| 129 |
+
model, alphabet = esm.pretrained.esm_if1_gvp4_t16_142M_UR50()
|
| 130 |
+
model = model.eval()
|
| 131 |
+
|
| 132 |
+
if args.multichain_backbone:
|
| 133 |
+
score_multichain_backbone(model, alphabet, args)
|
| 134 |
+
else:
|
| 135 |
+
score_singlechain_backbone(model, alphabet, args)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if __name__ == '__main__':
|
| 140 |
+
main()
|
scripts/variant_prediction/predict.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
_PROJECT_FILE = Path(__file__).resolve()
|
| 5 |
+
for _PROJECT_ROOT in _PROJECT_FILE.parents:
|
| 6 |
+
if (_PROJECT_ROOT / "model").is_dir():
|
| 7 |
+
if str(_PROJECT_ROOT) not in sys.path:
|
| 8 |
+
sys.path.insert(0, str(_PROJECT_ROOT))
|
| 9 |
+
break
|
| 10 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 11 |
+
#
|
| 12 |
+
# This source code is licensed under the MIT license found in the
|
| 13 |
+
# LICENSE file in the root directory of this source tree.
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import pathlib
|
| 17 |
+
import string
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from model.esm import Alphabet, FastaBatchedDataset, ProteinBertModel, pretrained, MSATransformer
|
| 22 |
+
import pandas as pd
|
| 23 |
+
from tqdm import tqdm
|
| 24 |
+
from Bio import SeqIO
|
| 25 |
+
import itertools
|
| 26 |
+
from typing import List, Tuple
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def remove_insertions(sequence: str) -> str:
|
| 31 |
+
""" Removes any insertions into the sequence. Needed to load aligned sequences in an MSA. """
|
| 32 |
+
# This is an efficient way to delete lowercase characters and insertion characters from a string
|
| 33 |
+
deletekeys = dict.fromkeys(string.ascii_lowercase)
|
| 34 |
+
deletekeys["."] = None
|
| 35 |
+
deletekeys["*"] = None
|
| 36 |
+
|
| 37 |
+
translation = str.maketrans(deletekeys)
|
| 38 |
+
return sequence.translate(translation)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def read_msa(filename: str, nseq: int) -> List[Tuple[str, str]]:
|
| 42 |
+
""" Reads the first nseq sequences from an MSA file, automatically removes insertions.
|
| 43 |
+
|
| 44 |
+
The input file must be in a3m format (although we use the SeqIO fasta parser)
|
| 45 |
+
for remove_insertions to work properly."""
|
| 46 |
+
|
| 47 |
+
msa = [
|
| 48 |
+
(record.description, remove_insertions(str(record.seq)))
|
| 49 |
+
for record in itertools.islice(SeqIO.parse(filename, "fasta"), nseq)
|
| 50 |
+
]
|
| 51 |
+
return msa
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def create_parser():
|
| 55 |
+
parser = argparse.ArgumentParser(
|
| 56 |
+
description="Label a deep mutational scan with predictions from an ensemble of ESM-1v models." # noqa
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# fmt: off
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--model-location",
|
| 62 |
+
type=str,
|
| 63 |
+
help="PyTorch model file OR name of pretrained model to download (see README for models)",
|
| 64 |
+
nargs="+",
|
| 65 |
+
)
|
| 66 |
+
parser.add_argument(
|
| 67 |
+
"--sequence",
|
| 68 |
+
type=str,
|
| 69 |
+
help="Base sequence to which mutations were applied",
|
| 70 |
+
)
|
| 71 |
+
parser.add_argument(
|
| 72 |
+
"--dms-input",
|
| 73 |
+
type=pathlib.Path,
|
| 74 |
+
help="CSV file containing the deep mutational scan",
|
| 75 |
+
)
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
"--mutation-col",
|
| 78 |
+
type=str,
|
| 79 |
+
default="mutant",
|
| 80 |
+
help="column in the deep mutational scan labeling the mutation as 'AiB'"
|
| 81 |
+
)
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--dms-output",
|
| 84 |
+
type=pathlib.Path,
|
| 85 |
+
help="Output file containing the deep mutational scan along with predictions",
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--offset-idx",
|
| 89 |
+
type=int,
|
| 90 |
+
default=0,
|
| 91 |
+
help="Offset of the mutation positions in `--mutation-col`"
|
| 92 |
+
)
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"--scoring-strategy",
|
| 95 |
+
type=str,
|
| 96 |
+
default="wt-marginals",
|
| 97 |
+
choices=["wt-marginals", "pseudo-ppl", "masked-marginals"],
|
| 98 |
+
help=""
|
| 99 |
+
)
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"--msa-path",
|
| 102 |
+
type=pathlib.Path,
|
| 103 |
+
help="path to MSA in a3m format (required for MSA Transformer)"
|
| 104 |
+
)
|
| 105 |
+
parser.add_argument(
|
| 106 |
+
"--msa-samples",
|
| 107 |
+
type=int,
|
| 108 |
+
default=400,
|
| 109 |
+
help="number of sequences to select from the start of the MSA"
|
| 110 |
+
)
|
| 111 |
+
# fmt: on
|
| 112 |
+
parser.add_argument("--nogpu", action="store_true", help="Do not use GPU even if available")
|
| 113 |
+
return parser
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def label_row(row, sequence, token_probs, alphabet, offset_idx):
|
| 117 |
+
wt, idx, mt = row[0], int(row[1:-1]) - offset_idx, row[-1]
|
| 118 |
+
assert sequence[idx] == wt, "The listed wildtype does not match the provided sequence"
|
| 119 |
+
|
| 120 |
+
wt_encoded, mt_encoded = alphabet.get_idx(wt), alphabet.get_idx(mt)
|
| 121 |
+
|
| 122 |
+
# add 1 for BOS
|
| 123 |
+
score = token_probs[0, 1 + idx, mt_encoded] - token_probs[0, 1 + idx, wt_encoded]
|
| 124 |
+
return score.item()
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _to_model_device(tokens, use_cuda):
|
| 128 |
+
return tokens.cuda() if use_cuda else tokens
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def compute_pppl(row, sequence, model, alphabet, offset_idx, use_cuda):
|
| 132 |
+
wt, idx, mt = row[0], int(row[1:-1]) - offset_idx, row[-1]
|
| 133 |
+
assert sequence[idx] == wt, "The listed wildtype does not match the provided sequence"
|
| 134 |
+
|
| 135 |
+
# modify the sequence
|
| 136 |
+
sequence = sequence[:idx] + mt + sequence[(idx + 1) :]
|
| 137 |
+
|
| 138 |
+
# encode the sequence
|
| 139 |
+
data = [
|
| 140 |
+
("protein1", sequence),
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
batch_converter = alphabet.get_batch_converter()
|
| 144 |
+
|
| 145 |
+
batch_labels, batch_strs, batch_tokens = batch_converter(data)
|
| 146 |
+
|
| 147 |
+
wt_encoded, mt_encoded = alphabet.get_idx(wt), alphabet.get_idx(mt)
|
| 148 |
+
|
| 149 |
+
# compute probabilities at each position
|
| 150 |
+
log_probs = []
|
| 151 |
+
for i in range(1, len(sequence) - 1):
|
| 152 |
+
batch_tokens_masked = batch_tokens.clone()
|
| 153 |
+
batch_tokens_masked[0, i] = alphabet.mask_idx
|
| 154 |
+
with torch.no_grad():
|
| 155 |
+
token_probs = torch.log_softmax(
|
| 156 |
+
model(_to_model_device(batch_tokens_masked, use_cuda))["logits"], dim=-1
|
| 157 |
+
)
|
| 158 |
+
log_probs.append(token_probs[0, i, alphabet.get_idx(sequence[i])].item()) # vocab size
|
| 159 |
+
return sum(log_probs)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def main(args):
|
| 163 |
+
# Load the deep mutational scan
|
| 164 |
+
df = pd.read_csv(args.dms_input)
|
| 165 |
+
|
| 166 |
+
# inference for each model
|
| 167 |
+
for model_location in args.model_location:
|
| 168 |
+
model, alphabet = pretrained.load_model_and_alphabet(model_location)
|
| 169 |
+
model.eval()
|
| 170 |
+
use_cuda = torch.cuda.is_available() and not args.nogpu
|
| 171 |
+
if use_cuda:
|
| 172 |
+
model = model.cuda()
|
| 173 |
+
print("Transferred model to GPU")
|
| 174 |
+
|
| 175 |
+
batch_converter = alphabet.get_batch_converter()
|
| 176 |
+
|
| 177 |
+
if isinstance(model, MSATransformer):
|
| 178 |
+
data = [read_msa(args.msa_path, args.msa_samples)]
|
| 179 |
+
assert (
|
| 180 |
+
args.scoring_strategy == "masked-marginals"
|
| 181 |
+
), "MSA Transformer only supports masked marginal strategy"
|
| 182 |
+
|
| 183 |
+
batch_labels, batch_strs, batch_tokens = batch_converter(data)
|
| 184 |
+
|
| 185 |
+
all_token_probs = []
|
| 186 |
+
for i in tqdm(range(batch_tokens.size(2))):
|
| 187 |
+
batch_tokens_masked = batch_tokens.clone()
|
| 188 |
+
batch_tokens_masked[0, 0, i] = alphabet.mask_idx # mask out first sequence
|
| 189 |
+
with torch.no_grad():
|
| 190 |
+
token_probs = torch.log_softmax(
|
| 191 |
+
model(_to_model_device(batch_tokens_masked, use_cuda))["logits"], dim=-1
|
| 192 |
+
)
|
| 193 |
+
all_token_probs.append(token_probs[:, 0, i]) # vocab size
|
| 194 |
+
token_probs = torch.cat(all_token_probs, dim=0).unsqueeze(0)
|
| 195 |
+
df[model_location] = df.apply(
|
| 196 |
+
lambda row: label_row(
|
| 197 |
+
row[args.mutation_col], args.sequence, token_probs, alphabet, args.offset_idx
|
| 198 |
+
),
|
| 199 |
+
axis=1,
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
else:
|
| 203 |
+
data = [
|
| 204 |
+
("protein1", args.sequence),
|
| 205 |
+
]
|
| 206 |
+
batch_labels, batch_strs, batch_tokens = batch_converter(data)
|
| 207 |
+
|
| 208 |
+
if args.scoring_strategy == "wt-marginals":
|
| 209 |
+
with torch.no_grad():
|
| 210 |
+
token_probs = torch.log_softmax(
|
| 211 |
+
model(_to_model_device(batch_tokens, use_cuda))["logits"], dim=-1
|
| 212 |
+
)
|
| 213 |
+
df[model_location] = df.apply(
|
| 214 |
+
lambda row: label_row(
|
| 215 |
+
row[args.mutation_col],
|
| 216 |
+
args.sequence,
|
| 217 |
+
token_probs,
|
| 218 |
+
alphabet,
|
| 219 |
+
args.offset_idx,
|
| 220 |
+
),
|
| 221 |
+
axis=1,
|
| 222 |
+
)
|
| 223 |
+
elif args.scoring_strategy == "masked-marginals":
|
| 224 |
+
all_token_probs = []
|
| 225 |
+
for i in tqdm(range(batch_tokens.size(1))):
|
| 226 |
+
batch_tokens_masked = batch_tokens.clone()
|
| 227 |
+
batch_tokens_masked[0, i] = alphabet.mask_idx
|
| 228 |
+
with torch.no_grad():
|
| 229 |
+
token_probs = torch.log_softmax(
|
| 230 |
+
model(_to_model_device(batch_tokens_masked, use_cuda))["logits"],
|
| 231 |
+
dim=-1,
|
| 232 |
+
)
|
| 233 |
+
all_token_probs.append(token_probs[:, i]) # vocab size
|
| 234 |
+
token_probs = torch.cat(all_token_probs, dim=0).unsqueeze(0)
|
| 235 |
+
df[model_location] = df.apply(
|
| 236 |
+
lambda row: label_row(
|
| 237 |
+
row[args.mutation_col],
|
| 238 |
+
args.sequence,
|
| 239 |
+
token_probs,
|
| 240 |
+
alphabet,
|
| 241 |
+
args.offset_idx,
|
| 242 |
+
),
|
| 243 |
+
axis=1,
|
| 244 |
+
)
|
| 245 |
+
elif args.scoring_strategy == "pseudo-ppl":
|
| 246 |
+
tqdm.pandas()
|
| 247 |
+
df[model_location] = df.progress_apply(
|
| 248 |
+
lambda row: compute_pppl(
|
| 249 |
+
row[args.mutation_col],
|
| 250 |
+
args.sequence,
|
| 251 |
+
model,
|
| 252 |
+
alphabet,
|
| 253 |
+
args.offset_idx,
|
| 254 |
+
use_cuda,
|
| 255 |
+
),
|
| 256 |
+
axis=1,
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
df.to_csv(args.dms_output)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
if __name__ == "__main__":
|
| 263 |
+
parser = create_parser()
|
| 264 |
+
args = parser.parse_args()
|
| 265 |
+
main(args)
|
tests/test_import_boundaries.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 6 |
+
MODEL_ROOT = PROJECT_ROOT / "model"
|
| 7 |
+
SCRIPT_ROOT = PROJECT_ROOT / "scripts"
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _python_files(root: Path):
|
| 11 |
+
return [path for path in root.rglob("*.py") if "__pycache__" not in path.parts]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_local_model_code_does_not_import_onescience_models_namespace():
|
| 15 |
+
offenders = []
|
| 16 |
+
for path in _python_files(MODEL_ROOT):
|
| 17 |
+
text = path.read_text(encoding="utf-8")
|
| 18 |
+
if "onescience.models." in text:
|
| 19 |
+
offenders.append(str(path.relative_to(PROJECT_ROOT)))
|
| 20 |
+
|
| 21 |
+
assert offenders == []
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_python_files_do_not_use_legacy_top_level_esm_or_openfold_imports():
|
| 25 |
+
pattern = re.compile(
|
| 26 |
+
r"^\s*(from\s+(esm|openfold)(\.|\s)|import\s+(esm|openfold)(\.|\s|$))",
|
| 27 |
+
re.MULTILINE,
|
| 28 |
+
)
|
| 29 |
+
offenders = []
|
| 30 |
+
for root in (MODEL_ROOT, SCRIPT_ROOT):
|
| 31 |
+
for path in _python_files(root):
|
| 32 |
+
text = path.read_text(encoding="utf-8")
|
| 33 |
+
if pattern.search(text):
|
| 34 |
+
offenders.append(str(path.relative_to(PROJECT_ROOT)))
|
| 35 |
+
|
| 36 |
+
assert offenders == []
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_scripts_bootstrap_project_root_before_importing_local_model():
|
| 40 |
+
offenders = []
|
| 41 |
+
for path in _python_files(SCRIPT_ROOT):
|
| 42 |
+
text = path.read_text(encoding="utf-8")
|
| 43 |
+
if "model.esm" in text and '_PROJECT_ROOT / "model"' not in text:
|
| 44 |
+
offenders.append(str(path.relative_to(PROJECT_ROOT)))
|
| 45 |
+
|
| 46 |
+
assert offenders == []
|
| 47 |
+
|
weight/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Weights
|
| 2 |
+
|
| 3 |
+
Model weights are not included in this extracted source package.
|
| 4 |
+
|
| 5 |
+
Recommended layouts:
|
| 6 |
+
|
| 7 |
+
- `weight/checkpoints/*.pt` when using `bash scripts/download_weights.sh ./weight`
|
| 8 |
+
- `${ONESCIENCE_MODELS_DIR}/esm_models/checkpoints/*.pt` when sharing weights with a OneScience environment
|
| 9 |
+
|
| 10 |
+
For named pretrained models, `model.esm.pretrained` can also download weights through PyTorch Hub and cache them under the active torch hub directory.
|
| 11 |
+
|
weight/esm-main/.flake8
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[flake8]
|
| 2 |
+
max-line-length = 99
|
| 3 |
+
ignore = E203,W503
|
| 4 |
+
exclude =
|
| 5 |
+
.git,
|
| 6 |
+
__pycache__,
|
| 7 |
+
build,
|
| 8 |
+
dist,
|
| 9 |
+
experimental
|
| 10 |
+
third_party
|
weight/esm-main/.git-blame-ignore-revs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Migrate code style to Black
|
| 2 |
+
8bc7e948cd9bf0b6d1f2113e221ef548ef663377
|
weight/esm-main/.github/ISSUE_TEMPLATE/bug.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: "[Bug Report]"
|
| 3 |
+
about: "Create a bug report. For other questions: see Discussions tab."
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
NOTE: if this is not a bug report, please use the [GitHub Discussions](https://github.com/facebookresearch/esm/discussions) for support questions (How do I do X?), feature requests, ideas, showcasing new applications, etc.
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
**Bug description**
|
| 11 |
+
Please enter a clear and concise description of what the bug is.
|
| 12 |
+
|
| 13 |
+
**Reproduction steps**
|
| 14 |
+
Enter steps to reproduce the behavior.
|
| 15 |
+
|
| 16 |
+
**Expected behavior**
|
| 17 |
+
Give a clear and concise description of what you expected to happen.
|
| 18 |
+
|
| 19 |
+
**Logs**
|
| 20 |
+
Please paste the command line output:
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
Output goes here
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
**Additional context**
|
| 27 |
+
Add any other context about the problem here. (like proxy settings, network setup, overall goals, etc.)
|
weight/esm-main/.gitignore
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# tensor dumps
|
| 2 |
+
*.pt
|
| 3 |
+
# Compiler Output #
|
| 4 |
+
###################
|
| 5 |
+
*.py[cod]
|
| 6 |
+
*.so
|
| 7 |
+
*.o
|
| 8 |
+
*.exe
|
| 9 |
+
*.class
|
| 10 |
+
|
| 11 |
+
# Folders #
|
| 12 |
+
###########
|
| 13 |
+
bin/
|
| 14 |
+
build/
|
| 15 |
+
dist/
|
| 16 |
+
local/
|
| 17 |
+
tmp/
|
| 18 |
+
__pycache__/
|
| 19 |
+
*.egg-info/
|
| 20 |
+
.idea/
|
| 21 |
+
.ipynb_checkpoints/
|
| 22 |
+
.vscode/
|
| 23 |
+
esm/dev
|
| 24 |
+
|
| 25 |
+
# Junk #
|
| 26 |
+
########
|
| 27 |
+
.DS_Store*
|
| 28 |
+
.*.swp
|
| 29 |
+
*.swp
|
| 30 |
+
*.log
|
| 31 |
+
*~
|
weight/esm-main/CODE_OF_CONDUCT.rst
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Code of Conduct
|
| 2 |
+
===============
|
| 3 |
+
|
| 4 |
+
Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please `read the full text`__ so that you can understand what actions will and will not be tolerated.
|
| 5 |
+
|
| 6 |
+
__ https://code.facebook.com/codeofconduct
|
weight/esm-main/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributing to esm
|
| 2 |
+
We want to make contributing to this project as easy and transparent as
|
| 3 |
+
possible.
|
| 4 |
+
|
| 5 |
+
## Pull Requests
|
| 6 |
+
We actively welcome your pull requests.
|
| 7 |
+
|
| 8 |
+
1. Fork the repo and create your branch from `master`.
|
| 9 |
+
2. If you've added code that should be tested, add tests.
|
| 10 |
+
3. If you've changed APIs, update the documentation.
|
| 11 |
+
4. Ensure the test suite passes.
|
| 12 |
+
5. Make sure your code lints.
|
| 13 |
+
6. If you haven't already, complete the Contributor License Agreement ("CLA").
|
| 14 |
+
|
| 15 |
+
## Contributor License Agreement ("CLA")
|
| 16 |
+
In order to accept your pull request, we need you to submit a CLA. You only need
|
| 17 |
+
to do this once to work on any of Facebook's open source projects.
|
| 18 |
+
|
| 19 |
+
Complete your CLA here: <https://code.facebook.com/cla>
|
| 20 |
+
|
| 21 |
+
## Issues
|
| 22 |
+
We use GitHub issues to track public bugs. Please ensure your description is
|
| 23 |
+
clear and has sufficient instructions to be able to reproduce the issue.
|
| 24 |
+
|
| 25 |
+
Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
|
| 26 |
+
disclosure of security bugs. In those cases, please go through the process
|
| 27 |
+
outlined on that page and do not file a public issue.
|
| 28 |
+
|
| 29 |
+
## License
|
| 30 |
+
By contributing to icp-block-mdp, you agree that your contributions will be licensed
|
| 31 |
+
under the LICENSE file in the root directory of this source tree.
|
weight/esm-main/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
weight/esm-main/README.md
ADDED
|
@@ -0,0 +1,795 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evolutionary Scale Modeling
|
| 2 |
+
|
| 3 |
+
[](https://esmatlas.com)
|
| 4 |
+
|
| 5 |
+
***Update April 2023:*** Code for the two simultaneous preprints on protein design is now released! Code for "Language models generalize beyond natural proteins" is under [examples/lm-design/](examples/lm-design/). Code for "A high-level programming language for generative protein design" is under [examples/protein-programming-language/](examples/protein-programming-language/).
|
| 6 |
+
|
| 7 |
+
This repository contains code and pre-trained weights for **Transformer protein language models** from the Meta Fundamental AI Research Protein Team (FAIR), including our state-of-the-art [**ESM-2** and **ESMFold**](#esmfold), as well as [**MSA Transformer**](https://www.biorxiv.org/content/10.1101/2021.02.12.430858v1), [**ESM-1v**](#zs_variant) for predicting variant effects and [**ESM-IF1**](#invf) for inverse folding.
|
| 8 |
+
Transformer protein language models were introduced in the [2019 preprint](https://doi.org/10.1101/622803) of the paper ["Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences"](https://doi.org/10.1073/pnas.2016239118).
|
| 9 |
+
ESM-2 outperforms all tested single-sequence protein language models across a range of structure prediction tasks.
|
| 10 |
+
ESMFold harnesses the ESM-2 language model to generate accurate structure predictions end to end directly from the sequence of a protein.
|
| 11 |
+
|
| 12 |
+
In November 2022, we released `v0` of the [ESM Metagenomic Atlas](https://esmatlas.com), an open atlas of 617 million predicted metagenomic protein structures.
|
| 13 |
+
The Atlas was updated in March 2023 in collaboration with EBI. The new `v2023_02` adds another 150 million predicted structures to the Atlas, as well as pre-computed ESM2 embeddings.
|
| 14 |
+
Bulk download, blog post and the resources provided on the Atlas website are documented [on this README](#atlas).
|
| 15 |
+
|
| 16 |
+
In December 2022, we released two simultaneous preprints on protein design.
|
| 17 |
+
* "Language models generalize beyond natural proteins" ([PAPER](https://doi.org/10.1101/2022.12.21.521521), [CODE](examples/lm-design/)) uses ESM2 to design de novo proteins. The code and data associated with the preprint can be found [here](examples/lm-design/).
|
| 18 |
+
* "A high-level programming language for generative protein design" ([PAPER](https://doi.org/10.1101/2022.12.21.521526), [CODE](examples/protein-programming-language/)) uses ESMFold to design proteins according to a high-level programming language.
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
<details><summary><b>Citation</b></summary>
|
| 23 |
+
For ESM2, ESMFold and ESM Atlas:
|
| 24 |
+
```bibtex
|
| 25 |
+
@article{lin2023evolutionary,
|
| 26 |
+
title = {Evolutionary-scale prediction of atomic-level protein structure with a language model},
|
| 27 |
+
author = {Zeming Lin and Halil Akin and Roshan Rao and Brian Hie and Zhongkai Zhu and Wenting Lu and Nikita Smetanin and Robert Verkuil and Ori Kabeli and Yaniv Shmueli and Allan dos Santos Costa and Maryam Fazel-Zarandi and Tom Sercu and Salvatore Candido and Alexander Rives },
|
| 28 |
+
journal = {Science},
|
| 29 |
+
volume = {379},
|
| 30 |
+
number = {6637},
|
| 31 |
+
pages = {1123-1130},
|
| 32 |
+
year = {2023},
|
| 33 |
+
doi = {10.1126/science.ade2574},
|
| 34 |
+
URL = {https://www.science.org/doi/abs/10.1126/science.ade2574},
|
| 35 |
+
note={Earlier versions as preprint: bioRxiv 2022.07.20.500902},
|
| 36 |
+
}
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
For transformer protein language models:
|
| 40 |
+
```bibtex
|
| 41 |
+
@article{rives2021biological,
|
| 42 |
+
title={Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences},
|
| 43 |
+
author={Rives, Alexander and Meier, Joshua and Sercu, Tom and Goyal, Siddharth and Lin, Zeming and Liu, Jason and Guo, Demi and Ott, Myle and Zitnick, C Lawrence and Ma, Jerry and others},
|
| 44 |
+
journal={Proceedings of the National Academy of Sciences},
|
| 45 |
+
volume={118},
|
| 46 |
+
number={15},
|
| 47 |
+
pages={e2016239118},
|
| 48 |
+
year={2021},
|
| 49 |
+
publisher={National Acad Sciences},
|
| 50 |
+
note={bioRxiv 10.1101/622803},
|
| 51 |
+
doi={10.1073/pnas.2016239118},
|
| 52 |
+
url={https://www.pnas.org/doi/full/10.1073/pnas.2016239118},
|
| 53 |
+
}
|
| 54 |
+
```
|
| 55 |
+
</details>
|
| 56 |
+
|
| 57 |
+
<details open><summary><b>Table of contents</b></summary>
|
| 58 |
+
|
| 59 |
+
- [Main models you should use](#main-models)
|
| 60 |
+
- [Usage](#usage)
|
| 61 |
+
- [Quick Start](#quickstart)
|
| 62 |
+
- [Getting Started with this repository](#repostart)
|
| 63 |
+
- [ESMFold Structure Prediction](#esmfold)
|
| 64 |
+
- [Compute embeddings in bulk from FASTA](#bulk_fasta)
|
| 65 |
+
- [CPU offloading for inference with large models](#fsdp)
|
| 66 |
+
- [Zero-shot variant prediction](#zs_variant)
|
| 67 |
+
- [Inverse folding](#invf)
|
| 68 |
+
- [ESM Metagenomic Atlas](#atlas)
|
| 69 |
+
- [Notebooks](#notebooks)
|
| 70 |
+
- [Available Models and Datasets](#available)
|
| 71 |
+
- [Pre-trained Models](#available-models)
|
| 72 |
+
- [ESM Structural Split Dataset](#available-esmssd)
|
| 73 |
+
- [Pre-training Dataset Split](#available-pretraining-split)
|
| 74 |
+
- [Comparison to related works](#perf_related)
|
| 75 |
+
- [Citations](#citations)
|
| 76 |
+
- [License](#license)
|
| 77 |
+
</details>
|
| 78 |
+
|
| 79 |
+
<details><summary><b>What's New</b></summary>
|
| 80 |
+
|
| 81 |
+
- April 2023: Code for the protein design preprints released under [examples/lm-design/](examples/lm-design/).
|
| 82 |
+
- March 2023: We release an update to the ESM Metagenomic Atlas, `v2023_02`. See [website](https://esmatlas.com/) and [bulk download details](#atlas).
|
| 83 |
+
- December 2022: The Meta Fundamental AI Research Protein Team (FAIR) released two simultaneous preprints on protein design:
|
| 84 |
+
["Language models generalize beyond natural proteins" (Verkuil, Kabeli, et al., 2022)](https://doi.org/10.1101/2022.12.21.521521), and ["A high-level programming language for generative protein design" (Hie, Candido, et al., 2022)](https://doi.org/10.1101/2022.12.21.521521).
|
| 85 |
+
- November 2022: ESM Metagenomic Atlas, a repository of 600M+ metagenomics structures released, see [website](https://esmatlas.com/) and [bulk download details](#atlas)
|
| 86 |
+
- November 2022: ESMFold - new end-to-end structure prediction model released (see [Lin et al. 2022](https://www.science.org/doi/abs/10.1126/science.ade2574))
|
| 87 |
+
- August 2022: ESM-2 - new SOTA Language Models released (see [Lin et al. 2022](https://www.science.org/doi/abs/10.1126/science.ade2574))
|
| 88 |
+
- April 2022: New inverse folding model ESM-IF1 released, trained on CATH and UniRef50 predicted structures.
|
| 89 |
+
- August 2021: Added flexibility to tokenizer to allow for spaces and special tokens (like `<mask>`) in sequence.
|
| 90 |
+
- July 2021: New pre-trained model ESM-1v released, trained on UniRef90 (see [Meier et al. 2021](https://doi.org/10.1101/2021.07.09.450648)).
|
| 91 |
+
- July 2021: New MSA Transformer released, with a minor fix in the row positional embeddings (`ESM-MSA-1b`).
|
| 92 |
+
- Feb 2021: MSA Transformer added (see [Rao et al. 2021](https://www.biorxiv.org/content/10.1101/2021.02.12.430858v1)). Example usage in [notebook](#notebooks).
|
| 93 |
+
- Dec 2020: [Self-Attention Contacts](#notebooks) for all pre-trained models (see [Rao et al. 2020](https://doi.org/10.1101/2020.12.15.422761))
|
| 94 |
+
- Dec 2020: Added new pre-trained model [ESM-1b](#perf_related) (see [Rives et al. 2019](https://doi.org/10.1101/622803) Appendix B)
|
| 95 |
+
- Dec 2020: [ESM Structural Split Dataset](#available-esmssd) (see [Rives et al. 2019](https://doi.org/10.1101/622803) Appendix A.10)
|
| 96 |
+
|
| 97 |
+
</details>
|
| 98 |
+
|
| 99 |
+
## Main models you should use <a name="main-models"></a>
|
| 100 |
+
|
| 101 |
+
| Shorthand | `esm.pretrained.` | Dataset | Description |
|
| 102 |
+
|-----------|-----------------------------|---------|--------------|
|
| 103 |
+
| ESM-2 | `esm2_t36_3B_UR50D()` `esm2_t48_15B_UR50D()` | UR50 (sample UR90) | SOTA general-purpose protein language model. Can be used to predict structure, function and other protein properties directly from individual sequences. Released with [Lin et al. 2022](https://www.science.org/doi/abs/10.1126/science.ade2574) (Aug 2022 update). |
|
| 104 |
+
| ESMFold | `esmfold_v1()` | PDB + UR50 | End-to-end single sequence 3D structure predictor (Nov 2022 update). |
|
| 105 |
+
| ESM-MSA-1b| `esm_msa1b_t12_100M_UR50S()` | UR50 + MSA | MSA Transformer language model. Can be used to extract embeddings from an MSA. Enables SOTA inference of structure. Released with [Rao et al. 2021](https://www.biorxiv.org/content/10.1101/2021.02.12.430858v2) (ICML'21 version, June 2021). |
|
| 106 |
+
| ESM-1v | `esm1v_t33_650M_UR90S_1()` ... `esm1v_t33_650M_UR90S_5()`| UR90 | Language model specialized for prediction of variant effects. Enables SOTA zero-shot prediction of the functional effects of sequence variations. Same architecture as ESM-1b, but trained on UniRef90. Released with [Meier et al. 2021](https://doi.org/10.1101/2021.07.09.450648). |
|
| 107 |
+
| ESM-IF1 | `esm_if1_gvp4_t16_142M_UR50()` | CATH + UR50 | Inverse folding model. Can be used to design sequences for given structures, or to predict functional effects of sequence variation for given structures. Enables SOTA fixed backbone sequence design. Released with [Hsu et al. 2022](https://doi.org/10.1101/2022.04.10.487779). |
|
| 108 |
+
|
| 109 |
+
For a complete list of available models, with details and release notes, see [Pre-trained Models](#available-models).
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
## Usage <a name="usage"></a>
|
| 113 |
+
|
| 114 |
+
### Quick start <a name="quickstart"></a>
|
| 115 |
+
|
| 116 |
+
An easy way to get started is to load ESM or ESMFold through the [HuggingFace transformers library](https://huggingface.co/docs/transformers/model_doc/esm),
|
| 117 |
+
which has simplified the ESMFold dependencies and provides a standardized API and tools to work with state-of-the-art pretrained models.
|
| 118 |
+
|
| 119 |
+
Alternatively, [ColabFold](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/ESMFold.ipynb) has integrated ESMFold so that you can
|
| 120 |
+
easily run it directly in the browser on a Google Colab instance.
|
| 121 |
+
|
| 122 |
+
We also provide an API which you can access through curl or on [the ESM Metagenomic Atlas web page](https://esmatlas.com/resources?action=fold).
|
| 123 |
+
```
|
| 124 |
+
curl -X POST --data "KVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL" https://api.esmatlas.com/foldSequence/v1/pdb/
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
For ESM-MSA-1b, ESM-IF1, or any of the other models you can use the original implementation from our repo directly via the instructions below.
|
| 128 |
+
|
| 129 |
+
### Getting started with this repo <a name="repostart"></a>
|
| 130 |
+
|
| 131 |
+
As a prerequisite, you must have PyTorch installed to use this repository.
|
| 132 |
+
|
| 133 |
+
You can use this one-liner for installation, using the latest release of esm:
|
| 134 |
+
|
| 135 |
+
```bash
|
| 136 |
+
pip install fair-esm # latest release, OR:
|
| 137 |
+
pip install git+https://github.com/facebookresearch/esm.git # bleeding edge, current repo main branch
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
To use the ESMFold model, make sure you start from an environment with python <= 3.9 and pytorch installed.
|
| 141 |
+
Then add the `[esmfold]` option to your pip install, which will install the dependencies for OpenFold
|
| 142 |
+
automatically. Openfold installation requires `nvcc`.
|
| 143 |
+
|
| 144 |
+
```bash
|
| 145 |
+
pip install "fair-esm[esmfold]"
|
| 146 |
+
# OpenFold and its remaining dependency
|
| 147 |
+
pip install 'dllogger @ git+https://github.com/NVIDIA/dllogger.git'
|
| 148 |
+
pip install 'openfold @ git+https://github.com/aqlaboratory/openfold.git@4b41059694619831a7db195b7e0988fc4ff3a307'
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
**NOTE**: If openfold installation fails, please double check that `nvcc` is available and that a cuda-compatable version of PyTorch has been installed.
|
| 152 |
+
|
| 153 |
+
Alternatively, we provide the `esmfold` conda environment, which can be built via `conda env create -f environment.yml`.
|
| 154 |
+
|
| 155 |
+
We also support PyTorch Hub, which removes the need to clone and/or install this repository yourself:
|
| 156 |
+
|
| 157 |
+
```python
|
| 158 |
+
import torch
|
| 159 |
+
model, alphabet = torch.hub.load("facebookresearch/esm:main", "esm2_t33_650M_UR50D")
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
After pip install, you can load and use a pretrained model as follows:
|
| 163 |
+
|
| 164 |
+
```python
|
| 165 |
+
import torch
|
| 166 |
+
import esm
|
| 167 |
+
|
| 168 |
+
# Load ESM-2 model
|
| 169 |
+
model, alphabet = esm.pretrained.esm2_t33_650M_UR50D()
|
| 170 |
+
batch_converter = alphabet.get_batch_converter()
|
| 171 |
+
model.eval() # disables dropout for deterministic results
|
| 172 |
+
|
| 173 |
+
# Prepare data (first 2 sequences from ESMStructuralSplitDataset superfamily / 4)
|
| 174 |
+
data = [
|
| 175 |
+
("protein1", "MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLAGG"),
|
| 176 |
+
("protein2", "KALTARQQEVFDLIRDHISQTGMPPTRAEIAQRLGFRSPNAAEEHLKALARKGVIEIVSGASRGIRLLQEE"),
|
| 177 |
+
("protein2 with mask","KALTARQQEVFDLIRD<mask>ISQTGMPPTRAEIAQRLGFRSPNAAEEHLKALARKGVIEIVSGASRGIRLLQEE"),
|
| 178 |
+
("protein3", "K A <mask> I S Q"),
|
| 179 |
+
]
|
| 180 |
+
batch_labels, batch_strs, batch_tokens = batch_converter(data)
|
| 181 |
+
batch_lens = (batch_tokens != alphabet.padding_idx).sum(1)
|
| 182 |
+
|
| 183 |
+
# Extract per-residue representations (on CPU)
|
| 184 |
+
with torch.no_grad():
|
| 185 |
+
results = model(batch_tokens, repr_layers=[33], return_contacts=True)
|
| 186 |
+
token_representations = results["representations"][33]
|
| 187 |
+
|
| 188 |
+
# Generate per-sequence representations via averaging
|
| 189 |
+
# NOTE: token 0 is always a beginning-of-sequence token, so the first residue is token 1.
|
| 190 |
+
sequence_representations = []
|
| 191 |
+
for i, tokens_len in enumerate(batch_lens):
|
| 192 |
+
sequence_representations.append(token_representations[i, 1 : tokens_len - 1].mean(0))
|
| 193 |
+
|
| 194 |
+
# Look at the unsupervised self-attention map contact predictions
|
| 195 |
+
import matplotlib.pyplot as plt
|
| 196 |
+
for (_, seq), tokens_len, attention_contacts in zip(data, batch_lens, results["contacts"]):
|
| 197 |
+
plt.matshow(attention_contacts[: tokens_len, : tokens_len])
|
| 198 |
+
plt.title(seq)
|
| 199 |
+
plt.show()
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
### ESMFold Structure Prediction <a name="esmfold"></a>
|
| 204 |
+
|
| 205 |
+
After installing with the `[esmfold]` option, you can use the ESMFold structure prediction model as follows:
|
| 206 |
+
|
| 207 |
+
```python
|
| 208 |
+
import torch
|
| 209 |
+
import esm
|
| 210 |
+
|
| 211 |
+
model = esm.pretrained.esmfold_v1()
|
| 212 |
+
model = model.eval().cuda()
|
| 213 |
+
|
| 214 |
+
# Optionally, uncomment to set a chunk size for axial attention. This can help reduce memory.
|
| 215 |
+
# Lower sizes will have lower memory requirements at the cost of increased speed.
|
| 216 |
+
# model.set_chunk_size(128)
|
| 217 |
+
|
| 218 |
+
sequence = "MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLAGG"
|
| 219 |
+
# Multimer prediction can be done with chains separated by ':'
|
| 220 |
+
|
| 221 |
+
with torch.no_grad():
|
| 222 |
+
output = model.infer_pdb(sequence)
|
| 223 |
+
|
| 224 |
+
with open("result.pdb", "w") as f:
|
| 225 |
+
f.write(output)
|
| 226 |
+
|
| 227 |
+
import biotite.structure.io as bsio
|
| 228 |
+
struct = bsio.load_structure("result.pdb", extra_fields=["b_factor"])
|
| 229 |
+
print(struct.b_factor.mean()) # this will be the pLDDT
|
| 230 |
+
# 88.3
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
Besides `esm.pretrained.esmfold_v1()` which is the best performing model we recommend using, we
|
| 235 |
+
also provide `esm.pretrained.esmfold_v0()` which was used for the experiments in
|
| 236 |
+
[Lin et al. 2022](https://www.science.org/doi/abs/10.1126/science.ade2574).
|
| 237 |
+
|
| 238 |
+
We also provide a command line interface (`esm-fold`) that efficiently predicts structures in bulk from a FASTA file using ESMFold:
|
| 239 |
+
```
|
| 240 |
+
usage: esm-fold [-h] -i FASTA -o PDB [--num-recycles NUM_RECYCLES]
|
| 241 |
+
[--max-tokens-per-batch MAX_TOKENS_PER_BATCH]
|
| 242 |
+
[--chunk-size CHUNK_SIZE] [--cpu-only] [--cpu-offload]
|
| 243 |
+
|
| 244 |
+
optional arguments:
|
| 245 |
+
-h, --help show this help message and exit
|
| 246 |
+
-i FASTA, --fasta FASTA
|
| 247 |
+
Path to input FASTA file
|
| 248 |
+
-o PDB, --pdb PDB Path to output PDB directory
|
| 249 |
+
--num-recycles NUM_RECYCLES
|
| 250 |
+
Number of recycles to run. Defaults to number used in
|
| 251 |
+
training (4).
|
| 252 |
+
--max-tokens-per-batch MAX_TOKENS_PER_BATCH
|
| 253 |
+
Maximum number of tokens per gpu forward-pass. This
|
| 254 |
+
will group shorter sequences together for batched
|
| 255 |
+
prediction. Lowering this can help with out of memory
|
| 256 |
+
issues, if these occur on short sequences.
|
| 257 |
+
--chunk-size CHUNK_SIZE
|
| 258 |
+
Chunks axial attention computation to reduce memory
|
| 259 |
+
usage from O(L^2) to O(L). Equivalent to running a for
|
| 260 |
+
loop over chunks of of each dimension. Lower values
|
| 261 |
+
will result in lower memory usage at the cost of
|
| 262 |
+
speed. Recommended values: 128, 64, 32. Default: None.
|
| 263 |
+
--cpu-only CPU only
|
| 264 |
+
--cpu-offload Enable CPU offloading
|
| 265 |
+
```
|
| 266 |
+
|
| 267 |
+
The command will make one prediction for every sequence in the fasta file. Multimers can be predicted and should be entered in the fasta file as a single sequence, with chains seprated by a ":" character.
|
| 268 |
+
|
| 269 |
+
By default, predictions will be batched together so that shorter sequences are predicted simultaneously. This can be disabled by setting `--max-tokens-per-batch=0`. Batching can significantly improve prediction speed on shorter sequences.
|
| 270 |
+
|
| 271 |
+
The `--cpu-offload` flag can be useful for making predictions on longer sequences. It will attempt to offload some parameters to the CPU RAM, rather than storing on GPU.
|
| 272 |
+
|
| 273 |
+
Finally, the ablation experiments for LMs of varying sizes [Lin et al. 2022 table S1](https://www.science.org/doi/abs/10.1126/science.ade2574) are released as `esm.pretrained.esmfold_structure_module_only_*()`. We don't recommend using these models for structure prediction.
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
### Compute embeddings in bulk from FASTA <a name="bulk_fasta"></a>
|
| 277 |
+
|
| 278 |
+
We provide a command line interface (`esm-extract`) that efficiently extracts embeddings in bulk for a FASTA file from the ESM:
|
| 279 |
+
```
|
| 280 |
+
usage: esm-extract [-h] [--toks_per_batch TOKS_PER_BATCH]
|
| 281 |
+
[--repr_layers REPR_LAYERS [REPR_LAYERS ...]] --include
|
| 282 |
+
{mean,per_tok,bos,contacts}
|
| 283 |
+
[{mean,per_tok,bos,contacts} ...]
|
| 284 |
+
[--truncation_seq_length TRUNCATION_SEQ_LENGTH]
|
| 285 |
+
model_location fasta_file output_dir
|
| 286 |
+
|
| 287 |
+
Extract per-token representations and model outputs for sequences in a FASTA
|
| 288 |
+
file
|
| 289 |
+
|
| 290 |
+
positional arguments:
|
| 291 |
+
model_location PyTorch model file OR name of pretrained model to
|
| 292 |
+
download (see README for models)
|
| 293 |
+
fasta_file FASTA file on which to extract representations
|
| 294 |
+
output_dir output directory for extracted representations
|
| 295 |
+
|
| 296 |
+
optional arguments:
|
| 297 |
+
-h, --help show this help message and exit
|
| 298 |
+
--toks_per_batch TOKS_PER_BATCH
|
| 299 |
+
maximum batch size
|
| 300 |
+
--repr_layers REPR_LAYERS [REPR_LAYERS ...]
|
| 301 |
+
layers indices from which to extract representations
|
| 302 |
+
(0 to num_layers, inclusive)
|
| 303 |
+
--include {mean,per_tok,bos,contacts} [{mean,per_tok,bos,contacts} ...]
|
| 304 |
+
specify which representations to return
|
| 305 |
+
--truncation_seq_length TRUNCATION_SEQ_LENGTH
|
| 306 |
+
truncate sequences longer than the given value
|
| 307 |
+
```
|
| 308 |
+
|
| 309 |
+
The following commands allow the extraction of the final-layer embedding for a FASTA file from the ESM-2 model:
|
| 310 |
+
|
| 311 |
+
```bash
|
| 312 |
+
esm-extract esm2_t33_650M_UR50D examples/data/some_proteins.fasta \
|
| 313 |
+
examples/data/some_proteins_emb_esm2 --repr_layers 0 32 33 --include
|
| 314 |
+
```
|
| 315 |
+
```bash
|
| 316 |
+
python scripts/extract.py esm2_t33_650M_UR50D examples/data/some_proteins.fasta \
|
| 317 |
+
examples/data/some_proteins_emb_esm2 --repr_layers 0 32 33 --include mean per_tok
|
| 318 |
+
```
|
| 319 |
+
|
| 320 |
+
A cuda device is optional and will be auto-detected.
|
| 321 |
+
|
| 322 |
+
Directory `some_proteins_emb_esm2/` now contains one `.pt` file per FASTA sequence; use `torch.load()` to load them.
|
| 323 |
+
`scripts/extract.py` has flags that determine what's included in the `.pt` file:
|
| 324 |
+
* `--repr-layers` (default: final only) selects which layers to include embeddings from.
|
| 325 |
+
* `--include` specifies what embeddings to save. You can use the following:
|
| 326 |
+
* `per_tok` includes the full sequence, with an embedding per amino acid (seq_len x hidden_dim).
|
| 327 |
+
* `mean` includes the embeddings averaged over the full sequence, per layer.
|
| 328 |
+
* `bos` includes the embeddings from the beginning-of-sequence token.
|
| 329 |
+
(NOTE: Don't use with the pre-trained models - we trained without bos-token supervision)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
### CPU offloading for inference with large models <a name="fsdp"></a>
|
| 333 |
+
If you want to load very large models like 15B and/or do inference on long sequences on your machine, regular GPU inference may lead to OOM errors.
|
| 334 |
+
We show how to load the model with Fairscale's [Fully Sharded Data Parallel (FSDP)](https://fairscale.readthedocs.io/en/stable/api/nn/fsdp.html) and
|
| 335 |
+
use its CPU offloading feature.
|
| 336 |
+
This allows to do inference of large models on a single GPU.
|
| 337 |
+
Please check out `examples/esm2_infer_fairscale_fsdp_cpu_offloading.py` for more details.
|
| 338 |
+
|
| 339 |
+
### Zero-shot variant prediction <a name="zs_variant"></a>
|
| 340 |
+
See "[examples/variant-prediction/](examples/variant-prediction/)" for code and pre-trained weights for the ESM-1v models described in
|
| 341 |
+
[Language models enable zero-shot prediction of the effects of mutations on protein function. (Meier et al. 2021)](https://doi.org/10.1101/2021.07.09.450648).
|
| 342 |
+
|
| 343 |
+
Note that ESM-2 could be used for variant prediction as well, and is expected to have similar performance to ESM-1v.
|
| 344 |
+
|
| 345 |
+
### Inverse folding <a name="invf"></a>
|
| 346 |
+
See "[examples/inverse_folding/](examples/inverse_folding/)" for detailed user guide. The ESM-IF1 model is described as `GVPTransformer` in [Learning inverse folding from millions of predicted structures. (Hsu et al. 2022)](https://doi.org/10.1101/2022.04.10.487779).
|
| 347 |
+
|
| 348 |
+
We also provide a colab notebook for the sequence design and sequence scoring functionalities.
|
| 349 |
+
|
| 350 |
+
[<img src="https://colab.research.google.com/assets/colab-badge.svg">](https://colab.research.google.com/github/facebookresearch/esm/blob/main/examples/inverse_folding/notebook_multichain.ipynb)
|
| 351 |
+
|
| 352 |
+
The ESM-IF1 inverse folding model is built for predicting protein sequences
|
| 353 |
+
from their backbone atom coordinates. We provide scripts here 1) to sample sequence
|
| 354 |
+
designs for a given structure and 2) to score sequences for a given structure.
|
| 355 |
+
|
| 356 |
+
Trained with 12M protein structures predicted by AlphaFold2, the ESM-IF1
|
| 357 |
+
model consists of invariant geometric input processing layers followed by a
|
| 358 |
+
sequence-to-sequence transformer, and achieves 51% native sequence recovery on
|
| 359 |
+
structurally held-out backbones with 72% recovery for buried residues.
|
| 360 |
+
The model is also trained with span masking to tolerate missing backbone
|
| 361 |
+
coordinates and therefore can predict sequences for partially masked structures.
|
| 362 |
+
|
| 363 |
+
#### Sample sequence designs for a given structure
|
| 364 |
+
The environment setup is described in [this subsection of examples/inverse_folding](examples/inverse_folding#recommended-environment).
|
| 365 |
+
|
| 366 |
+
To sample sequences for a given structure in PDB or mmCIF format, use the
|
| 367 |
+
`sample_sequences.py` script. The input file can have either `.pdb` or
|
| 368 |
+
`.cif` as suffix.
|
| 369 |
+
|
| 370 |
+
For example, to sample 3 sequence designs for the golgi casein kinase structure
|
| 371 |
+
(PDB [5YH2](https://www.rcsb.org/structure/5yh2); [PDB Molecule of the Month
|
| 372 |
+
from January 2022](https://pdb101.rcsb.org/motm/265)), we can run the following
|
| 373 |
+
command from the esm root directory:
|
| 374 |
+
```bash
|
| 375 |
+
python examples/inverse_folding/sample_sequences.py examples/inverse_folding/data/5YH2.pdb \
|
| 376 |
+
--chain C --temperature 1 --num-samples 3 --outpath examples/inverse_folding/output/sampled_sequences.fasta
|
| 377 |
+
```
|
| 378 |
+
|
| 379 |
+
The sampled sequences will be saved in a fasta format to the specified output file.
|
| 380 |
+
|
| 381 |
+
The temperature parameter controls the sharpness of the probability
|
| 382 |
+
distribution for sequence sampling. Higher sampling temperatures yield more
|
| 383 |
+
diverse sequences but likely with lower native sequence recovery.
|
| 384 |
+
The default sampling temperature is 1. To optimize for native sequence
|
| 385 |
+
recovery, we recommend sampling with low temperature such as 1e-6.
|
| 386 |
+
|
| 387 |
+
#### Scoring sequences
|
| 388 |
+
To score the conditional log-likelihoods for sequences conditioned on a given
|
| 389 |
+
structure, use the `score_log_likelihoods.py` script.
|
| 390 |
+
|
| 391 |
+
For example, to score the sequences in `examples/inverse_folding/data/5YH2_mutated_seqs.fasta`
|
| 392 |
+
according to the structure in `examples/inverse_folding/data/5YH2.pdb`, we can run
|
| 393 |
+
the following command from the esm root directory:
|
| 394 |
+
```
|
| 395 |
+
python examples/inverse_folding/score_log_likelihoods.py examples/inverse_folding/data/5YH2.pdb \
|
| 396 |
+
examples/inverse_folding/data/5YH2_mutated_seqs.fasta --chain C \
|
| 397 |
+
--outpath examples/inverse_folding/output/5YH2_mutated_seqs_scores.csv
|
| 398 |
+
```
|
| 399 |
+
|
| 400 |
+
The conditional log-likelihoods are saved in a csv format in the specified output path.
|
| 401 |
+
The output values are the average log-likelihoods averaged over all amino acids in a sequence.
|
| 402 |
+
|
| 403 |
+
For more information, see "[./examples/inverse_folding/](examples/inverse_folding/)" for detailed user guide.
|
| 404 |
+
|
| 405 |
+
## ESM Metagenomic Atlas <a name="atlas"></a>
|
| 406 |
+
|
| 407 |
+
Please visit the [ESM Metagenomic Atlas](https://esmatlas.com/) website, and
|
| 408 |
+
see our [blog post](https://ai.facebook.com/blog/protein-folding-esmfold-metagenomics/) to learn more.
|
| 409 |
+
|
| 410 |
+
Bulk download instructions available at a seperate README [here](scripts/atlas/README.md).
|
| 411 |
+
|
| 412 |
+
The Atlas resources include a page to [fold a sequence using ESMFold](https://esmatlas.com/resources?action=fold),
|
| 413 |
+
searching a subset of the ESM Atlas by [structure](https://esmatlas.com/resources?action=search_structure) or
|
| 414 |
+
[sequence](https://esmatlas.com/resources?action=search_sequence),
|
| 415 |
+
as well as an [API](https://esmatlas.com/about#api) to access those resources programmatically.
|
| 416 |
+
|
| 417 |
+
Foldseek provides search against the Atlas without the length limitation [here](https://search.foldseek.com/search).
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
## Notebooks <a name="notebooks"></a>
|
| 421 |
+
|
| 422 |
+
### Inverse folding - predicting or scoring sequences based on backbone structures
|
| 423 |
+
|
| 424 |
+
[<img src="https://colab.research.google.com/assets/colab-badge.svg">](https://colab.research.google.com/github/facebookresearch/esm/blob/main/examples/inverse_folding/notebook.ipynb)
|
| 425 |
+
|
| 426 |
+
The ESM-IF1 inverse folding model predicts protein sequences from their backbone atom coordinates, trained with 12M protein structures predicted by AlphaFold2.
|
| 427 |
+
This notetook guide you through examples of sampling sequences, calculating conditional log-likelihoods, and extracting encoder output as structure representation.
|
| 428 |
+
|
| 429 |
+
### Supervised variant prediction - training a classifier on the embeddings
|
| 430 |
+
|
| 431 |
+
[<img src="https://colab.research.google.com/assets/colab-badge.svg">](https://colab.research.google.com/github/facebookresearch/esm/blob/main/examples/sup_variant_prediction.ipynb)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
To help you get started with using the embeddings, this [jupyter notebook tutorial](examples/sup_variant_prediction.ipynb) shows how to train a supervised variant predictor using embeddings from ESM-1.
|
| 435 |
+
You can adopt a similar protocol to train a model for any downstream task, even with limited data.
|
| 436 |
+
First you can obtain the embeddings for ``examples/data/P62593.fasta`` either by [downloading the precomputed](https://dl.fbaipublicfiles.com/fair-esm/examples/P62593_reprs.tar.gz) embeddings
|
| 437 |
+
as instructed in the notebook or by running the following:
|
| 438 |
+
|
| 439 |
+
```bash
|
| 440 |
+
# Obtain the embeddings
|
| 441 |
+
python scripts/extract.py esm1v_t33_650M_UR90S_1 examples/data/P62593.fasta \
|
| 442 |
+
examples/data/P62593_emb_esm1v --repr_layers 33 --include mean
|
| 443 |
+
```
|
| 444 |
+
|
| 445 |
+
Then, follow the remaining instructions in the tutorial. You can also run the tutorial in a [colab notebook](https://colab.research.google.com/github/facebookresearch/esm/blob/main/examples/sup_variant_prediction.ipynb).
|
| 446 |
+
|
| 447 |
+
**Note, alternatively use [the newer instructions for zero-shot variant prediction](examples/variant-prediction/),
|
| 448 |
+
which predicts mutational effects without any supervised training.**
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
### Unsupervised contact prediction
|
| 452 |
+
[<img src="https://colab.research.google.com/assets/colab-badge.svg">](https://colab.research.google.com/github/facebookresearch/esm/blob/main/examples/contact_prediction.ipynb)
|
| 453 |
+
|
| 454 |
+
This [jupyter notebook tutorial](examples/contact_prediction.ipynb) demonstrates contact prediction with both the ESM-2 and MSA Transformer (ESM-MSA-1) models.
|
| 455 |
+
Contact prediction is based on a logistic regression over the model's attention maps.
|
| 456 |
+
This methodology is based on our ICLR 2021 paper,
|
| 457 |
+
[Transformer protein language models are unsupervised structure learners. (Rao et al. 2020)](https://doi.org/10.1101/2020.12.15.422761)
|
| 458 |
+
The MSA Transformer (ESM-MSA-1) takes a multiple sequence alignment (MSA) as input, and uses the tied row self-attention maps in the same way.
|
| 459 |
+
See [MSA Transformer. (Rao et al. 2021)](https://www.biorxiv.org/content/10.1101/2021.02.12.430858v1).
|
| 460 |
+
|
| 461 |
+
To get unsupervised attention-based contacts, call `model.predict_contacts(tokens)` or `model(tokens, return_contacts=True)`.
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
### ESMStructuralSplitDataset and self-attention contact prediction
|
| 465 |
+
[<img src="https://colab.research.google.com/assets/colab-badge.svg">](https://colab.research.google.com/github/facebookresearch/esm/blob/main/examples/esm_structural_dataset.ipynb)
|
| 466 |
+
|
| 467 |
+
And this [jupyter notebook tutorial](examples/esm_structural_dataset.ipynb) shows how to load and index the `ESMStructuralSplitDataset`,
|
| 468 |
+
and computes the self-attention map unsupervised contact predictions using ESM-2.
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
## Available Models and Datasets <a name="available"></a>
|
| 472 |
+
|
| 473 |
+
### Pre-trained Models <a name="available-models"></a>
|
| 474 |
+
|
| 475 |
+
| Shorthand | `esm.pretrained.` | #layers | #params | Dataset | Embedding Dim | Model URL (automatically downloaded to `~/.cache/torch/hub/checkpoints`) |
|
| 476 |
+
|-----------|---------------------|---------|-------------|---------|---------------|-----------------------------------------------------------------------|
|
| 477 |
+
| ESM-2 | `esm2_t48_15B_UR50D` | 48 | 15B | UR50/D 2021_04 | 5120 | https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t48_15B_UR50D.pt |
|
| 478 |
+
| | `esm2_t36_3B_UR50D` | 36 | 3B | UR50/D 2021_04 | 2560 | https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t36_3B_UR50D.pt |
|
| 479 |
+
| | `esm2_t33_650M_UR50D` | 33 | 650M | UR50/D 2021_04 | 1280 | https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t33_650M_UR50D.pt |
|
| 480 |
+
| | `esm2_t30_150M_UR50D` | 30 | 150M | UR50/D 2021_04 | 640 | https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t30_150M_UR50D.pt |
|
| 481 |
+
| | `esm2_t12_35M_UR50D` | 12 | 35M | UR50/D 2021_04 | 480 | https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t12_35M_UR50D.pt |
|
| 482 |
+
| | `esm2_t6_8M_UR50D` | 6 | 8M | UR50/D 2021_04 | 320 | https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t6_8M_UR50D.pt |
|
| 483 |
+
| ESMFold | `esmfold_v1` | 48 (+36) | 690M (+3B) | UR50/D 2021_04 | - | https://dl.fbaipublicfiles.com/fair-esm/models/esmfold_3B_v1.pt |
|
| 484 |
+
| | `esmfold_v0` | 48 (+36) | 690M (+3B) | UR50/D 2021_04 | - | https://dl.fbaipublicfiles.com/fair-esm/models/esmfold_3B_v0.pt |
|
| 485 |
+
| | `esmfold_structure_module_only_*` | 0 (+various) | various | UR50/D 2021_04 | - | https://dl.fbaipublicfiles.com/fair-esm/models/esmfold_structure_module_only_* |
|
| 486 |
+
| ESM-IF1 | `esm_if1_gvp4_t16_142M_UR50` | 20 | 124M | CATH 4.3 + predicted structures for UR50 | 512 | https://dl.fbaipublicfiles.com/fair-esm/models/esm_if1_gvp4_t16_142M_UR50.pt |
|
| 487 |
+
| ESM-1v | `esm1v_t33_650M_UR90S_[1-5]` | 33 | 650M | UR90/S 2020_03 | 1280 | https://dl.fbaipublicfiles.com/fair-esm/models/esm1v_t33_650M_UR90S_1.pt |
|
| 488 |
+
| ESM-MSA-1b| `esm_msa1b_t12_100M_UR50S` | 12 | 100M | UR50/S + MSA 2018_03 | 768 | https://dl.fbaipublicfiles.com/fair-esm/models/esm_msa1b_t12_100M_UR50S.pt |
|
| 489 |
+
| ESM-MSA-1 | `esm_msa1_t12_100M_UR50S` | 12 | 100M | UR50/S + MSA 2018_03 | 768 | https://dl.fbaipublicfiles.com/fair-esm/models/esm_msa1_t12_100M_UR50S.pt |
|
| 490 |
+
| ESM-1b | `esm1b_t33_650M_UR50S` | 33 | 650M | UR50/S 2018_03 | 1280 | https://dl.fbaipublicfiles.com/fair-esm/models/esm1b_t33_650M_UR50S.pt |
|
| 491 |
+
| ESM-1 | `esm1_t34_670M_UR50S` | 34 | 670M | UR50/S 2018_03 | 1280 | https://dl.fbaipublicfiles.com/fair-esm/models/esm1_t34_670M_UR50S.pt |
|
| 492 |
+
| | `esm1_t34_670M_UR50D` | 34 | 670M | UR50/D 2018_03 | 1280 | https://dl.fbaipublicfiles.com/fair-esm/models/esm1_t34_670M_UR50D.pt |
|
| 493 |
+
| | `esm1_t34_670M_UR100` | 34 | 670M | UR100 2018_03 | 1280 | https://dl.fbaipublicfiles.com/fair-esm/models/esm1_t34_670M_UR100.pt |
|
| 494 |
+
| | `esm1_t12_85M_UR50S` | 12 | 85M | UR50/S 2018_03 | 768 | https://dl.fbaipublicfiles.com/fair-esm/models/esm1_t12_85M_UR50S.pt |
|
| 495 |
+
| | `esm1_t6_43M_UR50S` | 6 | 43M | UR50/S 2018_03 | 768 | https://dl.fbaipublicfiles.com/fair-esm/models/esm1_t6_43M_UR50S.pt |
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
Here is a chronological list of the released models and the paper they were introduced in:
|
| 499 |
+
|
| 500 |
+
| Shorthand | Release Notes |
|
| 501 |
+
|------------|---------------|
|
| 502 |
+
| ESM-1 | Released with Rives et al. 2019 (Aug 2020 update). |
|
| 503 |
+
| ESM-1b | Released with Rives et al. 2019 (Dec 2020 update). See Appendix B. |
|
| 504 |
+
| ESM-MSA-1 | Released with Rao et al. 2021 (Preprint v1). |
|
| 505 |
+
| ESM-MSA-1b | Released with Rao et al. 2021 (ICML'21 version, June 2021). |
|
| 506 |
+
| ESM-1v | Released with Meier et al. 2021. |
|
| 507 |
+
| ESM-IF1 | Released with Hsu et al. 2022. |
|
| 508 |
+
| ESM-2 | Released with Lin et al. 2022. |
|
| 509 |
+
|
| 510 |
+
### ESM Structural Split Dataset <a name="available-esmssd"></a>
|
| 511 |
+
This is a five-fold cross validation dataset of protein domain structures that can be used to measure generalization of representations
|
| 512 |
+
across different levels of structural dissimilarity.
|
| 513 |
+
The dataset implements structural holdouts at the family, superfamily, and fold
|
| 514 |
+
level. The SCOPe database is used to classify domains. Independently for each level of structural hold-out,
|
| 515 |
+
the domains are split into 5 equal sets, i.e. five sets of folds, superfamilies, or families. This ensures
|
| 516 |
+
that for each of the five partitions, structures having the same classification do not appear in both the
|
| 517 |
+
train and test sets. For a given classification level each structure appears in a test set once, so that
|
| 518 |
+
in the cross validation experiment each of the structures will be evaluated exactly once.
|
| 519 |
+
|
| 520 |
+
The dataset provides 3d coordinates, distance maps, and secondary structure labels.
|
| 521 |
+
For further details on the construction of the dataset
|
| 522 |
+
see [Rives et al. 2019](https://doi.org/10.1101/622803) Appendix A.10.
|
| 523 |
+
|
| 524 |
+
This [jupyter notebook tutorial](examples/esm_structural_dataset.ipynb) shows how to load and index the `ESMStructuralSplitDataset`.
|
| 525 |
+
|
| 526 |
+
`ESMStructuralSplitDataset`, upon initializing, will download `splits` and `pkl`.
|
| 527 |
+
We also provide `msas` for each of the domains. The data can be directly downloaded below.
|
| 528 |
+
|
| 529 |
+
| Name | Description | URL |
|
| 530 |
+
|--------|-------------------------------------------------------------------------------|-----------------------------------------------------------------------|
|
| 531 |
+
| splits | train/valid splits | https://dl.fbaipublicfiles.com/fair-esm/structural-data/splits.tar.gz |
|
| 532 |
+
| pkl | pkl objects containing sequence, SSP labels, distance map, and 3d coordinates | https://dl.fbaipublicfiles.com/fair-esm/structural-data/pkl.tar.gz |
|
| 533 |
+
| msas | a3m files containing MSA for each domain | https://dl.fbaipublicfiles.com/fair-esm/structural-data/msas.tar.gz |
|
| 534 |
+
|
| 535 |
+
### Pre-training Dataset Split <a name="available-pretraining-split"></a>
|
| 536 |
+
The split files establishing which UniRef50 clusters were used as held-out evaluation set for pre-training
|
| 537 |
+
in [Rives et al. 2019](https://doi.org/10.1101/622803) and [Rao et al. 2021](https://doi.org/10.1101/2021.02.12.430858) can be found here:
|
| 538 |
+
* [UniRef50 IDs of evaluation set](https://dl.fbaipublicfiles.com/fair-esm/pretraining-data/uniref201803_ur50_valid_headers.txt.gz): 3.016 M clusters
|
| 539 |
+
* [UniRef100 IDs of evaluation set](https://dl.fbaipublicfiles.com/fair-esm/pretraining-data/uniref201803_ur100_valid_headers.txt.gz): 13.745 M proteins, expanding the same UniRef50 clusters.
|
| 540 |
+
|
| 541 |
+
These files only contain only the UniRef50 IDs and UniRef100 IDs corresponding to the [UniRef database, 2018-03 release](https://ftp.uniprot.org/pub/databases/uniprot/previous_releases/release-2018_03/uniref/)
|
| 542 |
+
which is released by the UniProt Consortium under a [Creative Commons Attribution (CC BY 4.0) License](https://www.uniprot.org/help/license).
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
### Comparison to related works <a name="perf_related"></a>
|
| 546 |
+
<!--
|
| 547 |
+
DO NOT EDIT THIS TABLE! This is the source of truth:
|
| 548 |
+
https://docs.google.com/spreadsheets/d/1RPvWF47rIMEr-Jg-SRCoGElHcwCl5d7RyEeSyPgp59A/edit#gid=0
|
| 549 |
+
exported via https://www.tablesgenerator.com/html_tables
|
| 550 |
+
-->
|
| 551 |
+
|
| 552 |
+
<table class="tg">
|
| 553 |
+
<thead>
|
| 554 |
+
<tr>
|
| 555 |
+
<th class="tg-0thz"><span style="font-weight:bold">Task</span></th>
|
| 556 |
+
<th class="tg-j6zm" colspan="3"><span style="font-weight:bold">Unsupervised contact prediction</span></th>
|
| 557 |
+
<th class="tg-j6zm" colspan="2"><span style="font-weight:bold">Structure Prediction</span></th>
|
| 558 |
+
</tr>
|
| 559 |
+
</thead>
|
| 560 |
+
<tbody>
|
| 561 |
+
<tr>
|
| 562 |
+
<td class="tg-j6zm"><span style="font-weight:bold">Test set</span></td>
|
| 563 |
+
<td class="tg-j6zm"><span style="font-weight:bold">Large valid</span></td>
|
| 564 |
+
<td class="tg-j6zm"><span style="font-weight:bold">CASP14</span></td>
|
| 565 |
+
<td class="tg-j6zm"><span style="font-weight:bold">CAMEO (Apr-Jun 2022)</span></td>
|
| 566 |
+
<td class="tg-j6zm"><span style="font-weight:bold">CASP14</span></td>
|
| 567 |
+
<td class="tg-j6zm"><span style="font-weight:bold">CAMEO (Apr-Jun 2022)</span></td>
|
| 568 |
+
</tr>
|
| 569 |
+
<tr>
|
| 570 |
+
<td class="tg-7zrl">Gremlin (Potts)</td>
|
| 571 |
+
<td class="tg-7zrl">39.3</td>
|
| 572 |
+
<td class="tg-7zrl"></td>
|
| 573 |
+
<td class="tg-7zrl"></td>
|
| 574 |
+
<td class="tg-7zrl"></td>
|
| 575 |
+
<td class="tg-7zrl"></td>
|
| 576 |
+
</tr>
|
| 577 |
+
<tr>
|
| 578 |
+
<td class="tg-7zrl">TAPE</td>
|
| 579 |
+
<td class="tg-7zrl">11.2</td>
|
| 580 |
+
<td class="tg-7zrl"></td>
|
| 581 |
+
<td class="tg-7zrl"></td>
|
| 582 |
+
<td class="tg-7zrl"></td>
|
| 583 |
+
<td class="tg-7zrl"></td>
|
| 584 |
+
</tr>
|
| 585 |
+
<tr>
|
| 586 |
+
<td class="tg-7zrl">ProtBert-BFD</td>
|
| 587 |
+
<td class="tg-7zrl">34.1</td>
|
| 588 |
+
<td class="tg-7zrl"></td>
|
| 589 |
+
<td class="tg-7zrl"></td>
|
| 590 |
+
<td class="tg-7zrl"></td>
|
| 591 |
+
<td class="tg-7zrl"></td>
|
| 592 |
+
</tr>
|
| 593 |
+
<tr>
|
| 594 |
+
<td class="tg-7zrl">Prot-T5-XL-BFD</td>
|
| 595 |
+
<td class="tg-7zrl">35.6</td>
|
| 596 |
+
<td class="tg-7zrl"></td>
|
| 597 |
+
<td class="tg-7zrl"></td>
|
| 598 |
+
<td class="tg-2b7s">46.1</td>
|
| 599 |
+
<td class="tg-2b7s">62.6</td>
|
| 600 |
+
</tr>
|
| 601 |
+
<tr>
|
| 602 |
+
<td class="tg-7zrl">Prot-T5-XL-Ur50 (3B)</td>
|
| 603 |
+
<td class="tg-7zrl">47.9</td>
|
| 604 |
+
<td class="tg-7zrl"></td>
|
| 605 |
+
<td class="tg-7zrl"></td>
|
| 606 |
+
<td class="tg-2b7s">49.8</td>
|
| 607 |
+
<td class="tg-2b7s">69.4</td>
|
| 608 |
+
</tr>
|
| 609 |
+
<tr>
|
| 610 |
+
<td class="tg-7zrl">ESM-1</td>
|
| 611 |
+
<td class="tg-7zrl">33.7</td>
|
| 612 |
+
<td class="tg-7zrl"></td>
|
| 613 |
+
<td class="tg-7zrl"></td>
|
| 614 |
+
<td class="tg-7zrl"></td>
|
| 615 |
+
<td class="tg-7zrl"></td>
|
| 616 |
+
</tr>
|
| 617 |
+
<tr>
|
| 618 |
+
<td class="tg-7zrl">ESM-1b</td>
|
| 619 |
+
<td class="tg-7zrl">41.1</td>
|
| 620 |
+
<td class="tg-7zrl">24.4</td>
|
| 621 |
+
<td class="tg-7zrl">39</td>
|
| 622 |
+
<td class="tg-2b7s">41.6</td>
|
| 623 |
+
<td class="tg-2b7s">64.5</td>
|
| 624 |
+
</tr>
|
| 625 |
+
<tr>
|
| 626 |
+
<td class="tg-7zrl">ESM-1v</td>
|
| 627 |
+
<td class="tg-7zrl">35.3</td>
|
| 628 |
+
<td class="tg-7zrl"></td>
|
| 629 |
+
<td class="tg-7zrl"></td>
|
| 630 |
+
<td class="tg-7zrl"></td>
|
| 631 |
+
<td class="tg-7zrl"></td>
|
| 632 |
+
</tr>
|
| 633 |
+
<tr>
|
| 634 |
+
<td class="tg-7zrl">ESM-MSA-1b</td>
|
| 635 |
+
<td class="tg-7zrl">57.4</td>
|
| 636 |
+
<td class="tg-7zrl"></td>
|
| 637 |
+
<td class="tg-7zrl"></td>
|
| 638 |
+
<td class="tg-7zrl"></td>
|
| 639 |
+
<td class="tg-7zrl"></td>
|
| 640 |
+
</tr>
|
| 641 |
+
<tr>
|
| 642 |
+
<td class="tg-7zrl">ESM-2 (8M)</td>
|
| 643 |
+
<td class="tg-7zrl">15.9</td>
|
| 644 |
+
<td class="tg-7zrl">9.8</td>
|
| 645 |
+
<td class="tg-7zrl">15.7</td>
|
| 646 |
+
<td class="tg-2b7s">36.7</td>
|
| 647 |
+
<td class="tg-2b7s">48.1</td>
|
| 648 |
+
</tr>
|
| 649 |
+
<tr>
|
| 650 |
+
<td class="tg-7zrl">ESM-2 (35M)</td>
|
| 651 |
+
<td class="tg-7zrl">28.8</td>
|
| 652 |
+
<td class="tg-7zrl">16.4</td>
|
| 653 |
+
<td class="tg-7zrl">28.4</td>
|
| 654 |
+
<td class="tg-2b7s">41.4</td>
|
| 655 |
+
<td class="tg-2b7s">56.4</td>
|
| 656 |
+
</tr>
|
| 657 |
+
<tr>
|
| 658 |
+
<td class="tg-7zrl">ESM-2 (150M)</td>
|
| 659 |
+
<td class="tg-7zrl">42.2</td>
|
| 660 |
+
<td class="tg-7zrl">26.8</td>
|
| 661 |
+
<td class="tg-7zrl">40.1</td>
|
| 662 |
+
<td class="tg-2b7s">49.0</td>
|
| 663 |
+
<td class="tg-2b7s">64.9</td>
|
| 664 |
+
</tr>
|
| 665 |
+
<tr>
|
| 666 |
+
<td class="tg-7zrl">ESM-2 (700M)</td>
|
| 667 |
+
<td class="tg-7zrl">50.1</td>
|
| 668 |
+
<td class="tg-7zrl">32.5</td>
|
| 669 |
+
<td class="tg-7zrl">47.6</td>
|
| 670 |
+
<td class="tg-2b7s">51.3</td>
|
| 671 |
+
<td class="tg-2b7s">70.1</td>
|
| 672 |
+
</tr>
|
| 673 |
+
<tr>
|
| 674 |
+
<td class="tg-7zrl">ESM-2 (3B)</td>
|
| 675 |
+
<td class="tg-7zrl">52.7</td>
|
| 676 |
+
<td class="tg-7zrl">34.0</td>
|
| 677 |
+
<td class="tg-7zrl">49.9</td>
|
| 678 |
+
<td class="tg-2b7s">52.5</td>
|
| 679 |
+
<td class="tg-2b7s">71.8</td>
|
| 680 |
+
</tr>
|
| 681 |
+
<tr>
|
| 682 |
+
<td class="tg-7zrl">ESM-2 (15B)</td>
|
| 683 |
+
<td class="tg-7zrl">54.5</td>
|
| 684 |
+
<td class="tg-7zrl">37.0</td>
|
| 685 |
+
<td class="tg-7zrl">51.7</td>
|
| 686 |
+
<td class="tg-2b7s">55.4</td>
|
| 687 |
+
<td class="tg-2b7s">72.1</td>
|
| 688 |
+
</tr>
|
| 689 |
+
</tbody>
|
| 690 |
+
</table>
|
| 691 |
+
|
| 692 |
+
Comparison to related protein language models on structure prediction tasks.
|
| 693 |
+
|
| 694 |
+
* All contact numbers are the top-L,LR precision metric, where long range means sequence separation of at least 24 residues
|
| 695 |
+
* For unsupervised contact prediction, a sparse linear combination of the attention heads is used to directly predict protein contacts,
|
| 696 |
+
fitted with logistic regression on 20 structures.
|
| 697 |
+
For more details on the method, see [Rao et al. 2020](https://doi.org/10.1101/2020.12.15.422761).
|
| 698 |
+
* For structure prediction, an AlphaFold2 structure module is trained directly from the frozen language model embeddings.
|
| 699 |
+
For more details on the method, see [Lin et al. 2022](https://www.science.org/doi/abs/10.1126/science.ade2574).
|
| 700 |
+
* Direct coupling analysis methods (Gremlin, mfDCA, Psicov) and ESM-MSA-1 use the [trRosetta MSAs](https://yanglab.nankai.edu.cn/trRosetta/benchmark/), while other methods predict from single sequence.
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
## Citations <a name="citations"></a>
|
| 704 |
+
|
| 705 |
+
If you find the models useful in your research, we ask that you cite the relevant paper:
|
| 706 |
+
|
| 707 |
+
```bibtex
|
| 708 |
+
@article{rives2019biological,
|
| 709 |
+
author={Rives, Alexander and Meier, Joshua and Sercu, Tom and Goyal, Siddharth and Lin, Zeming and Liu, Jason and Guo, Demi and Ott, Myle and Zitnick, C. Lawrence and Ma, Jerry and Fergus, Rob},
|
| 710 |
+
title={Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 Million Protein Sequences},
|
| 711 |
+
year={2019},
|
| 712 |
+
doi={10.1101/622803},
|
| 713 |
+
url={https://www.biorxiv.org/content/10.1101/622803v4},
|
| 714 |
+
journal={PNAS}
|
| 715 |
+
}
|
| 716 |
+
```
|
| 717 |
+
|
| 718 |
+
For the self-attention contact prediction:
|
| 719 |
+
|
| 720 |
+
```bibtex
|
| 721 |
+
@article{rao2020transformer,
|
| 722 |
+
author = {Rao, Roshan M and Meier, Joshua and Sercu, Tom and Ovchinnikov, Sergey and Rives, Alexander},
|
| 723 |
+
title={Transformer protein language models are unsupervised structure learners},
|
| 724 |
+
year={2020},
|
| 725 |
+
doi={10.1101/2020.12.15.422761},
|
| 726 |
+
url={https://www.biorxiv.org/content/10.1101/2020.12.15.422761v1},
|
| 727 |
+
journal={bioRxiv}
|
| 728 |
+
}
|
| 729 |
+
```
|
| 730 |
+
|
| 731 |
+
For the MSA Transformer:
|
| 732 |
+
|
| 733 |
+
```bibtex
|
| 734 |
+
@article{rao2021msa,
|
| 735 |
+
author = {Rao, Roshan and Liu, Jason and Verkuil, Robert and Meier, Joshua and Canny, John F. and Abbeel, Pieter and Sercu, Tom and Rives, Alexander},
|
| 736 |
+
title={MSA Transformer},
|
| 737 |
+
year={2021},
|
| 738 |
+
doi={10.1101/2021.02.12.430858},
|
| 739 |
+
url={https://www.biorxiv.org/content/10.1101/2021.02.12.430858v1},
|
| 740 |
+
journal={bioRxiv}
|
| 741 |
+
}
|
| 742 |
+
```
|
| 743 |
+
|
| 744 |
+
For variant prediction using ESM-1v:
|
| 745 |
+
|
| 746 |
+
```bibtex
|
| 747 |
+
@article{meier2021language,
|
| 748 |
+
author = {Meier, Joshua and Rao, Roshan and Verkuil, Robert and Liu, Jason and Sercu, Tom and Rives, Alexander},
|
| 749 |
+
title = {Language models enable zero-shot prediction of the effects of mutations on protein function},
|
| 750 |
+
year={2021},
|
| 751 |
+
doi={10.1101/2021.07.09.450648},
|
| 752 |
+
url={https://www.biorxiv.org/content/10.1101/2021.07.09.450648v1},
|
| 753 |
+
journal={bioRxiv}
|
| 754 |
+
}
|
| 755 |
+
```
|
| 756 |
+
|
| 757 |
+
For inverse folding using ESM-IF1:
|
| 758 |
+
|
| 759 |
+
```bibtex
|
| 760 |
+
@article{hsu2022learning,
|
| 761 |
+
author = {Hsu, Chloe and Verkuil, Robert and Liu, Jason and Lin, Zeming and Hie, Brian and Sercu, Tom and Lerer, Adam and Rives, Alexander},
|
| 762 |
+
title = {Learning inverse folding from millions of predicted structures},
|
| 763 |
+
year = {2022},
|
| 764 |
+
doi = {10.1101/2022.04.10.487779},
|
| 765 |
+
url = {https://www.biorxiv.org/content/early/2022/04/10/2022.04.10.487779},
|
| 766 |
+
journal = {ICML}
|
| 767 |
+
}
|
| 768 |
+
```
|
| 769 |
+
|
| 770 |
+
For the ESM-2 language model and ESMFold:
|
| 771 |
+
|
| 772 |
+
```bibtex
|
| 773 |
+
@article{lin2022language,
|
| 774 |
+
title={Language models of protein sequences at the scale of evolution enable accurate structure prediction},
|
| 775 |
+
author={Lin, Zeming and Akin, Halil and Rao, Roshan and Hie, Brian and Zhu, Zhongkai and Lu, Wenting and Smetanin, Nikita and dos Santos Costa, Allan and Fazel-Zarandi, Maryam and Sercu, Tom and Candido, Sal and others},
|
| 776 |
+
journal={bioRxiv},
|
| 777 |
+
year={2022},
|
| 778 |
+
publisher={Cold Spring Harbor Laboratory}
|
| 779 |
+
}
|
| 780 |
+
```
|
| 781 |
+
|
| 782 |
+
Much of this code builds on the [fairseq](https://github.com/pytorch/fairseq) sequence modeling framework. We use fairseq internally for our protein language modeling research. We highly recommend trying it out if you'd like to pre-train protein language models from scratch.
|
| 783 |
+
|
| 784 |
+
Additionally, if you would like to use the variant prediction benchmark from Meier et al. (2021), we provide a bibtex file with citations for all data in [./examples/variant-prediction/mutation_data.bib](./examples/variant-prediction/mutation_data.bib). You can cite each paper individually, or add all citations in bulk using the LaTeX command:
|
| 785 |
+
|
| 786 |
+
```tex
|
| 787 |
+
\nocite{wrenbeck2017deep,klesmith2015comprehensive,haddox2018mapping,romero2015dissecting,firnberg2014comprehensive,deng2012deep,stiffler2015evolvability,jacquier2013capturing,findlay2018comprehensive,mclaughlin2012spatial,kitzman2015massively,doud2016accurate,pokusaeva2019experimental,mishra2016systematic,kelsic2016rna,melnikov2014comprehensive,brenan2016phenotypic,rockah2015systematic,wu2015functional,aakre2015evolving,qi2014quantitative,matreyek2018multiplex,bandaru2017deconstruction,roscoe2013analyses,roscoe2014systematic,mavor2016determination,chan2017correlation,melamed2013deep,starita2013activity,araya2012fundamental}
|
| 788 |
+
```
|
| 789 |
+
|
| 790 |
+
## License <a name="license"></a>
|
| 791 |
+
|
| 792 |
+
This source code is licensed under the MIT license found in the `LICENSE` file
|
| 793 |
+
in the root directory of this source tree.
|
| 794 |
+
|
| 795 |
+
ESM Metagenomic Atlas (also referred to as “ESM Metagenomic Structure Atlas” or “ESM Atlas”) data is available under a CC BY 4.0 license for academic and commercial use. Copyright (c) Meta Platforms, Inc. All Rights Reserved. Use of the ESM Metagenomic Atlas data is subject to the Meta Open Source [Terms of Use](https://opensource.fb.com/legal/terms/) and [Privacy Policy](https://opensource.fb.com/legal/privacy/).
|
weight/esm-main/__pycache__/hubconf.cpython-311.pyc
ADDED
|
Binary file (1.83 kB). View file
|
|
|
weight/esm-main/environment.yml
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: esmfold
|
| 2 |
+
channels:
|
| 3 |
+
- conda-forge
|
| 4 |
+
- bioconda
|
| 5 |
+
- pytorch
|
| 6 |
+
dependencies:
|
| 7 |
+
- conda-forge::python=3.7
|
| 8 |
+
- conda-forge::setuptools=59.5.0
|
| 9 |
+
- conda-forge::pip
|
| 10 |
+
- conda-forge::openmm=7.5.1
|
| 11 |
+
- conda-forge::pdbfixer
|
| 12 |
+
- conda-forge::cudatoolkit==11.3.*
|
| 13 |
+
- conda-forge::einops
|
| 14 |
+
- conda-forge::fairscale
|
| 15 |
+
- conda-forge::omegaconf
|
| 16 |
+
- conda-forge::hydra-core
|
| 17 |
+
- conda-forge::pandas
|
| 18 |
+
- conda-forge::pytest
|
| 19 |
+
- bioconda::hmmer==3.3.2
|
| 20 |
+
- bioconda::hhsuite==3.3.0
|
| 21 |
+
- bioconda::kalign2==2.04
|
| 22 |
+
- pytorch::pytorch=1.12.*
|
| 23 |
+
- pip:
|
| 24 |
+
- biopython==1.79
|
| 25 |
+
- deepspeed==0.5.9
|
| 26 |
+
- dm-tree==0.1.6
|
| 27 |
+
- ml-collections==0.1.0
|
| 28 |
+
- numpy==1.21.2
|
| 29 |
+
- PyYAML==5.4.1
|
| 30 |
+
- requests==2.26.0
|
| 31 |
+
- scipy==1.7.1
|
| 32 |
+
- tqdm==4.62.2
|
| 33 |
+
- typing-extensions==3.10.0.2
|
| 34 |
+
- pytorch_lightning==1.5.10
|
| 35 |
+
- wandb==0.12.21
|
| 36 |
+
- git+https://github.com/NVIDIA/dllogger.git
|
weight/esm-main/esm/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
from .version import version as __version__ # noqa
|
| 7 |
+
|
| 8 |
+
from .data import Alphabet, BatchConverter, FastaBatchedDataset # noqa
|
| 9 |
+
from .model.esm1 import ProteinBertModel # noqa
|
| 10 |
+
from .model.esm2 import ESM2 # noqa
|
| 11 |
+
from .model.msa_transformer import MSATransformer #noqa
|
| 12 |
+
from . import pretrained # noqa
|
weight/esm-main/esm/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (630 Bytes). View file
|
|
|
weight/esm-main/esm/__pycache__/axial_attention.cpython-311.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
weight/esm-main/esm/__pycache__/constants.cpython-311.pyc
ADDED
|
Binary file (342 Bytes). View file
|
|
|
weight/esm-main/esm/__pycache__/data.cpython-311.pyc
ADDED
|
Binary file (27.1 kB). View file
|
|
|
weight/esm-main/esm/__pycache__/modules.cpython-311.pyc
ADDED
|
Binary file (23.7 kB). View file
|
|
|
weight/esm-main/esm/__pycache__/multihead_attention.cpython-311.pyc
ADDED
|
Binary file (24.8 kB). View file
|
|
|
weight/esm-main/esm/__pycache__/pretrained.cpython-311.pyc
ADDED
|
Binary file (29.7 kB). View file
|
|
|
weight/esm-main/esm/__pycache__/rotary_embedding.cpython-311.pyc
ADDED
|
Binary file (4.48 kB). View file
|
|
|
weight/esm-main/esm/__pycache__/version.cpython-311.pyc
ADDED
|
Binary file (219 Bytes). View file
|
|
|
weight/esm-main/esm/axial_attention.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class RowSelfAttention(nn.Module):
|
| 12 |
+
"""Compute self-attention over rows of a 2D input."""
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
embed_dim,
|
| 17 |
+
num_heads,
|
| 18 |
+
dropout=0.0,
|
| 19 |
+
max_tokens_per_msa: int = 2 ** 16,
|
| 20 |
+
):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.num_heads = num_heads
|
| 23 |
+
self.dropout = dropout
|
| 24 |
+
self.head_dim = embed_dim // num_heads
|
| 25 |
+
self.scaling = self.head_dim ** -0.5
|
| 26 |
+
self.max_tokens_per_msa = max_tokens_per_msa
|
| 27 |
+
self.attn_shape = "hnij"
|
| 28 |
+
|
| 29 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim)
|
| 30 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim)
|
| 31 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim)
|
| 32 |
+
|
| 33 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim)
|
| 34 |
+
self.dropout_module = nn.Dropout(dropout)
|
| 35 |
+
|
| 36 |
+
def align_scaling(self, q):
|
| 37 |
+
num_rows = q.size(0)
|
| 38 |
+
return self.scaling / math.sqrt(num_rows)
|
| 39 |
+
|
| 40 |
+
def _batched_forward(
|
| 41 |
+
self,
|
| 42 |
+
x,
|
| 43 |
+
self_attn_mask=None,
|
| 44 |
+
self_attn_padding_mask=None,
|
| 45 |
+
):
|
| 46 |
+
num_rows, num_cols, batch_size, embed_dim = x.size()
|
| 47 |
+
max_rows = max(1, self.max_tokens_per_msa // num_cols)
|
| 48 |
+
attns = 0
|
| 49 |
+
scaling = self.align_scaling(x)
|
| 50 |
+
for start in range(0, num_rows, max_rows):
|
| 51 |
+
attn_weights = self.compute_attention_weights(
|
| 52 |
+
x[start : start + max_rows],
|
| 53 |
+
scaling,
|
| 54 |
+
self_attn_mask=self_attn_mask,
|
| 55 |
+
self_attn_padding_mask=self_attn_padding_mask[:, start : start + max_rows]
|
| 56 |
+
if self_attn_padding_mask is not None
|
| 57 |
+
else None,
|
| 58 |
+
)
|
| 59 |
+
attns += attn_weights
|
| 60 |
+
attn_probs = attns.softmax(-1)
|
| 61 |
+
attn_probs = self.dropout_module(attn_probs)
|
| 62 |
+
|
| 63 |
+
outputs = []
|
| 64 |
+
for start in range(0, num_rows, max_rows):
|
| 65 |
+
output = self.compute_attention_update(x[start : start + max_rows], attn_probs)
|
| 66 |
+
outputs.append(output)
|
| 67 |
+
|
| 68 |
+
output = torch.cat(outputs, 0)
|
| 69 |
+
return output, attn_probs
|
| 70 |
+
|
| 71 |
+
def compute_attention_weights(
|
| 72 |
+
self,
|
| 73 |
+
x,
|
| 74 |
+
scaling: float,
|
| 75 |
+
self_attn_mask=None,
|
| 76 |
+
self_attn_padding_mask=None,
|
| 77 |
+
):
|
| 78 |
+
num_rows, num_cols, batch_size, embed_dim = x.size()
|
| 79 |
+
q = self.q_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim)
|
| 80 |
+
k = self.k_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim)
|
| 81 |
+
q *= scaling
|
| 82 |
+
if self_attn_padding_mask is not None:
|
| 83 |
+
# Zero out any padded aligned positions - this is important since
|
| 84 |
+
# we take a sum across the alignment axis.
|
| 85 |
+
q *= 1 - self_attn_padding_mask.permute(1, 2, 0).unsqueeze(3).unsqueeze(4).to(q)
|
| 86 |
+
|
| 87 |
+
attn_weights = torch.einsum(f"rinhd,rjnhd->{self.attn_shape}", q, k)
|
| 88 |
+
|
| 89 |
+
if self_attn_mask is not None:
|
| 90 |
+
raise NotImplementedError
|
| 91 |
+
# Mask Size: [B x R x C], Weights Size: [H x B x C x C]
|
| 92 |
+
|
| 93 |
+
if self_attn_padding_mask is not None:
|
| 94 |
+
attn_weights = attn_weights.masked_fill(
|
| 95 |
+
self_attn_padding_mask[:, 0].unsqueeze(0).unsqueeze(2),
|
| 96 |
+
-10000,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
return attn_weights
|
| 100 |
+
|
| 101 |
+
def compute_attention_update(
|
| 102 |
+
self,
|
| 103 |
+
x,
|
| 104 |
+
attn_probs,
|
| 105 |
+
):
|
| 106 |
+
num_rows, num_cols, batch_size, embed_dim = x.size()
|
| 107 |
+
v = self.v_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim)
|
| 108 |
+
context = torch.einsum(f"{self.attn_shape},rjnhd->rinhd", attn_probs, v)
|
| 109 |
+
context = context.contiguous().view(num_rows, num_cols, batch_size, embed_dim)
|
| 110 |
+
output = self.out_proj(context)
|
| 111 |
+
return output
|
| 112 |
+
|
| 113 |
+
def forward(
|
| 114 |
+
self,
|
| 115 |
+
x,
|
| 116 |
+
self_attn_mask=None,
|
| 117 |
+
self_attn_padding_mask=None,
|
| 118 |
+
):
|
| 119 |
+
num_rows, num_cols, batch_size, embed_dim = x.size()
|
| 120 |
+
if (num_rows * num_cols > self.max_tokens_per_msa) and not torch.is_grad_enabled():
|
| 121 |
+
return self._batched_forward(x, self_attn_mask, self_attn_padding_mask)
|
| 122 |
+
else:
|
| 123 |
+
scaling = self.align_scaling(x)
|
| 124 |
+
attn_weights = self.compute_attention_weights(
|
| 125 |
+
x, scaling, self_attn_mask, self_attn_padding_mask
|
| 126 |
+
)
|
| 127 |
+
attn_probs = attn_weights.softmax(-1)
|
| 128 |
+
attn_probs = self.dropout_module(attn_probs)
|
| 129 |
+
output = self.compute_attention_update(x, attn_probs)
|
| 130 |
+
return output, attn_probs
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class ColumnSelfAttention(nn.Module):
|
| 134 |
+
"""Compute self-attention over columns of a 2D input."""
|
| 135 |
+
|
| 136 |
+
def __init__(
|
| 137 |
+
self,
|
| 138 |
+
embed_dim,
|
| 139 |
+
num_heads,
|
| 140 |
+
dropout=0.0,
|
| 141 |
+
max_tokens_per_msa: int = 2 ** 16,
|
| 142 |
+
):
|
| 143 |
+
super().__init__()
|
| 144 |
+
|
| 145 |
+
self.num_heads = num_heads
|
| 146 |
+
self.dropout = dropout
|
| 147 |
+
self.head_dim = embed_dim // num_heads
|
| 148 |
+
self.scaling = self.head_dim ** -0.5
|
| 149 |
+
self.max_tokens_per_msa = max_tokens_per_msa
|
| 150 |
+
|
| 151 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim)
|
| 152 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim)
|
| 153 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim)
|
| 154 |
+
|
| 155 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim)
|
| 156 |
+
self.dropout_module = nn.Dropout(dropout)
|
| 157 |
+
|
| 158 |
+
def _batched_forward(
|
| 159 |
+
self,
|
| 160 |
+
x,
|
| 161 |
+
self_attn_mask=None,
|
| 162 |
+
self_attn_padding_mask=None,
|
| 163 |
+
):
|
| 164 |
+
num_rows, num_cols, batch_size, embed_dim = x.size()
|
| 165 |
+
max_cols = max(1, self.max_tokens_per_msa // num_rows)
|
| 166 |
+
outputs = []
|
| 167 |
+
attns = []
|
| 168 |
+
for start in range(0, num_cols, max_cols):
|
| 169 |
+
output, attn = self(
|
| 170 |
+
x[:, start : start + max_cols],
|
| 171 |
+
self_attn_mask=self_attn_mask,
|
| 172 |
+
self_attn_padding_mask=self_attn_padding_mask[:, :, start : start + max_cols]
|
| 173 |
+
if self_attn_padding_mask is not None
|
| 174 |
+
else None,
|
| 175 |
+
)
|
| 176 |
+
outputs.append(output)
|
| 177 |
+
attns.append(attn)
|
| 178 |
+
output = torch.cat(outputs, 1)
|
| 179 |
+
attns = torch.cat(attns, 1)
|
| 180 |
+
return output, attns
|
| 181 |
+
|
| 182 |
+
def compute_attention_update(
|
| 183 |
+
self,
|
| 184 |
+
x,
|
| 185 |
+
self_attn_mask=None,
|
| 186 |
+
self_attn_padding_mask=None,
|
| 187 |
+
):
|
| 188 |
+
num_rows, num_cols, batch_size, embed_dim = x.size()
|
| 189 |
+
if num_rows == 1:
|
| 190 |
+
# if there is only 1 position, this is equivalent and doesn't break with padding
|
| 191 |
+
attn_probs = torch.ones(
|
| 192 |
+
self.num_heads,
|
| 193 |
+
num_cols,
|
| 194 |
+
batch_size,
|
| 195 |
+
num_rows,
|
| 196 |
+
num_rows,
|
| 197 |
+
device=x.device,
|
| 198 |
+
dtype=x.dtype,
|
| 199 |
+
)
|
| 200 |
+
output = self.out_proj(self.v_proj(x))
|
| 201 |
+
else:
|
| 202 |
+
q = self.q_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim)
|
| 203 |
+
k = self.k_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim)
|
| 204 |
+
v = self.v_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim)
|
| 205 |
+
q *= self.scaling
|
| 206 |
+
|
| 207 |
+
attn_weights = torch.einsum("icnhd,jcnhd->hcnij", q, k)
|
| 208 |
+
|
| 209 |
+
if self_attn_mask is not None:
|
| 210 |
+
raise NotImplementedError
|
| 211 |
+
if self_attn_padding_mask is not None:
|
| 212 |
+
attn_weights = attn_weights.masked_fill(
|
| 213 |
+
self_attn_padding_mask.permute(2, 0, 1).unsqueeze(0).unsqueeze(3),
|
| 214 |
+
-10000,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
attn_probs = attn_weights.softmax(-1)
|
| 218 |
+
attn_probs = self.dropout_module(attn_probs)
|
| 219 |
+
context = torch.einsum("hcnij,jcnhd->icnhd", attn_probs, v)
|
| 220 |
+
context = context.contiguous().view(num_rows, num_cols, batch_size, embed_dim)
|
| 221 |
+
output = self.out_proj(context)
|
| 222 |
+
return output, attn_probs
|
| 223 |
+
|
| 224 |
+
def forward(
|
| 225 |
+
self,
|
| 226 |
+
x,
|
| 227 |
+
self_attn_mask=None,
|
| 228 |
+
self_attn_padding_mask=None,
|
| 229 |
+
):
|
| 230 |
+
num_rows, num_cols, batch_size, embed_dim = x.size()
|
| 231 |
+
# if False and num_rows * num_cols > 2 ** 14 and not torch.is_grad_enabled():
|
| 232 |
+
if (num_rows * num_cols) > self.max_tokens_per_msa and not torch.is_grad_enabled():
|
| 233 |
+
return self._batched_forward(
|
| 234 |
+
x,
|
| 235 |
+
self_attn_mask,
|
| 236 |
+
self_attn_padding_mask,
|
| 237 |
+
)
|
| 238 |
+
else:
|
| 239 |
+
return self.compute_attention_update(x, self_attn_mask, self_attn_padding_mask)
|
weight/esm-main/esm/constants.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
# fmt: off
|
| 7 |
+
proteinseq_toks = {
|
| 8 |
+
'toks': ['L', 'A', 'G', 'V', 'S', 'E', 'R', 'T', 'I', 'D', 'P', 'K', 'Q', 'N', 'F', 'Y', 'M', 'H', 'W', 'C', 'X', 'B', 'U', 'Z', 'O', '.', '-']
|
| 9 |
+
}
|
| 10 |
+
# fmt: on
|
weight/esm-main/esm/data.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
import itertools
|
| 7 |
+
import os
|
| 8 |
+
from typing import Sequence, Tuple, List, Union
|
| 9 |
+
import pickle
|
| 10 |
+
import re
|
| 11 |
+
import shutil
|
| 12 |
+
import torch
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from esm.constants import proteinseq_toks
|
| 15 |
+
|
| 16 |
+
RawMSA = Sequence[Tuple[str, str]]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class FastaBatchedDataset(object):
|
| 20 |
+
def __init__(self, sequence_labels, sequence_strs):
|
| 21 |
+
self.sequence_labels = list(sequence_labels)
|
| 22 |
+
self.sequence_strs = list(sequence_strs)
|
| 23 |
+
|
| 24 |
+
@classmethod
|
| 25 |
+
def from_file(cls, fasta_file):
|
| 26 |
+
sequence_labels, sequence_strs = [], []
|
| 27 |
+
cur_seq_label = None
|
| 28 |
+
buf = []
|
| 29 |
+
|
| 30 |
+
def _flush_current_seq():
|
| 31 |
+
nonlocal cur_seq_label, buf
|
| 32 |
+
if cur_seq_label is None:
|
| 33 |
+
return
|
| 34 |
+
sequence_labels.append(cur_seq_label)
|
| 35 |
+
sequence_strs.append("".join(buf))
|
| 36 |
+
cur_seq_label = None
|
| 37 |
+
buf = []
|
| 38 |
+
|
| 39 |
+
with open(fasta_file, "r") as infile:
|
| 40 |
+
for line_idx, line in enumerate(infile):
|
| 41 |
+
if line.startswith(">"): # label line
|
| 42 |
+
_flush_current_seq()
|
| 43 |
+
line = line[1:].strip()
|
| 44 |
+
if len(line) > 0:
|
| 45 |
+
cur_seq_label = line
|
| 46 |
+
else:
|
| 47 |
+
cur_seq_label = f"seqnum{line_idx:09d}"
|
| 48 |
+
else: # sequence line
|
| 49 |
+
buf.append(line.strip())
|
| 50 |
+
|
| 51 |
+
_flush_current_seq()
|
| 52 |
+
|
| 53 |
+
assert len(set(sequence_labels)) == len(
|
| 54 |
+
sequence_labels
|
| 55 |
+
), "Found duplicate sequence labels"
|
| 56 |
+
|
| 57 |
+
return cls(sequence_labels, sequence_strs)
|
| 58 |
+
|
| 59 |
+
def __len__(self):
|
| 60 |
+
return len(self.sequence_labels)
|
| 61 |
+
|
| 62 |
+
def __getitem__(self, idx):
|
| 63 |
+
return self.sequence_labels[idx], self.sequence_strs[idx]
|
| 64 |
+
|
| 65 |
+
def get_batch_indices(self, toks_per_batch, extra_toks_per_seq=0):
|
| 66 |
+
sizes = [(len(s), i) for i, s in enumerate(self.sequence_strs)]
|
| 67 |
+
sizes.sort()
|
| 68 |
+
batches = []
|
| 69 |
+
buf = []
|
| 70 |
+
max_len = 0
|
| 71 |
+
|
| 72 |
+
def _flush_current_buf():
|
| 73 |
+
nonlocal max_len, buf
|
| 74 |
+
if len(buf) == 0:
|
| 75 |
+
return
|
| 76 |
+
batches.append(buf)
|
| 77 |
+
buf = []
|
| 78 |
+
max_len = 0
|
| 79 |
+
|
| 80 |
+
for sz, i in sizes:
|
| 81 |
+
sz += extra_toks_per_seq
|
| 82 |
+
if max(sz, max_len) * (len(buf) + 1) > toks_per_batch:
|
| 83 |
+
_flush_current_buf()
|
| 84 |
+
max_len = max(max_len, sz)
|
| 85 |
+
buf.append(i)
|
| 86 |
+
|
| 87 |
+
_flush_current_buf()
|
| 88 |
+
return batches
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class Alphabet(object):
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
standard_toks: Sequence[str],
|
| 95 |
+
prepend_toks: Sequence[str] = ("<null_0>", "<pad>", "<eos>", "<unk>"),
|
| 96 |
+
append_toks: Sequence[str] = ("<cls>", "<mask>", "<sep>"),
|
| 97 |
+
prepend_bos: bool = True,
|
| 98 |
+
append_eos: bool = False,
|
| 99 |
+
use_msa: bool = False,
|
| 100 |
+
):
|
| 101 |
+
self.standard_toks = list(standard_toks)
|
| 102 |
+
self.prepend_toks = list(prepend_toks)
|
| 103 |
+
self.append_toks = list(append_toks)
|
| 104 |
+
self.prepend_bos = prepend_bos
|
| 105 |
+
self.append_eos = append_eos
|
| 106 |
+
self.use_msa = use_msa
|
| 107 |
+
|
| 108 |
+
self.all_toks = list(self.prepend_toks)
|
| 109 |
+
self.all_toks.extend(self.standard_toks)
|
| 110 |
+
for i in range((8 - (len(self.all_toks) % 8)) % 8):
|
| 111 |
+
self.all_toks.append(f"<null_{i + 1}>")
|
| 112 |
+
self.all_toks.extend(self.append_toks)
|
| 113 |
+
|
| 114 |
+
self.tok_to_idx = {tok: i for i, tok in enumerate(self.all_toks)}
|
| 115 |
+
|
| 116 |
+
self.unk_idx = self.tok_to_idx["<unk>"]
|
| 117 |
+
self.padding_idx = self.get_idx("<pad>")
|
| 118 |
+
self.cls_idx = self.get_idx("<cls>")
|
| 119 |
+
self.mask_idx = self.get_idx("<mask>")
|
| 120 |
+
self.eos_idx = self.get_idx("<eos>")
|
| 121 |
+
self.all_special_tokens = ['<eos>', '<unk>', '<pad>', '<cls>', '<mask>']
|
| 122 |
+
self.unique_no_split_tokens = self.all_toks
|
| 123 |
+
|
| 124 |
+
def __len__(self):
|
| 125 |
+
return len(self.all_toks)
|
| 126 |
+
|
| 127 |
+
def get_idx(self, tok):
|
| 128 |
+
return self.tok_to_idx.get(tok, self.unk_idx)
|
| 129 |
+
|
| 130 |
+
def get_tok(self, ind):
|
| 131 |
+
return self.all_toks[ind]
|
| 132 |
+
|
| 133 |
+
def to_dict(self):
|
| 134 |
+
return self.tok_to_idx.copy()
|
| 135 |
+
|
| 136 |
+
def get_batch_converter(self, truncation_seq_length: int = None):
|
| 137 |
+
if self.use_msa:
|
| 138 |
+
return MSABatchConverter(self, truncation_seq_length)
|
| 139 |
+
else:
|
| 140 |
+
return BatchConverter(self, truncation_seq_length)
|
| 141 |
+
|
| 142 |
+
@classmethod
|
| 143 |
+
def from_architecture(cls, name: str) -> "Alphabet":
|
| 144 |
+
if name in ("ESM-1", "protein_bert_base"):
|
| 145 |
+
standard_toks = proteinseq_toks["toks"]
|
| 146 |
+
prepend_toks: Tuple[str, ...] = ("<null_0>", "<pad>", "<eos>", "<unk>")
|
| 147 |
+
append_toks: Tuple[str, ...] = ("<cls>", "<mask>", "<sep>")
|
| 148 |
+
prepend_bos = True
|
| 149 |
+
append_eos = False
|
| 150 |
+
use_msa = False
|
| 151 |
+
elif name in ("ESM-1b", "roberta_large"):
|
| 152 |
+
standard_toks = proteinseq_toks["toks"]
|
| 153 |
+
prepend_toks = ("<cls>", "<pad>", "<eos>", "<unk>")
|
| 154 |
+
append_toks = ("<mask>",)
|
| 155 |
+
prepend_bos = True
|
| 156 |
+
append_eos = True
|
| 157 |
+
use_msa = False
|
| 158 |
+
elif name in ("MSA Transformer", "msa_transformer"):
|
| 159 |
+
standard_toks = proteinseq_toks["toks"]
|
| 160 |
+
prepend_toks = ("<cls>", "<pad>", "<eos>", "<unk>")
|
| 161 |
+
append_toks = ("<mask>",)
|
| 162 |
+
prepend_bos = True
|
| 163 |
+
append_eos = False
|
| 164 |
+
use_msa = True
|
| 165 |
+
elif "invariant_gvp" in name.lower():
|
| 166 |
+
standard_toks = proteinseq_toks["toks"]
|
| 167 |
+
prepend_toks = ("<null_0>", "<pad>", "<eos>", "<unk>")
|
| 168 |
+
append_toks = ("<mask>", "<cath>", "<af2>")
|
| 169 |
+
prepend_bos = True
|
| 170 |
+
append_eos = False
|
| 171 |
+
use_msa = False
|
| 172 |
+
else:
|
| 173 |
+
raise ValueError("Unknown architecture selected")
|
| 174 |
+
return cls(standard_toks, prepend_toks, append_toks, prepend_bos, append_eos, use_msa)
|
| 175 |
+
|
| 176 |
+
def _tokenize(self, text) -> str:
|
| 177 |
+
return text.split()
|
| 178 |
+
|
| 179 |
+
def tokenize(self, text, **kwargs) -> List[str]:
|
| 180 |
+
"""
|
| 181 |
+
Inspired by https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils.py
|
| 182 |
+
Converts a string in a sequence of tokens, using the tokenizer.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
text (:obj:`str`):
|
| 186 |
+
The sequence to be encoded.
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
:obj:`List[str]`: The list of tokens.
|
| 190 |
+
"""
|
| 191 |
+
|
| 192 |
+
def split_on_token(tok, text):
|
| 193 |
+
result = []
|
| 194 |
+
split_text = text.split(tok)
|
| 195 |
+
for i, sub_text in enumerate(split_text):
|
| 196 |
+
# AddedToken can control whitespace stripping around them.
|
| 197 |
+
# We use them for GPT2 and Roberta to have different behavior depending on the special token
|
| 198 |
+
# Cf. https://github.com/huggingface/transformers/pull/2778
|
| 199 |
+
# and https://github.com/huggingface/transformers/issues/3788
|
| 200 |
+
# We strip left and right by default
|
| 201 |
+
if i < len(split_text) - 1:
|
| 202 |
+
sub_text = sub_text.rstrip()
|
| 203 |
+
if i > 0:
|
| 204 |
+
sub_text = sub_text.lstrip()
|
| 205 |
+
|
| 206 |
+
if i == 0 and not sub_text:
|
| 207 |
+
result.append(tok)
|
| 208 |
+
elif i == len(split_text) - 1:
|
| 209 |
+
if sub_text:
|
| 210 |
+
result.append(sub_text)
|
| 211 |
+
else:
|
| 212 |
+
pass
|
| 213 |
+
else:
|
| 214 |
+
if sub_text:
|
| 215 |
+
result.append(sub_text)
|
| 216 |
+
result.append(tok)
|
| 217 |
+
return result
|
| 218 |
+
|
| 219 |
+
def split_on_tokens(tok_list, text):
|
| 220 |
+
if not text.strip():
|
| 221 |
+
return []
|
| 222 |
+
|
| 223 |
+
tokenized_text = []
|
| 224 |
+
text_list = [text]
|
| 225 |
+
for tok in tok_list:
|
| 226 |
+
tokenized_text = []
|
| 227 |
+
for sub_text in text_list:
|
| 228 |
+
if sub_text not in self.unique_no_split_tokens:
|
| 229 |
+
tokenized_text.extend(split_on_token(tok, sub_text))
|
| 230 |
+
else:
|
| 231 |
+
tokenized_text.append(sub_text)
|
| 232 |
+
text_list = tokenized_text
|
| 233 |
+
|
| 234 |
+
return list(
|
| 235 |
+
itertools.chain.from_iterable(
|
| 236 |
+
(
|
| 237 |
+
self._tokenize(token)
|
| 238 |
+
if token not in self.unique_no_split_tokens
|
| 239 |
+
else [token]
|
| 240 |
+
for token in tokenized_text
|
| 241 |
+
)
|
| 242 |
+
)
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
no_split_token = self.unique_no_split_tokens
|
| 246 |
+
tokenized_text = split_on_tokens(no_split_token, text)
|
| 247 |
+
return tokenized_text
|
| 248 |
+
|
| 249 |
+
def encode(self, text):
|
| 250 |
+
return [self.tok_to_idx[tok] for tok in self.tokenize(text)]
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class BatchConverter(object):
|
| 254 |
+
"""Callable to convert an unprocessed (labels + strings) batch to a
|
| 255 |
+
processed (labels + tensor) batch.
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
def __init__(self, alphabet, truncation_seq_length: int = None):
|
| 259 |
+
self.alphabet = alphabet
|
| 260 |
+
self.truncation_seq_length = truncation_seq_length
|
| 261 |
+
|
| 262 |
+
def __call__(self, raw_batch: Sequence[Tuple[str, str]]):
|
| 263 |
+
# RoBERTa uses an eos token, while ESM-1 does not.
|
| 264 |
+
batch_size = len(raw_batch)
|
| 265 |
+
batch_labels, seq_str_list = zip(*raw_batch)
|
| 266 |
+
seq_encoded_list = [self.alphabet.encode(seq_str) for seq_str in seq_str_list]
|
| 267 |
+
if self.truncation_seq_length:
|
| 268 |
+
seq_encoded_list = [seq_str[:self.truncation_seq_length] for seq_str in seq_encoded_list]
|
| 269 |
+
max_len = max(len(seq_encoded) for seq_encoded in seq_encoded_list)
|
| 270 |
+
tokens = torch.empty(
|
| 271 |
+
(
|
| 272 |
+
batch_size,
|
| 273 |
+
max_len + int(self.alphabet.prepend_bos) + int(self.alphabet.append_eos),
|
| 274 |
+
),
|
| 275 |
+
dtype=torch.int64,
|
| 276 |
+
)
|
| 277 |
+
tokens.fill_(self.alphabet.padding_idx)
|
| 278 |
+
labels = []
|
| 279 |
+
strs = []
|
| 280 |
+
|
| 281 |
+
for i, (label, seq_str, seq_encoded) in enumerate(
|
| 282 |
+
zip(batch_labels, seq_str_list, seq_encoded_list)
|
| 283 |
+
):
|
| 284 |
+
labels.append(label)
|
| 285 |
+
strs.append(seq_str)
|
| 286 |
+
if self.alphabet.prepend_bos:
|
| 287 |
+
tokens[i, 0] = self.alphabet.cls_idx
|
| 288 |
+
seq = torch.tensor(seq_encoded, dtype=torch.int64)
|
| 289 |
+
tokens[
|
| 290 |
+
i,
|
| 291 |
+
int(self.alphabet.prepend_bos) : len(seq_encoded)
|
| 292 |
+
+ int(self.alphabet.prepend_bos),
|
| 293 |
+
] = seq
|
| 294 |
+
if self.alphabet.append_eos:
|
| 295 |
+
tokens[i, len(seq_encoded) + int(self.alphabet.prepend_bos)] = self.alphabet.eos_idx
|
| 296 |
+
|
| 297 |
+
return labels, strs, tokens
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
class MSABatchConverter(BatchConverter):
|
| 301 |
+
def __call__(self, inputs: Union[Sequence[RawMSA], RawMSA]):
|
| 302 |
+
if isinstance(inputs[0][0], str):
|
| 303 |
+
# Input is a single MSA
|
| 304 |
+
raw_batch: Sequence[RawMSA] = [inputs] # type: ignore
|
| 305 |
+
else:
|
| 306 |
+
raw_batch = inputs # type: ignore
|
| 307 |
+
|
| 308 |
+
batch_size = len(raw_batch)
|
| 309 |
+
max_alignments = max(len(msa) for msa in raw_batch)
|
| 310 |
+
max_seqlen = max(len(msa[0][1]) for msa in raw_batch)
|
| 311 |
+
|
| 312 |
+
tokens = torch.empty(
|
| 313 |
+
(
|
| 314 |
+
batch_size,
|
| 315 |
+
max_alignments,
|
| 316 |
+
max_seqlen + int(self.alphabet.prepend_bos) + int(self.alphabet.append_eos),
|
| 317 |
+
),
|
| 318 |
+
dtype=torch.int64,
|
| 319 |
+
)
|
| 320 |
+
tokens.fill_(self.alphabet.padding_idx)
|
| 321 |
+
labels = []
|
| 322 |
+
strs = []
|
| 323 |
+
|
| 324 |
+
for i, msa in enumerate(raw_batch):
|
| 325 |
+
msa_seqlens = set(len(seq) for _, seq in msa)
|
| 326 |
+
if not len(msa_seqlens) == 1:
|
| 327 |
+
raise RuntimeError(
|
| 328 |
+
"Received unaligned sequences for input to MSA, all sequence "
|
| 329 |
+
"lengths must be equal."
|
| 330 |
+
)
|
| 331 |
+
msa_labels, msa_strs, msa_tokens = super().__call__(msa)
|
| 332 |
+
labels.append(msa_labels)
|
| 333 |
+
strs.append(msa_strs)
|
| 334 |
+
tokens[i, : msa_tokens.size(0), : msa_tokens.size(1)] = msa_tokens
|
| 335 |
+
|
| 336 |
+
return labels, strs, tokens
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def read_fasta(
|
| 340 |
+
path,
|
| 341 |
+
keep_gaps=True,
|
| 342 |
+
keep_insertions=True,
|
| 343 |
+
to_upper=False,
|
| 344 |
+
):
|
| 345 |
+
with open(path, "r") as f:
|
| 346 |
+
for result in read_alignment_lines(
|
| 347 |
+
f, keep_gaps=keep_gaps, keep_insertions=keep_insertions, to_upper=to_upper
|
| 348 |
+
):
|
| 349 |
+
yield result
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def read_alignment_lines(
|
| 353 |
+
lines,
|
| 354 |
+
keep_gaps=True,
|
| 355 |
+
keep_insertions=True,
|
| 356 |
+
to_upper=False,
|
| 357 |
+
):
|
| 358 |
+
seq = desc = None
|
| 359 |
+
|
| 360 |
+
def parse(s):
|
| 361 |
+
if not keep_gaps:
|
| 362 |
+
s = re.sub("-", "", s)
|
| 363 |
+
if not keep_insertions:
|
| 364 |
+
s = re.sub("[a-z]", "", s)
|
| 365 |
+
return s.upper() if to_upper else s
|
| 366 |
+
|
| 367 |
+
for line in lines:
|
| 368 |
+
# Line may be empty if seq % file_line_width == 0
|
| 369 |
+
if len(line) > 0 and line[0] == ">":
|
| 370 |
+
if seq is not None:
|
| 371 |
+
yield desc, parse(seq)
|
| 372 |
+
desc = line.strip().lstrip(">")
|
| 373 |
+
seq = ""
|
| 374 |
+
else:
|
| 375 |
+
assert isinstance(seq, str)
|
| 376 |
+
seq += line.strip()
|
| 377 |
+
assert isinstance(seq, str) and isinstance(desc, str)
|
| 378 |
+
yield desc, parse(seq)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
class ESMStructuralSplitDataset(torch.utils.data.Dataset):
|
| 382 |
+
"""
|
| 383 |
+
Structural Split Dataset as described in section A.10 of the supplement of our paper.
|
| 384 |
+
https://doi.org/10.1101/622803
|
| 385 |
+
|
| 386 |
+
We use the full version of SCOPe 2.07, clustered at 90% sequence identity,
|
| 387 |
+
generated on January 23, 2020.
|
| 388 |
+
|
| 389 |
+
For each SCOPe domain:
|
| 390 |
+
- We extract the sequence from the corresponding PDB file
|
| 391 |
+
- We extract the 3D coordinates of the Carbon beta atoms, aligning them
|
| 392 |
+
to the sequence. We put NaN where Cb atoms are missing.
|
| 393 |
+
- From the 3D coordinates, we calculate a pairwise distance map, based
|
| 394 |
+
on L2 distance
|
| 395 |
+
- We use DSSP to generate secondary structure labels for the corresponding
|
| 396 |
+
PDB file. This is also aligned to the sequence. We put - where SSP
|
| 397 |
+
labels are missing.
|
| 398 |
+
|
| 399 |
+
For each SCOPe classification level of family/superfamily/fold (in order of difficulty),
|
| 400 |
+
we have split the data into 5 partitions for cross validation. These are provided
|
| 401 |
+
in a downloaded splits folder, in the format:
|
| 402 |
+
splits/{split_level}/{cv_partition}/{train|valid}.txt
|
| 403 |
+
where train is the partition and valid is the concatentation of the remaining 4.
|
| 404 |
+
|
| 405 |
+
For each SCOPe domain, we provide a pkl dump that contains:
|
| 406 |
+
- seq : The domain sequence, stored as an L-length string
|
| 407 |
+
- ssp : The secondary structure labels, stored as an L-length string
|
| 408 |
+
- dist : The distance map, stored as an LxL numpy array
|
| 409 |
+
- coords : The 3D coordinates, stored as an Lx3 numpy array
|
| 410 |
+
|
| 411 |
+
"""
|
| 412 |
+
|
| 413 |
+
base_folder = "structural-data"
|
| 414 |
+
file_list = [
|
| 415 |
+
# url tar filename filename MD5 Hash
|
| 416 |
+
(
|
| 417 |
+
"https://dl.fbaipublicfiles.com/fair-esm/structural-data/splits.tar.gz",
|
| 418 |
+
"splits.tar.gz",
|
| 419 |
+
"splits",
|
| 420 |
+
"456fe1c7f22c9d3d8dfe9735da52411d",
|
| 421 |
+
),
|
| 422 |
+
(
|
| 423 |
+
"https://dl.fbaipublicfiles.com/fair-esm/structural-data/pkl.tar.gz",
|
| 424 |
+
"pkl.tar.gz",
|
| 425 |
+
"pkl",
|
| 426 |
+
"644ea91e56066c750cd50101d390f5db",
|
| 427 |
+
),
|
| 428 |
+
]
|
| 429 |
+
|
| 430 |
+
def __init__(
|
| 431 |
+
self,
|
| 432 |
+
split_level,
|
| 433 |
+
cv_partition,
|
| 434 |
+
split,
|
| 435 |
+
root_path=os.path.expanduser("~/.cache/torch/data/esm"),
|
| 436 |
+
download=False,
|
| 437 |
+
):
|
| 438 |
+
super().__init__()
|
| 439 |
+
assert split in [
|
| 440 |
+
"train",
|
| 441 |
+
"valid",
|
| 442 |
+
], "train_valid must be 'train' or 'valid'"
|
| 443 |
+
self.root_path = root_path
|
| 444 |
+
self.base_path = os.path.join(self.root_path, self.base_folder)
|
| 445 |
+
|
| 446 |
+
# check if root path has what you need or else download it
|
| 447 |
+
if download:
|
| 448 |
+
self.download()
|
| 449 |
+
|
| 450 |
+
self.split_file = os.path.join(
|
| 451 |
+
self.base_path, "splits", split_level, cv_partition, f"{split}.txt"
|
| 452 |
+
)
|
| 453 |
+
self.pkl_dir = os.path.join(self.base_path, "pkl")
|
| 454 |
+
self.names = []
|
| 455 |
+
with open(self.split_file) as f:
|
| 456 |
+
self.names = f.read().splitlines()
|
| 457 |
+
|
| 458 |
+
def __len__(self):
|
| 459 |
+
return len(self.names)
|
| 460 |
+
|
| 461 |
+
def _check_exists(self) -> bool:
|
| 462 |
+
for (_, _, filename, _) in self.file_list:
|
| 463 |
+
fpath = os.path.join(self.base_path, filename)
|
| 464 |
+
if not os.path.exists(fpath) or not os.path.isdir(fpath):
|
| 465 |
+
return False
|
| 466 |
+
return True
|
| 467 |
+
|
| 468 |
+
def download(self):
|
| 469 |
+
|
| 470 |
+
if self._check_exists():
|
| 471 |
+
print("Files already downloaded and verified")
|
| 472 |
+
return
|
| 473 |
+
|
| 474 |
+
from torchvision.datasets.utils import download_url
|
| 475 |
+
|
| 476 |
+
for url, tar_filename, filename, md5_hash in self.file_list:
|
| 477 |
+
download_path = os.path.join(self.base_path, tar_filename)
|
| 478 |
+
download_url(url=url, root=self.base_path, filename=tar_filename, md5=md5_hash)
|
| 479 |
+
shutil.unpack_archive(download_path, self.base_path)
|
| 480 |
+
|
| 481 |
+
def __getitem__(self, idx):
|
| 482 |
+
"""
|
| 483 |
+
Returns a dict with the following entires
|
| 484 |
+
- seq : Str (domain sequence)
|
| 485 |
+
- ssp : Str (SSP labels)
|
| 486 |
+
- dist : np.array (distance map)
|
| 487 |
+
- coords : np.array (3D coordinates)
|
| 488 |
+
"""
|
| 489 |
+
name = self.names[idx]
|
| 490 |
+
pkl_fname = os.path.join(self.pkl_dir, name[1:3], f"{name}.pkl")
|
| 491 |
+
with open(pkl_fname, "rb") as f:
|
| 492 |
+
obj = pickle.load(f)
|
| 493 |
+
return obj
|
weight/esm-main/esm/esmfold/v1/__init__.py
ADDED
|
File without changes
|
weight/esm-main/esm/esmfold/v1/categorical_mixture.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class CategoricalMixture:
|
| 9 |
+
def __init__(self, param, bins=50, start=0, end=1):
|
| 10 |
+
# All tensors are of shape ..., bins.
|
| 11 |
+
self.logits = param
|
| 12 |
+
bins = torch.linspace(
|
| 13 |
+
start, end, bins + 1, device=self.logits.device, dtype=self.logits.dtype
|
| 14 |
+
)
|
| 15 |
+
self.v_bins = (bins[:-1] + bins[1:]) / 2
|
| 16 |
+
|
| 17 |
+
def log_prob(self, true):
|
| 18 |
+
# Shapes are:
|
| 19 |
+
# self.probs: ... x bins
|
| 20 |
+
# true : ...
|
| 21 |
+
true_index = (
|
| 22 |
+
(
|
| 23 |
+
true.unsqueeze(-1)
|
| 24 |
+
- self.v_bins[
|
| 25 |
+
[
|
| 26 |
+
None,
|
| 27 |
+
]
|
| 28 |
+
* true.ndim
|
| 29 |
+
]
|
| 30 |
+
)
|
| 31 |
+
.abs()
|
| 32 |
+
.argmin(-1)
|
| 33 |
+
)
|
| 34 |
+
nll = self.logits.log_softmax(-1)
|
| 35 |
+
return torch.take_along_dim(nll, true_index.unsqueeze(-1), dim=-1).squeeze(-1)
|
| 36 |
+
|
| 37 |
+
def mean(self):
|
| 38 |
+
return (self.logits.softmax(-1) @ self.v_bins.unsqueeze(1)).squeeze(-1)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def categorical_lddt(logits, bins=50):
|
| 42 |
+
# Logits are ..., 37, bins.
|
| 43 |
+
return CategoricalMixture(logits, bins=bins).mean()
|