Views
No views yet
| Property | Details |
|---|---|
| Base Model | Qwen/Qwen3-Reranker-0.6B |
| Architecture | Cross-Encoder Reranker |
| Quantization | 8-bit (bitsandbytes) |
| Inference Device | CPU or GPU |
| Task | Document relevance classification |
| Output | Yes / No probability |
1# Requires transformers>=4.51.0,accelerate,bitsandbytes
2
3import torch
4from transformers import AutoTokenizer, AutoModelForCausalLM
5
6model_id = "ManiKumarAdapala/Qwen3-Reranker-0.6B-Q8_0-Safetensors"
7tokenizer = AutoTokenizer.from_pretrained(model_id, padding_side='left')
8
9model = AutoModelForCausalLM.from_pretrained(
10 model_id,
11 dtype=torch.float16, # CPU friendly
12 device_map={"": "cpu"}, #cuda for GPU usage
13).eval()
14
15
16# We recommend enabling flash_attention_2 for better acceleration and memory saving for cuda.
17# model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, attn_implementation="flash_attention_2").cuda().eval()
18
19token_false_id = tokenizer.convert_tokens_to_ids("no")
20token_true_id = tokenizer.convert_tokens_to_ids("yes")
21max_length = 128 # increasing this will increase computation time
22
23prefix = "<|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"
24suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
25
26prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)
27suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
28
29def format_instruction(instruction, query, doc):
30 if instruction is None:
31 instruction = 'Given a web search query, retrieve relevant passages that answer the query'
32 output = "<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}".format(instruction=instruction,query=query, doc=doc)
33 return output
34
35def process_inputs(pairs):
36 inputs = tokenizer(
37 pairs, padding=False, truncation='longest_first',
38 return_attention_mask=False, max_length=max_length - len(prefix_tokens) - len(suffix_tokens)
39 )
40 for i, ele in enumerate(inputs['input_ids']):
41 inputs['input_ids'][i] = prefix_tokens + ele + suffix_tokens
42 inputs = tokenizer.pad(inputs, padding=True, return_tensors="pt", max_length=max_length)
43 for key in inputs:
44 inputs[key] = inputs[key].to(model.device)
45 return inputs
46
47
48def compute_logits(inputs, **kwargs):
49 batch_scores = model(**inputs).logits[:, -1, :]
50 true_vector = batch_scores[:, token_true_id]
51 false_vector = batch_scores[:, token_false_id]
52 batch_scores = torch.stack([false_vector, true_vector], dim=1)
53 batch_scores = torch.nn.functional.log_softmax(batch_scores, dim=1)
54 scores = batch_scores[:, 1].exp().tolist()
55 return scores
56
57
58task = 'Given a web search query, retrieve relevant passages that answer the query'
59
60query = "what is photosynthesis ?"
61
62documents = [
63 "The French Revolution began in 1789...",
64 "Some plants are carnivorous and digest insects.",
65 "Photosynthesis is the process by which plants convert light into chemical energy.",
66]
67
68
69pairs = [format_instruction(task, query, doc) for doc in documents]
70
71# Tokenize the input texts
72inputs = process_inputs(pairs)
73scores = compute_logits(inputs)
74
75print("scores: ", scores)
76# output : scores: [0.0002269744873046875, 0.00042247772216796875, 0.994140625]
77
78# Sorting documents as per score
79sorted_docs = [doc for _, doc in sorted(zip(scores, documents), reverse=True)]
80print(sorted_docs)
81
82# Selecting top 3 as per ranking
83top_3_docs = sorted_docs[:3]
84print(top_3_docs)
85@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}
}