sakthai-kaggle-notebooks / scripts /sakthai-7b-post-train.py
Nanthasit's picture
Add post-training merge + benchmark script
9668dbd verified
Raw History Blame
14 kB
#!/usr/bin/env python3
"""
SakThai 7B Post-Training Pipeline
=================================
Run AFTER Kaggle notebook finishes training.
Steps:
1. Download LoRA adapter from HF
2. Merge with base Qwen2.5-7B-Instruct
3. Push merged safetensors to HF
4. Quantize to GGUF Q4_K_M
5. Run BFCL-style benchmark
6. Generate final report
Usage:
# HF_TOKEN must be set or passed via env
python3 sakthai-7b-post-train.py
Requires:
pip install transformers peft accelerate torch huggingface_hub
# For GGUF quant: llama.cpp built with llama-quantize
"""
import os
import json
import sys
import datetime
import torch
from huggingface_hub import login, HfApi, snapshot_download
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
# ─── Config ─────────────────────────────────────────────────
BASE_MODEL = "Qwen/Qwen2.5-7B-Instruct"
ADAPTER_REPO = "Nanthasit/sakthai-7b-lora-kaggle"
MERGED_REPO = "Nanthasit/sakthai-context-7b-tools"
HF_TOKEN = os.environ.get("HF_TOKEN")
WORK_DIR = "/opt/data/sakthai-7b-post"
os.makedirs(WORK_DIR, exist_ok=True)
REPORT = {
"pipeline": "sakthai-7b-post-train",
"start_time": str(datetime.datetime.now()),
"steps": {},
}
# ─── Auth ────────────────────────────────────────────────────
if HF_TOKEN:
login(token=HF_TOKEN, add_to_git_credential=True)
api = HfApi()
user = api.whoami()["name"]
print(f"✅ Authenticated as: {user}")
else:
print("❌ HF_TOKEN not set")
sys.exit(1)
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
# ═════════════════════════════════════════════════════════════
# Step 1: Download adapter
# ═════════════════════════════════════════════════════════════
print("\n" + "="*60)
print("📥 Step 1: Downloading LoRA adapter")
print("="*60)
adapter_path = f"{WORK_DIR}/adapter"
snapshot_download(
repo_id=ADAPTER_REPO,
local_dir=adapter_path,
repo_type="model",
)
print(f"✅ Adapter downloaded to {adapter_path}")
# ═════════════════════════════════════════════════════════════
# Step 2: Merge with base model
# ═════════════════════════════════════════════════════════════
print("\n" + "="*60)
print("🔗 Step 2: Merging LoRA with base model")
print("="*60)
merge_path = f"{WORK_DIR}/merged"
os.makedirs(merge_path, exist_ok=True)
try:
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, trust_remote_code=True)
if device == "cuda":
base = AutoModelForCausalLM.from_pretrained(
BASE_MODEL, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True
)
merged = PeftModel.from_pretrained(base, adapter_path)
merged_model = merged.merge_and_unload()
else:
# CPU merge — slower but works
print("CPU merge — this will take a while for 7B...")
base = AutoModelForCausalLM.from_pretrained(
BASE_MODEL, torch_dtype=torch.float32, device_map="cpu", trust_remote_code=True
)
merged = PeftModel.from_pretrained(base, adapter_path)
merged_model = merged.merge_and_unload()
merged_model.save_pretrained(merge_path, safe_serialization=True)
tokenizer.save_pretrained(merge_path)
print(f"✅ Merged model saved to {merge_path}")
REPORT["steps"]["merge"] = {"status": "success", "path": merge_path}
except Exception as e:
print(f"❌ Merge failed: {e}")
REPORT["steps"]["merge"] = {"status": "failed", "error": str(e)}
sys.exit(1)
# ═════════════════════════════════════════════════════════════
# Step 3: Push merged model to HF
# ═════════════════════════════════════════════════════════════
print("\n" + "="*60)
print("☁️ Step 3: Pushing merged model to HF Hub")
print("="*60)
try:
api.create_repo(repo_id=MERGED_REPO, repo_type="model", exist_ok=True, private=False)
api.upload_folder(
folder_path=merge_path,
repo_id=MERGED_REPO,
path_in_repo=".",
commit_message="Merge Qwen2.5-7B-Instruct + sakthai-v5 LoRA",
)
url = f"https://huggingface.co/{MERGED_REPO}"
print(f"✅ Merged model pushed: {url}")
REPORT["steps"]["push_merged"] = {"status": "success", "url": url}
except Exception as e:
print(f"❌ Push failed: {e}")
REPORT["steps"]["push_merged"] = {"status": "failed", "error": str(e)}
# ═════════════════════════════════════════════════════════════
# Step 4: GGUF Quantization (if llama.cpp is available)
# ═════════════════════════════════════════════════════════════
print("\n" + "="*60)
print("🔧 Step 4: GGUF Quantization")
print("="*60)
quant_path = f"{WORK_DIR}/gguf"
os.makedirs(quant_path, exist_ok=True)
# Check if llama-quantize is available
import shutil
llama_quantize = shutil.which("llama-quantize")
if llama_quantize:
print(f"Found llama-quantize at: {llama_quantize}")
f16_path = f"{quant_path}/sakthai-7b-tools-f16.gguf"
q4_path = f"{quant_path}/sakthai-7b-tools-Q4_K_M.gguf"
# Convert to FP16 GGUF first
convert_script = shutil.which("convert_hf_to_gguf.py") or "/tmp/llama.cpp/convert_hf_to_gguf.py"
if os.path.exists(convert_script):
import subprocess
subprocess.run([
sys.executable, convert_script, merge_path,
"--outfile", f16_path, "--outtype", "f16"
], check=True)
print(f"✅ FP16 GGUF: {f16_path}")
# Quantize to Q4_K_M
subprocess.run([
llama_quantize, f16_path, q4_path, "Q4_K_M"
], check=True)
print(f"✅ Q4_K_M GGUF: {q4_path}")
# Upload GGUF to HF
api.upload_file(
path_or_fileobj=q4_path,
path_in_repo="gguf/sakthai-7b-tools-Q4_K_M.gguf",
repo_id=MERGED_REPO,
repo_type="model",
commit_message="Add Q4_K_M GGUF quant for Ollama/llama.cpp",
)
print(f"✅ GGUF uploaded to HF")
REPORT["steps"]["gguf"] = {"status": "success", "path": q4_path}
else:
print("⚠️ convert_hf_to_gguf.py not found, skipping GGUF")
REPORT["steps"]["gguf"] = {"status": "skipped", "reason": "convert script not found"}
else:
print("⚠️ llama-quantize not found, skipping GGUF")
REPORT["steps"]["gguf"] = {"status": "skipped", "reason": "llama-quantize not found"}
# ═════════════════════════════════════════════════════════════
# Step 5: BFCL-Style Benchmark
# ═════════════════════════════════════════════════════════════
print("\n" + "="*60)
print("📊 Step 5: BFCL-Style Benchmark")
print("="*60)
BFCL_TESTS = [
# simple category
{"name": "simple/get_weather", "category": "simple",
"system": "You have access to get_weather(city: str) -> str. Use it when the user asks about weather.",
"prompt": "What's the weather in Paris?",
"expected_tool": "get_weather"},
{"name": "simple/search_web", "category": "simple",
"system": "You have access to search_web(query: str) -> list. Use it to answer questions needing current info.",
"prompt": "Search for latest news about AI",
"expected_tool": "search_web"},
# multiple (parallel)
{"name": "multiple/dual_weather", "category": "multiple",
"system": "You have access to get_weather(city: str) -> str. You can call multiple functions in parallel.",
"prompt": "Weather in Tokyo, London, and New York?",
"expects_parallel": True},
# irrelevance
{"name": "irrelevance/literature", "category": "irrelevance",
"system": "You have access to get_weather(city: str) -> str. Only call functions when the user asks for weather.",
"prompt": "Who wrote Romeo and Juliet?",
"expects_no_tool": True},
# simple_python
{"name": "simple_python/calculate", "category": "simple_python",
"system": "You have access to python_repl(code: str) -> str. Use it to run Python code for calculations.",
"prompt": "Calculate the factorial of 10",
"expected_tool": "python_repl"},
]
benchmark_results = []
for test in BFCL_TESTS:
print(f"\n{'─'*40}")
print(f"Testing: {test['name']}")
msgs = [
{"role": "system", "content": test["system"]},
{"role": "user", "content": test["prompt"]},
]
inputs = tokenizer.apply_chat_template(msgs, return_tensors="pt", add_generation_prompt=True)
inputs = inputs.to(merged_model.device if hasattr(merged_model, 'device') else "cpu")
with torch.no_grad():
outputs = merged_model.generate(
inputs,
max_new_tokens=256,
do_sample=False,
temperature=0.1,
pad_token_id=tokenizer.eos_token_id,
)
response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=False)
print(f"Response: {response[:200]}")
# Evaluate
result = {
"test": test["name"],
"category": test["category"],
"system": test["system"],
"prompt": test["prompt"],
"response_preview": response[:200],
}
# Check for expected tool
if test.get("expected_tool"):
result["expected_tool"] = test["expected_tool"]
result["detected_tool"] = test["expected_tool"] in response
result["passed"] = result["detected_tool"]
elif test.get("expects_no_tool"):
has_tool = any(t in response for t in ["get_weather(", "search_web(", "python_repl("])
result["expected_no_tool"] = True
result["detected_tool"] = not has_tool
result["passed"] = not has_tool
elif test.get("expects_parallel"):
# Check if multiple tool calls are present
count = response.count("get_weather(")
result["expected_parallel"] = True
result["detected_calls"] = count
result["passed"] = count >= 2
print(f"{'✅ PASS' if result['passed'] else '❌ FAIL'}")
benchmark_results.append(result)
REPORT["steps"]["benchmark"] = {
"status": "completed",
"results": benchmark_results,
}
passed = sum(1 for r in benchmark_results if r["passed"])
total = len(benchmark_results)
print(f"\n📊 Benchmark: {passed}/{total} passed")
# ═════════════════════════════════════════════════════════════
# Step 6: Save final report
# ═════════════════════════════════════════════════════════════
print("\n" + "="*60)
print("📄 Step 6: Saving final report")
print("="*60)
REPORT["end_time"] = str(datetime.datetime.now())
REPORT["summary"] = {
"merge_success": REPORT["steps"]["merge"]["status"] == "success",
"gguf_created": REPORT["steps"]["gguf"]["status"] == "success",
"benchmark_passed": f"{passed}/{total}",
}
report_path = f"{WORK_DIR}/final-report.json"
with open(report_path, "w") as f:
json.dump(REPORT, f, indent=2, default=str)
print(f"📄 Report: {report_path}")
# Push report
api.upload_file(
path_or_fileobj=report_path,
path_in_repo="results/final-report.json",
repo_id=MERGED_REPO,
repo_type="model",
commit_message="Final post-training report with merge + benchmark results",
)
try:
api.upload_file(
path_or_fileobj=report_path,
path_in_repo="results/post-train-report.json",
repo_id=ADAPTER_REPO,
repo_type="model",
commit_message="Post-training report",
)
except:
pass # Adapter repo might not accept it, that's fine
# ═════════════════════════════════════════════════════════════
# Summary
# ═════════════════════════════════════════════════════════════
print("\n" + "="*60)
print("📋 FINAL SUMMARY")
print("="*60)
print(f"Adapter: https://huggingface.co/{ADAPTER_REPO}")
print(f"Merged: https://huggingface.co/{MERGED_REPO}")
if REPORT["steps"]["gguf"]["status"] == "success":
print(f"GGUF: {MERGED_REPO}/gguf/sakthai-7b-tools-Q4_K_M.gguf")
print(f"Benchmark: {passed}/{total} tests passed")
print(f"\n✅ Pipeline complete!")
print("="*60)
# Print detailed benchmark
print(f"\n{'='*60}")
print("📊 DETAILED BENCHMARK RESULTS")
print(f"{'='*60}")
for r in benchmark_results:
icon = "✅" if r["passed"] else "❌"
print(f" {icon} {r['test']}")
print(f" {'='*50}")
print(f" Total: {passed}/{total} passed")