Views
No views yet

Qwen3ForCausalLM)

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('thebajajra/RexReranker-0.6B')
57model = LLM(model='thebajajra/RexReranker-0.6B', 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 = ["visual fractions workbooks for children",
74 "replacement motor mount for 2008 focus",
75]
76documents = [
77 "Fractions and Decimals Workbook for Grades 4 to 5",
78 "3pcs Set - Motor Mounts Kit Compatible with 08-11 Ford Focus 2.0L Auto Automatic and Manual Trans Transmission AT MT - Engine Mounts",
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()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("thebajajra/RexReranker-0.6B", padding_side='left')
34model = AutoModelForCausalLM.from_pretrained("thebajajra/RexReranker-0.6B").eval()
35# We recommend enabling flash_attention_2 for better acceleration and memory saving.
36# model = AutoModelForCausalLM.from_pretrained("thebajajra/RexReranker-0.6B", torch_dtype=torch.float16, attn_implementation="flash_attention_2").cuda().eval()
37token_false_id = tokenizer.convert_tokens_to_ids("no")
38token_true_id = tokenizer.convert_tokens_to_ids("yes")
39max_length = 8192
40
41prefix = "<|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"
42suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
43prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)
44suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
45
46task = 'Given a web search query, retrieve relevant passages that answer the query'
47
48queries = ["visual fractions workbooks for children",
49 "replacement motor mount for 2008 focus",
50]
51documents = [
52 "Fractions and Decimals Workbook for Grades 4 to 5",
53 "3pcs Set - Motor Mounts Kit Compatible with 08-11 Ford Focus 2.0L Auto Automatic and Manual Trans Transmission AT MT - Engine Mounts",
54]
55
56pairs = [format_instruction(task, query, doc) for query, doc in zip(queries, documents)]
57
58# Tokenize the input texts
59inputs = process_inputs(pairs)
60scores = compute_logits(inputs)
61
62print("scores: ", scores)
63