Datasets:
cleanup: training scripts live in deploy/, not the dataset repo
Browse files- train_brain_unified2.py +0 -180
train_brain_unified2.py
DELETED
|
@@ -1,180 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.10"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "unsloth", "trl>=0.12", "transformers>=4.57", "datasets>=3.0",
|
| 5 |
-
# "kagglehub", "pandas", "huggingface_hub>=0.25", "trackio",
|
| 6 |
-
# ]
|
| 7 |
-
# ///
|
| 8 |
-
"""One self-contained HF Job: WolBanking77 (Kaggle) -> YAATAL router schema
|
| 9 |
-
[+ oolel_v2 commerce from HF] -> Unsloth SFT on Granite-4.0-H 350M.
|
| 10 |
-
|
| 11 |
-
`hf jobs uv run <this-url>` runs it whole. Kaggle creds arrive as job SECRETS
|
| 12 |
-
(KAGGLE_USERNAME + KAGGLE_KEY via --secrets, never -e). Banking-only when OOLEL_HF is
|
| 13 |
-
unset — that's the cents-level smoke that proves Kaggle-fetch-from-a-job + the schema
|
| 14 |
-
mapping + Unsloth on the hybrid Granite, before we add commerce and go full.
|
| 15 |
-
|
| 16 |
-
Smoke: hf jobs uv run --flavor l4x1 --timeout 1h \
|
| 17 |
-
--secrets HF_TOKEN --secrets KAGGLE_USERNAME --secrets KAGGLE_KEY \
|
| 18 |
-
-e SMOKE=200 -e PUSH_REPO=MOH749/yaatal-brain-unsloth-smoke <url>
|
| 19 |
-
|
| 20 |
-
WolBanking77 is CC BY 4.0 (arXiv:2509.19271) — cite in the model card.
|
| 21 |
-
"""
|
| 22 |
-
import csv
|
| 23 |
-
import json
|
| 24 |
-
import os
|
| 25 |
-
import random
|
| 26 |
-
from pathlib import Path
|
| 27 |
-
|
| 28 |
-
BASE = os.environ.get("BASE", "unsloth/granite-4.0-h-350m")
|
| 29 |
-
PUSH_REPO = os.environ.get("PUSH_REPO", "MOH749/yaatal-tool-router-granite-350m-unsloth")
|
| 30 |
-
KAGGLE_SLUG = os.environ.get("KAGGLE_SLUG", "abdoukarimkandji/WolBanking77")
|
| 31 |
-
OOLEL_HF = os.environ.get("OOLEL_HF", "") # HF dataset id for commerce rows; empty = banking-only
|
| 32 |
-
OOLEL_FILE = os.environ.get("OOLEL_FILE", "train.jsonl")
|
| 33 |
-
TEXT_COL = os.environ.get("TEXT_COL", "input_wo") # WolBanking77 raw Wolof text column (their loader: input_wo)
|
| 34 |
-
LABEL_COL = os.environ.get("LABEL_COL", "label")
|
| 35 |
-
LANG = os.environ.get("LANG", "wo")
|
| 36 |
-
EPOCHS = float(os.environ.get("EPOCHS", "3"))
|
| 37 |
-
BATCH = int(os.environ.get("BATCH", "2")) # granite-4.0-h is MoE-hybrid; 8 OOMs the 22GB L4
|
| 38 |
-
GRAD_ACCUM = int(os.environ.get("GRAD_ACCUM", "8")) # effective batch ~16
|
| 39 |
-
LR = float(os.environ.get("LR", "2e-4"))
|
| 40 |
-
MAXSEQ = int(os.environ.get("MAXSEQ", "512")) # router utterances+JSON are short; 512 halves activation mem
|
| 41 |
-
LORA_R = int(os.environ.get("LORA_R", "16"))
|
| 42 |
-
SMOKE = int(os.environ.get("SMOKE", "0"))
|
| 43 |
-
REPORT = os.environ.get("REPORT", "trackio")
|
| 44 |
-
RUN_NAME = os.environ.get("RUN_NAME", f"brain-unified-{'smoke' if SMOKE else 'full'}")
|
| 45 |
-
|
| 46 |
-
SYSTEM = (
|
| 47 |
-
"You are YAATAL's on-device market-intent router. The user speaks Wolof, French, English, "
|
| 48 |
-
"or a mix. Output ONLY a JSON object with this exact shape: "
|
| 49 |
-
'{"domain": "...", "intent": "...", "needs_tool": true|false, "language": "...", '
|
| 50 |
-
'"entities": {"product": ..., "market": ..., "colors": [...], "price_constraint": ..., '
|
| 51 |
-
'"occasion": ..., "quantity": ..., "unit": ...}, "confidence": <0..1>}. '
|
| 52 |
-
'If the utterance is not a product search, output intent "none" with needs_tool false and '
|
| 53 |
-
"empty entities. Output JSON only — no prose, no markdown."
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def _read_table(path: Path) -> list[dict]:
|
| 58 |
-
if path.suffix in (".json", ".jsonl"):
|
| 59 |
-
txt = path.read_text(encoding="utf-8")
|
| 60 |
-
if path.suffix == ".jsonl":
|
| 61 |
-
return [json.loads(x) for x in txt.splitlines() if x.strip()]
|
| 62 |
-
d = json.loads(txt)
|
| 63 |
-
return d if isinstance(d, list) else d.get("data", [])
|
| 64 |
-
with path.open(encoding="utf-8", newline="") as f:
|
| 65 |
-
return list(csv.DictReader(f))
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def _find_split(root: Path, split: str) -> Path | None:
|
| 69 |
-
for pat in (f"*{split}*.csv", f"*{split}*.json", f"*{split}*.jsonl"):
|
| 70 |
-
hits = [h for h in sorted(root.rglob(pat)) if "audio" not in str(h).lower()]
|
| 71 |
-
if hits:
|
| 72 |
-
return hits[0]
|
| 73 |
-
return None
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
def _id2label(rows: list[dict]) -> dict[str, str]:
|
| 77 |
-
name_col = next((c for c in ("intent", "label_name", "category", "intent_name")
|
| 78 |
-
if rows and c in rows[0]), None)
|
| 79 |
-
if name_col:
|
| 80 |
-
return {str(r[LABEL_COL]): str(r[name_col]).strip().lower() for r in rows}
|
| 81 |
-
return {}
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
def banking_rows() -> list[dict]:
|
| 85 |
-
import kagglehub
|
| 86 |
-
root = Path(kagglehub.dataset_download(KAGGLE_SLUG))
|
| 87 |
-
tf = _find_split(root, "train")
|
| 88 |
-
if not tf:
|
| 89 |
-
raise SystemExit(f"No WolBanking77 train file under {root} (set TEXT_COL/paths).")
|
| 90 |
-
raw = _read_table(tf)
|
| 91 |
-
cols = list(raw[0].keys()) if raw else []
|
| 92 |
-
text_col = TEXT_COL if TEXT_COL in cols else next(
|
| 93 |
-
(c for c in ("input_wo", "text", "sentence", "wolof", "wo", "transcription", "utterance")
|
| 94 |
-
if c in cols), TEXT_COL)
|
| 95 |
-
label_col = LABEL_COL if LABEL_COL in cols else next(
|
| 96 |
-
(c for c in ("label", "intent", "category", "class") if c in cols), LABEL_COL)
|
| 97 |
-
print(f"[data] {tf.name} cols={cols} -> text={text_col} label={label_col}")
|
| 98 |
-
id2 = _id2label(raw)
|
| 99 |
-
out = []
|
| 100 |
-
for r in raw:
|
| 101 |
-
text = (r.get(text_col) or "").strip()
|
| 102 |
-
if not text:
|
| 103 |
-
continue
|
| 104 |
-
lab = r.get(label_col)
|
| 105 |
-
intent = id2.get(str(lab), str(lab).strip().lower())
|
| 106 |
-
out.append({"utterance": text, "target": {
|
| 107 |
-
"domain": "banking", "intent": intent, "needs_tool": True,
|
| 108 |
-
"language": LANG, "entities": {}, "confidence": 1.0}})
|
| 109 |
-
print(f"[data] banking rows={len(out)} from {tf.name}")
|
| 110 |
-
return out
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
def commerce_rows() -> list[dict]:
|
| 114 |
-
if not OOLEL_HF:
|
| 115 |
-
return []
|
| 116 |
-
from huggingface_hub import hf_hub_download
|
| 117 |
-
p = Path(hf_hub_download(repo_id=OOLEL_HF, filename=OOLEL_FILE, repo_type="dataset"))
|
| 118 |
-
rows = [json.loads(x) for x in p.read_text(encoding="utf-8").splitlines() if x.strip()]
|
| 119 |
-
print(f"[data] commerce rows={len(rows)} from {OOLEL_HF}/{OOLEL_FILE}")
|
| 120 |
-
return rows
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def main() -> int:
|
| 124 |
-
from unsloth import FastLanguageModel # patches transformers/trl — import first
|
| 125 |
-
from datasets import Dataset
|
| 126 |
-
from trl import SFTConfig, SFTTrainer
|
| 127 |
-
import inspect as _ins
|
| 128 |
-
|
| 129 |
-
model, tok = FastLanguageModel.from_pretrained(
|
| 130 |
-
model_name=BASE, max_seq_length=MAXSEQ, dtype=None,
|
| 131 |
-
load_in_4bit=False, full_finetuning=False)
|
| 132 |
-
model = FastLanguageModel.get_peft_model(
|
| 133 |
-
model, r=LORA_R, lora_alpha=LORA_R, lora_dropout=0.0, bias="none",
|
| 134 |
-
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
|
| 135 |
-
"gate_proj", "up_proj", "down_proj"],
|
| 136 |
-
use_gradient_checkpointing="unsloth", random_state=7, max_seq_length=MAXSEQ)
|
| 137 |
-
|
| 138 |
-
rows = banking_rows() + commerce_rows()
|
| 139 |
-
random.Random(7).shuffle(rows)
|
| 140 |
-
if SMOKE > 0:
|
| 141 |
-
rows = rows[:SMOKE]
|
| 142 |
-
|
| 143 |
-
def to_text(r: dict) -> str:
|
| 144 |
-
tgt = json.dumps(r["target"], ensure_ascii=False)
|
| 145 |
-
msgs = [{"role": "system", "content": SYSTEM},
|
| 146 |
-
{"role": "user", "content": str(r["utterance"])},
|
| 147 |
-
{"role": "assistant", "content": tgt}]
|
| 148 |
-
try:
|
| 149 |
-
return tok.apply_chat_template(msgs, tokenize=False)
|
| 150 |
-
except Exception:
|
| 151 |
-
return tok.apply_chat_template(
|
| 152 |
-
[{"role": "user", "content": SYSTEM + "\n\n" + str(r["utterance"])},
|
| 153 |
-
{"role": "assistant", "content": tgt}], tokenize=False)
|
| 154 |
-
|
| 155 |
-
ds = Dataset.from_list([{"text": to_text(r)} for r in rows])
|
| 156 |
-
print(f"[brain] rows={len(ds)} base={BASE} "
|
| 157 |
-
f"({'smoke' if SMOKE else f'{EPOCHS} ep'}) -> {PUSH_REPO}")
|
| 158 |
-
|
| 159 |
-
cfg = dict(
|
| 160 |
-
per_device_train_batch_size=BATCH, gradient_accumulation_steps=GRAD_ACCUM,
|
| 161 |
-
warmup_ratio=0.05, learning_rate=LR, logging_steps=5, optim="adamw_8bit",
|
| 162 |
-
weight_decay=0.01, lr_scheduler_type="linear", seed=7, bf16=True,
|
| 163 |
-
output_dir="out", report_to=REPORT, run_name=RUN_NAME,
|
| 164 |
-
push_to_hub=True, hub_model_id=PUSH_REPO, hub_strategy="end", hub_private_repo=True)
|
| 165 |
-
cfg["max_steps" if SMOKE else "num_train_epochs"] = 30 if SMOKE else EPOCHS
|
| 166 |
-
f = set(_ins.signature(SFTConfig).parameters)
|
| 167 |
-
cfg["max_seq_length" if "max_seq_length" in f else "max_length"] = MAXSEQ
|
| 168 |
-
if "dataset_text_field" in f:
|
| 169 |
-
cfg["dataset_text_field"] = "text"
|
| 170 |
-
|
| 171 |
-
kw = {"model": model, "train_dataset": ds, "args": SFTConfig(**cfg)}
|
| 172 |
-
kw["processing_class" if "processing_class" in _ins.signature(SFTTrainer).parameters
|
| 173 |
-
else "tokenizer"] = tok
|
| 174 |
-
SFTTrainer(**kw).train()
|
| 175 |
-
print(f"[done] pushed -> {PUSH_REPO}")
|
| 176 |
-
return 0
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
if __name__ == "__main__":
|
| 180 |
-
raise SystemExit(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|