File size: 10,438 Bytes
e04e3dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9be658b
223a221
 
 
 
9be658b
 
 
 
223a221
 
e04e3dc
 
223a221
e04e3dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# /// script
# dependencies = ["trl>=0.12.0", "peft>=0.7.0", "transformers>=4.44", "datasets", "accelerate"]
# ///
"""SakThai 0.5B config-upgrade fine-tune on combined-v7, scored on sakthai-bench-v1.

Changes vs the 2026-07-29 run that died at step 60/252:
  * report_to="none" — trackio's config->parquet export cannot serialise PEFT's
    empty `rank_pattern` struct and killed that run at the first checkpoint push
    (pyarrow ArrowNotImplementedError). No logger is worth losing a 2h run.
  * save_strategy="no" + a single push after training — no mid-run hub pushes,
    so an upload hiccup can never destroy a nearly-finished run.
  * trains on combined-v7 minus every row reserved by sakthai-bench-v1 and every
    row that so much as *offers* a held-out tool.
  * eval reads the balanced bench (simple / parallel / irrelevance_tools /
    irrelevance_no_tools) and reports the unseen-tool slice separately.
"""
import re, json, gc, hashlib, collections, urllib.request
import torch
from datasets import load_dataset, concatenate_datasets
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import LoraConfig, get_peft_model, PeftModel
from trl import SFTTrainer, SFTConfig

USER, BASE_MODEL = "Nanthasit", "Qwen/Qwen2.5-0.5B-Instruct"
OLD_MERGED   = f"{USER}/sakthai-context-0.5b-merged"
ADAPTER_REPO = f"{USER}/sakthai-context-0.5b-tools-v2"
MERGED_REPO  = f"{USER}/sakthai-context-0.5b-merged-v2"
DATASET      = f"{USER}/sakthai-combined-v7"
BENCH        = f"{USER}/sakthai-bench-v1"
EXCLUDE_URL  = f"https://huggingface.co/datasets/{BENCH}/resolve/main/train_exclude_fingerprints.json"
MAX_LEN = 1536

tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

# ── Manual ChatML renderer. Qwen's built-in template cannot render this data:
#    content=None on tool turns, arguments as a JSON string, tool results
#    sometimes lists. Validated locally on real rows before every run. ──────
def _text(c):
    return "" if c is None else (c if isinstance(c, str) else json.dumps(c, ensure_ascii=False))
def _tools_block(tools):
    if not tools: return ""
    sigs = "\n".join(json.dumps(t, ensure_ascii=False) for t in tools)
    return ("\n\n# Tools\n\nYou may call one or more functions. Signatures are within "
            "<tools></tools>:\n<tools>\n" + sigs + "\n</tools>\n\nFor each call return:\n"
            "<tool_call>\n{\"name\": <name>, \"arguments\": <json>}\n</tool_call>")
def _assistant_body(m):
    body = _text(m.get("content"))
    for tc in (m.get("tool_calls") or []):
        fn = tc.get("function", tc); a = fn.get("arguments", "{}")
        if not isinstance(a, str): a = json.dumps(a, ensure_ascii=False)
        body += ("\n" if body else "") + '<tool_call>\n{"name": "%s", "arguments": %s}\n</tool_call>' % (fn.get("name", ""), a)
    return body
def _render_msg(m, tools_sys):
    r = m.get("role")
    if r == "system": return "<|im_start|>system\n" + _text(m.get("content")) + _tools_block(tools_sys) + "<|im_end|>\n"
    if r == "user":   return "<|im_start|>user\n" + _text(m.get("content")) + "<|im_end|>\n"
    if r == "tool":   return "<|im_start|>user\n<tool_response>\n" + _text(m.get("content")) + "\n</tool_response><|im_end|>\n"
    if r == "assistant": return "<|im_start|>assistant\n" + _assistant_body(m) + "<|im_end|>\n"
    return ""
