Text Ranking
Transformers
GGUF
conversational
aashish1904 commited on
Commit
e7dd41d
·
verified ·
1 Parent(s): 14cc090

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +259 -0
README.md ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ---
3
+
4
+ license: apache-2.0
5
+ base_model:
6
+ - Qwen/Qwen3-0.6B-Base
7
+ library_name: transformers
8
+ pipeline_tag: text-ranking
9
+
10
+ ---
11
+
12
+ [![QuantFactory Banner](https://lh7-rt.googleusercontent.com/docsz/AD_4nXeiuCm7c8lEwEJuRey9kiVZsRn2W-b4pWlu3-X534V3YmVuVc2ZL-NXg2RkzSOOS2JXGHutDuyyNAUtdJI65jGTo8jT9Y99tMi4H4MqL44Uc5QKG77B0d6-JfIkZHFaUA71-RtjyYZWVIhqsNZcx8-OMaA?key=xt3VSDoCbmTY7o-cwwOFwQ)](https://hf.co/QuantFactory)
13
+
14
+
15
+ # QuantFactory/Qwen3-Reranker-0.6B-GGUF
16
+ This is quantized version of [Qwen/Qwen3-Reranker-0.6B](https://huggingface.co/Qwen/Qwen3-Reranker-0.6B) created using llama.cpp
17
+
18
+ # Original Model Card
19
+
20
+ # Qwen3-Reranker-0.6B
21
+
22
+ <p align="center">
23
+ <img src="https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/logo_qwen3.png" width="400"/>
24
+ <p>
25
+
26
+ ## Highlights
27
+
28
+ The Qwen3 Embedding model series is the latest proprietary model of the Qwen family, specifically designed for text embedding and ranking tasks. Building upon the dense foundational models of the Qwen3 series, it provides a comprehensive range of text embeddings and reranking models in various sizes (0.6B, 4B, and 8B). This series inherits the exceptional multilingual capabilities, long-text understanding, and reasoning skills of its foundational model. The Qwen3 Embedding series represents significant advancements in multiple text embedding and ranking tasks, including text retrieval, code retrieval, text classification, text clustering, and bitext mining.
29
+
30
+ **Exceptional Versatility**: The embedding model has achieved state-of-the-art performance across a wide range of downstream application evaluations. The 8B size embedding model ranks No.1 in the MTEB multilingual leaderboard (as of June 5, 2025, score 70.58), while the reranking model excels in various text retrieval scenarios.
31
+
32
+ **Comprehensive Flexibility**: The Qwen3 Embedding series offers a full spectrum of sizes (from 0.6B to 8B) for both embedding and reranking models, catering to diverse use cases that prioritize efficiency and effectiveness. Developers can seamlessly combine these two modules. Additionally, the embedding model allows for flexible vector definitions across all dimensions, and both embedding and reranking models support user-defined instructions to enhance performance for specific tasks, languages, or scenarios.
33
+
34
+ **Multilingual Capability**: The Qwen3 Embedding series offer support for over 100 languages, thanks to the multilingual capabilites of Qwen3 models. This includes various programming languages, and provides robust multilingual, cross-lingual, and code retrieval capabilities.
35
+
36
+ ## Model Overview
37
+
38
+ **Qwen3-Reranker-0.6B** has the following features:
39
+
40
+ - Model Type: Text Reranking
41
+ - Supported Languages: 100+ Languages
42
+ - Number of Paramaters: 0.6B
43
+ - Context Length: 32k
44
+
45
+ For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our [blog](https://qwenlm.github.io/blog/qwen3-embedding/), [GitHub](https://github.com/QwenLM/Qwen3-Embedding).
46
+
47
+ ## Qwen3 Embedding Series Model list
48
+
49
+ | Model Type | Models | Size | Layers | Sequence Length | Embedding Dimension | MRL Support | Instruction Aware |
50
+ |------------------|----------------------|------|--------|-----------------|---------------------|-------------|----------------|
51
+ | Text Embedding | [Qwen3-Embedding-0.6B](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B) | 0.6B | 28 | 32K | 1024 | Yes | Yes |
52
+ | Text Embedding | [Qwen3-Embedding-4B](https://huggingface.co/Qwen/Qwen3-Embedding-4B) | 4B | 36 | 32K | 2560 | Yes | Yes |
53
+ | Text Embedding | [Qwen3-Embedding-8B](https://huggingface.co/Qwen/Qwen3-Embedding-8B) | 8B | 36 | 32K | 4096 | Yes | Yes |
54
+ | Text Reranking | [Qwen3-Reranker-0.6B](https://huggingface.co/Qwen/Qwen3-Reranker-0.6B) | 0.6B | 28 | 32K | - | - | Yes |
55
+ | Text Reranking | [Qwen3-Reranker-4B](https://huggingface.co/Qwen/Qwen3-Reranker-4B) | 4B | 36 | 32K | - | - | Yes |
56
+ | Text Reranking | [Qwen3-Reranker-8B](https://huggingface.co/Qwen/Qwen3-Reranker-8B) | 8B | 36 | 32K | - | - | Yes |
57
+
58
+ > **Note**:
59
+ > - `MRL Support` indicates whether the embedding model supports custom dimensions for the final embedding.
60
+ > - `Instruction Aware` notes whether the embedding or reranking model supports customizing the input instruction according to different tasks.
61
+ > - Our evaluation indicates that, 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.
62
+
63
+
64
+ ## Usage
65
+
66
+ With Transformers versions earlier than 4.51.0, you may encounter the following error:
67
+ ```
68
+ KeyError: 'qwen3'
69
+ ```
70
+
71
+ ### Transformers Usage
72
+
73
+ ```python
74
+ # Requires transformers>=4.51.0
75
+ import torch
76
+ from transformers import AutoModel, AutoTokenizer, AutoModelForCausalLM
77
+
78
+ def format_instruction(instruction, query, doc):
79
+ if instruction is None:
80
+ instruction = 'Given a web search query, retrieve relevant passages that answer the query'
81
+ output = "<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}".format(instruction=instruction,query=query, doc=doc)
82
+ return output
83
+
84
+ def process_inputs(pairs):
85
+ inputs = tokenizer(
86
+ pairs, padding=False, truncation='longest_first',
87
+ return_attention_mask=False, max_length=max_length - len(prefix_tokens) - len(suffix_tokens)
88
+ )
89
+ for i, ele in enumerate(inputs['input_ids']):
90
+ inputs['input_ids'][i] = prefix_tokens + ele + suffix_tokens
91
+ inputs = tokenizer.pad(inputs, padding=True, return_tensors="pt", max_length=max_length)
92
+ for key in inputs:
93
+ inputs[key] = inputs[key].to(model.device)
94
+ return inputs
95
+
96
+ @torch.no_grad()
97
+ def compute_logits(inputs, **kwargs):
98
+ batch_scores = model(**inputs).logits[:, -1, :]
99
+ true_vector = batch_scores[:, token_true_id]
100
+ false_vector = batch_scores[:, token_false_id]
101
+ batch_scores = torch.stack([false_vector, true_vector], dim=1)
102
+ batch_scores = torch.nn.functional.log_softmax(batch_scores, dim=1)
103
+ scores = batch_scores[:, 1].exp().tolist()
104
+ return scores
105
+
106
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-Reranker-0.6B", padding_side='left')
107
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Reranker-0.6B").eval()
108
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving.
109
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Reranker-0.6B", torch_dtype=torch.float16, attn_implementation="flash_attention_2").cuda().eval()
110
+ token_false_id = tokenizer.convert_tokens_to_ids("no")
111
+ token_true_id = tokenizer.convert_tokens_to_ids("yes")
112
+ max_length = 8192
113
+
114
+ 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"
115
+ suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
116
+ prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)
117
+ suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
118
+
119
+ task = 'Given a web search query, retrieve relevant passages that answer the query'
120
+
121
+ queries = ["What is the capital of China?",
122
+ "Explain gravity",
123
+ ]
124
+
125
+ documents = [
126
+ "The capital of China is Beijing.",
127
+ "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.",
128
+ ]
129
+
130
+ pairs = [format_instruction(task, query, doc) for query, doc in zip(queries, documents)]
131
+
132
+ # Tokenize the input texts
133
+ inputs = process_inputs(pairs)
134
+ scores = compute_logits(inputs)
135
+
136
+ print("scores: ", scores)
137
+ ```
138
+
139
+
140
+ ### vLLM Usage
141
+
142
+ ```python
143
+ # Requires vllm>=0.8.5
144
+ import logging
145
+ from typing import Dict, Optional, List
146
+
147
+ import json
148
+ import logging
149
+
150
+ import torch
151
+
152
+ from transformers import AutoTokenizer, is_torch_npu_available
153
+ from vllm import LLM, SamplingParams
154
+ from vllm.distributed.parallel_state import destroy_model_parallel
155
+ import gc
156
+ import math
157
+ from vllm.inputs.data import TokensPrompt
158
+
159
+
160
+
161
+ def format_instruction(instruction, query, doc):
162
+ text = [
163
+ {"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\"."},
164
+ {"role": "user", "content": f"<Instruct>: {instruction}\n\n<Query>: {query}\n\n<Document>: {doc}"}
165
+ ]
166
+ return text
167
+
168
+ def process_inputs(pairs, instruction, max_length, suffix_tokens):
169
+ messages = [format_instruction(instruction, query, doc) for query, doc in pairs]
170
+ messages = tokenizer.apply_chat_template(
171
+ messages, tokenize=True, add_generation_prompt=False, enable_thinking=False
172
+ )
173
+ messages = [ele[:max_length] + suffix_tokens for ele in messages]
174
+ messages = [TokensPrompt(prompt_token_ids=ele) for ele in messages]
175
+ return messages
176
+
177
+ def compute_logits(model, messages, sampling_params, true_token, false_token):
178
+ outputs = model.generate(messages, sampling_params, use_tqdm=False)
179
+ scores = []
180
+ for i in range(len(outputs)):
181
+ final_logits = outputs[i].outputs[0].logprobs[-1]
182
+ token_count = len(outputs[i].outputs[0].token_ids)
183
+ if true_token not in final_logits:
184
+ true_logit = -10
185
+ else:
186
+ true_logit = final_logits[true_token].logprob
187
+ if false_token not in final_logits:
188
+ false_logit = -10
189
+ else:
190
+ false_logit = final_logits[false_token].logprob
191
+ true_score = math.exp(true_logit)
192
+ false_score = math.exp(false_logit)
193
+ score = true_score / (true_score + false_score)
194
+ scores.append(score)
195
+ return scores
196
+
197
+ number_of_gpu = torch.cuda.device_count()
198
+ tokenizer = AutoTokenizer.from_pretrained('Qwen/Qwen3-Reranker-0.6B')
199
+ model = LLM(model='Qwen/Qwen3-Reranker-0.6B', tensor_parallel_size=number_of_gpu, max_model_len=10000, enable_prefix_caching=True, gpu_memory_utilization=0.8)
200
+ tokenizer.padding_side = "left"
201
+ tokenizer.pad_token = tokenizer.eos_token
202
+ suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
203
+ max_length=8192
204
+ suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
205
+ true_token = tokenizer("yes", add_special_tokens=False).input_ids[0]
206
+ false_token = tokenizer("no", add_special_tokens=False).input_ids[0]
207
+ sampling_params = SamplingParams(temperature=0,
208
+ max_tokens=1,
209
+ logprobs=20,
210
+ allowed_token_ids=[true_token, false_token],
211
+ )
212
+
213
+
214
+ task = 'Given a web search query, retrieve relevant passages that answer the query'
215
+ queries = ["What is the capital of China?",
216
+ "Explain gravity",
217
+ ]
218
+ documents = [
219
+ "The capital of China is Beijing.",
220
+ "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.",
221
+ ]
222
+
223
+ pairs = list(zip(queries, documents))
224
+ inputs = process_inputs(pairs, task, max_length-len(suffix_tokens), suffix_tokens)
225
+ scores = compute_logits(model, inputs, sampling_params, true_token, false_token)
226
+ print('scores', scores)
227
+
228
+ destroy_model_parallel()
229
+ ```
230
+
231
+ 📌 **Tip**: 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%.
232
+
233
+ ## Evaluation
234
+
235
+ | Model | Param | MTEB-R | CMTEB-R | MMTEB-R | MLDR | MTEB-Code | FollowIR |
236
+ |------------------------------------|--------|---------|---------|---------|--------|-----------|----------|
237
+ | **Qwen3-Embedding-0.6B** | 0.6B | 61.82 | 71.02 | 64.64 | 50.26 | 75.41 | 5.09 |
238
+ | Jina-multilingual-reranker-v2-base | 0.3B | 58.22 | 63.37 | 63.73 | 39.66 | 58.98 | -0.68 |
239
+ | gte-multilingual-reranker-base | 0.3B | 59.51 | 74.08 | 59.44 | 66.33 | 54.18 | -1.64 |
240
+ | BGE-reranker-v2-m3 | 0.6B | 57.03 | 72.16 | 58.36 | 59.51 | 41.38 | -0.01 |
241
+ | **Qwen3-Reranker-0.6B** | 0.6B | 65.80 | 71.31 | 66.36 | 67.28 | 73.42 | 5.41 |
242
+ | **Qwen3-Reranker-4B** | 4B | **69.76** | 75.94 | 72.74 | 69.97 | 81.20 | **14.84** |
243
+ | **Qwen3-Reranker-8B** | 8B | 69.02 | **77.45** | **72.94** | **70.19** | **81.22** | 8.05 |
244
+
245
+ > **Note**:
246
+ > - Evaluation results for reranking models. We use the retrieval subsets of MTEB(eng, v2), MTEB(cmn, v1), MMTEB and MTEB (Code), which are MTEB-R, CMTEB-R, MMTEB-R and MTEB-Code.
247
+ > - All scores are our runs based on the top-100 candidates retrieved by dense embedding model [Qwen3-Embedding-0.6B](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B).
248
+
249
+ ## Citation
250
+ If you find our work helpful, feel free to give us a cite.
251
+
252
+ ```
253
+ @article{qwen3embedding,
254
+ title={Qwen3 Embedding: Advancing Text Embedding and Reranking Through Foundation Models},
255
+ author={Zhang, Yanzhao and Li, Mingxin and Long, Dingkun and Zhang, Xin and Lin, Huan and Yang, Baosong and Xie, Pengjun and Yang, An and Liu, Dayiheng and Lin, Junyang and Huang, Fei and Zhou, Jingren},
256
+ journal={arXiv preprint arXiv:2506.05176},
257
+ year={2025}
258
+ }
259
+ ```