zhiqing commited on
Commit
2405522
·
verified ·
1 Parent(s): 0d0e81b

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +248 -0
README.md ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model:
4
+ - Qwen/Qwen3-Reranker-0.6B
5
+ library_name: transformers
6
+ pipeline_tag: text-classification
7
+ ---
8
+ # Qwen3-Reranker-0.6B
9
+
10
+ <p align="center">
11
+ <img src="https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/logo_qwen3.png" width="400"/>
12
+ <p>
13
+
14
+ ## Highlights
15
+
16
+ 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.
17
+
18
+ **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.
19
+
20
+ **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.
21
+
22
+ **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.
23
+
24
+ ## Model Overview
25
+
26
+ **Qwen3-Reranker-0.6B** has the following features:
27
+
28
+ - Model Type: Text Reranking
29
+ - Supported Languages: 100+ Languages
30
+ - Number of Paramaters: 0.6B
31
+ - Context Length: 32k
32
+
33
+ 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).
34
+
35
+ ## Qwen3 Embedding Series Model list
36
+
37
+ | Model Type | Models | Size | Layers | Sequence Length | Embedding Dimension | MRL Support | Instruction Aware |
38
+ |------------------|----------------------|------|--------|-----------------|---------------------|-------------|----------------|
39
+ | Text Embedding | [Qwen3-Embedding-0.6B](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B) | 0.6B | 28 | 32K | 1024 | Yes | Yes |
40
+ | Text Embedding | [Qwen3-Embedding-4B](https://huggingface.co/Qwen/Qwen3-Embedding-4B) | 4B | 36 | 32K | 2560 | Yes | Yes |
41
+ | Text Embedding | [Qwen3-Embedding-8B](https://huggingface.co/Qwen/Qwen3-Embedding-8B) | 8B | 36 | 32K | 4096 | Yes | Yes |
42
+ | Text Reranking | [Qwen3-Reranker-0.6B](https://huggingface.co/Qwen/Qwen3-Reranker-0.6B) | 0.6B | 28 | 32K | - | - | Yes |
43
+ | Text Reranking | [Qwen3-Reranker-4B](https://huggingface.co/Qwen/Qwen3-Reranker-4B) | 4B | 36 | 32K | - | - | Yes |
44
+ | Text Reranking | [Qwen3-Reranker-8B](https://huggingface.co/Qwen/Qwen3-Reranker-8B) | 8B | 36 | 32K | - | - | Yes |
45
+
46
+ > **Note**:
47
+ > - `MRL Support` indicates whether the embedding model supports custom dimensions for the final embedding.
48
+ > - `Instruction Aware` notes whether the embedding or reranking model supports customizing the input instruction according to different tasks.
49
+ > - 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.
50
+
51
+
52
+ ## Usage
53
+
54
+ With Transformers versions earlier than 4.51.0, you may encounter the following error:
55
+ ```
56
+ KeyError: 'qwen3'
57
+ ```
58
+
59
+ ### Transformers Usage
60
+
61
+ ```python
62
+ # Requires transformers>=4.51.0
63
+ import torch
64
+ from transformers import AutoModel, AutoTokenizer, AutoModelForCausalLM
65
+
66
+ def format_instruction(instruction, query, doc):
67
+ if instruction is None:
68
+ instruction = 'Given a web search query, retrieve relevant passages that answer the query'
69
+ output = "<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}".format(instruction=instruction,query=query, doc=doc)
70
+ return output
71
+
72
+ def process_inputs(pairs):
73
+ inputs = tokenizer(
74
+ pairs, padding=False, truncation='longest_first',
75
+ return_attention_mask=False, max_length=max_length - len(prefix_tokens) - len(suffix_tokens)
76
+ )
77
+ for i, ele in enumerate(inputs['input_ids']):
78
+ inputs['input_ids'][i] = prefix_tokens + ele + suffix_tokens
79
+ inputs = tokenizer.pad(inputs, padding=True, return_tensors="pt", max_length=max_length)
80
+ for key in inputs:
81
+ inputs[key] = inputs[key].to(model.device)
82
+ return inputs
83
+
84
+ @torch.no_grad()
85
+ def compute_logits(inputs, **kwargs):
86
+ batch_scores = model(**inputs).logits[:, -1, :]
87
+ true_vector = batch_scores[:, token_true_id]
88
+ false_vector = batch_scores[:, token_false_id]
89
+ batch_scores = torch.stack([false_vector, true_vector], dim=1)
90
+ batch_scores = torch.nn.functional.log_softmax(batch_scores, dim=1)
91
+ scores = batch_scores[:, 1].exp().tolist()
92
+ return scores
93
+
94
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-Reranker-0.6B", padding_side='left')
95
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Reranker-0.6B").eval()
96
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving.
97
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Reranker-0.6B", torch_dtype=torch.float16, attn_implementation="flash_attention_2").cuda().eval()
98
+ token_false_id = tokenizer.convert_tokens_to_ids("no")
99
+ token_true_id = tokenizer.convert_tokens_to_ids("yes")
100
+ max_length = 8192
101
+
102
+ 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"
103
+ suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
104
+ prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)
105
+ suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
106
+
107
+ task = 'Given a web search query, retrieve relevant passages that answer the query'
108
+
109
+ queries = ["What is the capital of China?",
110
+ "Explain gravity",
111
+ ]
112
+
113
+ documents = [
114
+ "The capital of China is Beijing.",
115
+ "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.",
116
+ ]
117
+
118
+ pairs = [format_instruction(task, query, doc) for query, doc in zip(queries, documents)]
119
+
120
+ # Tokenize the input texts
121
+ inputs = process_inputs(pairs)
122
+ scores = compute_logits(inputs)
123
+
124
+ print("scores: ", scores)
125
+ ```
126
+
127
+
128
+ ### vLLM Usage
129
+
130
+ ```python
131
+ # Requires vllm>=0.8.5
132
+ import logging
133
+ from typing import Dict, Optional, List
134
+
135
+ import json
136
+ import logging
137
+
138
+ import torch
139
+
140
+ from transformers import AutoTokenizer, is_torch_npu_available
141
+ from vllm import LLM, SamplingParams
142
+ from vllm.distributed.parallel_state import destroy_model_parallel
143
+ import gc
144
+ import math
145
+ from vllm.inputs.data import TokensPrompt
146
+
147
+
148
+
149
+ def format_instruction(instruction, query, doc):
150
+ text = [
151
+ {"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\"."},
152
+ {"role": "user", "content": f"<Instruct>: {instruction}\n\n<Query>: {query}\n\n<Document>: {doc}"}
153
+ ]
154
+ return text
155
+
156
+ def process_inputs(pairs, instruction, max_length, suffix_tokens):
157
+ messages = [format_instruction(instruction, query, doc) for query, doc in pairs]
158
+ messages = tokenizer.apply_chat_template(
159
+ messages, tokenize=True, add_generation_prompt=False, enable_thinking=False
160
+ )
161
+ messages = [ele[:max_length] + suffix_tokens for ele in messages]
162
+ messages = [TokensPrompt(prompt_token_ids=ele) for ele in messages]
163
+ return messages
164
+
165
+ def compute_logits(model, messages, sampling_params, true_token, false_token):
166
+ outputs = model.generate(messages, sampling_params, use_tqdm=False)
167
+ scores = []
168
+ for i in range(len(outputs)):
169
+ final_logits = outputs[i].outputs[0].logprobs[-1]
170
+ token_count = len(outputs[i].outputs[0].token_ids)
171
+ if true_token not in final_logits:
172
+ true_logit = -10
173
+ else:
174
+ true_logit = final_logits[true_token].logprob
175
+ if false_token not in final_logits:
176
+ false_logit = -10
177
+ else:
178
+ false_logit = final_logits[false_token].logprob
179
+ true_score = math.exp(true_logit)
180
+ false_score = math.exp(false_logit)
181
+ score = true_score / (true_score + false_score)
182
+ scores.append(score)
183
+ return scores
184
+
185
+ number_of_gpu = torch.cuda.device_count()
186
+ tokenizer = AutoTokenizer.from_pretrained('Qwen/Qwen3-Reranker-0.6B')
187
+ 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)
188
+ tokenizer.padding_side = "left"
189
+ tokenizer.pad_token = tokenizer.eos_token
190
+ suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
191
+ max_length=8192
192
+ suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
193
+ true_token = tokenizer("yes", add_special_tokens=False).input_ids[0]
194
+ false_token = tokenizer("no", add_special_tokens=False).input_ids[0]
195
+ sampling_params = SamplingParams(temperature=0,
196
+ max_tokens=1,
197
+ logprobs=20,
198
+ allowed_token_ids=[true_token, false_token],
199
+ )
200
+
201
+
202
+ task = 'Given a web search query, retrieve relevant passages that answer the query'
203
+ queries = ["What is the capital of China?",
204
+ "Explain gravity",
205
+ ]
206
+ documents = [
207
+ "The capital of China is Beijing.",
208
+ "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.",
209
+ ]
210
+
211
+ pairs = list(zip(queries, documents))
212
+ inputs = process_inputs(pairs, task, max_length-len(suffix_tokens), suffix_tokens)
213
+ scores = compute_logits(model, inputs, sampling_params, true_token, false_token)
214
+ print('scores', scores)
215
+
216
+ destroy_model_parallel()
217
+ ```
218
+
219
+ 📌 **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%.
220
+
221
+ ## Evaluation
222
+
223
+ | Model | Param | MTEB-R | CMTEB-R | MMTEB-R | MLDR | MTEB-Code | FollowIR |
224
+ |------------------------------------|--------|---------|---------|---------|--------|-----------|----------|
225
+ | **Qwen3-Embedding-0.6B** | 0.6B | 61.82 | 71.02 | 64.64 | 50.26 | 75.41 | 5.09 |
226
+ | Jina-multilingual-reranker-v2-base | 0.3B | 58.22 | 63.37 | 63.73 | 39.66 | 58.98 | -0.68 |
227
+ | gte-multilingual-reranker-base | 0.3B | 59.51 | 74.08 | 59.44 | 66.33 | 54.18 | -1.64 |
228
+ | BGE-reranker-v2-m3 | 0.6B | 57.03 | 72.16 | 58.36 | 59.51 | 41.38 | -0.01 |
229
+ | **Qwen3-Reranker-0.6B** | 0.6B | 65.80 | 71.31 | 66.36 | 67.28 | 73.42 | 5.41 |
230
+ | **Qwen3-Reranker-4B** | 1.7B | **69.76** | 75.94 | 72.74 | 69.97 | 81.20 | **14.84** |
231
+ | **Qwen3-Reranker-8B** | 8B | 69.02 | **77.45** | **72.94** | **70.19** | **81.22** | 8.05 |
232
+
233
+ > **Note**:
234
+ > - 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.
235
+ > - 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).
236
+
237
+ ## Citation
238
+ If you find our work helpful, feel free to give us a cite.
239
+
240
+ ```
241
+ @misc{qwen3-embedding,
242
+ title = {Qwen3-Embedding},
243
+ url = {https://qwenlm.github.io/blog/qwen3/},
244
+ author = {Qwen Team},
245
+ month = {May},
246
+ year = {2025}
247
+ }
248
+ ```