liuqi6777 commited on
Commit
b321bfc
·
verified ·
1 Parent(s): e6c3ab7

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +396 -0
README.md ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model:
4
+ - Qwen/Qwen3-0.6B
5
+ tags:
6
+ - transformers
7
+ - sentence-similarity
8
+ - feature-extraction
9
+ - text-embeddings-inference
10
+ - reranking
11
+ pipeline_tag: feature-extraction
12
+ ---
13
+
14
+ <!-- <div align="center">
15
+ <p align="center">
16
+ <img src="assets/overall.jpg" width="50%" height="50%" />
17
+ </p>
18
+ </div> -->
19
+
20
+ <div align="center">
21
+ <h1>E2Rank: Your Text Embedding can Also be an Effective and Efficient Listwise Reranker</h1>
22
+
23
+ <!-- <a href='https://arxiv.org/pdf/2501.07572'><img src='https://img.shields.io/badge/Paper-arXiv-red'></a>
24
+ <img src="https://img.shields.io/github/stars/Alibaba-NLP/E2Rank?color=yellow" alt="Stars">
25
+ <a href='https://huggingface.co/papers/2501.07572'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Discussion-orange'></a>
26
+ <a href='https://huggingface.co/collections/callanwu/webwalker-677f6527407edfda44098b09'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Colloectionss-blue'></a>
27
+ <a href='https://huggingface.co/datasets/callanwu/WebWalkerQA'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Datasets-green'></a> -->
28
+
29
+ <!-- **Authors:** -->
30
+
31
+ <div class="is-size-5 publication-authors">
32
+ <span class="author-block">
33
+ <a href="https://liuqi6777.github.io">Qi Liu</a><sup>1,2</sup>,</span>
34
+ <span class="author-block">
35
+ Yanzhao Zhang<sup>2</sup>,</span>
36
+ <span class="author-block">
37
+ Mingxin Li<sup>2</sup>,
38
+ </span>
39
+ <span class="author-block">
40
+ Dingkun Long<sup>2</sup>,
41
+ </span>
42
+ <span class="author-block">
43
+ Pengjun Xie<sup>2</sup>,
44
+ </span>
45
+ <span class="author-block">
46
+ Jiaxin Mao<sup>1</sup>,
47
+ </span>
48
+ </div>
49
+ <!-- **Affiliations:** -->
50
+ <div class="is-size-5 publication-authors">
51
+ <span><sup>1</sup><i>GSAI, Renmin University of China,</i></span>
52
+ <span><sup>2</sup><i>Tongyi Lab, Alibaba Group</i></span>
53
+ </div>
54
+
55
+
56
+ <a href="https://Alibaba-NLP.github.io/E2Rank/">[🤖 Website]</a> |
57
+ <a href="https://arxiv.org/pdf/2501.07572">[📄 Arxiv Paper]</a> |
58
+ <a href="https://huggingface.co/collections/Alibaba-NLP/e2rank">[🤗 Huggingface Collection]</a> |
59
+ <a href="# 🚩Citation">[🚩 Citation]</a>
60
+
61
+ </div>
62
+
63
+ # 📌 Introduction
64
+
65
+ We introduce E2Rank,
66
+ meaning **E**fficient **E**mbedding-based **Rank**ing
67
+ (also meaning **Embedding-to-Rank**),
68
+ which extends a single text embedding model
69
+ to perform both high-quality retrieval and listwise reranking,
70
+ thereby achieving strong effectiveness with remarkable efficiency.
71
+
72
+ By applying cosine similarity between the query and
73
+ document embeddings as a unified ranking function, the listwise ranking prompt,
74
+ which is constructed from the original query and its candidate documents, serves
75
+ as an enhanced query enriched with signals from the top-K documents, akin to
76
+ pseudo-relevance feedback (PRF) in traditional retrieval models. This design
77
+ preserves the efficiency and representational quality of the base embedding model
78
+ while significantly improving its reranking performance.
79
+
80
+ Empirically, E2Rank achieves state-of-the-art results on the BEIR reranking benchmark
81
+ and demonstrates competitive performance on the reasoning-intensive BRIGHT benchmark,
82
+ with very low reranking latency. We also show that the ranking training process
83
+ improves embedding performance on the MTEB benchmark.
84
+ Our findings indicate that a single embedding model can effectively unify retrieval and reranking,
85
+ offering both computational efficiency and competitive ranking accuracy.
86
+
87
+ **Our work highlights the potential of single embedding models to serve as unified retrieval-reranking engines, offering a practical, efficient, and accurate alternative to complex multi-stage ranking systems.**
88
+
89
+
90
+ # 🚀 Quick Start
91
+
92
+ ## Model List
93
+
94
+ | Supported Task | Model Name | Size | Layers | Sequence Length | Embedding Dimension | Instruction Aware |
95
+ |-----------------------------|----------------------|------|--------|-----------------|---------------------|-------------------|
96
+ | **Embedding + Reranking** | [Alibaba-NLP/E2Rank-0.6B](https://huggingface.co/Alibaba-NLP/E2Rank-0.6B) | 0.6B | 28 | 32K | 1024 | Yes |
97
+ | **Embedding + Reranking** | [Alibaba-NLP/E2Rank-4B](https://huggingface.co/Alibaba-NLP/E2Rank-4B) | 4B | 36 | 32K | 2560 | Yes |
98
+ | **Embedding + Reranking** | [Alibaba-NLP/E2Rank-8B](https://huggingface.co/Alibaba-NLP/E2Rank-8B) | 8B | 36 | 32K | 4096 | Yes |
99
+ | Embedding Only | [Alibaba-NLP/E2Rank-0.6B-Embedding-Only](https://huggingface.co/Alibaba-NLP/E2Rank-0.6B-Embedding-Only) | 0.6B | 28 | 32K | 1024 | Yes |
100
+ | Embedding Only | [Alibaba-NLP/E2Rank-0.6B-Embedding-Only](https://huggingface.co/Alibaba-NLP/E2Rank-4B-Embedding-Only) | 4B | 36 | 32K | 2560 | Yes |
101
+ | Embedding Only | [Alibaba-NLP/E2Rank-0.6B-Embedding-Only](https://huggingface.co/Alibaba-NLP/E2Rank-8B-Embedding-Only) | 8B | 36 | 32K | 4096 | Yes |
102
+
103
+
104
+ > **Note**:
105
+ > - `Embedding Only` indicates that the model is trained only with the constrative learning and support embedding tasks, while `Embedding + Reranking` indicates the **full E2Rank model** trained with both embedding and reranking objectives (for more detals, please refer to the [paper]()).
106
+ > - `Instruction Aware` notes whether the model supports customizing the input instruction according to different tasks.
107
+ <!-- > - For `Listwise Reranking` models, they are supervised fine-tuned from the Qwen3 Models in the paradigm of RankGPT and support only the reranking task. -->
108
+
109
+ ## Usage
110
+
111
+ ### Embedding Model
112
+
113
+ The usage of E2Rank as an embedding model is similar to [Qwen3-Embedding](https://github.com/QwenLM/Qwen3-Embedding). The only difference is that Qwen3-Embedding will automatically append an EOS token, while E2Rank requires users to manully append the special token `<|endoftext|>` at the end of each input text.
114
+
115
+
116
+ **vLLM Usage (recommended)**
117
+
118
+ ```python
119
+ # Requires vllm>=0.8.5
120
+ import torch
121
+ import vllm
122
+ from vllm import LLM
123
+ from vllm.config import PoolerConfig
124
+
125
+ def get_detailed_instruct(task_description: str, query: str) -> str:
126
+ return f'Instruct: {task_description}\nQuery:{query}'
127
+
128
+ # Each query must come with a one-sentence instruction that describes the task
129
+ task = 'Given a web search query, retrieve relevant passages that answer the query'
130
+
131
+ queries = [
132
+ get_detailed_instruct(task, 'What is the capital of China?'),
133
+ get_detailed_instruct(task, 'Explain gravity')
134
+ ]
135
+ # No need to add instruction for retrieval documents
136
+ documents = [
137
+ "The capital of China is Beijing.",
138
+ "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."
139
+ ]
140
+ input_texts = queries + documents
141
+ input_texts = [t + "<|endoftext|>" for t in input_texts]
142
+
143
+ model = LLM(
144
+ model="Alibaba-NLP/E2Rank-0.6B",
145
+ task="embed",
146
+ override_pooler_config=PoolerConfig(pooling_type="LAST", normalize=True)
147
+ )
148
+
149
+ outputs = model.embed(input_texts)
150
+ embeddings = torch.tensor([o.outputs.embedding for o in outputs])
151
+ scores = (embeddings[:2] @ embeddings[2:].T)
152
+ print(scores.tolist())
153
+ # [[0.5958386659622192, 0.030148349702358246], [0.060259245336055756, 0.5595865249633789]]
154
+ ```
155
+
156
+ <details>
157
+ <summary><b>Transformers Usage</b></summary>
158
+
159
+ ```python
160
+ # Requires transformers>=4.51.0
161
+ import torch
162
+ import torch.nn.functional as F
163
+
164
+ from torch import Tensor
165
+ from transformers import AutoTokenizer, AutoModel
166
+
167
+
168
+ def last_token_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:
169
+ left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
170
+ if left_padding:
171
+ return last_hidden_states[:, -1]
172
+ else:
173
+ sequence_lengths = attention_mask.sum(dim=1) - 1
174
+ batch_size = last_hidden_states.shape[0]
175
+ return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
176
+
177
+
178
+ def get_detailed_instruct(task_description: str, query: str) -> str:
179
+ return f'Instruct: {task_description}\nQuery:{query}'
180
+
181
+ # Each query must come with a one-sentence instruction that describes the task
182
+ task = 'Given a web search query, retrieve relevant passages that answer the query'
183
+
184
+ queries = [
185
+ get_detailed_instruct(task, 'What is the capital of China?'),
186
+ get_detailed_instruct(task, 'Explain gravity')
187
+ ]
188
+ # No need to add instruction for retrieval documents
189
+ documents = [
190
+ "The capital of China is Beijing.",
191
+ "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."
192
+ ]
193
+ input_texts = queries + documents
194
+ input_texts = [t + "<|endoftext|>" for t in input_texts]
195
+
196
+ tokenizer = AutoTokenizer.from_pretrained('Alibaba-NLP/E2Rank-0.6B', padding_side='left')
197
+ model = AutoModel.from_pretrained('Alibaba-NLP/E2Rank-0.6B')
198
+
199
+ max_length = 8192
200
+
201
+ # Tokenize the input texts
202
+ batch_dict = tokenizer(
203
+ input_texts,
204
+ padding=True,
205
+ truncation=True,
206
+ max_length=max_length,
207
+ return_tensors="pt",
208
+ )
209
+ batch_dict.to(model.device)
210
+ with torch.no_grad():
211
+ outputs = model(**batch_dict)
212
+ embeddings = last_token_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
213
+
214
+ # normalize embeddings
215
+ embeddings = F.normalize(embeddings, p=2, dim=1)
216
+ scores = (embeddings[:2] @ embeddings[2:].T)
217
+
218
+ print(scores.tolist())
219
+ # [[0.5950675010681152, 0.030417663976550102], [0.061970409005880356, 0.562691330909729]]
220
+ ```
221
+ </details>
222
+
223
+
224
+ ### Reranking
225
+
226
+ For using E2Rank as a reranker, you only need to perform additional processing on the query by adding (part of) the docs that needs to be reranked to the *listwise prompt*, while the rest is the same as using the embedding model.
227
+
228
+ **vLLM Usage (recommended)**
229
+
230
+ ```python
231
+ # Requires vllm>=0.8.5
232
+ import torch
233
+ import vllm
234
+ from vllm import LLM
235
+ from vllm.config import PoolerConfig
236
+
237
+ model = LLM(
238
+ model="./checkpoints/E2Rank-0.6B",
239
+ task="embed",
240
+ override_pooler_config=PoolerConfig(pooling_type="LAST", normalize=True)
241
+ )
242
+ tokenizer = model.get_tokenizer()
243
+
244
+ def get_listwise_prompt(task_description: str, query: str, documents: list[str], num_input_docs: int = 20) -> str:
245
+ input_docs = documents[:num_input_docs]
246
+ input_docs = "\n".join([f"[{i}] {doc}" for i, doc in enumerate(input_docs, start=1)])
247
+ messages = [{
248
+ "role": "user",
249
+ "content": f'{task_description}\nDocuments:\n{input_docs}Search Query:{query}'
250
+ }]
251
+ text = tokenizer.apply_chat_template(
252
+ messages,
253
+ tokenize=False,
254
+ add_generation_prompt=True,
255
+ enable_thinking=False,
256
+ )
257
+ return text
258
+
259
+ task = 'Given a web search query and some relevant documents, rerank the documents that answer the query:'
260
+
261
+ queries = [
262
+ 'What is the capital of China?',
263
+ 'Explain gravity'
264
+ ]
265
+
266
+ # No need to add instruction for retrieval documents
267
+ documents = [
268
+ "The capital of China is Beijing.",
269
+ "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."
270
+ ]
271
+ documents = [doc + "<|endoftext|>" for doc in documents]
272
+
273
+ pseudo_queries = [
274
+ get_listwise_prompt(task, queries[0], documents),
275
+ get_listwise_prompt(task, queries[1], documents)
276
+ ] # no need to add the EOS token here
277
+
278
+ input_texts = pseudo_queries + documents
279
+
280
+ outputs = model.embed(input_texts)
281
+ embeddings = torch.tensor([o.outputs.embedding for o in outputs])
282
+ scores = (embeddings[:2] @ embeddings[2:].T)
283
+ print(scores.tolist())
284
+ # [[0.8516960144042969, 0.24043934047222137], [0.33099934458732605, 0.7905282974243164]]
285
+ ```
286
+
287
+ <details>
288
+ <summary><b>Transformers Usage</b></summary>
289
+
290
+ ```python
291
+ # Requires transformers>=4.51.0
292
+ import torch
293
+ import torch.nn.functional as F
294
+
295
+ from torch import Tensor
296
+ from transformers import AutoTokenizer, AutoModel
297
+
298
+
299
+ tokenizer = AutoTokenizer.from_pretrained('./checkpoints/E2Rank-0.6B', padding_side='left')
300
+ model = AutoModel.from_pretrained('./checkpoints/E2Rank-0.6B')
301
+
302
+
303
+ def last_token_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:
304
+ left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
305
+ if left_padding:
306
+ return last_hidden_states[:, -1]
307
+ else:
308
+ sequence_lengths = attention_mask.sum(dim=1) - 1
309
+ batch_size = last_hidden_states.shape[0]
310
+ return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
311
+
312
+
313
+ def get_listwise_prompt(task_description: str, query: str, documents: list[str], num_input_docs: int = 20) -> str:
314
+ input_docs = documents[:num_input_docs]
315
+ input_docs = "\n".join([f"[{i}] {doc}" for i, doc in enumerate(input_docs, start=1)])
316
+ messages = [{
317
+ "role": "user",
318
+ "content": f'{task_description}\nDocuments:\n{input_docs}Search Query:{query}'
319
+ }]
320
+ text = tokenizer.apply_chat_template(
321
+ messages,
322
+ tokenize=False,
323
+ add_generation_prompt=True,
324
+ enable_thinking=False,
325
+ )
326
+ return text
327
+
328
+ task = 'Given a web search query and some relevant documents, rerank the documents that answer the query:'
329
+
330
+ queries = [
331
+ 'What is the capital of China?',
332
+ 'Explain gravity'
333
+ ]
334
+
335
+ # No need to add instruction for retrieval documents
336
+ documents = [
337
+ "The capital of China is Beijing.",
338
+ "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."
339
+ ]
340
+ documents = [doc + "<|endoftext|>" for doc in documents]
341
+
342
+ pseudo_queries = [
343
+ get_listwise_prompt(task, queries[0], documents),
344
+ get_listwise_prompt(task, queries[1], documents)
345
+ ] # no need to add the EOS token here
346
+
347
+ input_texts = pseudo_queries + documents
348
+
349
+
350
+ max_length = 8192
351
+ # Tokenize the input texts
352
+ batch_dict = tokenizer(
353
+ input_texts,
354
+ padding=True,
355
+ truncation=True,
356
+ max_length=max_length,
357
+ return_tensors="pt",
358
+ )
359
+ batch_dict.to(model.device)
360
+ with torch.no_grad():
361
+ outputs = model(**batch_dict)
362
+ embeddings = last_token_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
363
+
364
+ # normalize embeddings
365
+ embeddings = F.normalize(embeddings, p=2, dim=1)
366
+ scores = (embeddings[:2] @ embeddings[2:].T)
367
+
368
+ print(scores.tolist())
369
+ # [[0.8513513207435608, 0.24268491566181183], [0.33154672384262085, 0.7923378944396973]]
370
+ ```
371
+ </details>
372
+
373
+ ### End-to-end search
374
+
375
+ Since E2Rank extends a single text embedding model to perform both high-quality retrieval and listwise reranking, you can directly use it to build an end-to-end search system. By reusing the embeddings computed during the retrieval stage, E2Rank only need to compute the pseudo query's embedding and can efficiently rerank the retrieved documents with minimal additional computational overhead.
376
+
377
+ Example code is comming soon.
378
+
379
+
380
+ # 🚩 Citation
381
+
382
+ If this work is helpful, please kindly cite as:
383
+
384
+ ```bibtext
385
+
386
+ ```
387
+
388
+ if you have any questions, please feel free to contact via qiliu6777[AT]gmail.com or create an issue.
389
+
390
+ <!-- ## Star History
391
+
392
+ <div align="center">
393
+
394
+ [![Star History Chart](https://api.star-history.com/svg?repos=Alibaba-NLP/E2Rank&type=Date)](https://www.star-history.com/#Alibaba-NLP/WebAgent&Date)
395
+
396
+ </div> -->