def render_chatml(messages, tools, add_generation_prompt=False):
    messages = messages or []
    out = []
    if not (messages and messages[0].get("role") == "system") and tools:
        out.append("<|im_start|>system\nYou are a helpful assistant." + _tools_block(tools) + "<|im_end|>\n")
    for i, m in enumerate(messages):
        out.append(_render_msg(m, tools if (i == 0 and m.get("role") == "system") else None))
    if add_generation_prompt: out.append("<|im_start|>assistant\n")
    return "".join(out)

def fingerprint(messages):
    return hashlib.sha1(json.dumps(messages, sort_keys=True, ensure_ascii=False).encode()).hexdigest()

# ── Data: v7 minus everything the benchmark reserves ─────────────────────
with urllib.request.urlopen(EXCLUDE_URL) as r:
    _ex = json.load(r)
EXCLUDE = set(_ex["fingerprints"])
HELD_OUT_TOOLS = set(_ex["held_out_tools"])
print(f"bench reserves {len(EXCLUDE)} rows; held-out tools: {sorted(HELD_OUT_TOOLS)}")

def _keep(ex):
    if fingerprint(ex["messages"]) in EXCLUDE:
        return False
    names = {(t.get("function") or {}).get("name") or t.get("name") for t in (ex.get("tools") or [])}
    return not (names & HELD_OUT_TOOLS)

def to_text(ex): return {"text": render_chatml(ex["messages"], ex.get("tools") or None)}

main = load_dataset(DATASET, split="train")
print("v7 train rows:", len(main))
main = main.filter(_keep)
print("after bench exclusion:", len(main))
train_ds = main.map(to_text, remove_columns=main.column_names)
try:
    supp = load_dataset(f"{USER}/sakthai-irrelevance-supplement", split="train").filter(_keep)
    train_ds = concatenate_datasets([train_ds, supp.map(to_text, remove_columns=supp.column_names)])
except Exception as e:
    print("supplement skipped:", e)
train_ds = train_ds.filter(lambda e: bool(e["text"]) and len(e["text"]) > 20)
# Drop over-length rows rather than truncate them: a row cut at MAX_LEN can end
# mid-<tool_call>, which teaches the model to emit unterminated calls (~4% of v7).
_before = len(train_ds)
train_ds = train_ds.filter(lambda e: len(tokenizer(e["text"]).input_ids) <= MAX_LEN)
print(f"dropped {_before - len(train_ds)} rows longer than {MAX_LEN} tokens")
print("train examples:", len(train_ds))

