Views
No views yet
pip install optimum[onnxruntime] transformers1import torch
2from optimum.onnxruntime import ORTModelForCausalLM
3from transformers import AutoTokenizer
4
5# Load model and tokenizer
6model = ORTModelForCausalLM.from_pretrained("thomasht86/Qwen3-Reranker-0.6B-int8-ONNX", use_cache=False)
7tokenizer = AutoTokenizer.from_pretrained("thomasht86/Qwen3-Reranker-0.6B-int8-ONNX", fix_mistral_regex=True)
8
9# Format input for reranking
10SYSTEM_PROMPT = '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".'
11
12def get_relevance_score(query: str, document: str, instruction: str = None) -> float:
13 if instruction is None:
14 instruction = "Given a web search query, retrieve relevant passages that answer the query"
15
16 user_content = f"<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {document}"
17
18 messages = [
19 {"role": "system", "content": SYSTEM_PROMPT},
20 {"role": "user", "content": user_content},
21 ]
22
23 text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=True)
24 text += "<think>\n\n</think>\n\n"
25
26 inputs = tokenizer(text, return_tensors="pt")
27 outputs = model(**inputs, use_cache=False)
28 logits = outputs.logits[:, -1, :]
29
30 # Get yes/no token probabilities
31 token_true_id = tokenizer.convert_tokens_to_ids("yes")
32 token_false_id = tokenizer.convert_tokens_to_ids("no")
33 true_false_logits = logits[:, [token_false_id, token_true_id]]
34 probs = torch.softmax(true_false_logits, dim=-1)
35
36 return probs[:, 1].item() # Probability of "yes" (relevant)
37
38# Example
39score = get_relevance_score(
40 query="What is the capital of France?",
41 document="Paris is the capital and largest city of France."
42)
43print(f"Relevance score: {score:.4f}")quantize_qwen3_reranker.py.1# Install uv if needed: pip install uv
2uv run quantize_qwen3_reranker.py --output-dir ./output1@article{qwen3embedding,
2 title={Qwen3 Embedding: Advancing Text Embedding and Reranking Through Foundation Models},
3 author={Zhang, Yanzhao and Li, Mingxin and Long, Dingkun and others},
4 journal={arXiv preprint arXiv:2506.05176},
5 year={2025}
6}