Views
No views yet
1from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
2from peft import PeftModel
3import torch
4
5base_model_id = "Qwen/Qwen2.5-7B-Instruct"
6adapter_id = "Jese/Qwen-2.5-SFT-QLoRA-4bit-v251027"
7
8compute_dtype = (
9 torch.bfloat16
10 if torch.cuda.is_available() and torch.cuda.get_device_capability(0)[0] >= 8
11 else torch.float16
12)
13quantization_config = BitsAndBytesConfig(
14 load_in_4bit=True,
15 bnb_4bit_compute_dtype=compute_dtype,
16 bnb_4bit_use_double_quant=True,
17 bnb_4bit_quant_type="nf4",
18)
19
20base_model = AutoModelForCausalLM.from_pretrained(
21 base_model_id,
22 quantization_config=quantization_config,
23 device_map="auto",
24 trust_remote_code=True,
25)
26tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)
27if tokenizer.pad_token is None:
28 tokenizer.pad_token = tokenizer.eos_token
29
30model = PeftModel.from_pretrained(base_model, adapter_id)
31model.eval()
32# 对齐 pad id,减少 warning/边角情况
33model.config.pad_token_id = tokenizer.pad_token_id
34model.generation_config.pad_token_id = tokenizer.pad_token_id
35model.config.use_cache = True
36
37# --- 推理 ---
38messages = [{"role": "user", "content": "Solve: 2 + 2 = ?"}]
39text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
40
41inputs = tokenizer(text, return_tensors="pt", add_special_tokens=False).to(model.device)
42with torch.inference_mode():
43 outputs = model.generate(
44 **inputs,
45 max_new_tokens=100,
46 do_sample=False, # 如需更“活泼”可设为 True 并加温度等
47 eos_token_id=tokenizer.eos_token_id,
48 pad_token_id=tokenizer.pad_token_id,
49 )
50# 只打印新生成内容,避免把 prompt 也 decode 出来
51gen_ids = outputs[:, inputs["input_ids"].shape[-1]:]
52print(tokenizer.decode(gen_ids[0], skip_special_tokens=True))1@misc{vonwerra2022trl,
2 title = {{TRL: Transformer Reinforcement Learning}},
3 author = {Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang and Kashif Rasul and Quentin Gallou{\'e}dec},
4 year = 2020,
5 journal = {GitHub repository},
6 publisher = {GitHub},
7 howpublished = {\url{https://github.com/huggingface/trl}}
8}