Views
No views yet
1from peft import PeftModel, PeftConfig
2from transformers import AutoModelForCausalLM, AutoTokenizer
3import torch
4
5# Set device
6device = "cuda" if torch.cuda.is_available() else "cpu"
7
8def load_model(base_model_id, adapter_model_id):
9 print("Loading models...")
10
11 # Load tokenizer
12 tokenizer = AutoTokenizer.from_pretrained(base_model_id)
13
14 # Load base model (using model's built-in quantization)
15 base_model = AutoModelForCausalLM.from_pretrained(
16 base_model_id,
17 device_map="auto",
18 low_cpu_mem_usage=True
19 )
20
21 # Load the PEFT model
22 model = PeftModel.from_pretrained(
23 base_model,
24 adapter_model_id,
25 device_map="auto"
26 )
27
28 model.eval()
29 print("Models loaded!")
30 return model, tokenizer
31
32def generate_response(model, tokenizer, prompt, max_length=4096, temperature=0.7):
33 with torch.no_grad():
34 inputs = tokenizer(prompt, return_tensors="pt").to(device)
35 outputs = model.generate(
36 **inputs,
37 max_length=max_length,
38 temperature=temperature,
39 do_sample=True,
40 top_p=0.95,
41 top_k=40,
42 num_return_sequences=1,
43 pad_token_id=tokenizer.eos_token_id
44 )
45 return tokenizer.decode(outputs[0], skip_special_tokens=True)
46
47def main():
48 model, tokenizer = load_model(
49 "unsloth/llama-3.2-1b-instruct-bnb-4bit",
50 "HackWeasel/llama-3.2-1b-QLORA-IMDB"
51 )
52
53 conversation_history = ""
54 print("\nWelcome! Start chatting with the model (type 'quit' to exit)")
55 print("Note: This model is fine-tuned on IMDB reviews data")
56
57 while True:
58 try:
59 user_input = input("\nYou: ").strip()
60 if user_input.lower() == 'quit':
61 print("Goodbye!")
62 break
63
64 if conversation_history:
65 full_prompt = f"{conversation_history}\nHuman: {user_input}\nAssistant:"
66 else:
67 full_prompt = f"Human: {user_input}\nAssistant:"
68
69 response = generate_response(model, tokenizer, full_prompt)
70 new_response = response.split("Assistant:")[-1].strip()
71 conversation_history = f"{conversation_history}\nHuman: {user_input}\nAssistant: {new_response}"
72 print("\nAssistant:", new_response)
73
74 except Exception as e:
75 print(f"An error occurred: {e}")
76 print("Continuing conversation...")
77
78if __name__ == "__main__":
79 main()