Nanthasit commited on
Commit
e04e3dc
·
verified ·
1 Parent(s): fbf7ab7

Add job-0.5b-v7.py (v7 + bench-v1, trackio crash fixed) and its local validator

Browse files
Files changed (2) hide show
  1. job-0.5b-v7.py +181 -0
  2. validate.py +109 -0
job-0.5b-v7.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # dependencies = ["trl>=0.12.0", "peft>=0.7.0", "transformers>=4.44", "datasets", "accelerate"]
3
+ # ///
4
+ """SakThai 0.5B config-upgrade fine-tune on combined-v7, scored on sakthai-bench-v1.
5
+
6
+ Changes vs the 2026-07-29 run that died at step 60/252:
7
+ * report_to="none" — trackio's config->parquet export cannot serialise PEFT's
8
+ empty `rank_pattern` struct and killed that run at the first checkpoint push
9
+ (pyarrow ArrowNotImplementedError). No logger is worth losing a 2h run.
10
+ * save_strategy="no" + a single push after training — no mid-run hub pushes,
11
+ so an upload hiccup can never destroy a nearly-finished run.
12
+ * trains on combined-v7 minus every row reserved by sakthai-bench-v1 and every
13
+ row that so much as *offers* a held-out tool.
14
+ * eval reads the balanced bench (simple / parallel / irrelevance_tools /
15
+ irrelevance_no_tools) and reports the unseen-tool slice separately.
16
+ """
17
+ import re, json, gc, hashlib, collections, urllib.request
18
+ import torch
19
+ from datasets import load_dataset, concatenate_datasets
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer
21
+ from peft import LoraConfig, get_peft_model, PeftModel
22
+ from trl import SFTTrainer, SFTConfig
23
+
24
+ USER, BASE_MODEL = "Nanthasit", "Qwen/Qwen2.5-0.5B-Instruct"
25
+ OLD_MERGED = f"{USER}/sakthai-context-0.5b-merged"
26
+ ADAPTER_REPO = f"{USER}/sakthai-context-0.5b-tools-v2"
27
+ MERGED_REPO = f"{USER}/sakthai-context-0.5b-merged-v2"
28
+ DATASET = f"{USER}/sakthai-combined-v7"
29
+ BENCH = f"{USER}/sakthai-bench-v1"
30
+ EXCLUDE_URL = f"https://huggingface.co/datasets/{BENCH}/resolve/main/train_exclude_fingerprints.json"
31
+ MAX_LEN = 1536
32
+
33
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
34
+ if tokenizer.pad_token is None:
35
+ tokenizer.pad_token = tokenizer.eos_token
36
+
37
+ # ── Manual ChatML renderer. Qwen's built-in template cannot render this data:
38
+ # content=None on tool turns, arguments as a JSON string, tool results
39
+ # sometimes lists. Validated locally on real rows before every run. ──────
40
+ def _text(c):
41
+ return "" if c is None else (c if isinstance(c, str) else json.dumps(c, ensure_ascii=False))
42
+ def _tools_block(tools):
43
+ if not tools: return ""
44
+ sigs = "\n".join(json.dumps(t, ensure_ascii=False) for t in tools)
45
+ return ("\n\n# Tools\n\nYou may call one or more functions. Signatures are within "
46
+ "<tools></tools>:\n<tools>\n" + sigs + "\n</tools>\n\nFor each call return:\n"
47
+ "<tool_call>\n{\"name\": <name>, \"arguments\": <json>}\n</tool_call>")
48
+ def _assistant_body(m):
49
+ body = _text(m.get("content"))
50
+ for tc in (m.get("tool_calls") or []):
51
+ fn = tc.get("function", tc); a = fn.get("arguments", "{}")
52
+ if not isinstance(a, str): a = json.dumps(a, ensure_ascii=False)
53
+ body += ("\n" if body else "") + '<tool_call>\n{"name": "%s", "arguments": %s}\n</tool_call>' % (fn.get("name", ""), a)
54
+ return body
55
+ def _render_msg(m, tools_sys):
56
+ r = m.get("role")
57
+ if r == "system": return "<|im_start|>system\n" + _text(m.get("content")) + _tools_block(tools_sys) + "<|im_end|>\n"
58
+ if r == "user": return "<|im_start|>user\n" + _text(m.get("content")) + "<|im_end|>\n"
59
+ if r == "tool": return "<|im_start|>user\n<tool_response>\n" + _text(m.get("content")) + "\n</tool_response><|im_end|>\n"
60
+ if r == "assistant": return "<|im_start|>assistant\n" + _assistant_body(m) + "<|im_end|>\n"
61
+ return ""
62
+ def render_chatml(messages, tools, add_generation_prompt=False):
63
+ messages = messages or []
64
+ out = []
65
+ if not (messages and messages[0].get("role") == "system") and tools:
66
+ out.append("<|im_start|>system\nYou are a helpful assistant." + _tools_block(tools) + "<|im_end|>\n")
67
+ for i, m in enumerate(messages):
68
+ out.append(_render_msg(m, tools if (i == 0 and m.get("role") == "system") else None))
69
+ if add_generation_prompt: out.append("<|im_start|>assistant\n")
70
+ return "".join(out)
71
+
72
+ def fingerprint(messages):
73
+ return hashlib.sha1(json.dumps(messages, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
74
+
75
+ # ── Data: v7 minus everything the benchmark reserves ─────────────────────
76
+ with urllib.request.urlopen(EXCLUDE_URL) as r:
77
+ _ex = json.load(r)
78
+ EXCLUDE = set(_ex["fingerprints"])
79
+ HELD_OUT_TOOLS = set(_ex["held_out_tools"])
80
+ print(f"bench reserves {len(EXCLUDE)} rows; held-out tools: {sorted(HELD_OUT_TOOLS)}")
81
+
82
+ def _keep(ex):
83
+ if fingerprint(ex["messages"]) in EXCLUDE:
84
+ return False
85
+ names = {(t.get("function") or {}).get("name") or t.get("name") for t in (ex.get("tools") or [])}
86
+ return not (names & HELD_OUT_TOOLS)
87
+
88
+ def to_text(ex): return {"text": render_chatml(ex["messages"], ex.get("tools") or None)}
89
+
90
+ main = load_dataset(DATASET, split="train")
91
+ print("v7 train rows:", len(main))
92
+ main = main.filter(_keep)
93
+ print("after bench exclusion:", len(main))
94
+ train_ds = main.map(to_text, remove_columns=main.column_names)
95
+ try:
96
+ supp = load_dataset(f"{USER}/sakthai-irrelevance-supplement", split="train").filter(_keep)
97
+ train_ds = concatenate_datasets([train_ds, supp.map(to_text, remove_columns=supp.column_names)])
98
+ except Exception as e:
99
+ print("supplement skipped:", e)
100
+ train_ds = train_ds.filter(lambda e: bool(e["text"]) and len(e["text"]) > 20)
101
+ # Drop over-length rows rather than truncate them: a row cut at MAX_LEN can end
102
+ # mid-<tool_call>, which teaches the model to emit unterminated calls (~4% of v7).
103
+ _before = len(train_ds)
104
+ train_ds = train_ds.filter(lambda e: len(tokenizer(e["text"]).input_ids) <= MAX_LEN)
105
+ print(f"dropped {_before - len(train_ds)} rows longer than {MAX_LEN} tokens")
106
+ print("train examples:", len(train_ds))
107
+
108
+ # ── Train FIRST, push ONCE ───────────────────────────────────────────────
109
+ model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, torch_dtype=torch.bfloat16, device_map="cuda")
110
+ model.config.use_cache = False
111
+ model = get_peft_model(model, LoraConfig(
112
+ r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", use_rslora=True,
113
+ target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"]))
114
+ model.print_trainable_parameters()
115
+ args = SFTConfig(output_dir="out-0.5b-v2", num_train_epochs=2, per_device_train_batch_size=8,
116
+ gradient_accumulation_steps=2, learning_rate=2e-4,
117
+ lr_scheduler_type="cosine", warmup_ratio=0.03, logging_steps=10,
118
+ save_strategy="no", bf16=True, max_length=MAX_LEN, packing=False,
119
+ dataset_text_field="text", push_to_hub=False, report_to="none",
120
+ run_name="sakthai-0.5b-v2-mlp-rslora-v7")
121
+ trainer = SFTTrainer(model=model, args=args, train_dataset=train_ds, processing_class=tokenizer)
122
+ trainer.train()
123
+
124
+ trainer.model.push_to_hub(ADAPTER_REPO); tokenizer.push_to_hub(ADAPTER_REPO)
125
+ print(f"pushed adapter -> {ADAPTER_REPO}")
126
+ del trainer, model; gc.collect(); torch.cuda.empty_cache()
127
+
128
+ base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, torch_dtype=torch.bfloat16, device_map="cuda")
129
+ merged = PeftModel.from_pretrained(base, ADAPTER_REPO).merge_and_unload()
130
+ merged.push_to_hub(MERGED_REPO); tokenizer.push_to_hub(MERGED_REPO)
131
+ del base, merged; gc.collect(); torch.cuda.empty_cache()
132
+ print(f"Trained + pushed: {ADAPTER_REPO} and {MERGED_REPO}")
133
+
134
+ # ── Eval on the balanced bench (non-fatal) ───────────────────────────────
135
+ _TC = re.compile(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", re.DOTALL)
136
+ TEST = load_dataset(BENCH, split="test")
137
+ CATS = ("simple", "parallel", "irrelevance_tools", "irrelevance_no_tools")
138
+
139
+ def _pred(t):
140
+ o = []
141
+ for mm in _TC.findall(t):
142
+ try: o.append(json.loads(mm).get("name"))
143
+ except Exception: pass
144
+ return [n for n in o if n]
145
+
146
+ def eval_repo(repo_id, label):
147
+ m = AutoModelForCausalLM.from_pretrained(repo_id, torch_dtype=torch.bfloat16, device_map="cuda"); m.eval()
148
+ b = collections.defaultdict(lambda: [0, 0]); ho = [0, 0]
149
+ for ex in TEST:
150
+ msgs, tools, cat = ex["messages"], (ex.get("tools") or None), ex["category"]
151
+ idx = next((i for i, mm in enumerate(msgs) if mm.get("role") == "assistant"), None)
152
+ if idx is None: continue
153
+ gold = ex["gold_tools"]
154
+ prompt = render_chatml(msgs[:idx], tools, add_generation_prompt=True)
155
+ ids = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).input_ids.to(m.device)
156
+ with torch.no_grad():
157
+ out = m.generate(ids, max_new_tokens=200, do_sample=False, pad_token_id=tokenizer.eos_token_id)
158
+ pred = _pred(tokenizer.decode(out[0][ids.shape[1]:], skip_special_tokens=True))
159
+ if cat.startswith("irrelevance"):
160
+ ok = len(pred) == 0
161
+ elif cat == "simple":
162
+ ok = bool(gold) and gold[0] in pred
163
+ else:
164
+ ok = set(gold).issubset(set(pred))
165
+ b[cat][0] += int(ok); b[cat][1] += 1
166
+ if ex.get("held_out_tool"):
167
+ ho[0] += int(ok); ho[1] += 1
168
+ print(f"\n=== sakthai-bench-v1: {label} ({repo_id}) ===")
169
+ print(f"{'category':<22}{'pass':>5}{'total':>6}{'acc':>8}")
170
+ tc = tt = 0
171
+ for c in CATS:
172
+ p, t = b[c]; tc += p; tt += t
173
+ print(f"{c:<22}{p:>5}{t:>6}{(f'{100*p/t:5.1f}%' if t else ' n/a'):>8}")
174
+ print(f"{'OVERALL':<22}{tc:>5}{tt:>6}{(f'{100*tc/tt:5.1f}%' if tt else ' n/a'):>8}")
175
+ 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}")
176
+ del m; gc.collect(); torch.cuda.empty_cache()
177
+
178
+ for repo, lbl in [(OLD_MERGED, "BEFORE"), (MERGED_REPO, "AFTER")]:
179
+ try: eval_repo(repo, lbl)
180
+ except Exception as e: print(f"[eval skipped for {repo}] {type(e).__name__}: {e}")
181
+ print("\nDone. Compare BEFORE / AFTER above.")
validate.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate every non-GPU part of the job script against real rows, locally.
2
+
3
+ The meta-lesson from the earlier fast-fails: anything that isn't the GPU itself
4
+ gets proven here first. Checks:
5
+ 1. renderer runs on every v7 + bench row without raising, and emits sane ChatML
6
+ 2. the bench-exclusion filter reproduces the builder's arithmetic
7
+ 3. the eval scorer is an oracle-pass: gold output must score 100% in every
8
+ category, otherwise the metric is broken before the model ever runs
9
+ 4. token-length distribution vs MAX_LEN (silent truncation check)
10
+ """
11
+ import json, re, sys, collections, importlib.util, pathlib
12
+
13
+ # Lift the pure functions out of the job script verbatim — no torch, no training
14
+ # body — so what is validated here is exactly the code that will run on the GPU.
15
+ src = pathlib.Path("job-0.5b-v7.py").read_text()
16
+ start = src.index("def _text(c):")
17
+ end = src.index("# ── Data: v7 minus")
18
+ ns = {"json": json, "hashlib": __import__("hashlib")}
19
+ exec(compile(src[start:end], "job-pure", "exec"), ns)
20
+ render_chatml = ns["render_chatml"]
21
+ fingerprint = ns["fingerprint"]
22
+ _TC = re.compile(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", re.DOTALL)
23
+
24
+ def _pred(t):
25
+ o = []
26
+ for mm in _TC.findall(t):
27
+ try: o.append(json.loads(mm).get("name"))
28
+ except Exception: pass
29
+ return [n for n in o if n]
30
+
31
+ def load(p):
32
+ return [json.loads(l) for l in open(p) if l.strip()]
33
+
34
+ train = load("v7/data/train.jsonl")
35
+ bench = load("bench/test.jsonl")
36
+ excl = json.load(open("bench/train_exclude_fingerprints.json"))
37
+ EXCLUDE, HELD = set(excl["fingerprints"]), set(excl["held_out_tools"])
38
+ fail = 0
39
+
40
+ # ── 1. renderer ──────────────────────────────────────────────────────────
41
+ bad, empty = 0, 0
42
+ lens = []
43
+ for ds, name in ((train, "v7 train"), (bench, "bench")):
44
+ for i, ex in enumerate(ds):
45
+ try:
46
+ t = render_chatml(ex["messages"], ex.get("tools") or None)
47
+ except Exception as e:
48
+ bad += 1
49
+ if bad <= 3: print(f" RENDER FAIL {name}[{i}]: {type(e).__name__}: {e}")
50
+ continue
51
+ if not t or len(t) < 20:
52
+ empty += 1
53
+ lens.append(len(t))
54
+ if "<|im_start|>" not in t or "<|im_end|>" not in t:
55
+ bad += 1
56
+ print(f"1. renderer: {len(lens)} rows rendered, {bad} failures, {empty} suspiciously short")
57
+ fail += bad + empty
58
+
59
+ # ── 2. exclusion filter reproduces the builder ───────────────────────────
60
+ def keep(ex):
61
+ if fingerprint(ex["messages"]) in EXCLUDE:
62
+ return False
63
+ names = {(t.get("function") or {}).get("name") or t.get("name") for t in (ex.get("tools") or [])}
64
+ return not (names & HELD)
65
+
66
+ kept = [ex for ex in train if keep(ex)]
67
+ bench_fps = {r["fingerprint"] for r in bench}
68
+ leaked = sum(1 for ex in kept if fingerprint(ex["messages"]) in bench_fps)
69
+ tool_leak = sum(1 for ex in kept
70
+ if {(t.get("function") or {}).get("name") or t.get("name")
71
+ for t in (ex.get("tools") or [])} & HELD)
72
+ print(f"2. filter: {len(train)} -> {len(kept)} kept; bench rows leaked into train: {leaked}; "
73
+ f"held-out tool schemas visible: {tool_leak}")
74
+ fail += leaked + tool_leak
75
+
76
+ # ── 3. oracle pass on the eval scorer ────────────────────────────────────
77
+ buckets = collections.defaultdict(lambda: [0, 0])
78
+ for ex in bench:
79
+ msgs, cat, gold = ex["messages"], ex["category"], ex["gold_tools"]
80
+ idx = next((i for i, m in enumerate(msgs) if m.get("role") == "assistant"), None)
81
+ if idx is None:
82
+ continue
83
+ # the oracle emits exactly what the reference assistant turn contains
84
+ body = ns["_assistant_body"](msgs[idx])
85
+ pred = _pred(body)
86
+ if cat.startswith("irrelevance"):
87
+ ok = len(pred) == 0
88
+ elif cat == "simple":
89
+ ok = bool(gold) and gold[0] in pred
90
+ else:
91
+ ok = set(gold).issubset(set(pred))
92
+ buckets[cat][0] += int(ok); buckets[cat][1] += 1
93
+ print("3. oracle scorer (gold output must score 100%):")
94
+ for c in ("simple", "parallel", "irrelevance_tools", "irrelevance_no_tools"):
95
+ p, t = buckets[c]
96
+ flag = "" if p == t else " <-- BROKEN"
97
+ print(f" {c:<22}{p:>4}/{t:<4} {100*p/t if t else 0:5.1f}%{flag}")
98
+ fail += (t - p)
99
+
100
+ # ── 4. truncation ────────────────────────────────────────────────────────
101
+ # rough char->token ratio for Qwen on this data is ~3.4 chars/token
102
+ approx = sorted(l / 3.4 for l in lens)
103
+ over = sum(1 for a in approx if a > 1536)
104
+ p50, p95, p99 = (approx[int(len(approx) * q)] for q in (0.5, 0.95, 0.99))
105
+ print(f"4. length: ~p50={p50:.0f} p95={p95:.0f} p99={p99:.0f} tokens; "
106
+ f"{over} rows ({100*over/len(approx):.1f}%) exceed MAX_LEN=1536")
107
+
108
+ print("\nRESULT:", "PASS" if fail == 0 else f"FAIL ({fail} problems)")
109
+ sys.exit(1 if fail else 0)