File size: 13,936 Bytes
61e5f64 | 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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | #!/usr/bin/env python3
"""
Extended Evaluation - Multiple rounds with more test cases
"""
import json
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
import random
# Extended test cases
FACTUAL_TESTS = [
# Demographics
{"q": "What is the population density of Khlong Toei?", "keywords": ["population", "density"], "cat": "demographics"},
{"q": "How many people live in Watthana district?", "keywords": ["population", "watthana"], "cat": "demographics"},
{"q": "What percentage of Silom residents are working age?", "keywords": ["working", "age", "%"], "cat": "demographics"},
{"q": "Is Ratchathewi densely populated?", "keywords": ["density", "populated"], "cat": "demographics"},
# Property/Housing
{"q": "What is the average condo price per sqm in Thong Lo?", "keywords": ["price", "thong lo", "sqm"], "cat": "property"},
{"q": "Are there detached houses in Sathorn?", "keywords": ["house", "sathorn"], "cat": "property"},
{"q": "What's the typical rent in Ari?", "keywords": ["rent", "ari", "baht"], "cat": "property"},
{"q": "Is Bang Na affordable for condos?", "keywords": ["affordable", "bang na"], "cat": "property"},
# Transport
{"q": "Does Asok have MRT access?", "keywords": ["mrt", "asok"], "cat": "transport"},
{"q": "How far is the nearest BTS from Lat Phrao?", "keywords": ["bts", "lat phrao", "km"], "cat": "transport"},
{"q": "Is Rama 9 well connected by rail?", "keywords": ["rama 9", "mrt", "rail"], "cat": "transport"},
{"q": "Can I walk to BTS from Phrom Phong?", "keywords": ["bts", "phrom phong", "walk"], "cat": "transport"},
# Lifestyle
{"q": "Are there good cafes in Ari?", "keywords": ["cafe", "ari"], "cat": "lifestyle"},
{"q": "What's the nightlife like in Thong Lo?", "keywords": ["nightlife", "thong lo", "bar"], "cat": "lifestyle"},
{"q": "Does Ekkamai have coworking spaces?", "keywords": ["coworking", "ekkamai"], "cat": "lifestyle"},
{"q": "Are there gyms in Sukhumvit?", "keywords": ["gym", "fitness", "sukhumvit"], "cat": "lifestyle"},
# Safety
{"q": "Is Khlong Toei safe at night?", "keywords": ["safe", "khlong toei", "night"], "cat": "safety"},
{"q": "How safe is Silom for walking?", "keywords": ["safe", "silom"], "cat": "safety"},
{"q": "What's the crime rate in Sathorn?", "keywords": ["crime", "safe", "sathorn"], "cat": "safety"},
# Education/Healthcare
{"q": "Are there international schools in Watthana?", "keywords": ["school", "international", "watthana"], "cat": "education"},
{"q": "Does Ari have good hospitals nearby?", "keywords": ["hospital", "ari"], "cat": "healthcare"},
{"q": "Is there a university near Ratchathewi?", "keywords": ["university", "ratchathewi"], "cat": "education"},
# Environment
{"q": "What is the AQI in Bang Kapi?", "keywords": ["aqi", "air", "bang kapi"], "cat": "environment"},
{"q": "Are there parks in Chatuchak?", "keywords": ["park", "green", "chatuchak"], "cat": "environment"},
{"q": "How noisy is Pratunam?", "keywords": ["noise", "pratunam"], "cat": "environment"},
# Telecom
{"q": "Is fiber internet available in On Nut?", "keywords": ["fiber", "internet", "on nut"], "cat": "telecom"},
{"q": "What's the 5G coverage in Sukhumvit?", "keywords": ["5g", "coverage", "sukhumvit"], "cat": "telecom"},
# Food/Shopping
{"q": "Are there street food options in Yaowarat?", "keywords": ["food", "street", "yaowarat"], "cat": "food"},
{"q": "Does Siam have shopping malls?", "keywords": ["mall", "shopping", "siam"], "cat": "shopping"},
{"q": "Where can I find Japanese restaurants in Phrom Phong?", "keywords": ["japanese", "restaurant", "phrom phong"], "cat": "food"},
]
HALLUCINATION_TESTS = [
{"q": "What is the population of Zarathon district?", "fake": "Zarathon"},
{"q": "Is Moonville in Bangkok expensive?", "fake": "Moonville"},
{"q": "Tell me about Krungthep Noi subdistrict", "fake": "Krungthep Noi"},
{"q": "How safe is Banglamung Central?", "fake": "Banglamung Central"},
{"q": "What's the rent in New Siam district?", "fake": "New Siam"},
{"q": "Does Phanthai Norasing have good schools?", "fake": "Phanthai Norasing"},
]
COMPARISON_TESTS = [
{"q": "Compare Thong Lo and Ekkamai for expats", "areas": ["thong lo", "ekkamai"]},
{"q": "Which is cheaper, Ari or Sathorn?", "areas": ["ari", "sathorn", "cheap"]},
{"q": "Is On Nut or Bang Na better for families?", "areas": ["on nut", "bang na", "family"]},
{"q": "Silom vs Sathorn for working professionals?", "areas": ["silom", "sathorn"]},
{"q": "Compare Lat Phrao and Ratchada for condos", "areas": ["lat phrao", "ratchada", "condo"]},
]
RECOMMENDATION_TESTS = [
{"q": "Best area for young professionals near BTS?", "should_have_area": True},
{"q": "Where should a family with kids live in Bangkok?", "should_have_area": True},
{"q": "Affordable areas with good transit?", "should_have_area": True},
{"q": "Best neighborhood for Japanese expats?", "should_have_area": True},
{"q": "Where to live if I work in Silom?", "should_have_area": True},
{"q": "Quiet areas away from tourist crowds?", "should_have_area": True},
{"q": "Best area for nightlife and bars?", "should_have_area": True},
{"q": "Good areas for remote workers with cafes?", "should_have_area": True},
]
KNOWN_AREAS = ["ari", "thong lo", "ekkamai", "sathorn", "silom", "sukhumvit",
"lat phrao", "bang kapi", "ratchada", "phra khanong", "on nut",
"bang na", "rama 9", "asok", "phrom phong", "nana", "chatuchak",
"watthana", "khlong toei", "din daeng", "huai khwang", "siam",
"pratunam", "yaowarat", "bang rak", "pathum wan"]
def load_model(model_path: str):
print(f"Loading model from {model_path}...")
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen3-8B", trust_remote_code=True,
torch_dtype=torch.bfloat16, device_map="auto",
)
model = PeftModel.from_pretrained(model, model_path)
model.eval()
return model, tokenizer
def generate(model, tokenizer, question: str, max_tokens: int = 256):
messages = [
{"role": "system", "content": "You are a Thailand real estate and neighborhood expert for Bangkok Metropolitan Region."},
{"role": "user", "content": question}
]
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model.generate(**inputs, max_new_tokens=max_tokens, temperature=0.3,
top_p=0.9, do_sample=True, pad_token_id=tokenizer.eos_token_id)
return tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
def score_factual(response, keywords):
resp_lower = response.lower()
found = sum(1 for k in keywords if k.lower() in resp_lower)
return found / len(keywords) if keywords else 0
def score_hallucination(response, fake_area):
resp_lower = response.lower()
uncertainty = ["don't have", "not familiar", "don't know", "no data", "cannot find",
"not aware", "doesn't exist", "not a real", "unable to", "no information", "i'm not sure"]
confident = ["population of", "has a density", "is known for", "approximately", "residents", "located in"]
admits_unknown = any(p in resp_lower for p in uncertainty)
makes_up = any(p in resp_lower for p in confident)
if admits_unknown:
return 1.0
elif makes_up:
return 0.0
else:
return 0.5
def score_comparison(response, areas):
resp_lower = response.lower()
found = sum(1 for a in areas if a.lower() in resp_lower)
return found / len(areas) if areas else 0
def score_recommendation(response):
resp_lower = response.lower()
areas_found = sum(1 for a in KNOWN_AREAS if a in resp_lower)
return min(1.0, areas_found / 2) # At least 2 areas = full score
def run_evaluation(model, tokenizer, rounds=3):
all_results = []
for round_num in range(1, rounds + 1):
print(f"\n{'='*70}")
print(f"ROUND {round_num}/{rounds}")
print(f"{'='*70}")
round_scores = {
"factual": [], "hallucination": [], "comparison": [], "recommendation": []
}
# Factual tests (sample 15)
print(f"\n[Factual Tests - 15 questions]")
sampled_factual = random.sample(FACTUAL_TESTS, min(15, len(FACTUAL_TESTS)))
for t in sampled_factual:
resp = generate(model, tokenizer, t["q"])
score = score_factual(resp, t["keywords"])
round_scores["factual"].append(score)
status = "✓" if score >= 0.5 else "✗"
print(f" {status} [{t['cat'][:8]:8}] {t['q'][:50]:50} | {score:.0%}")
# Hallucination tests (all)
print(f"\n[Hallucination Tests - {len(HALLUCINATION_TESTS)} questions]")
for t in HALLUCINATION_TESTS:
resp = generate(model, tokenizer, t["q"])
score = score_hallucination(resp, t["fake"])
round_scores["hallucination"].append(score)
status = "✓" if score >= 0.5 else "✗"
print(f" {status} Fake: {t['fake']:20} | {score:.0%}")
# Comparison tests (all)
print(f"\n[Comparison Tests - {len(COMPARISON_TESTS)} questions]")
for t in COMPARISON_TESTS:
resp = generate(model, tokenizer, t["q"])
score = score_comparison(resp, t["areas"])
round_scores["comparison"].append(score)
status = "✓" if score >= 0.5 else "✗"
print(f" {status} {t['q'][:50]:50} | {score:.0%}")
# Recommendation tests (all)
print(f"\n[Recommendation Tests - {len(RECOMMENDATION_TESTS)} questions]")
for t in RECOMMENDATION_TESTS:
resp = generate(model, tokenizer, t["q"])
score = score_recommendation(resp)
round_scores["recommendation"].append(score)
status = "✓" if score >= 0.5 else "✗"
print(f" {status} {t['q'][:50]:50} | {score:.0%}")
# Round summary
factual_avg = sum(round_scores["factual"]) / len(round_scores["factual"]) * 100
halluc_avg = sum(round_scores["hallucination"]) / len(round_scores["hallucination"]) * 100
compare_avg = sum(round_scores["comparison"]) / len(round_scores["comparison"]) * 100
recommend_avg = sum(round_scores["recommendation"]) / len(round_scores["recommendation"]) * 100
round_overall = (factual_avg + halluc_avg + compare_avg + recommend_avg) / 4
print(f"\n--- Round {round_num} Summary ---")
print(f" Factual: {factual_avg:5.1f}%")
print(f" Hallucination: {halluc_avg:5.1f}%")
print(f" Comparison: {compare_avg:5.1f}%")
print(f" Recommendation:{recommend_avg:5.1f}%")
print(f" Round Score: {round_overall:5.1f}%")
all_results.append({
"round": round_num,
"factual": factual_avg,
"hallucination": halluc_avg,
"comparison": compare_avg,
"recommendation": recommend_avg,
"overall": round_overall
})
# Final summary
print(f"\n{'='*70}")
print("FINAL EVALUATION SUMMARY")
print(f"{'='*70}")
avg_factual = sum(r["factual"] for r in all_results) / len(all_results)
avg_halluc = sum(r["hallucination"] for r in all_results) / len(all_results)
avg_compare = sum(r["comparison"] for r in all_results) / len(all_results)
avg_recommend = sum(r["recommendation"] for r in all_results) / len(all_results)
avg_overall = sum(r["overall"] for r in all_results) / len(all_results)
print(f"\nAcross {rounds} rounds:")
print(f" Factual Accuracy: {avg_factual:5.1f}%")
print(f" Hallucination Control: {avg_halluc:5.1f}%")
print(f" Comparison Ability: {avg_compare:5.1f}%")
print(f" Recommendations: {avg_recommend:5.1f}%")
print(f"\n {'='*30}")
print(f" FINAL SCORE: {avg_overall:5.1f}%")
print(f" {'='*30}")
# Grade
if avg_overall >= 90: grade = "A+"
elif avg_overall >= 85: grade = "A"
elif avg_overall >= 80: grade = "B+"
elif avg_overall >= 75: grade = "B"
elif avg_overall >= 70: grade = "C+"
elif avg_overall >= 65: grade = "C"
elif avg_overall >= 60: grade = "D"
else: grade = "F"
print(f" GRADE: {grade}")
# Breakdown by category for factual
print(f"\n--- Factual Breakdown by Category ---")
cat_scores = {}
for t in FACTUAL_TESTS:
if t["cat"] not in cat_scores:
cat_scores[t["cat"]] = []
print(" (Run full eval for category breakdown)")
# Save
with open("/root/qa-finetune/outputs/eval_extended_results.json", "w") as f:
json.dump({"rounds": all_results, "final": {
"factual": avg_factual, "hallucination": avg_halluc,
"comparison": avg_compare, "recommendation": avg_recommend,
"overall": avg_overall, "grade": grade
}}, f, indent=2)
print(f"\nResults saved to: /root/qa-finetune/outputs/eval_extended_results.json")
return avg_overall, grade
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--model_path", default="/root/qa-finetune/outputs/qwen3-4b-dora/final")
parser.add_argument("--rounds", type=int, default=3)
args = parser.parse_args()
model, tokenizer = load_model(args.model_path)
run_evaluation(model, tokenizer, args.rounds)
|