pstjohn commited on
Commit
8494378
·
verified ·
1 Parent(s): ffccf69

Upload folder using huggingface_hub

Browse files
Files changed (8) hide show
  1. LICENSE +203 -0
  2. README.md +34 -0
  3. config.json +40 -0
  4. esm_nv.py +474 -0
  5. model.safetensors +3 -0
  6. special_tokens_map.json +7 -0
  7. tokenizer_config.json +53 -0
  8. vocab.txt +33 -0
LICENSE ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
191
+ Copyright 2025 NVIDIA CORPORATION. All rights reserved.
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: mit
4
+ widget:
5
+ - text: MQIFVKTLTGKTITLEVEPS<mask>TIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG
6
+ ---
7
+
8
+ ## ESM-2 (TransformerEngine-optimized)
9
+
10
+ This version of the ESM-2 model is optimized with NVIDIA's
11
+ [TransformerEngine](https://github.com/NVIDIA/TransformerEngine) library. It is based on the
12
+ [original ESM-2 model](https://huggingface.co/facebook/esm2_t48_15B_UR50D) from Facebook Research,
13
+ and (within numerical precision) has identical weights and outputs.
14
+
15
+ ESM-2 is a state-of-the-art protein model trained on a masked language modelling objective. It is
16
+ suitable for fine-tuning on a wide range of tasks that take protein sequences as input. For detailed
17
+ information on the model architecture and training data, please refer to the [accompanying
18
+ paper](https://www.biorxiv.org/content/10.1101/2022.07.20.500902v2). You may also be interested in
19
+ some demo notebooks
20
+ ([PyTorch](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb),
21
+ [TensorFlow](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_language_modeling-tf.ipynb))
22
+ which demonstrate how to fine-tune ESM-2 models on your tasks of interest.
23
+
24
+ Several ESM-2 checkpoints are available in the Hub with varying sizes. Larger sizes generally have
25
+ somewhat better accuracy, but require much more memory and time to train:
26
+
27
+ | Checkpoint name | Num layers | Num parameters |
28
+ | ------------------------------------------------------------------------ | ---------- | -------------- |
29
+ | [esm2_t48_15B_UR50D](https://huggingface.co/nvidia/esm2_t48_15B_UR50D) | 48 | 15B |
30
+ | [esm2_t36_3B_UR50D](https://huggingface.co/nvidia/esm2_t36_3B_UR50D) | 36 | 3B |
31
+ | [esm2_t33_650M_UR50D](https://huggingface.co/nvidia/esm2_t33_650M_UR50D) | 33 | 650M |
32
+ | [esm2_t30_150M_UR50D](https://huggingface.co/nvidia/esm2_t30_150M_UR50D) | 30 | 150M |
33
+ | [esm2_t12_35M_UR50D](https://huggingface.co/nvidia/esm2_t12_35M_UR50D) | 12 | 35M |
34
+ | [esm2_t6_8M_UR50D](https://huggingface.co/nvidia/esm2_t6_8M_UR50D) | 6 | 8M |
config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "NVEsmForMaskedLM"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.0,
6
+ "attn_input_format": "bshd",
7
+ "auto_map": {
8
+ "AutoConfig": "esm_nv.NVEsmConfig",
9
+ "AutoModel": "esm_nv.NVEsmModel",
10
+ "AutoModelForMaskedLM": "esm_nv.NVEsmForMaskedLM"
11
+ },
12
+ "classifier_dropout": null,
13
+ "emb_layer_norm_before": false,
14
+ "encoder_activation": "gelu",
15
+ "esmfold_config": null,
16
+ "fuse_qkv_params": true,
17
+ "hidden_act": "gelu",
18
+ "hidden_dropout_prob": 0.0,
19
+ "hidden_size": 640,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 2560,
22
+ "is_folding_model": false,
23
+ "layer_norm_eps": 1e-05,
24
+ "mask_token_id": 32,
25
+ "max_position_embeddings": 1026,
26
+ "max_seq_length": null,
27
+ "micro_batch_size": null,
28
+ "model_type": "nv_esm",
29
+ "num_attention_heads": 20,
30
+ "num_hidden_layers": 30,
31
+ "pad_token_id": 1,
32
+ "position_embedding_type": "rotary",
33
+ "qkv_weight_interleaved": true,
34
+ "token_dropout": true,
35
+ "torch_dtype": "float32",
36
+ "transformers_version": "4.55.0.dev0",
37
+ "use_cache": true,
38
+ "vocab_list": null,
39
+ "vocab_size": 33
40
+ }
esm_nv.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
+ # SPDX-License-Identifier: LicenseRef-Apache2
4
+ # Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
5
+ # Copyright 2025 NVIDIA CORPORATION. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+
20
+ """TransformerEngine-optimized ESM model.
21
+
22
+ Adapted from `modeling_esm.py` in huggingface/transformers.
23
+ """
24
+
25
+ from typing import Optional, Tuple, Union
26
+
27
+ # TODO: put import guard around transformer_engine here, with an informative error message around
28
+ # installation and the nvidia docker container.
29
+ import torch
30
+ import transformer_engine.pytorch
31
+ from torch import nn
32
+ from torch.nn import CrossEntropyLoss
33
+ from transformer_engine.pytorch.attention.rope import RotaryPositionEmbedding
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutput,
36
+ BaseModelOutputWithPooling,
37
+ BaseModelOutputWithPoolingAndCrossAttentions,
38
+ MaskedLMOutput,
39
+ )
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.models.esm.configuration_esm import EsmConfig
42
+ from transformers.models.esm.modeling_esm import EsmEmbeddings, EsmPooler
43
+ from transformers.utils import logging
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ class NVEsmConfig(EsmConfig):
50
+ """NVEsmConfig is a configuration for the NVEsm model."""
51
+
52
+ model_type: str = "nv_esm"
53
+
54
+ def __init__(
55
+ self,
56
+ qkv_weight_interleaved: bool = True,
57
+ encoder_activation: str = "gelu",
58
+ attn_input_format: str = "bshd",
59
+ fuse_qkv_params: bool = True,
60
+ micro_batch_size: Optional[int] = None,
61
+ max_seq_length: Optional[int] = None,
62
+ **kwargs,
63
+ ):
64
+ """Initialize the NVEsmConfig with additional TE-related config options.
65
+
66
+ Args:
67
+ qkv_weight_interleaved: Whether to interleave the qkv weights. If set to `False`, the
68
+ QKV weight is interpreted as a concatenation of query, key, and value weights along
69
+ the `0th` dimension. The default interpretation is that the individual `q`, `k`, and
70
+ `v` weights for each attention head are interleaved. This parameter is set to `False`
71
+ when using :attr:`fuse_qkv_params=False`.
72
+ encoder_activation: The activation function to use in the encoder.
73
+ attn_input_format: The input format to use for the attention. This controls
74
+ whether the dimensions of the intermediate hidden states is 'batch first'
75
+ ('bshd') or 'sequence first' ('sbhd'). `s` stands for the sequence length,
76
+ `b` batch size, `h` the number of heads, `d` head size. Note that these
77
+ formats are very closely related to the `qkv_format` in the
78
+ `MultiHeadAttention` and `DotProductAttention` modules.
79
+ fuse_qkv_params: Whether to fuse the qkv parameters. If set to `True`,
80
+ `TransformerLayer` module exposes a single fused parameter for query-key-value.
81
+ This enables optimizations such as QKV fusion without concatentations/splits and
82
+ also enables the argument `fuse_wgrad_accumulation`.
83
+ micro_batch_size: The micro batch size to use for the attention. This is needed for
84
+ JIT Warmup, a technique where jit fused functions are warmed up before training to
85
+ ensure same kernels are used for forward propogation and activation recompute phase.
86
+ max_seq_length: The maximum sequence length to use for the attention. This is needed for
87
+ JIT Warmup, a technique where jit fused functions are warmed up before training to
88
+ ensure same kernels are used for forward propogation and activation recompute phase.
89
+ **kwargs: Additional config options to pass to EsmConfig.
90
+ """
91
+ super().__init__(**kwargs)
92
+ # Additional TE-related config options.
93
+ self.qkv_weight_interleaved = qkv_weight_interleaved
94
+ self.encoder_activation = encoder_activation
95
+ self.attn_input_format = attn_input_format
96
+ self.fuse_qkv_params = fuse_qkv_params
97
+ self.micro_batch_size = micro_batch_size
98
+ self.max_seq_length = max_seq_length
99
+
100
+
101
+ class NVEsmEncoder(nn.Module):
102
+ """NVEsmEncoder is a TransformerEngine-optimized ESM encoder."""
103
+
104
+ def __init__(self, config: NVEsmConfig):
105
+ """Initialize a NVEsmEncoder.
106
+
107
+ Args:
108
+ config (NVEsmConfig): The configuration of the model.
109
+ """
110
+ super().__init__()
111
+ self.config = config
112
+ self.layers = nn.ModuleList(
113
+ [
114
+ transformer_engine.pytorch.TransformerLayer(
115
+ hidden_size=config.hidden_size,
116
+ ffn_hidden_size=config.intermediate_size,
117
+ num_attention_heads=config.num_attention_heads,
118
+ layernorm_epsilon=config.layer_norm_eps,
119
+ hidden_dropout=config.hidden_dropout_prob,
120
+ attention_dropout=config.attention_probs_dropout_prob,
121
+ qkv_weight_interleaved=config.qkv_weight_interleaved,
122
+ layer_number=i + 1,
123
+ layer_type="encoder",
124
+ self_attn_mask_type="padding",
125
+ activation=config.encoder_activation,
126
+ attn_input_format=config.attn_input_format,
127
+ seq_length=config.max_seq_length,
128
+ micro_batch_size=config.micro_batch_size,
129
+ num_gqa_groups=config.num_attention_heads,
130
+ fuse_qkv_params=config.fuse_qkv_params,
131
+ params_dtype=config.torch_dtype,
132
+ window_size=(-1, -1),
133
+ )
134
+ for i in range(config.num_hidden_layers)
135
+ ]
136
+ )
137
+ self.emb_layer_norm_after = transformer_engine.pytorch.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
138
+ if config.position_embedding_type == "rotary":
139
+ self.rotary_embeddings = RotaryPositionEmbedding(config.hidden_size // config.num_attention_heads)
140
+ self.te_rope_emb = self.rotary_embeddings(max_seq_len=config.max_position_embeddings).cuda()
141
+ else:
142
+ self.te_rope_emb = None
143
+
144
+ def forward(
145
+ self,
146
+ hidden_states: torch.Tensor,
147
+ attention_mask: Optional[torch.Tensor] = None,
148
+ output_hidden_states: bool = False,
149
+ ):
150
+ """Forward pass of the NVEsmEncoder.
151
+
152
+ Args:
153
+ hidden_states (torch.Tensor): The hidden states.
154
+ attention_mask (torch.Tensor): The attention mask.
155
+ output_hidden_states (bool): Whether to output the hidden states.
156
+ """
157
+ all_hidden_states = () if output_hidden_states else None
158
+
159
+ for layer_module in self.layers:
160
+ if output_hidden_states:
161
+ all_hidden_states = (*all_hidden_states, hidden_states)
162
+
163
+ hidden_states = layer_module(
164
+ hidden_states,
165
+ attention_mask,
166
+ rotary_pos_emb=self.te_rope_emb,
167
+ )
168
+
169
+ hidden_states = self.emb_layer_norm_after(hidden_states)
170
+
171
+ if output_hidden_states:
172
+ all_hidden_states = (*all_hidden_states, hidden_states)
173
+
174
+ return BaseModelOutput(
175
+ last_hidden_state=hidden_states,
176
+ hidden_states=all_hidden_states,
177
+ )
178
+
179
+
180
+ class NVEsmPreTrainedModel(PreTrainedModel):
181
+ """An abstract class to handle weights initialization and pretrained model loading."""
182
+
183
+ config_class = NVEsmConfig
184
+ base_model_prefix = "esm"
185
+ supports_gradient_checkpointing = False
186
+ _no_split_modules = (
187
+ "TransformerLayer",
188
+ "EsmEmbeddings",
189
+ )
190
+
191
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
192
+ def _init_weights(self, module: nn.Module):
193
+ """Initialize the weights.
194
+
195
+ Args:
196
+ module (nn.Module): The module to initialize the weights for.
197
+ """
198
+ if isinstance(
199
+ module, (nn.Linear, transformer_engine.pytorch.Linear, transformer_engine.pytorch.LayerNormLinear)
200
+ ):
201
+ # Slightly different from the TF version which uses truncated_normal for initialization
202
+ # cf https://github.com/pytorch/pytorch/pull/5617
203
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
204
+ if module.bias is not None:
205
+ module.bias.data.zero_()
206
+ if isinstance(module, nn.Embedding):
207
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
208
+ if module.padding_idx is not None:
209
+ module.weight.data[module.padding_idx].zero_()
210
+ if isinstance(module, (nn.LayerNorm, transformer_engine.pytorch.LayerNorm)):
211
+ module.bias.data.zero_()
212
+ module.weight.data.fill_(1.0)
213
+ if isinstance(module, transformer_engine.pytorch.LayerNormLinear):
214
+ module.layer_norm_weight.data.fill_(1.0)
215
+ if module.layer_norm_bias is not None:
216
+ module.layer_norm_bias.data.zero_()
217
+
218
+
219
+ class NVEsmModel(NVEsmPreTrainedModel):
220
+ """The ESM Encoder-only protein language model.
221
+
222
+ This model uses NVDIA's TransformerEngine to optimize attention layer training and inference.
223
+ """
224
+
225
+ def __init__(self, config: NVEsmConfig, add_pooling_layer: bool = True):
226
+ """Initialize a NVEsmModel.
227
+
228
+ Args:
229
+ config (NVEsmConfig): The configuration of the model.
230
+ add_pooling_layer (bool): Whether to add a pooling layer.
231
+ """
232
+ super().__init__(config)
233
+ self.config = config
234
+
235
+ self.embeddings = EsmEmbeddings(config)
236
+ self.encoder = NVEsmEncoder(config)
237
+ self.pooler = EsmPooler(config) if add_pooling_layer else None
238
+
239
+ # Initialize weights and apply final processing
240
+ self.post_init()
241
+
242
+ def get_input_embeddings(self):
243
+ """Get the input embeddings of the model."""
244
+ return self.embeddings.word_embeddings
245
+
246
+ def set_input_embeddings(self, value: torch.Tensor):
247
+ """Set the input embeddings of the model.
248
+
249
+ Args:
250
+ value (torch.Tensor): The input embeddings.
251
+ """
252
+ self.embeddings.word_embeddings = value
253
+
254
+ def forward(
255
+ self,
256
+ input_ids: Optional[torch.Tensor] = None,
257
+ attention_mask: Optional[torch.Tensor] = None,
258
+ position_ids: Optional[torch.Tensor] = None,
259
+ head_mask: Optional[torch.Tensor] = None,
260
+ inputs_embeds: Optional[torch.Tensor] = None,
261
+ output_hidden_states: Optional[bool] = None,
262
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
263
+ """Forward pass of the NVEsmModel.
264
+
265
+ Args:
266
+ input_ids (torch.Tensor): The input ids.
267
+ attention_mask (torch.Tensor): The attention mask.
268
+ position_ids (torch.Tensor): The position ids.
269
+ head_mask (torch.Tensor): The head mask.
270
+ inputs_embeds (torch.Tensor): The input embeddings.
271
+ output_hidden_states (bool): Whether to output the hidden states.
272
+
273
+ Returns:
274
+ BaseModelOutputWithPooling: The output of the model.
275
+ """
276
+ r"""
277
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
278
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the
279
+ cross-attention if the model is configured as a decoder.
280
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
281
+ Mask to avoid performing attention on the padding token indices of the encoder input.
282
+ This mask is used in the cross-attention if the model is configured as a decoder. Mask
283
+ values selected in `[0, 1]`:
284
+
285
+ - 1 for tokens that are **not masked**,
286
+ - 0 for tokens that are **masked**.
287
+
288
+ Note that this mask is inverted when it is passed to TransformerEngine, which expects a
289
+ boolean mask where 1s are masked and 0s are not masked.
290
+ """
291
+ output_hidden_states = (
292
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
293
+ )
294
+
295
+ if input_ids is not None and inputs_embeds is not None:
296
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
297
+ elif input_ids is not None:
298
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
299
+ input_shape = input_ids.size()
300
+ elif inputs_embeds is not None:
301
+ input_shape = inputs_embeds.size()[:-1]
302
+ else:
303
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
304
+
305
+ batch_size, seq_length = input_shape
306
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
307
+
308
+ if attention_mask is None:
309
+ attention_mask = torch.ones(((batch_size, seq_length)), device=device)
310
+
311
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
312
+ # ourselves in which case we just need to make it broadcastable to all heads.
313
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
314
+
315
+ # TE expects a boolean attention mask, where 1s are masked and 0s are not masked
316
+ extended_attention_mask = extended_attention_mask < -1
317
+
318
+ # Prepare head mask if needed
319
+ # 1.0 in head_mask indicate we keep the head
320
+ # attention_probs has shape bsz x n_heads x N x N
321
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
322
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
323
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
324
+
325
+ embedding_output = self.embeddings(
326
+ input_ids=input_ids,
327
+ position_ids=position_ids,
328
+ attention_mask=attention_mask,
329
+ inputs_embeds=inputs_embeds,
330
+ )
331
+ encoder_outputs = self.encoder(
332
+ embedding_output,
333
+ attention_mask=extended_attention_mask,
334
+ output_hidden_states=output_hidden_states,
335
+ )
336
+ sequence_output = encoder_outputs[0]
337
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
338
+
339
+ return BaseModelOutputWithPooling(
340
+ last_hidden_state=sequence_output,
341
+ pooler_output=pooled_output,
342
+ hidden_states=encoder_outputs.hidden_states,
343
+ )
344
+
345
+
346
+ class NVEsmForMaskedLM(NVEsmPreTrainedModel):
347
+ """NVEsmForMaskedLM is a TransformerEngine-optimized ESM model for masked language modeling."""
348
+
349
+ _tied_weights_keys = ("lm_head.decoder.weight",)
350
+
351
+ def __init__(self, config: NVEsmConfig):
352
+ """Initialize a NVEsmForMaskedLM.
353
+
354
+ Args:
355
+ config (NVEsmConfig): The configuration of the model.
356
+ """
357
+ super().__init__(config)
358
+
359
+ if config.is_decoder:
360
+ logger.warning(
361
+ "If you want to use `EsmForMaskedLM` make sure `config.is_decoder=False` for "
362
+ "bi-directional self-attention."
363
+ )
364
+
365
+ self.esm = NVEsmModel(config, add_pooling_layer=False)
366
+ self.lm_head = NVEsmLMHead(config)
367
+
368
+ self.init_weights()
369
+ self.post_init()
370
+
371
+ def get_output_embeddings(self):
372
+ """Get the output embeddings of the model."""
373
+ return self.lm_head.decoder
374
+
375
+ def set_output_embeddings(self, new_embeddings):
376
+ """Set the output embeddings of the model."""
377
+ self.lm_head.decoder = new_embeddings
378
+
379
+ def forward(
380
+ self,
381
+ input_ids: Optional[torch.LongTensor] = None,
382
+ attention_mask: Optional[torch.Tensor] = None,
383
+ position_ids: Optional[torch.LongTensor] = None,
384
+ inputs_embeds: Optional[torch.FloatTensor] = None,
385
+ labels: Optional[torch.LongTensor] = None,
386
+ output_hidden_states: Optional[bool] = None,
387
+ ) -> Union[Tuple, MaskedLMOutput]:
388
+ """Forward pass of the NVEsmForMaskedLM.
389
+
390
+ Args:
391
+ input_ids (torch.LongTensor): The input ids.
392
+ attention_mask (torch.Tensor): The attention mask.
393
+ position_ids (torch.LongTensor): The position ids.
394
+ inputs_embeds (torch.FloatTensor): The input embeddings.
395
+ labels (torch.LongTensor): The labels.
396
+ output_hidden_states (bool): Whether to output the hidden states.
397
+
398
+ Returns:
399
+ MaskedLMOutput: The output of the model.
400
+ """
401
+ r"""
402
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
403
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
404
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
405
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
406
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
407
+ Used to hide legacy arguments that have been deprecated.
408
+ """
409
+ outputs = self.esm(
410
+ input_ids,
411
+ attention_mask=attention_mask,
412
+ position_ids=position_ids,
413
+ inputs_embeds=inputs_embeds,
414
+ output_hidden_states=output_hidden_states,
415
+ )
416
+ sequence_output = outputs[0]
417
+ prediction_scores = self.lm_head(sequence_output)
418
+
419
+ masked_lm_loss = None
420
+ if labels is not None:
421
+ loss_fct = CrossEntropyLoss()
422
+
423
+ labels = labels.to(prediction_scores.device)
424
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
425
+
426
+ return MaskedLMOutput(
427
+ loss=masked_lm_loss,
428
+ logits=prediction_scores,
429
+ hidden_states=outputs.hidden_states,
430
+ )
431
+
432
+ def predict_contacts(self, tokens: torch.Tensor, attention_mask: torch.Tensor):
433
+ """Predict the contacts of the model.
434
+
435
+ Args:
436
+ tokens (torch.Tensor): The tokens.
437
+ attention_mask (torch.Tensor): The attention mask.
438
+
439
+ Returns:
440
+ torch.Tensor: The predicted contacts.
441
+ """
442
+ return self.esm.predict_contacts(tokens, attention_mask=attention_mask)
443
+
444
+
445
+ class NVEsmLMHead(nn.Module):
446
+ """ESM Head for masked language modeling using TransformerEngine."""
447
+
448
+ def __init__(self, config: NVEsmConfig):
449
+ """Initialize a NVEsmLMHead.
450
+
451
+ Args:
452
+ config (NVEsmConfig): The configuration of the model.
453
+ """
454
+ super().__init__()
455
+ self.dense = transformer_engine.pytorch.Linear(config.hidden_size, config.hidden_size)
456
+
457
+ self.decoder = transformer_engine.pytorch.LayerNormLinear(
458
+ config.hidden_size,
459
+ config.vocab_size,
460
+ bias=True,
461
+ eps=config.layer_norm_eps,
462
+ )
463
+
464
+ def forward(self, features, **kwargs):
465
+ """Forward pass of the NVEsmLMHead.
466
+
467
+ Args:
468
+ features (torch.Tensor): The features.
469
+ **kwargs: Additional arguments.
470
+ """
471
+ x = self.dense(features)
472
+ x = torch.nn.functional.gelu(x)
473
+ x = self.decoder(x)
474
+ return x
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48728d06bb9ec5f5edb532c9faa27775af2aad0a50ca9e05f715d842dea33063
3
+ size 592618665
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "<cls>",
3
+ "eos_token": "<eos>",
4
+ "mask_token": "<mask>",
5
+ "pad_token": "<pad>",
6
+ "unk_token": "<unk>"
7
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<cls>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "<eos>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "32": {
36
+ "content": "<mask>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": false,
45
+ "cls_token": "<cls>",
46
+ "eos_token": "<eos>",
47
+ "extra_special_tokens": {},
48
+ "mask_token": "<mask>",
49
+ "model_max_length": 1000000000000000019884624838656,
50
+ "pad_token": "<pad>",
51
+ "tokenizer_class": "EsmTokenizer",
52
+ "unk_token": "<unk>"
53
+ }
vocab.txt ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <cls>
2
+ <pad>
3
+ <eos>
4
+ <unk>
5
+ L
6
+ A
7
+ G
8
+ V
9
+ S
10
+ E
11
+ R
12
+ T
13
+ I
14
+ D
15
+ P
16
+ K
17
+ Q
18
+ N
19
+ F
20
+ Y
21
+ M
22
+ H
23
+ W
24
+ C
25
+ X
26
+ B
27
+ U
28
+ Z
29
+ O
30
+ .
31
+ -
32
+ <null_1>
33
+ <mask>