izhx commited on
Commit
fa6f546
·
verified ·
1 Parent(s): 73bda90

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +230 -3
README.md CHANGED
@@ -1,3 +1,230 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model:
4
+ - Qwen/Qwen2.5-1.5B-Instruct
5
+ pipeline_tag: text-ranking
6
+ ---
7
+
8
+ # Lychee Rerank
9
+
10
+ [Github](https://github.com/vec-ai/lychee-embed) | [Paper](https://openreview.net/pdf?id=NC6G1KCxlt)
11
+
12
+ `Lychee-rerank` is the latest generalist text embedding model based on the `Qwen2.5` model. It is suitable for reranking of various text retrieval tasks, and supports multiple languages of `Qwen2.5`.
13
+ `Lychee-rerank` is jointly developed by the NLP Team of Harbin Institute of Technology, Shenzhen and is built based on an innovative multi-stage training framework (warm-up, task-learning, model merging, annealing).
14
+ The first batch of open source is 1.5B parameter version.
15
+
16
+ ![The multi-stage training framework](framework-crop.png)
17
+
18
+
19
+ **Lychee-embed**:
20
+
21
+ - Model Type: Text Reranking
22
+ - Language Support: 100+ Languages
23
+ - Param Size: 1.5B
24
+ - Context Length: 32k
25
+ - Model Precision: BF16
26
+
27
+ For more details, please refer to our [paper](https://openreview.net/pdf?id=NC6G1KCxlt).
28
+
29
+
30
+ ### Model List
31
+
32
+ | Model Type | Models | Size | Layers | Sequence Length | Embedding Dimension | MRL Support | Instruction Aware |
33
+ |------------------|----------------------|------|--------|-----------------|---------------------|-------------|----------------|
34
+ | Text Embedding | [lychee-embed](https://huggingface.co/vec-ai/lychee-embed) | 1.5B | 28 | 8K | 1636 | Yes | Yes |
35
+ | Text Reranking | [lychee-rerank](https://huggingface.co/vec-ai/lychee-rerank) | 1.5B | 28 | 8K | - | - | Yes |
36
+
37
+
38
+ > **Note**:
39
+ > - `MRL Support` indicates whether the embedding model supports custom dimensions for the final embedding.
40
+ > - `Instruction Aware` notes whether the embedding or reranking model supports customizing the input instruction according to different tasks.
41
+ > - Like most models, for most downstream tasks, using instructions (instruct) typically yields an improvement of 1% to 5% compared to not using them. Therefore, we recommend that developers create tailored instructions specific to their tasks and scenarios. In multilingual contexts, we also advise users to write their instructions in English, as most instructions utilized during the model training process were originally written in English.
42
+
43
+
44
+ ## Model Usage
45
+
46
+ 📌 **Tips**: We recommend that developers customize the `instruct` according to their specific scenarios, tasks, and languages. Our tests have shown that in most retrieval scenarios, not using an `instruct` on the `query` side can lead to a drop in retrieval performance by approximately 1% to 5%.
47
+
48
+
49
+ ### Transformers Usage
50
+
51
+ ```python
52
+ # Requires transformers>=4.51.0
53
+ import torch
54
+ from transformers import AutoTokenizer, AutoModelForCausalLM
55
+
56
+ def format_instruction(instruction, query, doc):
57
+ if instruction is None:
58
+ instruction = 'Given a web search query, retrieve relevant passages that answer the query'
59
+ output = "<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}".format(instruction=instruction,query=query, doc=doc)
60
+ return output
61
+
62
+ def process_inputs(pairs):
63
+ inputs = tokenizer(
64
+ pairs, padding=False, truncation='longest_first',
65
+ return_attention_mask=False, max_length=max_length - len(prefix_tokens) - len(suffix_tokens)
66
+ )
67
+ for i, ele in enumerate(inputs['input_ids']):
68
+ inputs['input_ids'][i] = prefix_tokens + ele + suffix_tokens
69
+ inputs = tokenizer.pad(inputs, padding=True, return_tensors="pt", max_length=max_length)
70
+ for key in inputs:
71
+ inputs[key] = inputs[key].to(model.device)
72
+ return inputs
73
+
74
+ @torch.no_grad()
75
+ def compute_logits(inputs, **kwargs):
76
+ batch_scores = model(**inputs).logits[:, -1, :]
77
+ true_vector = batch_scores[:, token_true_id]
78
+ false_vector = batch_scores[:, token_false_id]
79
+ batch_scores = torch.stack([false_vector, true_vector], dim=1)
80
+ batch_scores = torch.nn.functional.log_softmax(batch_scores, dim=1)
81
+ scores = batch_scores[:, 1].exp().tolist()
82
+ return scores
83
+
84
+ tokenizer = AutoTokenizer.from_pretrained("vec-ai/lychee-rerank", padding_side='left')
85
+ model = AutoModelForCausalLM.from_pretrained("vec-ai/lychee-rerank").eval()
86
+
87
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving.
88
+ # model = AutoModelForCausalLM.from_pretrained("vec-ai/lychee-rerank", torch_dtype=torch.float16, attn_implementation="flash_attention_2").cuda().eval()
89
+
90
+ token_false_id = tokenizer.convert_tokens_to_ids("no")
91
+ token_true_id = tokenizer.convert_tokens_to_ids("yes")
92
+ max_length = 8192
93
+
94
+ prefix = "<|im_start|>system\nJudge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be \"yes\" or \"no\".<|im_end|>\n<|im_start|>user\n"
95
+ suffix = "<|im_end|>\n<|im_start|>assistant\n"
96
+ prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)
97
+ suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
98
+
99
+ task = 'Given a web search query, retrieve relevant passages that answer the query'
100
+
101
+ queries = [
102
+ "What is the capital of China?",
103
+ "Explain gravity",
104
+ ]
105
+
106
+ documents = [
107
+ "The capital of China is Beijing.",
108
+ "Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun.",
109
+ ]
110
+
111
+ pairs = [format_instruction(task, query, doc) for query, doc in zip(queries, documents)]
112
+
113
+ # Tokenize the input texts
114
+ inputs = process_inputs(pairs)
115
+ scores = compute_logits(inputs)
116
+
117
+ print("scores: ", scores)
118
+ # [0.9398471117019653, 0.5553759336471558]
119
+ ```
120
+
121
+ ### vLLM Usage
122
+
123
+ ```python
124
+ # Requires vllm>=0.8.5
125
+ import math
126
+
127
+ import torch
128
+ from transformers import AutoTokenizer, is_torch_npu_available
129
+ from vllm import LLM, SamplingParams
130
+ from vllm.inputs.data import TokensPrompt
131
+
132
+
133
+ def format_instruction(instruction, query, doc):
134
+ text = [
135
+ {"role": "system", "content": "Judge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be \"yes\" or \"no\"."},
136
+ {"role": "user", "content": f"<Instruct>: {instruction}\n\n<Query>: {query}\n\n<Document>: {doc}"}
137
+ ]
138
+ return text
139
+
140
+ def process_inputs(pairs, instruction, max_length, suffix_tokens):
141
+ messages = [format_instruction(instruction, query, doc) for query, doc in pairs]
142
+ messages = tokenizer.apply_chat_template(
143
+ messages, tokenize=True, add_generation_prompt=False, enable_thinking=False
144
+ )
145
+ messages = [ele[:max_length] + suffix_tokens for ele in messages]
146
+ messages = [TokensPrompt(prompt_token_ids=ele) for ele in messages]
147
+ return messages
148
+
149
+ def compute_logits(model, messages, sampling_params, true_token, false_token):
150
+ outputs = model.generate(messages, sampling_params, use_tqdm=False)
151
+ scores = []
152
+ for i in range(len(outputs)):
153
+ final_logits = outputs[i].outputs[0].logprobs[-1]
154
+ token_count = len(outputs[i].outputs[0].token_ids)
155
+ if true_token not in final_logits:
156
+ true_logit = -10
157
+ else:
158
+ true_logit = final_logits[true_token].logprob
159
+ if false_token not in final_logits:
160
+ false_logit = -10
161
+ else:
162
+ false_logit = final_logits[false_token].logprob
163
+ true_score = math.exp(true_logit)
164
+ false_score = math.exp(false_logit)
165
+ score = true_score / (true_score + false_score)
166
+ scores.append(score)
167
+ return scores
168
+
169
+ number_of_gpu = torch.cuda.device_count()
170
+ tokenizer = AutoTokenizer.from_pretrained('vec-ai/lychee-rerank')
171
+ model = LLM(model='vec-ai/lychee-rerank', max_model_len=10000, enable_prefix_caching=True)
172
+ tokenizer.padding_side = "left"
173
+ tokenizer.pad_token = tokenizer.eos_token
174
+ suffix = "<|im_end|>\n<|im_start|>assistant\n"
175
+ max_length = 8192
176
+ suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
177
+ true_token = tokenizer("yes", add_special_tokens=False).input_ids[0]
178
+ false_token = tokenizer("no", add_special_tokens=False).input_ids[0]
179
+ sampling_params = SamplingParams(temperature=0,
180
+ max_tokens=1,
181
+ logprobs=20,
182
+ allowed_token_ids=[true_token, false_token],
183
+ )
184
+
185
+
186
+ task = 'Given a web search query, retrieve relevant passages that answer the query'
187
+ queries = [
188
+ "What is the capital of China?",
189
+ "Explain gravity",
190
+ ]
191
+ documents = [
192
+ "The capital of China is Beijing.",
193
+ "Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun.",
194
+ ]
195
+
196
+ pairs = list(zip(queries, documents))
197
+ inputs = process_inputs(pairs, task, max_length-len(suffix_tokens), suffix_tokens)
198
+ scores = compute_logits(model, inputs, sampling_params, true_token, false_token)
199
+ print('scores', scores)
200
+ # TODO
201
+ ```
202
+
203
+
204
+ ## Evaluation
205
+
206
+ | Model | Param | MTEB-R | CMTEB-R | MMTEB-R | MLDR | MTEB-Code | ToolBench | FollowIR | BRIGHT |
207
+ |---|---|---|---|---|---|---|---|---|---|
208
+ | **Lychee-embed** | 1.54B | 68.39 |69.77 | 58.43 | 53.85 | 72.54 | 86.35 | 5.74 | 19.47 |
209
+ ||
210
+ | Jina-multilingual-reranker-v2-base | 278M | 54.61 | 70.18 | 54.43 | 50.32 | 46.32 | 67.80 | -0.69 | 16.69 |
211
+ | mGTE-reranker | 304M | 55.71 | 72.01 | 56.61 | 61.40 | 45.92 | 67.58 | -1.14 | 10.76 |
212
+ | BGE-reranker-v2-m3 | 568M | 55.36 | 71.82 | 57.13 | 60.80 | 50.81 | 62.52 | -0.06 | 15.87 |
213
+ | BGE-reranker-v2-gemma | 9.24B | 60.81 | 71.74 | 69.80 | 49.10 | 68.63 | 68.14 | -2.13 | 17.68 |
214
+ | **Lychee-rerank** | 1.54B | 59.56 | 76.37 | 62.47 | 64.09 | 78.03 | 90.82 | 7.38 | 16.92 |
215
+
216
+ For more details, please refer to our [paper](assets/colm25-paper.pdf).
217
+
218
+ ## Citation
219
+
220
+ If you find our work helpful, feel free to give us a cite.
221
+
222
+ ```
223
+ @inproceedings{zhang2025phased,
224
+ title={Phased Training for LLM-powered Text Retrieval Models Beyond Data Scaling},
225
+ author={Xin Zhang and Yanzhao Zhang and Wen Xie and Dingkun Long and Mingxin Li and Pengjun Xie and Meishan Zhang and Wenjie Li and Min Zhang},
226
+ booktitle={Second Conference on Language Modeling},
227
+ year={2025},
228
+ url={https://openreview.net/forum?id=NC6G1KCxlt}
229
+ }
230
+ ```