jxliu2 commited on
Commit
b1c2ae9
·
verified ·
1 Parent(s): d1c7b25

Delete protgps

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. protgps/esm_models/esm2/checkpoints/esm2_t6_8M_UR50D-contact-regression.pt +0 -3
  2. protgps/esm_models/esm2/checkpoints/esm2_t6_8M_UR50D.pt +0 -3
  3. protgps/esm_models/esm2/facebookresearch_esm_main/.flake8 +0 -10
  4. protgps/esm_models/esm2/facebookresearch_esm_main/.git-blame-ignore-revs +0 -2
  5. protgps/esm_models/esm2/facebookresearch_esm_main/.github/ISSUE_TEMPLATE/bug.md +0 -27
  6. protgps/esm_models/esm2/facebookresearch_esm_main/.gitignore +0 -31
  7. protgps/esm_models/esm2/facebookresearch_esm_main/CODE_OF_CONDUCT.rst +0 -6
  8. protgps/esm_models/esm2/facebookresearch_esm_main/CONTRIBUTING.md +0 -31
  9. protgps/esm_models/esm2/facebookresearch_esm_main/LICENSE +0 -21
  10. protgps/esm_models/esm2/facebookresearch_esm_main/README.md +0 -795
  11. protgps/esm_models/esm2/facebookresearch_esm_main/__pycache__/hubconf.cpython-310.pyc +0 -0
  12. protgps/esm_models/esm2/facebookresearch_esm_main/__pycache__/hubconf.cpython-38.pyc +0 -0
  13. protgps/esm_models/esm2/facebookresearch_esm_main/environment.yml +0 -36
  14. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__init__.py +0 -12
  15. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/__init__.cpython-310.pyc +0 -0
  16. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/__init__.cpython-38.pyc +0 -0
  17. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/axial_attention.cpython-310.pyc +0 -0
  18. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/axial_attention.cpython-38.pyc +0 -0
  19. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/constants.cpython-310.pyc +0 -0
  20. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/constants.cpython-38.pyc +0 -0
  21. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/data.cpython-310.pyc +0 -0
  22. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/data.cpython-38.pyc +0 -0
  23. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/modules.cpython-310.pyc +0 -0
  24. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/modules.cpython-38.pyc +0 -0
  25. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/multihead_attention.cpython-310.pyc +0 -0
  26. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/multihead_attention.cpython-38.pyc +0 -0
  27. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/pretrained.cpython-310.pyc +0 -0
  28. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/pretrained.cpython-38.pyc +0 -0
  29. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/rotary_embedding.cpython-310.pyc +0 -0
  30. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/rotary_embedding.cpython-38.pyc +0 -0
  31. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/version.cpython-310.pyc +0 -0
  32. protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/version.cpython-38.pyc +0 -0
  33. protgps/esm_models/esm2/facebookresearch_esm_main/esm/axial_attention.py +0 -267
  34. protgps/esm_models/esm2/facebookresearch_esm_main/esm/constants.py +0 -10
  35. protgps/esm_models/esm2/facebookresearch_esm_main/esm/data.py +0 -503
  36. protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/__init__.py +0 -0
  37. protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/categorical_mixture.py +0 -43
  38. protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/esmfold.py +0 -363
  39. protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/misc.py +0 -308
  40. protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/pretrained.py +0 -183
  41. protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/tri_self_attn_block.py +0 -166
  42. protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/trunk.py +0 -261
  43. protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/__init__.py +0 -8
  44. protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/features.py +0 -359
  45. protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/gvp_encoder.py +0 -53
  46. protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/gvp_modules.py +0 -533
  47. protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/gvp_transformer.py +0 -139
  48. protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/gvp_transformer_encoder.py +0 -189
  49. protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/gvp_utils.py +0 -67
  50. protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/multichain_util.py +0 -152
