pstjohn commited on
Commit
1a4e094
·
verified ·
1 Parent(s): b0c46be

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. LICENSE +203 -0
  2. README.md +15 -11
  3. config.json +3 -2
  4. esm_nv.py +150 -50
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 CHANGED
@@ -1,8 +1,12 @@
1
- ---
 
 
2
  license: mit
3
  widget:
4
- - text: "MQIFVKTLTGKTITLEVEPS<mask>TIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG"
5
- ---
 
 
6
 
7
  ## ESM-2 (TransformerEngine-optimized)
8
 
@@ -23,11 +27,11 @@ which demonstrate how to fine-tune ESM-2 models on your tasks of interest.
23
  Several ESM-2 checkpoints are available in the Hub with varying sizes. Larger sizes generally have
24
  somewhat better accuracy, but require much more memory and time to train:
25
 
26
- | Checkpoint name | Num layers | Num parameters |
27
- |------------------------------|----|----------|
28
- | [esm2_t48_15B_UR50D](https://huggingface.co/nvidia/esm2_t48_15B_UR50D) | 48 | 15B |
29
- | [esm2_t36_3B_UR50D](https://huggingface.co/nvidia/esm2_t36_3B_UR50D) | 36 | 3B |
30
- | [esm2_t33_650M_UR50D](https://huggingface.co/nvidia/esm2_t33_650M_UR50D) | 33 | 650M |
31
- | [esm2_t30_150M_UR50D](https://huggingface.co/nvidia/esm2_t30_150M_UR50D) | 30 | 150M |
32
- | [esm2_t12_35M_UR50D](https://huggingface.co/nvidia/esm2_t12_35M_UR50D) | 12 | 35M |
33
- | [esm2_t6_8M_UR50D](https://huggingface.co/nvidia/esm2_t6_8M_UR50D) | 6 | 8M |
 
1
+ ______________________________________________________________________
2
+
3
+ library_name: transformers
4
  license: mit
5
  widget:
6
+
7
+ - text: "MQIFVKTLTGKTITLEVEPS<mask>TIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG"
8
+
9
+ ______________________________________________________________________
10
 
11
  ## ESM-2 (TransformerEngine-optimized)
12
 
 
27
  Several ESM-2 checkpoints are available in the Hub with varying sizes. Larger sizes generally have
28
  somewhat better accuracy, but require much more memory and time to train:
29
 
30
+ | Checkpoint name | Num layers | Num parameters |
31
+ | ------------------------------------------------------------------------ | ---------- | -------------- |
32
+ | [esm2_t48_15B_UR50D](https://huggingface.co/nvidia/esm2_t48_15B_UR50D) | 48 | 15B |
33
+ | [esm2_t36_3B_UR50D](https://huggingface.co/nvidia/esm2_t36_3B_UR50D) | 36 | 3B |
34
+ | [esm2_t33_650M_UR50D](https://huggingface.co/nvidia/esm2_t33_650M_UR50D) | 33 | 650M |
35
+ | [esm2_t30_150M_UR50D](https://huggingface.co/nvidia/esm2_t30_150M_UR50D) | 30 | 150M |
36
+ | [esm2_t12_35M_UR50D](https://huggingface.co/nvidia/esm2_t12_35M_UR50D) | 12 | 35M |
37
+ | [esm2_t6_8M_UR50D](https://huggingface.co/nvidia/esm2_t6_8M_UR50D) | 6 | 8M |
config.json CHANGED
@@ -23,6 +23,7 @@
23
  "layer_norm_eps": 1e-05,
24
  "mask_token_id": 32,
25
  "max_position_embeddings": 1026,
 
26
  "micro_batch_size": null,
27
  "model_type": "nv_esm",
28
  "num_attention_heads": 20,
@@ -32,8 +33,8 @@
32
  "qkv_weight_interleaved": true,
33
  "token_dropout": true,
34
  "torch_dtype": "float32",
35
- "transformers_version": "4.53.0.dev0",
36
  "use_cache": true,
37
  "vocab_list": null,
38
  "vocab_size": 33
39
- }
 
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,
 
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 CHANGED
@@ -2,6 +2,7 @@
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
  #
6
  # Licensed under the Apache License, Version 2.0 (the "License");
7
  # you may not use this file except in compliance with the License.
@@ -15,13 +16,17 @@
15
  # See the License for the specific language governing permissions and
16
  # limitations under the License.
17
 
18
- """TransformerEngine-optimized ESM model. Adapted from `modeling_esm.py` in
19
- huggingface/transformers."""
 
 
 
20
 
21
  from typing import Optional, Tuple, Union
22
 
 
 
23
  import torch
24
- import torch.utils.checkpoint
25
  import transformer_engine.pytorch
26
  from torch import nn
27
  from torch.nn import CrossEntropyLoss
@@ -37,10 +42,13 @@ from transformers.models.esm.configuration_esm import EsmConfig
37
  from transformers.models.esm.modeling_esm import EsmEmbeddings, EsmPooler
38
  from transformers.utils import logging
39
 
 
40
  logger = logging.get_logger(__name__)
41
 
42
 
43
  class NVEsmConfig(EsmConfig):
 
 
44
  model_type: str = "nv_esm"
45
 
46
  def __init__(
@@ -50,6 +58,7 @@ class NVEsmConfig(EsmConfig):
50
  attn_input_format: str = "bshd",
51
  fuse_qkv_params: bool = True,
52
  micro_batch_size: Optional[int] = None,
 
53
  **kwargs,
54
  ):
55
  """Initialize the NVEsmConfig with additional TE-related config options.
@@ -74,9 +83,11 @@ class NVEsmConfig(EsmConfig):
74
  micro_batch_size: The micro batch size to use for the attention. This is needed for
75
  JIT Warmup, a technique where jit fused functions are warmed up before training to
76
  ensure same kernels are used for forward propogation and activation recompute phase.
 
 
 
77
  **kwargs: Additional config options to pass to EsmConfig.
78
  """
79
-
80
  super().__init__(**kwargs)
81
  # Additional TE-related config options.
82
  self.qkv_weight_interleaved = qkv_weight_interleaved
@@ -84,10 +95,18 @@ class NVEsmConfig(EsmConfig):
84
  self.attn_input_format = attn_input_format
85
  self.fuse_qkv_params = fuse_qkv_params
86
  self.micro_batch_size = micro_batch_size
 
87
 
88
 
89
  class NVEsmEncoder(nn.Module):
90
- def __init__(self, config):
 
 
 
 
 
 
 
91
  super().__init__()
92
  self.config = config
93
  self.layers = nn.ModuleList(
@@ -105,39 +124,41 @@ class NVEsmEncoder(nn.Module):
105
  self_attn_mask_type="padding",
106
  activation=config.encoder_activation,
107
  attn_input_format=config.attn_input_format,
108
- seq_length=config.max_length,
109
  micro_batch_size=config.micro_batch_size,
110
  num_gqa_groups=config.num_attention_heads,
111
  fuse_qkv_params=config.fuse_qkv_params,
112
  params_dtype=config.torch_dtype,
 
113
  )
114
  for i in range(config.num_hidden_layers)
115
  ]
116
  )
117
- self.emb_layer_norm_after = transformer_engine.pytorch.LayerNorm(
118
- config.hidden_size, eps=config.layer_norm_eps
119
- )
120
  if config.position_embedding_type == "rotary":
121
- self.rotary_embeddings = RotaryPositionEmbedding(
122
- config.hidden_size // config.num_attention_heads
123
- )
124
- self.te_rope_emb = self.rotary_embeddings(
125
- max_seq_len=config.max_position_embeddings
126
- ).cuda()
127
  else:
128
  self.te_rope_emb = None
129
 
130
  def forward(
131
  self,
132
- hidden_states,
133
- attention_mask=None,
134
- output_hidden_states=False,
135
  ):
 
 
 
 
 
 
 
136
  all_hidden_states = () if output_hidden_states else None
137
 
138
  for layer_module in self.layers:
139
  if output_hidden_states:
140
- all_hidden_states = all_hidden_states + (hidden_states,)
141
 
142
  hidden_states = layer_module(
143
  hidden_states,
@@ -148,7 +169,7 @@ class NVEsmEncoder(nn.Module):
148
  hidden_states = self.emb_layer_norm_after(hidden_states)
149
 
150
  if output_hidden_states:
151
- all_hidden_states = all_hidden_states + (hidden_states,)
152
 
153
  return BaseModelOutput(
154
  last_hidden_state=hidden_states,
@@ -157,18 +178,42 @@ class NVEsmEncoder(nn.Module):
157
 
158
 
159
  class NVEsmPreTrainedModel(PreTrainedModel):
160
- """
161
- An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
162
- models.
163
- """
164
 
165
  config_class = NVEsmConfig
166
  base_model_prefix = "esm"
167
  supports_gradient_checkpointing = False
168
- _no_split_modules = [
169
  "TransformerLayer",
170
  "EsmEmbeddings",
171
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
 
174
  class NVEsmModel(NVEsmPreTrainedModel):
@@ -177,7 +222,13 @@ class NVEsmModel(NVEsmPreTrainedModel):
177
  This model uses NVDIA's TransformerEngine to optimize attention layer training and inference.
178
  """
179
 
180
- def __init__(self, config, add_pooling_layer=True):
 
 
 
 
 
 
181
  super().__init__(config)
182
  self.config = config
183
 
@@ -189,9 +240,15 @@ class NVEsmModel(NVEsmPreTrainedModel):
189
  self.post_init()
190
 
191
  def get_input_embeddings(self):
 
192
  return self.embeddings.word_embeddings
193
 
194
- def set_input_embeddings(self, value):
 
 
 
 
 
195
  self.embeddings.word_embeddings = value
196
 
197
  def forward(
@@ -203,6 +260,19 @@ class NVEsmModel(NVEsmPreTrainedModel):
203
  inputs_embeds: Optional[torch.Tensor] = None,
204
  output_hidden_states: Optional[bool] = None,
205
  ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  r"""
207
  encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
208
  Sequence of hidden-states at the output of the last layer of the encoder. Used in the
@@ -219,15 +289,11 @@ class NVEsmModel(NVEsmPreTrainedModel):
219
  boolean mask where 1s are masked and 0s are not masked.
220
  """
221
  output_hidden_states = (
222
- output_hidden_states
223
- if output_hidden_states is not None
224
- else self.config.output_hidden_states
225
  )
226
 
227
  if input_ids is not None and inputs_embeds is not None:
228
- raise ValueError(
229
- "You cannot specify both input_ids and inputs_embeds at the same time"
230
- )
231
  elif input_ids is not None:
232
  self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
233
  input_shape = input_ids.size()
@@ -244,9 +310,7 @@ class NVEsmModel(NVEsmPreTrainedModel):
244
 
245
  # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
246
  # ourselves in which case we just need to make it broadcastable to all heads.
247
- extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
248
- attention_mask, input_shape
249
- )
250
 
251
  # TE expects a boolean attention mask, where 1s are masked and 0s are not masked
252
  extended_attention_mask = extended_attention_mask < -1
@@ -270,9 +334,7 @@ class NVEsmModel(NVEsmPreTrainedModel):
270
  output_hidden_states=output_hidden_states,
271
  )
272
  sequence_output = encoder_outputs[0]
273
- pooled_output = (
274
- self.pooler(sequence_output) if self.pooler is not None else None
275
- )
276
 
277
  return BaseModelOutputWithPooling(
278
  last_hidden_state=sequence_output,
@@ -282,9 +344,16 @@ class NVEsmModel(NVEsmPreTrainedModel):
282
 
283
 
284
  class NVEsmForMaskedLM(NVEsmPreTrainedModel):
285
- _tied_weights_keys = ["lm_head.decoder.weight"]
 
 
286
 
287
- def __init__(self, config):
 
 
 
 
 
288
  super().__init__(config)
289
 
290
  if config.is_decoder:
@@ -300,9 +369,11 @@ class NVEsmForMaskedLM(NVEsmPreTrainedModel):
300
  self.post_init()
301
 
302
  def get_output_embeddings(self):
 
303
  return self.lm_head.decoder
304
 
305
  def set_output_embeddings(self, new_embeddings):
 
306
  self.lm_head.decoder = new_embeddings
307
 
308
  def forward(
@@ -314,6 +385,19 @@ class NVEsmForMaskedLM(NVEsmPreTrainedModel):
314
  labels: Optional[torch.LongTensor] = None,
315
  output_hidden_states: Optional[bool] = None,
316
  ) -> Union[Tuple, MaskedLMOutput]:
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  r"""
318
  labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
319
  Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
@@ -337,9 +421,7 @@ class NVEsmForMaskedLM(NVEsmPreTrainedModel):
337
  loss_fct = CrossEntropyLoss()
338
 
339
  labels = labels.to(prediction_scores.device)
340
- masked_lm_loss = loss_fct(
341
- prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
342
- )
343
 
344
  return MaskedLMOutput(
345
  loss=masked_lm_loss,
@@ -347,18 +429,30 @@ class NVEsmForMaskedLM(NVEsmPreTrainedModel):
347
  hidden_states=outputs.hidden_states,
348
  )
349
 
350
- def predict_contacts(self, tokens, attention_mask):
 
 
 
 
 
 
 
 
 
351
  return self.esm.predict_contacts(tokens, attention_mask=attention_mask)
352
 
353
 
354
  class NVEsmLMHead(nn.Module):
355
  """ESM Head for masked language modeling using TransformerEngine."""
356
 
357
- def __init__(self, config):
 
 
 
 
 
358
  super().__init__()
359
- self.dense = transformer_engine.pytorch.Linear(
360
- config.hidden_size, config.hidden_size
361
- )
362
 
363
  self.decoder = transformer_engine.pytorch.LayerNormLinear(
364
  config.hidden_size,
@@ -368,6 +462,12 @@ class NVEsmLMHead(nn.Module):
368
  )
369
 
370
  def forward(self, features, **kwargs):
 
 
 
 
 
 
371
  x = self.dense(features)
372
  x = torch.nn.functional.gelu(x)
373
  x = self.decoder(x)
 
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.
 
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
 
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__(
 
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.
 
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
 
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(
 
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,
 
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,
 
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):
 
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
 
 
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(
 
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
 
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()
 
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
 
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,
 
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:
 
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(
 
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, ...,
 
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,
 
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,
 
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)