Sentence Similarity
Transformers
Safetensors
English
mistral
feature-extraction
text-embedding
embeddings
information-retrieval
beir
text-classification
language-model
text-clustering
text-semantic-similarity
text-evaluation
text-reranking
Sentence Similarity
natural_questions
ms_marco
fever
hotpot_qa
mteb
custom_code
text-generation-inference
text-embeddings-inference
Inference Endpoints
Create modeling_mistral_encoder.py
Browse files- modeling_mistral_encoder.py +277 -0
modeling_mistral_encoder.py
ADDED
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List, Optional, Tuple, Union
|
2 |
+
import torch
|
3 |
+
import torch.multiprocessing as mp
|
4 |
+
|
5 |
+
from transformers import MistralModel, MistralPreTrainedModel, MistralConfig
|
6 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
7 |
+
from transformers.cache_utils import Cache, DynamicCache
|
8 |
+
from transformers.models.mistral.modeling_mistral import MistralDecoderLayer, MistralRMSNorm, MistralAttention, MistralFlashAttention2, MistralSdpaAttention, MistralMLP
|
9 |
+
from torch import Tensor, nn, device
|
10 |
+
from transformers.utils import logging
|
11 |
+
|
12 |
+
from .attn_mask_utils import _prepare_4d_causal_attention_mask
|
13 |
+
|
14 |
+
logger = logging.get_logger(__name__)
|
15 |
+
|
16 |
+
def batch_to_device(batch, target_device: device):
|
17 |
+
"""
|
18 |
+
send a pytorch batch to a device (CPU/GPU)
|
19 |
+
"""
|
20 |
+
for key in batch:
|
21 |
+
if isinstance(batch[key], Tensor):
|
22 |
+
batch[key] = batch[key].to(target_device)
|
23 |
+
return batch
|
24 |
+
|
25 |
+
class ModifiedMistralAttention(MistralAttention):
|
26 |
+
|
27 |
+
def __init__(self, *args, **kwargs):
|
28 |
+
super().__init__(*args, **kwargs)
|
29 |
+
self.is_causal = False
|
30 |
+
|
31 |
+
|
32 |
+
class ModifiedMistralFlashAttention2(MistralFlashAttention2):
|
33 |
+
|
34 |
+
def __init__(self, *args, **kwargs):
|
35 |
+
super().__init__(*args, **kwargs)
|
36 |
+
self.is_causal = False
|
37 |
+
|
38 |
+
|
39 |
+
class ModifiedMistralSdpaAttention(MistralSdpaAttention):
|
40 |
+
|
41 |
+
def __init__(self, *args, **kwargs):
|
42 |
+
super().__init__(*args, **kwargs)
|
43 |
+
self.is_causal = False
|
44 |
+
|
45 |
+
|
46 |
+
MISTRAL_ATTENTION_CLASSES = {
|
47 |
+
"eager": ModifiedMistralAttention,
|
48 |
+
"flash_attention_2": ModifiedMistralFlashAttention2,
|
49 |
+
"sdpa": ModifiedMistralSdpaAttention,
|
50 |
+
}
|
51 |
+
|
52 |
+
class ModifiedMistralDecoderLayer(MistralDecoderLayer):
|
53 |
+
def __init__(self, config: MistralConfig, layer_idx: int):
|
54 |
+
nn.Module.__init__(self)
|
55 |
+
self.hidden_size = config.hidden_size
|
56 |
+
|
57 |
+
self.self_attn = MISTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
|
58 |
+
|
59 |
+
self.mlp = MistralMLP(config)
|
60 |
+
self.input_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
61 |
+
self.post_attention_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
62 |
+
|
63 |
+
|
64 |
+
class MistralEncoderModel(MistralModel):
|
65 |
+
def __init__(self, config: MistralConfig):
|
66 |
+
MistralPreTrainedModel.__init__(self, config)
|
67 |
+
self.padding_idx = config.pad_token_id
|
68 |
+
self.vocab_size = config.vocab_size
|
69 |
+
|
70 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
71 |
+
self.layers = nn.ModuleList(
|
72 |
+
[ModifiedMistralDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
73 |
+
)
|
74 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
75 |
+
self.norm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
76 |
+
|
77 |
+
# sliding window is not supported for non-causal attention
|
78 |
+
if not self._use_flash_attention_2:
|
79 |
+
self.config.sliding_window = None
|
80 |
+
|
81 |
+
self.gradient_checkpointing = False
|
82 |
+
# Initialize weights and apply final processing
|
83 |
+
self.post_init()
|
84 |
+
|
85 |
+
def forward(
|
86 |
+
self,
|
87 |
+
input_ids: torch.LongTensor = None,
|
88 |
+
attention_mask: Optional[torch.Tensor] = None,
|
89 |
+
position_ids: Optional[torch.LongTensor] = None,
|
90 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
91 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
92 |
+
use_cache: Optional[bool] = None,
|
93 |
+
output_attentions: Optional[bool] = None,
|
94 |
+
output_hidden_states: Optional[bool] = None,
|
95 |
+
return_dict: Optional[bool] = None,
|
96 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
97 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
98 |
+
output_hidden_states = (
|
99 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
100 |
+
)
|
101 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
102 |
+
|
103 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
104 |
+
|
105 |
+
# retrieve input_ids and inputs_embeds
|
106 |
+
if input_ids is not None and inputs_embeds is not None:
|
107 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
108 |
+
elif input_ids is not None:
|
109 |
+
batch_size, seq_length = input_ids.shape
|
110 |
+
elif inputs_embeds is not None:
|
111 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
112 |
+
else:
|
113 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
114 |
+
|
115 |
+
if self.gradient_checkpointing and self.training:
|
116 |
+
if use_cache:
|
117 |
+
logger.warning_once(
|
118 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
119 |
+
)
|
120 |
+
use_cache = False
|
121 |
+
|
122 |
+
past_key_values_length = 0
|
123 |
+
|
124 |
+
if use_cache:
|
125 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
126 |
+
if use_legacy_cache:
|
127 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
128 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
129 |
+
|
130 |
+
if position_ids is None:
|
131 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
132 |
+
position_ids = torch.arange(
|
133 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
134 |
+
)
|
135 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
136 |
+
else:
|
137 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
138 |
+
|
139 |
+
if inputs_embeds is None:
|
140 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
141 |
+
|
142 |
+
if attention_mask is not None and self._use_flash_attention_2 and use_cache:
|
143 |
+
is_padding_right = attention_mask[:, -1].sum().item() != batch_size
|
144 |
+
if is_padding_right:
|
145 |
+
raise ValueError(
|
146 |
+
"You are attempting to perform batched generation with padding_side='right'"
|
147 |
+
" this may lead to unexpected behaviour for Flash Attention version of Mistral. Make sure to "
|
148 |
+
" call `tokenizer.padding_side = 'left'` before tokenizing the input. "
|
149 |
+
)
|
150 |
+
|
151 |
+
if self._use_flash_attention_2:
|
152 |
+
# 2d mask is passed through the layers
|
153 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
154 |
+
else:
|
155 |
+
# 4d mask is passed through the layers
|
156 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
157 |
+
attention_mask,
|
158 |
+
(batch_size, seq_length),
|
159 |
+
inputs_embeds,
|
160 |
+
past_key_values_length,
|
161 |
+
sliding_window=self.config.sliding_window,
|
162 |
+
)
|
163 |
+
|
164 |
+
hidden_states = inputs_embeds
|
165 |
+
|
166 |
+
# decoder layers
|
167 |
+
all_hidden_states = () if output_hidden_states else None
|
168 |
+
all_self_attns = () if output_attentions else None
|
169 |
+
next_decoder_cache = None
|
170 |
+
|
171 |
+
for decoder_layer in self.layers:
|
172 |
+
if output_hidden_states:
|
173 |
+
all_hidden_states += (hidden_states,)
|
174 |
+
|
175 |
+
if self.gradient_checkpointing and self.training:
|
176 |
+
layer_outputs = self._gradient_checkpointing_func(
|
177 |
+
decoder_layer.__call__,
|
178 |
+
hidden_states,
|
179 |
+
attention_mask,
|
180 |
+
position_ids,
|
181 |
+
past_key_values,
|
182 |
+
output_attentions,
|
183 |
+
use_cache,
|
184 |
+
)
|
185 |
+
else:
|
186 |
+
layer_outputs = decoder_layer(
|
187 |
+
hidden_states,
|
188 |
+
attention_mask=attention_mask,
|
189 |
+
position_ids=position_ids,
|
190 |
+
past_key_value=past_key_values,
|
191 |
+
output_attentions=output_attentions,
|
192 |
+
use_cache=use_cache,
|
193 |
+
)
|
194 |
+
|
195 |
+
hidden_states = layer_outputs[0]
|
196 |
+
|
197 |
+
if use_cache:
|
198 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
199 |
+
|
200 |
+
if output_attentions:
|
201 |
+
all_self_attns += (layer_outputs[1],)
|
202 |
+
|
203 |
+
hidden_states = self.norm(hidden_states)
|
204 |
+
|
205 |
+
# add hidden states from the last decoder layer
|
206 |
+
if output_hidden_states:
|
207 |
+
all_hidden_states += (hidden_states,)
|
208 |
+
|
209 |
+
next_cache = None
|
210 |
+
if use_cache:
|
211 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
212 |
+
|
213 |
+
if not return_dict:
|
214 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
215 |
+
return BaseModelOutputWithPast(
|
216 |
+
last_hidden_state=hidden_states,
|
217 |
+
past_key_values=next_cache,
|
218 |
+
hidden_states=all_hidden_states,
|
219 |
+
attentions=all_self_attns,
|
220 |
+
)
|
221 |
+
|
222 |
+
def prepare_for_tokenization(self, text):
|
223 |
+
|
224 |
+
text = '[INST] ' + text.strip() + ' [/INST]'
|
225 |
+
# if self.pooling_mode == "eos_token":
|
226 |
+
# text = text.strip() + ' </s>'
|
227 |
+
return text
|
228 |
+
|
229 |
+
def tokenize(self, texts):
|
230 |
+
# return self.tokenizer(texts, return_tensors='pt', padding=True, truncation=True, max_length=self.max_length)
|
231 |
+
|
232 |
+
texts_2 = []
|
233 |
+
original_texts = []
|
234 |
+
for text in texts:
|
235 |
+
t = text.split("!@#$%^&*()")
|
236 |
+
texts_2.append(t[1])
|
237 |
+
original_texts.append("".join(t))
|
238 |
+
|
239 |
+
original = self.tokenizer(original_texts, return_tensors='pt', padding=True, truncation=True, max_length=self.max_length)
|
240 |
+
embed_mask = None
|
241 |
+
for t_i, t in enumerate(texts_2):
|
242 |
+
ids = self.tokenizer([t], return_tensors='pt', padding=True, truncation=True, max_length=self.max_length, add_special_tokens=False)
|
243 |
+
if embed_mask is None:
|
244 |
+
e_m = torch.zeros_like(original["attention_mask"][t_i])
|
245 |
+
if len(ids["input_ids"][0]) > 0:
|
246 |
+
e_m[-len(ids["input_ids"][0]):] = torch.ones(len(ids["input_ids"][0]))
|
247 |
+
embed_mask = e_m.unsqueeze(0)
|
248 |
+
else:
|
249 |
+
e_m = torch.zeros_like(original["attention_mask"][t_i])
|
250 |
+
if len(ids["input_ids"][0]) > 0:
|
251 |
+
e_m[-len(ids["input_ids"][0]):] = torch.ones(len(ids["input_ids"][0]))
|
252 |
+
embed_mask = torch.cat((embed_mask, e_m.unsqueeze(0)), dim=0)
|
253 |
+
|
254 |
+
original["embed_mask"] = embed_mask
|
255 |
+
return original
|
256 |
+
|
257 |
+
def _skip_instruction(self, sentence_feature):
|
258 |
+
assert sentence_feature["attention_mask"].shape == sentence_feature["embed_mask"].shape
|
259 |
+
sentence_feature["attention_mask"] = sentence_feature["embed_mask"]
|
260 |
+
|
261 |
+
def _encode(self, sentences_batch, device, convert_to_numpy, multiprocessing=False):
|
262 |
+
|
263 |
+
if multiprocessing:
|
264 |
+
rank = mp.current_process()._identity[0]
|
265 |
+
if device is None and torch.cuda.is_available():
|
266 |
+
device = f"cuda:{rank % torch.cuda.device_count()}"
|
267 |
+
|
268 |
+
self.to(device)
|
269 |
+
features = self.tokenize([self.prepare_for_tokenization(sentence) for sentence in sentences_batch])
|
270 |
+
features = batch_to_device(features, device)
|
271 |
+
|
272 |
+
with torch.no_grad():
|
273 |
+
embeddings = self.forward(features)
|
274 |
+
embeddings = embeddings.detach()
|
275 |
+
embeddings = embeddings.cpu()
|
276 |
+
|
277 |
+
return embeddings
|