File size: 4,386 Bytes
58f007a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#!/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()