Fill-Mask
Transformers
PyTorch
Safetensors
English
nomic_bert
custom_code
zpn commited on
Commit
e119b48
1 Parent(s): 3e386a9

Upload NomicBertForPreTraining

Browse files
config.json CHANGED
@@ -5,7 +5,7 @@
5
  ],
6
  "attn_pdrop": 0.0,
7
  "auto_map": {
8
- "AutoConfig": "configuration_nomic_bert.NomicBertConfig",
9
  "AutoModelForMaskedLM": "modeling_hf_nomic_bert.NomicBertForPreTraining"
10
  },
11
  "bos_token_id": null,
 
5
  ],
6
  "attn_pdrop": 0.0,
7
  "auto_map": {
8
+ "AutoConfig": "configuration_hf_nomic_bert.NomicBertConfig",
9
  "AutoModelForMaskedLM": "modeling_hf_nomic_bert.NomicBertForPreTraining"
10
  },
11
  "bos_token_id": null,
configuration_hf_nomic_bert.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import GPT2Config
2
+
3
+
4
+ class NomicBertConfig(GPT2Config):
5
+ model_type = "nomic_bert"
6
+
7
+ def __init__(self,
8
+ prenorm=False,
9
+ parallel_block=False,
10
+ parallel_block_tied_norm=False,
11
+ rotary_emb_fraction=0.0,
12
+ fused_dropout_add_ln=False,
13
+ fused_bias_fc=False,
14
+ use_flash_attn=False,
15
+ use_xentropy=False,
16
+ qkv_proj_bias=True,
17
+ rotary_emb_base=1000,
18
+ rotary_emb_scale_base=None,
19
+ rotary_emb_interleaved=False,
20
+ mlp_fc1_bias=True,
21
+ mlp_fc2_bias=True,
22
+ use_rms_norm=False,
23
+ causal=False,
24
+ type_vocab_size=2,
25
+ dense_seq_output=True,
26
+ pad_vocab_size_multiple=1,
27
+ tie_word_embeddings=True,
28
+ **kwargs,
29
+ ):
30
+ self.prenorm = prenorm
31
+ self.parallel_block = parallel_block
32
+ self.parallel_block_tied_norm = parallel_block_tied_norm
33
+ self.rotary_emb_fraction = rotary_emb_fraction
34
+ self.tie_word_embeddings = tie_word_embeddings
35
+ self.fused_dropout_add_ln = fused_dropout_add_ln
36
+ self.fused_bias_fc = fused_bias_fc
37
+ self.use_flash_attn = use_flash_attn
38
+ self.use_xentropy = use_xentropy
39
+ self.qkv_proj_bias = qkv_proj_bias
40
+ self.rotary_emb_base = rotary_emb_base
41
+ self.rotary_emb_scale_base = rotary_emb_scale_base
42
+ self.rotary_emb_interleaved = rotary_emb_interleaved
43
+ self.mlp_fc1_bias = mlp_fc1_bias
44
+ self.mlp_fc2_bias = mlp_fc2_bias
45
+ self.use_rms_norm = use_rms_norm
46
+ self.causal = causal
47
+ self.type_vocab_size = type_vocab_size
48
+ self.dense_seq_output = dense_seq_output
49
+ self.pad_vocab_size_multiple = pad_vocab_size_multiple
50
+
51
+ super().__init__(**kwargs)
modeling_hf_nomic_bert.py CHANGED
@@ -4,7 +4,6 @@
4
  # https://github.com/mlcommons/training_results_v2.1/blob/main/Azure-HazyResearch/benchmarks/bert/implementations/ND96amsr_A100_v4/modeling.py
5
 
6
  # Inspired by https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py
7
-
8
  import os
9
  import logging
10
  from functools import partial
@@ -21,12 +20,258 @@ from transformers.models.bert.modeling_bert import (
21
  SequenceClassifierOutput
22
  )
23
 
24
- from contrastors.models.encoder.configuration_nomic_bert import NomicBertConfig
25
- from contrastors.models.model_utils import state_dict_from_pretrained, filter_shapes
26
- from contrastors.models.encoder.bert import remap_bert_state_dict
 
 
 
 
 
 
 
 
 
 
27
 
