Upload folder using huggingface_hub
Browse files- config.yaml +83 -0
- eval_extended.py +292 -0
- eval_strict.py +416 -0
- inference.py +149 -0
- requirements.txt +27 -0
- run_training.sh +46 -0
- train_dora.py +186 -0
config.yaml
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DoRA Fine-tuning Config for Qwen3-4B
|
| 2 |
+
# Optimized for H100 80GB
|
| 3 |
+
|
| 4 |
+
# Model
|
| 5 |
+
base_model: Qwen/Qwen3-8B
|
| 6 |
+
model_type: AutoModelForCausalLM
|
| 7 |
+
tokenizer_type: AutoTokenizer
|
| 8 |
+
trust_remote_code: true
|
| 9 |
+
|
| 10 |
+
# Dataset
|
| 11 |
+
datasets:
|
| 12 |
+
- path: output/qwen3_train.jsonl
|
| 13 |
+
type: chat
|
| 14 |
+
split: train
|
| 15 |
+
- path: output/qwen3_val.jsonl
|
| 16 |
+
type: chat
|
| 17 |
+
split: eval
|
| 18 |
+
|
| 19 |
+
# Chat template (Qwen3 uses ChatML)
|
| 20 |
+
chat_template: chatml
|
| 21 |
+
|
| 22 |
+
# DoRA Configuration
|
| 23 |
+
adapter: dora
|
| 24 |
+
lora_r: 64 # Rank - higher for more capacity
|
| 25 |
+
lora_alpha: 128 # Alpha = 2 * r is common
|
| 26 |
+
lora_dropout: 0.05
|
| 27 |
+
lora_target_modules:
|
| 28 |
+
- q_proj
|
| 29 |
+
- k_proj
|
| 30 |
+
- v_proj
|
| 31 |
+
- o_proj
|
| 32 |
+
- gate_proj
|
| 33 |
+
- up_proj
|
| 34 |
+
- down_proj
|
| 35 |
+
|
| 36 |
+
# Training hyperparameters
|
| 37 |
+
num_epochs: 3
|
| 38 |
+
micro_batch_size: 64 # Per GPU batch size
|
| 39 |
+
gradient_accumulation_steps: 2 # Effective batch = 4 * 4 = 16
|
| 40 |
+
learning_rate: 0.0002
|
| 41 |
+
lr_scheduler: cosine
|
| 42 |
+
warmup_ratio: 0.05
|
| 43 |
+
weight_decay: 0.01
|
| 44 |
+
max_grad_norm: 1.0
|
| 45 |
+
|
| 46 |
+
# Optimizer
|
| 47 |
+
optimizer: adamw_torch_fused
|
| 48 |
+
adam_beta1: 0.9
|
| 49 |
+
adam_beta2: 0.999
|
| 50 |
+
adam_epsilon: 1e-8
|
| 51 |
+
|
| 52 |
+
# Precision
|
| 53 |
+
bf16: true
|
| 54 |
+
tf32: true
|
| 55 |
+
|
| 56 |
+
# Sequence length
|
| 57 |
+
sequence_len: 2048 # Sufficient for Q&A pairs
|
| 58 |
+
sample_packing: true # Pack multiple samples per sequence
|
| 59 |
+
pad_to_sequence_len: false
|
| 60 |
+
|
| 61 |
+
# Evaluation
|
| 62 |
+
eval_steps: 500
|
| 63 |
+
eval_batch_size: 4
|
| 64 |
+
save_steps: 500
|
| 65 |
+
save_total_limit: 3
|
| 66 |
+
|
| 67 |
+
# Logging
|
| 68 |
+
logging_steps: 50
|
| 69 |
+
report_to: tensorboard
|
| 70 |
+
wandb_project: tha-fm-qwen3
|
| 71 |
+
wandb_run_name: dora-qwen3-4b-v1
|
| 72 |
+
|
| 73 |
+
# Output
|
| 74 |
+
output_dir: ./outputs/qwen3-4b-dora
|
| 75 |
+
hub_model_id: null # Set to push to HuggingFace
|
| 76 |
+
|
| 77 |
+
# Performance
|
| 78 |
+
gradient_checkpointing: true
|
| 79 |
+
flash_attention: false
|
| 80 |
+
dataloader_num_workers: 4
|
| 81 |
+
|
| 82 |
+
# Misc
|
| 83 |
+
seed: 42
|
eval_extended.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
"""
|
| 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)
|
eval_strict.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 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/q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in/env python3
|
| 2 |
+
"""
|
| 3 |
+
Inference script for DoRA fine-tuned Qwen3-4B model.
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
python inference.py --model_path ./outputs/qwen3-4b-dora/final
|
| 7 |
+
python inference.py --model_path ./outputs/qwen3-4b-dora/final --interactive
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import torch
|
| 12 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 13 |
+
from peft import PeftModel
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def load_model(model_path: str, base_model: str = "Qwen/Qwen3-4B-Instruct"):
|
| 17 |
+
"""Load the fine-tuned model."""
|
| 18 |
+
print(f"Loading base model: {base_model}")
|
| 19 |
+
|
| 20 |
+
# Load tokenizer
|
| 21 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 22 |
+
model_path,
|
| 23 |
+
trust_remote_code=True,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# Load base model
|
| 27 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 28 |
+
base_model,
|
| 29 |
+
trust_remote_code=True,
|
| 30 |
+
torch_dtype=torch.bfloat16,
|
| 31 |
+
device_map="auto",
|
| 32 |
+
attn_implementation="flash_attention_2",
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# Load DoRA adapter
|
| 36 |
+
print(f"Loading DoRA adapter from: {model_path}")
|
| 37 |
+
model = PeftModel.from_pretrained(model, model_path)
|
| 38 |
+
model.eval()
|
| 39 |
+
|
| 40 |
+
return model, tokenizer
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def generate_response(model, tokenizer, question: str, max_new_tokens: int = 512):
|
| 44 |
+
"""Generate a response to a question."""
|
| 45 |
+
|
| 46 |
+
# Format as chat
|
| 47 |
+
messages = [
|
| 48 |
+
{"role": "system", "content": "You are a Thailand real estate and neighborhood expert for Bangkok Metropolitan Region."},
|
| 49 |
+
{"role": "user", "content": question}
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
# Apply chat template
|
| 53 |
+
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 54 |
+
|
| 55 |
+
# Tokenize
|
| 56 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 57 |
+
|
| 58 |
+
# Generate
|
| 59 |
+
with torch.no_grad():
|
| 60 |
+
outputs = model.generate(
|
| 61 |
+
**inputs,
|
| 62 |
+
max_new_tokens=max_new_tokens,
|
| 63 |
+
temperature=0.7,
|
| 64 |
+
top_p=0.9,
|
| 65 |
+
do_sample=True,
|
| 66 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# Decode
|
| 70 |
+
response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
|
| 71 |
+
return response.strip()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def run_evaluation(model, tokenizer):
|
| 75 |
+
"""Run evaluation on sample questions."""
|
| 76 |
+
|
| 77 |
+
test_questions = [
|
| 78 |
+
"What's the population of Thong Lo?",
|
| 79 |
+
"Is Sathorn expensive?",
|
| 80 |
+
"Best areas for Japanese expats?",
|
| 81 |
+
"Does Ari have good cafes?",
|
| 82 |
+
"Is Bang Kapi safe at night?",
|
| 83 |
+
"Compare Ekkamai and Thong Lo",
|
| 84 |
+
"Good area for families with kids?",
|
| 85 |
+
"Where can I find affordable condos near BTS?",
|
| 86 |
+
"What's the vibe like in Ari?",
|
| 87 |
+
"Is fiber internet available in Lat Phrao?",
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
print("\n" + "=" * 60)
|
| 91 |
+
print("EVALUATION")
|
| 92 |
+
print("=" * 60)
|
| 93 |
+
|
| 94 |
+
for q in test_questions:
|
| 95 |
+
print(f"\nQ: {q}")
|
| 96 |
+
response = generate_response(model, tokenizer, q)
|
| 97 |
+
print(f"A: {response}")
|
| 98 |
+
print("-" * 40)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def interactive_mode(model, tokenizer):
|
| 102 |
+
"""Run interactive Q&A session."""
|
| 103 |
+
|
| 104 |
+
print("\n" + "=" * 60)
|
| 105 |
+
print("INTERACTIVE MODE")
|
| 106 |
+
print("Type 'quit' or 'exit' to stop")
|
| 107 |
+
print("=" * 60)
|
| 108 |
+
|
| 109 |
+
while True:
|
| 110 |
+
print()
|
| 111 |
+
question = input("You: ").strip()
|
| 112 |
+
|
| 113 |
+
if question.lower() in ["quit", "exit", "q"]:
|
| 114 |
+
print("Goodbye!")
|
| 115 |
+
break
|
| 116 |
+
|
| 117 |
+
if not question:
|
| 118 |
+
continue
|
| 119 |
+
|
| 120 |
+
response = generate_response(model, tokenizer, question)
|
| 121 |
+
print(f"Assistant: {response}")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def main():
|
| 125 |
+
parser = argparse.ArgumentParser(description="Inference for fine-tuned Qwen3-4B")
|
| 126 |
+
parser.add_argument("--model_path", type=str, required=True, help="Path to fine-tuned model")
|
| 127 |
+
parser.add_argument("--base_model", type=str, default="Qwen/Qwen3-4B-Instruct", help="Base model name")
|
| 128 |
+
parser.add_argument("--interactive", action="store_true", help="Run in interactive mode")
|
| 129 |
+
parser.add_argument("--question", type=str, help="Single question to answer")
|
| 130 |
+
args = parser.parse_args()
|
| 131 |
+
|
| 132 |
+
# Load model
|
| 133 |
+
model, tokenizer = load_model(args.model_path, args.base_model)
|
| 134 |
+
|
| 135 |
+
if args.question:
|
| 136 |
+
# Single question mode
|
| 137 |
+
response = generate_response(model, tokenizer, args.question)
|
| 138 |
+
print(f"Q: {args.question}")
|
| 139 |
+
print(f"A: {response}")
|
| 140 |
+
elif args.interactive:
|
| 141 |
+
# Interactive mode
|
| 142 |
+
interactive_mode(model, tokenizer)
|
| 143 |
+
else:
|
| 144 |
+
# Evaluation mode
|
| 145 |
+
run_evaluation(model, tokenizer)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DoRA Fine-tuning Requirements for Qwen3-4B
|
| 2 |
+
# Tested with Python 3.10+
|
| 3 |
+
|
| 4 |
+
# Core
|
| 5 |
+
torch>=2.1.0
|
| 6 |
+
transformers>=4.40.0
|
| 7 |
+
accelerate>=0.27.0
|
| 8 |
+
datasets>=2.18.0
|
| 9 |
+
|
| 10 |
+
# PEFT (for DoRA/LoRA)
|
| 11 |
+
peft>=0.10.0
|
| 12 |
+
|
| 13 |
+
# TRL (for SFTTrainer)
|
| 14 |
+
trl>=0.8.0
|
| 15 |
+
|
| 16 |
+
# Flash Attention (optional but recommended)
|
| 17 |
+
flash-attn>=2.5.0
|
| 18 |
+
|
| 19 |
+
# Utilities
|
| 20 |
+
pyyaml>=6.0
|
| 21 |
+
wandb>=0.16.0
|
| 22 |
+
sentencepiece>=0.1.99
|
| 23 |
+
protobuf>=3.20.0
|
| 24 |
+
|
| 25 |
+
# For evaluation
|
| 26 |
+
evaluate>=0.4.0
|
| 27 |
+
rouge-score>=0.1.2
|
run_training.sh
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# DoRA Fine-tuning Script for Qwen3-4B on H100
|
| 3 |
+
# Usage: ./run_training.sh
|
| 4 |
+
|
| 5 |
+
set -e
|
| 6 |
+
|
| 7 |
+
echo "=============================================="
|
| 8 |
+
echo "DoRA Fine-tuning for Qwen3-4B"
|
| 9 |
+
echo "=============================================="
|
| 10 |
+
|
| 11 |
+
# Check GPU
|
| 12 |
+
echo ""
|
| 13 |
+
echo "GPU Info:"
|
| 14 |
+
nvidia-smi --query-gpu=name,memory.total,memory.free --format=csv
|
| 15 |
+
|
| 16 |
+
# Activate environment (adjust path as needed)
|
| 17 |
+
# source /path/to/venv/bin/activate
|
| 18 |
+
|
| 19 |
+
# Set environment variables
|
| 20 |
+
export CUDA_VISIBLE_DEVICES=0
|
| 21 |
+
export WANDB_PROJECT="tha-fm-qwen3"
|
| 22 |
+
export HF_HOME="/workspace/hf_cache" # Adjust for Runpod
|
| 23 |
+
|
| 24 |
+
# Optional: Login to HuggingFace (for gated models)
|
| 25 |
+
# huggingface-cli login --token $HF_TOKEN
|
| 26 |
+
|
| 27 |
+
# Optional: Login to WandB
|
| 28 |
+
# wandb login $WANDB_API_KEY
|
| 29 |
+
|
| 30 |
+
echo ""
|
| 31 |
+
echo "Starting training..."
|
| 32 |
+
echo ""
|
| 33 |
+
|
| 34 |
+
# Run training
|
| 35 |
+
python train_dora.py \
|
| 36 |
+
--config config.yaml
|
| 37 |
+
|
| 38 |
+
echo ""
|
| 39 |
+
echo "=============================================="
|
| 40 |
+
echo "Training Complete!"
|
| 41 |
+
echo "=============================================="
|
| 42 |
+
|
| 43 |
+
# List output files
|
| 44 |
+
echo ""
|
| 45 |
+
echo "Output files:"
|
| 46 |
+
ls -lh ../outputs/qwen3-4b-dora/
|
train_dora.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""DoRA Fine-tuning Script for Qwen3-4B"""
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import argparse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import yaml
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 13 |
+
from peft import LoraConfig, get_peft_model, TaskType
|
| 14 |
+
from trl import SFTTrainer, SFTConfig
|
| 15 |
+
|
| 16 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 17 |
+
|
| 18 |
+
def load_config(config_path: str) -> dict:
|
| 19 |
+
with open(config_path) as f:
|
| 20 |
+
return yaml.safe_load(f)
|
| 21 |
+
|
| 22 |
+
def setup_model_and_tokenizer(config: dict):
|
| 23 |
+
model_name = config["base_model"]
|
| 24 |
+
print(f"Loading model: {model_name}")
|
| 25 |
+
|
| 26 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 27 |
+
model_name,
|
| 28 |
+
trust_remote_code=config.get("trust_remote_code", True),
|
| 29 |
+
padding_side="right",
|
| 30 |
+
)
|
| 31 |
+
if tokenizer.pad_token is None:
|
| 32 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 33 |
+
|
| 34 |
+
model_kwargs = {
|
| 35 |
+
"trust_remote_code": config.get("trust_remote_code", True),
|
| 36 |
+
"torch_dtype": torch.bfloat16,
|
| 37 |
+
"device_map": "auto",
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, **model_kwargs)
|
| 41 |
+
|
| 42 |
+
if config.get("gradient_checkpointing", True):
|
| 43 |
+
model.gradient_checkpointing_enable()
|
| 44 |
+
|
| 45 |
+
peft_config = LoraConfig(
|
| 46 |
+
task_type=TaskType.CAUSAL_LM,
|
| 47 |
+
r=config.get("lora_r", 64),
|
| 48 |
+
lora_alpha=config.get("lora_alpha", 128),
|
| 49 |
+
lora_dropout=config.get("lora_dropout", 0.05),
|
| 50 |
+
target_modules=config.get("lora_target_modules", [
|
| 51 |
+
"q_proj", "k_proj", "v_proj", "o_proj",
|
| 52 |
+
"gate_proj", "up_proj", "down_proj"
|
| 53 |
+
]),
|
| 54 |
+
use_dora=True,
|
| 55 |
+
bias="none",
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
model = get_peft_model(model, peft_config)
|
| 59 |
+
model.print_trainable_parameters()
|
| 60 |
+
|
| 61 |
+
return model, tokenizer
|
| 62 |
+
|
| 63 |
+
def load_datasets(config: dict):
|
| 64 |
+
script_dir = Path(__file__).parent.parent
|
| 65 |
+
train_path = script_dir / config["datasets"][0]["path"]
|
| 66 |
+
val_path = script_dir / config["datasets"][1]["path"]
|
| 67 |
+
|
| 68 |
+
print(f"Loading training data from: {train_path}")
|
| 69 |
+
print(f"Loading validation data from: {val_path}")
|
| 70 |
+
|
| 71 |
+
train_dataset = load_dataset("json", data_files=str(train_path), split="train")
|
| 72 |
+
val_dataset = load_dataset("json", data_files=str(val_path), split="train")
|
| 73 |
+
|
| 74 |
+
print(f"Training samples: {len(train_dataset):,}")
|
| 75 |
+
print(f"Validation samples: {len(val_dataset):,}")
|
| 76 |
+
|
| 77 |
+
return train_dataset, val_dataset
|
| 78 |
+
|
| 79 |
+
def format_chat(example, tokenizer):
|
| 80 |
+
messages = example["messages"]
|
| 81 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
|
| 82 |
+
return {"text": text}
|
| 83 |
+
|
| 84 |
+
def main():
|
| 85 |
+
parser = argparse.ArgumentParser()
|
| 86 |
+
parser.add_argument("--config", type=str, default="config.yaml")
|
| 87 |
+
parser.add_argument("--resume", type=str, help="Resume from checkpoint")
|
| 88 |
+
args = parser.parse_args()
|
| 89 |
+
|
| 90 |
+
config_path = Path(__file__).parent / args.config
|
| 91 |
+
config = load_config(config_path)
|
| 92 |
+
|
| 93 |
+
print("=" * 60)
|
| 94 |
+
print("DoRA Fine-tuning for Qwen3-4B")
|
| 95 |
+
print("=" * 60)
|
| 96 |
+
print(f"Model: {config['base_model']}")
|
| 97 |
+
print(f"Epochs: {config['num_epochs']}")
|
| 98 |
+
print(f"LR: {config['learning_rate']}")
|
| 99 |
+
print(f"Batch: {config['micro_batch_size']} x {config['gradient_accumulation_steps']} = {config['micro_batch_size'] * config['gradient_accumulation_steps']}")
|
| 100 |
+
print(f"DoRA rank: {config['lora_r']}")
|
| 101 |
+
|
| 102 |
+
print("\n" + "-" * 40)
|
| 103 |
+
print("Loading model...")
|
| 104 |
+
model, tokenizer = setup_model_and_tokenizer(config)
|
| 105 |
+
|
| 106 |
+
print("\n" + "-" * 40)
|
| 107 |
+
print("Loading datasets...")
|
| 108 |
+
train_dataset, val_dataset = load_datasets(config)
|
| 109 |
+
|
| 110 |
+
print("Formatting datasets...")
|
| 111 |
+
train_dataset = train_dataset.map(
|
| 112 |
+
lambda x: format_chat(x, tokenizer),
|
| 113 |
+
remove_columns=train_dataset.column_names,
|
| 114 |
+
num_proc=4
|
| 115 |
+
)
|
| 116 |
+
val_dataset = val_dataset.map(
|
| 117 |
+
lambda x: format_chat(x, tokenizer),
|
| 118 |
+
remove_columns=val_dataset.column_names,
|
| 119 |
+
num_proc=4
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
output_dir = Path(__file__).parent.parent / config["output_dir"]
|
| 123 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 124 |
+
|
| 125 |
+
# Use SFTConfig instead of TrainingArguments
|
| 126 |
+
sft_config = SFTConfig(
|
| 127 |
+
output_dir=str(output_dir),
|
| 128 |
+
num_train_epochs=config["num_epochs"],
|
| 129 |
+
per_device_train_batch_size=config["micro_batch_size"],
|
| 130 |
+
per_device_eval_batch_size=config.get("eval_batch_size", config["micro_batch_size"]),
|
| 131 |
+
gradient_accumulation_steps=config["gradient_accumulation_steps"],
|
| 132 |
+
learning_rate=config["learning_rate"],
|
| 133 |
+
lr_scheduler_type=config.get("lr_scheduler", "cosine"),
|
| 134 |
+
warmup_ratio=config.get("warmup_ratio", 0.05),
|
| 135 |
+
weight_decay=config.get("weight_decay", 0.01),
|
| 136 |
+
max_grad_norm=config.get("max_grad_norm", 1.0),
|
| 137 |
+
bf16=config.get("bf16", True),
|
| 138 |
+
tf32=config.get("tf32", True),
|
| 139 |
+
logging_steps=config.get("logging_steps", 50),
|
| 140 |
+
eval_strategy="steps",
|
| 141 |
+
eval_steps=config.get("eval_steps", 500),
|
| 142 |
+
save_strategy="steps",
|
| 143 |
+
save_steps=config.get("save_steps", 500),
|
| 144 |
+
save_total_limit=config.get("save_total_limit", 3),
|
| 145 |
+
load_best_model_at_end=True,
|
| 146 |
+
metric_for_best_model="eval_loss",
|
| 147 |
+
greater_is_better=False,
|
| 148 |
+
report_to=config.get("report_to", "tensorboard"),
|
| 149 |
+
run_name=f"dora-{datetime.now().strftime('%Y%m%d_%H%M')}",
|
| 150 |
+
dataloader_num_workers=config.get("dataloader_num_workers", 4),
|
| 151 |
+
seed=config.get("seed", 42),
|
| 152 |
+
gradient_checkpointing=config.get("gradient_checkpointing", True),
|
| 153 |
+
optim=config.get("optimizer", "adamw_torch_fused"),
|
| 154 |
+
max_length=config.get("sequence_len", 1024),
|
| 155 |
+
packing=False,
|
| 156 |
+
dataset_text_field="text",
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
print("\n" + "-" * 40)
|
| 160 |
+
print("Setting up trainer...")
|
| 161 |
+
trainer = SFTTrainer(
|
| 162 |
+
model=model,
|
| 163 |
+
args=sft_config,
|
| 164 |
+
train_dataset=train_dataset,
|
| 165 |
+
eval_dataset=val_dataset,
|
| 166 |
+
processing_class=tokenizer,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
print("\n" + "=" * 60)
|
| 170 |
+
print("Starting training...")
|
| 171 |
+
print("=" * 60)
|
| 172 |
+
|
| 173 |
+
if args.resume:
|
| 174 |
+
trainer.train(resume_from_checkpoint=args.resume)
|
| 175 |
+
else:
|
| 176 |
+
trainer.train()
|
| 177 |
+
|
| 178 |
+
print("\nSaving final model...")
|
| 179 |
+
final_path = output_dir / "final"
|
| 180 |
+
trainer.save_model(str(final_path))
|
| 181 |
+
tokenizer.save_pretrained(str(final_path))
|
| 182 |
+
print(f"Model saved to: {final_path}")
|
| 183 |
+
print("\nTraining complete!")
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
main()
|