#!/usr/bin/env python3 """ Inference script for DoRA fine-tuned Qwen3-4B model. Usage: python inference.py --model_path ./outputs/qwen3-4b-dora/final python inference.py --model_path ./outputs/qwen3-4b-dora/final --interactive """ import argparse import torch from transformers import AutoModelForCausalLM, AutoTokenizer from peft import PeftModel def load_model(model_path: str, base_model: str = "Qwen/Qwen3-4B-Instruct"): """Load the fine-tuned model.""" print(f"Loading base model: {base_model}") # Load tokenizer tokenizer = AutoTokenizer.from_pretrained( model_path, trust_remote_code=True, ) # Load base model model = AutoModelForCausalLM.from_pretrained( base_model, trust_remote_code=True, torch_dtype=torch.bfloat16, device_map="auto", attn_implementation="flash_attention_2", ) # Load DoRA adapter print(f"Loading DoRA adapter from: {model_path}") model = PeftModel.from_pretrained(model, model_path) model.eval() return model, tokenizer def generate_response(model, tokenizer, question: str, max_new_tokens: int = 512): """Generate a response to a question.""" # Format as chat messages = [ {"role": "system", "content": "You are a Thailand real estate and neighborhood expert for Bangkok Metropolitan Region."}, {"role": "user", "content": question} ] # Apply chat template prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) # Tokenize inputs = tokenizer(prompt, return_tensors="pt").to(model.device) # Generate with torch.no_grad(): outputs = model.generate( **inputs, max_new_tokens=max_new_tokens, temperature=0.7, top_p=0.9, do_sample=True, pad_token_id=tokenizer.eos_token_id, ) # Decode response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True) return response.strip() def run_evaluation(model, tokenizer): """Run evaluation on sample questions.""" test_questions = [ "What's the population of Thong Lo?", "Is Sathorn expensive?", "Best areas for Japanese expats?", "Does Ari have good cafes?", "Is Bang Kapi safe at night?", "Compare Ekkamai and Thong Lo", "Good area for families with kids?", "Where can I find affordable condos near BTS?", "What's the vibe like in Ari?", "Is fiber internet available in Lat Phrao?", ] print("\n" + "=" * 60) print("EVALUATION") print("=" * 60) for q in test_questions: print(f"\nQ: {q}") response = generate_response(model, tokenizer, q) print(f"A: {response}") print("-" * 40) def interactive_mode(model, tokenizer): """Run interactive Q&A session.""" print("\n" + "=" * 60) print("INTERACTIVE MODE") print("Type 'quit' or 'exit' to stop") print("=" * 60) while True: print() question = input("You: ").strip() if question.lower() in ["quit", "exit", "q"]: print("Goodbye!") break if not question: continue response = generate_response(model, tokenizer, question) print(f"Assistant: {response}") def main(): parser = argparse.ArgumentParser(description="Inference for fine-tuned Qwen3-4B") parser.add_argument("--model_path", type=str, required=True, help="Path to fine-tuned model") parser.add_argument("--base_model", type=str, default="Qwen/Qwen3-4B-Instruct", help="Base model name") parser.add_argument("--interactive", action="store_true", help="Run in interactive mode") parser.add_argument("--question", type=str, help="Single question to answer") args = parser.parse_args() # Load model model, tokenizer = load_model(args.model_path, args.base_model) if args.question: # Single question mode response = generate_response(model, tokenizer, args.question) print(f"Q: {args.question}") print(f"A: {response}") elif args.interactive: # Interactive mode interactive_mode(model, tokenizer) else: # Evaluation mode run_evaluation(model, tokenizer) if __name__ == "__main__": main()