28
  logger = logging.getLogger(__name__)
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  class NomicBertPreTrainedModel(PreTrainedModel):
32
  """An abstract class to handle weights initialization and
 
4
  # https://github.com/mlcommons/training_results_v2.1/blob/main/Azure-HazyResearch/benchmarks/bert/implementations/ND96amsr_A100_v4/modeling.py
5
 
6
  # Inspired by https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py
 
7
  import os
8
  import logging
9
  from functools import partial
 
20
  SequenceClassifierOutput
21
  )
22
 
23
+ import re
24
+ from collections import OrderedDict
25
+ from safetensors.torch import load_file as safe_load_file
26
+ from transformers.utils import (
27
+ SAFE_WEIGHTS_INDEX_NAME,
28
+ SAFE_WEIGHTS_NAME,
29
+ WEIGHTS_INDEX_NAME,
30
+ WEIGHTS_NAME,
31
+ )
32
+ from transformers.utils.hub import cached_file, get_checkpoint_shard_files
33
+
34
+
35
+ from .configuration_hf_nomic_bert import NomicBertConfig
36
 
37
  logger = logging.getLogger(__name__)
38
 
39
+ # adapted from flash attention, added safe serialization option for hf models
40
+ def state_dict_from_pretrained(model_name, safe_serialization=False, device=None, dtype=None):
41
+ # If not fp32, then we don't want to load directly to the GPU
42
+ mapped_device = "cpu" if dtype not in [torch.float32, None] else device
43
+ is_sharded = False
44
+ load_safe = False
45
+ resolved_archive_file = None
46
+
47
+ weights_path = os.path.join(model_name, WEIGHTS_NAME)
48
+ weights_index_path = os.path.join(model_name, WEIGHTS_INDEX_NAME)
49
+ safe_weights_path = os.path.join(model_name, SAFE_WEIGHTS_NAME)
50
+ safe_weights_index_path = os.path.join(model_name, SAFE_WEIGHTS_INDEX_NAME)
51
+
52
+ if os.path.isfile(weights_path):
53
+ resolved_archive_file = cached_file(
54
+ model_name, WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False
55
+ )
56
+ elif os.path.isfile(weights_index_path):
57
+ resolved_archive_file = cached_file(
58
+ model_name, WEIGHTS_INDEX_NAME, _raise_exceptions_for_missing_entries=False
59
+ )
60
+ is_sharded = True
61
+ elif os.path.isfile(safe_weights_path):
62
+ resolved_archive_file = cached_file(
63
+ model_name, SAFE_WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False
64
+ )
65
+ load_safe = True
66
+ elif os.path.isfile(safe_weights_index_path):
67
+ resolved_archive_file = cached_file(
68
+ model_name, SAFE_WEIGHTS_INDEX_NAME, _raise_exceptions_for_missing_entries=False
69
+ )
70
+ is_sharded = True
71
+ load_safe = True
72
+ else: # Try loading from HF hub instead of from local files
73
+ weight_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME
74
+ resolved_archive_file = cached_file(model_name, weight_name, _raise_exceptions_for_missing_entries=False)
75
+ if resolved_archive_file is None:
76
+ weight_index = WEIGHTS_INDEX_NAME if not safe_serialization else SAFE_WEIGHTS_INDEX_NAME
77
+ resolved_archive_file = cached_file(model_name, weight_index,
78
+ _raise_exceptions_for_missing_entries=False)
79
+ if resolved_archive_file is not None:
80
+ is_sharded = True
81
+
82
+ load_safe = safe_serialization
83
+
84
+ if resolved_archive_file is None:
85
+ raise EnvironmentError(f"Model name {model_name} was not found.")
86
+
87
+ if load_safe:
88
+ loader = partial(safe_load_file, device=mapped_device)
89
+ else:
90
+ loader = partial(torch.load, map_location=mapped_device)
91
+
92
+ if is_sharded:
93
+ # resolved_archive_file becomes a list of files that point to the different
94
+ # checkpoint shards in this case.
95
+ resolved_archive_file, sharded_metadata = get_checkpoint_shard_files(
96
+ model_name, resolved_archive_file
97
+ )
98
+ state_dict = {}
99
+ for sharded_file in resolved_archive_file:
100
+ state_dict.update(loader(sharded_file))
101
+ else:
102
+ state_dict = loader(resolved_archive_file)
103
+ # Convert dtype before moving to GPU to save memory
104
+ if dtype is not None:
105
+ state_dict = {k: v.to(dtype=dtype) for k, v in state_dict.items()}
106
+ state_dict = {k: v.to(device=device) for k, v in state_dict.items()}
107
+ return state_dict
108
+
109
+
110
+ def filter_shapes(state_dict, model):
111
+ """
112
+ Filters the state dict to match the current model shape.
113
+ """
114
+ filtered_state_dict = {}
115
+ for key, value in state_dict.items():
116
+ if key in model.state_dict():
117
+ if value.shape == model.state_dict()[key].shape:
118
+ filtered_state_dict[key] = value
119
+ return filtered_state_dict
120
+
121
+
122
+ def remap_bert_state_dict(state_dict, config, remove_bert=False, remove_cls_weights=False, add_pooling_layer=False):
123
+ """
124
+ Map the state_dict of a Huggingface BERT model to be flash_attn compatible.
125
+ """
126
+ def add_bert_prefix(key):
127
+ # prepend bert. to the key
128
+ if key.startswith("bert.") or key.startswith("cls."):
129
+ return key
130
+ return f"bert.{key}"
131
+
132
+ state_dict = OrderedDict((add_bert_prefix(k), v) for k, v in state_dict.items())
133
+
134
+ # LayerNorm
135
+ def key_mapping_ln_gamma_beta(key):
136
+ key = re.sub(r"LayerNorm.gamma$", "LayerNorm.weight", key)
137
+ key = re.sub(r"LayerNorm.beta$", "LayerNorm.bias", key)
138
+ return key
139
+
140
+ state_dict = OrderedDict((key_mapping_ln_gamma_beta(k), v) for k, v in state_dict.items())
141
+
142
+ # Layers
143
+ def key_mapping_layers(key):
144
+ return re.sub(r"^bert.encoder.layer\.", "bert.encoder.layers.", key)
145
+
146
+ state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items())
147
+
148
+ # LayerNorm
149
+ def key_mapping_ln(key):
150
+ key = re.sub(r"^bert.embeddings.LayerNorm.", "bert.emb_ln.", key)
151
+ key = re.sub(
152
+ r"^bert.encoder.layers.(\d+).attention.output.LayerNorm.(weight|bias)",
153
+ r"bert.encoder.layers.\1.norm1.\2",
154
+ key,
155
+ )
156
+ key = re.sub(
157
+ r"^bert.encoder.layers.(\d+).output.LayerNorm.(weight|bias)",
158
+ r"bert.encoder.layers.\1.norm2.\2",
159
+ key,
160
+ )
161
+ key = re.sub(
162
+ r"^cls.predictions.transform.LayerNorm.(weight|bias)",
163
+ r"cls.predictions.transform.layer_norm.\1",
164
+ key,
165
+ )
166
+ return key
167
+
168
+ state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items())
169
+
170
+ # MLP
171
+ def key_mapping_mlp(key):
172
+ key = re.sub(
173
+ r"^bert.encoder.layers.(\d+).intermediate.dense.(weight|bias)",
174
+ r"bert.encoder.layers.\1.mlp.fc1.\2",
175
+ key,
176
+ )
177
+ key = re.sub(
178
+ r"^bert.encoder.layers.(\d+).output.dense.(weight|bias)",
179
+ r"bert.encoder.layers.\1.mlp.fc2.\2",
180
+ key,
181
+ )
182
+ return key
183
+
184
+ state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items())
185
+
186
+ # Attention
187
+ last_layer_subset = getattr(config, "last_layer_subset", False)
188
+ for d in range(config.num_hidden_layers):
189
+ if f"bert.encoder.layers.{d}.attention.self.query.weight" not in state_dict:
190
+ continue
191
+ Wq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.weight")
192
+ Wk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.weight")
193
+ Wv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.weight")
194
+ bq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.bias")
195
+ bk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.bias")
196
+ bv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.bias")
197
+ if not (last_layer_subset and d == config.num_hidden_layers - 1):
198
+ state_dict[f"bert.encoder.layers.{d}.attn.Wqkv.weight"] = torch.cat(
199
+ [Wq, Wk, Wv], dim=0
200
+ )
201
+ state_dict[f"bert.encoder.layers.{d}.attn.Wqkv.bias"] = torch.cat([bq, bk, bv], dim=0)
202
+ else:
203
+ state_dict[f"bert.encoder.layers.{d}.attn.Wq.weight"] = Wq
204
+ state_dict[f"bert.encoder.layers.{d}.attn.Wkv.weight"] = torch.cat([Wk, Wv], dim=0)
205
+ state_dict[f"bert.encoder.layers.{d}.attn.Wq.bias"] = bq
206
+ state_dict[f"bert.encoder.layers.{d}.attn.Wkv.bias"] = torch.cat([bk, bv], dim=0)
207
+
208
+ def key_mapping_attn(key):
209
+ return re.sub(
210
+ r"^bert.encoder.layers.(\d+).attention.output.dense.(weight|bias)",
211
+ r"bert.encoder.layers.\1.attn.out_proj.\2",
212
+ key,
213
+ )
214
+
215
+ state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items())
216
+
217
+ def key_mapping_decoder_bias(key):
218
+ return re.sub(r"^cls.predictions.bias", "cls.predictions.decoder.bias", key)
219
+
220
+
221
+ # remove nsp weights, we don't use
222
+ state_dict.pop("cls.seq_relationship.weight", None)
223
+ state_dict.pop("cls.seq_relationship.bias", None)
224
+ state_dict.pop("bert.embeddings.position_ids", None)
225
+
226
+ state_dict = OrderedDict((key_mapping_decoder_bias(k), v) for k, v in state_dict.items())
227
+
228
+ # Word embedding
229
+ pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1)
230
+ if pad_vocab_size_multiple > 1:
231
+ word_embeddings = state_dict["bert.embeddings.word_embeddings.weight"]
232
+ state_dict["bert.embeddings.word_embeddings.weight"] = F.pad(
233
+ word_embeddings, (0, 0, 0, config.vocab_size - word_embeddings.shape[0])
234
+ )
235
+ decoder_weight = state_dict["cls.predictions.decoder.weight"]
236
+ state_dict["cls.predictions.decoder.weight"] = F.pad(
237
+ decoder_weight, (0, 0, 0, config.vocab_size - decoder_weight.shape[0])
238
+ )
239
+ # If the vocab was padded, we want to set the decoder bias for those padded indices to be
240
+ # strongly negative (i.e. the decoder shouldn't predict those indices).
241
+ # TD [2022-05-09]: I don't think it affects the MLPerf training.
242
+ if "cls.predictions.decoder.bias" in state_dict:
243
+ decoder_bias = state_dict["cls.predictions.decoder.bias"]
244
+ state_dict["cls.predictions.decoder.bias"] = F.pad(
245
+ decoder_bias, (0, config.vocab_size - decoder_bias.shape[0]), value=-100.0
246
+ )
247
+
248
+ if add_pooling_layer is False:
249
+ pooler_weights = ["bert.pooler.dense.weight",
250
+ "bert.pooler.dense.bias",
251
+ ]
252
+ for key in pooler_weights:
253
+ state_dict.pop(key, None)
254
+
255
+ if remove_cls_weights:
256
+ cls_weights = ["cls.predictions.decoder.bias",
257
+ "cls.predictions.transform.dense.weight",
258
+ "cls.predictions.transform.dense.bias",
259
+ "cls.predictions.transform.layer_norm.weight",
260
+ "cls.predictions.transform.layer_norm.bias",
261
+ "cls.predictions.decoder.weight"]
262
+ for weight in cls_weights:
263
+ state_dict.pop(weight, None)
264
+
265
+ if remove_bert:
266
+ def remove_bert_prefix(key):
267
+ key = re.sub(r"^bert.", "", key)
268
+ return key
269
+
270
+ state_dict = OrderedDict((remove_bert_prefix(k), v) for k, v in state_dict.items())
271
+
272
+
273
+ return state_dict
274
+
275
 
276
  class NomicBertPreTrainedModel(PreTrainedModel):
277
  """An abstract class to handle weights initialization and