AIArchiveInfo/Qwen3-Reranker-4B
010
1---2license: apache-2.03base_model:4- Qwen/Qwen3-4B-Base5library_name: transformers6tags:7- sentence-transformers8pipeline_tag: text-ranking9---10 11> **Byte-identical preservation mirror** of [`Qwen/Qwen3-Reranker-4B`](https://huggingface.co/Qwen/Qwen3-Reranker-4B) at revision [`22e683669bc0`](https://huggingface.co/Qwen/Qwen3-Reranker-4B/tree/22e683669bc0f0bd69640a1354a6d0aebcfeede5), archived 2026-09-25 by AIArchive. All credit belongs to the original authors. No weights were trained, fine-tuned, or altered in any way. The original license (apache-2.0) is included verbatim and continues to govern this copy.12 13# Qwen3-Reranker-4B14 15<p align="center">16 <img src="https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/logo_qwen3.png" width="400"/>17<p>18 19## Highlights20 21The 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.22 23**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.24 25**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.26 27**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.28 29**Qwen3-Reranker-4B** has the following features:30 31- Model Type: Text Reranking32- Supported Languages: 100+ Languages33- Number of Paramaters: 4B34- Context Length: 32k35 36For 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).37 38## Qwen3 Embedding Series Model list39 40| Model Type | Models | Size | Layers | Sequence Length | Embedding Dimension | MRL Support | Instruction Aware |41|------------------|----------------------|------|--------|-----------------|---------------------|-------------|----------------|42| Text Embedding | [Qwen3-Embedding-0.6B](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B) | 0.6B | 28 | 32K | 1024 | Yes | Yes |43| Text Embedding | [Qwen3-Embedding-4B](https://huggingface.co/Qwen/Qwen3-Embedding-4B) | 4B | 36 | 32K | 2560 | Yes | Yes |44| Text Embedding | [Qwen3-Embedding-8B](https://huggingface.co/Qwen/Qwen3-Embedding-8B) | 8B | 36 | 32K | 4096 | Yes | Yes |45| Text Reranking | [Qwen3-Reranker-0.6B](https://huggingface.co/Qwen/Qwen3-Reranker-0.6B) | 0.6B | 28 | 32K | - | - | Yes |46| Text Reranking | [Qwen3-Reranker-4B](https://huggingface.co/Qwen/Qwen3-Reranker-4B) | 4B | 36 | 32K | - | - | Yes |47| Text Reranking | [Qwen3-Reranker-8B](https://huggingface.co/Qwen/Qwen3-Reranker-8B) | 8B | 36 | 32K | - | - | Yes |48 49> **Note**:50> - `MRL Support` indicates whether the embedding model supports custom dimensions for the final embedding. 51> - `Instruction Aware` notes whether the embedding or reranking model supports customizing the input instruction according to different tasks.52> - 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.53 54 55## Usage56 57### Using Sentence Transformers58 59Install Sentence Transformers:60```bash61pip install sentence_transformers62```63 64```python65from sentence_transformers import CrossEncoder66 67model = CrossEncoder("Qwen/Qwen3-Reranker-4B")68 69query = "What is the capital of China?"70documents = [71 "The capital of China is Beijing.",72 "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.",73]74 75pairs = [(query, doc) for doc in documents]76scores = model.predict(pairs)77print(scores)78# [ 6.4375 -14.375 ]79 80rankings = model.rank(query, documents)81print(rankings)82# [{'corpus_id': 0, 'score': 6.4375}, {'corpus_id': 1, 'score': -14.375}]83```84 85By default, scores are raw logit differences. To get 0-1 probability scores, pass a Sigmoid activation function:86```python87scores = model.predict([(query, doc) for doc in documents], activation_fn=torch.nn.Sigmoid())88```89 90The model uses a default prompt `"query"` which injects the instruction `"Given a web search query, retrieve relevant passages that answer the query"` into the chat template. You can provide a custom instruction via the `prompts` parameter:91```python92model = CrossEncoder(93 "Qwen/Qwen3-Reranker-4B",94 prompts={"classification": "Classify whether the document matches the query topic"},95 default_prompt_name="classification",96)97```98 99### Using Transformers100 101With Transformers versions earlier than 4.51.0, you may encounter the following error:102```103KeyError: 'qwen3'104```105 106```python107# Requires transformers>=4.51.0108import torch109from transformers import AutoModel, AutoTokenizer, AutoModelForCausalLM110 111def format_instruction(instruction, query, doc):112 if instruction is None:113 instruction = 'Given a web search query, retrieve relevant passages that answer the query'114 output = "<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}".format(instruction=instruction,query=query, doc=doc)115 return output116 117def process_inputs(pairs):118 inputs = tokenizer(119 pairs, padding=False, truncation='longest_first',120 return_attention_mask=False, max_length=max_length - len(prefix_tokens) - len(suffix_tokens)121 )122 for i, ele in enumerate(inputs['input_ids']):123 inputs['input_ids'][i] = prefix_tokens + ele + suffix_tokens124 inputs = tokenizer.pad(inputs, padding=True, return_tensors="pt", max_length=max_length)125 for key in inputs:126 inputs[key] = inputs[key].to(model.device)127 return inputs128 129@torch.no_grad()130def compute_logits(inputs, **kwargs):131 batch_scores = model(**inputs).logits[:, -1, :]132 true_vector = batch_scores[:, token_true_id]133 false_vector = batch_scores[:, token_false_id]134 batch_scores = torch.stack([false_vector, true_vector], dim=1)135 batch_scores = torch.nn.functional.log_softmax(batch_scores, dim=1)136 scores = batch_scores[:, 1].exp().tolist()137 return scores138 139tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-Reranker-4B", padding_side='left')140model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Reranker-4B").eval()141 142# We recommend enabling flash_attention_2 for better acceleration and memory saving.143# model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Reranker-4B", torch_dtype=torch.float16, attn_implementation="flash_attention_2").cuda().eval()144 145token_false_id = tokenizer.convert_tokens_to_ids("no")146token_true_id = tokenizer.convert_tokens_to_ids("yes")147max_length = 8192148 149prefix = "<|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"150suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"151prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)152suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)153 154task = 'Given a web search query, retrieve relevant passages that answer the query'155 156queries = ["What is the capital of China?",157 "Explain gravity",158]159 160documents = [161 "The capital of China is Beijing.",162 "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.",163]164 165pairs = [format_instruction(task, query, doc) for query, doc in zip(queries, documents)]166 167# Tokenize the input texts168inputs = process_inputs(pairs)169scores = compute_logits(inputs)170 171print("scores: ", scores)172```173 174### vLLM Usage 175 176```python177# Requires vllm>=0.8.5178import logging179from typing import Dict, Optional, List180 181import json182import logging183 184import torch185 186from transformers import AutoTokenizer, is_torch_npu_available187from vllm import LLM, SamplingParams188from vllm.distributed.parallel_state import destroy_model_parallel189import gc190import math191from vllm.inputs.data import TokensPrompt192 193 194 195def format_instruction(instruction, query, doc):196 text = [197 {"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\"."},198 {"role": "user", "content": f"<Instruct>: {instruction}\n\n<Query>: {query}\n\n<Document>: {doc}"}199 ]200 return text201 202def process_inputs(pairs, instruction, max_length, suffix_tokens):203 messages = [format_instruction(instruction, query, doc) for query, doc in pairs]204 messages = tokenizer.apply_chat_template(205 messages, tokenize=True, add_generation_prompt=False, enable_thinking=False206 )207 messages = [ele[:max_length] + suffix_tokens for ele in messages]208 messages = [TokensPrompt(prompt_token_ids=ele) for ele in messages]209 return messages210 211def compute_logits(model, messages, sampling_params, true_token, false_token):212 outputs = model.generate(messages, sampling_params, use_tqdm=False)213 scores = []214 for i in range(len(outputs)):215 final_logits = outputs[i].outputs[0].logprobs[-1]216 token_count = len(outputs[i].outputs[0].token_ids)217 if true_token not in final_logits:218 true_logit = -10219 else:220 true_logit = final_logits[true_token].logprob221 if false_token not in final_logits:222 false_logit = -10223 else:224 false_logit = final_logits[false_token].logprob225 true_score = math.exp(true_logit)226 false_score = math.exp(false_logit)227 score = true_score / (true_score + false_score)228 scores.append(score)229 return scores230 231number_of_gpu = torch.cuda.device_count()232tokenizer = AutoTokenizer.from_pretrained('Qwen/Qwen3-Reranker-4B')233model = LLM(model='Qwen/Qwen3-Reranker-4B', tensor_parallel_size=number_of_gpu, max_model_len=10000, enable_prefix_caching=True, gpu_memory_utilization=0.8)234tokenizer.padding_side = "left"235tokenizer.pad_token = tokenizer.eos_token236suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"237max_length=8192238suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)239true_token = tokenizer("yes", add_special_tokens=False).input_ids[0]240false_token = tokenizer("no", add_special_tokens=False).input_ids[0]241sampling_params = SamplingParams(temperature=0, 242 max_tokens=1,243 logprobs=20, 244 allowed_token_ids=[true_token, false_token],245)246 247 248task = 'Given a web search query, retrieve relevant passages that answer the query'249queries = ["What is the capital of China?",250 "Explain gravity",251]252documents = [253 "The capital of China is Beijing.",254 "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.",255]256 257pairs = list(zip(queries, documents))258inputs = process_inputs(pairs, task, max_length-len(suffix_tokens), suffix_tokens)259scores = compute_logits(model, inputs, sampling_params, true_token, false_token)260print('scores', scores)261 262destroy_model_parallel()263```264 265 266๐ **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%.267 268## Evaluation269 270| Model | Param | MTEB-R | CMTEB-R | MMTEB-R | MLDR | MTEB-Code | FollowIR |271|------------------------------------|--------|---------|---------|---------|--------|-----------|----------|272| **Qwen3-Embedding-0.6B** | 0.6B | 61.82 | 71.02 | 64.64 | 50.26 | 75.41 | 5.09 |273| Jina-multilingual-reranker-v2-base | 0.3B | 58.22 | 63.37 | 63.73 | 39.66 | 58.98 | -0.68 |274| gte-multilingual-reranker-base | 0.3B | 59.51 | 74.08 | 59.44 | 66.33 | 54.18 | -1.64 |275| BGE-reranker-v2-m3 | 0.6B | 57.03 | 72.16 | 58.36 | 59.51 | 41.38 | -0.01 |276| **Qwen3-Reranker-0.6B** | 0.6B | 65.80 | 71.31 | 66.36 | 67.28 | 73.42 | 5.41 |277| **Qwen3-Reranker-4B** | 4B | **69.76** | 75.94 | 72.74 | 69.97 | 81.20 | **14.84** |278| **Qwen3-Reranker-8B** | 8B | 69.02 | **77.45** | **72.94** | **70.19** | **81.22** | 8.05 |279 280> **Note**: 281> - 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.282> - 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).283 284## Citation285If you find our work helpful, feel free to give us a cite.286 287```288@article{qwen3embedding,289 title={Qwen3 Embedding: Advancing Text Embedding and Reranking Through Foundation Models},290 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},291 journal={arXiv preprint arXiv:2506.05176},292 year={2025}293}294```