Download eval_strict.py from puzzled-neuron/tha-bmr-training-scripts: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/puzzled-neuron/tha-bmr-training-scripts/resolve/main/eval_strict.py
- Command line
-
hf download hf://puzzled-neuron/tha-bmr-training-scripts/eval_strict.py
-
curl -L -o eval_strict.py https://huggingface.co/puzzled-neuron/tha-bmr-training-scripts/resolve/main/eval_strict.py
14.6 kB
| #!/usr/bin/env python3 | |
| """ | |
| Strict Evaluation Script for Fine-tuned Qwen3-8B DoRA Model | |
| Tests: | |
| 1. Factual Accuracy - Does it return correct facts from training data? | |
| 2. Hallucination Detection - Does it make up facts about unknown areas? | |
| 3. Consistency - Same question, same answer? | |
| 4. Format Quality - Proper response structure? | |
| 5. Coverage - Can it answer across all categories? | |
| """ | |
| import json | |
| import random | |
| import torch | |
| from pathlib import Path | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from peft import PeftModel | |
| from collections import defaultdict | |
| import re | |
| # Ground truth test cases (from training data) | |
| FACTUAL_TESTS = [ | |
| { | |
| "question": "What is the population density of Khlong Toei?", | |
| "expected_keywords": ["population", "density", "khlong toei"], | |
| "category": "demographics" | |
| }, | |
| { | |
| "question": "Is fiber internet available in Thong Lo?", | |
| "expected_keywords": ["fiber", "internet", "available", "thong lo"], | |
| "category": "telecom" | |
| }, | |
| { | |
| "question": "What type of housing is common in Sathorn?", | |
| "expected_keywords": ["condo", "housing", "sathorn"], | |
| "category": "housing" | |
| }, | |
| { | |
| "question": "How safe is Ari at night?", | |
| "expected_keywords": ["safe", "ari", "night"], | |
| "category": "safety" | |
| }, | |
| { | |
| "question": "What is the average condo price in Sukhumvit?", | |
| "expected_keywords": ["price", "condo", "baht", "sukhumvit"], | |
| "category": "property" | |
| }, | |
| { | |
| "question": "Does Lat Phrao have good BTS access?", | |
| "expected_keywords": ["bts", "mrt", "transit", "lat phrao"], | |
| "category": "transport" | |
| }, | |
| { | |
| "question": "What is the expat population like in Ekkamai?", | |
| "expected_keywords": ["expat", "foreigner", "ekkamai"], | |
| "category": "demographics" | |
| }, | |
| { | |
| "question": "Are there international schools near Ari?", | |
| "expected_keywords": ["school", "international", "education", "ari"], | |
| "category": "education" | |
| }, | |
| { | |
| "question": "What's the air quality like in Bang Kapi?", | |
| "expected_keywords": ["air", "quality", "aqi", "bang kapi"], | |
| "category": "environment" | |
| }, | |
| { | |
| "question": "Is Phra Khanong good for families?", | |
| "expected_keywords": ["family", "families", "phra khanong"], | |
| "category": "lifestyle" | |
| }, | |
| ] | |
| # Hallucination tests - areas that DON'T exist or aren't in BMR | |
| HALLUCINATION_TESTS = [ | |
| { | |
| "question": "What is the population of Zarathon district?", | |
| "should_admit_unknown": True, | |
| "fake_area": "Zarathon" | |
| }, | |
| { | |
| "question": "Is Moonville in Bangkok expensive?", | |
| "should_admit_unknown": True, | |
| "fake_area": "Moonville" | |
| }, | |
| { | |
| "question": "Tell me about Krungthep Noi subdistrict", | |
| "should_admit_unknown": True, | |
| "fake_area": "Krungthep Noi" | |
| }, | |
| ] | |
| # Comparison tests | |
| COMPARISON_TESTS = [ | |
| { | |
| "question": "Compare Thong Lo and Ekkamai for expats", | |
| "expected_mentions": ["thong lo", "ekkamai"], | |
| "category": "comparison" | |
| }, | |
| { | |
| "question": "Which is cheaper, Ari or Sathorn?", | |
| "expected_mentions": ["ari", "sathorn", "price", "cheaper"], | |
| "category": "comparison" | |
| }, | |
| ] | |
| # Recommendation tests | |
| RECOMMENDATION_TESTS = [ | |
| { | |
| "question": "Best area for young professionals near BTS?", | |
| "should_recommend_area": True, | |
| "category": "recommendation" | |
| }, | |
| { | |
| "question": "Where should a family with kids live in Bangkok?", | |
| "should_recommend_area": True, | |
| "category": "recommendation" | |
| }, | |
| { | |
| "question": "Affordable areas with good transit?", | |
| "should_recommend_area": True, | |
| "category": "recommendation" | |
| }, | |
| ] | |
| def load_model(model_path: str, base_model: str = "Qwen/Qwen3-8B"): | |
| """Load the fine-tuned model.""" | |
| print(f"Loading base model: {base_model}") | |
| tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| base_model, | |
| trust_remote_code=True, | |
| torch_dtype=torch.bfloat16, | |
| device_map="auto", | |
| ) | |
| 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 = 256): | |
| """Generate a response.""" | |
| 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_new_tokens, | |
| temperature=0.3, # Lower temp for more deterministic eval | |
| top_p=0.9, | |
| do_sample=True, | |
| pad_token_id=tokenizer.eos_token_id, | |
| ) | |
| response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True) | |
| return response.strip() | |
| def check_keywords(response: str, keywords: list) -> tuple: | |
| """Check if response contains expected keywords.""" | |
| response_lower = response.lower() | |
| found = [] | |
| missing = [] | |
| for kw in keywords: | |
| if kw.lower() in response_lower: | |
| found.append(kw) | |
| else: | |
| missing.append(kw) | |
| return found, missing | |
| def check_hallucination(response: str, fake_area: str) -> bool: | |
| """Check if model admits it doesn't know about fake area.""" | |
| uncertainty_phrases = [ | |
| "don't have information", | |
| "not familiar", | |
| "don't know", | |
| "no data", | |
| "cannot find", | |
| "not aware", | |
| "doesn't exist", | |
| "not a real", | |
| "unable to find", | |
| "no information", | |
| "i'm not sure", | |
| "i don't have", | |
| ] | |
| response_lower = response.lower() | |
| # Check if it admits uncertainty | |
| admits_unknown = any(phrase in response_lower for phrase in uncertainty_phrases) | |
| # Check if it confidently makes up facts (bad) | |
| confident_phrases = ["population of", "located in", "has a density", "is known for", "residents live"] | |
| makes_up_facts = any(phrase in response_lower for phrase in confident_phrases) | |
| return admits_unknown or not makes_up_facts | |
| def check_recommendation(response: str) -> bool: | |
| """Check if response provides actual area recommendations.""" | |
| # Common Bangkok areas | |
| 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"] | |
| response_lower = response.lower() | |
| return any(area in response_lower for area in areas) | |
| def run_consistency_test(model, tokenizer, question: str, n_runs: int = 3) -> float: | |
| """Check if model gives consistent answers.""" | |
| responses = [] | |
| for _ in range(n_runs): | |
| resp = generate_response(model, tokenizer, question) | |
| responses.append(resp.lower()) | |
| # Simple consistency: check if key facts are mentioned in all responses | |
| # Extract numbers and area names mentioned | |
| all_words = [set(re.findall(r'\b\w+\b', r)) for r in responses] | |
| common_words = set.intersection(*all_words) if all_words else set() | |
| # Higher ratio of common words = more consistent | |
| avg_len = sum(len(w) for w in all_words) / len(all_words) | |
| consistency = len(common_words) / avg_len if avg_len > 0 else 0 | |
| return consistency | |
| def evaluate(model_path: str): | |
| """Run full evaluation.""" | |
| model, tokenizer = load_model(model_path) | |
| results = { | |
| "factual": {"passed": 0, "total": 0, "details": []}, | |
| "hallucination": {"passed": 0, "total": 0, "details": []}, | |
| "comparison": {"passed": 0, "total": 0, "details": []}, | |
| "recommendation": {"passed": 0, "total": 0, "details": []}, | |
| "consistency": {"scores": [], "details": []}, | |
| } | |
| print("\n" + "=" * 70) | |
| print("STRICT EVALUATION - Fine-tuned Qwen3-8B DoRA") | |
| print("=" * 70) | |
| # 1. Factual Tests | |
| print("\n[1/5] FACTUAL ACCURACY TESTS") | |
| print("-" * 50) | |
| for test in FACTUAL_TESTS: | |
| response = generate_response(model, tokenizer, test["question"]) | |
| found, missing = check_keywords(response, test["expected_keywords"]) | |
| passed = len(missing) <= 1 # Allow 1 missing keyword | |
| results["factual"]["total"] += 1 | |
| if passed: | |
| results["factual"]["passed"] += 1 | |
| status = "✓ PASS" if passed else "✗ FAIL" | |
| print(f"\nQ: {test['question']}") | |
| print(f"A: {response[:200]}..." if len(response) > 200 else f"A: {response}") | |
| print(f"Keywords found: {found}, missing: {missing}") | |
| print(f"[{status}]") | |
| results["factual"]["details"].append({ | |
| "question": test["question"], | |
| "response": response, | |
| "passed": passed, | |
| "found": found, | |
| "missing": missing | |
| }) | |
| # 2. Hallucination Tests | |
| print("\n\n[2/5] HALLUCINATION DETECTION TESTS") | |
| print("-" * 50) | |
| for test in HALLUCINATION_TESTS: | |
| response = generate_response(model, tokenizer, test["question"]) | |
| passed = check_hallucination(response, test["fake_area"]) | |
| results["hallucination"]["total"] += 1 | |
| if passed: | |
| results["hallucination"]["passed"] += 1 | |
| status = "✓ PASS" if passed else "✗ FAIL (hallucinated)" | |
| print(f"\nQ: {test['question']}") | |
| print(f"A: {response[:200]}..." if len(response) > 200 else f"A: {response}") | |
| print(f"[{status}]") | |
| results["hallucination"]["details"].append({ | |
| "question": test["question"], | |
| "response": response, | |
| "passed": passed, | |
| "fake_area": test["fake_area"] | |
| }) | |
| # 3. Comparison Tests | |
| print("\n\n[3/5] COMPARISON TESTS") | |
| print("-" * 50) | |
| for test in COMPARISON_TESTS: | |
| response = generate_response(model, tokenizer, test["question"]) | |
| found, missing = check_keywords(response, test["expected_mentions"]) | |
| passed = len(missing) == 0 | |
| results["comparison"]["total"] += 1 | |
| if passed: | |
| results["comparison"]["passed"] += 1 | |
| status = "✓ PASS" if passed else "✗ FAIL" | |
| print(f"\nQ: {test['question']}") | |
| print(f"A: {response[:300]}..." if len(response) > 300 else f"A: {response}") | |
| print(f"[{status}]") | |
| results["comparison"]["details"].append({ | |
| "question": test["question"], | |
| "response": response, | |
| "passed": passed | |
| }) | |
| # 4. Recommendation Tests | |
| print("\n\n[4/5] RECOMMENDATION TESTS") | |
| print("-" * 50) | |
| for test in RECOMMENDATION_TESTS: | |
| response = generate_response(model, tokenizer, test["question"]) | |
| passed = check_recommendation(response) | |
| results["recommendation"]["total"] += 1 | |
| if passed: | |
| results["recommendation"]["passed"] += 1 | |
| status = "✓ PASS" if passed else "✗ FAIL" | |
| print(f"\nQ: {test['question']}") | |
| print(f"A: {response[:300]}..." if len(response) > 300 else f"A: {response}") | |
| print(f"[{status}]") | |
| results["recommendation"]["details"].append({ | |
| "question": test["question"], | |
| "response": response, | |
| "passed": passed | |
| }) | |
| # 5. Consistency Tests | |
| print("\n\n[5/5] CONSISTENCY TESTS") | |
| print("-" * 50) | |
| consistency_questions = [ | |
| "What is the average rent in Thong Lo?", | |
| "Is Ari a good area for expats?", | |
| ] | |
| for q in consistency_questions: | |
| score = run_consistency_test(model, tokenizer, q) | |
| results["consistency"]["scores"].append(score) | |
| print(f"\nQ: {q}") | |
| print(f"Consistency score: {score:.2%}") | |
| # Summary | |
| print("\n\n" + "=" * 70) | |
| print("EVALUATION SUMMARY") | |
| print("=" * 70) | |
| factual_score = results["factual"]["passed"] / results["factual"]["total"] * 100 | |
| halluc_score = results["hallucination"]["passed"] / results["hallucination"]["total"] * 100 | |
| compare_score = results["comparison"]["passed"] / results["comparison"]["total"] * 100 | |
| recommend_score = results["recommendation"]["passed"] / results["recommendation"]["total"] * 100 | |
| consistency_avg = sum(results["consistency"]["scores"]) / len(results["consistency"]["scores"]) * 100 if results["consistency"]["scores"] else 0 | |
| print(f"\n1. Factual Accuracy: {results['factual']['passed']}/{results['factual']['total']} ({factual_score:.1f}%)") | |
| print(f"2. Hallucination Control: {results['hallucination']['passed']}/{results['hallucination']['total']} ({halluc_score:.1f}%)") | |
| print(f"3. Comparison Ability: {results['comparison']['passed']}/{results['comparison']['total']} ({compare_score:.1f}%)") | |
| print(f"4. Recommendations: {results['recommendation']['passed']}/{results['recommendation']['total']} ({recommend_score:.1f}%)") | |
| print(f"5. Consistency: {consistency_avg:.1f}%") | |
| overall = (factual_score + halluc_score + compare_score + recommend_score + consistency_avg) / 5 | |
| print(f"\n{'='*50}") | |
| print(f"OVERALL SCORE: {overall:.1f}%") | |
| print(f"{'='*50}") | |
| # Grade | |
| if overall >= 90: | |
| grade = "A - Excellent" | |
| elif overall >= 80: | |
| grade = "B - Good" | |
| elif overall >= 70: | |
| grade = "C - Acceptable" | |
| elif overall >= 60: | |
| grade = "D - Needs Improvement" | |
| else: | |
| grade = "F - Failed" | |
| print(f"GRADE: {grade}") | |
| # Save results | |
| with open("/root/qa-finetune/outputs/eval_results.json", "w") as f: | |
| json.dump(results, f, indent=2) | |
| print(f"\nDetailed results saved to: /root/qa-finetune/outputs/eval_results.json") | |
| return results | |
| if __name__ == "__main__": | |
| import argparse | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--model_path", type=str, default="/root/qa-finetune/outputs/qwen3-4b-dora/final") | |
| args = parser.parse_args() | |
| evaluate(args.model_path) | |