Views
No views yet


pip install transformers peft torch accelerate bitsandbytes1from transformers import AutoModelForCausalLM, AutoTokenizer
2from peft import PeftModel
3import torch
4from transformers import BitsAndBytesConfig
5
6bnb_config = BitsAndBytesConfig(
7 load_in_4bit=True,
8 bnb_4bit_quant_type="nf4",
9 bnb_4bit_use_double_quant=True,
10 bnb_4bit_compute_dtype=torch.float16
11)
12
13# Load base model with 4-bit quantization
14model = AutoModelForCausalLM.from_pretrained(
15 "Qwen/Qwen2.5-3B-Instruct",
16 device_map="auto",
17 quantization_config=bnb_config,
18 dtype=torch.float16,
19)
20
21# Load LoRA adapter
22model = PeftModel.from_pretrained(model, "path/to/qwen_userturn_lora")
23tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-3B-Instruct")
24
25# Prepare conversation context
26conversation = [
27 {"role": "user", "content": "I'm looking for a restaurant in downtown"},
28 {"role": "assistant", "content": "What type of cuisine would you prefer?"}
29]
30
31inputs = tokenizer.apply_chat_template(
32 conversation,
33 return_tensors="pt",
34 tokenize=True,
35 add_generation_prompt=False
36).to(model.device)
37
38user_open_tokens = tokenizer.encode("<|im_start|>user\n", add_special_tokens=False, return_tensors="pt").to(model.device)
39
40# Directly concatenate the tensors
41input_ids = torch.cat([inputs, user_open_tokens], dim=-1)
42attention_mask = torch.ones_like(input_ids)
43input_len = int(input_ids.shape[1])
44
45bad = tokenizer(
46 ["<|im_start|>assistant", "<|im_start|>system", "<|im_start|>user"],
47 add_special_tokens=False, return_tensors="pt"
48)["input_ids"].tolist()
49logits_processors = LogitsProcessorList([NoBadWordsLogitsProcessor(bad, eos_token_id=tokenizer.eos_token_id)])
50
51# Generate prediction
52with torch.no_grad():
53 outputs = model.generate(
54 input_ids,
55 max_new_tokens=128,
56 do_sample=True,
57 temperature=0.4,
58 top_p=0.9,
59 attention_mask=attention_mask,
60 logits_processor=logits_processors
61 )
62
63predicted_user_turn = tokenizer.decode(
64 outputs[0][input_len:],
65 skip_special_tokens=True
66)
67
68print(f"Predicted user turn: {predicted_user_turn}")1# QLoRA Configuration
2LoRA Rank: 16
3LoRA Alpha: 32
4LoRA Dropout: 0.01
5Target Modules: [
6 "q_proj", "k_proj", "v_proj", "o_proj",
7 "gate_proj", "up_proj", "down_proj"
8]
9
10# Quantization
11Load in 4-bit: True
12BnB 4-bit Compute Dtype: float16
13BnB 4-bit Quant Type: nf4
14BnB 4-bit Use Double Quant: True1@bachelorsthesis{sebastianboehler2025userturn,
2 title={To what extent can open-source Large Language Models predict the next user turn in multi-turn dialogues across open-domain and task-oriented settings?},
3 author={Sebastian Boehler},
4 school={IU International University of Applied Sciences},
5 year={2025},
6 type={Bachelor's Thesis},
7 note={Model: qwen2.5-3b-dialogue-userturn-lora}
8}1@article{qwen2.5,
2 title={Qwen2.5: A Party of Foundation Models},
3 author={Qwen Team},
4 journal={arXiv preprint},
5 year={2024}
6}