Datasets:
Tasks:
Text Generation
Languages:
English
Size:
n<1K
Tags:
code
notebooks
training-scripts
dataset:Nanthasit/sakthai-kaggle-notebooks
license-mit
dataset-card
License:
Download job-0.5b-exp.py from Nanthasit/sakthai-kaggle-notebooks: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/datasets/Nanthasit/sakthai-kaggle-notebooks/resolve/main/job-0.5b-exp.py
- Command line
-
hf download hf://datasets/Nanthasit/sakthai-kaggle-notebooks/job-0.5b-exp.py
-
curl -L -o job-0.5b-exp.py https://huggingface.co/datasets/Nanthasit/sakthai-kaggle-notebooks/resolve/main/job-0.5b-exp.py
13.2 kB
| # /// 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 | |
| from collections import Counter | |
| import torch | |
| import torch.nn.functional as F | |
| 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)) | |
| DUP_CAP = int(os.environ.get("SAK_DUP_CAP", "0")) # 0 = off; N = keep at most N copies of an identical pair | |
| def cap_duplicates(pairs, cap): | |
| """Keep at most `cap` copies of each identical (prompt, completion) pair. | |
| cap <= 0 disables (returns the list unchanged).""" | |
| if cap <= 0: | |
| return list(pairs) | |
| seen, out = Counter(), [] | |
| for p in pairs: | |
| k = _key(p) | |
| if seen[k] < cap: | |
| out.append(p) | |
| seen[k] += 1 | |
| return out | |
| def _key(p): | |
| return (p["prompt"], p["completion"]) | |
| pairs = cap_duplicates(pairs, DUP_CAP) | |
| print(f"after SAK_DUP_CAP={DUP_CAP}: {len(pairs)} 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}") | |
| def zero_nonfinite_grads(model): | |
| """If ANY parameter gradient is non-finite, zero ALL gradients (making the | |
| next optimizer step a no-op) and return the offender count. Finite grads | |
| are left untouched and 0 is returned.""" | |
| bad = [n for n, p in model.named_parameters() | |
| if p.grad is not None and not torch.isfinite(p.grad).all()] | |
| if bad: | |
| for p in model.parameters(): | |
| if p.grad is not None: | |
| p.grad.zero_() | |
| return len(bad) | |
| def reforward_diagnostics(model, input_ids, attention_mask, labels): | |
| """No-grad reforward WITHOUT labels (fused linear+CE models return | |
| logits=None when labels are passed — the bug that killed the first two | |
| diagnostic runs). Manual shifted cross-entropy over unmasked labels.""" | |
| with torch.no_grad(): | |
| out = model(input_ids=input_ids, attention_mask=attention_mask) | |
| logits = out.logits | |
| result = { | |
| "logits_nan": bool(torch.isnan(logits).any()), | |
| "logits_inf": bool(torch.isinf(logits).any()), | |
| "loss": None, | |
| } | |
| shifted = logits[:, :-1].float() | |
| targets = labels[:, 1:] | |
| mask = targets != -100 | |
| if mask.any(): | |
| result["loss"] = float(F.cross_entropy(shifted[mask], targets[mask])) | |
| return result | |
| class NanGuard(SFTTrainer): | |
| _events = 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) | |
| n_bad = zero_nonfinite_grads(model) | |
| if n_bad or not torch.isfinite(loss): | |
| NanGuard._events += 1 | |
| print(f"\n!!! non-finite ({n_bad} grad params) event #{NanGuard._events} " | |
| f"at step {self.state.global_step} epoch {self.state.epoch}") | |
| print(">>> gradients zeroed - update skipped, training continues") | |
| if NanGuard._events <= 2: | |
| try: | |
| unmasked = (labels != -100).sum(-1) | |
| print("unmasked labels/row:", unmasked.tolist()) | |
| diag = reforward_diagnostics(model, ids, inputs.get("attention_mask"), labels) | |
| print("reforward:", diag) | |
| for k in range(ids.shape[0]): | |
| txt = tokenizer.decode(ids[k], skip_special_tokens=False).replace(tokenizer.pad_token, "") | |
| print(f"--- row {k} unmasked={unmasked[k].item()}: {repr(txt[-250:])}") | |
| except Exception as e: | |
| import traceback; print("diag failed (continuing):", 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._events: | |
| print(f"NanGuard skipped {NanGuard._events} 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") | |