Views
No views yet

[!NOTE] This model is based on Qwen3-Reranker-4B-seq-cls model, part of the Qwen3 Reranker series, modified as a sequence classification model instead. See Updated Usage for details on how to use it, or Original Usage for the original usage.
{title} {description} formatGiven a text with a mention enclosed between the '[' and ']' characters, retrieve relevant entities that the mention refers to.[ and ] characters1from vllm import LLM
2
3MODEL_NAME = "samyhaff/Qwen3-Reranker-4B-seq-cls-entity-disambiguation"
4
5PREFIX = '<|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
6"no".<|im_end|>\n<|im_start|>user\n'
7SUFFIX = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
8TASK = "Given a text with a mention enclosed between the '[' and ']' characters, retrieve relevant entities that the mention refers to."
9
10model = LLM(model=MODEL_NAME, runner="pooling")
11
12# Enclose the mention between '[' and ']' in the context
13context = "In 1969, [Armstrong] became the first human to walk on the Moon."
14
15# Candidates as title, description couples
16candidates = [
17 ("Neil Armstrong", "American astronaut and aeronautical engineer who was the first person to walk on the Moon."),
18 ("Louis Armstrong", "American jazz trumpeter, vocalist, and one of the most influential figures in jazz history."),
19]
20
21query = f"{PREFIX}<Instruct>: {TASK}\n<Query>: {context}\n"
22documents = [
23 f"<Document>: {title} {description}{SUFFIX}"
24 for title, description in candidates
25]
26
27outputs = model.score(query, documents)
28scores = [out.outputs.score for out in outputs]
29best_idx = scores.index(max(scores))
30print(f"Best candidate: {candidates[best_idx][0]}") # Neil Armstrong@article{qwen3embedding,
title={LELA: an LLM-based Entity Linking Approach with Zero-Shot Domain Adaptation},
author={Samy Haffoudhi, Fabian M. Suchanek, Nils Holzenberger},
journal={arXiv preprint arXiv:2601.05192},
year={2026}
}
@article{qwen3embedding,
title={Qwen3 Embedding: Advancing Text Embedding and Reranking Through Foundation Models},
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},
journal={arXiv preprint arXiv:2506.05176},
year={2025}
}| Model Type | Models | Size | Layers | Sequence Length | Embedding Dimension | MRL Support | Instruction Aware |
|---|---|---|---|---|---|---|---|
| Text Embedding | Qwen3-Embedding-0.6B | 0.6B | 28 | 32K | 1024 | Yes | Yes |
| Text Embedding | Qwen3-Embedding-4B | 4B | 36 | 32K | 2560 | Yes | Yes |
| Text Embedding | Qwen3-Embedding-8B | 8B | 36 | 32K | 4096 | Yes | Yes |
| Text Reranking | Qwen3-Reranker-0.6B | 0.6B | 28 | 32K | - | - | Yes |
| Text Reranking | Qwen3-Reranker-4B | 4B | 36 | 32K | - | - | Yes |
| Text Reranking | Qwen3-Reranker-8B | 8B | 36 | 32K | - | - | Yes |
Note:
MRL Supportindicates whether the embedding model supports custom dimensions for the final embedding.Instruction Awarenotes whether the embedding or reranking model supports customizing the input instruction according to different tasks.- 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.
KeyError: 'qwen3'1# Requires transformers>=4.51.0
2from sentence_transformers import CrossEncoder
3
4
5def format_queries(query, instruction=None):
6 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'
7 if instruction is None:
8 instruction = (
9 "Given a web search query, retrieve relevant passages that answer the query"
10 )
11 return f"{prefix}<Instruct>: {instruction}\n<Query>: {query}\n"
12
13
14def format_document(document):
15 suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
16 return f"<Document>: {document}{suffix}"
17
18
19model = CrossEncoder("tomaarsen/Qwen3-Reranker-4B-seq-cls")
20
21task = "Given a web search query, retrieve relevant passages that answer the query"
22
23queries = [
24 "Which planet is known as the Red Planet?",
25 "Which planet is known as the Red Planet?",
26 "Which planet is known as the Red Planet?",
27 "Which planet is known as the Red Planet?",
28]
29
30documents = [
31 "Venus is often called Earth's twin because of its similar size and proximity.",
32 "Mars, known for its reddish appearance, is often referred to as the Red Planet.",
33 "Jupiter, the largest planet in our solar system, has a prominent red spot.",
34 "Saturn, famous for its rings, is sometimes mistaken for the Red Planet.",
35]
36
37pairs = [
38 [format_queries(query, task), format_document(doc)]
39 for query, doc in zip(queries, documents)
40]
41scores = model.predict(pairs)
42print(scores.tolist())
43# [0.00012360254186205566, 0.98269122838974, 0.0014677430735900998, 0.2251107543706894]1# Requires transformers>=4.51.0
2from transformers import AutoModelForSequenceClassification, AutoTokenizer
3
4
5def format_instruction(instruction, query, doc):
6 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'
7 suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
8 if instruction is None:
9 instruction = (
10 "Given a web search query, retrieve relevant passages that answer the query"
11 )
12 output = f"{prefix}<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}{suffix}"
13 return output
14
15
16tokenizer = AutoTokenizer.from_pretrained("tomaarsen/Qwen3-Reranker-4B-seq-cls", padding_side="left")
17model = AutoModelForSequenceClassification.from_pretrained("tomaarsen/Qwen3-Reranker-4B-seq-cls").eval()
18# We recommend enabling flash_attention_2 for better acceleration and memory saving.
19# model = AutoModelForSequenceClassification.from_pretrained("tomaarsen/Qwen3-Reranker-4B-seq-cls", torch_dtype=torch.float16, attn_implementation="flash_attention_2").cuda().eval()
20max_length = 8192
21
22task = "Given a web search query, retrieve relevant passages that answer the query"
23
24queries = [
25 "Which planet is known as the Red Planet?",
26 "Which planet is known as the Red Planet?",
27 "Which planet is known as the Red Planet?",
28 "Which planet is known as the Red Planet?",
29]
30
31documents = [
32 "Venus is often called Earth's twin because of its similar size and proximity.",
33 "Mars, known for its reddish appearance, is often referred to as the Red Planet.",
34 "Jupiter, the largest planet in our solar system, has a prominent red spot.",
35 "Saturn, famous for its rings, is sometimes mistaken for the Red Planet.",
36]
37
38pairs = [format_instruction(task, query, doc) for query, doc in zip(queries, documents)]
39inputs = tokenizer(
40 pairs,
41 padding=True,
42 truncation=True,
43 max_length=max_length,
44 return_tensors="pt",
45)
46logits = model(**inputs).logits.squeeze()
47print(logits.tolist())
48# [-8.998334884643555, 4.0390801429748535, -6.5225725173950195, -1.2361359596252441]
49
50scores = logits.sigmoid()
51print(scores.tolist())
52# [0.00012360018445178866, 0.98269122838974, 0.001467725494876504, 0.2251092940568924]1# Requires transformers>=4.51.0
2import torch
3from transformers import AutoModel, AutoTokenizer, AutoModelForCausalLM
4
5def format_instruction(instruction, query, doc):
6 if instruction is None:
7 instruction = 'Given a web search query, retrieve relevant passages that answer the query'
8 output = "<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}".format(instruction=instruction,query=query, doc=doc)
9 return output
10
11def process_inputs(pairs):
12 inputs = tokenizer(
13 pairs, padding=False, truncation='longest_first',
14 return_attention_mask=False, max_length=max_length - len(prefix_tokens) - len(suffix_tokens)
15 )
16 for i, ele in enumerate(inputs['input_ids']):
17 inputs['input_ids'][i] = prefix_tokens + ele + suffix_tokens
18 inputs = tokenizer.pad(inputs, padding=True, return_tensors="pt", max_length=max_length)
19 for key in inputs:
20 inputs[key] = inputs[key].to(model.device)
21 return inputs
22
23@torch.no_grad()
24def compute_logits(inputs, **kwargs):
25 batch_scores = model(**inputs).logits[:, -1, :]
26 true_vector = batch_scores[:, token_true_id]
27 false_vector = batch_scores[:, token_false_id]
28 batch_scores = torch.stack([false_vector, true_vector], dim=1)
29 batch_scores = torch.nn.functional.log_softmax(batch_scores, dim=1)
30 scores = batch_scores[:, 1].exp().tolist()
31 return scores
32
33tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-Reranker-4B", padding_side='left')
34model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Reranker-4B").eval()
35
36# We recommend enabling flash_attention_2 for better acceleration and memory saving.
37# model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Reranker-4B", torch_dtype=torch.float16, attn_implementation="flash_attention_2").cuda().eval()
38
39token_false_id = tokenizer.convert_tokens_to_ids("no")
40token_true_id = tokenizer.convert_tokens_to_ids("yes")
41max_length = 8192
42
43prefix = "<|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"
44suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
45prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)
46suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
47
48task = 'Given a web search query, retrieve relevant passages that answer the query'
49
50queries = [
51 "Which planet is known as the Red Planet?",
52 "Which planet is known as the Red Planet?",
53 "Which planet is known as the Red Planet?",
54 "Which planet is known as the Red Planet?",
55]
56
57documents = [
58 "Venus is often called Earth's twin because of its similar size and proximity.",
59 "Mars, known for its reddish appearance, is often referred to as the Red Planet.",
60 "Jupiter, the largest planet in our solar system, has a prominent red spot.",
61 "Saturn, famous for its rings, is sometimes mistaken for the Red Planet.",
62]
63
64pairs = [format_instruction(task, query, doc) for query, doc in zip(queries, documents)]
65
66# Tokenize the input texts
67inputs = process_inputs(pairs)
68scores = compute_logits(inputs)
69
70print("scores: ", scores)
71# scores: [0.0001237865217262879, 0.9826870560646057, 0.0014700202737003565, 0.2253335416316986]1# Requires vllm>=0.8.5
2import logging
3from typing import Dict, Optional, List
4
5import json
6import logging
7
8import torch
9
10from transformers import AutoTokenizer, is_torch_npu_available
11from vllm import LLM, SamplingParams
12from vllm.distributed.parallel_state import destroy_model_parallel
13import gc
14import math
15from vllm.inputs.data import TokensPrompt
16
17
18
19def format_instruction(instruction, query, doc):
20 text = [
21 {"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\"."},
22 {"role": "user", "content": f"<Instruct>: {instruction}\n\n<Query>: {query}\n\n<Document>: {doc}"}
23 ]
24 return text
25
26def process_inputs(pairs, instruction, max_length, suffix_tokens):
27 messages = [format_instruction(instruction, query, doc) for query, doc in pairs]
28 messages = tokenizer.apply_chat_template(
29 messages, tokenize=True, add_generation_prompt=False, enable_thinking=False
30 )
31 messages = [ele[:max_length] + suffix_tokens for ele in messages]
32 messages = [TokensPrompt(prompt_token_ids=ele) for ele in messages]
33 return messages
34
35def compute_logits(model, messages, sampling_params, true_token, false_token):
36 outputs = model.generate(messages, sampling_params, use_tqdm=False)
37 scores = []
38 for i in range(len(outputs)):
39 final_logits = outputs[i].outputs[0].logprobs[-1]
40 token_count = len(outputs[i].outputs[0].token_ids)
41 if true_token not in final_logits:
42 true_logit = -10
43 else:
44 true_logit = final_logits[true_token].logprob
45 if false_token not in final_logits:
46 false_logit = -10
47 else:
48 false_logit = final_logits[false_token].logprob
49 true_score = math.exp(true_logit)
50 false_score = math.exp(false_logit)
51 score = true_score / (true_score + false_score)
52 scores.append(score)
53 return scores
54
55number_of_gpu = torch.cuda.device_count()
56tokenizer = AutoTokenizer.from_pretrained('Qwen/Qwen3-Reranker-4B')
57model = 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)
58tokenizer.padding_side = "left"
59tokenizer.pad_token = tokenizer.eos_token
60suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
61max_length=8192
62suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
63true_token = tokenizer("yes", add_special_tokens=False).input_ids[0]
64false_token = tokenizer("no", add_special_tokens=False).input_ids[0]
65sampling_params = SamplingParams(temperature=0,
66 max_tokens=1,
67 logprobs=20,
68 allowed_token_ids=[true_token, false_token],
69)
70
71
72task = 'Given a web search query, retrieve relevant passages that answer the query'
73queries = ["What is the capital of China?",
74 "Explain gravity",
75]
76documents = [
77 "The capital of China is Beijing.",
78 "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.",
79]
80
81pairs = list(zip(queries, documents))
82inputs = process_inputs(pairs, task, max_length-len(suffix_tokens), suffix_tokens)
83scores = compute_logits(model, inputs, sampling_params, true_token, false_token)
84print('scores', scores)
85
86destroy_model_parallel()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%.| Model | Param | MTEB-R | CMTEB-R | MMTEB-R | MLDR | MTEB-Code | FollowIR |
|---|---|---|---|---|---|---|---|
| Qwen3-Embedding-0.6B | 0.6B | 61.82 | 71.02 | 64.64 | 50.26 | 75.41 | 5.09 |
| Jina-multilingual-reranker-v2-base | 0.3B | 58.22 | 63.37 | 63.73 | 39.66 | 58.98 | -0.68 |
| gte-multilingual-reranker-base | 0.3B | 59.51 | 74.08 | 59.44 | 66.33 | 54.18 | -1.64 |
| BGE-reranker-v2-m3 | 0.6B | 57.03 | 72.16 | 58.36 | 59.51 | 41.38 | -0.01 |
| Qwen3-Reranker-0.6B | 0.6B | 65.80 | 71.31 | 66.36 | 67.28 | 73.42 | 5.41 |
| Qwen3-Reranker-4B | 4B | 69.76 | 75.94 | 72.74 | 69.97 | 81.20 | 14.84 |
| Qwen3-Reranker-8B | 8B | 69.02 | 77.45 | 72.94 | 70.19 | 81.22 | 8.05 |
Note:
- 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.
- All scores are our runs based on the top-100 candidates retrieved by dense embedding model Qwen3-Embedding-0.6B.
@article{qwen3embedding,
title={Qwen3 Embedding: Advancing Text Embedding and Reranking Through Foundation Models},
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},
journal={arXiv preprint arXiv:2506.05176},
year={2025}
}