puzzled-neuron commited on
Commit
3d8b0da
·
verified ·
1 Parent(s): 5a1aad4

Upload training/inference.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. training/inference.py +149 -0
training/inference.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Inference script for DoRA fine-tuned Qwen3-4B model.
4
+
5
+ Usage:
6
+ python inference.py --model_path ./outputs/qwen3-4b-dora/final
7
+ python inference.py --model_path ./outputs/qwen3-4b-dora/final --interactive
8
+ """
9
+
10
+ import argparse
11
+ import torch
12
+ from transformers import AutoModelForCausalLM, AutoTokenizer
13
+ from peft import PeftModel
14
+
15
+
16
+ def load_model(model_path: str, base_model: str = "Qwen/Qwen3-4B-Instruct"):
17
+ """Load the fine-tuned model."""
18
+ print(f"Loading base model: {base_model}")
19
+
20
+ # Load tokenizer
21
+ tokenizer = AutoTokenizer.from_pretrained(
22
+ model_path,
23
+ trust_remote_code=True,
24
+ )
25
+
26
+ # Load base model
27
+ model = AutoModelForCausalLM.from_pretrained(
28
+ base_model,
29
+ trust_remote_code=True,
30
+ torch_dtype=torch.bfloat16,
31
+ device_map="auto",
32
+ attn_implementation="flash_attention_2",
33
+ )
34
+
35
+ # Load DoRA adapter
36
+ print(f"Loading DoRA adapter from: {model_path}")
37
+ model = PeftModel.from_pretrained(model, model_path)
38
+ model.eval()
39
+
40
+ return model, tokenizer
41
+
42
+
43
+ def generate_response(model, tokenizer, question: str, max_new_tokens: int = 512):
44
+ """Generate a response to a question."""
45
+
46
+ # Format as chat
47
+ messages = [
48
+ {"role": "system", "content": "You are a Thailand real estate and neighborhood expert for Bangkok Metropolitan Region."},
49
+ {"role": "user", "content": question}
50
+ ]
51
+
52
+ # Apply chat template
53
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
54
+
55
+ # Tokenize
56
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
57
+
58
+ # Generate
59
+ with torch.no_grad():
60
+ outputs = model.generate(
61
+ **inputs,
62
+ max_new_tokens=max_new_tokens,
63
+ temperature=0.7,
64
+ top_p=0.9,
65
+ do_sample=True,
66
+ pad_token_id=tokenizer.eos_token_id,
67
+ )
68
+
69
+ # Decode
70
+ response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
71
+ return response.strip()
72
+
73
+
74
+ def run_evaluation(model, tokenizer):
75
+ """Run evaluation on sample questions."""
76
+
77
+ test_questions = [
78
+ "What's the population of Thong Lo?",
79
+ "Is Sathorn expensive?",
80
+ "Best areas for Japanese expats?",
81
+ "Does Ari have good cafes?",
82
+ "Is Bang Kapi safe at night?",
83
+ "Compare Ekkamai and Thong Lo",
84
+ "Good area for families with kids?",
85
+ "Where can I find affordable condos near BTS?",
86
+ "What's the vibe like in Ari?",
87
+ "Is fiber internet available in Lat Phrao?",
88
+ ]
89
+
90
+ print("\n" + "=" * 60)
91
+ print("EVALUATION")
92
+ print("=" * 60)
93
+
94
+ for q in test_questions:
95
+ print(f"\nQ: {q}")
96
+ response = generate_response(model, tokenizer, q)
97
+ print(f"A: {response}")
98
+ print("-" * 40)
99
+
100
+
101
+ def interactive_mode(model, tokenizer):
102
+ """Run interactive Q&A session."""
103
+
104
+ print("\n" + "=" * 60)
105
+ print("INTERACTIVE MODE")
106
+ print("Type 'quit' or 'exit' to stop")
107
+ print("=" * 60)
108
+
109
+ while True:
110
+ print()
111
+ question = input("You: ").strip()
112
+
113
+ if question.lower() in ["quit", "exit", "q"]:
114
+ print("Goodbye!")
115
+ break
116
+
117
+ if not question:
118
+ continue
119
+
120
+ response = generate_response(model, tokenizer, question)
121
+ print(f"Assistant: {response}")
122
+
123
+
124
+ def main():
125
+ parser = argparse.ArgumentParser(description="Inference for fine-tuned Qwen3-4B")
126
+ parser.add_argument("--model_path", type=str, required=True, help="Path to fine-tuned model")
127
+ parser.add_argument("--base_model", type=str, default="Qwen/Qwen3-4B-Instruct", help="Base model name")
128
+ parser.add_argument("--interactive", action="store_true", help="Run in interactive mode")
129
+ parser.add_argument("--question", type=str, help="Single question to answer")
130
+ args = parser.parse_args()
131
+
132
+ # Load model
133
+ model, tokenizer = load_model(args.model_path, args.base_model)
134
+
135
+ if args.question:
136
+ # Single question mode
137
+ response = generate_response(model, tokenizer, args.question)
138
+ print(f"Q: {args.question}")
139
+ print(f"A: {response}")
140
+ elif args.interactive:
141
+ # Interactive mode
142
+ interactive_mode(model, tokenizer)
143
+ else:
144
+ # Evaluation mode
145
+ run_evaluation(model, tokenizer)
146
+
147
+
148
+ if __name__ == "__main__":
149
+ main()