revanth1996 commited on
Commit
74e6299
1 Parent(s): f9b9083

Create modeling_hf_nomic_bert.py

Browse files
Files changed (1) hide show
  1. modeling_hf_nomic_bert.py +1218 -0
modeling_hf_nomic_bert.py ADDED
@@ -0,0 +1,1218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, Tri Dao.
2
+ # This BERT implementation is based on our MLPerf 2.0 and MLPerf 2.1 BERT implementation.
3
+ # https://github.com/mlcommons/training_results_v2.0/blob/main/HazyResearch/benchmarks/bert/implementations/pytorch/modeling.py
4
+ # https://github.com/mlcommons/training_results_v2.1/blob/main/Azure-HazyResearch/benchmarks/bert/implementations/ND96amsr_A100_v4/modeling.py
5
+
6
+ import logging
7
+
8
+ # Inspired by https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py
9
+ import os
10
+ import re
11
+ from collections import OrderedDict
12
+ from functools import partial
13
+ from typing import List, Optional, Tuple, Union
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from einops import rearrange, repeat
19
+ from safetensors.torch import load_file as safe_load_file
20
+ from transformers import GPT2Config, PreTrainedModel
21
+ from transformers.models.bert.modeling_bert import (
22
+ BaseModelOutputWithPoolingAndCrossAttentions,
23
+ MaskedLMOutput,
24
+ SequenceClassifierOutput,
25
+ )
26
+ from transformers.utils import SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, WEIGHTS_INDEX_NAME, WEIGHTS_NAME
27
+ from transformers.utils.hub import cached_file, get_checkpoint_shard_files
28
+
29
+ from .configuration_hf_nomic_bert import NomicBertConfig
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ # adapted from flash attention, added safe serialization option for hf models
35
+ def state_dict_from_pretrained(model_name, safe_serialization=False, device=None, dtype=None):
36
+ # If not fp32, then we don't want to load directly to the GPU
37
+ mapped_device = "cpu" if dtype not in [torch.float32, None] else device
38
+ is_sharded = False
39
+ load_safe = False
40
+ resolved_archive_file = None
41
+
42
+ weights_path = os.path.join(model_name, WEIGHTS_NAME)
43
+ weights_index_path = os.path.join(model_name, WEIGHTS_INDEX_NAME)
44
+ safe_weights_path = os.path.join(model_name, SAFE_WEIGHTS_NAME)
45
+ safe_weights_index_path = os.path.join(model_name, SAFE_WEIGHTS_INDEX_NAME)
46
+
47
+ if os.path.isfile(weights_path):
48
+ resolved_archive_file = cached_file(model_name, WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False)
49
+ elif os.path.isfile(weights_index_path):
50
+ resolved_archive_file = cached_file(model_name, WEIGHTS_INDEX_NAME, _raise_exceptions_for_missing_entries=False)
51
+ is_sharded = True
52
+ elif os.path.isfile(safe_weights_path):
53
+ resolved_archive_file = cached_file(model_name, SAFE_WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False)
54
+ load_safe = True
55
+ elif os.path.isfile(safe_weights_index_path):
56
+ resolved_archive_file = cached_file(
57
+ model_name, SAFE_WEIGHTS_INDEX_NAME, _raise_exceptions_for_missing_entries=False
58
+ )
59
+ is_sharded = True
60
+ load_safe = True
61
+ else: # Try loading from HF hub instead of from local files
62
+ weight_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME
63
+ resolved_archive_file = cached_file(model_name, weight_name, _raise_exceptions_for_missing_entries=False)
64
+ if resolved_archive_file is None:
65
+ weight_index = WEIGHTS_INDEX_NAME if not safe_serialization else SAFE_WEIGHTS_INDEX_NAME
66
+ resolved_archive_file = cached_file(model_name, weight_index, _raise_exceptions_for_missing_entries=False)
67
+ if resolved_archive_file is not None:
68
+ is_sharded = True
69
+
70
+ load_safe = safe_serialization
71
+
72
+ if resolved_archive_file is None:
73
+ raise EnvironmentError(f"Model name {model_name} was not found.")
74
+
75
+ if load_safe:
76
+ loader = partial(safe_load_file, device=mapped_device)
77
+ else:
78
+ loader = partial(torch.load, map_location=mapped_device)
79
+
80
+ if is_sharded:
81
+ # resolved_archive_file becomes a list of files that point to the different
82
+ # checkpoint shards in this case.
83
+ resolved_archive_file, sharded_metadata = get_checkpoint_shard_files(model_name, resolved_archive_file)
84
+ state_dict = {}
85
+ for sharded_file in resolved_archive_file:
86
+ state_dict.update(loader(sharded_file))
87
+ else:
88
+ state_dict = loader(resolved_archive_file)
89
+ # Convert dtype before moving to GPU to save memory
90
+ if dtype is not None:
91
+ state_dict = {k: v.to(dtype=dtype) for k, v in state_dict.items()}
92
+ state_dict = {k: v.to(device=device) for k, v in state_dict.items()}
93
+ return state_dict
94
+
95
+
96
+ def filter_shapes(state_dict, model):
97
+ """
98
+ Filters the state dict to match the current model shape.
99
+ """
100
+ filtered_state_dict = {}
101
+ for key, value in state_dict.items():
102
+ if key in model.state_dict():
103
+ if value.shape == model.state_dict()[key].shape:
104
+ filtered_state_dict[key] = value
105
+ return filtered_state_dict
106
+
107
+
108
+ def remap_bert_state_dict(state_dict, config, remove_bert=False, remove_cls_weights=False, add_pooling_layer=False):
109
+ """
110
+ Map the state_dict of a Huggingface BERT model to be flash_attn compatible.
111
+ """
112
+
113
+ def add_bert_prefix(key):
114
+ # prepend bert. to the key
115
+ if key.startswith("bert.") or key.startswith("cls."):
116
+ return key
117
+ return f"bert.{key}"
118
+
119
+ state_dict = OrderedDict((add_bert_prefix(k), v) for k, v in state_dict.items())
120
+
121
+ # LayerNorm
122
+ def key_mapping_ln_gamma_beta(key):
123
+ key = re.sub(r"LayerNorm.gamma$", "LayerNorm.weight", key)
124
+ key = re.sub(r"LayerNorm.beta$", "LayerNorm.bias", key)
125
+ return key
126
+
127
+ state_dict = OrderedDict((key_mapping_ln_gamma_beta(k), v) for k, v in state_dict.items())
128
+
129
+ # Layers
130
+ def key_mapping_layers(key):
131
+ return re.sub(r"^bert.encoder.layer\.", "bert.encoder.layers.", key)
132
+
133
+ state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items())
134
+
135
+ # LayerNorm
136
+ def key_mapping_ln(key):
137
+ key = re.sub(r"^bert.embeddings.LayerNorm.", "bert.emb_ln.", key)
138
+ key = re.sub(
139
+ r"^bert.encoder.layers.(\d+).attention.output.LayerNorm.(weight|bias)",
140
+ r"bert.encoder.layers.\1.norm1.\2",
141
+ key,
142
+ )
143
+ key = re.sub(
144
+ r"^bert.encoder.layers.(\d+).output.LayerNorm.(weight|bias)",
145
+ r"bert.encoder.layers.\1.norm2.\2",
146
+ key,
147
+ )
148
+ key = re.sub(
149
+ r"^cls.predictions.transform.LayerNorm.(weight|bias)",
150
+ r"cls.predictions.transform.layer_norm.\1",
151
+ key,
152
+ )
153
+ return key
154
+
155
+ state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items())
156
+
157
+ # MLP
158
+ def key_mapping_mlp(key):
159
+ key = re.sub(
160
+ r"^bert.encoder.layers.(\d+).intermediate.dense.(weight|bias)",
161
+ r"bert.encoder.layers.\1.mlp.fc1.\2",
162
+ key,
163
+ )
164
+ key = re.sub(
165
+ r"^bert.encoder.layers.(\d+).output.dense.(weight|bias)",
166
+ r"bert.encoder.layers.\1.mlp.fc2.\2",
167
+ key,
168
+ )
169
+ return key
170
+
171
+ state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items())
172
+
173
+ # Attention
174
+ last_layer_subset = getattr(config, "last_layer_subset", False)
175
+ for d in range(config.num_hidden_layers):
176
+ if f"bert.encoder.layers.{d}.attention.self.query.weight" not in state_dict:
177
+ continue
178
+ Wq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.weight")
179
+ Wk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.weight")
180
+ Wv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.weight")
181
+ bq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.bias")
182
+ bk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.bias")
183
+ bv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.bias")
184
+ if not (last_layer_subset and d == config.num_hidden_layers - 1):
185
+ state_dict[f"bert.encoder.layers.{d}.attn.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0)
186
+ state_dict[f"bert.encoder.layers.{d}.attn.Wqkv.bias"] = torch.cat([bq, bk, bv], dim=0)
187
+ else:
188
+ state_dict[f"bert.encoder.layers.{d}.attn.Wq.weight"] = Wq
189
+ state_dict[f"bert.encoder.layers.{d}.attn.Wkv.weight"] = torch.cat([Wk, Wv], dim=0)
190
+ state_dict[f"bert.encoder.layers.{d}.attn.Wq.bias"] = bq
191
+ state_dict[f"bert.encoder.layers.{d}.attn.Wkv.bias"] = torch.cat([bk, bv], dim=0)
192
+
193
+ def key_mapping_attn(key):
194
+ return re.sub(
195
+ r"^bert.encoder.layers.(\d+).attention.output.dense.(weight|bias)",
196
+ r"bert.encoder.layers.\1.attn.out_proj.\2",
197
+ key,
198
+ )
199
+
200
+ state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items())
201
+
202
+ def key_mapping_decoder_bias(key):
203
+ return re.sub(r"^cls.predictions.bias", "cls.predictions.decoder.bias", key)
204
+
205
+ # remove nsp weights, we don't use
206
+ state_dict.pop("cls.seq_relationship.weight", None)
207
+ state_dict.pop("cls.seq_relationship.bias", None)
208
+ state_dict.pop("bert.embeddings.position_ids", None)
209
+
210
+ state_dict = OrderedDict((key_mapping_decoder_bias(k), v) for k, v in state_dict.items())
211
+
212
+ if remove_cls_weights:
213
+ cls_weights = [
214
+ "cls.predictions.decoder.bias",
215
+ "cls.predictions.transform.dense.weight",
216
+ "cls.predictions.transform.dense.bias",
217
+ "cls.predictions.transform.layer_norm.weight",
218
+ "cls.predictions.transform.layer_norm.bias",
219
+ "cls.predictions.decoder.weight",
220
+ ]
221
+ for weight in cls_weights:
222
+ state_dict.pop(weight, None)
223
+
224
+ # Word embedding
225
+ pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1)
226
+ if pad_vocab_size_multiple > 1:
227
+ word_embeddings = state_dict["bert.embeddings.word_embeddings.weight"]
228
+ state_dict["bert.embeddings.word_embeddings.weight"] = F.pad(
229
+ word_embeddings, (0, 0, 0, config.vocab_size - word_embeddings.shape[0])
230
+ )
231
+ if not remove_cls_weights:
232
+ decoder_weight = state_dict["cls.predictions.decoder.weight"]
233
+ state_dict["cls.predictions.decoder.weight"] = F.pad(
234
+ decoder_weight, (0, 0, 0, config.vocab_size - decoder_weight.shape[0])
235
+ )
236
+ # If the vocab was padded, we want to set the decoder bias for those padded indices to be
237
+ # strongly negative (i.e. the decoder shouldn't predict those indices).
238
+ # TD [2022-05-09]: I don't think it affects the MLPerf training.
239
+ if "cls.predictions.decoder.bias" in state_dict:
240
+ decoder_bias = state_dict["cls.predictions.decoder.bias"]
241
+ state_dict["cls.predictions.decoder.bias"] = F.pad(
242
+ decoder_bias, (0, config.vocab_size - decoder_bias.shape[0]), value=-100.0
243
+ )
244
+
245
+ if add_pooling_layer is False:
246
+ pooler_weights = [
247
+ "bert.pooler.dense.weight",
248
+ "bert.pooler.dense.bias",
249
+ ]
250
+ for key in pooler_weights:
251
+ state_dict.pop(key, None)
252
+
253
+ if remove_bert:
254
+
255
+ def remove_bert_prefix(key):
256
+ key = re.sub(r"^bert.", "", key)
257
+ return key
258
+
259
+ state_dict = OrderedDict((remove_bert_prefix(k), v) for k, v in state_dict.items())
260
+
261
+ return state_dict
262
+
263
+
264
+ class NomicBertPreTrainedModel(PreTrainedModel):
265
+ """An abstract class to handle weights initialization and
266
+ a simple interface for dowloading and loading pretrained models.
267
+ """
268
+
269
+ config_class = NomicBertConfig
270
+ base_model_prefix = "model"
271
+ supports_gradient_checkpointing = True
272
+ _no_split_modules = ["Block"]
273
+ _skip_keys_device_placement = "past_key_values"
274
+
275
+ def __init__(self, config, *inputs, **kwargs):
276
+ super().__init__(config)
277
+ if not isinstance(config, GPT2Config):
278
+ raise ValueError(
279
+ "Parameter config in `{}(config)` should be an instance of class `GPT2Config`. "
280
+ "To create a model from a Google pretrained model use "
281
+ "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format(
282
+ self.__class__.__name__, self.__class__.__name__
283
+ )
284
+ )
285
+ self.config = config
286
+
287
+ @classmethod
288
+ def from_pretrained(cls, model_name, config=None, *inputs, **kwargs):
289
+ """
290
+ Instantiate a NomicBertPreTrainedModel from a pre-trained model file or a pytorch state dict.
291
+ Download and cache the pre-trained model file if needed.
292
+ Params:
293
+ pretrained_model_name_or_path: either:
294
+ - a path or url to a pretrained model archive containing:
295
+ . `bert_config.json` a configuration file for the model
296
+ . `pytorch_model.bin` a PyTorch dump of a NomicBertForPretraining instance
297
+ - a path or url to a pretrained model archive containing:
298
+ . `bert_config.json` a configuration file for the model
299
+ . `model.chkpt` a TensorFlow checkpoint
300
+ *inputs, **kwargs: additional input for the specific NomicBert class
301
+ (ex: num_labels for NomicBertForSequenceClassification)
302
+ """
303
+ # Instantiate model.
304
+ if config is None:
305
+ config = cls.config_class.from_pretrained(model_name)
306
+ remove_cls = cls != NomicBertForPreTraining
307
+ remove_bert_prefix = cls != NomicBertForPreTraining
308
+ ignore_mismatched_shapes = kwargs.pop("ignore_mismatched_sizes", False)
309
+ num_labels = kwargs.pop("num_labels", None)
310
+ rotary_scaling_factor = kwargs.pop("rotary_scaling_factor", None)
311
+ if rotary_scaling_factor:
312
+ config.rotary_scaling_factor = rotary_scaling_factor
313
+
314
+ if config.n_positions <= 0 and config.rotary_emb_fraction > 0:
315
+ config.n_positions = 2048
316
+ if num_labels:
317
+ config.num_labels = num_labels
318
+
319
+ if "add_pooling_layer" in kwargs:
320
+ model = cls(config, *inputs, add_pooling_layer=kwargs.pop("add_pooling_layer"))
321
+ else:
322
+ if cls == NomicBertModel:
323
+ model = cls(config, *inputs, add_pooling_layer=False)
324
+ else:
325
+ model = cls(config, *inputs)
326
+ # TODO: fix this
327
+ # Assuming we know what we're doing when loading from disk
328
+ # Prob a bad assumption but i'm tired and want to train this asap
329
+ if os.path.exists(model_name):
330
+ model_path = f"{model_name}/pytorch_model.bin"
331
+ if os.path.exists(model_path):
332
+ state_dict = torch.load(f"{model_name}/pytorch_model.bin")
333
+ else:
334
+ model_path = f"{model_name}/model.safetensors"
335
+ if not os.path.exists(model_path):
336
+ raise ValueError(f"Model path {model_path} not found")
337
+ state_dict = safe_load_file(model_path)
338
+
339
+ if ignore_mismatched_shapes:
340
+ state_dict = filter_shapes(state_dict, model)
341
+ load_return = model.load_state_dict(state_dict, strict=False)
342
+ else:
343
+ # TODO: can probably check config class and see if we need to remap from a bert model
344
+ state_dict = state_dict_from_pretrained(model_name, safe_serialization=kwargs.get("safe_serialization", False))
345
+ state_dict = remap_bert_state_dict(
346
+ state_dict,
347
+ config,
348
+ remove_bert=remove_bert_prefix,
349
+ remove_cls_weights=remove_cls,
350
+ add_pooling_layer=getattr(config, "add_pooling_layer", False),
351
+ )
352
+ if ignore_mismatched_shapes:
353
+ state_dict = filter_shapes(state_dict, model)
354
+
355
+ load_return = model.load_state_dict(state_dict, strict=True)
356
+ logger.warning(load_return)
357
+ return model
358
+
359
+ def _set_gradient_checkpointing(self, module, value=False):
360
+ if isinstance(module, NomicBertEncoder):
361
+ module.gradient_checkpointing = value
362
+
363
+
364
+ # https://github.com/huggingface/transformers/blob/7032e0203262ebb2ebf55da8d2e01f873973e835/src/transformers/models/bert/modeling_bert.py#L748
365
+ def _init_weights(module, initializer_range=0.02):
366
+ if isinstance(module, nn.Linear):
367
+ nn.init.normal_(module.weight, std=initializer_range)
368
+ if module.bias is not None:
369
+ nn.init.zeros_(module.bias)
370
+ elif isinstance(module, nn.Embedding):
371
+ nn.init.normal_(module.weight, std=initializer_range)
372
+ if module.padding_idx is not None:
373
+ nn.init.zeros_(module.weight[module.padding_idx])
374
+
375
+
376
+ class NomicBertEmbeddings(nn.Module):
377
+ def __init__(self, config):
378
+ """
379
+ If max_position_embeddings <= 0, there's no position embeddings
380
+ If type_vocab_size <= 0, there's no token type embeddings
381
+ """
382
+ super().__init__()
383
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
384
+ self.max_position_embeddings = config.max_position_embeddings if config.rotary_emb_fraction <= 0 else 0
385
+ self.type_vocab_size = config.type_vocab_size
386
+ if self.max_position_embeddings > 0 and config.rotary_emb_fraction <= 0:
387
+ self.position_embeddings = nn.Embedding(
388
+ config.max_position_embeddings,
389
+ config.hidden_size,
390
+ )
391
+ if self.type_vocab_size > 0:
392
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
393
+
394
+ def forward(self, input_ids, position_ids=None, token_type_ids=None):
395
+ """
396
+ input_ids: (batch, seqlen)
397
+ position_ids: (batch, seqlen)
398
+ token_type_ids: (batch, seqlen)
399
+ """
400
+ batch_size, seqlen = input_ids.shape
401
+ embeddings = self.word_embeddings(input_ids)
402
+
403
+ if self.type_vocab_size > 0:
404
+ if token_type_ids is None:
405
+ token_type_ids = torch.zeros(seqlen, dtype=torch.long, device=input_ids.device)
406
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
407
+ embeddings = embeddings + token_type_embeddings
408
+
409
+ if self.max_position_embeddings > 0:
410
+ if position_ids is None:
411
+ position_ids = torch.arange(seqlen, dtype=torch.long, device=input_ids.device)
412
+ position_embeddings = self.position_embeddings(position_ids)
413
+ embeddings = embeddings + position_embeddings
414
+ return embeddings
415
+
416
+
417
+ class NomicBertMLP(nn.Module):
418
+ def __init__(
419
+ self,
420
+ in_features,
421
+ hidden_features=None,
422
+ out_features=None,
423
+ activation=F.gelu,
424
+ bias1=True,
425
+ bias2=True,
426
+ return_residual=False,
427
+ fused_bias_fc=False,
428
+ ):
429
+ super().__init__()
430
+ out_features = out_features if out_features is not None else in_features
431
+ hidden_features = hidden_features if hidden_features is not None else in_features * 4
432
+ self.return_residual = return_residual
433
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1)
434
+ approximate = "tanh" if activation in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"] else "none"
435
+ self.activation = nn.GELU(approximate=approximate) if activation == "gelu" else activation
436
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2)
437
+
438
+ def forward(self, x):
439
+ y = self.fc1(x)
440
+ y = self.activation(y)
441
+ y = self.fc2(y)
442
+ return y if not self.return_residual else (y, x)
443
+
444
+
445
+ class NomciBertGatedMLP(nn.Module):
446
+ def __init__(
447
+ self,
448
+ in_features,
449
+ hidden_features=None,
450
+ out_features=None,
451
+ activation=F.sigmoid,
452
+ bias1=True,
453
+ bias2=True,
454
+ multiple_of=256,
455
+ return_residual=False,
456
+ fused_bias_fc=True,
457
+ device=None,
458
+ dtype=None,
459
+ ):
460
+ super().__init__()
461
+ out_features = out_features if out_features is not None else in_features
462
+ hidden_features = hidden_features if hidden_features is not None else int(8 * in_features / 3)
463
+ hidden_features = (hidden_features + multiple_of - 1) // multiple_of * multiple_of
464
+ self.return_residual = return_residual
465
+
466
+ self.fc11 = nn.Linear(in_features, hidden_features, bias=bias1)
467
+ self.fc12 = nn.Linear(in_features, hidden_features, bias=bias1)
468
+ self.activation = activation
469
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2)
470
+
471
+ def forward(self, x):
472
+ y = self.fc11(x)
473
+ gate = self.fc12(x)
474
+ if self.activation == F.sigmoid: # Special case for GLU
475
+ y = F.glu(torch.cat([y, gate], dim=-1), dim=-1)
476
+ else:
477
+ y = y * self.activation(gate)
478
+ y = self.fc2(y)
479
+ return y if not self.return_residual else (y, x)
480
+
481
+
482
+ def rotate_half(x, interleaved=False):
483
+ if not interleaved:
484
+ x1, x2 = x.chunk(2, dim=-1)
485
+ return torch.cat((-x2, x1), dim=-1)
486
+ else:
487
+ x1, x2 = x[..., ::2], x[..., 1::2]
488
+ return rearrange(torch.stack((-x2, x1), dim=-1), "... d two -> ... (d two)", two=2)
489
+
490
+
491
+ def apply_rotary_emb(x, cos, sin, offset=0, interleaved=False):
492
+ """
493
+ x: (batch_size, seqlen, nheads, headdim)
494
+ cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2)
495
+ """
496
+ ro_dim = cos.shape[-1] * 2
497
+ assert ro_dim <= x.shape[-1]
498
+ cos, sin = (
499
+ cos[offset : offset + x.shape[1]],
500
+ sin[offset : offset + x.shape[1]],
501
+ )
502
+ cos = repeat(cos, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
503
+ sin = repeat(sin, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
504
+ return torch.cat(
505
+ [x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]],
506
+ dim=-1,
507
+ )
508
+
509
+
510
+ class NomicBertRotaryEmbedding(nn.Module):
511
+ def __init__(
512
+ self,
513
+ dim: int,
514
+ base=10000.0,
515
+ interleaved=False,
516
+ scale_base=None,
517
+ pos_idx_in_fp32=True,
518
+ device=None,
519
+ ):
520
+ """
521
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
522
+ of 1st half and 2nd half (GPT-NeoX style).
523
+ pos_idx_in_fp32: if True, the position indices [0.0, ..., seqlen - 1] are in fp32,
524
+ otherwise they might be in lower precision.
525
+ This option was added because previously (before 2023-07-02), when we construct
526
+ the position indices, we use the dtype of self.inv_freq. In most cases this would
527
+ be fp32, but if the model is trained in pure bf16 (not mixed precision), then
528
+ self.inv_freq would be bf16, and the position indices are also in bf16.
529
+ Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the
530
+ embeddings for some positions will coincide.
531
+ To maintain compatibility with models previously trained in pure bf16,
532
+ we add this option.
533
+ """
534
+ super().__init__()
535
+ self.dim = dim
536
+ self.base = float(base)
537
+ self.pos_idx_in_fp32 = pos_idx_in_fp32
538
+ # Generate and save the inverse frequency buffer (non trainable)
539
+ inv_freq = self._compute_inv_freq(device)
540
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
541
+ self.interleaved = interleaved
542
+ self.scale_base = scale_base
543
+ scale = (
544
+ (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)
545
+ if scale_base is not None
546
+ else None
547
+ )
548
+ self.register_buffer("scale", scale, persistent=False)
549
+
550
+ self._seq_len_cached = 0
551
+ self._cos_cached = None
552
+ self._sin_cached = None
553
+ self._cos_k_cached = None
554
+ self._sin_k_cached = None
555
+
556
+ def _compute_inv_freq(self, device=None):
557
+ return 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
558
+
559
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
560
+ # Reset the tables if the sequence length has changed,
561
+ # if we're on a new device (possibly due to tracing for instance),
562
+ # or if we're switching from inference mode to training
563
+ if (
564
+ seqlen > self._seq_len_cached
565
+ or self._cos_cached is None
566
+ or self._cos_cached.device != device
567
+ or self._cos_cached.dtype != dtype
568
+ or (self.training and self._cos_cached.is_inference())
569
+ ):
570
+ self._seq_len_cached = seqlen
571
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
572
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
573
+ # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
574
+ if self.pos_idx_in_fp32:
575
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
576
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
577
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
578
+ # cos & sin output to change significantly.
579
+ # We want to recompute self.inv_freq if it was not loaded in fp32
580
+ if self.inv_freq.dtype != torch.float32:
581
+ inv_freq = self._compute_inv_freq(device=device)
582
+ else:
583
+ inv_freq = self.inv_freq
584
+ else:
585
+ t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
586
+ inv_freq = self.inv_freq
587
+ # Don't do einsum, it converts fp32 to fp16 under AMP
588
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
589
+ freqs = torch.outer(t, inv_freq)
590
+ self._cos_cached = torch.cos(freqs).to(dtype)
591
+ self._sin_cached = torch.sin(freqs).to(dtype)
592
+
593
+ def forward(
594
+ self,
595
+ qkv: torch.Tensor,
596
+ kv: Optional[torch.Tensor] = None,
597
+ seqlen_offset: Union[int, torch.Tensor] = 0,
598
+ max_seqlen: Optional[int] = None,
599
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
600
+ """
601
+ qkv: (batch, seqlen, 3, nheads, headdim) if kv is none,
602
+ else it's just q of shape (batch, seqlen, nheads, headdim)
603
+ kv: (batch, seqlen, 2, nheads, headdim)
604
+ seqlen_offset: (batch_size,) or int. Each sequence in x is shifted by this amount.
605
+ Most commonly used in inference when we have KV cache.
606
+ If it's a tensor of shape (batch_size,), then to update the cos / sin cache, one
607
+ should pass in max_seqlen, which will update the cos / sin cache up to that length.
608
+ Apply rotary embedding *inplace* to qkv and / or kv.
609
+ """
610
+ seqlen = qkv.shape[1]
611
+ if seqlen > self._seq_len_cached:
612
+ self._update_cos_sin_cache(seqlen, device=qkv.device, dtype=qkv.dtype)
613
+ elif max_seqlen is not None:
614
+ self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
615
+ elif isinstance(seqlen_offset, int):
616
+ self._update_cos_sin_cache(seqlen + seqlen_offset, device=qkv.device, dtype=qkv.dtype)
617
+
618
+ q_rot = apply_rotary_emb(qkv[:, :, 0], self._cos_cached, self._sin_cached, seqlen_offset, self.interleaved)
619
+ k_rot = apply_rotary_emb(qkv[:, :, 1], self._cos_cached, self._sin_cached, seqlen_offset, self.interleaved)
620
+ return torch.stack((q_rot, k_rot, qkv[:, :, 2]), dim=2)
621
+
622
+
623
+ class NomicBertDynamicNTKRotaryEmbedding(NomicBertRotaryEmbedding):
624
+ def __init__(self, rotary_scaling_factor, max_position_embeddings, **kwargs):
625
+ super().__init__(**kwargs)
626
+ self.rotary_scaling_factor = rotary_scaling_factor
627
+ self.max_position_embeddings = max_position_embeddings
628
+
629
+ def _compute_inv_freq(self, base=None, device=None):
630
+ if base is None:
631
+ base = self.base
632
+ return 1.0 / (base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
633
+
634
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
635
+ # Reset the tables if the sequence length has changed,
636
+ # if we're on a new device (possibly due to tracing for instance),
637
+ # or if we're switching from inference mode to training
638
+ if seqlen > self.max_position_embeddings:
639
+ base = self.base * (
640
+ (self.rotary_scaling_factor * seqlen / self.max_position_embeddings) - (self.rotary_scaling_factor - 1)
641
+ ) ** (self.dim / (self.dim - 2))
642
+ inv_freq = self._compute_inv_freq(base=base, device=device)
643
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
644
+
645
+ if (
646
+ seqlen > self._seq_len_cached
647
+ or self._cos_cached is None
648
+ or self._cos_cached.device != device
649
+ or self._cos_cached.dtype != dtype
650
+ or (self.training and self._cos_cached.is_inference())
651
+ ):
652
+ self._seq_len_cached = seqlen
653
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
654
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
655
+ # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
656
+ if self.pos_idx_in_fp32:
657
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
658
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
659
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
660
+ # cos & sin output to change significantly.
661
+ # We want to recompute self.inv_freq if it was not loaded in fp32
662
+ if self.inv_freq.dtype != torch.float32:
663
+ if seqlen > self.max_position_embeddings:
664
+ base = self.base * (
665
+ (self.scaling_factor * seqlen / self.max_position_embeddings) - (self.scaling_factor - 1)
666
+ ) ** (self.dim / (self.dim - 2))
667
+ else:
668
+ base = self.base
669
+ inv_freq = self._compute_inv_freq(device=device, base=base)
670
+ else:
671
+ inv_freq = self.inv_freq
672
+ else:
673
+ t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
674
+ inv_freq = self.inv_freq
675
+ # Don't do einsum, it converts fp32 to fp16 under AMP
676
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
677
+ freqs = torch.outer(t, inv_freq)
678
+ if self.scale is None:
679
+ self._cos_cached = torch.cos(freqs).to(dtype)
680
+ self._sin_cached = torch.sin(freqs).to(dtype)
681
+ else:
682
+ power = (
683
+ torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device) - seqlen // 2
684
+ ) / self.scale_base
685
+ scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
686
+ # We want the multiplication by scale to happen in fp32
687
+ self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
688
+ self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
689
+ self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
690
+ self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
691
+
692
+
693
+ class NomicBertAttention(nn.Module):
694
+ """Multi-head self-attention and cross-attention"""
695
+
696
+ def __init__(
697
+ self,
698
+ config,
699
+ ) -> None:
700
+ """
701
+ num_heads_kv: can be used to toggle MQA / GQA. If None, use num_heads.
702
+ return_residual: whether to return the input x along with the output. This is for
703
+ performance reason: for post-norm architecture, returning the input allows us
704
+ to fuse the backward of nn.Linear with the residual connection.
705
+ """
706
+ super().__init__()
707
+ self.embed_dim = config.n_embd
708
+ self.use_flash_attn = config.use_flash_attn
709
+ self.fused_bias_fc = config.fused_bias_fc
710
+
711
+ self.num_heads = config.n_head
712
+ self.num_heads_kv = config.num_heads_kv if getattr(config, "num_heads_kv", None) is not None else self.num_heads
713
+ assert self.embed_dim % self.num_heads == 0, "embed_dim must be divisible by num_heads"
714
+ self.head_dim = self.embed_dim // self.num_heads
715
+ # we don't really support mqa / gqa for now
716
+ qkv_dim = self.head_dim * (self.num_heads + 2 * self.num_heads_kv)
717
+
718
+ self.register_buffer(
719
+ "norm_factor",
720
+ torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32)).to(torch.get_default_dtype()),
721
+ persistent=False,
722
+ )
723
+
724
+ self.rotary_emb_dim = self.head_dim * config.rotary_emb_fraction
725
+ if self.rotary_emb_dim > 0:
726
+ if config.rotary_scaling_factor:
727
+ self.rotary_emb = NomicBertDynamicNTKRotaryEmbedding(
728
+ dim=self.rotary_emb_dim,
729
+ base=config.rotary_emb_base,
730
+ scale_base=config.rotary_emb_scale_base,
731
+ interleaved=config.rotary_emb_interleaved,
732
+ rotary_scaling_factor=config.rotary_scaling_factor,
733
+ max_position_embeddings=config.max_trained_positions,
734
+ )
735
+ else:
736
+ self.rotary_emb = NomicBertRotaryEmbedding(
737
+ dim=self.rotary_emb_dim,
738
+ base=config.rotary_emb_base,
739
+ scale_base=config.rotary_emb_scale_base,
740
+ interleaved=config.rotary_emb_interleaved,
741
+ )
742
+ # bug in xformers: https://github.com/facebookresearch/xformers/issues/841
743
+ # uses the head dimension instead of the sequence dimension
744
+ self.rotary_head_dim = getattr(config, "rotary_head_dim", False)
745
+
746
+ self.Wqkv = nn.Linear(self.embed_dim, qkv_dim, bias=config.qkv_proj_bias)
747
+
748
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.qkv_proj_bias)
749
+ self.causal = config.causal
750
+ self.drop = nn.Dropout(config.attn_pdrop)
751
+
752
+ def forward(
753
+ self,
754
+ hidden_states: torch.Tensor,
755
+ attention_mask: Optional[torch.Tensor] = None,
756
+ position_ids: Optional[torch.LongTensor] = None,
757
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
758
+ output_attentions: bool = False,
759
+ use_cache: bool = False,
760
+ is_padded_inputs: Optional[bool] = True,
761
+ cu_seqlens: Optional[torch.Tensor] = None,
762
+ max_seq_len: Optional[int] = None,
763
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
764
+
765
+ has_layer_past = past_key_value is not None
766
+
767
+ if has_layer_past:
768
+ past_key_value = past_key_value[0]
769
+ past_len = past_key_value[1]
770
+ else:
771
+ past_len = 0
772
+
773
+ qkv = self.Wqkv(hidden_states)
774
+ qkv = rearrange(qkv, "... (three h d) -> ... three h d", three=3, d=self.head_dim)
775
+
776
+ past_key_value = (past_key_value, past_len + qkv.size(1)) if use_cache else None
777
+
778
+ if self.rotary_emb_dim > 0:
779
+ if self.rotary_head_dim:
780
+ qkv = rearrange(qkv, "b s three h d -> b h three s d")
781
+ qkv = self.rotary_emb(qkv, seqlen_offset=past_len)
782
+
783
+ if self.rotary_head_dim:
784
+ qkv = rearrange(qkv, "b h three s d -> b s three h d")
785
+
786
+ query, key, value = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
787
+
788
+ query = query.permute(0, 2, 1, 3)
789
+ key = key.permute(0, 2, 1, 3)
790
+ value = value.permute(0, 2, 1, 3)
791
+
792
+ attention_scores = torch.matmul(query, key.transpose(-1, -2)) / self.norm_factor
793
+ if attention_mask is not None:
794
+ attention_scores = attention_scores + attention_mask
795
+
796
+ attentions_probs = F.softmax(attention_scores, dim=-1)
797
+ attentions_probs = self.drop(attentions_probs)
798
+
799
+ attn_output = torch.matmul(attentions_probs, value)
800
+ attn_output = rearrange(attn_output.permute(0, 2, 1, 3), "... h d -> ... (h d)")
801
+
802
+ attn_output = self.out_proj(attn_output)
803
+
804
+ return attn_output
805
+
806
+
807
+ class NomicBertBlock(nn.Module):
808
+ def __init__(
809
+ self,
810
+ config,
811
+ ):
812
+ super().__init__()
813
+ self.prenorm = config.prenorm
814
+ self.fused_dropout_add_ln = config.fused_dropout_add_ln
815
+
816
+ self.attn = NomicBertAttention(config)
817
+ activation = (
818
+ F.sigmoid
819
+ if config.activation_function == "glu"
820
+ else (F.silu if config.activation_function == "swiglu" else F.gelu)
821
+ )
822
+ if config.activation_function in ["glu", "swiglu", "geglu"]:
823
+ self.mlp = NomciBertGatedMLP(
824
+ config.n_embd,
825
+ hidden_features=config.n_inner,
826
+ bias1=config.mlp_fc1_bias,
827
+ bias2=config.mlp_fc2_bias,
828
+ activation=activation,
829
+ fused_bias_fc=config.fused_bias_fc,
830
+ )
831
+ else:
832
+ self.mlp = NomicBertMLP(
833
+ config.n_embd,
834
+ hidden_features=config.n_inner,
835
+ bias1=config.mlp_fc1_bias,
836
+ bias2=config.mlp_fc2_bias,
837
+ activation=activation,
838
+ fused_bias_fc=config.fused_bias_fc,
839
+ )
840
+
841
+ self.dropout1 = nn.Dropout(config.resid_pdrop)
842
+ self.norm1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
843
+ self.norm2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
844
+ self.dropout2 = nn.Dropout(config.resid_pdrop)
845
+
846
+ def forward(
847
+ self,
848
+ hidden_states: torch.Tensor,
849
+ hidden_states2: torch.Tensor,
850
+ residual: Optional[torch.Tensor] = None,
851
+ attention_mask: Optional[torch.Tensor] = None,
852
+ position_ids: Optional[torch.LongTensor] = None,
853
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
854
+ is_padded_inputs: Optional[bool] = True,
855
+ output_attentions: Optional[bool] = False,
856
+ use_cache: Optional[bool] = False,
857
+ cu_seqlens: Optional[torch.Tensor] = None,
858
+ max_seq_len: Optional[int] = None,
859
+ ):
860
+ r"""Pass the input through the encoder layer.
861
+ Args:
862
+ hidden_states: the sequence to the encoder layer (required).
863
+ residual: if postnorm, residual=None, If prenorm, hidden_states = Attn/MLP(LN(residual))
864
+ mixer_subset: for cross-attention only. If not None, will take a subset of x
865
+ before applying the query projection. Useful for e.g., ViT where we only care
866
+ about the CLS token in the last layer.
867
+ """
868
+ if self.prenorm:
869
+ dropped = self.dropout1(hidden_states)
870
+ residual = (dropped + residual) if residual is not None else dropped
871
+ hidden_states = self.norm1(residual.to(dtype=self.norm1.weight.dtype))
872
+ hidden_states = self.attn(
873
+ hidden_states,
874
+ attention_mask=attention_mask,
875
+ is_padded_inputs=is_padded_inputs,
876
+ cu_seqlens=cu_seqlens,
877
+ max_seq_len=max_seq_len,
878
+ )
879
+
880
+ dropped = self.dropout2(hidden_states)
881
+ residual = (dropped + residual) if residual is not None else dropped
882
+ hidden_states = self.norm2(residual.to(dtype=self.norm2.weight.dtype))
883
+ hidden_states = self.mlp(hidden_states)
884
+
885
+ return hidden_states, None, residual
886
+ else:
887
+ assert residual is None
888
+ attn_outputs = self.attn(
889
+ hidden_states,
890
+ attention_mask=attention_mask,
891
+ is_padded_inputs=is_padded_inputs,
892
+ cu_seqlens=cu_seqlens,
893
+ max_seq_len=max_seq_len,
894
+ )
895
+ hidden_states = self.norm1((self.dropout1(attn_outputs) + hidden_states).to(dtype=self.norm1.weight.dtype))
896
+ mlp_out = self.mlp(hidden_states)
897
+
898
+ hidden_states = self.norm2((self.dropout2(mlp_out) + hidden_states).to(dtype=self.norm2.weight.dtype))
899
+ return hidden_states, None, None
900
+
901
+
902
+ class NomicBertEncoder(nn.Module):
903
+ def __init__(self, config: GPT2Config):
904
+ super().__init__()
905
+ self.layers = nn.ModuleList([NomicBertBlock(config) for _ in range(config.n_layer)])
906
+ self.gradient_checkpointing = False
907
+ self.config = config
908
+
909
+ def forward(
910
+ self,
911
+ hidden_states: torch.LongTensor = None,
912
+ attention_mask: Optional[torch.Tensor] = None,
913
+ position_ids: Optional[torch.LongTensor] = None,
914
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
915
+ inputs_embeds: Optional[torch.FloatTensor] = None,
916
+ use_cache: Optional[bool] = None,
917
+ output_attentions: Optional[bool] = None,
918
+ output_hidden_states: Optional[bool] = None,
919
+ return_dict: Optional[bool] = None,
920
+ is_padded_inputs: Optional[bool] = True,
921
+ ):
922
+ """If subset_mask is not None, we only want output for the subset of the sequence.
923
+ This means that we only compute the last layer output for these tokens.
924
+ subset_mask: (batch, seqlen), dtype=torch.bool
925
+ """
926
+ hidden_states2 = None
927
+ residual = None
928
+
929
+ for _, layer in enumerate(self.layers):
930
+ if self.gradient_checkpointing and self.training:
931
+
932
+ def create_custom_forward(module):
933
+ def custom_forward(*inputs):
934
+ # None for past_key_value
935
+ return module(*inputs)
936
+
937
+ return custom_forward
938
+
939
+ hidden_states, hidden_states2, residual = torch.utils.checkpoint.checkpoint(
940
+ create_custom_forward(layer),
941
+ hidden_states,
942
+ hidden_states2,
943
+ residual,
944
+ attention_mask,
945
+ None,
946
+ None,
947
+ is_padded_inputs,
948
+ # if you freeze ANY layers, you need `use_reentrant=False`
949
+ # https://github.com/huggingface/transformers/issues/21381
950
+ # https://discuss.pytorch.org/t/checkpoint-with-no-grad-requiring-inputs-problem/19117/7
951
+ use_reentrant=False,
952
+ )
953
+
954
+ else:
955
+ hidden_states, hidden_states2, residual = layer(
956
+ hidden_states,
957
+ hidden_states2,
958
+ residual,
959
+ attention_mask,
960
+ position_ids,
961
+ None,
962
+ is_padded_inputs,
963
+ output_attentions,
964
+ use_cache,
965
+ )
966
+ return hidden_states
967
+
968
+
969
+ class NomicBertPooler(nn.Module):
970
+ def __init__(self, config):
971
+ super().__init__()
972
+ self.dense = nn.Linear(config.n_embd, config.n_embd)
973
+ self.activation = nn.Tanh()
974
+
975
+ def forward(self, hidden_states, pool=True):
976
+ # We "pool" the model by simply taking the hidden state corresponding
977
+ # to the first token.
978
+ first_token_tensor = hidden_states[:, 0] if pool else hidden_states
979
+ pooled_output = self.dense(first_token_tensor)
980
+ pooled_output = self.activation(pooled_output)
981
+ return pooled_output
982
+
983
+
984
+ class NomicBertPredictionHeadTransform(nn.Module):
985
+ def __init__(self, config):
986
+ super().__init__()
987
+ self.dense = nn.Linear(config.n_embd, config.n_embd, bias=config.mlp_fc1_bias)
988
+ approximate = "tanh" if config.activation_function in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"] else "none"
989
+ if config.activation_function == "swiglu":
990
+ self.transform_act_fn = F.silu
991
+ else:
992
+ self.transform_act_fn = nn.GELU(approximate=approximate)
993
+
994
+ self.layer_norm = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
995
+
996
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
997
+ hidden_states = self.dense(hidden_states)
998
+ hidden_states = self.transform_act_fn(hidden_states)
999
+ hidden_states = self.layer_norm(hidden_states)
1000
+
1001
+ return hidden_states
1002
+
1003
+
1004
+ class NomicBertLMPredictionHead(nn.Module):
1005
+ def __init__(self, config):
1006
+ super().__init__()
1007
+
1008
+ self.transform = NomicBertPredictionHeadTransform(config)
1009
+
1010
+ self.decoder = nn.Linear(config.n_embd, config.vocab_size, bias=config.mlp_fc1_bias)
1011
+
1012
+ def forward(self, hidden_states):
1013
+ hidden_states = self.transform(hidden_states)
1014
+ hidden_states = self.decoder(hidden_states)
1015
+ return hidden_states
1016
+
1017
+
1018
+ class NomicBertPreTrainingHeads(nn.Module):
1019
+ def __init__(self, config):
1020
+ super().__init__()
1021
+ self.predictions = NomicBertLMPredictionHead(config)
1022
+
1023
+ def forward(self, sequence_output):
1024
+ prediction_scores = self.predictions(sequence_output)
1025
+ return prediction_scores
1026
+
1027
+
1028
+ class NomicBertModel(NomicBertPreTrainedModel):
1029
+ def __init__(self, config: GPT2Config, add_pooling_layer=True):
1030
+ super().__init__(config)
1031
+ self.pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1)
1032
+ if config.vocab_size % self.pad_vocab_size_multiple != 0:
1033
+ config.vocab_size += self.pad_vocab_size_multiple - (config.vocab_size % self.pad_vocab_size_multiple)
1034
+
1035
+ assert config.activation_function in [
1036
+ "gelu",
1037
+ "gelu_new",
1038
+ "gelu_fast",
1039
+ "gelu_pytorch_tanh",
1040
+ "swiglu",
1041
+ "geglu",
1042
+ "glu",
1043
+ ]
1044
+
1045
+ self.embeddings = NomicBertEmbeddings(config)
1046
+ self.emb_drop = nn.Dropout(config.resid_pdrop)
1047
+ self.emb_ln = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
1048
+ self.encoder = NomicBertEncoder(config)
1049
+ self.pooler = NomicBertPooler(config) if add_pooling_layer else None
1050
+
1051
+ self.apply(partial(_init_weights, initializer_range=config.initializer_range))
1052
+
1053
+ def forward(
1054
+ self,
1055
+ input_ids,
1056
+ attention_mask=None,
1057
+ token_type_ids=None,
1058
+ position_ids=None,
1059
+ return_dict=None,
1060
+ ):
1061
+ if token_type_ids is None:
1062
+ token_type_ids = torch.zeros_like(input_ids)
1063
+ hidden_states = self.embeddings(input_ids, position_ids=position_ids, token_type_ids=token_type_ids)
1064
+ hidden_states = self.emb_ln(hidden_states)
1065
+ hidden_states = self.emb_drop(hidden_states)
1066
+
1067
+ attention_mask = self.get_extended_attention_mask(attention_mask, input_ids.shape)
1068
+ sequence_output = self.encoder(hidden_states, attention_mask=attention_mask, return_dict=return_dict)
1069
+
1070
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1071
+
1072
+ return BaseModelOutputWithPoolingAndCrossAttentions(
1073
+ last_hidden_state=sequence_output,
1074
+ pooler_output=pooled_output,
1075
+ )
1076
+
1077
+
1078
+ class NomicBertForPreTraining(NomicBertPreTrainedModel):
1079
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1080
+
1081
+ def __init__(self, config: GPT2Config):
1082
+ super().__init__(config)
1083
+
1084
+ self.bert = NomicBertModel(config, add_pooling_layer=getattr(config, "add_pooling_layer", False))
1085
+ self.cls = NomicBertPreTrainingHeads(config)
1086
+ self.mlm_loss = nn.CrossEntropyLoss()
1087
+
1088
+ # Initialize weights and apply final processing
1089
+ self.apply(partial(_init_weights, initializer_range=config.initializer_range))
1090
+ self.tie_weights()
1091
+
1092
+ def tie_weights(self):
1093
+ self.cls.predictions.decoder.weight = self.bert.embeddings.word_embeddings.weight
1094
+
1095
+ def forward(
1096
+ self,
1097
+ input_ids,
1098
+ position_ids=None,
1099
+ token_type_ids=None,
1100
+ attention_mask=None,
1101
+ labels=None,
1102
+ ):
1103
+ """
1104
+ If labels are provided, they must be -100 for masked out tokens (as specified in the attention
1105
+ mask).
1106
+ Outputs:
1107
+ if `labels` and `next_sentence_label` are not `None`:
1108
+ Outputs the total_loss which is the sum of the masked language modeling loss and the next
1109
+ sentence classification loss.
1110
+ if `labels` or `next_sentence_label` is `None`:
1111
+ Outputs a tuple comprising
1112
+ - the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and
1113
+ - the next sentence classification logits of shape [batch_size, 2].
1114
+ """
1115
+ outputs = self.bert(
1116
+ input_ids,
1117
+ position_ids=position_ids,
1118
+ token_type_ids=token_type_ids,
1119
+ attention_mask=attention_mask.bool() if attention_mask is not None else None,
1120
+ )
1121
+ sequence_output, _ = outputs.last_hidden_state, outputs.pooler_output
1122
+
1123
+ prediction_scores = self.cls(sequence_output)
1124
+
1125
+ total_loss = None
1126
+ if labels is not None:
1127
+ masked_lm_loss = self.mlm_loss(
1128
+ rearrange(prediction_scores, "... v -> (...) v"),
1129
+ rearrange(labels, "... -> (...)"),
1130
+ )
1131
+ total_loss = masked_lm_loss.float()
1132
+
1133
+ return MaskedLMOutput(
1134
+ loss=total_loss,
1135
+ logits=prediction_scores,
1136
+ hidden_states=outputs.hidden_states,
1137
+ attentions=None,
1138
+ )
1139
+
1140
+
1141
+ class NomicBertForSequenceClassification(NomicBertPreTrainedModel):
1142
+ def __init__(self, config):
1143
+ super().__init__(config)
1144
+ self.num_labels = config.num_labels
1145
+ self.config = config
1146
+
1147
+ self.bert = NomicBertModel(config)
1148
+ classifier_dropout = getattr(config, "classifier_dropout", config.embd_pdrop)
1149
+ self.dropout = nn.Dropout(classifier_dropout)
1150
+ self.classifier = nn.Linear(config.n_embd, config.num_labels)
1151
+
1152
+ # Initialize weights and apply final processing
1153
+ self.post_init()
1154
+
1155
+ def forward(
1156
+ self,
1157
+ input_ids: Optional[torch.Tensor] = None,
1158
+ attention_mask: Optional[torch.Tensor] = None,
1159
+ token_type_ids: Optional[torch.Tensor] = None,
1160
+ position_ids: Optional[torch.Tensor] = None,
1161
+ head_mask: Optional[torch.Tensor] = None,
1162
+ inputs_embeds: Optional[torch.Tensor] = None,
1163
+ labels: Optional[torch.Tensor] = None,
1164
+ output_attentions: Optional[bool] = None,
1165
+ output_hidden_states: Optional[bool] = None,
1166
+ return_dict: Optional[bool] = None,
1167
+ ):
1168
+ r"""
1169
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1170
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1171
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1172
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1173
+ """
1174
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1175
+ outputs = self.bert(
1176
+ input_ids,
1177
+ position_ids=position_ids,
1178
+ token_type_ids=token_type_ids,
1179
+ attention_mask=attention_mask.bool() if attention_mask is not None else None,
1180
+ )
1181
+
1182
+ pooled_output = outputs[1]
1183
+
1184
+ pooled_output = self.dropout(pooled_output)
1185
+ logits = self.classifier(pooled_output)
1186
+
1187
+ loss = None
1188
+ if labels is not None:
1189
+ if self.config.problem_type is None:
1190
+ if self.num_labels == 1:
1191
+ self.config.problem_type = "regression"
1192
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1193
+ self.config.problem_type = "single_label_classification"
1194
+ else:
1195
+ self.config.problem_type = "multi_label_classification"
1196
+
1197
+ if self.config.problem_type == "regression":
1198
+ loss_fct = nn.MSELoss()
1199
+ if self.num_labels == 1:
1200
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1201
+ else:
1202
+ loss = loss_fct(logits, labels)
1203
+ elif self.config.problem_type == "single_label_classification":
1204
+ loss_fct = nn.CrossEntropyLoss()
1205
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1206
+ elif self.config.problem_type == "multi_label_classification":
1207
+ loss_fct = nn.BCEWithLogitsLoss()
1208
+ loss = loss_fct(logits, labels)
1209
+ if not return_dict:
1210
+ output = (logits,) + outputs[2:]
1211
+ return ((loss,) + output) if loss is not None else output
1212
+
1213
+ return SequenceClassifierOutput(
1214
+ loss=loss,
1215
+ logits=logits,
1216
+ hidden_states=outputs.hidden_states,
1217
+ attentions=outputs.attentions,
1218
+ )