# ── Train FIRST, push ONCE ───────────────────────────────────────────────
model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, torch_dtype=torch.bfloat16, device_map="cuda")
model.config.use_cache = False
model = get_peft_model(model, LoraConfig(
    r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", use_rslora=True,
    target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"]))
model.print_trainable_parameters()
# Tuned for a single H200 (141 GB): effective batch 64 (32 x 2) instead of 16.
# That is a 4x larger effective batch, so the LR is sqrt-scaled 2e-4 -> 4e-4 and
# warmup widened to 10% (the step count is small enough that 3% was ~3 steps).
# 3 epochs rather than 2 buys back optimizer steps (66 -> 99) that the big batch
# costs, and on this hardware the extra epoch is nearly free.
# Gradient checkpointing stays off (worth ~30% throughput), but the micro-batch is
# 32 not 64: at 64 with full activations this OOMs at ~140 GB. 32 peaks near 67 GB.
args = SFTConfig(output_dir="out-0.5b-v2", num_train_epochs=3, per_device_train_batch_size=32,
                 gradient_accumulation_steps=2, learning_rate=4e-4,
                 gradient_checkpointing=False,
                 lr_scheduler_type="cosine", warmup_ratio=0.1, logging_steps=5,
                 save_strategy="no", bf16=True, max_length=MAX_LEN, packing=False,
                 dataset_text_field="text", push_to_hub=False, report_to="none",
                 run_name="sakthai-0.5b-v2-mlp-rslora-v7-h200")
trainer = SFTTrainer(model=model, args=args, train_dataset=train_ds, processing_class=tokenizer)
trainer.train()

trainer.model.push_to_hub(ADAPTER_REPO); tokenizer.push_to_hub(ADAPTER_REPO)
print(f"pushed adapter -> {ADAPTER_REPO}")
del trainer, model; gc.collect(); torch.cuda.empty_cache()

base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, torch_dtype=torch.bfloat16, device_map="cuda")
merged = PeftModel.from_pretrained(base, ADAPTER_REPO).merge_and_unload()
merged.push_to_hub(MERGED_REPO); tokenizer.push_to_hub(MERGED_REPO)
del base, merged; gc.collect(); torch.cuda.empty_cache()
print(f"Trained + pushed: {ADAPTER_REPO} and {MERGED_REPO}")

# ── Eval on the balanced bench (non-fatal) ───────────────────────────────
_TC = re.compile(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", re.DOTALL)
TEST = load_dataset(BENCH, split="test")
CATS = ("simple", "parallel", "irrelevance_tools", "irrelevance_no_tools")

def _pred(t):
    o = []
    for mm in _TC.findall(t):
        try: o.append(json.loads(mm).get("name"))
        except Exception: pass
    return [n for n in o if n]

def eval_repo(repo_id, label):
    m = AutoModelForCausalLM.from_pretrained(repo_id, torch_dtype=torch.bfloat16, device_map="cuda"); m.eval()
    b = collections.defaultdict(lambda: [0, 0]); ho = [0, 0]
    for ex in TEST:
        msgs, tools, cat = ex["messages"], (ex.get("tools") or None), ex["category"]
        idx = next((i for i, mm in enumerate(msgs) if mm.get("role") == "assistant"), None)
        if idx is None: continue
        gold = ex["gold_tools"]
        prompt = render_chatml(msgs[:idx], tools, add_generation_prompt=True)
        ids = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).input_ids.to(m.device)
        with torch.no_grad():
            out = m.generate(ids, max_new_tokens=200, do_sample=False, pad_token_id=tokenizer.eos_token_id)
        pred = _pred(tokenizer.decode(out[0][ids.shape[1]:], skip_special_tokens=True))
        if cat.startswith("irrelevance"):
            ok = len(pred) == 0
        elif cat == "simple":
            ok = bool(gold) and gold[0] in pred
        else:
            ok = set(gold).issubset(set(pred))
        b[cat][0] += int(ok); b[cat][1] += 1
        if ex.get("held_out_tool"):
            ho[0] += int(ok); ho[1] += 1
    print(f"\n=== sakthai-bench-v1: {label} ({repo_id}) ===")
    print(f"{'category':<22}{'pass':>5}{'total':>6}{'acc':>8}")
    tc = tt = 0
    for c in CATS:
        p, t = b[c]; tc += p; tt += t
        print(f"{c:<22}{p:>5}{t:>6}{(f'{100*p/t:5.1f}%' if t else '  n/a'):>8}")
    print(f"{'OVERALL':<22}{tc:>5}{tt:>6}{(f'{100*tc/tt:5.1f}%' if tt else '  n/a'):>8}")
    print(f"{'(held-out tools)':<22}{ho[0]:>5}{ho[1]:>6}{(f'{100*ho[0]/ho[1]:5.1f}%' if ho[1] else '  n/a'):>8}")
    del m; gc.collect(); torch.cuda.empty_cache()

for repo, lbl in [(OLD_MERGED, "BEFORE"), (MERGED_REPO, "AFTER")]:
    try: eval_repo(repo, lbl)
    except Exception as e: print(f"[eval skipped for {repo}] {type(e).__name__}: {e}")
print("\nDone. Compare BEFORE / AFTER above.")