protgps/esm_models/esm2/checkpoints/esm2_t6_8M_UR50D-contact-regression.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:8f7a4557d57713b97ba0e484303007efb7230d25299c0ac47a0a1b12a87bbb9d
3
- size 1511
 
 
 
 
protgps/esm_models/esm2/checkpoints/esm2_t6_8M_UR50D.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:46f002a9870c9bdecd0ea887acb1f9a38a6b561e8f8bf8a6990b679b9d31b928
3
- size 30099493
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/.flake8 DELETED
@@ -1,10 +0,0 @@
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
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/.git-blame-ignore-revs DELETED
@@ -1,2 +0,0 @@
1
- # Migrate code style to Black
2
- 8bc7e948cd9bf0b6d1f2113e221ef548ef663377
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/.github/ISSUE_TEMPLATE/bug.md DELETED
@@ -1,27 +0,0 @@
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.)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/.gitignore DELETED
@@ -1,31 +0,0 @@
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
- *~
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/CODE_OF_CONDUCT.rst DELETED
@@ -1,6 +0,0 @@
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
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/CONTRIBUTING.md DELETED
@@ -1,31 +0,0 @@
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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/LICENSE DELETED
@@ -1,21 +0,0 @@
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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/README.md DELETED
@@ -1,795 +0,0 @@
1
- # Evolutionary Scale Modeling
2
-
3
- [![atlas](https://user-images.githubusercontent.com/3605224/199301187-a9e38b3f-71a7-44be-94f4-db0d66143c53.png)](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/).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/__pycache__/hubconf.cpython-310.pyc DELETED
Binary file (434 Bytes)
 
protgps/esm_models/esm2/facebookresearch_esm_main/__pycache__/hubconf.cpython-38.pyc DELETED
Binary file (1.43 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/environment.yml DELETED
@@ -1,36 +0,0 @@
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__init__.py DELETED
@@ -1,12 +0,0 @@
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
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/__init__.cpython-310.pyc DELETED
Binary file (529 Bytes)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/__init__.cpython-38.pyc DELETED
Binary file (489 Bytes)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/axial_attention.cpython-310.pyc DELETED
Binary file (5.54 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/axial_attention.cpython-38.pyc DELETED
Binary file (5.43 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/constants.cpython-310.pyc DELETED
Binary file (327 Bytes)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/constants.cpython-38.pyc DELETED
Binary file (337 Bytes)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/data.cpython-310.pyc DELETED
Binary file (15.5 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/data.cpython-38.pyc DELETED
Binary file (15.4 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/modules.cpython-310.pyc DELETED
Binary file (13.1 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/modules.cpython-38.pyc DELETED
Binary file (12.9 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/multihead_attention.cpython-310.pyc DELETED
Binary file (12 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/multihead_attention.cpython-38.pyc DELETED
Binary file (11.9 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/pretrained.cpython-310.pyc DELETED
Binary file (19.6 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/pretrained.cpython-38.pyc DELETED
Binary file (20.4 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/rotary_embedding.cpython-310.pyc DELETED
Binary file (2.79 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/rotary_embedding.cpython-38.pyc DELETED
Binary file (2.73 kB)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/version.cpython-310.pyc DELETED
Binary file (225 Bytes)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/__pycache__/version.cpython-38.pyc DELETED
Binary file (185 Bytes)
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/axial_attention.py DELETED
@@ -1,267 +0,0 @@
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[
56
- :, start : start + max_rows
57
- ]
58
- if self_attn_padding_mask is not None
59
- else None,
60
- )
61
- attns += attn_weights
62
- attn_probs = attns.softmax(-1)
63
- attn_probs = self.dropout_module(attn_probs)
64
-
65
- outputs = []
66
- for start in range(0, num_rows, max_rows):
67
- output = self.compute_attention_update(
68
- x[start : start + max_rows], attn_probs
69
- )
70
- outputs.append(output)
71
-
72
- output = torch.cat(outputs, 0)
73
- return output, attn_probs
74
-
75
- def compute_attention_weights(
76
- self,
77
- x,
78
- scaling: float,
79
- self_attn_mask=None,
80
- self_attn_padding_mask=None,
81
- ):
82
- num_rows, num_cols, batch_size, embed_dim = x.size()
83
- q = self.q_proj(x).view(
84
- num_rows, num_cols, batch_size, self.num_heads, self.head_dim
85
- )
86
- k = self.k_proj(x).view(
87
- num_rows, num_cols, batch_size, self.num_heads, self.head_dim
88
- )
89
- q *= scaling
90
- if self_attn_padding_mask is not None:
91
- # Zero out any padded aligned positions - this is important since
92
- # we take a sum across the alignment axis.
93
- q *= 1 - self_attn_padding_mask.permute(1, 2, 0).unsqueeze(3).unsqueeze(
94
- 4
95
- ).to(q)
96
-
97
- attn_weights = torch.einsum(f"rinhd,rjnhd->{self.attn_shape}", q, k)
98
-
99
- if self_attn_mask is not None:
100
- raise NotImplementedError
101
- # Mask Size: [B x R x C], Weights Size: [H x B x C x C]
102
-
103
- if self_attn_padding_mask is not None:
104
- attn_weights = attn_weights.masked_fill(
105
- self_attn_padding_mask[:, 0].unsqueeze(0).unsqueeze(2),
106
- -10000,
107
- )
108
-
109
- return attn_weights
110
-
111
- def compute_attention_update(
112
- self,
113
- x,
114
- attn_probs,
115
- ):
116
- num_rows, num_cols, batch_size, embed_dim = x.size()
117
- v = self.v_proj(x).view(
118
- num_rows, num_cols, batch_size, self.num_heads, self.head_dim
119
- )
120
- context = torch.einsum(f"{self.attn_shape},rjnhd->rinhd", attn_probs, v)
121
- context = context.contiguous().view(num_rows, num_cols, batch_size, embed_dim)
122
- output = self.out_proj(context)
123
- return output
124
-
125
- def forward(
126
- self,
127
- x,
128
- self_attn_mask=None,
129
- self_attn_padding_mask=None,
130
- ):
131
- num_rows, num_cols, batch_size, embed_dim = x.size()
132
- if (
133
- num_rows * num_cols > self.max_tokens_per_msa
134
- ) and not torch.is_grad_enabled():
135
- return self._batched_forward(x, self_attn_mask, self_attn_padding_mask)
136
- else:
137
- scaling = self.align_scaling(x)
138
- attn_weights = self.compute_attention_weights(
139
- x, scaling, self_attn_mask, self_attn_padding_mask
140
- )
141
- attn_probs = attn_weights.softmax(-1)
142
- attn_probs = self.dropout_module(attn_probs)
143
- output = self.compute_attention_update(x, attn_probs)
144
- return output, attn_probs
145
-
146
-
147
- class ColumnSelfAttention(nn.Module):
148
- """Compute self-attention over columns of a 2D input."""
149
-
150
- def __init__(
151
- self,
152
- embed_dim,
153
- num_heads,
154
- dropout=0.0,
155
- max_tokens_per_msa: int = 2**16,
156
- ):
157
- super().__init__()
158
-
159
- self.num_heads = num_heads
160
- self.dropout = dropout
161
- self.head_dim = embed_dim // num_heads
162
- self.scaling = self.head_dim**-0.5
163
- self.max_tokens_per_msa = max_tokens_per_msa
164
-
165
- self.k_proj = nn.Linear(embed_dim, embed_dim)
166
- self.v_proj = nn.Linear(embed_dim, embed_dim)
167
- self.q_proj = nn.Linear(embed_dim, embed_dim)
168
-
169
- self.out_proj = nn.Linear(embed_dim, embed_dim)
170
- self.dropout_module = nn.Dropout(dropout)
171
-
172
- def _batched_forward(
173
- self,
174
- x,
175
- self_attn_mask=None,
176
- self_attn_padding_mask=None,
177
- ):
178
- num_rows, num_cols, batch_size, embed_dim = x.size()
179
- max_cols = max(1, self.max_tokens_per_msa // num_rows)
180
- outputs = []
181
- attns = []
182
- for start in range(0, num_cols, max_cols):
183
- output, attn = self(
184
- x[:, start : start + max_cols],
185
- self_attn_mask=self_attn_mask,
186
- self_attn_padding_mask=self_attn_padding_mask[
187
- :, :, start : start + max_cols
188
- ]
189
- if self_attn_padding_mask is not None
190
- else None,
191
- )
192
- outputs.append(output)
193
- attns.append(attn)
194
- output = torch.cat(outputs, 1)
195
- attns = torch.cat(attns, 1)
196
- return output, attns
197
-
198
- def compute_attention_update(
199
- self,
200
- x,
201
- self_attn_mask=None,
202
- self_attn_padding_mask=None,
203
- ):
204
- num_rows, num_cols, batch_size, embed_dim = x.size()
205
- if num_rows == 1:
206
- # if there is only 1 position, this is equivalent and doesn't break with padding
207
- attn_probs = torch.ones(
208
- self.num_heads,
209
- num_cols,
210
- batch_size,
211
- num_rows,
212
- num_rows,
213
- device=x.device,
214
- dtype=x.dtype,
215
- )
216
- output = self.out_proj(self.v_proj(x))
217
- else:
218
- q = self.q_proj(x).view(
219
- num_rows, num_cols, batch_size, self.num_heads, self.head_dim
220
- )
221
- k = self.k_proj(x).view(
222
- num_rows, num_cols, batch_size, self.num_heads, self.head_dim
223
- )
224
- v = self.v_proj(x).view(
225
- num_rows, num_cols, batch_size, self.num_heads, self.head_dim
226
- )
227
- q *= self.scaling
228
-
229
- attn_weights = torch.einsum("icnhd,jcnhd->hcnij", q, k)
230
-
231
- if self_attn_mask is not None:
232
- raise NotImplementedError
233
- if self_attn_padding_mask is not None:
234
- attn_weights = attn_weights.masked_fill(
235
- self_attn_padding_mask.permute(2, 0, 1).unsqueeze(0).unsqueeze(3),
236
- -10000,
237
- )
238
-
239
- attn_probs = attn_weights.softmax(-1)
240
- attn_probs = self.dropout_module(attn_probs)
241
- context = torch.einsum("hcnij,jcnhd->icnhd", attn_probs, v)
242
- context = context.contiguous().view(
243
- num_rows, num_cols, batch_size, embed_dim
244
- )
245
- output = self.out_proj(context)
246
- return output, attn_probs
247
-
248
- def forward(
249
- self,
250
- x,
251
- self_attn_mask=None,
252
- self_attn_padding_mask=None,
253
- ):
254
- num_rows, num_cols, batch_size, embed_dim = x.size()
255
- # if False and num_rows * num_cols > 2 ** 14 and not torch.is_grad_enabled():
256
- if (
257
- num_rows * num_cols
258
- ) > self.max_tokens_per_msa and not torch.is_grad_enabled():
259
- return self._batched_forward(
260
- x,
261
- self_attn_mask,
262
- self_attn_padding_mask,
263
- )
264
- else:
265
- return self.compute_attention_update(
266
- x, self_attn_mask, self_attn_padding_mask
267
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/constants.py DELETED
@@ -1,10 +0,0 @@
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
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/data.py DELETED
@@ -1,503 +0,0 @@
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 esm.constants import proteinseq_toks
14
-
15
- RawMSA = Sequence[Tuple[str, str]]
16
-
17
-
18
- class FastaBatchedDataset(object):
19
- def __init__(self, sequence_labels, sequence_strs):
20
- self.sequence_labels = list(sequence_labels)
21
- self.sequence_strs = list(sequence_strs)
22
-
23
- @classmethod
24
- def from_file(cls, fasta_file):
25
- sequence_labels, sequence_strs = [], []
26
- cur_seq_label = None
27
- buf = []
28
-
29
- def _flush_current_seq():
30
- nonlocal cur_seq_label, buf
31
- if cur_seq_label is None:
32
- return
33
- sequence_labels.append(cur_seq_label)
34
- sequence_strs.append("".join(buf))
35
- cur_seq_label = None
36
- buf = []
37
-
38
- with open(fasta_file, "r") as infile:
39
- for line_idx, line in enumerate(infile):
40
- if line.startswith(">"): # label line
41
- _flush_current_seq()
42
- line = line[1:].strip()
43
- if len(line) > 0:
44
- cur_seq_label = line
45
- else:
46
- cur_seq_label = f"seqnum{line_idx:09d}"
47
- else: # sequence line
48
- buf.append(line.strip())
49
-
50
- _flush_current_seq()
51
-
52
- assert len(set(sequence_labels)) == len(sequence_labels), (
53
- "Found duplicate sequence labels"
54
- )
55
-
56
- return cls(sequence_labels, sequence_strs)
57
-
58
- def __len__(self):
59
- return len(self.sequence_labels)
60
-
61
- def __getitem__(self, idx):
62
- return self.sequence_labels[idx], self.sequence_strs[idx]
63
-
64
- def get_batch_indices(self, toks_per_batch, extra_toks_per_seq=0):
65
- sizes = [(len(s), i) for i, s in enumerate(self.sequence_strs)]
66
- sizes.sort()
67
- batches = []
68
- buf = []
69
- max_len = 0
70
-
71
- def _flush_current_buf():
72
- nonlocal max_len, buf
73
- if len(buf) == 0:
74
- return
75
- batches.append(buf)
76
- buf = []
77
- max_len = 0
78
-
79
- for sz, i in sizes:
80
- sz += extra_toks_per_seq
81
- if max(sz, max_len) * (len(buf) + 1) > toks_per_batch:
82
- _flush_current_buf()
83
- max_len = max(max_len, sz)
84
- buf.append(i)
85
-
86
- _flush_current_buf()
87
- return batches
88
-
89
-
90
- class Alphabet(object):
91
- def __init__(
92
- self,
93
- standard_toks: Sequence[str],
94
- prepend_toks: Sequence[str] = ("<null_0>", "<pad>", "<eos>", "<unk>"),
95
- append_toks: Sequence[str] = ("<cls>", "<mask>", "<sep>"),
96
- prepend_bos: bool = True,
97
- append_eos: bool = False,
98
- use_msa: bool = False,
99
- ):
100
- self.standard_toks = list(standard_toks)
101
- self.prepend_toks = list(prepend_toks)
102
- self.append_toks = list(append_toks)
103
- self.prepend_bos = prepend_bos
104
- self.append_eos = append_eos
105
- self.use_msa = use_msa
106
-
107
- self.all_toks = list(self.prepend_toks)
108
- self.all_toks.extend(self.standard_toks)
109
- for i in range((8 - (len(self.all_toks) % 8)) % 8):
110
- self.all_toks.append(f"<null_{i + 1}>")
111
- self.all_toks.extend(self.append_toks)
112
-
113
- self.tok_to_idx = {tok: i for i, tok in enumerate(self.all_toks)}
114
-
115
- self.unk_idx = self.tok_to_idx["<unk>"]
116
- self.padding_idx = self.get_idx("<pad>")
117
- self.cls_idx = self.get_idx("<cls>")
118
- self.mask_idx = self.get_idx("<mask>")
119
- self.eos_idx = self.get_idx("<eos>")
120
- self.all_special_tokens = ["<eos>", "<unk>", "<pad>", "<cls>", "<mask>"]
121
- self.unique_no_split_tokens = self.all_toks
122
-
123
- def __len__(self):
124
- return len(self.all_toks)
125
-
126
- def get_idx(self, tok):
127
- return self.tok_to_idx.get(tok, self.unk_idx)
128
-
129
- def get_tok(self, ind):
130
- return self.all_toks[ind]
131
-
132
- def to_dict(self):
133
- return self.tok_to_idx.copy()
134
-
135
- def get_batch_converter(self, truncation_seq_length: int = None):
136
- if self.use_msa:
137
- return MSABatchConverter(self, truncation_seq_length)
138
- else:
139
- return BatchConverter(self, truncation_seq_length)
140
-
141
- @classmethod
142
- def from_architecture(cls, name: str) -> "Alphabet":
143
- if name in ("ESM-1", "protein_bert_base"):
144
- standard_toks = proteinseq_toks["toks"]
145
- prepend_toks: Tuple[str, ...] = ("<null_0>", "<pad>", "<eos>", "<unk>")
146
- append_toks: Tuple[str, ...] = ("<cls>", "<mask>", "<sep>")
147
- prepend_bos = True
148
- append_eos = False
149
- use_msa = False
150
- elif name in ("ESM-1b", "roberta_large"):
151
- standard_toks = proteinseq_toks["toks"]
152
- prepend_toks = ("<cls>", "<pad>", "<eos>", "<unk>")
153
- append_toks = ("<mask>",)
154
- prepend_bos = True
155
- append_eos = True
156
- use_msa = False
157
- elif name in ("MSA Transformer", "msa_transformer"):
158
- standard_toks = proteinseq_toks["toks"]
159
- prepend_toks = ("<cls>", "<pad>", "<eos>", "<unk>")
160
- append_toks = ("<mask>",)
161
- prepend_bos = True
162
- append_eos = False
163
- use_msa = True
164
- elif "invariant_gvp" in name.lower():
165
- standard_toks = proteinseq_toks["toks"]
166
- prepend_toks = ("<null_0>", "<pad>", "<eos>", "<unk>")
167
- append_toks = ("<mask>", "<cath>", "<af2>")
168
- prepend_bos = True
169
- append_eos = False
170
- use_msa = False
171
- else:
172
- raise ValueError("Unknown architecture selected")
173
- return cls(
174
- standard_toks, prepend_toks, append_toks, prepend_bos, append_eos, use_msa
175
- )
176
-
177
- def _tokenize(self, text) -> str:
178
- return text.split()
179
-
180
- def tokenize(self, text, **kwargs) -> List[str]:
181
- """
182
- Inspired by https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils.py
183
- Converts a string in a sequence of tokens, using the tokenizer.
184
-
185
- Args:
186
- text (:obj:`str`):
187
- The sequence to be encoded.
188
-
189
- Returns:
190
- :obj:`List[str]`: The list of tokens.
191
- """
192
-
193
- def split_on_token(tok, text):
194
- result = []
195
- split_text = text.split(tok)
196
- for i, sub_text in enumerate(split_text):
197
- # AddedToken can control whitespace stripping around them.
198
- # We use them for GPT2 and Roberta to have different behavior depending on the special token
199
- # Cf. https://github.com/huggingface/transformers/pull/2778
200
- # and https://github.com/huggingface/transformers/issues/3788
201
- # We strip left and right by default
202
- if i < len(split_text) - 1:
203
- sub_text = sub_text.rstrip()
204
- if i > 0:
205
- sub_text = sub_text.lstrip()
206
-
207
- if i == 0 and not sub_text:
208
- result.append(tok)
209
- elif i == len(split_text) - 1:
210
- if sub_text:
211
- result.append(sub_text)
212
- else:
213
- pass
214
- else:
215
- if sub_text:
216
- result.append(sub_text)
217
- result.append(tok)
218
- return result
219
-
220
- def split_on_tokens(tok_list, text):
221
- if not text.strip():
222
- return []
223
-
224
- tokenized_text = []
225
- text_list = [text]
226
- for tok in tok_list:
227
- tokenized_text = []
228
- for sub_text in text_list:
229
- if sub_text not in self.unique_no_split_tokens:
230
- tokenized_text.extend(split_on_token(tok, sub_text))
231
- else:
232
- tokenized_text.append(sub_text)
233
- text_list = tokenized_text
234
-
235
- return list(
236
- itertools.chain.from_iterable(
237
- (
238
- self._tokenize(token)
239
- if token not in self.unique_no_split_tokens
240
- else [token]
241
- for token in tokenized_text
242
- )
243
- )
244
- )
245
-
246
- no_split_token = self.unique_no_split_tokens
247
- tokenized_text = split_on_tokens(no_split_token, text)
248
- return tokenized_text
249
-
250
- def encode(self, text):
251
- return [self.tok_to_idx[tok] for tok in self.tokenize(text)]
252
-
253
-
254
- class BatchConverter(object):
255
- """Callable to convert an unprocessed (labels + strings) batch to a
256
- processed (labels + tensor) batch.
257
- """
258
-
259
- def __init__(self, alphabet, truncation_seq_length: int = None):
260
- self.alphabet = alphabet
261
- self.truncation_seq_length = truncation_seq_length
262
-
263
- def __call__(self, raw_batch: Sequence[Tuple[str, str]]):
264
- # RoBERTa uses an eos token, while ESM-1 does not.
265
- batch_size = len(raw_batch)
266
- batch_labels, seq_str_list = zip(*raw_batch)
267
- seq_encoded_list = [self.alphabet.encode(seq_str) for seq_str in seq_str_list]
268
- if self.truncation_seq_length:
269
- seq_encoded_list = [
270
- seq_str[: self.truncation_seq_length] for seq_str in seq_encoded_list
271
- ]
272
- max_len = max(len(seq_encoded) for seq_encoded in seq_encoded_list)
273
- tokens = torch.empty(
274
- (
275
- batch_size,
276
- max_len
277
- + int(self.alphabet.prepend_bos)
278
- + int(self.alphabet.append_eos),
279
- ),
280
- dtype=torch.int64,
281
- )
282
- tokens.fill_(self.alphabet.padding_idx)
283
- labels = []
284
- strs = []
285
-
286
- for i, (label, seq_str, seq_encoded) in enumerate(
287
- zip(batch_labels, seq_str_list, seq_encoded_list)
288
- ):
289
- labels.append(label)
290
- strs.append(seq_str)
291
- if self.alphabet.prepend_bos:
292
- tokens[i, 0] = self.alphabet.cls_idx
293
- seq = torch.tensor(seq_encoded, dtype=torch.int64)
294
- tokens[
295
- i,
296
- int(self.alphabet.prepend_bos) : len(seq_encoded)
297
- + int(self.alphabet.prepend_bos),
298
- ] = seq
299
- if self.alphabet.append_eos:
300
- tokens[i, len(seq_encoded) + int(self.alphabet.prepend_bos)] = (
301
- self.alphabet.eos_idx
302
- )
303
-
304
- return labels, strs, tokens
305
-
306
-
307
- class MSABatchConverter(BatchConverter):
308
- def __call__(self, inputs: Union[Sequence[RawMSA], RawMSA]):
309
- if isinstance(inputs[0][0], str):
310
- # Input is a single MSA
311
- raw_batch: Sequence[RawMSA] = [inputs] # type: ignore
312
- else:
313
- raw_batch = inputs # type: ignore
314
-
315
- batch_size = len(raw_batch)
316
- max_alignments = max(len(msa) for msa in raw_batch)
317
- max_seqlen = max(len(msa[0][1]) for msa in raw_batch)
318
-
319
- tokens = torch.empty(
320
- (
321
- batch_size,
322
- max_alignments,
323
- max_seqlen
324
- + int(self.alphabet.prepend_bos)
325
- + int(self.alphabet.append_eos),
326
- ),
327
- dtype=torch.int64,
328
- )
329
- tokens.fill_(self.alphabet.padding_idx)
330
- labels = []
331
- strs = []
332
-
333
- for i, msa in enumerate(raw_batch):
334
- msa_seqlens = set(len(seq) for _, seq in msa)
335
- if not len(msa_seqlens) == 1:
336
- raise RuntimeError(
337
- "Received unaligned sequences for input to MSA, all sequence "
338
- "lengths must be equal."
339
- )
340
- msa_labels, msa_strs, msa_tokens = super().__call__(msa)
341
- labels.append(msa_labels)
342
- strs.append(msa_strs)
343
- tokens[i, : msa_tokens.size(0), : msa_tokens.size(1)] = msa_tokens
344
-
345
- return labels, strs, tokens
346
-
347
-
348
- def read_fasta(
349
- path,
350
- keep_gaps=True,
351
- keep_insertions=True,
352
- to_upper=False,
353
- ):
354
- with open(path, "r") as f:
355
- for result in read_alignment_lines(
356
- f, keep_gaps=keep_gaps, keep_insertions=keep_insertions, to_upper=to_upper
357
- ):
358
- yield result
359
-
360
-
361
- def read_alignment_lines(
362
- lines,
363
- keep_gaps=True,
364
- keep_insertions=True,
365
- to_upper=False,
366
- ):
367
- seq = desc = None
368
-
369
- def parse(s):
370
- if not keep_gaps:
371
- s = re.sub("-", "", s)
372
- if not keep_insertions:
373
- s = re.sub("[a-z]", "", s)
374
- return s.upper() if to_upper else s
375
-
376
- for line in lines:
377
- # Line may be empty if seq % file_line_width == 0
378
- if len(line) > 0 and line[0] == ">":
379
- if seq is not None:
380
- yield desc, parse(seq)
381
- desc = line.strip().lstrip(">")
382
- seq = ""
383
- else:
384
- assert isinstance(seq, str)
385
- seq += line.strip()
386
- assert isinstance(seq, str) and isinstance(desc, str)
387
- yield desc, parse(seq)
388
-
389
-
390
- class ESMStructuralSplitDataset(torch.utils.data.Dataset):
391
- """
392
- Structural Split Dataset as described in section A.10 of the supplement of our paper.
393
- https://doi.org/10.1101/622803
394
-
395
- We use the full version of SCOPe 2.07, clustered at 90% sequence identity,
396
- generated on January 23, 2020.
397
-
398
- For each SCOPe domain:
399
- - We extract the sequence from the corresponding PDB file
400
- - We extract the 3D coordinates of the Carbon beta atoms, aligning them
401
- to the sequence. We put NaN where Cb atoms are missing.
402
- - From the 3D coordinates, we calculate a pairwise distance map, based
403
- on L2 distance
404
- - We use DSSP to generate secondary structure labels for the corresponding
405
- PDB file. This is also aligned to the sequence. We put - where SSP
406
- labels are missing.
407
-
408
- For each SCOPe classification level of family/superfamily/fold (in order of difficulty),
409
- we have split the data into 5 partitions for cross validation. These are provided
410
- in a downloaded splits folder, in the format:
411
- splits/{split_level}/{cv_partition}/{train|valid}.txt
412
- where train is the partition and valid is the concatentation of the remaining 4.
413
-
414
- For each SCOPe domain, we provide a pkl dump that contains:
415
- - seq : The domain sequence, stored as an L-length string
416
- - ssp : The secondary structure labels, stored as an L-length string
417
- - dist : The distance map, stored as an LxL numpy array
418
- - coords : The 3D coordinates, stored as an Lx3 numpy array
419
-
420
- """
421
-
422
- base_folder = "structural-data"
423
- file_list = [
424
- # url tar filename filename MD5 Hash
425
- (
426
- "https://dl.fbaipublicfiles.com/fair-esm/structural-data/splits.tar.gz",
427
- "splits.tar.gz",
428
- "splits",
429
- "456fe1c7f22c9d3d8dfe9735da52411d",
430
- ),
431
- (
432
- "https://dl.fbaipublicfiles.com/fair-esm/structural-data/pkl.tar.gz",
433
- "pkl.tar.gz",
434
- "pkl",
435
- "644ea91e56066c750cd50101d390f5db",
436
- ),
437
- ]
438
-
439
- def __init__(
440
- self,
441
- split_level,
442
- cv_partition,
443
- split,
444
- root_path=os.path.expanduser("~/.cache/torch/data/esm"),
445
- download=False,
446
- ):
447
- super().__init__()
448
- assert split in [
449
- "train",
450
- "valid",
451
- ], "train_valid must be 'train' or 'valid'"
452
- self.root_path = root_path
453
- self.base_path = os.path.join(self.root_path, self.base_folder)
454
-
455
- # check if root path has what you need or else download it
456
- if download:
457
- self.download()
458
-
459
- self.split_file = os.path.join(
460
- self.base_path, "splits", split_level, cv_partition, f"{split}.txt"
461
- )
462
- self.pkl_dir = os.path.join(self.base_path, "pkl")
463
- self.names = []
464
- with open(self.split_file) as f:
465
- self.names = f.read().splitlines()
466
-
467
- def __len__(self):
468
- return len(self.names)
469
-
470
- def _check_exists(self) -> bool:
471
- for _, _, filename, _ in self.file_list:
472
- fpath = os.path.join(self.base_path, filename)
473
- if not os.path.exists(fpath) or not os.path.isdir(fpath):
474
- return False
475
- return True
476
-
477
- def download(self):
478
- if self._check_exists():
479
- print("Files already downloaded and verified")
480
- return
481
-
482
- from torchvision.datasets.utils import download_url
483
-
484
- for url, tar_filename, filename, md5_hash in self.file_list:
485
- download_path = os.path.join(self.base_path, tar_filename)
486
- download_url(
487
- url=url, root=self.base_path, filename=tar_filename, md5=md5_hash
488
- )
489
- shutil.unpack_archive(download_path, self.base_path)
490
-
491
- def __getitem__(self, idx):
492
- """
493
- Returns a dict with the following entires
494
- - seq : Str (domain sequence)
495
- - ssp : Str (SSP labels)
496
- - dist : np.array (distance map)
497
- - coords : np.array (3D coordinates)
498
- """
499
- name = self.names[idx]
500
- pkl_fname = os.path.join(self.pkl_dir, name[1:3], f"{name}.pkl")
501
- with open(pkl_fname, "rb") as f:
502
- obj = pickle.load(f)
503
- return obj
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/__init__.py DELETED
File without changes
protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/categorical_mixture.py DELETED
@@ -1,43 +0,0 @@
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/esmfold.py DELETED
@@ -1,363 +0,0 @@
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
7
- from functools import partial
8
-
9
- import torch
10
- import torch.nn as nn
11
- from torch.nn import LayerNorm
12
-
13
- import esm
14
- from esm import Alphabet
15
- from esm.esmfold.v1.categorical_mixture import categorical_lddt
16
- from esm.esmfold.v1.misc import (
17
- batch_encode_sequences,
18
- collate_dense_tensors,
19
- output_to_pdb,
20
- )
21
- from esm.esmfold.v1.trunk import FoldingTrunk, FoldingTrunkConfig
22
- from openfold.data.data_transforms import make_atom14_masks
23
- from openfold.np import residue_constants
24
- from openfold.utils.loss import compute_predicted_aligned_error, compute_tm
25
-
26
-
27
- @dataclass
28
- class ESMFoldConfig:
29
- trunk: T.Any = FoldingTrunkConfig()
30
- lddt_head_hid_dim: int = 128
31
-
32
-
33
- load_fn = esm.pretrained.load_model_and_alphabet
34
- esm_registry = {
35
- "esm2_8M": partial(load_fn, "esm2_t6_8M_UR50D_500K"),
36
- "esm2_8M_270K": esm.pretrained.esm2_t6_8M_UR50D,
37
- "esm2_35M": partial(load_fn, "esm2_t12_35M_UR50D_500K"),
38
- "esm2_35M_270K": esm.pretrained.esm2_t12_35M_UR50D,
39
- "esm2_150M": partial(load_fn, "esm2_t30_150M_UR50D_500K"),
40
- "esm2_150M_270K": partial(load_fn, "esm2_t30_150M_UR50D_270K"),
41
- "esm2_650M": esm.pretrained.esm2_t33_650M_UR50D,
42
- "esm2_650M_270K": partial(load_fn, "esm2_t33_650M_270K_UR50D"),
43
- "esm2_3B": esm.pretrained.esm2_t36_3B_UR50D,
44
- "esm2_3B_270K": partial(load_fn, "esm2_t36_3B_UR50D_500K"),
45
- "esm2_15B": esm.pretrained.esm2_t48_15B_UR50D,
46
- }
47
-
48
-
49
- class ESMFold(nn.Module):
50
- def __init__(self, esmfold_config=None, **kwargs):
51
- super().__init__()
52
-
53
- self.cfg = esmfold_config if esmfold_config else ESMFoldConfig(**kwargs)
54
- cfg = self.cfg
55
-
56
- self.distogram_bins = 64
57
-
58
- self.esm, self.esm_dict = esm_registry.get(cfg.esm_type)()
59
-
60
- self.esm.requires_grad_(False)
61
- self.esm.half()
62
-
63
- self.esm_feats = self.esm.embed_dim
64
- self.esm_attns = self.esm.num_layers * self.esm.attention_heads
65
- self.register_buffer("af2_to_esm", ESMFold._af2_to_esm(self.esm_dict))
66
- self.esm_s_combine = nn.Parameter(torch.zeros(self.esm.num_layers + 1))
67
-
68
- c_s = cfg.trunk.sequence_state_dim
69
- c_z = cfg.trunk.pairwise_state_dim
70
-
71
- self.esm_s_mlp = nn.Sequential(
72
- LayerNorm(self.esm_feats),
73
- nn.Linear(self.esm_feats, c_s),
74
- nn.ReLU(),
75
- nn.Linear(c_s, c_s),
76
- )
77
- if cfg.use_esm_attn_map:
78
- self.esm_z_mlp = nn.Sequential(
79
- LayerNorm(self.esm_attns),
80
- nn.Linear(self.esm_attns, c_z),
81
- nn.ReLU(),
82
- nn.Linear(c_z, c_z),
83
- )
84
-
85
- # 0 is padding, N is unknown residues, N + 1 is mask.
86
- self.n_tokens_embed = residue_constants.restype_num + 3
87
- self.pad_idx = 0
88
- self.unk_idx = self.n_tokens_embed - 2
89
- self.mask_idx = self.n_tokens_embed - 1
90
- self.embedding = nn.Embedding(self.n_tokens_embed, c_s, padding_idx=0)
91
-
92
- self.trunk = FoldingTrunk(**cfg.trunk)
93
-
94
- self.distogram_head = nn.Linear(c_z, self.distogram_bins)
95
- self.ptm_head = nn.Linear(c_z, self.distogram_bins)
96
- self.lm_head = nn.Linear(c_s, self.n_tokens_embed)
97
- self.lddt_bins = 50
98
- self.lddt_head = nn.Sequential(
99
- nn.LayerNorm(cfg.trunk.structure_module.c_s),
100
- nn.Linear(cfg.trunk.structure_module.c_s, cfg.lddt_head_hid_dim),
101
- nn.Linear(cfg.lddt_head_hid_dim, cfg.lddt_head_hid_dim),
102
- nn.Linear(cfg.lddt_head_hid_dim, 37 * self.lddt_bins),
103
- )
104
-
105
- @staticmethod
106
- def _af2_to_esm(d: Alphabet):
107
- # Remember that t is shifted from residue_constants by 1 (0 is padding).
108
- esm_reorder = [d.padding_idx] + [
109
- d.get_idx(v) for v in residue_constants.restypes_with_x
110
- ]
111
- return torch.tensor(esm_reorder)
112
-
113
- def _af2_idx_to_esm_idx(self, aa, mask):
114
- aa = (aa + 1).masked_fill(mask != 1, 0)
115
- return self.af2_to_esm[aa]
116
-
117
- def _compute_language_model_representations(
118
- self, esmaa: torch.Tensor
119
- ) -> torch.Tensor:
120
- """Adds bos/eos tokens for the language model, since the structure module doesn't use these."""
121
- batch_size = esmaa.size(0)
122
-
123
- bosi, eosi = self.esm_dict.cls_idx, self.esm_dict.eos_idx
124
- bos = esmaa.new_full((batch_size, 1), bosi)
125
- eos = esmaa.new_full((batch_size, 1), self.esm_dict.padding_idx)
126
- esmaa = torch.cat([bos, esmaa, eos], dim=1)
127
- # Use the first padding index as eos during inference.
128
- esmaa[range(batch_size), (esmaa != 1).sum(1)] = eosi
129
-
130
- res = self.esm(
131
- esmaa,
132
- repr_layers=range(self.esm.num_layers + 1),
133
- need_head_weights=self.cfg.use_esm_attn_map,
134
- )
135
- esm_s = torch.stack(
136
- [v for _, v in sorted(res["representations"].items())], dim=2
137
- )
138
- esm_s = esm_s[:, 1:-1] # B, L, nLayers, C
139
- esm_z = (
140
- res["attentions"].permute(0, 4, 3, 1, 2).flatten(3, 4)[:, 1:-1, 1:-1, :]
141
- if self.cfg.use_esm_attn_map
142
- else None
143
- )
144
- return esm_s, esm_z
145
-
146
- def _mask_inputs_to_esm(self, esmaa, pattern):
147
- new_esmaa = esmaa.clone()
148
- new_esmaa[pattern == 1] = self.esm_dict.mask_idx
149
- return new_esmaa
150
-
151
- def forward(
152
- self,
153
- aa: torch.Tensor,
154
- mask: T.Optional[torch.Tensor] = None,
155
- residx: T.Optional[torch.Tensor] = None,
156
- masking_pattern: T.Optional[torch.Tensor] = None,
157
- num_recycles: T.Optional[int] = None,
158
- ):
159
- """Runs a forward pass given input tokens. Use `model.infer` to
160
- run inference from a sequence.
161
-
162
- Args:
163
- aa (torch.Tensor): Tensor containing indices corresponding to amino acids. Indices match
164
- openfold.np.residue_constants.restype_order_with_x.
165
- mask (torch.Tensor): Binary tensor with 1 meaning position is unmasked and 0 meaning position is masked.
166
- residx (torch.Tensor): Residue indices of amino acids. Will assume contiguous if not provided.
167
- masking_pattern (torch.Tensor): Optional masking to pass to the input. Binary tensor of the same size
168
- as `aa`. Positions with 1 will be masked. ESMFold sometimes produces different samples when
169
- different masks are provided.
170
- num_recycles (int): How many recycle iterations to perform. If None, defaults to training max
171
- recycles, which is 3.
172
- """
173
-
174
- if mask is None:
175
- mask = torch.ones_like(aa)
176
-
177
- B = aa.shape[0]
178
- L = aa.shape[1]
179
- device = aa.device
180
-
181
- if residx is None:
182
- residx = torch.arange(L, device=device).expand_as(aa)
183
-
184
- # === ESM ===
185
- esmaa = self._af2_idx_to_esm_idx(aa, mask)
186
-
187
- if masking_pattern is not None:
188
- esmaa = self._mask_inputs_to_esm(esmaa, masking_pattern)
189
-
190
- esm_s, esm_z = self._compute_language_model_representations(esmaa)
191
-
192
- # Convert esm_s to the precision used by the trunk and
193
- # the structure module. These tensors may be a lower precision if, for example,
194
- # we're running the language model in fp16 precision.
195
- esm_s = esm_s.to(self.esm_s_combine.dtype)
196
- esm_s = esm_s.detach()
197
-
198
- # === preprocessing ===
199
- esm_s = (self.esm_s_combine.softmax(0).unsqueeze(0) @ esm_s).squeeze(2)
200
-
201
- s_s_0 = self.esm_s_mlp(esm_s)
202
- if self.cfg.use_esm_attn_map:
203
- esm_z = esm_z.to(self.esm_s_combine.dtype)
204
- esm_z = esm_z.detach()
205
- s_z_0 = self.esm_z_mlp(esm_z)
206
- else:
207
- s_z_0 = s_s_0.new_zeros(B, L, L, self.cfg.trunk.pairwise_state_dim)
208
-
209
- s_s_0 += self.embedding(aa)
210
-
211
- structure: dict = self.trunk(
212
- s_s_0, s_z_0, aa, residx, mask, no_recycles=num_recycles
213
- )
214
- # Documenting what we expect:
215
- structure = {
216
- k: v
217
- for k, v in structure.items()
218
- if k
219
- in [
220
- "s_z",
221
- "s_s",
222
- "frames",
223
- "sidechain_frames",
224
- "unnormalized_angles",
225
- "angles",
226
- "positions",
227
- "states",
228
- ]
229
- }
230
-
231
- disto_logits = self.distogram_head(structure["s_z"])
232
- disto_logits = (disto_logits + disto_logits.transpose(1, 2)) / 2
233
- structure["distogram_logits"] = disto_logits
234
-
235
- lm_logits = self.lm_head(structure["s_s"])
236
- structure["lm_logits"] = lm_logits
237
-
238
- structure["aatype"] = aa
239
- make_atom14_masks(structure)
240
-
241
- for k in [
242
- "atom14_atom_exists",
243
- "atom37_atom_exists",
244
- ]:
245
- structure[k] *= mask.unsqueeze(-1)
246
- structure["residue_index"] = residx
247
-
248
- lddt_head = self.lddt_head(structure["states"]).reshape(
249
- structure["states"].shape[0], B, L, -1, self.lddt_bins
250
- )
251
- structure["lddt_head"] = lddt_head
252
- plddt = categorical_lddt(lddt_head[-1], bins=self.lddt_bins)
253
- structure["plddt"] = (
254
- 100 * plddt
255
- ) # we predict plDDT between 0 and 1, scale to be between 0 and 100.
256
-
257
- ptm_logits = self.ptm_head(structure["s_z"])
258
-
259
- seqlen = mask.type(torch.int64).sum(1)
260
- structure["ptm_logits"] = ptm_logits
261
- structure["ptm"] = torch.stack(
262
- [
263
- compute_tm(
264
- batch_ptm_logits[None, :sl, :sl],
265
- max_bins=31,
266
- no_bins=self.distogram_bins,
267
- )
268
- for batch_ptm_logits, sl in zip(ptm_logits, seqlen)
269
- ]
270
- )
271
- structure.update(
272
- compute_predicted_aligned_error(
273
- ptm_logits, max_bin=31, no_bins=self.distogram_bins
274
- )
275
- )
276
-
277
- return structure
278
-
279
- @torch.no_grad()
280
- def infer(
281
- self,
282
- sequences: T.Union[str, T.List[str]],
283
- residx=None,
284
- masking_pattern: T.Optional[torch.Tensor] = None,
285
- num_recycles: T.Optional[int] = None,
286
- residue_index_offset: T.Optional[int] = 512,
287
- chain_linker: T.Optional[str] = "G" * 25,
288
- ):
289
- """Runs a forward pass given input sequences.
290
-
291
- Args:
292
- sequences (Union[str, List[str]]): A list of sequences to make predictions for. Multimers can also be passed in,
293
- each chain should be separated by a ':' token (e.g. "<chain1>:<chain2>:<chain3>").
294
- residx (torch.Tensor): Residue indices of amino acids. Will assume contiguous if not provided.
295
- masking_pattern (torch.Tensor): Optional masking to pass to the input. Binary tensor of the same size
296
- as `aa`. Positions with 1 will be masked. ESMFold sometimes produces different samples when
297
- different masks are provided.
298
- num_recycles (int): How many recycle iterations to perform. If None, defaults to training max
299
- recycles (cfg.trunk.max_recycles), which is 4.
300
- residue_index_offset (int): Residue index separation between chains if predicting a multimer. Has no effect on
301
- single chain predictions. Default: 512.
302
- chain_linker (str): Linker to use between chains if predicting a multimer. Has no effect on single chain
303
- predictions. Default: length-25 poly-G ("G" * 25).
304
- """
305
- if isinstance(sequences, str):
306
- sequences = [sequences]
307
-
308
- aatype, mask, _residx, linker_mask, chain_index = batch_encode_sequences(
309
- sequences, residue_index_offset, chain_linker
310
- )
311
-
312
- if residx is None:
313
- residx = _residx
314
- elif not isinstance(residx, torch.Tensor):
315
- residx = collate_dense_tensors(residx)
316
-
317
- aatype, mask, residx, linker_mask = map(
318
- lambda x: x.to(self.device), (aatype, mask, residx, linker_mask)
319
- )
320
-
321
- output = self.forward(
322
- aatype,
323
- mask=mask,
324
- residx=residx,
325
- masking_pattern=masking_pattern,
326
- num_recycles=num_recycles,
327
- )
328
-
329
- output["atom37_atom_exists"] = output[
330
- "atom37_atom_exists"
331
- ] * linker_mask.unsqueeze(2)
332
-
333
- output["mean_plddt"] = (output["plddt"] * output["atom37_atom_exists"]).sum(
334
- dim=(1, 2)
335
- ) / output["atom37_atom_exists"].sum(dim=(1, 2))
336
- output["chain_index"] = chain_index
337
-
338
- return output
339
-
340
- def output_to_pdb(self, output: T.Dict) -> T.List[str]:
341
- """Returns the pbd (file) string from the model given the model output."""
342
- return output_to_pdb(output)
343
-
344
- def infer_pdbs(self, seqs: T.List[str], *args, **kwargs) -> T.List[str]:
345
- """Returns list of pdb (files) strings from the model given a list of input sequences."""
346
- output = self.infer(seqs, *args, **kwargs)
347
- return self.output_to_pdb(output)
348
-
349
- def infer_pdb(self, sequence: str, *args, **kwargs) -> str:
350
- """Returns the pdb (file) string from the model given an input sequence."""
351
- return self.infer_pdbs([sequence], *args, **kwargs)[0]
352
-
353
- def set_chunk_size(self, chunk_size: T.Optional[int]):
354
- # This parameter means the axial attention will be computed
355
- # in a chunked manner. This should make the memory used more or less O(L) instead of O(L^2).
356
- # It's equivalent to running a for loop over chunks of the dimension we're iterative over,
357
- # where the chunk_size is the size of the chunks, so 128 would mean to parse 128-lengthed chunks.
358
- # Setting the value to None will return to default behavior, disable chunking.
359
- self.trunk.set_chunk_size(chunk_size)
360
-
361
- @property
362
- def device(self):
363
- return self.esm_s_combine.device
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/misc.py DELETED
@@ -1,308 +0,0 @@
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
-
7
- import numpy as np
8
- import torch
9
- import torch.nn.functional as F
10
- from einops import rearrange, repeat
11
- from torch import nn
12
- from openfold.np import residue_constants
13
- from openfold.np.protein import Protein as OFProtein
14
- from openfold.np.protein import to_pdb
15
- from openfold.utils.feats import atom14_to_atom37
16
-
17
-
18
- def encode_sequence(
19
- seq: str,
20
- residue_index_offset: T.Optional[int] = 512,
21
- chain_linker: T.Optional[str] = "G" * 25,
22
- ) -> T.Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
23
- if chain_linker is None:
24
- chain_linker = ""
25
- if residue_index_offset is None:
26
- residue_index_offset = 0
27
-
28
- chains = seq.split(":")
29
- seq = chain_linker.join(chains)
30
-
31
- unk_idx = residue_constants.restype_order_with_x["X"]
32
- encoded = torch.tensor(
33
- [residue_constants.restype_order_with_x.get(aa, unk_idx) for aa in seq]
34
- )
35
- residx = torch.arange(len(encoded))
36
-
37
- if residue_index_offset > 0:
38
- start = 0
39
- for i, chain in enumerate(chains):
40
- residx[start : start + len(chain) + len(chain_linker)] += (
41
- i * residue_index_offset
42
- )
43
- start += len(chain) + len(chain_linker)
44
-
45
- linker_mask = torch.ones_like(encoded, dtype=torch.float32)
46
- chain_index = []
47
- offset = 0
48
- for i, chain in enumerate(chains):
49
- if i > 0:
50
- chain_index.extend([i - 1] * len(chain_linker))
51
- chain_index.extend([i] * len(chain))
52
- offset += len(chain)
53
- linker_mask[offset : offset + len(chain_linker)] = 0
54
- offset += len(chain_linker)
55
-
56
- chain_index = torch.tensor(chain_index, dtype=torch.int64)
57
-
58
- return encoded, residx, linker_mask, chain_index
59
-
60
-
61
- def batch_encode_sequences(
62
- sequences: T.Sequence[str],
63
- residue_index_offset: T.Optional[int] = 512,
64
- chain_linker: T.Optional[str] = "G" * 25,
65
- ) -> T.Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
66
- aatype_list = []
67
- residx_list = []
68
- linker_mask_list = []
69
- chain_index_list = []
70
- for seq in sequences:
71
- aatype_seq, residx_seq, linker_mask_seq, chain_index_seq = encode_sequence(
72
- seq,
73
- residue_index_offset=residue_index_offset,
74
- chain_linker=chain_linker,
75
- )
76
- aatype_list.append(aatype_seq)
77
- residx_list.append(residx_seq)
78
- linker_mask_list.append(linker_mask_seq)
79
- chain_index_list.append(chain_index_seq)
80
-
81
- aatype = collate_dense_tensors(aatype_list)
82
- mask = collate_dense_tensors(
83
- [aatype.new_ones(len(aatype_seq)) for aatype_seq in aatype_list]
84
- )
85
- residx = collate_dense_tensors(residx_list)
86
- linker_mask = collate_dense_tensors(linker_mask_list)
87
- chain_index_list = collate_dense_tensors(chain_index_list, -1)
88
-
89
- return aatype, mask, residx, linker_mask, chain_index_list
90
-
91
-
92
- def output_to_pdb(output: T.Dict) -> T.List[str]:
93
- """Returns the pbd (file) string from the model given the model output."""
94
- # atom14_to_atom37 must be called first, as it fails on latest numpy if the
95
- # input is a numpy array. It will work if the input is a torch tensor.
96
- final_atom_positions = atom14_to_atom37(output["positions"][-1], output)
97
- output = {k: v.to("cpu").numpy() for k, v in output.items()}
98
- final_atom_positions = final_atom_positions.cpu().numpy()
99
- final_atom_mask = output["atom37_atom_exists"]
100
- pdbs = []
101
- for i in range(output["aatype"].shape[0]):
102
- aa = output["aatype"][i]
103
- pred_pos = final_atom_positions[i]
104
- mask = final_atom_mask[i]
105
- resid = output["residue_index"][i] + 1
106
- pred = OFProtein(
107
- aatype=aa,
108
- atom_positions=pred_pos,
109
- atom_mask=mask,
110
- residue_index=resid,
111
- b_factors=output["plddt"][i],
112
- chain_index=output["chain_index"][i] if "chain_index" in output else None,
113
- )
114
- pdbs.append(to_pdb(pred))
115
- return pdbs
116
-
117
-
118
- def collate_dense_tensors(
119
- samples: T.List[torch.Tensor], pad_v: float = 0
120
- ) -> torch.Tensor:
121
- """
122
- Takes a list of tensors with the following dimensions:
123
- [(d_11, ..., d_1K),
124
- (d_21, ..., d_2K),
125
- ...,
126
- (d_N1, ..., d_NK)]
127
- and stack + pads them into a single tensor of:
128
- (N, max_i=1,N { d_i1 }, ..., max_i=1,N {diK})
129
- """
130
- if len(samples) == 0:
131
- return torch.Tensor()
132
- if len(set(x.dim() for x in samples)) != 1:
133
- raise RuntimeError(
134
- f"Samples has varying dimensions: {[x.dim() for x in samples]}"
135
- )
136
- (device,) = tuple(set(x.device for x in samples)) # assumes all on same device
137
- max_shape = [max(lst) for lst in zip(*[x.shape for x in samples])]
138
- result = torch.empty(
139
- len(samples), *max_shape, dtype=samples[0].dtype, device=device
140
- )
141
- result.fill_(pad_v)
142
- for i in range(len(samples)):
143
- result_i = result[i]
144
- t = samples[i]
145
- result_i[tuple(slice(0, k) for k in t.shape)] = t
146
- return result
147
-
148
-
149
- class Attention(nn.Module):
150
- def __init__(self, embed_dim, num_heads, head_width, gated=False):
151
- super().__init__()
152
- assert embed_dim == num_heads * head_width
153
-
154
- self.embed_dim = embed_dim
155
- self.num_heads = num_heads
156
- self.head_width = head_width
157
-
158
- self.proj = nn.Linear(embed_dim, embed_dim * 3, bias=False)
159
- self.o_proj = nn.Linear(embed_dim, embed_dim, bias=True)
160
- self.gated = gated
161
- if gated:
162
- self.g_proj = nn.Linear(embed_dim, embed_dim)
163
- torch.nn.init.zeros_(self.g_proj.weight)
164
- torch.nn.init.ones_(self.g_proj.bias)
165
-
166
- self.rescale_factor = self.head_width**-0.5
167
-
168
- torch.nn.init.zeros_(self.o_proj.bias)
169
-
170
- def forward(self, x, mask=None, bias=None, indices=None):
171
- """
172
- Basic self attention with optional mask and external pairwise bias.
173
- To handle sequences of different lengths, use mask.
174
-
175
- Inputs:
176
- x: batch of input sequneces (.. x L x C)
177
- mask: batch of boolean masks where 1=valid, 0=padding position (.. x L_k). optional.
178
- bias: batch of scalar pairwise attention biases (.. x Lq x Lk x num_heads). optional.
179
-
180
- Outputs:
181
- sequence projection (B x L x embed_dim), attention maps (B x L x L x num_heads)
182
- """
183
-
184
- t = rearrange(self.proj(x), "... l (h c) -> ... h l c", h=self.num_heads)
185
- q, k, v = t.chunk(3, dim=-1)
186
-
187
- q = self.rescale_factor * q
188
- a = torch.einsum("...qc,...kc->...qk", q, k)
189
-
190
- # Add external attention bias.
191
- if bias is not None:
192
- a = a + rearrange(bias, "... lq lk h -> ... h lq lk")
193
-
194
- # Do not attend to padding tokens.
195
- if mask is not None:
196
- mask = repeat(
197
- mask, "... lk -> ... h lq lk", h=self.num_heads, lq=q.shape[-2]
198
- )
199
- a = a.masked_fill(mask == False, -np.inf)
200
-
201
- a = F.softmax(a, dim=-1)
202
-
203
- y = torch.einsum("...hqk,...hkc->...qhc", a, v)
204
- y = rearrange(y, "... h c -> ... (h c)", h=self.num_heads)
205
-
206
- if self.gated:
207
- y = self.g_proj(x).sigmoid() * y
208
- y = self.o_proj(y)
209
-
210
- return y, rearrange(a, "... lq lk h -> ... h lq lk")
211
-
212
-
213
- class Dropout(nn.Module):
214
- """
215
- Implementation of dropout with the ability to share the dropout mask
216
- along a particular dimension.
217
- """
218
-
219
- def __init__(self, r: float, batch_dim: T.Union[int, T.List[int]]):
220
- super(Dropout, self).__init__()
221
-
222
- self.r = r
223
- if type(batch_dim) == int:
224
- batch_dim = [batch_dim]
225
- self.batch_dim = batch_dim
226
- self.dropout = nn.Dropout(self.r)
227
-
228
- def forward(self, x: torch.Tensor) -> torch.Tensor:
229
- shape = list(x.shape)
230
- if self.batch_dim is not None:
231
- for bd in self.batch_dim:
232
- shape[bd] = 1
233
- return x * self.dropout(x.new_ones(shape))
234
-
235
-
236
- class SequenceToPair(nn.Module):
237
- def __init__(self, sequence_state_dim, inner_dim, pairwise_state_dim):
238
- super().__init__()
239
-
240
- self.layernorm = nn.LayerNorm(sequence_state_dim)
241
- self.proj = nn.Linear(sequence_state_dim, inner_dim * 2, bias=True)
242
- self.o_proj = nn.Linear(2 * inner_dim, pairwise_state_dim, bias=True)
243
-
244
- torch.nn.init.zeros_(self.proj.bias)
245
- torch.nn.init.zeros_(self.o_proj.bias)
246
-
247
- def forward(self, sequence_state):
248
- """
249
- Inputs:
250
- sequence_state: B x L x sequence_state_dim
251
-
252
- Output:
253
- pairwise_state: B x L x L x pairwise_state_dim
254
-
255
- Intermediate state:
256
- B x L x L x 2*inner_dim
257
- """
258
-
259
- assert len(sequence_state.shape) == 3
260
-
261
- s = self.layernorm(sequence_state)
262
- s = self.proj(s)
263
- q, k = s.chunk(2, dim=-1)
264
-
265
- prod = q[:, None, :, :] * k[:, :, None, :]
266
- diff = q[:, None, :, :] - k[:, :, None, :]
267
-
268
- x = torch.cat([prod, diff], dim=-1)
269
- x = self.o_proj(x)
270
-
271
- return x
272
-
273
-
274
- class PairToSequence(nn.Module):
275
- def __init__(self, pairwise_state_dim, num_heads):
276
- super().__init__()
277
-
278
- self.layernorm = nn.LayerNorm(pairwise_state_dim)
279
- self.linear = nn.Linear(pairwise_state_dim, num_heads, bias=False)
280
-
281
- def forward(self, pairwise_state):
282
- """
283
- Inputs:
284
- pairwise_state: B x L x L x pairwise_state_dim
285
-
286
- Output:
287
- pairwise_bias: B x L x L x num_heads
288
- """
289
- assert len(pairwise_state.shape) == 4
290
- z = self.layernorm(pairwise_state)
291
- pairwise_bias = self.linear(z)
292
- return pairwise_bias
293
-
294
-
295
- class ResidueMLP(nn.Module):
296
- def __init__(self, embed_dim, inner_dim, norm=nn.LayerNorm, dropout=0):
297
- super().__init__()
298
-
299
- self.mlp = nn.Sequential(
300
- norm(embed_dim),
301
- nn.Linear(embed_dim, inner_dim),
302
- nn.ReLU(),
303
- nn.Linear(inner_dim, embed_dim),
304
- nn.Dropout(dropout),
305
- )
306
-
307
- def forward(self, x):
308
- return x + self.mlp(x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/pretrained.py DELETED
@@ -1,183 +0,0 @@
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
- from pathlib import Path
7
-
8
- import torch
9
-
10
- from esm.esmfold.v1.esmfold import ESMFold
11
-
12
-
13
- def _load_model(model_name):
14
- if model_name.endswith(".pt"): # local, treat as filepath
15
- model_path = Path(model_name)
16
- model_data = torch.load(str(model_path), map_location="cpu")
17
- else: # load from hub
18
- url = f"https://dl.fbaipublicfiles.com/fair-esm/models/{model_name}.pt"
19
- model_data = torch.hub.load_state_dict_from_url(
20
- url, progress=False, map_location="cpu"
21
- )
22
-
23
- cfg = model_data["cfg"]["model"]
24
- model_state = model_data["model"]
25
- model = ESMFold(esmfold_config=cfg)
26
-
27
- expected_keys = set(model.state_dict().keys())
28
- found_keys = set(model_state.keys())
29
-
30
- missing_essential_keys = []
31
- for missing_key in expected_keys - found_keys:
32
- if not missing_key.startswith("esm."):
33
- missing_essential_keys.append(missing_key)
34
-
35
- if missing_essential_keys:
36
- raise RuntimeError(f"Keys '{', '.join(missing_essential_keys)}' are missing.")
37
-
38
- model.load_state_dict(model_state, strict=False)
39
-
40
- return model
41
-
42
-
43
- def esmfold_v0():
44
- """
45
- ESMFold v0 model with 3B ESM-2, 48 folding blocks.
46
- This version was used for the paper (Lin et al, 2022). It was trained
47
- on all PDB chains until 2020-05, to ensure temporal holdout with CASP14
48
- and the CAMEO validation and test set reported there.
49
- """
50
- return _load_model("esmfold_3B_v0")
51
-
52
-
53
- def esmfold_v1():
54
- """
55
- ESMFold v1 model using 3B ESM-2, 48 folding blocks.
56
- ESMFold provides fast high accuracy atomic level structure prediction
57
- directly from the individual sequence of a protein. ESMFold uses the ESM2
58
- protein language model to extract meaningful representations from the
59
- protein sequence.
60
- """
61
- return _load_model("esmfold_3B_v1")
62
-
63
-
64
- def esmfold_structure_module_only_8M():
65
- """
66
- ESMFold baseline model using 8M ESM-2, 0 folding blocks.
67
- ESM-2 here is trained out to 500K updates.
68
- This is a model designed to test the capabilities of the language model
69
- when ablated for number of parameters in the language model.
70
- See table S1 in (Lin et al, 2022).
71
- """
72
- return _load_model("esmfold_structure_module_only_8M")
73
-
74
-
75
- def esmfold_structure_module_only_8M_270K():
76
- """
77
- ESMFold baseline model using 8M ESM-2, 0 folding blocks.
78
- ESM-2 here is trained out to 270K updates.
79
- This is a model designed to test the capabilities of the language model
80
- when ablated for number of parameters in the language model.
81
- See table S1 in (Lin et al, 2022).
82
- """
83
- return _load_model("esmfold_structure_module_only_8M_270K")
84
-
85
-
86
- def esmfold_structure_module_only_35M():
87
- """
88
- ESMFold baseline model using 35M ESM-2, 0 folding blocks.
89
- ESM-2 here is trained out to 500K updates.
90
- This is a model designed to test the capabilities of the language model
91
- when ablated for number of parameters in the language model.
92
- See table S1 in (Lin et al, 2022).
93
- """
94
- return _load_model("esmfold_structure_module_only_35M")
95
-
96
-
97
- def esmfold_structure_module_only_35M_270K():
98
- """
99
- ESMFold baseline model using 35M ESM-2, 0 folding blocks.
100
- ESM-2 here is trained out to 270K updates.
101
- This is a model designed to test the capabilities of the language model
102
- when ablated for number of parameters in the language model.
103
- See table S1 in (Lin et al, 2022).
104
- """
105
- return _load_model("esmfold_structure_module_only_35M_270K")
106
-
107
-
108
- def esmfold_structure_module_only_150M():
109
- """
110
- ESMFold baseline model using 150M ESM-2, 0 folding blocks.
111
- ESM-2 here is trained out to 500K updates.
112
- This is a model designed to test the capabilities of the language model
113
- when ablated for number of parameters in the language model.
114
- See table S1 in (Lin et al, 2022).
115
- """
116
- return _load_model("esmfold_structure_module_only_150M")
117
-
118
-
119
- def esmfold_structure_module_only_150M_270K():
120
- """
121
- ESMFold baseline model using 150M ESM-2, 0 folding blocks.
122
- ESM-2 here is trained out to 270K updates.
123
- This is a model designed to test the capabilities of the language model
124
- when ablated for number of parameters in the language model.
125
- See table S1 in (Lin et al, 2022).
126
- """
127
- return _load_model("esmfold_structure_module_only_150M_270K")
128
-
129
-
130
- def esmfold_structure_module_only_650M():
131
- """
132
- ESMFold baseline model using 650M ESM-2, 0 folding blocks.
133
- ESM-2 here is trained out to 500K updates.
134
- This is a model designed to test the capabilities of the language model
135
- when ablated for number of parameters in the language model.
136
- See table S1 in (Lin et al, 2022).
137
- """
138
- return _load_model("esmfold_structure_module_only_650M")
139
-
140
-
141
- def esmfold_structure_module_only_650M_270K():
142
- """
143
- ESMFold baseline model using 650M ESM-2, 0 folding blocks.
144
- ESM-2 here is trained out to 270K updates.
145
- This is a model designed to test the capabilities of the language model
146
- when ablated for number of parameters in the language model.
147
- See table S1 in (Lin et al, 2022).
148
- """
149
- return _load_model("esmfold_structure_module_only_650M_270K")
150
-
151
-
152
- def esmfold_structure_module_only_3B():
153
- """
154
- ESMFold baseline model using 3B ESM-2, 0 folding blocks.
155
- ESM-2 here is trained out to 500K updates.
156
- This is a model designed to test the capabilities of the language model
157
- when ablated for number of parameters in the language model.
158
- See table S1 in (Lin et al, 2022).
159
- """
160
- return _load_model("esmfold_structure_module_only_3B")
161
-
162
-
163
- def esmfold_structure_module_only_3B_270K():
164
- """
165
- ESMFold baseline model using 3B ESM-2, 0 folding blocks.
166
- ESM-2 here is trained out to 270K updates.
167
- This is a model designed to test the capabilities of the language model
168
- when ablated for number of parameters in the language model.
169
- See table S1 in (Lin et al, 2022).
170
- """
171
- return _load_model("esmfold_structure_module_only_3B_270K")
172
-
173
-
174
- def esmfold_structure_module_only_15B():
175
- """
176
- ESMFold baseline model using 15B ESM-2, 0 folding blocks.
177
- ESM-2 here is trained out to 270K updates.
178
- The 15B parameter ESM-2 was not trained out to 500K updates
179
- This is a model designed to test the capabilities of the language model
180
- when ablated for number of parameters in the language model.
181
- See table S1 in (Lin et al, 2022).
182
- """
183
- return _load_model("esmfold_structure_module_only_15B")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/tri_self_attn_block.py DELETED
@@ -1,166 +0,0 @@
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 openfold.model.triangular_attention import (
7
- TriangleAttentionEndingNode,
8
- TriangleAttentionStartingNode,
9
- )
10
- from openfold.model.triangular_multiplicative_update import (
11
- TriangleMultiplicationIncoming,
12
- TriangleMultiplicationOutgoing,
13
- )
14
- from torch import nn
15
-
16
- from 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(
80
- sequence_state_dim, 4 * sequence_state_dim, dropout=dropout
81
- )
82
- self.mlp_pair = ResidueMLP(
83
- pairwise_state_dim, 4 * pairwise_state_dim, dropout=dropout
84
- )
85
-
86
- assert dropout < 0.4
87
- self.drop = nn.Dropout(dropout)
88
- self.row_drop = Dropout(dropout * 2, 2)
89
- self.col_drop = Dropout(dropout * 2, 1)
90
-
91
- torch.nn.init.zeros_(self.tri_mul_in.linear_z.weight)
92
- torch.nn.init.zeros_(self.tri_mul_in.linear_z.bias)
93
- torch.nn.init.zeros_(self.tri_mul_out.linear_z.weight)
94
- torch.nn.init.zeros_(self.tri_mul_out.linear_z.bias)
95
- torch.nn.init.zeros_(self.tri_att_start.mha.linear_o.weight)
96
- torch.nn.init.zeros_(self.tri_att_start.mha.linear_o.bias)
97
- torch.nn.init.zeros_(self.tri_att_end.mha.linear_o.weight)
98
- torch.nn.init.zeros_(self.tri_att_end.mha.linear_o.bias)
99
-
100
- torch.nn.init.zeros_(self.sequence_to_pair.o_proj.weight)
101
- torch.nn.init.zeros_(self.sequence_to_pair.o_proj.bias)
102
- torch.nn.init.zeros_(self.pair_to_sequence.linear.weight)
103
- torch.nn.init.zeros_(self.seq_attention.o_proj.weight)
104
- torch.nn.init.zeros_(self.seq_attention.o_proj.bias)
105
- torch.nn.init.zeros_(self.mlp_seq.mlp[-2].weight)
106
- torch.nn.init.zeros_(self.mlp_seq.mlp[-2].bias)
107
- torch.nn.init.zeros_(self.mlp_pair.mlp[-2].weight)
108
- torch.nn.init.zeros_(self.mlp_pair.mlp[-2].bias)
109
-
110
- def forward(
111
- self, sequence_state, pairwise_state, mask=None, chunk_size=None, **__kwargs
112
- ):
113
- """
114
- Inputs:
115
- sequence_state: B x L x sequence_state_dim
116
- pairwise_state: B x L x L x pairwise_state_dim
117
- mask: B x L boolean tensor of valid positions
118
-
119
- Output:
120
- sequence_state: B x L x sequence_state_dim
121
- pairwise_state: B x L x L x pairwise_state_dim
122
- """
123
- assert len(sequence_state.shape) == 3
124
- assert len(pairwise_state.shape) == 4
125
- if mask is not None:
126
- assert len(mask.shape) == 2
127
-
128
- batch_dim, seq_dim, sequence_state_dim = sequence_state.shape
129
- pairwise_state_dim = pairwise_state.shape[3]
130
- assert sequence_state_dim == self.sequence_state_dim
131
- assert pairwise_state_dim == self.pairwise_state_dim
132
- assert batch_dim == pairwise_state.shape[0]
133
- assert seq_dim == pairwise_state.shape[1]
134
- assert seq_dim == pairwise_state.shape[2]
135
-
136
- # Update sequence state
137
- bias = self.pair_to_sequence(pairwise_state)
138
-
139
- # Self attention with bias + mlp.
140
- y = self.layernorm_1(sequence_state)
141
- y, _ = self.seq_attention(y, mask=mask, bias=bias)
142
- sequence_state = sequence_state + self.drop(y)
143
- sequence_state = self.mlp_seq(sequence_state)
144
-
145
- # Update pairwise state
146
- pairwise_state = pairwise_state + self.sequence_to_pair(sequence_state)
147
-
148
- # Axial attention with triangular bias.
149
- tri_mask = mask.unsqueeze(2) * mask.unsqueeze(1) if mask is not None else None
150
- pairwise_state = pairwise_state + self.row_drop(
151
- self.tri_mul_out(pairwise_state, mask=tri_mask)
152
- )
153
- pairwise_state = pairwise_state + self.col_drop(
154
- self.tri_mul_in(pairwise_state, mask=tri_mask)
155
- )
156
- pairwise_state = pairwise_state + self.row_drop(
157
- self.tri_att_start(pairwise_state, mask=tri_mask, chunk_size=chunk_size)
158
- )
159
- pairwise_state = pairwise_state + self.col_drop(
160
- self.tri_att_end(pairwise_state, mask=tri_mask, chunk_size=chunk_size)
161
- )
162
-
163
- # MLP over pairs.
164
- pairwise_state = self.mlp_pair(pairwise_state)
165
-
166
- return sequence_state, pairwise_state
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/esmfold/v1/trunk.py DELETED
@@ -1,261 +0,0 @@
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
-
9
- import torch
10
- import torch.nn as nn
11
- from openfold.model.structure_module import StructureModule
12
-
13
- from esm.esmfold.v1.tri_self_attn_block import TriangularSelfAttentionBlock
14
-
15
-
16
- @dataclass
17
- class StructureModuleConfig:
18
- c_s: int = 384
19
- c_z: int = 128
20
- c_ipa: int = 16
21
- c_resnet: int = 128
22
- no_heads_ipa: int = 12
23
- no_qk_points: int = 4
24
- no_v_points: int = 8
25
- dropout_rate: float = 0.1
26
- no_blocks: int = 8
27
- no_transition_layers: int = 1
28
- no_resnet_blocks: int = 2
29
- no_angles: int = 7
30
- trans_scale_factor: int = 10
31
- epsilon: float = 1e-8
32
- inf: float = 1e5
33
-
34
-
35
- @dataclass
36
- class FoldingTrunkConfig:
37
- _name: str = "FoldingTrunkConfig"
38
- num_blocks: int = 48
39
- sequence_state_dim: int = 1024
40
- pairwise_state_dim: int = 128
41
- sequence_head_width: int = 32
42
- pairwise_head_width: int = 32
43
- position_bins: int = 32
44
- dropout: float = 0
45
- layer_drop: float = 0
46
- cpu_grad_checkpoint: bool = False
47
-
48
- max_recycles: int = 4
49
- chunk_size: T.Optional[int] = None
50
-
51
- structure_module: StructureModuleConfig = StructureModuleConfig()
52
-
53
-
54
- def get_axial_mask(mask):
55
- """
56
- Helper to convert B x L mask of valid positions to axial mask used
57
- in row column attentions.
58
-
59
- Input:
60
- mask: B x L tensor of booleans
61
-
62
- Output:
63
- mask: B x L x L tensor of booleans
64
- """
65
-
66
- if mask is None:
67
- return None
68
- assert len(mask.shape) == 2
69
- batch_dim, seq_dim = mask.shape
70
- m = mask.unsqueeze(1).expand(batch_dim, seq_dim, seq_dim)
71
- m = m.reshape(batch_dim * seq_dim, seq_dim)
72
- return m
73
-
74
-
75
- class RelativePosition(nn.Module):
76
- def __init__(self, bins, pairwise_state_dim):
77
- super().__init__()
78
- self.bins = bins
79
-
80
- # Note an additional offset is used so that the 0th position
81
- # is reserved for masked pairs.
82
- self.embedding = torch.nn.Embedding(2 * bins + 2, pairwise_state_dim)
83
-
84
- def forward(self, residue_index, mask=None):
85
- """
86
- Input:
87
- residue_index: B x L tensor of indices (dytpe=torch.long)
88
- mask: B x L tensor of booleans
89
-
90
- Output:
91
- pairwise_state: B x L x L x pairwise_state_dim tensor of embeddings
92
- """
93
-
94
- assert residue_index.dtype == torch.long
95
- if mask is not None:
96
- assert residue_index.shape == mask.shape
97
-
98
- diff = residue_index[:, None, :] - residue_index[:, :, None]
99
- diff = diff.clamp(-self.bins, self.bins)
100
- diff = diff + self.bins + 1 # Add 1 to adjust for padding index.
101
-
102
- if mask is not None:
103
- mask = mask[:, None, :] * mask[:, :, None]
104
- diff[mask == False] = 0
105
-
106
- output = self.embedding(diff)
107
- return output
108
-
109
-
110
- class FoldingTrunk(nn.Module):
111
- def __init__(self, **kwargs):
112
- super().__init__()
113
- self.cfg = FoldingTrunkConfig(**kwargs)
114
- assert self.cfg.max_recycles > 0
115
-
116
- c_s = self.cfg.sequence_state_dim
117
- c_z = self.cfg.pairwise_state_dim
118
-
119
- assert c_s % self.cfg.sequence_head_width == 0
120
- assert c_z % self.cfg.pairwise_head_width == 0
121
- block = TriangularSelfAttentionBlock
122
-
123
- self.pairwise_positional_embedding = RelativePosition(
124
- self.cfg.position_bins, c_z
125
- )
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(
160
- self,
161
- seq_feats,
162
- pair_feats,
163
- true_aa,
164
- residx,
165
- mask,
166
- no_recycles: T.Optional[int] = None,
167
- ):
168
- """
169
- Inputs:
170
- seq_feats: B x L x C tensor of sequence features
171
- pair_feats: B x L x L x C tensor of pair features
172
- residx: B x L long tensor giving the position in the sequence
173
- mask: B x L boolean tensor indicating valid residues
174
-
175
- Output:
176
- predicted_structure: B x L x (num_atoms_per_residue * 3) tensor wrapped in a Coordinates object
177
- """
178
-
179
- device = seq_feats.device
180
- s_s_0 = seq_feats
181
- s_z_0 = pair_feats
182
-
183
- if no_recycles is None:
184
- no_recycles = self.cfg.max_recycles
185
- else:
186
- assert no_recycles >= 0, "Number of recycles must not be negative."
187
- no_recycles += 1 # First 'recycle' is just the standard forward pass through the model.
188
-
189
- def trunk_iter(s, z, residx, mask):
190
- z = z + self.pairwise_positional_embedding(residx, mask=mask)
191
-
192
- for block in self.blocks:
193
- s, z = block(
194
- s, z, mask=mask, residue_index=residx, chunk_size=self.chunk_size
195
- )
196
- return s, z
197
-
198
- s_s = s_s_0
199
- s_z = s_z_0
200
- recycle_s = torch.zeros_like(s_s)
201
- recycle_z = torch.zeros_like(s_z)
202
- recycle_bins = torch.zeros(*s_z.shape[:-1], device=device, dtype=torch.int64)
203
-
204
- assert no_recycles > 0
205
- for recycle_idx in range(no_recycles):
206
- with ExitStack() if recycle_idx == no_recycles - 1 else torch.no_grad():
207
- # === Recycling ===
208
- recycle_s = self.recycle_s_norm(recycle_s.detach())
209
- recycle_z = self.recycle_z_norm(recycle_z.detach())
210
- recycle_z += self.recycle_disto(recycle_bins.detach())
211
-
212
- s_s, s_z = trunk_iter(
213
- s_s_0 + recycle_s, s_z_0 + recycle_z, residx, mask
214
- )
215
-
216
- # === Structure module ===
217
- structure = self.structure_module(
218
- {"single": self.trunk2sm_s(s_s), "pair": self.trunk2sm_z(s_z)},
219
- true_aa,
220
- mask.float(),
221
- )
222
-
223
- recycle_s = s_s
224
- recycle_z = s_z
225
- # Distogram needs the N, CA, C coordinates, and bin constants same as alphafold.
226
- recycle_bins = FoldingTrunk.distogram(
227
- structure["positions"][-1][:, :, :3],
228
- 3.375,
229
- 21.375,
230
- self.recycle_bins,
231
- )
232
-
233
- assert isinstance(structure, dict) # type: ignore
234
- structure["s_s"] = s_s
235
- structure["s_z"] = s_z
236
-
237
- return structure
238
-
239
- @staticmethod
240
- def distogram(coords, min_bin, max_bin, num_bins):
241
- # Coords are [... L x 3 x 3], where it's [N, CA, C] x 3 coordinates.
242
- boundaries = torch.linspace(
243
- min_bin,
244
- max_bin,
245
- num_bins - 1,
246
- device=coords.device,
247
- )
248
- boundaries = boundaries**2
249
- N, CA, C = [x.squeeze(-2) for x in coords.chunk(3, dim=-2)]
250
- # Infer CB coordinates.
251
- b = CA - N
252
- c = C - CA
253
- a = b.cross(c, dim=-1)
254
- CB = -0.58273431 * a + 0.56802827 * b - 0.54067466 * c + CA
255
- dists = (
256
- (CB[..., None, :, :] - CB[..., :, None, :])
257
- .pow(2)
258
- .sum(dim=-1, keepdims=True)
259
- )
260
- bins = torch.sum(dists > boundaries, dim=-1) # [..., L, L]
261
- return bins
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/__init__.py DELETED
@@ -1,8 +0,0 @@
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 . import gvp_transformer
7
- from . import util
8
- from . import multichain_util
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/features.py DELETED
@@ -1,359 +0,0 @@
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
- # Portions of this file were adapted from the open source code for the following
7
- # two papers:
8
- #
9
- # Ingraham, J., Garg, V., Barzilay, R., & Jaakkola, T. (2019). Generative
10
- # models for graph-based protein design. Advances in Neural Information
11
- # Processing Systems, 32.
12
- #
13
- # Jing, B., Eismann, S., Suriana, P., Townshend, R. J. L., & Dror, R. (2020).
14
- # Learning from Protein Structure with Geometric Vector Perceptrons. In
15
- # International Conference on Learning Representations.
16
- #
17
- # MIT License
18
- #
19
- # Copyright (c) 2020 Bowen Jing, Stephan Eismann, Patricia Suriana, Raphael Townshend, Ron Dror
20
- #
21
- # Permission is hereby granted, free of charge, to any person obtaining a copy
22
- # of this software and associated documentation files (the "Software"), to deal
23
- # in the Software without restriction, including without limitation the rights
24
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
25
- # copies of the Software, and to permit persons to whom the Software is
26
- # furnished to do so, subject to the following conditions:
27
- #
28
- # The above copyright notice and this permission notice shall be included in all
29
- # copies or substantial portions of the Software.
30
- #
31
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
34
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
36
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
37
- # SOFTWARE.
38
- #
39
- # ================================================================
40
- # The below license applies to the portions of the code (parts of
41
- # src/datasets.py and src/models.py) adapted from Ingraham, et al.
42
- # ================================================================
43
- #
44
- # MIT License
45
- #
46
- # Copyright (c) 2019 John Ingraham, Vikas Garg, Regina Barzilay, Tommi Jaakkola
47
- #
48
- # Permission is hereby granted, free of charge, to any person obtaining a copy
49
- # of this software and associated documentation files (the "Software"), to deal
50
- # in the Software without restriction, including without limitation the rights
51
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
52
- # copies of the Software, and to permit persons to whom the Software is
53
- # furnished to do so, subject to the following conditions:
54
- #
55
- # The above copyright notice and this permission notice shall be included in all
56
- # copies or substantial portions of the Software.
57
- #
58
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
59
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
60
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
61
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
62
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
63
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
64
- # SOFTWARE.
65
-
66
- import math
67
- import numpy as np
68
- import torch
69
- import torch.nn as nn
70
- import torch.nn.functional as F
71
-
72
- from .gvp_utils import flatten_graph
73
- from .gvp_modules import GVP, LayerNorm
74
- from .util import normalize, norm, nan_to_num, rbf
75
-
76
-
77
- class GVPInputFeaturizer(nn.Module):
78
- @staticmethod
79
- def get_node_features(coords, coord_mask, with_coord_mask=True):
80
- # scalar features
81
- node_scalar_features = GVPInputFeaturizer._dihedrals(coords)
82
- if with_coord_mask:
83
- node_scalar_features = torch.cat(
84
- [node_scalar_features, coord_mask.float().unsqueeze(-1)], dim=-1
85
- )
86
- # vector features
87
- X_ca = coords[:, :, 1]
88
- orientations = GVPInputFeaturizer._orientations(X_ca)
89
- sidechains = GVPInputFeaturizer._sidechains(coords)
90
- node_vector_features = torch.cat(
91
- [orientations, sidechains.unsqueeze(-2)], dim=-2
92
- )
93
- return node_scalar_features, node_vector_features
94
-
95
- @staticmethod
96
- def _orientations(X):
97
- forward = normalize(X[:, 1:] - X[:, :-1])
98
- backward = normalize(X[:, :-1] - X[:, 1:])
99
- forward = F.pad(forward, [0, 0, 0, 1])
100
- backward = F.pad(backward, [0, 0, 1, 0])
101
- return torch.cat([forward.unsqueeze(-2), backward.unsqueeze(-2)], -2)
102
-
103
- @staticmethod
104
- def _sidechains(X):
105
- n, origin, c = X[:, :, 0], X[:, :, 1], X[:, :, 2]
106
- c, n = normalize(c - origin), normalize(n - origin)
107
- bisector = normalize(c + n)
108
- perp = normalize(torch.cross(c, n, dim=-1))
109
- vec = -bisector * math.sqrt(1 / 3) - perp * math.sqrt(2 / 3)
110
- return vec
111
-
112
- @staticmethod
113
- def _dihedrals(X, eps=1e-7):
114
- X = torch.flatten(X[:, :, :3], 1, 2)
115
- bsz = X.shape[0]
116
- dX = X[:, 1:] - X[:, :-1]
117
- U = normalize(dX, dim=-1)
118
- u_2 = U[:, :-2]
119
- u_1 = U[:, 1:-1]
120
- u_0 = U[:, 2:]
121
-
122
- # Backbone normals
123
- n_2 = normalize(torch.cross(u_2, u_1, dim=-1), dim=-1)
124
- n_1 = normalize(torch.cross(u_1, u_0, dim=-1), dim=-1)
125
-
126
- # Angle between normals
127
- cosD = torch.sum(n_2 * n_1, -1)
128
- cosD = torch.clamp(cosD, -1 + eps, 1 - eps)
129
- D = torch.sign(torch.sum(u_2 * n_1, -1)) * torch.acos(cosD)
130
-
131
- # This scheme will remove phi[0], psi[-1], omega[-1]
132
- D = F.pad(D, [1, 2])
133
- D = torch.reshape(D, [bsz, -1, 3])
134
- # Lift angle representations to the circle
135
- D_features = torch.cat([torch.cos(D), torch.sin(D)], -1)
136
- return D_features
137
-
138
- @staticmethod
139
- def _positional_embeddings(
140
- edge_index,
141
- num_embeddings=None,
142
- num_positional_embeddings=16,
143
- period_range=[2, 1000],
144
- ):
145
- # From https://github.com/jingraham/neurips19-graph-protein-design
146
- num_embeddings = num_embeddings or num_positional_embeddings
147
- d = edge_index[0] - edge_index[1]
148
-
149
- frequency = torch.exp(
150
- torch.arange(
151
- 0, num_embeddings, 2, dtype=torch.float32, device=edge_index.device
152
- )
153
- * -(np.log(10000.0) / num_embeddings)
154
- )
155
- angles = d.unsqueeze(-1) * frequency
156
- E = torch.cat((torch.cos(angles), torch.sin(angles)), -1)
157
- return E
158
-
159
- @staticmethod
160
- def _dist(X, coord_mask, padding_mask, top_k_neighbors, eps=1e-8):
161
- """Pairwise euclidean distances"""
162
- bsz, maxlen = X.size(0), X.size(1)
163
- coord_mask_2D = torch.unsqueeze(coord_mask, 1) * torch.unsqueeze(coord_mask, 2)
164
- residue_mask = ~padding_mask
165
- residue_mask_2D = torch.unsqueeze(residue_mask, 1) * torch.unsqueeze(
166
- residue_mask, 2
167
- )
168
- dX = torch.unsqueeze(X, 1) - torch.unsqueeze(X, 2)
169
- D = coord_mask_2D * norm(dX, dim=-1)
170
-
171
- # sorting preference: first those with coords, then among the residues that
172
- # exist but are masked use distance in sequence as tie breaker, and then the
173
- # residues that came from padding are last
174
- seqpos = torch.arange(maxlen, device=X.device)
175
- Dseq = torch.abs(seqpos.unsqueeze(1) - seqpos.unsqueeze(0)).repeat(bsz, 1, 1)
176
- D_adjust = (
177
- nan_to_num(D)
178
- + (~coord_mask_2D) * (1e8 + Dseq * 1e6)
179
- + (~residue_mask_2D) * (1e10)
180
- )
181
-
182
- if top_k_neighbors == -1:
183
- D_neighbors = D_adjust
184
- E_idx = seqpos.repeat(*D_neighbors.shape[:-1], 1)
185
- else:
186
- # Identify k nearest neighbors (including self)
187
- k = min(top_k_neighbors, X.size(1))
188
- D_neighbors, E_idx = torch.topk(D_adjust, k, dim=-1, largest=False)
189
-
190
- coord_mask_neighbors = D_neighbors < 5e7
191
- residue_mask_neighbors = D_neighbors < 5e9
192
- return D_neighbors, E_idx, coord_mask_neighbors, residue_mask_neighbors
193
-
194
-
195
- class Normalize(nn.Module):
196
- def __init__(self, features, epsilon=1e-6):
197
- super(Normalize, self).__init__()
198
- self.gain = nn.Parameter(torch.ones(features))
199
- self.bias = nn.Parameter(torch.zeros(features))
200
- self.epsilon = epsilon
201
-
202
- def forward(self, x, dim=-1):
203
- mu = x.mean(dim, keepdim=True)
204
- sigma = torch.sqrt(x.var(dim, keepdim=True) + self.epsilon)
205
- gain = self.gain
206
- bias = self.bias
207
- # Reshape
208
- if dim != -1:
209
- shape = [1] * len(mu.size())
210
- shape[dim] = self.gain.size()[0]
211
- gain = gain.view(shape)
212
- bias = bias.view(shape)
213
- return gain * (x - mu) / (sigma + self.epsilon) + bias
214
-
215
-
216
- class DihedralFeatures(nn.Module):
217
- def __init__(self, node_embed_dim):
218
- """Embed dihedral angle features."""
219
- super(DihedralFeatures, self).__init__()
220
- # 3 dihedral angles; sin and cos of each angle
221
- node_in = 6
222
- # Normalization and embedding
223
- self.node_embedding = nn.Linear(node_in, node_embed_dim, bias=True)
224
- self.norm_nodes = Normalize(node_embed_dim)
225
-
226
- def forward(self, X):
227
- """Featurize coordinates as an attributed graph"""
228
- V = self._dihedrals(X)
229
- V = self.node_embedding(V)
230
- V = self.norm_nodes(V)
231
- return V
232
-
233
- @staticmethod
234
- def _dihedrals(X, eps=1e-7, return_angles=False):
235
- # First 3 coordinates are N, CA, C
236
- X = X[:, :, :3, :].reshape(X.shape[0], 3 * X.shape[1], 3)
237
-
238
- # Shifted slices of unit vectors
239
- dX = X[:, 1:, :] - X[:, :-1, :]
240
- U = F.normalize(dX, dim=-1)
241
- u_2 = U[:, :-2, :]
242
- u_1 = U[:, 1:-1, :]
243
- u_0 = U[:, 2:, :]
244
- # Backbone normals
245
- n_2 = F.normalize(torch.cross(u_2, u_1, dim=-1), dim=-1)
246
- n_1 = F.normalize(torch.cross(u_1, u_0, dim=-1), dim=-1)
247
-
248
- # Angle between normals
249
- cosD = (n_2 * n_1).sum(-1)
250
- cosD = torch.clamp(cosD, -1 + eps, 1 - eps)
251
- D = torch.sign((u_2 * n_1).sum(-1)) * torch.acos(cosD)
252
-
253
- # This scheme will remove phi[0], psi[-1], omega[-1]
254
- D = F.pad(D, (1, 2), "constant", 0)
255
- D = D.view((D.size(0), int(D.size(1) / 3), 3))
256
- phi, psi, omega = torch.unbind(D, -1)
257
-
258
- if return_angles:
259
- return phi, psi, omega
260
-
261
- # Lift angle representations to the circle
262
- D_features = torch.cat((torch.cos(D), torch.sin(D)), 2)
263
- return D_features
264
-
265
-
266
- class GVPGraphEmbedding(GVPInputFeaturizer):
267
- def __init__(self, args):
268
- super().__init__()
269
- self.top_k_neighbors = args.top_k_neighbors
270
- self.num_positional_embeddings = 16
271
- self.remove_edges_without_coords = True
272
- node_input_dim = (7, 3)
273
- edge_input_dim = (34, 1)
274
- node_hidden_dim = (args.node_hidden_dim_scalar, args.node_hidden_dim_vector)
275
- edge_hidden_dim = (args.edge_hidden_dim_scalar, args.edge_hidden_dim_vector)
276
- self.embed_node = nn.Sequential(
277
- GVP(node_input_dim, node_hidden_dim, activations=(None, None)),
278
- LayerNorm(node_hidden_dim, eps=1e-4),
279
- )
280
- self.embed_edge = nn.Sequential(
281
- GVP(edge_input_dim, edge_hidden_dim, activations=(None, None)),
282
- LayerNorm(edge_hidden_dim, eps=1e-4),
283
- )
284
- self.embed_confidence = nn.Linear(16, args.node_hidden_dim_scalar)
285
-
286
- def forward(self, coords, coord_mask, padding_mask, confidence):
287
- with torch.no_grad():
288
- node_features = self.get_node_features(coords, coord_mask)
289
- edge_features, edge_index = self.get_edge_features(
290
- coords, coord_mask, padding_mask
291
- )
292
- node_embeddings_scalar, node_embeddings_vector = self.embed_node(node_features)
293
- edge_embeddings = self.embed_edge(edge_features)
294
-
295
- rbf_rep = rbf(confidence, 0.0, 1.0)
296
- node_embeddings = (
297
- node_embeddings_scalar + self.embed_confidence(rbf_rep),
298
- node_embeddings_vector,
299
- )
300
-
301
- node_embeddings, edge_embeddings, edge_index = flatten_graph(
302
- node_embeddings, edge_embeddings, edge_index
303
- )
304
- return node_embeddings, edge_embeddings, edge_index
305
-
306
- def get_edge_features(self, coords, coord_mask, padding_mask):
307
- X_ca = coords[:, :, 1]
308
- # Get distances to the top k neighbors
309
- E_dist, E_idx, E_coord_mask, E_residue_mask = GVPInputFeaturizer._dist(
310
- X_ca, coord_mask, padding_mask, self.top_k_neighbors
311
- )
312
- # Flatten the graph to be batch size 1 for torch_geometric package
313
- dest = E_idx
314
- B, L, k = E_idx.shape[:3]
315
- src = torch.arange(L, device=E_idx.device).view([1, L, 1]).expand(B, L, k)
316
- # After flattening, [2, B, E]
317
- edge_index = torch.stack([src, dest], dim=0).flatten(2, 3)
318
- # After flattening, [B, E]
319
- E_dist = E_dist.flatten(1, 2)
320
- E_coord_mask = E_coord_mask.flatten(1, 2).unsqueeze(-1)
321
- E_residue_mask = E_residue_mask.flatten(1, 2)
322
- # Calculate relative positional embeddings and distance RBF
323
- pos_embeddings = GVPInputFeaturizer._positional_embeddings(
324
- edge_index,
325
- num_positional_embeddings=self.num_positional_embeddings,
326
- )
327
- D_rbf = rbf(E_dist, 0.0, 20.0)
328
- # Calculate relative orientation
329
- X_src = X_ca.unsqueeze(2).expand(-1, -1, k, -1).flatten(1, 2)
330
- X_dest = torch.gather(
331
- X_ca, 1, edge_index[1, :, :].unsqueeze(-1).expand([B, L * k, 3])
332
- )
333
- coord_mask_src = coord_mask.unsqueeze(2).expand(-1, -1, k).flatten(1, 2)
334
- coord_mask_dest = torch.gather(
335
- coord_mask, 1, edge_index[1, :, :].expand([B, L * k])
336
- )
337
- E_vectors = X_src - X_dest
338
- # For the ones without coordinates, substitute in the average vector
339
- E_vector_mean = torch.sum(
340
- E_vectors * E_coord_mask, dim=1, keepdims=True
341
- ) / torch.sum(E_coord_mask, dim=1, keepdims=True)
342
- E_vectors = E_vectors * E_coord_mask + E_vector_mean * ~(E_coord_mask)
343
- # Normalize and remove nans
344
- edge_s = torch.cat([D_rbf, pos_embeddings], dim=-1)
345
- edge_v = normalize(E_vectors).unsqueeze(-2)
346
- edge_s, edge_v = map(nan_to_num, (edge_s, edge_v))
347
- # Also add indications of whether the coordinates are present
348
- edge_s = torch.cat(
349
- [
350
- edge_s,
351
- (~coord_mask_src).float().unsqueeze(-1),
352
- (~coord_mask_dest).float().unsqueeze(-1),
353
- ],
354
- dim=-1,
355
- )
356
- edge_index[:, ~E_residue_mask] = -1
357
- if self.remove_edges_without_coords:
358
- edge_index[:, ~E_coord_mask.squeeze(-1)] = -1
359
- return (edge_s, edge_v), edge_index.transpose(0, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/gvp_encoder.py DELETED
@@ -1,53 +0,0 @@
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
-
7
- import torch
8
- import torch.nn as nn
9
- import torch.nn.functional as F
10
-
11
- from .features import GVPGraphEmbedding
12
- from .gvp_modules import GVPConvLayer
13
- from .gvp_utils import unflatten_graph
14
-
15
-
16
- class GVPEncoder(nn.Module):
17
- def __init__(self, args):
18
- super().__init__()
19
- self.args = args
20
- self.embed_graph = GVPGraphEmbedding(args)
21
-
22
- node_hidden_dim = (args.node_hidden_dim_scalar, args.node_hidden_dim_vector)
23
- edge_hidden_dim = (args.edge_hidden_dim_scalar, args.edge_hidden_dim_vector)
24
-
25
- conv_activations = (F.relu, torch.sigmoid)
26
- self.encoder_layers = nn.ModuleList(
27
- GVPConvLayer(
28
- node_hidden_dim,
29
- edge_hidden_dim,
30
- drop_rate=args.dropout,
31
- vector_gate=True,
32
- attention_heads=0,
33
- n_message=3,
34
- conv_activations=conv_activations,
35
- n_edge_gvps=0,
36
- eps=1e-4,
37
- layernorm=True,
38
- )
39
- for i in range(args.num_encoder_layers)
40
- )
41
-
42
- def forward(self, coords, coord_mask, padding_mask, confidence):
43
- node_embeddings, edge_embeddings, edge_index = self.embed_graph(
44
- coords, coord_mask, padding_mask, confidence
45
- )
46
-
47
- for i, layer in enumerate(self.encoder_layers):
48
- node_embeddings, edge_embeddings = layer(
49
- node_embeddings, edge_index, edge_embeddings
50
- )
51
-
52
- node_embeddings = unflatten_graph(node_embeddings, coords.shape[0])
53
- return node_embeddings
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/gvp_modules.py DELETED
@@ -1,533 +0,0 @@
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 torch
30
- from torch import nn
31
- import torch.nn.functional as F
32
- from torch_geometric.nn import MessagePassing
33
-
34
-
35
- def tuple_size(tp):
36
- return tuple([0 if a is None else a.size() for a in tp])
37
-
38
-
39
- def tuple_sum(tp1, tp2):
40
- s1, v1 = tp1
41
- s2, v2 = tp2
42
- if v2 is None and v2 is None:
43
- return (s1 + s2, None)
44
- return (s1 + s2, v1 + v2)
45
-
46
-
47
- def tuple_cat(*args, dim=-1):
48
- """
49
- Concatenates any number of tuples (s, V) elementwise.
50
-
51
- :param dim: dimension along which to concatenate when viewed
52
- as the `dim` index for the scalar-channel tensors.
53
- This means that `dim=-1` will be applied as
54
- `dim=-2` for the vector-channel tensors.
55
- """
56
- dim %= len(args[0][0].shape)
57
- s_args, v_args = list(zip(*args))
58
- return torch.cat(s_args, dim=dim), torch.cat(v_args, dim=dim)
59
-
60
-
61
- def tuple_index(x, idx):
62
- """
63
- Indexes into a tuple (s, V) along the first dimension.
64
-
65
- :param idx: any object which can be used to index into a `torch.Tensor`
66
- """
67
- return x[0][idx], x[1][idx]
68
-
69
-
70
- def randn(n, dims, device="cpu"):
71
- """
72
- Returns random tuples (s, V) drawn elementwise from a normal distribution.
73
-
74
- :param n: number of data points
75
- :param dims: tuple of dimensions (n_scalar, n_vector)
76
-
77
- :return: (s, V) with s.shape = (n, n_scalar) and
78
- V.shape = (n, n_vector, 3)
79
- """
80
- return torch.randn(n, dims[0], device=device), torch.randn(
81
- n, dims[1], 3, device=device
82
- )
83
-
84
-
85
- def _norm_no_nan(x, axis=-1, keepdims=False, eps=1e-8, sqrt=True):
86
- """
87
- L2 norm of tensor clamped above a minimum value `eps`.
88
-
89
- :param sqrt: if `False`, returns the square of the L2 norm
90
- """
91
- # clamp is slow
92
- # out = torch.clamp(torch.sum(torch.square(x), axis, keepdims), min=eps)
93
- out = torch.sum(torch.square(x), axis, keepdims) + eps
94
- return torch.sqrt(out) if sqrt else out
95
-
96
-
97
- def _split(x, nv):
98
- """
99
- Splits a merged representation of (s, V) back into a tuple.
100
- Should be used only with `_merge(s, V)` and only if the tuple
101
- representation cannot be used.
102
-
103
- :param x: the `torch.Tensor` returned from `_merge`
104
- :param nv: the number of vector channels in the input to `_merge`
105
- """
106
- v = torch.reshape(x[..., -3 * nv :], x.shape[:-1] + (nv, 3))
107
- s = x[..., : -3 * nv]
108
- return s, v
109
-
110
-
111
- def _merge(s, v):
112
- """
113
- Merges a tuple (s, V) into a single `torch.Tensor`, where the
114
- vector channels are flattened and appended to the scalar channels.
115
- Should be used only if the tuple representation cannot be used.
116
- Use `_split(x, nv)` to reverse.
117
- """
118
- v = torch.reshape(v, v.shape[:-2] + (3 * v.shape[-2],))
119
- return torch.cat([s, v], -1)
120
-
121
-
122
- class GVP(nn.Module):
123
- """
124
- Geometric Vector Perceptron. See manuscript and README.md
125
- for more details.
126
-
127
- :param in_dims: tuple (n_scalar, n_vector)
128
- :param out_dims: tuple (n_scalar, n_vector)
129
- :param h_dim: intermediate number of vector channels, optional
130
- :param activations: tuple of functions (scalar_act, vector_act)
131
- :param tuple_io: whether to keep accepting tuple inputs and outputs when vi
132
- or vo = 0
133
- """
134
-
135
- def __init__(
136
- self,
137
- in_dims,
138
- out_dims,
139
- h_dim=None,
140
- vector_gate=False,
141
- activations=(F.relu, torch.sigmoid),
142
- tuple_io=True,
143
- eps=1e-8,
144
- ):
145
- super(GVP, self).__init__()
146
- self.si, self.vi = in_dims
147
- self.so, self.vo = out_dims
148
- self.tuple_io = tuple_io
149
- if self.vi:
150
- self.h_dim = h_dim or max(self.vi, self.vo)
151
- self.wh = nn.Linear(self.vi, self.h_dim, bias=False)
152
- self.ws = nn.Linear(self.h_dim + self.si, self.so)
153
- if self.vo:
154
- self.wv = nn.Linear(self.h_dim, self.vo, bias=False)
155
- if vector_gate:
156
- self.wg = nn.Linear(self.so, self.vo)
157
- else:
158
- self.ws = nn.Linear(self.si, self.so)
159
-
160
- self.vector_gate = vector_gate
161
- self.scalar_act, self.vector_act = activations
162
- self.eps = eps
163
-
164
- def forward(self, x):
165
- """
166
- :param x: tuple (s, V) of `torch.Tensor`,
167
- or (if vectors_in is 0), a single `torch.Tensor`
168
- :return: tuple (s, V) of `torch.Tensor`,
169
- or (if vectors_out is 0), a single `torch.Tensor`
170
- """
171
- if self.vi:
172
- s, v = x
173
- v = torch.transpose(v, -1, -2)
174
- vh = self.wh(v)
175
- vn = _norm_no_nan(vh, axis=-2, eps=self.eps)
176
- s = self.ws(torch.cat([s, vn], -1))
177
- if self.scalar_act:
178
- s = self.scalar_act(s)
179
- if self.vo:
180
- v = self.wv(vh)
181
- v = torch.transpose(v, -1, -2)
182
- if self.vector_gate:
183
- g = self.wg(s).unsqueeze(-1)
184
- else:
185
- g = _norm_no_nan(v, axis=-1, keepdims=True, eps=self.eps)
186
- if self.vector_act:
187
- g = self.vector_act(g)
188
- v = v * g
189
- else:
190
- if self.tuple_io:
191
- assert x[1] is None
192
- x = x[0]
193
- s = self.ws(x)
194
- if self.scalar_act:
195
- s = self.scalar_act(s)
196
- if self.vo:
197
- v = torch.zeros(list(s.shape)[:-1] + [self.vo, 3], device=s.device)
198
-
199
- if self.vo:
200
- return (s, v)
201
- elif self.tuple_io:
202
- return (s, None)
203
- else:
204
- return s
205
-
206
-
207
- class _VDropout(nn.Module):
208
- """
209
- Vector channel dropout where the elements of each
210
- vector channel are dropped together.
211
- """
212
-
213
- def __init__(self, drop_rate):
214
- super(_VDropout, self).__init__()
215
- self.drop_rate = drop_rate
216
-
217
- def forward(self, x):
218
- """
219
- :param x: `torch.Tensor` corresponding to vector channels
220
- """
221
- if x is None:
222
- return None
223
- device = x.device
224
- if not self.training:
225
- return x
226
- mask = torch.bernoulli(
227
- (1 - self.drop_rate) * torch.ones(x.shape[:-1], device=device)
228
- ).unsqueeze(-1)
229
- x = mask * x / (1 - self.drop_rate)
230
- return x
231
-
232
-
233
- class Dropout(nn.Module):
234
- """
235
- Combined dropout for tuples (s, V).
236
- Takes tuples (s, V) as input and as output.
237
- """
238
-
239
- def __init__(self, drop_rate):
240
- super(Dropout, self).__init__()
241
- self.sdropout = nn.Dropout(drop_rate)
242
- self.vdropout = _VDropout(drop_rate)
243
-
244
- def forward(self, x):
245
- """
246
- :param x: tuple (s, V) of `torch.Tensor`,
247
- or single `torch.Tensor`
248
- (will be assumed to be scalar channels)
249
- """
250
- if type(x) is torch.Tensor:
251
- return self.sdropout(x)
252
- s, v = x
253
- return self.sdropout(s), self.vdropout(v)
254
-
255
-
256
- class LayerNorm(nn.Module):
257
- """
258
- Combined LayerNorm for tuples (s, V).
259
- Takes tuples (s, V) as input and as output.
260
- """
261
-
262
- def __init__(self, dims, tuple_io=True, eps=1e-8):
263
- super(LayerNorm, self).__init__()
264
- self.tuple_io = tuple_io
265
- self.s, self.v = dims
266
- self.scalar_norm = nn.LayerNorm(self.s)
267
- self.eps = eps
268
-
269
- def forward(self, x):
270
- """
271
- :param x: tuple (s, V) of `torch.Tensor`,
272
- or single `torch.Tensor`
273
- (will be assumed to be scalar channels)
274
- """
275
- if not self.v:
276
- if self.tuple_io:
277
- return self.scalar_norm(x[0]), None
278
- return self.scalar_norm(x)
279
- s, v = x
280
- vn = _norm_no_nan(v, axis=-1, keepdims=True, sqrt=False, eps=self.eps)
281
- nonzero_mask = vn > 2 * self.eps
282
- vn = torch.sum(vn * nonzero_mask, dim=-2, keepdim=True) / (
283
- self.eps + torch.sum(nonzero_mask, dim=-2, keepdim=True)
284
- )
285
- vn = torch.sqrt(vn + self.eps)
286
- v = nonzero_mask * (v / vn)
287
- return self.scalar_norm(s), v
288
-
289
-
290
- class GVPConv(MessagePassing):
291
- """
292
- Graph convolution / message passing with Geometric Vector Perceptrons.
293
- Takes in a graph with node and edge embeddings,
294
- and returns new node embeddings.
295
-
296
- This does NOT do residual updates and pointwise feedforward layers
297
- ---see `GVPConvLayer`.
298
-
299
- :param in_dims: input node embedding dimensions (n_scalar, n_vector)
300
- :param out_dims: output node embedding dimensions (n_scalar, n_vector)
301
- :param edge_dims: input edge embedding dimensions (n_scalar, n_vector)
302
- :param n_layers: number of GVPs in the message function
303
- :param module_list: preconstructed message function, overrides n_layers
304
- :param aggr: should be "add" if some incoming edges are masked, as in
305
- a masked autoregressive decoder architecture
306
- """
307
-
308
- def __init__(
309
- self,
310
- in_dims,
311
- out_dims,
312
- edge_dims,
313
- n_layers=3,
314
- vector_gate=False,
315
- module_list=None,
316
- aggr="mean",
317
- eps=1e-8,
318
- activations=(F.relu, torch.sigmoid),
319
- ):
320
- super(GVPConv, self).__init__(aggr=aggr)
321
- self.eps = eps
322
- self.si, self.vi = in_dims
323
- self.so, self.vo = out_dims
324
- self.se, self.ve = edge_dims
325
-
326
- module_list = module_list or []
327
- if not module_list:
328
- if n_layers == 1:
329
- module_list.append(
330
- GVP(
331
- (2 * self.si + self.se, 2 * self.vi + self.ve),
332
- (self.so, self.vo),
333
- activations=(None, None),
334
- )
335
- )
336
- else:
337
- module_list.append(
338
- GVP(
339
- (2 * self.si + self.se, 2 * self.vi + self.ve),
340
- out_dims,
341
- vector_gate=vector_gate,
342
- activations=activations,
343
- )
344
- )
345
- for i in range(n_layers - 2):
346
- module_list.append(GVP(out_dims, out_dims, vector_gate=vector_gate))
347
- module_list.append(GVP(out_dims, out_dims, activations=(None, None)))
348
- self.message_func = nn.Sequential(*module_list)
349
-
350
- def forward(self, x, edge_index, edge_attr):
351
- """
352
- :param x: tuple (s, V) of `torch.Tensor`
353
- :param edge_index: array of shape [2, n_edges]
354
- :param edge_attr: tuple (s, V) of `torch.Tensor`
355
- """
356
- x_s, x_v = x
357
- message = self.propagate(
358
- edge_index,
359
- s=x_s,
360
- v=x_v.reshape(x_v.shape[0], 3 * x_v.shape[1]),
361
- edge_attr=edge_attr,
362
- )
363
- return _split(message, self.vo)
364
-
365
- def message(self, s_i, v_i, s_j, v_j, edge_attr):
366
- v_j = v_j.view(v_j.shape[0], v_j.shape[1] // 3, 3)
367
- v_i = v_i.view(v_i.shape[0], v_i.shape[1] // 3, 3)
368
- message = tuple_cat((s_j, v_j), edge_attr, (s_i, v_i))
369
- message = self.message_func(message)
370
- return _merge(*message)
371
-
372
-
373
- class GVPConvLayer(nn.Module):
374
- """
375
- Full graph convolution / message passing layer with
376
- Geometric Vector Perceptrons. Residually updates node embeddings with
377
- aggregated incoming messages, applies a pointwise feedforward
378
- network to node embeddings, and returns updated node embeddings.
379
-
380
- To only compute the aggregated messages, see `GVPConv`.
381
-
382
- :param node_dims: node embedding dimensions (n_scalar, n_vector)
383
- :param edge_dims: input edge embedding dimensions (n_scalar, n_vector)
384
- :param n_message: number of GVPs to use in message function
385
- :param n_feedforward: number of GVPs to use in feedforward function
386
- :param drop_rate: drop probability in all dropout layers
387
- :param autoregressive: if `True`, this `GVPConvLayer` will be used
388
- with a different set of input node embeddings for messages
389
- where src >= dst
390
- """
391
-
392
- def __init__(
393
- self,
394
- node_dims,
395
- edge_dims,
396
- vector_gate=False,
397
- n_message=3,
398
- n_feedforward=2,
399
- drop_rate=0.1,
400
- autoregressive=False,
401
- attention_heads=0,
402
- conv_activations=(F.relu, torch.sigmoid),
403
- n_edge_gvps=0,
404
- layernorm=True,
405
- eps=1e-8,
406
- ):
407
- super(GVPConvLayer, self).__init__()
408
- if attention_heads == 0:
409
- self.conv = GVPConv(
410
- node_dims,
411
- node_dims,
412
- edge_dims,
413
- n_layers=n_message,
414
- vector_gate=vector_gate,
415
- aggr="add" if autoregressive else "mean",
416
- activations=conv_activations,
417
- eps=eps,
418
- )
419
- else:
420
- raise NotImplementedError
421
- if layernorm:
422
- self.norm = nn.ModuleList([LayerNorm(node_dims, eps=eps) for _ in range(2)])
423
- else:
424
- self.norm = nn.ModuleList([nn.Identity() for _ in range(2)])
425
- self.dropout = nn.ModuleList([Dropout(drop_rate) for _ in range(2)])
426
-
427
- ff_func = []
428
- if n_feedforward == 1:
429
- ff_func.append(GVP(node_dims, node_dims, activations=(None, None)))
430
- else:
431
- hid_dims = 4 * node_dims[0], 2 * node_dims[1]
432
- ff_func.append(GVP(node_dims, hid_dims, vector_gate=vector_gate))
433
- for i in range(n_feedforward - 2):
434
- ff_func.append(GVP(hid_dims, hid_dims, vector_gate=vector_gate))
435
- ff_func.append(GVP(hid_dims, node_dims, activations=(None, None)))
436
- self.ff_func = nn.Sequential(*ff_func)
437
-
438
- self.edge_message_func = None
439
- if n_edge_gvps > 0:
440
- si, vi = node_dims
441
- se, ve = edge_dims
442
- module_list = [
443
- GVP((2 * si + se, 2 * vi + ve), edge_dims, vector_gate=vector_gate)
444
- ]
445
- for i in range(n_edge_gvps - 2):
446
- module_list.append(GVP(edge_dims, edge_dims, vector_gate=vector_gate))
447
- if n_edge_gvps > 1:
448
- module_list.append(GVP(edge_dims, edge_dims, activations=(None, None)))
449
- self.edge_message_func = nn.Sequential(*module_list)
450
- if layernorm:
451
- self.edge_norm = LayerNorm(edge_dims, eps=eps)
452
- else:
453
- self.edge_norm = nn.Identity()
454
- self.edge_dropout = Dropout(drop_rate)
455
-
456
- def forward(self, x, edge_index, edge_attr, autoregressive_x=None, node_mask=None):
457
- """
458
- :param x: tuple (s, V) of `torch.Tensor`
459
- :param edge_index: array of shape [2, n_edges]
460
- :param edge_attr: tuple (s, V) of `torch.Tensor`
461
- :param autoregressive_x: tuple (s, V) of `torch.Tensor`.
462
- If not `None`, will be used as srcqq node embeddings
463
- for forming messages where src >= dst. The corrent node
464
- embeddings `x` will still be the base of the update and the
465
- pointwise feedforward.
466
- :param node_mask: array of type `bool` to index into the first
467
- dim of node embeddings (s, V). If not `None`, only
468
- these nodes will be updated.
469
- """
470
- if self.edge_message_func:
471
- src, dst = edge_index
472
- if autoregressive_x is None:
473
- x_src = x[0][src], x[1][src]
474
- else:
475
- mask = (src < dst).unsqueeze(-1)
476
- x_src = (
477
- torch.where(mask, x[0][src], autoregressive_x[0][src]),
478
- torch.where(
479
- mask.unsqueeze(-1), x[1][src], autoregressive_x[1][src]
480
- ),
481
- )
482
- x_dst = x[0][dst], x[1][dst]
483
- x_edge = (
484
- torch.cat([x_src[0], edge_attr[0], x_dst[0]], dim=-1),
485
- torch.cat([x_src[1], edge_attr[1], x_dst[1]], dim=-2),
486
- )
487
- edge_attr_dh = self.edge_message_func(x_edge)
488
- edge_attr = self.edge_norm(
489
- tuple_sum(edge_attr, self.edge_dropout(edge_attr_dh))
490
- )
491
-
492
- if autoregressive_x is not None:
493
- # Guarding this import here to remove the dependency on torch_scatter, since this isn't used
494
- # in ESM-IF1
495
- from torch_scatter import scatter_add
496
-
497
- src, dst = edge_index
498
- mask = src < dst
499
- edge_index_forward = edge_index[:, mask]
500
- edge_index_backward = edge_index[:, ~mask]
501
- edge_attr_forward = tuple_index(edge_attr, mask)
502
- edge_attr_backward = tuple_index(edge_attr, ~mask)
503
-
504
- dh = tuple_sum(
505
- self.conv(x, edge_index_forward, edge_attr_forward),
506
- self.conv(autoregressive_x, edge_index_backward, edge_attr_backward),
507
- )
508
-
509
- count = (
510
- scatter_add(torch.ones_like(dst), dst, dim_size=dh[0].size(0))
511
- .clamp(min=1)
512
- .unsqueeze(-1)
513
- )
514
-
515
- dh = dh[0] / count, dh[1] / count.unsqueeze(-1)
516
-
517
- else:
518
- dh = self.conv(x, edge_index, edge_attr)
519
-
520
- if node_mask is not None:
521
- x_ = x
522
- x, dh = tuple_index(x, node_mask), tuple_index(dh, node_mask)
523
-
524
- x = self.norm[0](tuple_sum(x, self.dropout[0](dh)))
525
-
526
- dh = self.ff_func(x)
527
- x = self.norm[1](tuple_sum(x, self.dropout[1](dh)))
528
-
529
- if node_mask is not None:
530
- x_[0][node_mask], x_[1][node_mask] = x[0], x[1]
531
- x = x_
532
-
533
- return x, edge_attr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/gvp_transformer.py DELETED
@@ -1,139 +0,0 @@
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 torch
7
- from torch import nn
8
- import torch.nn.functional as F
9
-
10
-
11
- from .gvp_transformer_encoder import GVPTransformerEncoder
12
- from .transformer_decoder import TransformerDecoder
13
- from .util import CoordBatchConverter
14
-
15
-
16
- class GVPTransformerModel(nn.Module):
17
- """
18
- GVP-Transformer inverse folding model.
19
-
20
- Architecture: Geometric GVP-GNN as initial layers, followed by
21
- sequence-to-sequence Transformer encoder and decoder.
22
- """
23
-
24
- def __init__(self, args, alphabet):
25
- super().__init__()
26
- encoder_embed_tokens = self.build_embedding(
27
- args,
28
- alphabet,
29
- args.encoder_embed_dim,
30
- )
31
- decoder_embed_tokens = self.build_embedding(
32
- args,
33
- alphabet,
34
- args.decoder_embed_dim,
35
- )
36
- encoder = self.build_encoder(args, alphabet, encoder_embed_tokens)
37
- decoder = self.build_decoder(args, alphabet, decoder_embed_tokens)
38
- self.args = args
39
- self.encoder = encoder
40
- self.decoder = decoder
41
-
42
- @classmethod
43
- def build_encoder(cls, args, src_dict, embed_tokens):
44
- encoder = GVPTransformerEncoder(args, src_dict, embed_tokens)
45
- return encoder
46
-
47
- @classmethod
48
- def build_decoder(cls, args, tgt_dict, embed_tokens):
49
- decoder = TransformerDecoder(
50
- args,
51
- tgt_dict,
52
- embed_tokens,
53
- )
54
- return decoder
55
-
56
- @classmethod
57
- def build_embedding(cls, args, dictionary, embed_dim):
58
- num_embeddings = len(dictionary)
59
- padding_idx = dictionary.padding_idx
60
- emb = nn.Embedding(num_embeddings, embed_dim, padding_idx)
61
- nn.init.normal_(emb.weight, mean=0, std=embed_dim**-0.5)
62
- nn.init.constant_(emb.weight[padding_idx], 0)
63
- return emb
64
-
65
- def forward(
66
- self,
67
- coords,
68
- padding_mask,
69
- confidence,
70
- prev_output_tokens,
71
- return_all_hiddens: bool = False,
72
- features_only: bool = False,
73
- ):
74
- encoder_out = self.encoder(
75
- coords, padding_mask, confidence, return_all_hiddens=return_all_hiddens
76
- )
77
- logits, extra = self.decoder(
78
- prev_output_tokens,
79
- encoder_out=encoder_out,
80
- features_only=features_only,
81
- return_all_hiddens=return_all_hiddens,
82
- )
83
- return logits, extra
84
-
85
- def sample(
86
- self, coords, partial_seq=None, temperature=1.0, confidence=None, device=None
87
- ):
88
- """
89
- Samples sequences based on multinomial sampling (no beam search).
90
-
91
- Args:
92
- coords: L x 3 x 3 list representing one backbone
93
- partial_seq: Optional, partial sequence with mask tokens if part of
94
- the sequence is known
95
- temperature: sampling temperature, use low temperature for higher
96
- sequence recovery and high temperature for higher diversity
97
- confidence: optional length L list of confidence scores for coordinates
98
- """
99
- L = len(coords)
100
- # Convert to batch format
101
- batch_converter = CoordBatchConverter(self.decoder.dictionary)
102
- batch_coords, confidence, _, _, padding_mask = batch_converter(
103
- [(coords, confidence, None)], device=device
104
- )
105
-
106
- # Start with prepend token
107
- mask_idx = self.decoder.dictionary.get_idx("<mask>")
108
- sampled_tokens = torch.full((1, 1 + L), mask_idx, dtype=int)
109
- sampled_tokens[0, 0] = self.decoder.dictionary.get_idx("<cath>")
110
- if partial_seq is not None:
111
- for i, c in enumerate(partial_seq):
112
- sampled_tokens[0, i + 1] = self.decoder.dictionary.get_idx(c)
113
-
114
- # Save incremental states for faster sampling
115
- incremental_state = dict()
116
-
117
- # Run encoder only once
118
- encoder_out = self.encoder(batch_coords, padding_mask, confidence)
119
-
120
- # Make sure all tensors are on the same device if a GPU is present
121
- if device:
122
- sampled_tokens = sampled_tokens.to(device)
123
-
124
- # Decode one token at a time
125
- for i in range(1, L + 1):
126
- logits, _ = self.decoder(
127
- sampled_tokens[:, :i],
128
- encoder_out,
129
- incremental_state=incremental_state,
130
- )
131
- logits = logits[0].transpose(0, 1)
132
- logits /= temperature
133
- probs = F.softmax(logits, dim=-1)
134
- if sampled_tokens[0, i] == mask_idx:
135
- sampled_tokens[:, i] = torch.multinomial(probs, 1).squeeze(-1)
136
- sampled_seq = sampled_tokens[0, 1:]
137
-
138
- # Convert back to string via lookup
139
- return "".join([self.decoder.dictionary.get_tok(a) for a in sampled_seq])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/gvp_transformer_encoder.py DELETED
@@ -1,189 +0,0 @@
1
- # Copyright (c) Meta Platforms, Inc. and affiliates.
2
- #
3
- # Contents of this file were adapted from the open source fairseq repository.
4
- #
5
- # This source code is licensed under the MIT license found in the
6
- # LICENSE file in the root directory of this source tree.
7
-
8
- import argparse
9
- import math
10
-
11
- import torch
12
- import torch.nn as nn
13
-
14
- from esm.modules import SinusoidalPositionalEmbedding
15
- from .features import GVPInputFeaturizer, DihedralFeatures
16
- from .gvp_encoder import GVPEncoder
17
- from .transformer_layer import TransformerEncoderLayer
18
- from .util import nan_to_num, get_rotation_frames, rotate, rbf
19
-
20
-
21
- class GVPTransformerEncoder(nn.Module):
22
- """
23
- Transformer encoder consisting of *args.encoder.layers* layers. Each layer
24
- is a :class:`TransformerEncoderLayer`.
25
-
26
- Args:
27
- args (argparse.Namespace): parsed command-line arguments
28
- dictionary (~fairseq.data.Dictionary): encoding dictionary
29
- embed_tokens (torch.nn.Embedding): input embedding
30
- """
31
-
32
- def __init__(self, args, dictionary, embed_tokens):
33
- super().__init__()
34
- self.args = args
35
- self.dictionary = dictionary
36
-
37
- self.dropout_module = nn.Dropout(args.dropout)
38
-
39
- embed_dim = embed_tokens.embedding_dim
40
- self.padding_idx = embed_tokens.padding_idx
41
-
42
- self.embed_tokens = embed_tokens
43
- self.embed_scale = math.sqrt(embed_dim)
44
- self.embed_positions = SinusoidalPositionalEmbedding(
45
- embed_dim,
46
- self.padding_idx,
47
- )
48
- self.embed_gvp_input_features = nn.Linear(15, embed_dim)
49
- self.embed_confidence = nn.Linear(16, embed_dim)
50
- self.embed_dihedrals = DihedralFeatures(embed_dim)
51
-
52
- gvp_args = argparse.Namespace()
53
- for k, v in vars(args).items():
54
- if k.startswith("gvp_"):
55
- setattr(gvp_args, k[4:], v)
56
- self.gvp_encoder = GVPEncoder(gvp_args)
57
- gvp_out_dim = gvp_args.node_hidden_dim_scalar + (
58
- 3 * gvp_args.node_hidden_dim_vector
59
- )
60
- self.embed_gvp_output = nn.Linear(gvp_out_dim, embed_dim)
61
-
62
- self.layers = nn.ModuleList([])
63
- self.layers.extend(
64
- [self.build_encoder_layer(args) for i in range(args.encoder_layers)]
65
- )
66
- self.num_layers = len(self.layers)
67
- self.layer_norm = nn.LayerNorm(embed_dim)
68
-
69
- def build_encoder_layer(self, args):
70
- return TransformerEncoderLayer(args)
71
-
72
- def forward_embedding(self, coords, padding_mask, confidence):
73
- """
74
- Args:
75
- coords: N, CA, C backbone coordinates in shape length x 3 (atoms) x 3
76
- padding_mask: boolean Tensor (true for padding) of shape length
77
- confidence: confidence scores between 0 and 1 of shape length
78
- """
79
- components = dict()
80
- coord_mask = torch.all(torch.all(torch.isfinite(coords), dim=-1), dim=-1)
81
- coords = nan_to_num(coords)
82
- mask_tokens = (
83
- padding_mask * self.dictionary.padding_idx
84
- + ~padding_mask * self.dictionary.get_idx("<mask>")
85
- )
86
- components["tokens"] = self.embed_tokens(mask_tokens) * self.embed_scale
87
- components["diherals"] = self.embed_dihedrals(coords)
88
-
89
- # GVP encoder
90
- gvp_out_scalars, gvp_out_vectors = self.gvp_encoder(
91
- coords, coord_mask, padding_mask, confidence
92
- )
93
- R = get_rotation_frames(coords)
94
- # Rotate to local rotation frame for rotation-invariance
95
- gvp_out_features = torch.cat(
96
- [
97
- gvp_out_scalars,
98
- rotate(gvp_out_vectors, R.transpose(-2, -1)).flatten(-2, -1),
99
- ],
100
- dim=-1,
101
- )
102
- components["gvp_out"] = self.embed_gvp_output(gvp_out_features)
103
-
104
- components["confidence"] = self.embed_confidence(rbf(confidence, 0.0, 1.0))
105
-
106
- # In addition to GVP encoder outputs, also directly embed GVP input node
107
- # features to the Transformer
108
- scalar_features, vector_features = GVPInputFeaturizer.get_node_features(
109
- coords, coord_mask, with_coord_mask=False
110
- )
111
- features = torch.cat(
112
- [
113
- scalar_features,
114
- rotate(vector_features, R.transpose(-2, -1)).flatten(-2, -1),
115
- ],
116
- dim=-1,
117
- )
118
- components["gvp_input_features"] = self.embed_gvp_input_features(features)
119
-
120
- embed = sum(components.values())
121
- # for k, v in components.items():
122
- # print(k, torch.mean(v, dim=(0,1)), torch.std(v, dim=(0,1)))
123
-
124
- x = embed
125
- x = x + self.embed_positions(mask_tokens)
126
- x = self.dropout_module(x)
127
- return x, components
128
-
129
- def forward(
130
- self,
131
- coords,
132
- encoder_padding_mask,
133
- confidence,
134
- return_all_hiddens: bool = False,
135
- ):
136
- """
137
- Args:
138
- coords (Tensor): backbone coordinates
139
- shape batch_size x num_residues x num_atoms (3 for N, CA, C) x 3
140
- encoder_padding_mask (ByteTensor): the positions of
141
- padding elements of shape `(batch_size x num_residues)`
142
- confidence (Tensor): the confidence score of shape (batch_size x
143
- num_residues). The value is between 0. and 1. for each residue
144
- coordinate, or -1. if no coordinate is given
145
- return_all_hiddens (bool, optional): also return all of the
146
- intermediate hidden states (default: False).
147
-
148
- Returns:
149
- dict:
150
- - **encoder_out** (Tensor): the last encoder layer's output of
151
- shape `(num_residues, batch_size, embed_dim)`
152
- - **encoder_padding_mask** (ByteTensor): the positions of
153
- padding elements of shape `(batch_size, num_residues)`
154
- - **encoder_embedding** (Tensor): the (scaled) embedding lookup
155
- of shape `(batch_size, num_residues, embed_dim)`
156
- - **encoder_states** (List[Tensor]): all intermediate
157
- hidden states of shape `(num_residues, batch_size, embed_dim)`.
158
- Only populated if *return_all_hiddens* is True.
159
- """
160
- x, encoder_embedding = self.forward_embedding(
161
- coords, encoder_padding_mask, confidence
162
- )
163
- # account for padding while computing the representation
164
- x = x * (1 - encoder_padding_mask.unsqueeze(-1).type_as(x))
165
-
166
- # B x T x C -> T x B x C
167
- x = x.transpose(0, 1)
168
-
169
- encoder_states = []
170
-
171
- if return_all_hiddens:
172
- encoder_states.append(x)
173
-
174
- # encoder layers
175
- for layer in self.layers:
176
- x = layer(x, encoder_padding_mask=encoder_padding_mask)
177
- if return_all_hiddens:
178
- assert encoder_states is not None
179
- encoder_states.append(x)
180
-
181
- if self.layer_norm is not None:
182
- x = self.layer_norm(x)
183
-
184
- return {
185
- "encoder_out": [x], # T x B x C
186
- "encoder_padding_mask": [encoder_padding_mask], # B x T
187
- "encoder_embedding": [encoder_embedding], # dictionary
188
- "encoder_states": encoder_states, # List[T x B x C]
189
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/gvp_utils.py DELETED
@@ -1,67 +0,0 @@
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 torch
7
-
8
-
9
- def flatten_graph(node_embeddings, edge_embeddings, edge_index):
10
- """
11
- Flattens the graph into a batch size one (with disconnected subgraphs for
12
- each example) to be compatible with pytorch-geometric package.
13
- Args:
14
- node_embeddings: node embeddings in tuple form (scalar, vector)
15
- - scalar: shape batch size x nodes x node_embed_dim
16
- - vector: shape batch size x nodes x node_embed_dim x 3
17
- edge_embeddings: edge embeddings of in tuple form (scalar, vector)
18
- - scalar: shape batch size x edges x edge_embed_dim
19
- - vector: shape batch size x edges x edge_embed_dim x 3
20
- edge_index: shape batch_size x 2 (source node and target node) x edges
21
- Returns:
22
- node_embeddings: node embeddings in tuple form (scalar, vector)
23
- - scalar: shape batch total_nodes x node_embed_dim
24
- - vector: shape batch total_nodes x node_embed_dim x 3
25
- edge_embeddings: edge embeddings of in tuple form (scalar, vector)
26
- - scalar: shape batch total_edges x edge_embed_dim
27
- - vector: shape batch total_edges x edge_embed_dim x 3
28
- edge_index: shape 2 x total_edges
29
- """
30
- x_s, x_v = node_embeddings
31
- e_s, e_v = edge_embeddings
32
- batch_size, N = x_s.shape[0], x_s.shape[1]
33
- node_embeddings = (torch.flatten(x_s, 0, 1), torch.flatten(x_v, 0, 1))
34
- edge_embeddings = (torch.flatten(e_s, 0, 1), torch.flatten(e_v, 0, 1))
35
-
36
- edge_mask = torch.any(edge_index != -1, dim=1)
37
- # Re-number the nodes by adding batch_idx * N to each batch
38
- edge_index = edge_index + (
39
- torch.arange(batch_size, device=edge_index.device) * N
40
- ).unsqueeze(-1).unsqueeze(-1)
41
- edge_index = edge_index.permute(1, 0, 2).flatten(1, 2)
42
- edge_mask = edge_mask.flatten()
43
- edge_index = edge_index[:, edge_mask]
44
- edge_embeddings = (
45
- edge_embeddings[0][edge_mask, :],
46
- edge_embeddings[1][edge_mask, :],
47
- )
48
- return node_embeddings, edge_embeddings, edge_index
49
-
50
-
51
- def unflatten_graph(node_embeddings, batch_size):
52
- """
53
- Unflattens node embeddings.
54
- Args:
55
- node_embeddings: node embeddings in tuple form (scalar, vector)
56
- - scalar: shape batch total_nodes x node_embed_dim
57
- - vector: shape batch total_nodes x node_embed_dim x 3
58
- batch_size: int
59
- Returns:
60
- node_embeddings: node embeddings in tuple form (scalar, vector)
61
- - scalar: shape batch size x nodes x node_embed_dim
62
- - vector: shape batch size x nodes x node_embed_dim x 3
63
- """
64
- x_s, x_v = node_embeddings
65
- x_s = x_s.reshape(batch_size, -1, x_s.shape[1])
66
- x_v = x_v.reshape(batch_size, -1, x_v.shape[1], x_v.shape[2])
67
- return (x_s, x_v)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
protgps/esm_models/esm2/facebookresearch_esm_main/esm/inverse_folding/multichain_util.py DELETED
@@ -1,152 +0,0 @@
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 biotite.structure
7
- import numpy as np
8
-
9
- from esm.inverse_folding.util import (
10
- load_structure,
11
- extract_coords_from_structure,
12
- get_sequence_loss,
13
- get_encoder_output,
14
- )
15
-
16
-
17
- def extract_coords_from_complex(structure: biotite.structure.AtomArray):
18
- """
19
- Args:
20
- structure: biotite AtomArray
21
- Returns:
22
- Tuple (coords_list, seq_list)
23
- - coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C
24
- coordinates representing the backbone of each chain
25
- - seqs: Dictionary mapping chain ids to native sequences of each chain
26
- """
27
- coords = {}
28
- seqs = {}
29
- all_chains = biotite.structure.get_chains(structure)
30
- for chain_id in all_chains:
31
- chain = structure[structure.chain_id == chain_id]
32
- coords[chain_id], seqs[chain_id] = extract_coords_from_structure(chain)
33
- return coords, seqs
34
-
35
-
36
- def load_complex_coords(fpath, chains):
37
- """
38
- Args:
39
- fpath: filepath to either pdb or cif file
40
- chains: the chain ids (the order matters for autoregressive model)
41
- Returns:
42
- Tuple (coords_list, seq_list)
43
- - coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C
44
- coordinates representing the backbone of each chain
45
- - seqs: Dictionary mapping chain ids to native sequences of each chain
46
- """
47
- structure = load_structure(fpath, chains)
48
- return extract_coords_from_complex(structure)
49
-
50
-
51
- def _concatenate_coords(coords, target_chain_id, padding_length=10):
52
- """
53
- Args:
54
- coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C
55
- coordinates representing the backbone of each chain
56
- target_chain_id: The chain id to sample sequences for
57
- padding_length: Length of padding between concatenated chains
58
- Returns:
59
- Tuple (coords, seq)
60
- - coords is an L x 3 x 3 array for N, CA, C coordinates, a
61
- concatenation of the chains with padding in between
62
- - seq is the extracted sequence, with padding tokens inserted
63
- between the concatenated chains
64
- """
65
- pad_coords = np.full((padding_length, 3, 3), np.nan, dtype=np.float32)
66
- # For best performance, put the target chain first in concatenation.
67
- coords_list = [coords[target_chain_id]]
68
- for chain_id in coords:
69
- if chain_id == target_chain_id:
70
- continue
71
- coords_list.append(pad_coords)
72
- coords_list.append(coords[chain_id])
73
- coords_concatenated = np.concatenate(coords_list, axis=0)
74
- return coords_concatenated
75
-
76
-
77
- def sample_sequence_in_complex(
78
- model, coords, target_chain_id, temperature=1.0, padding_length=10
79
- ):
80
- """
81
- Samples sequence for one chain in a complex.
82
- Args:
83
- model: An instance of the GVPTransformer model
84
- coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C
85
- coordinates representing the backbone of each chain
86
- target_chain_id: The chain id to sample sequences for
87
- padding_length: padding length in between chains
88
- Returns:
89
- Sampled sequence for the target chain
90
- """
91
- target_chain_len = coords[target_chain_id].shape[0]
92
- all_coords = _concatenate_coords(coords, target_chain_id)
93
- device = next(model.parameters()).device
94
-
95
- # Supply padding tokens for other chains to avoid unused sampling for speed
96
- padding_pattern = ["<pad>"] * all_coords.shape[0]
97
- for i in range(target_chain_len):
98
- padding_pattern[i] = "<mask>"
99
- sampled = model.sample(
100
- all_coords, partial_seq=padding_pattern, temperature=temperature, device=device
101
- )
102
- sampled = sampled[:target_chain_len]
103
- return sampled
104
-
105
-
106
- def score_sequence_in_complex(
107
- model, alphabet, coords, target_chain_id, target_seq, padding_length=10
108
- ):
109
- """
110
- Scores sequence for one chain in a complex.
111
- Args:
112
- model: An instance of the GVPTransformer model
113
- alphabet: Alphabet for the model
114
- coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C
115
- coordinates representing the backbone of each chain
116
- target_chain_id: The chain id to sample sequences for
117
- target_seq: Target sequence for the target chain for scoring.
118
- padding_length: padding length in between chains
119
- Returns:
120
- Tuple (ll_fullseq, ll_withcoord)
121
- - ll_fullseq: Average log-likelihood over the full target chain
122
- - ll_withcoord: Average log-likelihood in target chain excluding those
123
- residues without coordinates
124
- """
125
- all_coords = _concatenate_coords(coords, target_chain_id)
126
-
127
- loss, target_padding_mask = get_sequence_loss(
128
- model, alphabet, all_coords, target_seq
129
- )
130
- ll_fullseq = -np.sum(loss * ~target_padding_mask) / np.sum(~target_padding_mask)
131
-
132
- # Also calculate average when excluding masked portions
133
- coord_mask = np.all(np.isfinite(coords[target_chain_id]), axis=(-1, -2))
134
- ll_withcoord = -np.sum(loss * coord_mask) / np.sum(coord_mask)
135
- return ll_fullseq, ll_withcoord
136
-
137
-
138
- def get_encoder_output_for_complex(model, alphabet, coords, target_chain_id):
139
- """
140
- Args:
141
- model: An instance of the GVPTransformer model
142
- alphabet: Alphabet for the model
143
- coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C
144
- coordinates representing the backbone of each chain
145
- target_chain_id: The chain id to sample sequences for
146
- Returns:
147
- Dictionary mapping chain id to encoder output for each chain
148
- """
149
- all_coords = _concatenate_coords(coords, target_chain_id)
150
- all_rep = get_encoder_output(model, alphabet, all_coords)
151
- target_chain_len = coords[target_chain_id].shape[0]
152
- return all_rep[:target_chain_len]