puzzled-neuron commited on
Commit
61e5f64
·
verified ·
1 Parent(s): 534fc07

Upload training/eval_extended.py with huggingface_hub

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