MOH749 commited on
Commit
800deeb
·
verified ·
1 Parent(s): c0648c6

Upload train_brain_unified4.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train_brain_unified4.py +190 -0
train_brain_unified4.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ MAX_STEPS = int(os.environ.get("MAX_STEPS", "0")) # >0 caps steps (the original router trained ~60 steps)
44
+ GRAD_CKPT = os.environ.get("GRAD_CKPT", "1") not in ("0", "false", "False") # off = faster on a big GPU
45
+ REPORT = os.environ.get("REPORT", "trackio")
46
+ RUN_NAME = os.environ.get("RUN_NAME", f"brain-unified-{'smoke' if SMOKE else 'full'}")
47
+
48
+ SYSTEM = (
49
+ "You are YAATAL's on-device market-intent router. The user speaks Wolof, French, English, "
50
+ "or a mix. Output ONLY a JSON object with this exact shape: "
51
+ '{"domain": "...", "intent": "...", "needs_tool": true|false, "language": "...", '
52
+ '"entities": {"product": ..., "market": ..., "colors": [...], "price_constraint": ..., '
53
+ '"occasion": ..., "quantity": ..., "unit": ...}, "confidence": <0..1>}. '
54
+ 'If the utterance is not a product search, output intent "none" with needs_tool false and '
55
+ "empty entities. Output JSON only — no prose, no markdown."
56
+ )
57
+
58
+
59
+ def _read_table(path: Path) -> list[dict]:
60
+ if path.suffix in (".json", ".jsonl"):
61
+ txt = path.read_text(encoding="utf-8")
62
+ if path.suffix == ".jsonl":
63
+ return [json.loads(x) for x in txt.splitlines() if x.strip()]
64
+ d = json.loads(txt)
65
+ return d if isinstance(d, list) else d.get("data", [])
66
+ with path.open(encoding="utf-8", newline="") as f:
67
+ return list(csv.DictReader(f))
68
+
69
+
70
+ def _find_split(root: Path, split: str) -> Path | None:
71
+ for pat in (f"*{split}*.csv", f"*{split}*.json", f"*{split}*.jsonl"):
72
+ hits = [h for h in sorted(root.rglob(pat)) if "audio" not in str(h).lower()]
73
+ if hits:
74
+ return hits[0]
75
+ return None
76
+
77
+
78
+ def _id2label(rows: list[dict]) -> dict[str, str]:
79
+ name_col = next((c for c in ("intent", "label_name", "category", "intent_name")
80
+ if rows and c in rows[0]), None)
81
+ if name_col:
82
+ return {str(r[LABEL_COL]): str(r[name_col]).strip().lower() for r in rows}
83
+ return {}
84
+
85
+
86
+ def banking_rows() -> list[dict]:
87
+ import kagglehub
88
+ root = Path(kagglehub.dataset_download(KAGGLE_SLUG))
89
+ tf = _find_split(root, "train")
90
+ if not tf:
91
+ raise SystemExit(f"No WolBanking77 train file under {root} (set TEXT_COL/paths).")
92
+ raw = _read_table(tf)
93
+ cols = list(raw[0].keys()) if raw else []
94
+ text_col = TEXT_COL if TEXT_COL in cols else next(
95
+ (c for c in ("input_wo", "text", "sentence", "wolof", "wo", "transcription", "utterance")
96
+ if c in cols), TEXT_COL)
97
+ label_col = LABEL_COL if LABEL_COL in cols else next(
98
+ (c for c in ("label", "intent", "category", "class") if c in cols), LABEL_COL)
99
+ print(f"[data] {tf.name} cols={cols} -> text={text_col} label={label_col}")
100
+ id2 = _id2label(raw)
101
+ out = []
102
+ for r in raw:
103
+ text = (r.get(text_col) or "").strip()
104
+ if not text:
105
+ continue
106
+ lab = r.get(label_col)
107
+ intent = id2.get(str(lab), str(lab).strip().lower())
108
+ out.append({"utterance": text, "target": {
109
+ "domain": "banking", "intent": intent, "needs_tool": True,
110
+ "language": LANG, "entities": {}, "confidence": 1.0}})
111
+ print(f"[data] banking rows={len(out)} from {tf.name}")
112
+ return out
113
+
114
+
115
+ def commerce_rows() -> list[dict]:
116
+ if not OOLEL_HF:
117
+ return []
118
+ from huggingface_hub import hf_hub_download
119
+ p = Path(hf_hub_download(repo_id=OOLEL_HF, filename=OOLEL_FILE, repo_type="dataset"))
120
+ rows = [json.loads(x) for x in p.read_text(encoding="utf-8").splitlines() if x.strip()]
121
+ print(f"[data] commerce rows={len(rows)} from {OOLEL_HF}/{OOLEL_FILE}")
122
+ return rows
123
+
124
+
125
+ def main() -> int:
126
+ from unsloth import FastLanguageModel # patches transformers/trl — import first
127
+ from datasets import Dataset
128
+ from trl import SFTConfig, SFTTrainer
129
+ import inspect as _ins
130
+
131
+ model, tok = FastLanguageModel.from_pretrained(
132
+ model_name=BASE, max_seq_length=MAXSEQ, dtype=None,
133
+ load_in_4bit=False, full_finetuning=False)
134
+ model = FastLanguageModel.get_peft_model(
135
+ model, r=LORA_R, lora_alpha=LORA_R, lora_dropout=0.0, bias="none",
136
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
137
+ "gate_proj", "up_proj", "down_proj"],
138
+ use_gradient_checkpointing=("unsloth" if GRAD_CKPT else False), random_state=7, max_seq_length=MAXSEQ)
139
+
140
+ rows = banking_rows() + commerce_rows()
141
+ random.Random(7).shuffle(rows)
142
+ if SMOKE > 0:
143
+ rows = rows[:SMOKE]
144
+
145
+ def to_text(r: dict) -> str:
146
+ tgt = json.dumps(r["target"], ensure_ascii=False)
147
+ msgs = [{"role": "system", "content": SYSTEM},
148
+ {"role": "user", "content": str(r["utterance"])},
149
+ {"role": "assistant", "content": tgt}]
150
+ try:
151
+ return tok.apply_chat_template(msgs, tokenize=False)
152
+ except Exception:
153
+ return tok.apply_chat_template(
154
+ [{"role": "user", "content": SYSTEM + "\n\n" + str(r["utterance"])},
155
+ {"role": "assistant", "content": tgt}], tokenize=False)
156
+
157
+ ds = Dataset.from_list([{"text": to_text(r)} for r in rows])
158
+ print(f"[brain] rows={len(ds)} base={BASE} "
159
+ f"({'smoke' if SMOKE else f'{EPOCHS} ep'}) -> {PUSH_REPO}")
160
+
161
+ cfg = dict(
162
+ per_device_train_batch_size=BATCH, gradient_accumulation_steps=GRAD_ACCUM,
163
+ warmup_ratio=0.05, learning_rate=LR, logging_steps=5, optim="adamw_8bit",
164
+ weight_decay=0.01, lr_scheduler_type="linear", seed=7, bf16=True,
165
+ output_dir="out", report_to=REPORT, run_name=RUN_NAME,
166
+ push_to_hub=True, hub_model_id=PUSH_REPO, hub_strategy="end", hub_private_repo=True)
167
+ if SMOKE:
168
+ cfg["max_steps"] = 30
169
+ elif MAX_STEPS > 0:
170
+ cfg["max_steps"] = MAX_STEPS
171
+ else:
172
+ cfg["num_train_epochs"] = EPOCHS
173
+ f = set(_ins.signature(SFTConfig).parameters)
174
+ cfg["max_seq_length" if "max_seq_length" in f else "max_length"] = MAXSEQ
175
+ if "dataset_text_field" in f:
176
+ cfg["dataset_text_field"] = "text"
177
+
178
+ kw = {"model": model, "train_dataset": ds, "args": SFTConfig(**cfg)}
179
+ kw["processing_class" if "processing_class" in _ins.signature(SFTTrainer).parameters
180
+ else "tokenizer"] = tok
181
+ trainer = SFTTrainer(**kw)
182
+ trainer.train()
183
+ model.push_to_hub(PUSH_REPO, private=True) # explicit: hub_strategy="end" did NOT push the Unsloth adapter
184
+ tok.push_to_hub(PUSH_REPO, private=True)
185
+ print(f"[done] pushed -> {PUSH_REPO}")
186
+ return 0
187
+
188
+
189
+ if __name__ == "__main__":
190
+ raise SystemExit(main())