thennal commited on
Commit
e22c103
·
verified ·
1 Parent(s): 5d45d1b

Upload LLMEncoder

Browse files
Files changed (4) hide show
  1. README.md +199 -0
  2. config.json +34 -0
  3. llmencoder.py +468 -0
  4. model.safetensors +3 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "meta-llama/Meta-Llama-3-8B-Instruct",
3
+ "architectures": [
4
+ "LLMEncoder"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoModel": "llmencoder.LLMEncoder"
10
+ },
11
+ "bos_token_id": 128000,
12
+ "doc_max_length": 400,
13
+ "eos_token_id": 128009,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 4096,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 14336,
18
+ "max_position_embeddings": 8192,
19
+ "mlp_bias": false,
20
+ "num_attention_heads": 32,
21
+ "num_hidden_layers": 5,
22
+ "num_key_value_heads": 8,
23
+ "pooling_mode": "weighted_mean",
24
+ "pretraining_tp": 1,
25
+ "rms_norm_eps": 1e-05,
26
+ "rope_scaling": null,
27
+ "rope_theta": 500000.0,
28
+ "skip_instruction": true,
29
+ "tie_word_embeddings": false,
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.44.2",
32
+ "use_cache": true,
33
+ "vocab_size": 128256
34
+ }
llmencoder.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ from typing import Dict, List, Optional, Union
5
+
6
+ import numpy as np
7
+ import torch
8
+ import torch.multiprocessing as mp
9
+ from peft import PeftModel
10
+ from torch import Tensor, device, nn
11
+ from tqdm.autonotebook import tqdm, trange
12
+ from transformers import (
13
+ AutoModel,
14
+ AutoConfig,
15
+ PretrainedConfig,
16
+ PreTrainedModel,
17
+ AutoTokenizer,
18
+ LlamaConfig,
19
+ MistralConfig,
20
+ GemmaConfig,
21
+ Qwen2Config,
22
+ )
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ def batch_to_device(batch, target_device: device):
28
+ """
29
+ send a pytorch batch to a device (CPU/GPU)
30
+ """
31
+ for key in batch:
32
+ if isinstance(batch[key], Tensor):
33
+ batch[key] = batch[key].to(target_device)
34
+ return batch
35
+
36
+
37
+ class LLMEncoderConfig(PretrainedConfig):
38
+ def __init__(
39
+ self,
40
+ pooling_mode: str = "weighted_mean",
41
+ max_length: int = 512,
42
+ doc_max_length: int = 400,
43
+ skip_instruction: bool = True,
44
+ **kwargs,
45
+ ):
46
+ if pooling_mode not in ["mean", "weighted_mean", "eos_token", "bos_token"]:
47
+ raise ValueError(
48
+ (f"Pooling mode {pooling_mode} is not supported.",
49
+ "Please choose one of 'mean', 'weighted_mean', 'eos_token', 'bos_token'.")
50
+ )
51
+ self.pooling_mode = pooling_mode
52
+ self.max_length = max_length
53
+ self.doc_max_length = doc_max_length
54
+ self.skip_instruction = skip_instruction
55
+
56
+ super().__init__(**kwargs)
57
+
58
+ class LLMEncoder(PreTrainedModel):
59
+ def __init__(
60
+ self,
61
+ model: PreTrainedModel,
62
+ tokenizer: AutoTokenizer,
63
+ config: LLMEncoderConfig
64
+ ):
65
+ super().__init__(config)
66
+ self.model = model
67
+ self.tokenizer = tokenizer
68
+ self.pooling_mode = config.pooling_mode
69
+ self.max_length = config.max_length
70
+ self.doc_max_length = config.doc_max_length
71
+ self.skip_instruction = config.skip_instruction
72
+
73
+ @classmethod
74
+ def from_pretrained(
75
+ self,
76
+ base_model_name_or_path,
77
+ peft_model_name_or_path=None,
78
+ config=LLMEncoderConfig(),
79
+ **kwargs,
80
+ ):
81
+ """
82
+ Load a pretrained model from a model identifier or path.
83
+ Args:
84
+ base_model_name_or_path: Model identifier or path to pretrained model.
85
+ peft_model_name_or_path: Path to any PEFT models to apply.
86
+ Returns: L3Prune model.
87
+ """
88
+
89
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name_or_path)
90
+ tokenizer.pad_token = tokenizer.eos_token
91
+ tokenizer.padding_side = "left"
92
+
93
+ model_config = AutoConfig.from_pretrained(base_model_name_or_path)
94
+ model = AutoModel.from_pretrained(base_model_name_or_path, **kwargs)
95
+
96
+ config = LLMEncoderConfig(**(config.__dict__ | model_config.__dict__))
97
+
98
+ if peft_model_name_or_path is not None:
99
+ model = PeftModel.from_pretrained(
100
+ model,
101
+ peft_model_name_or_path,
102
+ )
103
+ model = model.merge_and_unload()
104
+
105
+ return self(model=model, tokenizer=tokenizer, config=config)
106
+
107
+ def prune(self, percent_prune=0):
108
+ """
109
+ Prune a model to a percentage of layers of the base model. If percent_prune is equal to or greater than 1,
110
+ it is taken as the specific layer number to prune to. For example, if percent_prune=0.3, 30% of the layers will be pruned. If
111
+ percent_prune=3, the model will be pruned to 3 layers.
112
+ """
113
+ # take it as the specific layer number to prune to
114
+ if percent_prune >= 1:
115
+ new_num_layers = int(percent_prune)
116
+ else:
117
+ new_num_layers = int(self.model.config.num_hidden_layers * (1 - percent_prune))
118
+ print(f"Pruning to {new_num_layers} layer.")
119
+ self.model.layers = self.model.layers[:new_num_layers]
120
+ self.model.config.num_hidden_layers = new_num_layers
121
+ self.config.num_hidden_layers = new_num_layers
122
+
123
+ def prepare_for_tokenization(self, text):
124
+ if self.model.config._name_or_path == "meta-llama/Meta-Llama-3-8B-Instruct":
125
+ text = (
126
+ "<|start_header_id|>user<|end_header_id|>\n\n"
127
+ + text.strip()
128
+ + "<|eot_id|>"
129
+ )
130
+ return text
131
+ if self.model.config._name_or_path in [
132
+ "mistralai/Mistral-7B-Instruct-v0.2",
133
+ "meta-llama/Llama-2-7b-chat-hf",
134
+ ]:
135
+ text = "[INST] " + text.strip() + " [/INST]"
136
+ if self.model.config._name_or_path in [
137
+ "google/gemma-2-9b-it",
138
+ ]:
139
+ text = "<bos><start_of_turn>user\n" + text.strip() + "<end_of_turn>"
140
+ if self.model.config._name_or_path in [
141
+ "Qwen/Qwen2-1.5B-Instruct",
142
+ "Qwen/Qwen2-7B-Instruct",
143
+ ]:
144
+ text = "<|im_start|>user\n" + text.strip() + "<|im_end|>"
145
+ if self.pooling_mode == "eos_token":
146
+ if self.model.config._name_or_path == "meta-llama/Meta-Llama-3-8B":
147
+ text = text.strip() + "<|end_of_text|>"
148
+ elif isinstance(self.model.config, LlamaConfig) or isinstance(
149
+ self.model.config, MistralConfig
150
+ ):
151
+ text = text.strip() + " </s>"
152
+ elif isinstance(self.model.config, GemmaConfig):
153
+ text = text.strip() + "<eos>"
154
+ elif isinstance(self.model.config, Qwen2Config):
155
+ text = text.strip() + "<|endoftext|>"
156
+ return text
157
+
158
+ def tokenize(self, texts):
159
+ texts_2 = []
160
+ original_texts = []
161
+ for text in texts:
162
+ t = text.split("!@#$%^&*()")
163
+ texts_2.append(t[1] if len(t) > 1 else "")
164
+ original_texts.append("".join(t))
165
+
166
+ original = self.tokenizer(
167
+ original_texts,
168
+ return_tensors="pt",
169
+ padding=True,
170
+ truncation=True,
171
+ max_length=self.max_length,
172
+ )
173
+ embed_mask = None
174
+ for t_i, t in enumerate(texts_2):
175
+ ids = self.tokenizer(
176
+ [t],
177
+ return_tensors="pt",
178
+ padding=True,
179
+ truncation=True,
180
+ max_length=self.max_length,
181
+ add_special_tokens=False,
182
+ )
183
+ if embed_mask is None:
184
+ e_m = torch.zeros_like(original["attention_mask"][t_i])
185
+ if len(ids["input_ids"][0]) > 0:
186
+ e_m[-len(ids["input_ids"][0]) :] = torch.ones(
187
+ len(ids["input_ids"][0])
188
+ )
189
+ embed_mask = e_m.unsqueeze(0)
190
+ else:
191
+ e_m = torch.zeros_like(original["attention_mask"][t_i])
192
+ if len(ids["input_ids"][0]) > 0:
193
+ e_m[-len(ids["input_ids"][0]) :] = torch.ones(
194
+ len(ids["input_ids"][0])
195
+ )
196
+ embed_mask = torch.cat((embed_mask, e_m.unsqueeze(0)), dim=0)
197
+
198
+ original["embed_mask"] = embed_mask
199
+ return original
200
+
201
+ def _skip_instruction(self, sentence_feature):
202
+ assert (
203
+ sentence_feature["attention_mask"].shape
204
+ == sentence_feature["embed_mask"].shape
205
+ )
206
+ sentence_feature["attention_mask"] = sentence_feature["embed_mask"]
207
+
208
+ def forward(self, sentence_feature: Dict[str, Tensor]):
209
+ embed_mask = None
210
+ if "embed_mask" in sentence_feature:
211
+ embed_mask = sentence_feature.pop("embed_mask")
212
+ reps = self.model(**sentence_feature)
213
+ sentence_feature["embed_mask"] = embed_mask
214
+
215
+ return self.get_pooling(sentence_feature, reps.last_hidden_state)
216
+
217
+ def get_pooling(self, features, last_hidden_states): # All models padded from left
218
+ assert (
219
+ self.tokenizer.padding_side == "left"
220
+ ), "Pooling modes are implemented for padding from left."
221
+ if self.skip_instruction:
222
+ self._skip_instruction(features)
223
+ seq_lengths = features["attention_mask"].sum(dim=-1)
224
+ if self.pooling_mode == "mean":
225
+ return torch.stack(
226
+ [
227
+ last_hidden_states[i, -length:, :].mean(dim=0)
228
+ for i, length in enumerate(seq_lengths)
229
+ ],
230
+ dim=0,
231
+ )
232
+ elif self.pooling_mode == "weighted_mean":
233
+ bs, l, _ = last_hidden_states.shape
234
+ complete_weights = torch.zeros(bs, l, device=last_hidden_states.device)
235
+ for i, seq_l in enumerate(seq_lengths):
236
+ if seq_l > 0:
237
+ complete_weights[i, -seq_l:] = torch.arange(seq_l) + 1
238
+ complete_weights[i] /= torch.clamp(
239
+ complete_weights[i].sum(), min=1e-9
240
+ )
241
+ return torch.sum(last_hidden_states * complete_weights.unsqueeze(-1), dim=1)
242
+ elif self.pooling_mode == "eos_token" or self.pooling_mode == "last_token":
243
+ return last_hidden_states[:, -1]
244
+ elif self.pooling_mode == "bos_token":
245
+ return last_hidden_states[
246
+ features["input_ids"] == self.tokenizer.bos_token_id
247
+ ]
248
+ else:
249
+ raise ValueError(f"{self.pooling_mode} is not implemented yet.")
250
+
251
+ def _convert_to_str(self, instruction, text):
252
+ tokenized_q = self.tokenizer(
253
+ text,
254
+ return_tensors="pt",
255
+ padding=True,
256
+ truncation=True,
257
+ max_length=self.max_length,
258
+ add_special_tokens=False,
259
+ )
260
+ tokenized_q_length = len(tokenized_q["input_ids"][0])
261
+
262
+ while tokenized_q_length > self.doc_max_length:
263
+ reduction_ratio = self.doc_max_length / tokenized_q_length
264
+ reduced_length = int(len(text.split()) * reduction_ratio)
265
+ text = " ".join(text.split()[:reduced_length])
266
+ tokenized_q = self.tokenizer(
267
+ text,
268
+ return_tensors="pt",
269
+ padding=True,
270
+ truncation=True,
271
+ max_length=self.max_length,
272
+ add_special_tokens=False,
273
+ )
274
+ tokenized_q_length = len(tokenized_q["input_ids"][0])
275
+
276
+ return (
277
+ f"{instruction.strip()} !@#$%^&*(){text}"
278
+ if instruction
279
+ else f"!@#$%^&*(){text}"
280
+ )
281
+
282
+ def encode(
283
+ self,
284
+ sentences: Union[str, List[str]],
285
+ batch_size: int = 32,
286
+ show_progress_bar: bool = True,
287
+ convert_to_numpy: bool = False,
288
+ convert_to_tensor: bool = False,
289
+ device: Optional[str] = None,
290
+ ):
291
+ """
292
+ Encode a list of sentences to their respective embeddings. The sentences can be a list of strings or a string.
293
+ Args:
294
+ sentences: sentence or sentences to encode.
295
+ batch_size: batch size for turning sentence tokens into embeddings.
296
+ show_progress_bar: whether to show progress bars during encoding steps.
297
+ convert_to_numpy: If true, return numpy arrays instead of torch tensors.
298
+ convert_to_tensor: If true, return torch tensors (default).
299
+ device: torch backend device identifier (e.g., 'cuda', 'cpu','mps' etc.). If not specified,
300
+ the default is to use cuda when available, otherwise cpu. Note that only the choice of 'cuda' supports
301
+ multiprocessing as currently implemented.
302
+
303
+ Returns: embeddings of the sentences. Embeddings are detached and always on the CPU (see _encode implementation).
304
+
305
+ """
306
+ if isinstance(sentences[0], str) and isinstance(sentences[-1], int):
307
+ sentences = [sentences]
308
+ # required for MEDI version of MTEB
309
+ if isinstance(sentences[0], str):
310
+ sentences = [[""] + [sentence] for sentence in sentences]
311
+
312
+ if device is None:
313
+ device = "cuda" if torch.cuda.is_available() else "cpu"
314
+
315
+ concatenated_input_texts = []
316
+ for sentence in sentences:
317
+ assert isinstance(sentence[0], str)
318
+ assert isinstance(sentence[1], str)
319
+ concatenated_input_texts.append(
320
+ self._convert_to_str(sentence[0], sentence[1])
321
+ )
322
+ sentences = concatenated_input_texts
323
+
324
+ self.eval()
325
+
326
+ if convert_to_tensor:
327
+ convert_to_numpy = False
328
+
329
+ length_sorted_idx = np.argsort([-self._text_length(sen) for sen in sentences])
330
+ sentences_sorted = [sentences[idx] for idx in length_sorted_idx]
331
+ all_embeddings = []
332
+
333
+ if torch.cuda.device_count() <= 1:
334
+ # This branch also support mps devices
335
+ self.to(device)
336
+ for start_index in trange(
337
+ 0,
338
+ len(sentences),
339
+ batch_size,
340
+ desc="Batches",
341
+ disable=not show_progress_bar,
342
+ ):
343
+ sentences_batch = sentences_sorted[
344
+ start_index : start_index + batch_size
345
+ ]
346
+ embeddings = self._encode(
347
+ sentences_batch, device=device, convert_to_numpy=convert_to_numpy
348
+ )
349
+ all_embeddings.append(embeddings)
350
+ else:
351
+
352
+ num_proc = torch.cuda.device_count()
353
+ cuda_compatible_multiprocess = mp.get_context("spawn")
354
+ with cuda_compatible_multiprocess.Pool(num_proc) as p:
355
+ sentences_batches = [
356
+ sentences_sorted[start_index : start_index + batch_size]
357
+ for start_index in range(0, len(sentences), batch_size)
358
+ ]
359
+
360
+ progress_bar = tqdm(
361
+ total=len(sentences_batches),
362
+ desc="Batches",
363
+ disable=not show_progress_bar,
364
+ )
365
+ results = []
366
+
367
+ def update(*args):
368
+ progress_bar.update()
369
+
370
+ for batch in sentences_batches:
371
+ results.append(
372
+ p.apply_async(
373
+ self._encode,
374
+ args=(batch, None, convert_to_numpy, True),
375
+ callback=update,
376
+ )
377
+ )
378
+
379
+ all_embeddings = [result.get() for result in results]
380
+ progress_bar.close()
381
+
382
+ all_embeddings = torch.cat(all_embeddings, dim=0)
383
+ all_embeddings = all_embeddings[np.argsort(length_sorted_idx)]
384
+ all_embeddings = all_embeddings.to(torch.float32)
385
+ if convert_to_numpy:
386
+ all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings])
387
+ return all_embeddings
388
+
389
+ def save(self, output_path, merge_before_save=False, save_config=True):
390
+ if merge_before_save and isinstance(self.model, PeftModel):
391
+ self.model = self.model.merge_and_unload()
392
+ if hasattr(self.model, "_hf_peft_config_loaded"):
393
+ self.model._hf_peft_config_loaded = False
394
+
395
+ self.model.save_pretrained(output_path)
396
+ self.tokenizer.save_pretrained(output_path)
397
+
398
+ l3prune_config = {
399
+ "pooling_mode": self.pooling_mode,
400
+ "max_length": self.max_length,
401
+ "doc_max_length": self.doc_max_length,
402
+ "skip_instruction": self.skip_instruction,
403
+ }
404
+
405
+ if save_config:
406
+ os.makedirs(output_path, exist_ok=True)
407
+ with open(f"{output_path}/l3prune_config.json", "w") as fOut:
408
+ json.dump(l3prune_config, fOut, indent=4)
409
+
410
+ def _encode(
411
+ self,
412
+ sentences_batch,
413
+ device: Optional[str] = None,
414
+ convert_to_numpy: bool = False,
415
+ multiprocessing=False,
416
+ ):
417
+ if multiprocessing:
418
+ # multiprocessing only supports CUDA devices at this time, so we ignore the value of device
419
+ # and use cuda:rank for the device
420
+ rank = mp.current_process()._identity[0]
421
+ if device is None and torch.cuda.is_available():
422
+ device = f"cuda:{rank % torch.cuda.device_count()}"
423
+
424
+ self.to(device)
425
+ features = self.tokenize(
426
+ [self.prepare_for_tokenization(sentence) for sentence in sentences_batch]
427
+ )
428
+ features = batch_to_device(features, device)
429
+
430
+ with torch.no_grad():
431
+ embeddings = self.forward(features)
432
+ embeddings = embeddings.detach()
433
+ embeddings = embeddings.cpu()
434
+
435
+ return embeddings
436
+
437
+ def _text_length(self, text: Union[List[int], List[List[int]]]):
438
+ """
439
+ Help function to get the length for the input text. Text can be either a string (which means a single text)
440
+ a list of ints (which means a single tokenized text), or a tuple of list of ints
441
+ (representing several text inputs to the model).
442
+ """
443
+ if (
444
+ isinstance(text, str)
445
+ or (isinstance(text, list) and isinstance(text[0], int))
446
+ or len(text) == 0
447
+ ): # Single text, list of ints, or empty
448
+ return len(text)
449
+ if isinstance(text, dict): # {key: value} case
450
+ return len(next(iter(text.values())))
451
+ elif not hasattr(text, "__len__"): # Object has no len() method
452
+ return 1
453
+ else:
454
+ return sum([len(t) for t in text])
455
+
456
+ def resize_token_embeddings(
457
+ self,
458
+ new_num_tokens: Optional[int] = None,
459
+ pad_to_multiple_of: Optional[int] = None,
460
+ ) -> nn.Embedding:
461
+ return self.model.resize_token_embeddings(
462
+ new_num_tokens=new_num_tokens, pad_to_multiple_of=pad_to_multiple_of
463
+ )
464
+
465
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
466
+ self.model.gradient_checkpointing_enable(
467
+ gradient_checkpointing_kwargs=gradient_checkpointing_kwargs
468
+ )
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e14394a3153d6c87cdc54a89e3460da6903e8e500e8984dfd048bc2569253c5
3
+ size 3231806784