File size: 12,037 Bytes
07ad4c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# /// script
# dependencies = ["trl>=1.9.0", "peft>=0.7.0", "transformers>=4.44", "datasets", "accelerate"]
# ///
"""SakThai 0.5B improvement experiments, scored on sakthai-bench-v1.

Two modes, selected by SAK_MODE, each changing ONE variable from the run before it
so the bench table attributes the difference to a single cause:

  lora-masked  LoRA (same config as the v7 baseline) + prompt masking.
               vs the baseline this isolates *masking*.
  full-masked  Full fine-tune of all 494M params + prompt masking.
               vs lora-masked this isolates *LoRA vs full fine-tune*.

Prompt masking: the baseline computes loss over the whole rendered string,
including a system prompt that carries the entire <tools> schema block — so much
of the gradient teaches the model to reproduce schemas rather than call them.
Here each assistant turn becomes its own prompt/completion pair and TRL's
completion_only_loss masks the prompt. This also roughly doubles the number of
supervised examples (2050 conversations -> ~3822 turns).

Adapters/models are pushed to *-exp-<mode> repos so the baseline v2 artifacts are
never overwritten by an experiment. This script does NOT evaluate: scoring is done
once, for all variants together, by eval_bench.py in the sakthai-bench-v1 repo, so
every number in a comparison comes from the same scorer.
"""
import os, json, gc, random, hashlib, urllib.request
import torch
from datasets import load_dataset, Dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import LoraConfig, get_peft_model
from trl import SFTTrainer, SFTConfig

MODE = os.environ.get("SAK_MODE", "lora-masked")
assert MODE in ("lora-masked", "full-masked"), MODE
SEED = int(os.environ.get("SAK_SEED", "20260729"))
# Trainer seed is SEPARATE from the data seed above. Conflating them is what broke
# every -v2 run: the 19:30 revision passed seed=SEED into SFTConfig, moving the
# trainer seed off its previous default of 42, and all four runs then hit NaN at
# epoch 0.756 — at 4e-4 AND at 2e-5, so the LR was never the cause. Keep 42 unless
# you are deliberately probing seed sensitivity, and change ONE of these at a time.
TRAINER_SEED = int(os.environ.get("SAK_TRAINER_SEED", "42"))
EPOCHS = int(os.environ.get("SAK_EPOCHS", "3"))
TAG = os.environ.get("SAK_TAG", "v2")
random.seed(SEED)

USER, BASE_MODEL = "Nanthasit", "Qwen/Qwen2.5-0.5B-Instruct"
OLD_MERGED = f"{USER}/sakthai-context-0.5b-merged"
OUT_REPO   = f"{USER}/sakthai-context-0.5b-exp-{MODE}-{TAG}"
DATASET    = f"{USER}/sakthai-combined-v7"
BENCH      = f"{USER}/sakthai-bench-v2"
EXCLUDE_URL = f"https://huggingface.co/datasets/{BENCH}/resolve/main/train_exclude_fingerprints.json"
MAX_LEN = int(os.environ.get("SAK_MAXLEN", "1536"))
MAX_TURNS_PER_CONV, PARALLEL_OVERSAMPLE = 4, 3
# Selection is ~90% but argument accuracy is 43.6% — that gap is now the target.
# Rank is the main capacity lever for memorising argument shapes; dropout and
# sequence length are the secondary ones (the latter because over-length pairs
# are dropped, and long prompts are where argument-heavy calls live).
RANK = int(os.environ.get("SAK_RANK", "16"))
DROPOUT = float(os.environ.get("SAK_DROPOUT", "0.05"))

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

# ── Manual ChatML renderer (Qwen's template cannot render this data) ──────
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: explode into prompt/completion pairs, one per assistant turn ────
with urllib.request.urlopen(EXCLUDE_URL) as r:
    _ex = json.load(r)
