hsila commited on
Commit
f1b1689
·
verified ·
1 Parent(s): 2ffc22c

Add modeling_hf_nomic_bert.py

Browse files
Files changed (1) hide show
  1. modeling_hf_nomic_bert.py +2115 -0
modeling_hf_nomic_bert.py ADDED
@@ -0,0 +1,2115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 collections
7
+ import logging
8
+
9
+ # Inspired by https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py
10
+ import math
11
+ import os
12
+ import re
13
+ from collections import OrderedDict
14
+ from functools import partial
15
+ from typing import List, Optional, Tuple, Union
16
+
17
+ import numpy as np
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from einops import rearrange, repeat
22
+ from safetensors.torch import load_file as safe_load_file
23
+ from torch.nn.modules.utils import _pair
24
+ from transformers import GPT2Config, PreTrainedModel, ViTConfig, ViTModel
25
+ from transformers.modeling_outputs import BaseModelOutputWithPast
26
+ from transformers.models.bert.modeling_bert import (
27
+ BaseModelOutputWithPoolingAndCrossAttentions,
28
+ MaskedLMOutput,
29
+ SequenceClassifierOutput,
30
+ )
31
+ from transformers.utils import SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, WEIGHTS_INDEX_NAME, WEIGHTS_NAME
32
+ from transformers.utils.hub import cached_file, get_checkpoint_shard_files
33
+
34
+ from .configuration_hf_nomic_bert import NomicBertConfig
35
+
36
+ try:
37
+ from torch.nn.functional import scaled_dot_product_attention
38
+ except ImportError:
39
+ scaled_dot_product_attention = None
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+
44
+ # adapted from flash attention, added safe serialization option for hf models
45
+ def state_dict_from_pretrained(model_name, safe_serialization=False, device=None, dtype=None):
46
+ # If not fp32, then we don't want to load directly to the GPU
47
+ mapped_device = "cpu" if dtype not in [torch.float32, None] else device
48
+ is_sharded = False
49
+ load_safe = False
50
+ resolved_archive_file = None
51
+
52
+ weights_path = os.path.join(model_name, WEIGHTS_NAME)
53
+ weights_index_path = os.path.join(model_name, WEIGHTS_INDEX_NAME)
54
+ safe_weights_path = os.path.join(model_name, SAFE_WEIGHTS_NAME)
55
+ safe_weights_index_path = os.path.join(model_name, SAFE_WEIGHTS_INDEX_NAME)
56
+
57
+ if os.path.isfile(weights_path):
58
+ resolved_archive_file = cached_file(model_name, WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False)
59
+ elif os.path.isfile(weights_index_path):
60
+ resolved_archive_file = cached_file(model_name, WEIGHTS_INDEX_NAME, _raise_exceptions_for_missing_entries=False)
61
+ is_sharded = True
62
+ elif os.path.isfile(safe_weights_path):
63
+ resolved_archive_file = cached_file(model_name, SAFE_WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False)
64
+ load_safe = True
65
+ elif os.path.isfile(safe_weights_index_path):
66
+ resolved_archive_file = cached_file(
67
+ model_name, SAFE_WEIGHTS_INDEX_NAME, _raise_exceptions_for_missing_entries=False
68
+ )
69
+ is_sharded = True
70
+ load_safe = True
71
+ else: # Try loading from HF hub instead of from local files
72
+ resolved_archive_file = None
73
+ for weight_name in [WEIGHTS_NAME, SAFE_WEIGHTS_NAME, WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_INDEX_NAME]:
74
+ resolved_archive_file = cached_file(model_name, weight_name, _raise_exceptions_for_missing_entries=False)
75
+ if resolved_archive_file is not None:
76
+ if weight_name in [SAFE_WEIGHTS_NAME, SAFE_WEIGHTS_INDEX_NAME]:
77
+ load_safe = True
78
+ if weight_name in [WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_INDEX_NAME]:
79
+ is_sharded = True
80
+ break
81
+
82
+ if resolved_archive_file is None:
83
+ raise EnvironmentError(f"Model name {model_name} was not found.")
84
+
85
+ if load_safe:
86
+ loader = partial(safe_load_file, device=mapped_device)
87
+ else:
88
+ loader = partial(torch.load, map_location=mapped_device)
89
+
90
+ if is_sharded:
91
+ # resolved_archive_file becomes a list of files that point to the different
92
+ # checkpoint shards in this case.
93
+ resolved_archive_file, sharded_metadata = get_checkpoint_shard_files(model_name, resolved_archive_file)
94
+ state_dict = {}
95
+ for sharded_file in resolved_archive_file:
96
+ state_dict.update(loader(sharded_file))
97
+ else:
98
+ state_dict = loader(resolved_archive_file)
99
+ # Convert dtype before moving to GPU to save memory
100
+ if dtype is not None:
101
+ state_dict = {k: v.to(dtype=dtype) for k, v in state_dict.items()}
102
+ state_dict = {k: v.to(device=device) for k, v in state_dict.items()}
103
+ return state_dict
104
+
105
+
106
+ def filter_shapes(state_dict, model):
107
+ """
108
+ Filters the state dict to match the current model shape.
109
+ """
110
+ filtered_state_dict = {}
111
+ for key, value in state_dict.items():
112
+ if key in model.state_dict():
113
+ if value.shape == model.state_dict()[key].shape:
114
+ filtered_state_dict[key] = value
115
+ return filtered_state_dict
116
+
117
+
118
+ def remap_bert_state_dict(
119
+ state_dict,
120
+ config,
121
+ remove_bert=False,
122
+ remove_cls_weights=False,
123
+ add_pooling_layer=False,
124
+ ):
125
+ """
126
+ Map the state_dict of a Huggingface BERT model to be flash_attn compatible.
127
+ """
128
+
129
+ def add_bert_prefix(key):
130
+ # prepend bert. to the key
131
+ if key.startswith("bert.") or key.startswith("cls."):
132
+ return key
133
+ return f"bert.{key}"
134
+
135
+ state_dict = OrderedDict((add_bert_prefix(k), v) for k, v in state_dict.items())
136
+
137
+ # LayerNorm
138
+ def key_mapping_ln_gamma_beta(key):
139
+ key = re.sub(r"LayerNorm.gamma$", "LayerNorm.weight", key)
140
+ key = re.sub(r"LayerNorm.beta$", "LayerNorm.bias", key)
141
+ return key
142
+
143
+ state_dict = OrderedDict((key_mapping_ln_gamma_beta(k), v) for k, v in state_dict.items())
144
+
145
+ # Layers
146
+ def key_mapping_layers(key):
147
+ return re.sub(r"^bert.encoder.layer\.", "bert.encoder.layers.", key)
148
+
149
+ state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items())
150
+
151
+ # LayerNorm
152
+ def key_mapping_ln(key):
153
+ key = re.sub(r"^bert.embeddings.LayerNorm.", "bert.emb_ln.", key)
154
+ key = re.sub(
155
+ r"^bert.encoder.layers.(\d+).attention.output.LayerNorm.(weight|bias)",
156
+ r"bert.encoder.layers.\1.norm1.\2",
157
+ key,
158
+ )
159
+ key = re.sub(
160
+ r"^bert.encoder.layers.(\d+).output.LayerNorm.(weight|bias)",
161
+ r"bert.encoder.layers.\1.norm2.\2",
162
+ key,
163
+ )
164
+ key = re.sub(
165
+ r"^cls.predictions.transform.LayerNorm.(weight|bias)",
166
+ r"cls.predictions.transform.layer_norm.\1",
167
+ key,
168
+ )
169
+ return key
170
+
171
+ state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items())
172
+
173
+ # MLP
174
+ def key_mapping_mlp(key):
175
+ key = re.sub(
176
+ r"^bert.encoder.layers.(\d+).intermediate.dense.(weight|bias)",
177
+ r"bert.encoder.layers.\1.mlp.fc1.\2",
178
+ key,
179
+ )
180
+ key = re.sub(
181
+ r"^bert.encoder.layers.(\d+).output.dense.(weight|bias)",
182
+ r"bert.encoder.layers.\1.mlp.fc2.\2",
183
+ key,
184
+ )
185
+ return key
186
+
187
+ state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items())
188
+
189
+ # Attention
190
+ last_layer_subset = getattr(config, "last_layer_subset", False)
191
+ for d in range(config.num_hidden_layers):
192
+ if f"bert.encoder.layers.{d}.attention.self.query.weight" not in state_dict:
193
+ continue
194
+ Wq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.weight")
195
+ Wk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.weight")
196
+ Wv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.weight")
197
+ bq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.bias")
198
+ bk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.bias")
199
+ bv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.bias")
200
+ if not (last_layer_subset and d == config.num_hidden_layers - 1):
201
+ state_dict[f"bert.encoder.layers.{d}.attn.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0)
202
+ state_dict[f"bert.encoder.layers.{d}.attn.Wqkv.bias"] = torch.cat([bq, bk, bv], dim=0)
203
+ else:
204
+ state_dict[f"bert.encoder.layers.{d}.attn.Wq.weight"] = Wq
205
+ state_dict[f"bert.encoder.layers.{d}.attn.Wkv.weight"] = torch.cat([Wk, Wv], dim=0)
206
+ state_dict[f"bert.encoder.layers.{d}.attn.Wq.bias"] = bq
207
+ state_dict[f"bert.encoder.layers.{d}.attn.Wkv.bias"] = torch.cat([bk, bv], dim=0)
208
+
209
+ def key_mapping_attn(key):
210
+ return re.sub(
211
+ r"^bert.encoder.layers.(\d+).attention.output.dense.(weight|bias)",
212
+ r"bert.encoder.layers.\1.attn.out_proj.\2",
213
+ key,
214
+ )
215
+
216
+ state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items())
217
+
218
+ def key_mapping_decoder_bias(key):
219
+ return re.sub(r"^cls.predictions.bias", "cls.predictions.decoder.bias", key)
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
+ if remove_cls_weights:
229
+ cls_weights = [
230
+ "cls.predictions.decoder.bias",
231
+ "cls.predictions.transform.dense.weight",
232
+ "cls.predictions.transform.dense.bias",
233
+ "cls.predictions.transform.layer_norm.weight",
234
+ "cls.predictions.transform.layer_norm.bias",
235
+ "cls.predictions.decoder.weight",
236
+ ]
237
+ for weight in cls_weights:
238
+ state_dict.pop(weight, None)
239
+
240
+ # Word embedding
241
+ pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1)
242
+ if pad_vocab_size_multiple > 1:
243
+ word_embeddings = state_dict["bert.embeddings.word_embeddings.weight"]
244
+ state_dict["bert.embeddings.word_embeddings.weight"] = F.pad(
245
+ word_embeddings, (0, 0, 0, config.vocab_size - word_embeddings.shape[0])
246
+ )
247
+ if not remove_cls_weights:
248
+ if "cls.predictions.decoder.weight" not in state_dict:
249
+ state_dict['cls.predictions.decoder.weight'] = state_dict['bert.embeddings.word_embeddings.weight'].clone()
250
+ else:
251
+ decoder_weight = state_dict["cls.predictions.decoder.weight"]
252
+ state_dict["cls.predictions.decoder.weight"] = F.pad(
253
+ decoder_weight, (0, 0, 0, config.vocab_size - decoder_weight.shape[0])
254
+ )
255
+ # If the vocab was padded, we want to set the decoder bias for those padded indices to be
256
+ # strongly negative (i.e. the decoder shouldn't predict those indices).
257
+ # TD [2022-05-09]: I don't think it affects the MLPerf training.
258
+ if "cls.predictions.decoder.bias" in state_dict:
259
+ decoder_bias = state_dict["cls.predictions.decoder.bias"]
260
+ state_dict["cls.predictions.decoder.bias"] = F.pad(
261
+ decoder_bias, (0, config.vocab_size - decoder_bias.shape[0]), value=-100.0
262
+ )
263
+
264
+ if add_pooling_layer is False:
265
+ pooler_weights = [
266
+ "bert.pooler.dense.weight",
267
+ "bert.pooler.dense.bias",
268
+ ]
269
+ for key in pooler_weights:
270
+ state_dict.pop(key, None)
271
+
272
+ if remove_bert:
273
+
274
+ def remove_bert_prefix(key):
275
+ key = re.sub(r"^bert.", "", key)
276
+ return key
277
+
278
+ state_dict = OrderedDict((remove_bert_prefix(k), v) for k, v in state_dict.items())
279
+
280
+ return state_dict
281
+
282
+
283
+ def _trunc_normal_(tensor, mean, std, a, b):
284
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
285
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
286
+ def norm_cdf(x):
287
+ # Computes standard normal cumulative distribution function
288
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
289
+
290
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
291
+ print(
292
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
293
+ "The distribution of values may be incorrect.",
294
+ stacklevel=2,
295
+ )
296
+
297
+ # Values are generated by using a truncated uniform distribution and
298
+ # then using the inverse CDF for the normal distribution.
299
+ # Get upper and lower cdf values
300
+ l = norm_cdf((a - mean) / std)
301
+ u = norm_cdf((b - mean) / std)
302
+
303
+ # Uniformly fill tensor with values from [l, u], then translate to
304
+ # [2l-1, 2u-1].
305
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
306
+
307
+ # Use inverse cdf transform for normal distribution to get truncated
308
+ # standard normal
309
+ tensor.erfinv_()
310
+
311
+ # Transform to proper mean, std
312
+ tensor.mul_(std * math.sqrt(2.0))
313
+ tensor.add_(mean)
314
+
315
+ # Clamp to ensure it's in the proper range
316
+ tensor.clamp_(min=a, max=b)
317
+ return tensor
318
+
319
+
320
+ def trunc_normal_tf_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0):
321
+ r"""Fills the input Tensor with values drawn from a truncated
322
+ normal distribution. The values are effectively drawn from the
323
+ normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
324
+ with values outside :math:`[a, b]` redrawn until they are within
325
+ the bounds. The method used for generating the random values works
326
+ best when :math:`a \leq \text{mean} \leq b`.
327
+
328
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
329
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
330
+ and the result is subsquently scaled and shifted by the mean and std args.
331
+
332
+ Args:
333
+ tensor: an n-dimensional `torch.Tensor`
334
+ mean: the mean of the normal distribution
335
+ std: the standard deviation of the normal distribution
336
+ a: the minimum cutoff value
337
+ b: the maximum cutoff value
338
+ Examples:
339
+ >>> w = torch.empty(3, 5)
340
+ >>> nn.init.trunc_normal_(w)
341
+ """
342
+ with torch.no_grad():
343
+ _trunc_normal_(tensor, 0, 1.0, a, b)
344
+ tensor.mul_(std).add_(mean)
345
+ return tensor
346
+
347
+
348
+ class NomicBertPreTrainedModel(PreTrainedModel):
349
+ """An abstract class to handle weights initialization and
350
+ a simple interface for dowloading and loading pretrained models.
351
+ """
352
+
353
+ config_class = NomicBertConfig
354
+ base_model_prefix = "model"
355
+ supports_gradient_checkpointing = True
356
+ _no_split_modules = ["Block"]
357
+ _skip_keys_device_placement = "past_key_values"
358
+
359
+ def __init__(self, config, *inputs, **kwargs):
360
+ super().__init__(config)
361
+ if not isinstance(config, GPT2Config):
362
+ raise ValueError(
363
+ "Parameter config in `{}(config)` should be an instance of class `GPT2Config`. "
364
+ "To create a model from a Google pretrained model use "
365
+ "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format(
366
+ self.__class__.__name__, self.__class__.__name__
367
+ )
368
+ )
369
+ self.config = config
370
+
371
+ @classmethod
372
+ def from_pretrained(cls, model_name, config=None, *inputs, **kwargs):
373
+ """
374
+ Instantiate a NomicBertPreTrainedModel from a pre-trained model file or a pytorch state dict.
375
+ Download and cache the pre-trained model file if needed.
376
+
377
+ Params:
378
+ pretrained_model_name_or_path: either:
379
+ - a path or url to a pretrained model archive containing:
380
+ . `bert_config.json` a configuration file for the model
381
+ . `pytorch_model.bin` a PyTorch dump of a NomicBertForPretraining instance
382
+ - a path or url to a pretrained model archive containing:
383
+ . `bert_config.json` a configuration file for the model
384
+ . `model.chkpt` a TensorFlow checkpoint
385
+ *inputs, **kwargs: additional input for the specific NomicBert class
386
+ (ex: num_labels for NomicBertForSequenceClassification)
387
+ """
388
+ # Instantiate model.
389
+ if config is None:
390
+ config = cls.config_class.from_pretrained(model_name)
391
+ remove_cls = cls != NomicBertForPreTraining
392
+ remove_bert_prefix = cls != NomicBertForPreTraining and cls != NomicBertForSequenceClassification
393
+ ignore_mismatched_shapes = kwargs.pop("ignore_mismatched_sizes", False)
394
+ num_labels = kwargs.pop("num_labels", None)
395
+ rotary_scaling_factor = kwargs.pop("rotary_scaling_factor", None)
396
+ strict = kwargs.pop("strict", True)
397
+ dtype = kwargs.pop("torch_dtype", None)
398
+ if rotary_scaling_factor:
399
+ config.rotary_scaling_factor = rotary_scaling_factor
400
+
401
+ if config.n_positions <= 0 and config.rotary_emb_fraction > 0:
402
+ config.n_positions = 2048
403
+ if num_labels:
404
+ config.num_labels = num_labels
405
+
406
+ if "add_pooling_layer" in kwargs:
407
+ model = cls(config, *inputs, add_pooling_layer=kwargs.pop("add_pooling_layer"))
408
+ else:
409
+ if cls == NomicBertModel:
410
+ model = cls(config, *inputs, add_pooling_layer=False)
411
+ else:
412
+ model = cls(config, *inputs)
413
+
414
+ if dtype is not None:
415
+ model = model.to(dtype=dtype)
416
+ # TODO: fix this
417
+ # Assuming we know what we're doing when loading from disk
418
+ # Prob a bad assumption but i'm tired and want to train this asap
419
+ if os.path.exists(model_name):
420
+ model_path = f"{model_name}/pytorch_model.bin"
421
+ if os.path.exists(model_path):
422
+ state_dict = torch.load(f"{model_name}/pytorch_model.bin")
423
+ else:
424
+ model_path = f"{model_name}/model.safetensors"
425
+ if not os.path.exists(model_path):
426
+ raise ValueError(f"Model path {model_path} not found")
427
+ state_dict = safe_load_file(model_path)
428
+
429
+ if ignore_mismatched_shapes:
430
+ state_dict = filter_shapes(state_dict, model)
431
+ load_return = model.load_state_dict(state_dict, strict=False)
432
+ else:
433
+ # TODO: can probably check config class and see if we need to remap from a bert model
434
+ state_dict = state_dict_from_pretrained(model_name, dtype=dtype)
435
+ state_dict = remap_bert_state_dict(
436
+ state_dict,
437
+ config,
438
+ remove_bert=remove_bert_prefix,
439
+ remove_cls_weights=remove_cls,
440
+ add_pooling_layer=getattr(config, "add_pooling_layer", False),
441
+ )
442
+ if ignore_mismatched_shapes:
443
+ state_dict = filter_shapes(state_dict, model)
444
+
445
+ load_return = model.load_state_dict(state_dict, strict=strict)
446
+ logger.warning(load_return)
447
+ return model
448
+
449
+ def _set_gradient_checkpointing(self, module, value=False):
450
+ if isinstance(module, NomicBertEncoder):
451
+ module.gradient_checkpointing = value
452
+
453
+
454
+ # https://github.com/huggingface/transformers/blob/7032e0203262ebb2ebf55da8d2e01f873973e835/src/transformers/models/bert/modeling_bert.py#L748
455
+ def _init_weights(module, initializer_range=0.02):
456
+ if isinstance(module, nn.Linear):
457
+ nn.init.normal_(module.weight, std=initializer_range)
458
+ if module.bias is not None:
459
+ nn.init.zeros_(module.bias)
460
+ elif isinstance(module, nn.Embedding):
461
+ nn.init.normal_(module.weight, std=initializer_range)
462
+ if module.padding_idx is not None:
463
+ nn.init.zeros_(module.weight[module.padding_idx])
464
+
465
+
466
+ def _ntuple(n):
467
+ def parse(x):
468
+ if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
469
+ return tuple(x)
470
+ return tuple(repeat(x, n))
471
+
472
+ return parse
473
+
474
+
475
+ to_1tuple = _ntuple(1)
476
+ to_2tuple = _ntuple(2)
477
+ to_3tuple = _ntuple(3)
478
+ to_4tuple = _ntuple(4)
479
+ to_ntuple = _ntuple
480
+
481
+
482
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False):
483
+ """
484
+ Create 2D sin/cos positional embeddings.
485
+
486
+ Args:
487
+ embed_dim (`int`):
488
+ Embedding dimension.
489
+ grid_size (`int`):
490
+ The grid height and width.
491
+ add_cls_token (`bool`, *optional*, defaults to `False`):
492
+ Whether or not to add a classification (CLS) token.
493
+
494
+ Returns:
495
+ (`torch.FloatTensor` of shape (grid_size*grid_size, embed_dim) or (1+grid_size*grid_size, embed_dim): the
496
+ position embeddings (with or without classification token)
497
+ """
498
+ grid_h = np.arange(grid_size, dtype=np.float32)
499
+
500
+ grid_w = np.arange(grid_size, dtype=np.float32)
501
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
502
+ grid = np.stack(grid, axis=0)
503
+
504
+ grid = grid.reshape([2, 1, grid_size, grid_size])
505
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
506
+ if add_cls_token:
507
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
508
+ return pos_embed
509
+
510
+
511
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
512
+ if embed_dim % 2 != 0:
513
+ raise ValueError("embed_dim must be even")
514
+
515
+ # use half of dimensions to encode grid_h
516
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
517
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
518
+
519
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
520
+ return emb
521
+
522
+
523
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
524
+ """
525
+ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
526
+ """
527
+ if embed_dim % 2 != 0:
528
+ raise ValueError("embed_dim must be even")
529
+
530
+ omega = np.arange(embed_dim // 2, dtype=float)
531
+ omega /= embed_dim / 2.0
532
+ omega = 1.0 / 10000**omega # (D/2,)
533
+
534
+ pos = pos.reshape(-1) # (M,)
535
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
536
+
537
+ emb_sin = np.sin(out) # (M, D/2)
538
+ emb_cos = np.cos(out) # (M, D/2)
539
+
540
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
541
+ return emb
542
+
543
+
544
+ def ndgrid(*tensors) -> Tuple[torch.Tensor, ...]:
545
+ """generate N-D grid in dimension order.
546
+
547
+ The ndgrid function is like meshgrid except that the order of the first two input arguments are switched.
548
+
549
+ That is, the statement
550
+ [X1,X2,X3] = ndgrid(x1,x2,x3)
551
+
552
+ produces the same result as
553
+
554
+ [X2,X1,X3] = meshgrid(x2,x1,x3)
555
+
556
+ This naming is based on MATLAB, the purpose is to avoid confusion due to torch's change to make
557
+ torch.meshgrid behaviour move from matching ndgrid ('ij') indexing to numpy meshgrid defaults of ('xy').
558
+
559
+ """
560
+ try:
561
+ return torch.meshgrid(*tensors, indexing='ij')
562
+ except TypeError:
563
+ # old PyTorch < 1.10 will follow this path as it does not have indexing arg,
564
+ # the old behaviour of meshgrid was 'ij'
565
+ return torch.meshgrid(*tensors)
566
+
567
+
568
+ def build_fourier_pos_embed(
569
+ feat_shape: List[int],
570
+ bands: Optional[torch.Tensor] = None,
571
+ num_bands: int = 64,
572
+ max_res: int = 224,
573
+ temperature: float = 10000.0,
574
+ linear_bands: bool = False,
575
+ include_grid: bool = False,
576
+ in_pixels: bool = True,
577
+ ref_feat_shape: Optional[List[int]] = None,
578
+ dtype: torch.dtype = torch.float32,
579
+ device: Optional[torch.device] = None,
580
+ ) -> List[torch.Tensor]:
581
+ """
582
+
583
+ Args:
584
+ feat_shape: Feature shape for embedding.
585
+ bands: Pre-calculated frequency bands.
586
+ num_bands: Number of frequency bands (determines output dim).
587
+ max_res: Maximum resolution for pixel based freq.
588
+ temperature: Temperature for non-pixel freq.
589
+ linear_bands: Linear band spacing for pixel based freq.
590
+ include_grid: Include the spatial grid in output.
591
+ in_pixels: Output in pixel freq.
592
+ ref_feat_shape: Reference feature shape for resize / fine-tune.
593
+ dtype: Output dtype.
594
+ device: Output device.
595
+
596
+ Returns:
597
+
598
+ """
599
+ if bands is None:
600
+ if in_pixels:
601
+ bands = pixel_freq_bands(
602
+ num_bands,
603
+ float(max_res),
604
+ linear_bands=linear_bands,
605
+ device=device,
606
+ )
607
+ else:
608
+ bands = freq_bands(
609
+ num_bands,
610
+ temperature=temperature,
611
+ step=1,
612
+ device=device,
613
+ )
614
+ else:
615
+ if device is None:
616
+ device = bands.device
617
+ if dtype is None:
618
+ dtype = bands.dtype
619
+
620
+ if in_pixels:
621
+ t = [torch.linspace(-1.0, 1.0, steps=s, device=device, dtype=torch.float32) for s in feat_shape]
622
+ else:
623
+ t = [torch.arange(s, device=device, dtype=torch.int64).to(torch.float32) for s in feat_shape]
624
+
625
+ if ref_feat_shape is not None:
626
+ # eva's scheme for resizing rope embeddings (ref shape = pretrain)
627
+ t = [x / f * r for x, f, r in zip(t, feat_shape, ref_feat_shape)]
628
+
629
+ grid = torch.stack(ndgrid(t), dim=-1)
630
+ grid = grid.unsqueeze(-1)
631
+ pos = grid * bands
632
+
633
+ pos_sin, pos_cos = pos.sin().to(dtype=dtype), pos.cos().to(dtype)
634
+ out = [grid, pos_sin, pos_cos] if include_grid else [pos_sin, pos_cos]
635
+ return out
636
+
637
+
638
+ def build_rotary_pos_embed(
639
+ feat_shape: List[int],
640
+ bands: Optional[torch.Tensor] = None,
641
+ dim: int = 64,
642
+ max_res: int = 224,
643
+ temperature: float = 10000.0,
644
+ linear_bands: bool = False,
645
+ in_pixels: bool = True,
646
+ ref_feat_shape: Optional[List[int]] = None,
647
+ dtype: torch.dtype = torch.float32,
648
+ device: Optional[torch.device] = None,
649
+ ):
650
+ """
651
+
652
+ Args:
653
+ feat_shape: Spatial shape of the target tensor for embedding.
654
+ bands: Optional pre-generated frequency bands
655
+ dim: Output dimension of embedding tensor.
656
+ max_res: Maximum resolution for pixel mode.
657
+ temperature: Temperature (inv freq) for non-pixel mode
658
+ linear_bands: Linearly (instead of log) spaced bands for pixel mode
659
+ in_pixels: Pixel vs language (inv freq) mode.
660
+ dtype: Output dtype.
661
+ device: Output device.
662
+
663
+ Returns:
664
+
665
+ """
666
+ sin_emb, cos_emb = build_fourier_pos_embed(
667
+ feat_shape,
668
+ bands=bands,
669
+ num_bands=dim // 4,
670
+ max_res=max_res,
671
+ temperature=temperature,
672
+ linear_bands=linear_bands,
673
+ in_pixels=in_pixels,
674
+ ref_feat_shape=ref_feat_shape,
675
+ device=device,
676
+ dtype=dtype,
677
+ )
678
+ num_spatial_dim = 1
679
+ # this would be much nicer as a .numel() call to torch.Size(), but torchscript sucks
680
+ for x in feat_shape:
681
+ num_spatial_dim *= x
682
+ sin_emb = sin_emb.reshape(num_spatial_dim, -1).repeat_interleave(2, -1)
683
+ cos_emb = cos_emb.reshape(num_spatial_dim, -1).repeat_interleave(2, -1)
684
+ return sin_emb, cos_emb
685
+
686
+
687
+ def freq_bands(
688
+ num_bands: int,
689
+ temperature: float = 10000.0,
690
+ step: int = 2,
691
+ device: Optional[torch.device] = None,
692
+ ) -> torch.Tensor:
693
+ exp = torch.arange(0, num_bands, step, dtype=torch.int64, device=device).to(torch.float32) / num_bands
694
+ bands = 1.0 / (temperature**exp)
695
+ return bands
696
+
697
+
698
+ def pixel_freq_bands(
699
+ num_bands: int,
700
+ max_freq: float = 224.0,
701
+ linear_bands: bool = True,
702
+ device: Optional[torch.device] = None,
703
+ ):
704
+ if linear_bands:
705
+ bands = torch.linspace(1.0, max_freq / 2, num_bands, dtype=torch.float32, device=device)
706
+ else:
707
+ bands = 2 ** torch.linspace(0, math.log(max_freq, 2) - 1, num_bands, dtype=torch.float32, device=device)
708
+ return bands * torch.pi
709
+
710
+
711
+ def rot(x):
712
+ return torch.stack([-x[..., 1::2], x[..., ::2]], -1).reshape(x.shape)
713
+
714
+
715
+ def apply_rot_embed_cat(x: torch.Tensor, emb):
716
+ sin_emb, cos_emb = emb.tensor_split(2, -1)
717
+ if sin_emb.ndim == 3:
718
+ return x * cos_emb.unsqueeze(1).expand_as(x) + rot(x) * sin_emb.unsqueeze(1).expand_as(x)
719
+ return x * cos_emb + rot(x) * sin_emb
720
+
721
+
722
+ # taken from https://github.com/huggingface/pytorch-image-models/blob/cb0e4391beedcc5ac3ae4bce16561b95c326f32c/timm/layers/pos_embed_sincos.py#L363
723
+ class NomicVisionRotaryEmbeddingCat(nn.Module):
724
+ """Rotary position embedding w/ concatenatd sin & cos
725
+
726
+ The following impl/resources were referenced for this impl:
727
+ * https://github.com/lucidrains/vit-pytorch/blob/6f3a5fcf0bca1c5ec33a35ef48d97213709df4ba/vit_pytorch/rvt.py
728
+ * https://blog.eleuther.ai/rotary-embeddings/
729
+ """
730
+
731
+ def __init__(
732
+ self,
733
+ dim,
734
+ max_res=224,
735
+ temperature=10000,
736
+ in_pixels=True,
737
+ linear_bands: bool = False,
738
+ feat_shape: Optional[List[int]] = None,
739
+ ref_feat_shape: Optional[List[int]] = None,
740
+ ):
741
+ super().__init__()
742
+ self.dim = dim
743
+ self.max_res = max_res
744
+ self.temperature = temperature
745
+ self.in_pixels = in_pixels
746
+ self.feat_shape = feat_shape
747
+ self.ref_feat_shape = ref_feat_shape
748
+
749
+ if feat_shape is None:
750
+ # only cache bands
751
+ if in_pixels:
752
+ bands = pixel_freq_bands(
753
+ dim // 4,
754
+ float(max_res),
755
+ linear_bands=linear_bands,
756
+ )
757
+ else:
758
+ bands = freq_bands(
759
+ dim // 4,
760
+ temperature=temperature,
761
+ step=1,
762
+ )
763
+ self.register_buffer(
764
+ 'bands',
765
+ bands,
766
+ persistent=False,
767
+ )
768
+ self.pos_embed = None
769
+ else:
770
+ # cache full sin/cos embeddings if shape provided up front
771
+ embeds = build_rotary_pos_embed(
772
+ feat_shape=feat_shape,
773
+ dim=dim,
774
+ max_res=max_res,
775
+ linear_bands=linear_bands,
776
+ in_pixels=in_pixels,
777
+ ref_feat_shape=self.ref_feat_shape,
778
+ )
779
+ self.bands = None
780
+ self.register_buffer(
781
+ 'pos_embed',
782
+ torch.cat(embeds, -1),
783
+ persistent=False,
784
+ )
785
+
786
+ def get_embed(self, shape: Optional[List[int]] = None):
787
+ if self.bands is not None and shape is not None:
788
+ # rebuild embeddings every call, use if target shape changes
789
+ embeds = build_rotary_pos_embed(
790
+ shape,
791
+ self.bands,
792
+ in_pixels=self.in_pixels,
793
+ ref_feat_shape=self.ref_feat_shape,
794
+ )
795
+ return torch.cat(embeds, -1)
796
+ elif self.pos_embed is not None:
797
+ return self.pos_embed
798
+ else:
799
+ assert False, "get_embed() requires pre-computed pos_embed or valid shape w/ pre-computed bands"
800
+
801
+ def forward(self, x):
802
+ # assuming channel-first tensor where spatial dim are >= 2
803
+ pos_embed = self.get_embed(x.shape[2:])
804
+ return apply_rot_embed_cat(x, pos_embed)
805
+
806
+
807
+ class NomicVisionPatchEmbeddings(nn.Module):
808
+ def __init__(
809
+ self,
810
+ config,
811
+ ):
812
+ super().__init__()
813
+ img_size = _pair(config.img_size)
814
+ patch_size = _pair(config.patch_size)
815
+ self.img_size = img_size
816
+ self.patch_size = patch_size
817
+ self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
818
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
819
+
820
+ self.proj = nn.Linear(
821
+ config.num_channels * patch_size[0] * patch_size[1], config.n_embd, bias=config.patch_embed_bias
822
+ )
823
+
824
+ self.learned_pos_embedding = False
825
+ self.sinusoidal_pos_embedding = False
826
+ self.no_embed_class = getattr(config, "no_embed_class", False)
827
+
828
+ self.cls_token = (
829
+ nn.Parameter(torch.zeros(1, 1, config.n_embd)) if not getattr(config, "no_cls_token", False) else None
830
+ )
831
+ if config.learned_pos_embedding:
832
+ # this is the default in DINO
833
+ self.learned_pos_embedding = True
834
+ # hack for timm dinov2 with registers
835
+ num_patches = self.num_patches if getattr(config, "register_tokens", 0) > 0 else self.num_patches + 1
836
+ self.pos_embed = (
837
+ nn.Parameter(torch.randn(1, num_patches, config.n_embd) * 0.02)
838
+ if getattr(config, "use_pos_embed", True)
839
+ else None
840
+ )
841
+ elif getattr(config, "sinusoidal_pos_embedding", False):
842
+ self.sinusoidal_pos_embedding = True
843
+ if getattr(config, "use_pos_embed", True):
844
+ self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches + 1, config.n_embd), requires_grad=False)
845
+ pos_embed = get_2d_sincos_pos_embed(config.n_embd, self.grid_size[0], add_cls_token=True)
846
+ self.pos_embed.data.copy_(torch.from_numpy(pos_embed).to(self.pos_embed))
847
+ else:
848
+ self.pos_embed = None
849
+ else:
850
+ self.pos_embed = (
851
+ nn.Parameter(torch.randn(1, self.num_patches + 1, config.n_embd) * 0.02)
852
+ if getattr(config, "use_pos_embed", True)
853
+ else None
854
+ )
855
+
856
+ if getattr(config, "register_tokens", 0) > 0:
857
+ self.reg_token = nn.Parameter(torch.randn(1, config.register_tokens, config.n_embd) * 0.02)
858
+ else:
859
+ self.reg_token = None
860
+
861
+ if config.mask_token:
862
+ self.mask_token = nn.Parameter(torch.zeros(1, config.n_embd))
863
+
864
+ self.patch_dropout = nn.Identity()
865
+
866
+ if getattr(config, "use_rotary_pos_emb", False):
867
+ ref_feat_shape = getattr(config, "ref_feat_shape", None)
868
+ ref_feat_shape = to_2tuple(ref_feat_shape) if ref_feat_shape is not None else None
869
+ self.rope = NomicVisionRotaryEmbeddingCat(
870
+ config.n_embd // config.n_head,
871
+ in_pixels=False,
872
+ feat_shape=self.grid_size,
873
+ ref_feat_shape=ref_feat_shape,
874
+ )
875
+ else:
876
+ self.rope = None
877
+
878
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
879
+ """
880
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
881
+ resolution images.
882
+
883
+ Source:
884
+ https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
885
+ """
886
+ num_patches = embeddings.shape[1] - 1
887
+ num_positions = self.pos_embed.shape[1] - 1
888
+ if num_patches == num_positions and height == width:
889
+ return self.pos_embed
890
+ class_pos_embed = self.pos_embed[:, 0]
891
+ patch_pos_embed = self.pos_embed[:, 1:]
892
+ dim = embeddings.shape[-1]
893
+ height = height // self.patch_size[0]
894
+ width = width // self.patch_size[1]
895
+ # we add a small number to avoid floating point error in the interpolation
896
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
897
+ height, width = height + 0.1, width + 0.1
898
+ patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
899
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
900
+ patch_pos_embed = nn.functional.interpolate(
901
+ patch_pos_embed,
902
+ scale_factor=(height / math.sqrt(num_positions), width / math.sqrt(num_positions)),
903
+ mode="bicubic",
904
+ align_corners=False,
905
+ )
906
+ if int(height) != patch_pos_embed.shape[-2] or int(width) != patch_pos_embed.shape[-1]:
907
+ raise ValueError("Width or height does not match with the interpolated position embeddings")
908
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
909
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
910
+
911
+ def forward(self, x):
912
+ # deepspeed case where the input is in fp32
913
+ if x.dtype != self.proj.weight.dtype:
914
+ x = x.to(dtype=self.proj.weight.dtype)
915
+
916
+ _, _, height, width = x.shape
917
+ x = self.proj(
918
+ rearrange(
919
+ x,
920
+ "b c (h p1) (w p2) -> b h w (c p1 p2)",
921
+ p1=self.patch_size[0],
922
+ p2=self.patch_size[1],
923
+ )
924
+ )
925
+ embeddings = rearrange(x, "b h w c -> b (h w) c")
926
+
927
+ to_cat = []
928
+ if self.cls_token is not None:
929
+ if self.sinusoidal_pos_embedding:
930
+ cls_token = self.cls_token + self.pos_embed[:, 0]
931
+ cls_token = cls_token.expand(embeddings.shape[0], -1, -1)
932
+ to_cat += [cls_token]
933
+ else:
934
+ cls_token = self.cls_token.expand(embeddings.shape[0], 1, -1)
935
+ to_cat += [cls_token]
936
+
937
+ if self.reg_token is not None:
938
+ to_cat += [self.reg_token.expand(embeddings.shape[0], -1, -1)]
939
+
940
+ rot_pos_embed = self.rope.get_embed() if self.rope is not None else None
941
+
942
+ if self.no_embed_class:
943
+ if self.learned_pos_embedding:
944
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
945
+ else:
946
+ if self.pos_embed is not None:
947
+ embeddings = embeddings + self.pos_embed
948
+ if to_cat:
949
+ embeddings = torch.cat(to_cat + [embeddings], dim=1)
950
+ else:
951
+ if to_cat:
952
+ embeddings = torch.cat(to_cat + [embeddings], dim=1)
953
+ if self.learned_pos_embedding:
954
+ if self.pos_embed is not None:
955
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
956
+ else:
957
+ if self.pos_embed is not None:
958
+ embeddings = embeddings + self.pos_embed
959
+
960
+ embeddings = self.patch_dropout(embeddings)
961
+
962
+ return embeddings, rot_pos_embed
963
+
964
+
965
+ class NomicBertEmbeddings(nn.Module):
966
+ def __init__(self, config):
967
+ """
968
+ If max_position_embeddings <= 0, there's no position embeddings
969
+ If type_vocab_size <= 0, there's no token type embeddings
970
+ """
971
+ super().__init__()
972
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
973
+ self.max_position_embeddings = config.max_position_embeddings if config.rotary_emb_fraction <= 0 else 0
974
+ self.type_vocab_size = config.type_vocab_size
975
+ if self.max_position_embeddings > 0 and config.rotary_emb_fraction <= 0:
976
+ self.position_embeddings = nn.Embedding(
977
+ config.max_position_embeddings,
978
+ config.hidden_size,
979
+ )
980
+ if self.type_vocab_size > 0:
981
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
982
+
983
+ def forward(self, input_ids, position_ids=None, token_type_ids=None):
984
+ """
985
+ input_ids: (batch, seqlen)
986
+ position_ids: (batch, seqlen)
987
+ token_type_ids: (batch, seqlen)
988
+ """
989
+ batch_size, seqlen = input_ids.shape
990
+ embeddings = self.word_embeddings(input_ids)
991
+
992
+ if self.type_vocab_size > 0:
993
+ if token_type_ids is None:
994
+ token_type_ids = torch.zeros(seqlen, dtype=torch.long, device=input_ids.device)
995
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
996
+ embeddings = embeddings + token_type_embeddings
997
+
998
+ if self.max_position_embeddings > 0:
999
+ if position_ids is None:
1000
+ position_ids = torch.arange(seqlen, dtype=torch.long, device=input_ids.device)
1001
+ position_embeddings = self.position_embeddings(position_ids)
1002
+ embeddings = embeddings + position_embeddings
1003
+ return embeddings
1004
+
1005
+
1006
+ class NomicBertMLP(nn.Module):
1007
+ def __init__(
1008
+ self,
1009
+ in_features,
1010
+ hidden_features=None,
1011
+ out_features=None,
1012
+ activation=F.gelu,
1013
+ bias1=True,
1014
+ bias2=True,
1015
+ return_residual=False,
1016
+ fused_bias_fc=False,
1017
+ ):
1018
+ super().__init__()
1019
+ out_features = out_features if out_features is not None else in_features
1020
+ hidden_features = hidden_features if hidden_features is not None else in_features * 4
1021
+ self.return_residual = return_residual
1022
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1)
1023
+ approximate = "tanh" if activation in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"] else "none"
1024
+ self.activation = nn.GELU(approximate=approximate) if activation == "gelu" else activation
1025
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2)
1026
+
1027
+ def forward(self, x):
1028
+ y = self.fc1(x)
1029
+ y = self.activation(y)
1030
+ y = self.fc2(y)
1031
+ return y if not self.return_residual else (y, x)
1032
+
1033
+
1034
+ class NomciBertGatedMLP(nn.Module):
1035
+ def __init__(
1036
+ self,
1037
+ in_features,
1038
+ hidden_features=None,
1039
+ out_features=None,
1040
+ activation=F.sigmoid,
1041
+ bias1=True,
1042
+ bias2=True,
1043
+ multiple_of=256,
1044
+ return_residual=False,
1045
+ fused_bias_fc=True,
1046
+ device=None,
1047
+ dtype=None,
1048
+ norm_layer=False,
1049
+ ):
1050
+ super().__init__()
1051
+ out_features = out_features if out_features is not None else in_features
1052
+ hidden_features = hidden_features if hidden_features is not None else int(8 * in_features / 3)
1053
+ hidden_features = int((hidden_features + multiple_of - 1) // multiple_of * multiple_of)
1054
+ self.return_residual = return_residual
1055
+
1056
+ self.fc11 = nn.Linear(in_features, hidden_features, bias=bias1)
1057
+ self.fc12 = nn.Linear(in_features, hidden_features, bias=bias1)
1058
+ self.activation = activation
1059
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2)
1060
+ self.norm = nn.LayerNorm(hidden_features) if norm_layer else nn.Identity()
1061
+
1062
+ def forward(self, x):
1063
+ y = self.fc11(x)
1064
+ gate = self.fc12(x)
1065
+ if self.activation == F.sigmoid: # Special case for GLU
1066
+ y = F.glu(torch.cat([y, gate], dim=-1), dim=-1)
1067
+ else:
1068
+ y = y * self.activation(gate)
1069
+
1070
+ # eva uses layer norm after the activation
1071
+ y = self.norm(y)
1072
+
1073
+ y = self.fc2(y)
1074
+ return y if not self.return_residual else (y, x)
1075
+
1076
+
1077
+ def rotate_half(x, interleaved=False):
1078
+ if not interleaved:
1079
+ x1, x2 = x.chunk(2, dim=-1)
1080
+ return torch.cat((-x2, x1), dim=-1)
1081
+ else:
1082
+ x1, x2 = x[..., ::2], x[..., 1::2]
1083
+ return rearrange(torch.stack((-x2, x1), dim=-1), "... d two -> ... (d two)", two=2)
1084
+
1085
+
1086
+ def apply_rotary_emb(x, cos, sin, offset=0, interleaved=False):
1087
+ """
1088
+ x: (batch_size, seqlen, nheads, headdim)
1089
+ cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2)
1090
+ """
1091
+ ro_dim = cos.shape[-1] * 2
1092
+ assert ro_dim <= x.shape[-1]
1093
+ cos, sin = (
1094
+ cos[offset : offset + x.shape[1]],
1095
+ sin[offset : offset + x.shape[1]],
1096
+ )
1097
+ cos = repeat(cos, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
1098
+ sin = repeat(sin, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
1099
+ return torch.cat(
1100
+ [x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]],
1101
+ dim=-1,
1102
+ )
1103
+
1104
+
1105
+ class NomicBertRotaryEmbedding(nn.Module):
1106
+ def __init__(
1107
+ self,
1108
+ dim: int,
1109
+ base=10000.0,
1110
+ interleaved=False,
1111
+ scale_base=None,
1112
+ pos_idx_in_fp32=True,
1113
+ device=None,
1114
+ ):
1115
+ """
1116
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
1117
+ of 1st half and 2nd half (GPT-NeoX style).
1118
+ pos_idx_in_fp32: if True, the position indices [0.0, ..., seqlen - 1] are in fp32,
1119
+ otherwise they might be in lower precision.
1120
+ This option was added because previously (before 2023-07-02), when we construct
1121
+ the position indices, we use the dtype of self.inv_freq. In most cases this would
1122
+ be fp32, but if the model is trained in pure bf16 (not mixed precision), then
1123
+ self.inv_freq would be bf16, and the position indices are also in bf16.
1124
+ Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the
1125
+ embeddings for some positions will coincide.
1126
+ To maintain compatibility with models previously trained in pure bf16,
1127
+ we add this option.
1128
+ """
1129
+ super().__init__()
1130
+ self.dim = dim
1131
+ self.base = float(base)
1132
+ self.pos_idx_in_fp32 = pos_idx_in_fp32
1133
+ # Generate and save the inverse frequency buffer (non trainable)
1134
+ inv_freq = self._compute_inv_freq(device)
1135
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
1136
+ self.interleaved = interleaved
1137
+ self.scale_base = scale_base
1138
+ scale = (
1139
+ (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)
1140
+ if scale_base is not None
1141
+ else None
1142
+ )
1143
+ self.register_buffer("scale", scale, persistent=False)
1144
+
1145
+ self._seq_len_cached = 0
1146
+ self._cos_cached = None
1147
+ self._sin_cached = None
1148
+ self._cos_k_cached = None
1149
+ self._sin_k_cached = None
1150
+
1151
+ def _compute_inv_freq(self, device=None):
1152
+ return 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
1153
+
1154
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
1155
+ # Reset the tables if the sequence length has changed,
1156
+ # if we're on a new device (possibly due to tracing for instance),
1157
+ # or if we're switching from inference mode to training
1158
+ if (
1159
+ seqlen > self._seq_len_cached
1160
+ or self._cos_cached is None
1161
+ or self._cos_cached.device != device
1162
+ or self._cos_cached.dtype != dtype
1163
+ or (self.training and self._cos_cached.is_inference())
1164
+ ):
1165
+ self._seq_len_cached = seqlen
1166
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
1167
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
1168
+ # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
1169
+ if self.pos_idx_in_fp32:
1170
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
1171
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
1172
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
1173
+ # cos & sin output to change significantly.
1174
+ # We want to recompute self.inv_freq if it was not loaded in fp32
1175
+ if self.inv_freq.dtype != torch.float32:
1176
+ inv_freq = self._compute_inv_freq(device=device)
1177
+ else:
1178
+ inv_freq = self.inv_freq
1179
+ else:
1180
+ t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
1181
+ inv_freq = self.inv_freq
1182
+ # Don't do einsum, it converts fp32 to fp16 under AMP
1183
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
1184
+ freqs = torch.outer(t, inv_freq)
1185
+ self._cos_cached = torch.cos(freqs).to(dtype)
1186
+ self._sin_cached = torch.sin(freqs).to(dtype)
1187
+
1188
+ def forward(
1189
+ self,
1190
+ qkv: torch.Tensor,
1191
+ kv: Optional[torch.Tensor] = None,
1192
+ seqlen_offset: Union[int, torch.Tensor] = 0,
1193
+ max_seqlen: Optional[int] = None,
1194
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
1195
+ """
1196
+ qkv: (batch, seqlen, 3, nheads, headdim) if kv is none,
1197
+ else it's just q of shape (batch, seqlen, nheads, headdim)
1198
+ kv: (batch, seqlen, 2, nheads, headdim)
1199
+ seqlen_offset: (batch_size,) or int. Each sequence in x is shifted by this amount.
1200
+ Most commonly used in inference when we have KV cache.
1201
+ If it's a tensor of shape (batch_size,), then to update the cos / sin cache, one
1202
+ should pass in max_seqlen, which will update the cos / sin cache up to that length.
1203
+ Apply rotary embedding *inplace* to qkv and / or kv.
1204
+ """
1205
+ seqlen = qkv.shape[1]
1206
+ if seqlen > self._seq_len_cached:
1207
+ self._update_cos_sin_cache(seqlen, device=qkv.device, dtype=qkv.dtype)
1208
+ elif max_seqlen is not None:
1209
+ self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
1210
+ elif isinstance(seqlen_offset, int):
1211
+ self._update_cos_sin_cache(seqlen + seqlen_offset, device=qkv.device, dtype=qkv.dtype)
1212
+
1213
+ q_rot = apply_rotary_emb(qkv[:, :, 0], self._cos_cached, self._sin_cached, seqlen_offset, self.interleaved)
1214
+ k_rot = apply_rotary_emb(qkv[:, :, 1], self._cos_cached, self._sin_cached, seqlen_offset, self.interleaved)
1215
+ return torch.stack((q_rot, k_rot, qkv[:, :, 2]), dim=2)
1216
+
1217
+
1218
+ class NomicBertDynamicNTKRotaryEmbedding(NomicBertRotaryEmbedding):
1219
+ def __init__(self, rotary_scaling_factor, max_position_embeddings, **kwargs):
1220
+ super().__init__(**kwargs)
1221
+ self.rotary_scaling_factor = rotary_scaling_factor
1222
+ self.max_position_embeddings = max_position_embeddings
1223
+
1224
+ def _compute_inv_freq(self, base=None, device=None):
1225
+ if base is None:
1226
+ base = self.base
1227
+ return 1.0 / (base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
1228
+
1229
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
1230
+ # Reset the tables if the sequence length has changed,
1231
+ # if we're on a new device (possibly due to tracing for instance),
1232
+ # or if we're switching from inference mode to training
1233
+ if seqlen > self.max_position_embeddings:
1234
+ base = self.base * (
1235
+ (self.rotary_scaling_factor * seqlen / self.max_position_embeddings) - (self.rotary_scaling_factor - 1)
1236
+ ) ** (self.dim / (self.dim - 2))
1237
+ inv_freq = self._compute_inv_freq(base=base, device=device)
1238
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
1239
+
1240
+ if (
1241
+ seqlen > self._seq_len_cached
1242
+ or self._cos_cached is None
1243
+ or self._cos_cached.device != device
1244
+ or self._cos_cached.dtype != dtype
1245
+ or (self.training and self._cos_cached.is_inference())
1246
+ ):
1247
+ self._seq_len_cached = seqlen
1248
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
1249
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
1250
+ # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
1251
+ if self.pos_idx_in_fp32:
1252
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
1253
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
1254
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
1255
+ # cos & sin output to change significantly.
1256
+ # We want to recompute self.inv_freq if it was not loaded in fp32
1257
+ if self.inv_freq.dtype != torch.float32:
1258
+ if seqlen > self.max_position_embeddings:
1259
+ base = self.base * (
1260
+ (self.scaling_factor * seqlen / self.max_position_embeddings) - (self.scaling_factor - 1)
1261
+ ) ** (self.dim / (self.dim - 2))
1262
+ else:
1263
+ base = self.base
1264
+ inv_freq = self._compute_inv_freq(device=device, base=base)
1265
+ else:
1266
+ inv_freq = self.inv_freq
1267
+ else:
1268
+ t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
1269
+ inv_freq = self.inv_freq
1270
+ # Don't do einsum, it converts fp32 to fp16 under AMP
1271
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
1272
+ freqs = torch.outer(t, inv_freq)
1273
+ if self.scale is None:
1274
+ self._cos_cached = torch.cos(freqs).to(dtype)
1275
+ self._sin_cached = torch.sin(freqs).to(dtype)
1276
+ else:
1277
+ power = (
1278
+ torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device) - seqlen // 2
1279
+ ) / self.scale_base
1280
+ scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
1281
+ # We want the multiplication by scale to happen in fp32
1282
+ self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
1283
+ self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
1284
+ self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
1285
+ self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
1286
+
1287
+
1288
+ class NomicBertAttention(nn.Module):
1289
+ """Multi-head self-attention and cross-attention"""
1290
+
1291
+ def __init__(
1292
+ self,
1293
+ config,
1294
+ ) -> None:
1295
+ """
1296
+ num_heads_kv: can be used to toggle MQA / GQA. If None, use num_heads.
1297
+ return_residual: whether to return the input x along with the output. This is for
1298
+ performance reason: for post-norm architecture, returning the input allows us
1299
+ to fuse the backward of nn.Linear with the residual connection.
1300
+ """
1301
+ super().__init__()
1302
+ self.embed_dim = config.n_embd
1303
+ self.use_flash_attn = config.use_flash_attn
1304
+ self.fused_bias_fc = config.fused_bias_fc
1305
+
1306
+ self.num_heads = config.n_head
1307
+ self.num_heads_kv = config.num_heads_kv if getattr(config, "num_heads_kv", None) is not None else self.num_heads
1308
+ assert self.embed_dim % self.num_heads == 0, "embed_dim must be divisible by num_heads"
1309
+ self.head_dim = self.embed_dim // self.num_heads
1310
+ # we don't really support mqa / gqa for now
1311
+ qkv_dim = self.head_dim * (self.num_heads + 2 * self.num_heads_kv)
1312
+
1313
+ self.register_buffer(
1314
+ "norm_factor",
1315
+ torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32)).to(torch.get_default_dtype()),
1316
+ persistent=False,
1317
+ )
1318
+
1319
+ self.rotary_emb_dim = self.head_dim * config.rotary_emb_fraction
1320
+ if self.rotary_emb_dim > 0:
1321
+ if getattr(config, "rotary_scaling_factor", None):
1322
+ self.rotary_emb = NomicBertDynamicNTKRotaryEmbedding(
1323
+ dim=self.rotary_emb_dim,
1324
+ base=config.rotary_emb_base,
1325
+ scale_base=config.rotary_emb_scale_base,
1326
+ interleaved=config.rotary_emb_interleaved,
1327
+ rotary_scaling_factor=config.rotary_scaling_factor,
1328
+ max_position_embeddings=config.max_trained_positions,
1329
+ )
1330
+ else:
1331
+ self.rotary_emb = NomicBertRotaryEmbedding(
1332
+ dim=self.rotary_emb_dim,
1333
+ base=config.rotary_emb_base,
1334
+ scale_base=config.rotary_emb_scale_base,
1335
+ interleaved=config.rotary_emb_interleaved,
1336
+ )
1337
+ # bug in xformers: https://github.com/facebookresearch/xformers/issues/841
1338
+ # uses the head dimension instead of the sequence dimension
1339
+ self.rotary_head_dim = getattr(config, "rotary_head_dim", False)
1340
+
1341
+ self.Wqkv = nn.Linear(self.embed_dim, qkv_dim, bias=config.qkv_proj_bias)
1342
+
1343
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.qkv_proj_bias)
1344
+ self.causal = config.causal
1345
+ self.drop = nn.Dropout(config.attn_pdrop)
1346
+ self.num_prefix_tokens = max(getattr(config, "register_tokens", 1), 1)
1347
+
1348
+ def forward(
1349
+ self,
1350
+ hidden_states: torch.Tensor,
1351
+ attention_mask: Optional[torch.Tensor] = None,
1352
+ position_ids: Optional[torch.LongTensor] = None,
1353
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1354
+ output_attentions: bool = False,
1355
+ use_cache: bool = False,
1356
+ is_padded_inputs: Optional[bool] = True,
1357
+ cu_seqlens: Optional[torch.Tensor] = None,
1358
+ max_seq_len: Optional[int] = None,
1359
+ rope: Optional[torch.Tensor] = None,
1360
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1361
+
1362
+ has_layer_past = past_key_value is not None
1363
+
1364
+ if has_layer_past:
1365
+ past_key_value = past_key_value[0]
1366
+ past_len = past_key_value[1]
1367
+ else:
1368
+ past_len = 0
1369
+
1370
+ qkv = self.Wqkv(hidden_states)
1371
+ qkv = rearrange(qkv, "... (three h d) -> ... three h d", three=3, d=self.head_dim)
1372
+
1373
+ past_key_value = (past_key_value, past_len + qkv.size(1)) if use_cache else None
1374
+
1375
+ if self.rotary_emb_dim > 0:
1376
+ if self.rotary_head_dim:
1377
+ qkv = rearrange(qkv, "b s three h d -> b h three s d")
1378
+ qkv = self.rotary_emb(qkv, seqlen_offset=past_len)
1379
+
1380
+ if self.rotary_head_dim:
1381
+ qkv = rearrange(qkv, "b h three s d -> b s three h d")
1382
+ elif rope is not None:
1383
+ q, k, v = qkv.permute(0, 3, 1, 2, 4).unbind(dim=-2)
1384
+ q = torch.cat(
1385
+ [q[:, :, : self.num_prefix_tokens], apply_rot_embed_cat(q[:, :, self.num_prefix_tokens :], rope)], dim=2
1386
+ ).type_as(q)
1387
+ k = torch.cat(
1388
+ [k[:, :, : self.num_prefix_tokens], apply_rot_embed_cat(k[:, :, self.num_prefix_tokens :], rope)], dim=2
1389
+ ).type_as(q)
1390
+
1391
+ qkv = torch.stack([q, k, v], dim=-2)
1392
+ qkv = rearrange(qkv, "b h s three d -> b s three h d")
1393
+
1394
+ query, key, value = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
1395
+
1396
+ query = query.permute(0, 2, 1, 3)
1397
+ key = key.permute(0, 2, 1, 3)
1398
+ value = value.permute(0, 2, 1, 3)
1399
+ if scaled_dot_product_attention is not None:
1400
+ attn_output = F.scaled_dot_product_attention(
1401
+ query, key, value, attn_mask=attention_mask, dropout_p=self.drop.p, is_causal=False
1402
+ )
1403
+ else:
1404
+ attention_scores = torch.matmul(query, key.transpose(-1, -2)) / self.norm_factor
1405
+ if attention_mask is not None:
1406
+ attention_scores = attention_scores + attention_mask
1407
+
1408
+ attentions_probs = F.softmax(attention_scores, dim=-1)
1409
+ attentions_probs = self.drop(attentions_probs)
1410
+
1411
+ attn_output = torch.matmul(attentions_probs, value)
1412
+
1413
+ attn_output = rearrange(attn_output.permute(0, 2, 1, 3), "... h d -> ... (h d)")
1414
+
1415
+ attn_output = self.out_proj(attn_output)
1416
+
1417
+ return attn_output
1418
+
1419
+
1420
+ class NomicBertBlock(NomicBertPreTrainedModel):
1421
+ def __init__(
1422
+ self,
1423
+ config,
1424
+ ):
1425
+ super().__init__(config=config)
1426
+ self.prenorm = config.prenorm
1427
+ self.fused_dropout_add_ln = config.fused_dropout_add_ln
1428
+
1429
+ self.attn = NomicBertAttention(config)
1430
+ activation = (
1431
+ F.sigmoid
1432
+ if config.activation_function == "glu"
1433
+ else (F.silu if config.activation_function == "swiglu" else F.gelu)
1434
+ )
1435
+ if config.activation_function in ["glu", "swiglu", "geglu"]:
1436
+ self.mlp = NomciBertGatedMLP(
1437
+ config.n_embd,
1438
+ hidden_features=config.n_inner,
1439
+ bias1=config.mlp_fc1_bias,
1440
+ bias2=config.mlp_fc2_bias,
1441
+ activation=activation,
1442
+ fused_bias_fc=config.fused_bias_fc,
1443
+ norm_layer=getattr(config, "norm_mlp", False),
1444
+ )
1445
+ else:
1446
+ self.mlp = NomicBertMLP(
1447
+ config.n_embd,
1448
+ hidden_features=config.n_inner,
1449
+ bias1=config.mlp_fc1_bias,
1450
+ bias2=config.mlp_fc2_bias,
1451
+ activation=activation,
1452
+ fused_bias_fc=config.fused_bias_fc,
1453
+ )
1454
+
1455
+ self.dropout1 = nn.Dropout(config.resid_pdrop)
1456
+ self.norm1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
1457
+ self.norm2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
1458
+ self.dropout2 = nn.Dropout(config.resid_pdrop)
1459
+
1460
+ def forward(
1461
+ self,
1462
+ hidden_states: torch.Tensor,
1463
+ hidden_states2: torch.Tensor,
1464
+ residual: Optional[torch.Tensor] = None,
1465
+ attention_mask: Optional[torch.Tensor] = None,
1466
+ position_ids: Optional[torch.LongTensor] = None,
1467
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1468
+ is_padded_inputs: Optional[bool] = True,
1469
+ output_attentions: Optional[bool] = False,
1470
+ use_cache: Optional[bool] = False,
1471
+ cu_seqlens: Optional[torch.Tensor] = None,
1472
+ max_seq_len: Optional[int] = None,
1473
+ rope: Optional[torch.Tensor] = None,
1474
+ ):
1475
+ r"""Pass the input through the encoder layer.
1476
+
1477
+ Args:
1478
+ hidden_states: the sequence to the encoder layer (required).
1479
+ residual: if postnorm, residual=None, If prenorm, hidden_states = Attn/MLP(LN(residual))
1480
+ mixer_subset: for cross-attention only. If not None, will take a subset of x
1481
+ before applying the query projection. Useful for e.g., ViT where we only care
1482
+ about the CLS token in the last layer.
1483
+ """
1484
+ if self.prenorm:
1485
+ dropped = self.dropout1(hidden_states)
1486
+ residual = (dropped + residual) if residual is not None else dropped
1487
+ hidden_states = self.norm1(residual.to(dtype=self.norm1.weight.dtype))
1488
+ hidden_states = self.attn(
1489
+ hidden_states,
1490
+ attention_mask=attention_mask,
1491
+ is_padded_inputs=is_padded_inputs,
1492
+ cu_seqlens=cu_seqlens,
1493
+ max_seq_len=max_seq_len,
1494
+ rope=rope,
1495
+ )
1496
+
1497
+ dropped = self.dropout2(hidden_states)
1498
+ residual = (dropped + residual) if residual is not None else dropped
1499
+ hidden_states = self.norm2(residual.to(dtype=self.norm2.weight.dtype))
1500
+ hidden_states = self.mlp(hidden_states)
1501
+
1502
+ return hidden_states, None, residual
1503
+ else:
1504
+ assert residual is None
1505
+ attn_outputs = self.attn(
1506
+ hidden_states,
1507
+ attention_mask=attention_mask,
1508
+ is_padded_inputs=is_padded_inputs,
1509
+ cu_seqlens=cu_seqlens,
1510
+ max_seq_len=max_seq_len,
1511
+ rope=rope,
1512
+ )
1513
+ hidden_states = self.norm1((self.dropout1(attn_outputs) + hidden_states).to(dtype=self.norm1.weight.dtype))
1514
+ mlp_out = self.mlp(hidden_states)
1515
+
1516
+ hidden_states = self.norm2((self.dropout2(mlp_out) + hidden_states).to(dtype=self.norm2.weight.dtype))
1517
+ return hidden_states, None, None
1518
+
1519
+
1520
+ class NomicBertEncoder(nn.Module):
1521
+ def __init__(self, config: GPT2Config):
1522
+ super().__init__()
1523
+ self.layers = nn.ModuleList([NomicBertBlock(config) for _ in range(config.n_layer)])
1524
+ self.gradient_checkpointing = False
1525
+ self.config = config
1526
+
1527
+ def forward(
1528
+ self,
1529
+ hidden_states: torch.LongTensor = None,
1530
+ attention_mask: Optional[torch.Tensor] = None,
1531
+ position_ids: Optional[torch.LongTensor] = None,
1532
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1533
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1534
+ use_cache: Optional[bool] = None,
1535
+ output_attentions: Optional[bool] = None,
1536
+ output_hidden_states: Optional[bool] = None,
1537
+ return_dict: Optional[bool] = None,
1538
+ is_padded_inputs: Optional[bool] = True,
1539
+ rope: Optional[torch.Tensor] = None,
1540
+ ):
1541
+ """If subset_mask is not None, we only want output for the subset of the sequence.
1542
+ This means that we only compute the last layer output for these tokens.
1543
+ subset_mask: (batch, seqlen), dtype=torch.bool
1544
+ """
1545
+ hidden_states2 = None
1546
+ residual = None
1547
+
1548
+ for _, layer in enumerate(self.layers):
1549
+ if self.gradient_checkpointing and self.training:
1550
+
1551
+ def create_custom_forward(module):
1552
+ def custom_forward(*inputs):
1553
+ # None for past_key_value
1554
+ return module(*inputs)
1555
+
1556
+ return custom_forward
1557
+
1558
+ hidden_states, hidden_states2, residual = torch.utils.checkpoint.checkpoint(
1559
+ create_custom_forward(layer),
1560
+ hidden_states,
1561
+ hidden_states2,
1562
+ residual,
1563
+ attention_mask,
1564
+ position_ids,
1565
+ past_key_values,
1566
+ is_padded_inputs,
1567
+ output_attentions,
1568
+ use_cache,
1569
+ None,
1570
+ None,
1571
+ rope,
1572
+ # if you freeze ANY layers, you need `use_reentrant=False`
1573
+ # https://github.com/huggingface/transformers/issues/21381
1574
+ # https://discuss.pytorch.org/t/checkpoint-with-no-grad-requiring-inputs-problem/19117/7
1575
+ use_reentrant=False,
1576
+ )
1577
+
1578
+ else:
1579
+ hidden_states, hidden_states2, residual = layer(
1580
+ hidden_states,
1581
+ hidden_states2,
1582
+ residual,
1583
+ attention_mask,
1584
+ position_ids,
1585
+ None,
1586
+ is_padded_inputs,
1587
+ output_attentions,
1588
+ use_cache,
1589
+ rope=rope,
1590
+ )
1591
+ return hidden_states
1592
+
1593
+
1594
+ class NomicBertPooler(nn.Module):
1595
+ def __init__(self, config):
1596
+ super().__init__()
1597
+ self.dense = nn.Linear(config.n_embd, config.n_embd)
1598
+ self.activation = nn.Tanh()
1599
+
1600
+ def forward(self, hidden_states, pool=True):
1601
+ # We "pool" the model by simply taking the hidden state corresponding
1602
+ # to the first token.
1603
+ first_token_tensor = hidden_states[:, 0] if pool else hidden_states
1604
+ pooled_output = self.dense(first_token_tensor)
1605
+ pooled_output = self.activation(pooled_output)
1606
+ return pooled_output
1607
+
1608
+
1609
+ class NomicBertPredictionHeadTransform(nn.Module):
1610
+ def __init__(self, config):
1611
+ super().__init__()
1612
+ self.dense = nn.Linear(config.n_embd, config.n_embd, bias=config.mlp_fc1_bias)
1613
+ approximate = "tanh" if config.activation_function in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"] else "none"
1614
+ if config.activation_function == "swiglu":
1615
+ self.transform_act_fn = F.silu
1616
+ else:
1617
+ self.transform_act_fn = nn.GELU(approximate=approximate)
1618
+
1619
+ self.layer_norm = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
1620
+
1621
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1622
+ hidden_states = self.dense(hidden_states)
1623
+ hidden_states = self.transform_act_fn(hidden_states)
1624
+ hidden_states = self.layer_norm(hidden_states)
1625
+
1626
+ return hidden_states
1627
+
1628
+
1629
+ class NomicBertLMPredictionHead(nn.Module):
1630
+ def __init__(self, config):
1631
+ super().__init__()
1632
+
1633
+ self.transform = NomicBertPredictionHeadTransform(config)
1634
+
1635
+ self.decoder = nn.Linear(config.n_embd, config.vocab_size, bias=config.mlp_fc1_bias)
1636
+
1637
+ def forward(self, hidden_states):
1638
+ hidden_states = self.transform(hidden_states)
1639
+ hidden_states = self.decoder(hidden_states)
1640
+ return hidden_states
1641
+
1642
+
1643
+ class NomicBertPreTrainingHeads(nn.Module):
1644
+ def __init__(self, config):
1645
+ super().__init__()
1646
+ self.predictions = NomicBertLMPredictionHead(config)
1647
+
1648
+ def forward(self, sequence_output):
1649
+ prediction_scores = self.predictions(sequence_output)
1650
+ return prediction_scores
1651
+
1652
+
1653
+ class NomicBertModel(NomicBertPreTrainedModel):
1654
+ def __init__(self, config: GPT2Config, add_pooling_layer=True):
1655
+ super().__init__(config)
1656
+ self.pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1)
1657
+ if config.vocab_size % self.pad_vocab_size_multiple != 0:
1658
+ config.vocab_size += self.pad_vocab_size_multiple - (config.vocab_size % self.pad_vocab_size_multiple)
1659
+
1660
+ assert config.activation_function in [
1661
+ "gelu",
1662
+ "gelu_new",
1663
+ "gelu_fast",
1664
+ "gelu_pytorch_tanh",
1665
+ "swiglu",
1666
+ "geglu",
1667
+ "glu",
1668
+ ]
1669
+
1670
+ self.embeddings = NomicBertEmbeddings(config)
1671
+ self.emb_drop = nn.Dropout(config.resid_pdrop)
1672
+ self.emb_ln = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
1673
+ self.encoder = NomicBertEncoder(config)
1674
+ self.pooler = NomicBertPooler(config) if add_pooling_layer else None
1675
+
1676
+ self.apply(partial(_init_weights, initializer_range=config.initializer_range))
1677
+
1678
+ def forward(
1679
+ self,
1680
+ input_ids,
1681
+ attention_mask=None,
1682
+ position_ids=None,
1683
+ token_type_ids=None,
1684
+ return_dict=None,
1685
+ matryoshka_dim=None,
1686
+ ):
1687
+ if token_type_ids is None:
1688
+ token_type_ids = torch.zeros_like(input_ids)
1689
+ hidden_states = self.embeddings(input_ids, position_ids=position_ids, token_type_ids=token_type_ids)
1690
+ hidden_states = self.emb_ln(hidden_states)
1691
+ hidden_states = self.emb_drop(hidden_states)
1692
+
1693
+ attention_mask = self.get_extended_attention_mask(attention_mask, input_ids.shape)
1694
+ sequence_output = self.encoder(hidden_states, attention_mask=attention_mask, return_dict=return_dict)
1695
+
1696
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1697
+
1698
+ if matryoshka_dim:
1699
+ sequence_output = sequence_output[:, :matryoshka_dim]
1700
+
1701
+ return BaseModelOutputWithPoolingAndCrossAttentions(
1702
+ last_hidden_state=sequence_output,
1703
+ pooler_output=pooled_output,
1704
+ )
1705
+
1706
+
1707
+ class NomicBertForPreTraining(NomicBertPreTrainedModel):
1708
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1709
+
1710
+ def __init__(self, config: GPT2Config):
1711
+ super().__init__(config)
1712
+
1713
+ self.bert = NomicBertModel(config, add_pooling_layer=getattr(config, "add_pooling_layer", False))
1714
+ self.cls = NomicBertPreTrainingHeads(config)
1715
+ self.mlm_loss = nn.CrossEntropyLoss()
1716
+
1717
+ # Initialize weights and apply final processing
1718
+ self.apply(partial(_init_weights, initializer_range=config.initializer_range))
1719
+ self.tie_weights()
1720
+
1721
+ def tie_weights(self):
1722
+ self.cls.predictions.decoder.weight = self.bert.embeddings.word_embeddings.weight
1723
+
1724
+ def forward(
1725
+ self,
1726
+ input_ids,
1727
+ position_ids=None,
1728
+ token_type_ids=None,
1729
+ attention_mask=None,
1730
+ labels=None,
1731
+ ):
1732
+ """
1733
+ If labels are provided, they must be -100 for masked out tokens (as specified in the attention
1734
+ mask).
1735
+ Outputs:
1736
+ if `labels` and `next_sentence_label` are not `None`:
1737
+ Outputs the total_loss which is the sum of the masked language modeling loss and the next
1738
+ sentence classification loss.
1739
+ if `labels` or `next_sentence_label` is `None`:
1740
+ Outputs a tuple comprising
1741
+ - the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and
1742
+ - the next sentence classification logits of shape [batch_size, 2].
1743
+
1744
+ """
1745
+ outputs = self.bert(
1746
+ input_ids,
1747
+ position_ids=position_ids,
1748
+ token_type_ids=token_type_ids,
1749
+ attention_mask=attention_mask.bool() if attention_mask is not None else None,
1750
+ )
1751
+ sequence_output, _ = outputs.last_hidden_state, outputs.pooler_output
1752
+
1753
+ prediction_scores = self.cls(sequence_output)
1754
+
1755
+ total_loss = None
1756
+ if labels is not None:
1757
+ masked_lm_loss = self.mlm_loss(
1758
+ rearrange(prediction_scores, "... v -> (...) v"),
1759
+ rearrange(labels, "... -> (...)"),
1760
+ )
1761
+ total_loss = masked_lm_loss.float()
1762
+
1763
+ return MaskedLMOutput(
1764
+ loss=total_loss,
1765
+ logits=prediction_scores,
1766
+ hidden_states=outputs.hidden_states,
1767
+ attentions=None,
1768
+ )
1769
+
1770
+
1771
+ class NomicBertForSequenceClassification(NomicBertPreTrainedModel):
1772
+ def __init__(self, config):
1773
+ super().__init__(config)
1774
+ self.num_labels = config.num_labels
1775
+ self.config = config
1776
+
1777
+ self.bert = NomicBertModel(config)
1778
+ classifier_dropout = getattr(config, "classifier_dropout", config.embd_pdrop)
1779
+ self.dropout = nn.Dropout(classifier_dropout)
1780
+ self.classifier = nn.Linear(config.n_embd, config.num_labels)
1781
+
1782
+ # Initialize weights and apply final processing
1783
+ self.post_init()
1784
+
1785
+ def forward(
1786
+ self,
1787
+ input_ids: Optional[torch.Tensor] = None,
1788
+ attention_mask: Optional[torch.Tensor] = None,
1789
+ token_type_ids: Optional[torch.Tensor] = None,
1790
+ position_ids: Optional[torch.Tensor] = None,
1791
+ head_mask: Optional[torch.Tensor] = None,
1792
+ inputs_embeds: Optional[torch.Tensor] = None,
1793
+ labels: Optional[torch.Tensor] = None,
1794
+ output_attentions: Optional[bool] = None,
1795
+ output_hidden_states: Optional[bool] = None,
1796
+ return_dict: Optional[bool] = None,
1797
+ ):
1798
+ r"""
1799
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1800
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1801
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1802
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1803
+ """
1804
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1805
+ outputs = self.bert(
1806
+ input_ids,
1807
+ position_ids=position_ids,
1808
+ token_type_ids=token_type_ids,
1809
+ attention_mask=attention_mask.bool() if attention_mask is not None else None,
1810
+ )
1811
+
1812
+ pooled_output = outputs[1]
1813
+
1814
+ pooled_output = self.dropout(pooled_output)
1815
+ logits = self.classifier(pooled_output)
1816
+
1817
+ loss = None
1818
+ if labels is not None:
1819
+ if self.config.problem_type is None:
1820
+ if self.num_labels == 1:
1821
+ self.config.problem_type = "regression"
1822
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1823
+ self.config.problem_type = "single_label_classification"
1824
+ else:
1825
+ self.config.problem_type = "multi_label_classification"
1826
+
1827
+ if self.config.problem_type == "regression":
1828
+ loss_fct = nn.MSELoss()
1829
+ if self.num_labels == 1:
1830
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1831
+ else:
1832
+ loss = loss_fct(logits, labels)
1833
+ elif self.config.problem_type == "single_label_classification":
1834
+ loss_fct = nn.CrossEntropyLoss()
1835
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1836
+ elif self.config.problem_type == "multi_label_classification":
1837
+ loss_fct = nn.BCEWithLogitsLoss()
1838
+ loss = loss_fct(logits, labels)
1839
+ if not return_dict:
1840
+ output = (logits,) + outputs[2:]
1841
+ return ((loss,) + output) if loss is not None else output
1842
+
1843
+ return SequenceClassifierOutput(
1844
+ loss=loss,
1845
+ logits=logits,
1846
+ hidden_states=outputs.hidden_states,
1847
+ attentions=outputs.attentions,
1848
+ )
1849
+
1850
+
1851
+ def hf_vit_config_to_vit_config(vit_config: ViTConfig) -> GPT2Config:
1852
+ return GPT2Config(
1853
+ n_embd=vit_config.hidden_size,
1854
+ n_layer=vit_config.num_hidden_layers,
1855
+ n_head=vit_config.num_attention_heads,
1856
+ n_inner=vit_config.intermediate_size,
1857
+ activation_function=vit_config.hidden_act,
1858
+ vocab_size=0, # no vocab since using patches
1859
+ n_positions=0, # No absolute position embedding
1860
+ resid_pdrop=0.0, # No dropout
1861
+ embd_pdrop=getattr(vit_config, "dropout", 0.0),
1862
+ attn_pdrop=vit_config.attention_probs_dropout_prob,
1863
+ layer_norm_epsilon=vit_config.layer_norm_eps,
1864
+ initializer_range=vit_config.initializer_range,
1865
+ bos_token_id=None,
1866
+ eos_token_id=None,
1867
+ # These are new arguments not in the original GPT2Config
1868
+ drop_path_rate=0.0,
1869
+ # Why is there double layer norm??
1870
+ prepre_layernom=False,
1871
+ layer_scale=False,
1872
+ layer_scale_init=None,
1873
+ img_size=vit_config.image_size,
1874
+ patch_size=vit_config.patch_size,
1875
+ num_channels=vit_config.num_channels,
1876
+ prenorm=True,
1877
+ parallel_block=False,
1878
+ parallel_block_tied_norm=False,
1879
+ rotary_emb_fraction=0,
1880
+ tie_word_embeddings=False,
1881
+ fused_dropout_add_ln=True,
1882
+ fused_bias_fc=True,
1883
+ patch_embed_bias=True,
1884
+ use_flash_attn=True,
1885
+ qkv_proj_bias=True,
1886
+ mlp_fc1_bias=getattr(vit_config, "mlp_fc1_bias", True),
1887
+ mlp_fc2_bias=getattr(vit_config, "mlp_fc2_bias", True),
1888
+ use_rms_norm=False,
1889
+ causal=False,
1890
+ hidden_features_scaling_factor=1.0,
1891
+ mask_token=False,
1892
+ learned_pos_embedding=False,
1893
+ patch_dropout=0,
1894
+ sinusoidal_pos_embedding=vit_config.model_type == "vit_mae",
1895
+ )
1896
+
1897
+
1898
+ class NomicAttentionPooling(nn.Module):
1899
+ def __init__(self, config):
1900
+ super().__init__()
1901
+ self.embed_dim = config.n_embd
1902
+ self.use_flash_attn = config.use_flash_attn
1903
+ self.fused_bias_fc = config.fused_bias_fc
1904
+
1905
+ self.num_heads = config.n_head
1906
+ self.num_heads_kv = config.num_heads_kv if getattr(config, "num_heads_kv", None) is not None else self.num_heads
1907
+ assert self.embed_dim % self.num_heads == 0, "embed_dim must be divisible by num_heads"
1908
+ self.head_dim = self.embed_dim // self.num_heads
1909
+ # we don't really support mqa / gqa for now
1910
+ kv_dim = 2 * self.head_dim * self.num_heads_kv
1911
+
1912
+ self.register_buffer(
1913
+ "norm_factor",
1914
+ torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32)).to(torch.get_default_dtype()),
1915
+ persistent=False,
1916
+ )
1917
+
1918
+ self.Wq = nn.Linear(self.embed_dim, self.embed_dim, bias=config.qkv_proj_bias)
1919
+ self.Wkv = nn.Linear(self.embed_dim, kv_dim, bias=config.qkv_proj_bias)
1920
+
1921
+ self.latent = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
1922
+
1923
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.qkv_proj_bias)
1924
+ self.causal = config.causal
1925
+ self.drop = nn.Dropout(config.attn_pdrop)
1926
+
1927
+ def init_weights(self):
1928
+ trunc_normal_tf_(self.latent, std=self.embed_dim**-0.5)
1929
+
1930
+ def forward(
1931
+ self,
1932
+ kv,
1933
+ attention_mask=None,
1934
+ cu_seqlens_k=None,
1935
+ max_seqlen_k=None,
1936
+ is_padded_inputs: Optional[bool] = True,
1937
+ output_attentions: bool = False,
1938
+ ):
1939
+ """Implements the multihead softmax attention.
1940
+ Arguments
1941
+ ---------
1942
+ q: The tensor containing the query. (B, Sq, H, D)
1943
+ kv: The tensor containing the key and value. (B, Sk, 2, H_k, D)
1944
+ causal: if passed, will override self.causal
1945
+ cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths
1946
+ of the sequences in the batch, used to index into q.
1947
+ max_seqlen: int. Maximum sequence length in the batch of q.
1948
+ cu_seqlens_k: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths
1949
+ of the sequences in the batch, used to index into kv.
1950
+ max_seqlen_k: int. Maximum sequence length in the batch of k and v.
1951
+ """
1952
+ q_latent = self.latent.expand(kv.size(0), -1, -1)
1953
+ q = self.Wq(q_latent)
1954
+ bsz, q_len, h_size = q.shape
1955
+ kv = self.Wkv(kv)
1956
+ query = rearrange(q, "... (h d) -> ... h d", d=self.head_dim)
1957
+ kv = rearrange(kv, "... (two hkv d) -> ... two hkv d", two=2, d=self.head_dim)
1958
+
1959
+ key, value = kv[:, :, 0], kv[:, :, 1]
1960
+
1961
+ query = query.permute(0, 2, 1, 3)
1962
+ key = key.permute(0, 2, 1, 3)
1963
+ value = value.permute(0, 2, 1, 3)
1964
+
1965
+ attention_scores = torch.matmul(query, key.transpose(-1, -2)) / self.norm_factor
1966
+ if attention_mask is not None:
1967
+ attention_scores = attention_scores + attention_mask
1968
+
1969
+ attentions_probs = F.softmax(attention_scores, dim=-1)
1970
+ attentions_probs = self.drop(attentions_probs)
1971
+
1972
+ attn_output = torch.matmul(attentions_probs, value)
1973
+ attn_output = rearrange(attn_output.permute(0, 2, 1, 3), "... h d -> ... (h d)")
1974
+
1975
+ attn_output = self.out_proj(attn_output)
1976
+
1977
+ return attn_output
1978
+
1979
+
1980
+ class NomicMultiHeadAttentionPooling(nn.Module):
1981
+ def __init__(
1982
+ self,
1983
+ config,
1984
+ ):
1985
+ super().__init__()
1986
+ self.prenorm = config.prenorm
1987
+ self.fused_dropout_add_ln = config.fused_dropout_add_ln
1988
+
1989
+ self.attn = NomicAttentionPooling(config)
1990
+ activation = (
1991
+ F.sigmoid
1992
+ if config.activation_function == "glu"
1993
+ else (F.silu if config.activation_function == "swiglu" else F.gelu)
1994
+ )
1995
+ if config.activation_function in ["glu", "swiglu", "geglu"]:
1996
+ self.mlp = NomciBertGatedMLP(
1997
+ config.n_embd,
1998
+ hidden_features=config.n_inner,
1999
+ bias1=config.mlp_fc1_bias,
2000
+ bias2=config.mlp_fc2_bias,
2001
+ activation=activation,
2002
+ fused_bias_fc=config.fused_bias_fc,
2003
+ )
2004
+ else:
2005
+ self.mlp = NomicBertMLP(
2006
+ config.n_embd,
2007
+ hidden_features=config.n_inner,
2008
+ bias1=config.mlp_fc1_bias,
2009
+ bias2=config.mlp_fc2_bias,
2010
+ activation=activation,
2011
+ fused_bias_fc=config.fused_bias_fc,
2012
+ )
2013
+
2014
+ self.dropout1 = nn.Dropout(config.resid_pdrop)
2015
+ self.norm1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
2016
+ self.dropout2 = nn.Dropout(config.resid_pdrop)
2017
+
2018
+ def forward(
2019
+ self,
2020
+ hidden_states: torch.Tensor,
2021
+ attention_mask: Optional[torch.Tensor] = None,
2022
+ ):
2023
+ r"""Pass the input through the encoder layer.
2024
+
2025
+ Args:
2026
+ hidden_states: the sequence to the encoder layer (required).
2027
+ residual: if postnorm, residual=None, If prenorm, hidden_states = Attn/MLP(LN(residual))
2028
+ mixer_subset: for cross-attention only. If not None, will take a subset of x
2029
+ before applying the query projection. Useful for e.g., ViT where we only care
2030
+ about the CLS token in the last layer.
2031
+ """
2032
+
2033
+ attn_outputs = self.attn(
2034
+ hidden_states,
2035
+ attention_mask=attention_mask,
2036
+ )
2037
+
2038
+ normed = self.norm1(attn_outputs)
2039
+ hidden_states = hidden_states + self.mlp(normed)
2040
+
2041
+ return hidden_states
2042
+
2043
+
2044
+ class NomicVisionPreTrainedModel(PreTrainedModel):
2045
+ """An abstract class to handle weights initialization and
2046
+ a simple interface for dowloading and loading pretrained models.
2047
+ """
2048
+
2049
+ config_class = NomicBertConfig
2050
+ base_model_prefix = "model"
2051
+ supports_gradient_checkpointing = True
2052
+ _no_split_modules = ["Block"]
2053
+ _skip_keys_device_placement = "past_key_values"
2054
+
2055
+ def __init__(self, config, *inputs, **kwargs):
2056
+ super().__init__(config)
2057
+ if not isinstance(config, GPT2Config):
2058
+ raise ValueError(
2059
+ "Parameter config in `{}(config)` should be an instance of class `GPT2Config`. "
2060
+ "To create a model from a Google pretrained model use "
2061
+ "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format(
2062
+ self.__class__.__name__, self.__class__.__name__
2063
+ )
2064
+ )
2065
+ self.config = config
2066
+
2067
+
2068
+ class NomicVisionModel(NomicVisionPreTrainedModel):
2069
+ def __init__(self, config):
2070
+ super().__init__(config)
2071
+
2072
+ self.embeddings = NomicVisionPatchEmbeddings(config)
2073
+ self.layers = nn.ModuleList([NomicBertBlock(config) for _ in range(config.n_layer)])
2074
+
2075
+ self.selector = NomicMultiHeadAttentionPooling(config)
2076
+
2077
+ self.global_pool = getattr(config, "global_pool", None)
2078
+ self.num_prefix_tokens = (1 if not getattr(config, "no_cls_token", False) else 0) + getattr(
2079
+ config, "register_tokens", 0
2080
+ )
2081
+
2082
+ self.apply(partial(_init_weights, initializer_range=config.initializer_range))
2083
+
2084
+ def forward(
2085
+ self,
2086
+ pixel_values,
2087
+ attention_mask=None,
2088
+ position_ids=None,
2089
+ token_type_ids=None,
2090
+ return_dict=None,
2091
+ matryoshka_dim=None,
2092
+ ):
2093
+ embeddings, rope = self.embeddings(pixel_values)
2094
+
2095
+ original_dtype = embeddings.dtype
2096
+
2097
+ hidden_states = embeddings
2098
+ # unused but easier to pass to gradient checkpointing as words
2099
+ residual = None
2100
+ for layer in self.layers:
2101
+ # need to pass none for backwards compatability
2102
+ hidden_states, _, residual = layer(
2103
+ hidden_states, None, residual=residual, is_padded_inputs=False, rope=rope
2104
+ )
2105
+
2106
+ hidden_states = hidden_states + residual
2107
+ if self.global_pool == "avg":
2108
+ hidden_states = hidden_states[:, self.num_prefix_tokens :].mean(dim=1)
2109
+
2110
+ pooled_output = self.selector(hidden_states)
2111
+
2112
+ return BaseModelOutputWithPast(
2113
+ last_hidden_state=pooled_output,
2114
+ hidden_states=hidden_states,
2115
+ )