# /// 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 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- 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. NOTE: no seed is safe — # seeds 20260729, 42, and 777 all eventually hit the schedule-deterministic # backward NaN (steps 42/113/62 respectively on the 3797-row set). The NanGuard # below is the actual protection; the seed only moves where the poison lands. 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 " ":\n\n" + sigs + "\n\n\nFor each call return:\n" "\n{\"name\": , \"arguments\": }\n") 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 "") + '\n{"name": "%s", "arguments": %s}\n' % (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\n" + _text(m.get("content")) + "\n<|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 NanGuard(SFTTrainer): """Survive the schedule-deterministic backward-pass NaN AND capture it. Forensics so far (2026-07-29): loss finite, grads NaN, at one deterministic step per (row set, trainer seed); identical across LoRA/full-FT, rank 16-64, lr 2e-5..4e-4, 3/6 epochs; batch content and physical rows fully unremarkable (index intersection of two fatal batches over the same data = empty). The mechanism only exists at tensor level, so: on the first non-finite gradient, dump the batch + an fp32 re-forward for diagnosis, then ZERO the gradients and skip this optimizer step — the model never sees the poison and training completes.""" _dumped = 0 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): NanGuard._dumped += 1 # SAFETY FIRST: neutralize before any diagnostic can crash. Zeroed # grads make the coming optimizer.step a no-op; the poison never # reaches the weights even if everything below throws. for p in model.parameters(): if p.grad is not None: p.grad.zero_() print(f"\n!!! non-finite {'grads' if grads_bad else 'loss'} #{NanGuard._dumped} " f"at global_step {self.state.global_step} epoch {self.state.epoch}") print(">>> gradients zeroed - this update is skipped, training continues") if NanGuard._dumped <= 2: # full dump only for the first two events try: unmasked = (labels != -100).sum(-1) 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), "id range:", ids.min().item(), ids.max().item()) print("unmasked label tokens per row:", unmasked.tolist()) bad_params = [n for n, p in model.named_parameters() if p.grad is not None and not torch.isfinite(p.grad).all()] print(f"non-finite grad params: 0 after zeroing; offenders were " f"{len(bad_params)} (grads already cleared)") with torch.no_grad(): outbf = model(input_ids=ids, attention_mask=inputs.get("attention_mask"), labels=labels) print("bf16 no-grad reforward loss:", None if outbf.loss is None else outbf.loss.item(), "logits nan:", torch.isnan(outbf.logits).any().item(), "inf:", torch.isinf(outbf.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[-300:])) except Exception as e: import traceback print("diagnostic dump failed (training continues):", type(e).__name__, e) traceback.print_exc() return torch.zeros_like(loss) return loss trainer = NanGuard(model=model, args=args, train_dataset=train_ds, processing_class=tokenizer) trainer.train() if NanGuard._dumped: print(f"\nNanGuard skipped {NanGuard._dumped} poisoned micro-batches; weights stayed clean.") 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")