Views
No views yet
1from transformers import AutoTokenizer
2import onnxruntime as ort
3import numpy as np
4import torch
5from typing import List
6
7
8class Qwen3RerankerONNX:
9 def __init__(
10 self,
11 model_path: str = "shawnw3i/Qwen3-Reranker-0.6B-ONNX/model.onnx",
12 tokenizer_dir: str = "shawnw3i/Qwen3-Reranker-0.6B-ONNX",
13 providers: List[str] = ("CUDAExecutionProvider", "CPUExecutionProvider"),
14 max_length: int = 2048,
15 ):
16 self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_dir, padding_side="left")
17 self.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"
18 self.suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
19 self.prefix_tokens = self.tokenizer.encode(self.prefix, add_special_tokens=False)
20 self.suffix_tokens = self.tokenizer.encode(self.suffix, add_special_tokens=False)
21 self.default_instruction = (
22 "Given a web search query, retrieve relevant passages that answer the query"
23 )
24 self.max_length = max_length
25 self.token_false_id = self.tokenizer.convert_tokens_to_ids("no")
26 self.token_true_id = self.tokenizer.convert_tokens_to_ids("yes")
27 self.session = ort.InferenceSession(model_path, providers=list(providers))
28 self.output_name = "logits"
29
30 def _format_instruction(self, instruction: str, query: str, doc: str) -> str:
31 inst = instruction if instruction is not None else self.default_instruction
32 return f"<Instruct>: {inst}\n<Query>: {query}\n<Document>: {doc}"
33
34 def _tokenize(self, pairs: List[str]):
35 encoded = self.tokenizer(
36 [self.prefix + s + self.suffix for s in pairs],
37 padding=True,
38 truncation="longest_first",
39 max_length=self.max_length - len(self.prefix_tokens) - len(self.suffix_tokens),
40 add_special_tokens=False,
41 return_tensors="np",
42 )
43 input_ids = encoded["input_ids"].astype(np.int64)
44 attention_mask = encoded["attention_mask"].astype(np.int64)
45 seq_len = input_ids.shape[1]
46 position_ids = (
47 np.arange(seq_len, dtype=np.int64)[None, :].repeat(input_ids.shape[0], axis=0)
48 )
49 return input_ids, attention_mask, position_ids
50
51 def infer(
52 self,
53 queries: List[str],
54 documents: List[str],
55 instruction: str = None,
56 ):
57 if len(queries) == 1 and len(documents) > 1:
58 queries = [queries[0]] * len(documents)
59 elif len(queries) != len(documents):
60 raise ValueError("The number of queries must be 1 or equal to the number of documents.")
61 pairs = [
62 self._format_instruction(instruction, q, d) for q, d in zip(queries, documents)
63 ]
64 input_ids, attention_mask, position_ids = self._tokenize(pairs)
65 ort_inputs = {
66 "input_ids": input_ids,
67 "attention_mask": attention_mask,
68 "position_ids": position_ids,
69 }
70 logits_np = self.session.run([self.output_name], ort_inputs)[0]
71 last_token_logits = torch.from_numpy(logits_np[:, -1, :]).float()
72 false_logits = last_token_logits[:, self.token_false_id]
73 true_logits = last_token_logits[:, self.token_true_id]
74 probs = torch.softmax(torch.stack([false_logits, true_logits], dim=1), dim=1)
75 scores_no = probs[:, 0].tolist()
76 scores_yes = probs[:, 1].tolist()
77 return scores_yes, scores_no
| 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'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 | 1.7B | 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.
@misc{qwen3-embedding,
title = {Qwen3-Embedding},
url = {https://qwenlm.github.io/blog/qwen3/},
author = {Qwen Team},
month = {May},
year = {2025}
}