Views
No views yet
1!pip install peft accelerate bitsandbytes
2from peft import PeftModel, PeftConfig
3from transformers import AutoModelForCausalLM, AutoTokenizer
4
5# Function to generate and solve problems using the fine-tuned model
6def generate_and_solve_problems(model, tokenizer, num_problems=5):
7 """
8 Generate and solve math and reasoning problems using the fine-tuned model.
9
10 Parameters:
11 model: Fine-tuned language model
12 tokenizer: Corresponding tokenizer
13 num_problems: Number of problems to generate and solve
14 """
15 # Prompt template
16 test_prompt = """Below is a math problem. Solve the problem step by step and provide a detailed explanation.
17
18### Problem:
19{}
20
21### Solution:"""
22
23 # Sample test problems
24 test_problems = [
25 "A car travels at 40 mph for 2 hours, then at 60 mph for another 3 hours. How far does it travel in total?",
26 "If the sum of three consecutive integers is 72, what are the integers?",
27 "A train leaves Station A at 10:00 AM traveling at 50 mph. Another train leaves Station A at 12:00 PM traveling at 70 mph on the same track. At what time will the second train catch up to the first?",
28 "A rectangle has a length of 12 units and a width of 8 units. If the length is increased by 50% and the width is reduced by 25%, what is the new area of the rectangle?",
29 "If a person invests $1000 in a savings account that earns 5% annual interest compounded yearly, how much money will be in the account after 10 years?"
30 ]
31
32 # Use only the specified number of problems
33 test_problems = test_problems[:num_problems]
34
35 for problem in test_problems:
36 # Create the prompt
37 prompt = test_prompt.format(problem)
38
39 # Tokenize and generate response
40 inputs = tokenizer(prompt, return_tensors="pt", truncation=True, padding=True).to("cuda")
41 outputs = model.generate(
42 input_ids=inputs["input_ids"],
43 attention_mask=inputs["attention_mask"],
44 max_length=512,
45 temperature=0.7,
46 top_p=0.9,
47 do_sample=True,
48 )
49 response = tokenizer.decode(outputs[0], skip_special_tokens=True)
50
51 # Print the problem and the solution
52 print(response)
53 print("\n" + "="*50 + "\n")
54
55# Example usage with model and tokenizer
56
57base_model_name = "unsloth/phi-3-mini-4k-instruct-bnb-4bit"
58lora_model_name = "Vijayendra/Phi3-LoRA-GSM8k"
59
60# Load base model and tokenizer
61base_model = AutoModelForCausalLM.from_pretrained(base_model_name, device_map="auto", torch_dtype="auto")
62tokenizer = AutoTokenizer.from_pretrained(base_model_name)
63
64# Load the fine-tuned LoRA model
65model = PeftModel.from_pretrained(base_model, lora_model_name)
66model.eval()
67
68# Call the function to solve problems
69generate_and_solve_problems(model, tokenizer)