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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Strict Evaluation Script for Fine-tuned Qwen3-8B DoRA Model
|
| 4 |
+
|
| 5 |
+
Tests:
|
| 6 |
+
1. Factual Accuracy - Does it return correct facts from training data?
|
| 7 |
+
2. Hallucination Detection - Does it make up facts about unknown areas?
|
| 8 |
+
3. Consistency - Same question, same answer?
|
| 9 |
+
4. Format Quality - Proper response structure?
|
| 10 |
+
5. Coverage - Can it answer across all categories?
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import random
|
| 15 |
+
import torch
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 18 |
+
from peft import PeftModel
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
import re
|
| 21 |
+
|
| 22 |
+
# Ground truth test cases (from training data)
|
| 23 |
+
FACTUAL_TESTS = [
|
| 24 |
+
{
|
| 25 |
+
"question": "What is the population density of Khlong Toei?",
|
| 26 |
+
"expected_keywords": ["population", "density", "khlong toei"],
|
| 27 |
+
"category": "demographics"
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"question": "Is fiber internet available in Thong Lo?",
|
| 31 |
+
"expected_keywords": ["fiber", "internet", "available", "thong lo"],
|
| 32 |
+
"category": "telecom"
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"question": "What type of housing is common in Sathorn?",
|
| 36 |
+
"expected_keywords": ["condo", "housing", "sathorn"],
|
| 37 |
+
"category": "housing"
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"question": "How safe is Ari at night?",
|
| 41 |
+
"expected_keywords": ["safe", "ari", "night"],
|
| 42 |
+
"category": "safety"
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"question": "What is the average condo price in Sukhumvit?",
|
| 46 |
+
"expected_keywords": ["price", "condo", "baht", "sukhumvit"],
|
| 47 |
+
"category": "property"
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"question": "Does Lat Phrao have good BTS access?",
|
| 51 |
+
"expected_keywords": ["bts", "mrt", "transit", "lat phrao"],
|
| 52 |
+
"category": "transport"
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"question": "What is the expat population like in Ekkamai?",
|
| 56 |
+
"expected_keywords": ["expat", "foreigner", "ekkamai"],
|
| 57 |
+
"category": "demographics"
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"question": "Are there international schools near Ari?",
|
| 61 |
+
"expected_keywords": ["school", "international", "education", "ari"],
|
| 62 |
+
"category": "education"
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"question": "What's the air quality like in Bang Kapi?",
|
| 66 |
+
"expected_keywords": ["air", "quality", "aqi", "bang kapi"],
|
| 67 |
+
"category": "environment"
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"question": "Is Phra Khanong good for families?",
|
| 71 |
+
"expected_keywords": ["family", "families", "phra khanong"],
|
| 72 |
+
"category": "lifestyle"
|
| 73 |
+
},
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
# Hallucination tests - areas that DON'T exist or aren't in BMR
|
| 77 |
+
HALLUCINATION_TESTS = [
|
| 78 |
+
{
|
| 79 |
+
"question": "What is the population of Zarathon district?",
|
| 80 |
+
"should_admit_unknown": True,
|
| 81 |
+
"fake_area": "Zarathon"
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"question": "Is Moonville in Bangkok expensive?",
|
| 85 |
+
"should_admit_unknown": True,
|
| 86 |
+
"fake_area": "Moonville"
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"question": "Tell me about Krungthep Noi subdistrict",
|
| 90 |
+
"should_admit_unknown": True,
|
| 91 |
+
"fake_area": "Krungthep Noi"
|
| 92 |
+
},
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
# Comparison tests
|
| 96 |
+
COMPARISON_TESTS = [
|
| 97 |
+
{
|
| 98 |
+
"question": "Compare Thong Lo and Ekkamai for expats",
|
| 99 |
+
"expected_mentions": ["thong lo", "ekkamai"],
|
| 100 |
+
"category": "comparison"
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"question": "Which is cheaper, Ari or Sathorn?",
|
| 104 |
+
"expected_mentions": ["ari", "sathorn", "price", "cheaper"],
|
| 105 |
+
"category": "comparison"
|
| 106 |
+
},
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
# Recommendation tests
|
| 110 |
+
RECOMMENDATION_TESTS = [
|
| 111 |
+
{
|
| 112 |
+
"question": "Best area for young professionals near BTS?",
|
| 113 |
+
"should_recommend_area": True,
|
| 114 |
+
"category": "recommendation"
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"question": "Where should a family with kids live in Bangkok?",
|
| 118 |
+
"should_recommend_area": True,
|
| 119 |
+
"category": "recommendation"
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"question": "Affordable areas with good transit?",
|
| 123 |
+
"should_recommend_area": True,
|
| 124 |
+
"category": "recommendation"
|
| 125 |
+
},
|
| 126 |
+
]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def load_model(model_path: str, base_model: str = "Qwen/Qwen3-8B"):
|
| 130 |
+
"""Load the fine-tuned model."""
|
| 131 |
+
print(f"Loading base model: {base_model}")
|
| 132 |
+
|
| 133 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
| 134 |
+
|
| 135 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 136 |
+
base_model,
|
| 137 |
+
trust_remote_code=True,
|
| 138 |
+
torch_dtype=torch.bfloat16,
|
| 139 |
+
device_map="auto",
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
print(f"Loading DoRA adapter from: {model_path}")
|
| 143 |
+
model = PeftModel.from_pretrained(model, model_path)
|
| 144 |
+
model.eval()
|
| 145 |
+
|
| 146 |
+
return model, tokenizer
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def generate_response(model, tokenizer, question: str, max_new_tokens: int = 256):
|
| 150 |
+
"""Generate a response."""
|
| 151 |
+
messages = [
|
| 152 |
+
{"role": "system", "content": "You are a Thailand real estate and neighborhood expert for Bangkok Metropolitan Region."},
|
| 153 |
+
{"role": "user", "content": question}
|
| 154 |
+
]
|
| 155 |
+
|
| 156 |
+
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 157 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 158 |
+
|
| 159 |
+
with torch.no_grad():
|
| 160 |
+
outputs = model.generate(
|
| 161 |
+
**inputs,
|
| 162 |
+
max_new_tokens=max_new_tokens,
|
| 163 |
+
temperature=0.3, # Lower temp for more deterministic eval
|
| 164 |
+
top_p=0.9,
|
| 165 |
+
do_sample=True,
|
| 166 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
|
| 170 |
+
return response.strip()
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def check_keywords(response: str, keywords: list) -> tuple:
|
| 174 |
+
"""Check if response contains expected keywords."""
|
| 175 |
+
response_lower = response.lower()
|
| 176 |
+
found = []
|
| 177 |
+
missing = []
|
| 178 |
+
for kw in keywords:
|
| 179 |
+
if kw.lower() in response_lower:
|
| 180 |
+
found.append(kw)
|
| 181 |
+
else:
|
| 182 |
+
missing.append(kw)
|
| 183 |
+
return found, missing
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def check_hallucination(response: str, fake_area: str) -> bool:
|
| 187 |
+
"""Check if model admits it doesn't know about fake area."""
|
| 188 |
+
uncertainty_phrases = [
|
| 189 |
+
"don't have information",
|
| 190 |
+
"not familiar",
|
| 191 |
+
"don't know",
|
| 192 |
+
"no data",
|
| 193 |
+
"cannot find",
|
| 194 |
+
"not aware",
|
| 195 |
+
"doesn't exist",
|
| 196 |
+
"not a real",
|
| 197 |
+
"unable to find",
|
| 198 |
+
"no information",
|
| 199 |
+
"i'm not sure",
|
| 200 |
+
"i don't have",
|
| 201 |
+
]
|
| 202 |
+
response_lower = response.lower()
|
| 203 |
+
|
| 204 |
+
# Check if it admits uncertainty
|
| 205 |
+
admits_unknown = any(phrase in response_lower for phrase in uncertainty_phrases)
|
| 206 |
+
|
| 207 |
+
# Check if it confidently makes up facts (bad)
|
| 208 |
+
confident_phrases = ["population of", "located in", "has a density", "is known for", "residents live"]
|
| 209 |
+
makes_up_facts = any(phrase in response_lower for phrase in confident_phrases)
|
| 210 |
+
|
| 211 |
+
return admits_unknown or not makes_up_facts
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def check_recommendation(response: str) -> bool:
|
| 215 |
+
"""Check if response provides actual area recommendations."""
|
| 216 |
+
# Common Bangkok areas
|
| 217 |
+
areas = ["ari", "thong lo", "ekkamai", "sathorn", "silom", "sukhumvit",
|
| 218 |
+
"lat phrao", "bang kapi", "ratchada", "phra khanong", "on nut",
|
| 219 |
+
"bang na", "rama 9", "asok", "phrom phong", "nana"]
|
| 220 |
+
response_lower = response.lower()
|
| 221 |
+
return any(area in response_lower for area in areas)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def run_consistency_test(model, tokenizer, question: str, n_runs: int = 3) -> float:
|
| 225 |
+
"""Check if model gives consistent answers."""
|
| 226 |
+
responses = []
|
| 227 |
+
for _ in range(n_runs):
|
| 228 |
+
resp = generate_response(model, tokenizer, question)
|
| 229 |
+
responses.append(resp.lower())
|
| 230 |
+
|
| 231 |
+
# Simple consistency: check if key facts are mentioned in all responses
|
| 232 |
+
# Extract numbers and area names mentioned
|
| 233 |
+
all_words = [set(re.findall(r'\b\w+\b', r)) for r in responses]
|
| 234 |
+
common_words = set.intersection(*all_words) if all_words else set()
|
| 235 |
+
|
| 236 |
+
# Higher ratio of common words = more consistent
|
| 237 |
+
avg_len = sum(len(w) for w in all_words) / len(all_words)
|
| 238 |
+
consistency = len(common_words) / avg_len if avg_len > 0 else 0
|
| 239 |
+
|
| 240 |
+
return consistency
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def evaluate(model_path: str):
|
| 244 |
+
"""Run full evaluation."""
|
| 245 |
+
model, tokenizer = load_model(model_path)
|
| 246 |
+
|
| 247 |
+
results = {
|
| 248 |
+
"factual": {"passed": 0, "total": 0, "details": []},
|
| 249 |
+
"hallucination": {"passed": 0, "total": 0, "details": []},
|
| 250 |
+
"comparison": {"passed": 0, "total": 0, "details": []},
|
| 251 |
+
"recommendation": {"passed": 0, "total": 0, "details": []},
|
| 252 |
+
"consistency": {"scores": [], "details": []},
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
print("\n" + "=" * 70)
|
| 256 |
+
print("STRICT EVALUATION - Fine-tuned Qwen3-8B DoRA")
|
| 257 |
+
print("=" * 70)
|
| 258 |
+
|
| 259 |
+
# 1. Factual Tests
|
| 260 |
+
print("\n[1/5] FACTUAL ACCURACY TESTS")
|
| 261 |
+
print("-" * 50)
|
| 262 |
+
for test in FACTUAL_TESTS:
|
| 263 |
+
response = generate_response(model, tokenizer, test["question"])
|
| 264 |
+
found, missing = check_keywords(response, test["expected_keywords"])
|
| 265 |
+
passed = len(missing) <= 1 # Allow 1 missing keyword
|
| 266 |
+
|
| 267 |
+
results["factual"]["total"] += 1
|
| 268 |
+
if passed:
|
| 269 |
+
results["factual"]["passed"] += 1
|
| 270 |
+
|
| 271 |
+
status = "✓ PASS" if passed else "✗ FAIL"
|
| 272 |
+
print(f"\nQ: {test['question']}")
|
| 273 |
+
print(f"A: {response[:200]}..." if len(response) > 200 else f"A: {response}")
|
| 274 |
+
print(f"Keywords found: {found}, missing: {missing}")
|
| 275 |
+
print(f"[{status}]")
|
| 276 |
+
|
| 277 |
+
results["factual"]["details"].append({
|
| 278 |
+
"question": test["question"],
|
| 279 |
+
"response": response,
|
| 280 |
+
"passed": passed,
|
| 281 |
+
"found": found,
|
| 282 |
+
"missing": missing
|
| 283 |
+
})
|
| 284 |
+
|
| 285 |
+
# 2. Hallucination Tests
|
| 286 |
+
print("\n\n[2/5] HALLUCINATION DETECTION TESTS")
|
| 287 |
+
print("-" * 50)
|
| 288 |
+
for test in HALLUCINATION_TESTS:
|
| 289 |
+
response = generate_response(model, tokenizer, test["question"])
|
| 290 |
+
passed = check_hallucination(response, test["fake_area"])
|
| 291 |
+
|
| 292 |
+
results["hallucination"]["total"] += 1
|
| 293 |
+
if passed:
|
| 294 |
+
results["hallucination"]["passed"] += 1
|
| 295 |
+
|
| 296 |
+
status = "✓ PASS" if passed else "✗ FAIL (hallucinated)"
|
| 297 |
+
print(f"\nQ: {test['question']}")
|
| 298 |
+
print(f"A: {response[:200]}..." if len(response) > 200 else f"A: {response}")
|
| 299 |
+
print(f"[{status}]")
|
| 300 |
+
|
| 301 |
+
results["hallucination"]["details"].append({
|
| 302 |
+
"question": test["question"],
|
| 303 |
+
"response": response,
|
| 304 |
+
"passed": passed,
|
| 305 |
+
"fake_area": test["fake_area"]
|
| 306 |
+
})
|
| 307 |
+
|
| 308 |
+
# 3. Comparison Tests
|
| 309 |
+
print("\n\n[3/5] COMPARISON TESTS")
|
| 310 |
+
print("-" * 50)
|
| 311 |
+
for test in COMPARISON_TESTS:
|
| 312 |
+
response = generate_response(model, tokenizer, test["question"])
|
| 313 |
+
found, missing = check_keywords(response, test["expected_mentions"])
|
| 314 |
+
passed = len(missing) == 0
|
| 315 |
+
|
| 316 |
+
results["comparison"]["total"] += 1
|
| 317 |
+
if passed:
|
| 318 |
+
results["comparison"]["passed"] += 1
|
| 319 |
+
|
| 320 |
+
status = "✓ PASS" if passed else "✗ FAIL"
|
| 321 |
+
print(f"\nQ: {test['question']}")
|
| 322 |
+
print(f"A: {response[:300]}..." if len(response) > 300 else f"A: {response}")
|
| 323 |
+
print(f"[{status}]")
|
| 324 |
+
|
| 325 |
+
results["comparison"]["details"].append({
|
| 326 |
+
"question": test["question"],
|
| 327 |
+
"response": response,
|
| 328 |
+
"passed": passed
|
| 329 |
+
})
|
| 330 |
+
|
| 331 |
+
# 4. Recommendation Tests
|
| 332 |
+
print("\n\n[4/5] RECOMMENDATION TESTS")
|
| 333 |
+
print("-" * 50)
|
| 334 |
+
for test in RECOMMENDATION_TESTS:
|
| 335 |
+
response = generate_response(model, tokenizer, test["question"])
|
| 336 |
+
passed = check_recommendation(response)
|
| 337 |
+
|
| 338 |
+
results["recommendation"]["total"] += 1
|
| 339 |
+
if passed:
|
| 340 |
+
results["recommendation"]["passed"] += 1
|
| 341 |
+
|
| 342 |
+
status = "✓ PASS" if passed else "✗ FAIL"
|
| 343 |
+
print(f"\nQ: {test['question']}")
|
| 344 |
+
print(f"A: {response[:300]}..." if len(response) > 300 else f"A: {response}")
|
| 345 |
+
print(f"[{status}]")
|
| 346 |
+
|
| 347 |
+
results["recommendation"]["details"].append({
|
| 348 |
+
"question": test["question"],
|
| 349 |
+
"response": response,
|
| 350 |
+
"passed": passed
|
| 351 |
+
})
|
| 352 |
+
|
| 353 |
+
# 5. Consistency Tests
|
| 354 |
+
print("\n\n[5/5] CONSISTENCY TESTS")
|
| 355 |
+
print("-" * 50)
|
| 356 |
+
consistency_questions = [
|
| 357 |
+
"What is the average rent in Thong Lo?",
|
| 358 |
+
"Is Ari a good area for expats?",
|
| 359 |
+
]
|
| 360 |
+
for q in consistency_questions:
|
| 361 |
+
score = run_consistency_test(model, tokenizer, q)
|
| 362 |
+
results["consistency"]["scores"].append(score)
|
| 363 |
+
print(f"\nQ: {q}")
|
| 364 |
+
print(f"Consistency score: {score:.2%}")
|
| 365 |
+
|
| 366 |
+
# Summary
|
| 367 |
+
print("\n\n" + "=" * 70)
|
| 368 |
+
print("EVALUATION SUMMARY")
|
| 369 |
+
print("=" * 70)
|
| 370 |
+
|
| 371 |
+
factual_score = results["factual"]["passed"] / results["factual"]["total"] * 100
|
| 372 |
+
halluc_score = results["hallucination"]["passed"] / results["hallucination"]["total"] * 100
|
| 373 |
+
compare_score = results["comparison"]["passed"] / results["comparison"]["total"] * 100
|
| 374 |
+
recommend_score = results["recommendation"]["passed"] / results["recommendation"]["total"] * 100
|
| 375 |
+
consistency_avg = sum(results["consistency"]["scores"]) / len(results["consistency"]["scores"]) * 100 if results["consistency"]["scores"] else 0
|
| 376 |
+
|
| 377 |
+
print(f"\n1. Factual Accuracy: {results['factual']['passed']}/{results['factual']['total']} ({factual_score:.1f}%)")
|
| 378 |
+
print(f"2. Hallucination Control: {results['hallucination']['passed']}/{results['hallucination']['total']} ({halluc_score:.1f}%)")
|
| 379 |
+
print(f"3. Comparison Ability: {results['comparison']['passed']}/{results['comparison']['total']} ({compare_score:.1f}%)")
|
| 380 |
+
print(f"4. Recommendations: {results['recommendation']['passed']}/{results['recommendation']['total']} ({recommend_score:.1f}%)")
|
| 381 |
+
print(f"5. Consistency: {consistency_avg:.1f}%")
|
| 382 |
+
|
| 383 |
+
overall = (factual_score + halluc_score + compare_score + recommend_score + consistency_avg) / 5
|
| 384 |
+
print(f"\n{'='*50}")
|
| 385 |
+
print(f"OVERALL SCORE: {overall:.1f}%")
|
| 386 |
+
print(f"{'='*50}")
|
| 387 |
+
|
| 388 |
+
# Grade
|
| 389 |
+
if overall >= 90:
|
| 390 |
+
grade = "A - Excellent"
|
| 391 |
+
elif overall >= 80:
|
| 392 |
+
grade = "B - Good"
|
| 393 |
+
elif overall >= 70:
|
| 394 |
+
grade = "C - Acceptable"
|
| 395 |
+
elif overall >= 60:
|
| 396 |
+
grade = "D - Needs Improvement"
|
| 397 |
+
else:
|
| 398 |
+
grade = "F - Failed"
|
| 399 |
+
|
| 400 |
+
print(f"GRADE: {grade}")
|
| 401 |
+
|
| 402 |
+
# Save results
|
| 403 |
+
with open("/root/qa-finetune/outputs/eval_results.json", "w") as f:
|
| 404 |
+
json.dump(results, f, indent=2)
|
| 405 |
+
print(f"\nDetailed results saved to: /root/qa-finetune/outputs/eval_results.json")
|
| 406 |
+
|
| 407 |
+
return results
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
if __name__ == "__main__":
|
| 411 |
+
import argparse
|
| 412 |
+
parser = argparse.ArgumentParser()
|
| 413 |
+
parser.add_argument("--model_path", type=str, default="/root/qa-finetune/outputs/qwen3-4b-dora/final")
|
| 414 |
+
args = parser.parse_args()
|
| 415 |
+
|
| 416 |
+
evaluate(args.model_path)
|