EXCLUDE, HELD_OUT_TOOLS = set(_ex["fingerprints"]), set(_ex["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)

raw = load_dataset(DATASET, split="train").filter(_keep)
print(f"conversations after bench exclusion: {len(raw)} | "
      f"rank={RANK} dropout={DROPOUT} max_len={MAX_LEN}")

pairs = []
for ex in raw:
    msgs, tools = ex["messages"], (ex.get("tools") or None)
    idxs = [i for i, m in enumerate(msgs) if m.get("role") == "assistant"]
    # Cap long conversations: 6% of them would otherwise contribute 20% of rows.
    if len(idxs) > MAX_TURNS_PER_CONV:
        idxs = sorted(random.sample(idxs, MAX_TURNS_PER_CONV))
    for i in idxs:
        completion = _assistant_body(msgs[i])
        if not completion.strip():
            continue
        gold = [(tc.get("function") or {}).get("name") for tc in (msgs[i].get("tool_calls") or [])]
        gold = [n for n in gold if n]
        pair = {
            "prompt": render_chatml(msgs[:i], tools, add_generation_prompt=True),
            "completion": completion + "<|im_end|>",
        }
        # Exploding to turn level collapses parallel calls to ~5% of turns (most
        # assistant turns in multi-turn chats are plain replies after a tool
        # result), while the bench is 30% parallel. Oversample so the training
        # mix is not itself the reason parallel scores move.
        pairs.extend([pair] * (PARALLEL_OVERSAMPLE if len(gold) > 1 else 1))
print("prompt/completion pairs:", len(pairs))

train_ds = Dataset.from_list(pairs)
_before = len(train_ds)
train_ds = train_ds.filter(
    lambda e: len(tokenizer(e["prompt"] + e["completion"]).input_ids) <= MAX_LEN)
print(f"dropped {_before - len(train_ds)} pairs over {MAX_LEN} tokens; training on {len(train_ds)}")

# ── Train ────────────────────────────────────────────────────────────────
model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, torch_dtype=torch.bfloat16, device_map="cuda")
model.config.use_cache = False
if MODE == "lora-masked":
    model = get_peft_model(model, LoraConfig(
        r=RANK, lora_alpha=2 * RANK, lora_dropout=DROPOUT, 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()
    # 4e-4 (sqrt-scaled for batch 64) is marginally unstable: it survives 3 epochs
    # but diverges to NaN by 6. Overridable so longer runs can drop it.
    lr = float(os.environ.get("SAK_LR", "4e-4"))
else:
    # Full fine-tune needs a far lower LR than LoRA; 4e-4 would destroy the base.
    lr = float(os.environ.get("SAK_LR", "2e-5"))
    print("full fine-tune: all", sum(p.numel() for p in model.parameters()), "params trainable")

args = SFTConfig(output_dir=f"out-{MODE}-{TAG}", num_train_epochs=EPOCHS, seed=TRAINER_SEED,
                 per_device_train_batch_size=32, gradient_accumulation_steps=2,
                 learning_rate=lr, gradient_checkpointing=False,
                 lr_scheduler_type="cosine", warmup_ratio=0.1, logging_steps=5,
                 save_strategy="no", bf16=True, max_length=MAX_LEN,
                 completion_only_loss=True,          # mask the prompt
                 push_to_hub=False, report_to="none", run_name=f"sakthai-0.5b-{MODE}-{TAG}")
class NanHunter(SFTTrainer):
    """Catch the first non-finite gradient in the act and dump the batch that
    caused it. v2/v3 runs died with loss still FINITE but grad_norm NaN, always
    at the same step for LoRA and full-FT under a given seed — so the trigger
    is in the backward pass of one deterministic batch. This aborts before the
    poisoned optimizer step, prints the complete batch, and re-runs the forward
    in fp32 to separate a bf16-precision blowup from a data/label mechanism."""
    def training_step(self, model, inputs, num_items_in_batch=None):
        ids, labels = inputs["input_ids"], inputs["labels"]
        loss = super().training_step(model, inputs, num_items_in_batch)
        grads_bad = any(p.grad is not None and not torch.isfinite(p.grad).all()
                        for p in model.parameters() if p.requires_grad)
        if grads_bad or not torch.isfinite(loss):
            unmasked = (labels != -100).sum(-1)
            print(f"\n!!! non-finite {'grads' if grads_bad else 'loss'} at global_step "
                  f"{self.state.global_step} epoch {self.state.epoch}")
            print("micro-batch loss:", loss.item() if hasattr(loss, 'item') else loss)
            print("num_items_in_batch:", num_items_in_batch)
            print("shape:", tuple(ids.shape), "input id range:", ids.min().item(), ids.max().item())
            print("unmasked label tokens per row:", unmasked.tolist())
            with torch.no_grad():
                out32 = model.float()(input_ids=ids,
                                      attention_mask=inputs.get("attention_mask"),
                                      labels=labels)
                print("fp32 reforward loss:", None if out32.loss is None else out32.loss.item())
                print("fp32 logits nan:", torch.isnan(out32.logits).any().item(),
                      "inf:", torch.isinf(out32.logits).any().item())
            for k in range(ids.shape[0]):
                txt = tokenizer.decode(ids[k], skip_special_tokens=False)
                txt = txt.replace(tokenizer.pad_token, "")
                print(f"--- row {k} unmasked={unmasked[k].item()} chars={len(txt)}")
                print("  tail:", repr(txt[-400:]))
            raise RuntimeError("NaN hunted - batch dumped above, aborting before weights are poisoned")
        return loss

trainer = NanHunter(model=model, args=args, train_dataset=train_ds, processing_class=tokenizer)
trainer.train()

if MODE == "lora-masked":
    merged = trainer.model.merge_and_unload()
else:
    merged = trainer.model
merged.push_to_hub(OUT_REPO); tokenizer.push_to_hub(OUT_REPO)
print(f"pushed -> {OUT_REPO}")

print(f"\nDone: {MODE}. Score it with eval_bench.py from the bench repo:")
print(f"  SAK_MODELS={OUT_REPO} -> Nanthasit/sakthai-bench-v1/eval_bench.py")