PEFT
Safetensors
English
retrieval
instructions
orionweller commited on
Commit
96e5732
1 Parent(s): 5ba4e2f

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +197 -197
README.md CHANGED
@@ -1,202 +1,202 @@
1
  ---
2
  base_model: mistralai/Mistral-7B-v0.1
3
  library_name: peft
 
 
 
 
 
 
 
 
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
-
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]
200
- ### Framework versions
201
-
202
- - PEFT 0.12.0
 
1
  ---
2
  base_model: mistralai/Mistral-7B-v0.1
3
  library_name: peft
4
+ license: apache-2.0
5
+ language:
6
+ - en
7
+ tags:
8
+ - retrieval
9
+ - instructions
10
+ datasets:
11
+ - samaya-ai/msmarco-w-instructions
12
  ---
13
 
14
+ # Model Summary
15
+
16
+ Promptriever is a bi-encoder retrieval model that can take in natural language instructions and prompts. This version, `promptriever-mistral-v0.1-7b-v1` was instruction-trained on a corpus of 490k MSMarco samples with instructions and 490k without instructions. See the [paper](todo) for more details.
17
+
18
+ - **Repository:** [orionw/Promptriever](https://github.com/orionw/promptriever)
19
+ - **Paper:** [Promptriever: Instruction-Trained Retrievers Can Be Prompted Like Language Models](TODO)
20
+ - **Instruction-Training Dataset:** [samaya-ai/msmarco-w-instructions](https://huggingface.co/datasets/samaya-ai/msmarco-w-instructions)
21
+
22
+
23
+ # Use
24
+
25
+ You can use MTEB to load this model ([source code](https://github.com/embeddings-benchmark/mteb/blob/main/mteb/models/promptriever_models.py)):
26
+ ```python
27
+ import mteb
28
+ model = mteb.get_model("samaya-ai/promptriever-mistral-v0.1-7b-v1")
29
+ tasks = mteb.get_tasks(tasks=["NFCorpus"], languages=["eng"])
30
+ evaluation = mteb.MTEB(tasks=tasks)
31
+ evaluation.run(model, batch_size=16)
32
+ ```
33
+
34
+ If you want to use a different framework, here's an example of how to batch:
35
+ ```python
36
+ import torch
37
+ import torch.nn.functional as F
38
+ from transformers import AutoTokenizer, AutoModel
39
+ from peft import PeftModel, PeftConfig
40
+ import numpy as np
41
+
42
+ class Promptriever:
43
+ def __init__(self, model_name_or_path):
44
+ self.model, self.tokenizer = self.get_model(model_name_or_path)
45
+ self.model.eval().cuda()
46
+
47
+ def get_model(self, peft_model_name):
48
+ # Load the PEFT configuration to get the base model name
49
+ peft_config = PeftConfig.from_pretrained(peft_model_name)
50
+ base_model_name = peft_config.base_model_name_or_path
51
+
52
+ # Load the base model and tokenizer
53
+ base_model = AutoModel.from_pretrained(base_model_name)
54
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name)
55
+ tokenizer.pad_token = tokenizer.eos_token
56
+ tokenizer.pad_token_id = tokenizer.eos_token_id
57
+ tokenizer.padding_side = "right"
58
+
59
+ # Load and merge the PEFT model
60
+ model = PeftModel.from_pretrained(base_model, peft_model_name)
61
+ model = model.merge_and_unload()
62
+
63
+ # can be much longer, but for the example 512 is enough
64
+ model.config.max_length = 512
65
+ tokenizer.model_max_length = 512
66
+
67
+ return model, tokenizer
68
+
69
+ def create_batch_dict(self, tokenizer, input_texts):
70
+ max_length = self.model.config.max_length
71
+ batch_dict = tokenizer(
72
+ input_texts,
73
+ max_length=max_length - 1,
74
+ return_token_type_ids=False,
75
+ return_attention_mask=False,
76
+ padding=False,
77
+ truncation=True,
78
+ )
79
+ batch_dict["input_ids"] = [
80
+ input_ids + [tokenizer.eos_token_id]
81
+ for input_ids in batch_dict["input_ids"]
82
+ ]
83
+ return tokenizer.pad(
84
+ batch_dict,
85
+ padding=True,
86
+ pad_to_multiple_of=8,
87
+ return_attention_mask=True,
88
+ return_tensors="pt",
89
+ )
90
+
91
+ def encode(self, sentences, max_length: int = 2048, batch_size: int = 4):
92
+ all_embeddings = []
93
+ for i in range(0, len(sentences), batch_size):
94
+ batch_texts = sentences[i : i + batch_size]
95
+
96
+ batch_dict = self.create_batch_dict(self.tokenizer, batch_texts)
97
+ batch_dict = {
98
+ key: value.to(self.model.device) for key, value in batch_dict.items()
99
+ }
100
+
101
+ with torch.cuda.amp.autocast():
102
+ with torch.no_grad():
103
+ outputs = self.model(**batch_dict)
104
+ last_hidden_state = outputs.last_hidden_state
105
+ sequence_lengths = batch_dict["attention_mask"].sum(dim=1) - 1
106
+ batch_size = last_hidden_state.shape[0]
107
+ reps = last_hidden_state[
108
+ torch.arange(batch_size, device=last_hidden_state.device),
109
+ sequence_lengths,
110
+ ]
111
+ embeddings = F.normalize(reps, p=2, dim=-1)
112
+ all_embeddings.append(embeddings.cpu().numpy())
113
+
114
+ return np.concatenate(all_embeddings, axis=0)
115
+
116
+ # Initialize the model
117
+ model = Promptriever("samaya-ai/promptriever-llama3.1-8b-instruct-v1")
118
+
119
+ # Example query and instruction
120
+ query = "What universities are in Baltimore, Maryland?"
121
+
122
+ # add specific relevance conditions if desired (and/or/not) and any other prompts
123
+ instruction = "A relevant document would describe any university in Baltimore. I am not interested in any university that was the first American university. Think carefully about these conditions when determining relevance."
124
+
125
+ # Combine query and instruction with **two spaces** after "query: "
126
+ input_text = f"query: {query.strip()} {instruction.strip()}".strip()
127
+
128
+ # Example documents
129
+ # NOTE: double space after `passage:`
130
+ doc1 = "passage: Johns Hopkins University (often abbreviated as Johns Hopkins, Hopkins, or JHU) is a private research university in Baltimore, Maryland. Founded in 1876, Johns Hopkins was the first American university based on the European research institution model."
131
+ doc2 = "passage: Johns Hopkins University (often abbreviated as Johns Hopkins, Hopkins, or JHU) is a private research university in Baltimore, Maryland. Founded in 1876, Johns Hopkins was the second American university based on the European research institution model."
132
+
133
+ # Encode query and documents
134
+ query_embedding = model.encode([input_text])
135
+ doc_embeddings = model.encode([doc1, doc2])
136
+
137
+ # Calculate similarities
138
+ similarities = np.dot(query_embedding, doc_embeddings.T)[0]
139
+ print(f"Similarities: {similarities}") # Similarities: [0.53341305 0.53451955]
140
+ assert similarities[1] > similarities[0]
141
+
142
+
143
+ # change up the instruction to the opposite, to see it works
144
+ instruction = "A relevant document would describe any university in Baltimore. I am interested in any university that was the first American university. Think carefully about these conditions when determining relevance."
145
+ input_text = f"query: {query.strip()} {instruction.strip()}".strip()
146
+ query_embedding = model.encode([input_text])
147
+ similarities = np.dot(query_embedding, doc_embeddings.T)[0]
148
+ print(f"Similarities: {similarities}") # Similarities: [0.60182875 0.5874183 ]
149
+ assert similarities[0] > similarities[1]
150
+ ```
151
+
152
+ # Training
153
+
154
+ We used a fork of [Tevatron](https://github.com/orionw/tevatron) to fine-tune promptriever with the [samaya-ai/msmarco-w-instructions](https://huggingface.co/datasets/samaya-ai/msmarco-w-instructions) dataset.
155
+
156
+ You can reproduce this with [this script](https://github.com/orionw/promptriever/blob/main/scripts/training/train_instruct_mistral_v1.sh) (reproduced here for convenience).
157
+
158
+ ```bash
159
+ #!/bin/bash
160
+ deepspeed --include localhost:$3 --master_port "6000$4" --module tevatron.retriever.driver.train \
161
+ --deepspeed deepspeed/ds_zero3_config.json \
162
+ --output_dir retriever-mistral-$1 \
163
+ --model_name_or_path mistralai/Mistral-7B-v0.1 \
164
+ --lora \
165
+ --lora_r 32 \
166
+ --lora_target_modules q_proj,k_proj,v_proj,o_proj,down_proj,up_proj,gate_proj \
167
+ --save_steps 500 \
168
+ --dataset_name $2 \
169
+ --query_prefix "query: " \
170
+ --passage_prefix "passage: " \
171
+ --bf16 \
172
+ --pooling eos \
173
+ --append_eos_token \
174
+ --normalize \
175
+ --temperature 0.01 \
176
+ --per_device_train_batch_size 8 \
177
+ --gradient_checkpointing \
178
+ --train_group_size 16 \
179
+ --learning_rate 1e-4 \
180
+ --query_max_len 304 \
181
+ --passage_max_len 196 \
182
+ --num_train_epochs 1 \
183
+ --logging_steps 10 \
184
+ --overwrite_output_dir \
185
+ --warmup_steps 100 \
186
+ --gradient_accumulation_steps 4 \
187
+ --negatives_first_n 3
188
+ ```
189
+
190
+ # License
191
+ This model was used for research efforts and is not used in any production systems at Samaya AI. Usage must follow the license of the base model as well, as this is a LoRA fine-tune.
192
+
193
+ # Citation
194
+
195
+ ```bibtex
196
+ @article{weller2024promptriever,
197
+ title={Promptriever: Instruction-Trained Retrievers Can Be Prompted Like Language Models},
198
+ author={Weller, Orion and Van Durme, Benjamin and Lawrie, Dawn and Paranjape, Ashwin and Zhang, Yuhao and Hessel, Jack},
199
+ journal={arXiv preprint TODO},
200
+ year={2024}
201
+ }
202
+ ```