MOH749 commited on
Commit
2e97991
·
verified ·
1 Parent(s): 676fa68

Upload train_brain_unified.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train_brain_unified.py +172 -0
train_brain_unified.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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", "text")
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", "8"))
38
+ GRAD_ACCUM = int(os.environ.get("GRAD_ACCUM", "2"))
39
+ LR = float(os.environ.get("LR", "2e-4"))
40
+ MAXSEQ = int(os.environ.get("MAXSEQ", "1024"))
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
+ id2 = _id2label(raw)
92
+ out = []
93
+ for r in raw:
94
+ text = (r.get(TEXT_COL) or "").strip()
95
+ if not text:
96
+ continue
97
+ intent = id2.get(str(r[LABEL_COL]), str(r[LABEL_COL]).strip().lower())
98
+ out.append({"utterance": text, "target": {
99
+ "domain": "banking", "intent": intent, "needs_tool": True,
100
+ "language": LANG, "entities": {}, "confidence": 1.0}})
101
+ print(f"[data] banking rows={len(out)} from {tf.name}")
102
+ return out
103
+
104
+
105
+ def commerce_rows() -> list[dict]:
106
+ if not OOLEL_HF:
107
+ return []
108
+ from huggingface_hub import hf_hub_download
109
+ p = Path(hf_hub_download(repo_id=OOLEL_HF, filename=OOLEL_FILE, repo_type="dataset"))
110
+ rows = [json.loads(x) for x in p.read_text(encoding="utf-8").splitlines() if x.strip()]
111
+ print(f"[data] commerce rows={len(rows)} from {OOLEL_HF}/{OOLEL_FILE}")
112
+ return rows
113
+
114
+
115
+ def main() -> int:
116
+ from unsloth import FastLanguageModel # patches transformers/trl — import first
117
+ from datasets import Dataset
118
+ from trl import SFTConfig, SFTTrainer
119
+ import inspect as _ins
120
+
121
+ model, tok = FastLanguageModel.from_pretrained(
122
+ model_name=BASE, max_seq_length=MAXSEQ, dtype=None,
123
+ load_in_4bit=False, full_finetuning=False)
124
+ model = FastLanguageModel.get_peft_model(
125
+ model, r=LORA_R, lora_alpha=LORA_R, lora_dropout=0.0, bias="none",
126
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
127
+ "gate_proj", "up_proj", "down_proj"],
128
+ use_gradient_checkpointing="unsloth", random_state=7, max_seq_length=MAXSEQ)
129
+
130
+ rows = banking_rows() + commerce_rows()
131
+ random.Random(7).shuffle(rows)
132
+ if SMOKE > 0:
133
+ rows = rows[:SMOKE]
134
+
135
+ def to_text(r: dict) -> str:
136
+ tgt = json.dumps(r["target"], ensure_ascii=False)
137
+ msgs = [{"role": "system", "content": SYSTEM},
138
+ {"role": "user", "content": str(r["utterance"])},
139
+ {"role": "assistant", "content": tgt}]
140
+ try:
141
+ return tok.apply_chat_template(msgs, tokenize=False)
142
+ except Exception:
143
+ return tok.apply_chat_template(
144
+ [{"role": "user", "content": SYSTEM + "\n\n" + str(r["utterance"])},
145
+ {"role": "assistant", "content": tgt}], tokenize=False)
146
+
147
+ ds = Dataset.from_list([{"text": to_text(r)} for r in rows])
148
+ print(f"[brain] rows={len(ds)} base={BASE} "
149
+ f"({'smoke' if SMOKE else f'{EPOCHS} ep'}) -> {PUSH_REPO}")
150
+
151
+ cfg = dict(
152
+ per_device_train_batch_size=BATCH, gradient_accumulation_steps=GRAD_ACCUM,
153
+ warmup_ratio=0.05, learning_rate=LR, logging_steps=5, optim="adamw_8bit",
154
+ weight_decay=0.01, lr_scheduler_type="linear", seed=7, bf16=True,
155
+ output_dir="out", report_to=REPORT, run_name=RUN_NAME,
156
+ push_to_hub=True, hub_model_id=PUSH_REPO, hub_strategy="end", hub_private_repo=True)
157
+ cfg["max_steps" if SMOKE else "num_train_epochs"] = 30 if SMOKE else EPOCHS
158
+ f = set(_ins.signature(SFTConfig).parameters)
159
+ cfg["max_seq_length" if "max_seq_length" in f else "max_length"] = MAXSEQ
160
+ if "dataset_text_field" in f:
161
+ cfg["dataset_text_field"] = "text"
162
+
163
+ kw = {"model": model, "train_dataset": ds, "args": SFTConfig(**cfg)}
164
+ kw["processing_class" if "processing_class" in _ins.signature(SFTTrainer).parameters
165
+ else "tokenizer"] = tok
166
+ SFTTrainer(**kw).train()
167
+ print(f"[done] pushed -> {PUSH_REPO}")
168
+ return 0
169
+
170
+
171
+ if __name__ == "__main__":
172
+ raise SystemExit(main())