Nanthasit commited on
Commit
9668dbd
·
verified ·
1 Parent(s): cfd7fc7

Add post-training merge + benchmark script

Browse files
Files changed (1) hide show
  1. scripts/sakthai-7b-post-train.py +337 -0
scripts/sakthai-7b-post-train.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ SakThai 7B Post-Training Pipeline
4
+ =================================
5
+ Run AFTER Kaggle notebook finishes training.
6
+
7
+ Steps:
8
+ 1. Download LoRA adapter from HF
9
+ 2. Merge with base Qwen2.5-7B-Instruct
10
+ 3. Push merged safetensors to HF
11
+ 4. Quantize to GGUF Q4_K_M
12
+ 5. Run BFCL-style benchmark
13
+ 6. Generate final report
14
+
15
+ Usage:
16
+ # HF_TOKEN must be set or passed via env
17
+ python3 sakthai-7b-post-train.py
18
+
19
+ Requires:
20
+ pip install transformers peft accelerate torch huggingface_hub
21
+ # For GGUF quant: llama.cpp built with llama-quantize
22
+ """
23
+
24
+ import os
25
+ import json
26
+ import sys
27
+ import datetime
28
+ import torch
29
+ from huggingface_hub import login, HfApi, snapshot_download
30
+ from transformers import AutoModelForCausalLM, AutoTokenizer
31
+ from peft import PeftModel
32
+
33
+ # ─── Config ─────────────────────────────────────────────────
34
+ BASE_MODEL = "Qwen/Qwen2.5-7B-Instruct"
35
+ ADAPTER_REPO = "Nanthasit/sakthai-7b-lora-kaggle"
36
+ MERGED_REPO = "Nanthasit/sakthai-context-7b-tools"
37
+ HF_TOKEN = os.environ.get("HF_TOKEN")
38
+ WORK_DIR = "/opt/data/sakthai-7b-post"
39
+ os.makedirs(WORK_DIR, exist_ok=True)
40
+
41
+ REPORT = {
42
+ "pipeline": "sakthai-7b-post-train",
43
+ "start_time": str(datetime.datetime.now()),
44
+ "steps": {},
45
+ }
46
+
47
+ # ─── Auth ────────────────────────────────────────────────────
48
+ if HF_TOKEN:
49
+ login(token=HF_TOKEN, add_to_git_credential=True)
50
+ api = HfApi()
51
+ user = api.whoami()["name"]
52
+ print(f"✅ Authenticated as: {user}")
53
+ else:
54
+ print("❌ HF_TOKEN not set")
55
+ sys.exit(1)
56
+
57
+ device = "cuda" if torch.cuda.is_available() else "cpu"
58
+ print(f"Using device: {device}")
59
+
60
+ # ═════════════════════════════════════════════════════════════
61
+ # Step 1: Download adapter
62
+ # ═════════════════════════════════════════════════════════════
63
+ print("\n" + "="*60)
64
+ print("📥 Step 1: Downloading LoRA adapter")
65
+ print("="*60)
66
+ adapter_path = f"{WORK_DIR}/adapter"
67
+ snapshot_download(
68
+ repo_id=ADAPTER_REPO,
69
+ local_dir=adapter_path,
70
+ repo_type="model",
71
+ )
72
+ print(f"✅ Adapter downloaded to {adapter_path}")
73
+
74
+ # ═════════════════════════════════════════════════════════════
75
+ # Step 2: Merge with base model
76
+ # ═════════════════════════════════════════════════════════════
77
+ print("\n" + "="*60)
78
+ print("🔗 Step 2: Merging LoRA with base model")
79
+ print("="*60)
80
+ merge_path = f"{WORK_DIR}/merged"
81
+ os.makedirs(merge_path, exist_ok=True)
82
+
83
+ try:
84
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, trust_remote_code=True)
85
+
86
+ if device == "cuda":
87
+ base = AutoModelForCausalLM.from_pretrained(
88
+ BASE_MODEL, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True
89
+ )
90
+ merged = PeftModel.from_pretrained(base, adapter_path)
91
+ merged_model = merged.merge_and_unload()
92
+ else:
93
+ # CPU merge — slower but works
94
+ print("CPU merge — this will take a while for 7B...")
95
+ base = AutoModelForCausalLM.from_pretrained(
96
+ BASE_MODEL, torch_dtype=torch.float32, device_map="cpu", trust_remote_code=True
97
+ )
98
+ merged = PeftModel.from_pretrained(base, adapter_path)
99
+ merged_model = merged.merge_and_unload()
100
+
101
+ merged_model.save_pretrained(merge_path, safe_serialization=True)
102
+ tokenizer.save_pretrained(merge_path)
103
+ print(f"✅ Merged model saved to {merge_path}")
104
+ REPORT["steps"]["merge"] = {"status": "success", "path": merge_path}
105
+ except Exception as e:
106
+ print(f"❌ Merge failed: {e}")
107
+ REPORT["steps"]["merge"] = {"status": "failed", "error": str(e)}
108
+ sys.exit(1)
109
+
110
+ # ═════════════════════════════════════════════════════════════
111
+ # Step 3: Push merged model to HF
112
+ # ═════════════════════════════════════════════════════════════
113
+ print("\n" + "="*60)
114
+ print("☁️ Step 3: Pushing merged model to HF Hub")
115
+ print("="*60)
116
+ try:
117
+ api.create_repo(repo_id=MERGED_REPO, repo_type="model", exist_ok=True, private=False)
118
+ api.upload_folder(
119
+ folder_path=merge_path,
120
+ repo_id=MERGED_REPO,
121
+ path_in_repo=".",
122
+ commit_message="Merge Qwen2.5-7B-Instruct + sakthai-v5 LoRA",
123
+ )
124
+ url = f"https://huggingface.co/{MERGED_REPO}"
125
+ print(f"✅ Merged model pushed: {url}")
126
+ REPORT["steps"]["push_merged"] = {"status": "success", "url": url}
127
+ except Exception as e:
128
+ print(f"❌ Push failed: {e}")
129
+ REPORT["steps"]["push_merged"] = {"status": "failed", "error": str(e)}
130
+
131
+ # ═════════════════════════════════════════════════════════════
132
+ # Step 4: GGUF Quantization (if llama.cpp is available)
133
+ # ═════════════════════════════════════════════════════════════
134
+ print("\n" + "="*60)
135
+ print("🔧 Step 4: GGUF Quantization")
136
+ print("="*60)
137
+ quant_path = f"{WORK_DIR}/gguf"
138
+ os.makedirs(quant_path, exist_ok=True)
139
+
140
+ # Check if llama-quantize is available
141
+ import shutil
142
+ llama_quantize = shutil.which("llama-quantize")
143
+
144
+ if llama_quantize:
145
+ print(f"Found llama-quantize at: {llama_quantize}")
146
+ f16_path = f"{quant_path}/sakthai-7b-tools-f16.gguf"
147
+ q4_path = f"{quant_path}/sakthai-7b-tools-Q4_K_M.gguf"
148
+
149
+ # Convert to FP16 GGUF first
150
+ convert_script = shutil.which("convert_hf_to_gguf.py") or "/tmp/llama.cpp/convert_hf_to_gguf.py"
151
+ if os.path.exists(convert_script):
152
+ import subprocess
153
+ subprocess.run([
154
+ sys.executable, convert_script, merge_path,
155
+ "--outfile", f16_path, "--outtype", "f16"
156
+ ], check=True)
157
+ print(f"✅ FP16 GGUF: {f16_path}")
158
+
159
+ # Quantize to Q4_K_M
160
+ subprocess.run([
161
+ llama_quantize, f16_path, q4_path, "Q4_K_M"
162
+ ], check=True)
163
+ print(f"✅ Q4_K_M GGUF: {q4_path}")
164
+
165
+ # Upload GGUF to HF
166
+ api.upload_file(
167
+ path_or_fileobj=q4_path,
168
+ path_in_repo="gguf/sakthai-7b-tools-Q4_K_M.gguf",
169
+ repo_id=MERGED_REPO,
170
+ repo_type="model",
171
+ commit_message="Add Q4_K_M GGUF quant for Ollama/llama.cpp",
172
+ )
173
+ print(f"✅ GGUF uploaded to HF")
174
+ REPORT["steps"]["gguf"] = {"status": "success", "path": q4_path}
175
+ else:
176
+ print("⚠️ convert_hf_to_gguf.py not found, skipping GGUF")
177
+ REPORT["steps"]["gguf"] = {"status": "skipped", "reason": "convert script not found"}
178
+ else:
179
+ print("⚠️ llama-quantize not found, skipping GGUF")
180
+ REPORT["steps"]["gguf"] = {"status": "skipped", "reason": "llama-quantize not found"}
181
+
182
+ # ═════════════════════════════════════════════════════════════
183
+ # Step 5: BFCL-Style Benchmark
184
+ # ═════════════════════════════════════════════════════════════
185
+ print("\n" + "="*60)
186
+ print("📊 Step 5: BFCL-Style Benchmark")
187
+ print("="*60)
188
+
189
+ BFCL_TESTS = [
190
+ # simple category
191
+ {"name": "simple/get_weather", "category": "simple",
192
+ "system": "You have access to get_weather(city: str) -> str. Use it when the user asks about weather.",
193
+ "prompt": "What's the weather in Paris?",
194
+ "expected_tool": "get_weather"},
195
+ {"name": "simple/search_web", "category": "simple",
196
+ "system": "You have access to search_web(query: str) -> list. Use it to answer questions needing current info.",
197
+ "prompt": "Search for latest news about AI",
198
+ "expected_tool": "search_web"},
199
+ # multiple (parallel)
200
+ {"name": "multiple/dual_weather", "category": "multiple",
201
+ "system": "You have access to get_weather(city: str) -> str. You can call multiple functions in parallel.",
202
+ "prompt": "Weather in Tokyo, London, and New York?",
203
+ "expects_parallel": True},
204
+ # irrelevance
205
+ {"name": "irrelevance/literature", "category": "irrelevance",
206
+ "system": "You have access to get_weather(city: str) -> str. Only call functions when the user asks for weather.",
207
+ "prompt": "Who wrote Romeo and Juliet?",
208
+ "expects_no_tool": True},
209
+ # simple_python
210
+ {"name": "simple_python/calculate", "category": "simple_python",
211
+ "system": "You have access to python_repl(code: str) -> str. Use it to run Python code for calculations.",
212
+ "prompt": "Calculate the factorial of 10",
213
+ "expected_tool": "python_repl"},
214
+ ]
215
+
216
+ benchmark_results = []
217
+ for test in BFCL_TESTS:
218
+ print(f"\n{'─'*40}")
219
+ print(f"Testing: {test['name']}")
220
+
221
+ msgs = [
222
+ {"role": "system", "content": test["system"]},
223
+ {"role": "user", "content": test["prompt"]},
224
+ ]
225
+ inputs = tokenizer.apply_chat_template(msgs, return_tensors="pt", add_generation_prompt=True)
226
+ inputs = inputs.to(merged_model.device if hasattr(merged_model, 'device') else "cpu")
227
+
228
+ with torch.no_grad():
229
+ outputs = merged_model.generate(
230
+ inputs,
231
+ max_new_tokens=256,
232
+ do_sample=False,
233
+ temperature=0.1,
234
+ pad_token_id=tokenizer.eos_token_id,
235
+ )
236
+
237
+ response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=False)
238
+ print(f"Response: {response[:200]}")
239
+
240
+ # Evaluate
241
+ result = {
242
+ "test": test["name"],
243
+ "category": test["category"],
244
+ "system": test["system"],
245
+ "prompt": test["prompt"],
246
+ "response_preview": response[:200],
247
+ }
248
+
249
+ # Check for expected tool
250
+ if test.get("expected_tool"):
251
+ result["expected_tool"] = test["expected_tool"]
252
+ result["detected_tool"] = test["expected_tool"] in response
253
+ result["passed"] = result["detected_tool"]
254
+ elif test.get("expects_no_tool"):
255
+ has_tool = any(t in response for t in ["get_weather(", "search_web(", "python_repl("])
256
+ result["expected_no_tool"] = True
257
+ result["detected_tool"] = not has_tool
258
+ result["passed"] = not has_tool
259
+ elif test.get("expects_parallel"):
260
+ # Check if multiple tool calls are present
261
+ count = response.count("get_weather(")
262
+ result["expected_parallel"] = True
263
+ result["detected_calls"] = count
264
+ result["passed"] = count >= 2
265
+
266
+ print(f"{'✅ PASS' if result['passed'] else '❌ FAIL'}")
267
+ benchmark_results.append(result)
268
+
269
+ REPORT["steps"]["benchmark"] = {
270
+ "status": "completed",
271
+ "results": benchmark_results,
272
+ }
273
+ passed = sum(1 for r in benchmark_results if r["passed"])
274
+ total = len(benchmark_results)
275
+ print(f"\n📊 Benchmark: {passed}/{total} passed")
276
+
277
+ # ═════════════════════════════════════════════════════════════
278
+ # Step 6: Save final report
279
+ # ═════════════════════════════════════════════════════════════
280
+ print("\n" + "="*60)
281
+ print("📄 Step 6: Saving final report")
282
+ print("="*60)
283
+
284
+ REPORT["end_time"] = str(datetime.datetime.now())
285
+ REPORT["summary"] = {
286
+ "merge_success": REPORT["steps"]["merge"]["status"] == "success",
287
+ "gguf_created": REPORT["steps"]["gguf"]["status"] == "success",
288
+ "benchmark_passed": f"{passed}/{total}",
289
+ }
290
+
291
+ report_path = f"{WORK_DIR}/final-report.json"
292
+ with open(report_path, "w") as f:
293
+ json.dump(REPORT, f, indent=2, default=str)
294
+ print(f"📄 Report: {report_path}")
295
+
296
+ # Push report
297
+ api.upload_file(
298
+ path_or_fileobj=report_path,
299
+ path_in_repo="results/final-report.json",
300
+ repo_id=MERGED_REPO,
301
+ repo_type="model",
302
+ commit_message="Final post-training report with merge + benchmark results",
303
+ )
304
+ try:
305
+ api.upload_file(
306
+ path_or_fileobj=report_path,
307
+ path_in_repo="results/post-train-report.json",
308
+ repo_id=ADAPTER_REPO,
309
+ repo_type="model",
310
+ commit_message="Post-training report",
311
+ )
312
+ except:
313
+ pass # Adapter repo might not accept it, that's fine
314
+
315
+ # ═════════════════════════════════════════════════════════════
316
+ # Summary
317
+ # ═════════════════════════════════════════════════════════════
318
+ print("\n" + "="*60)
319
+ print("📋 FINAL SUMMARY")
320
+ print("="*60)
321
+ print(f"Adapter: https://huggingface.co/{ADAPTER_REPO}")
322
+ print(f"Merged: https://huggingface.co/{MERGED_REPO}")
323
+ if REPORT["steps"]["gguf"]["status"] == "success":
324
+ print(f"GGUF: {MERGED_REPO}/gguf/sakthai-7b-tools-Q4_K_M.gguf")
325
+ print(f"Benchmark: {passed}/{total} tests passed")
326
+ print(f"\n✅ Pipeline complete!")
327
+ print("="*60)
328
+
329
+ # Print detailed benchmark
330
+ print(f"\n{'='*60}")
331
+ print("📊 DETAILED BENCHMARK RESULTS")
332
+ print(f"{'='*60}")
333
+ for r in benchmark_results:
334
+ icon = "✅" if r["passed"] else "❌"
335
+ print(f" {icon} {r['test']}")
336
+ print(f" {'='*50}")
337
+ print(f" Total: {passed}/{total} passed")