File size: 12,485 Bytes
6da8440 1c08ed0 6da8440 aa35807 6da8440 aa35807 6da8440 aa35807 6da8440 aa35807 6da8440 b7d9871 6da8440 b7d9871 6da8440 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | """Fine-tune Gemma 4 into Bloxy with Unsloth (QLoRA).
Loss is computed only on what Bloxy should learn to write: assistant text and
tool calls. System/user turns and tool results are masked out.
Examples:
# free Kaggle/Colab test (T4 16 GB): small model, 60 steps
python scripts/train.py --model unsloth/gemma-4-E4B-it --max_steps 60 --max_len 2048
# real run on a RunPod A6000 48 GB
python scripts/train.py --model unsloth/gemma-4-12b-it --hub_model_id YOURNAME/Bloxy-12B-v1
Env: HF_TOKEN (write token) is needed for --hub_model_id and private datasets.
"""
from __future__ import annotations
import argparse
import gzip
import json
import math
import os
import random
import re
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TURN_MODEL = "<|turn>model\n"
EMPTY_THOUGHT = "<|channel>thought\n<channel|>"
TURN_END = "<turn|>"
TOOL_RESP_OPEN = "<|tool_response>"
TOOL_RESP_CLOSE = "<tool_response|>"
def parse_args():
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="unsloth/gemma-4-12b-it")
ap.add_argument("--data", default=str(ROOT / "out" / "train.jsonl.gz"),
help="local train.jsonl(.gz) or a HF dataset repo id holding train.jsonl.gz")
ap.add_argument("--val", default=None, help="local val.jsonl (default: next to --data)")
ap.add_argument("--max_len", type=int, default=4096)
ap.add_argument("--epochs", type=float, default=1.0)
ap.add_argument("--max_steps", type=int, default=-1)
ap.add_argument("--limit", type=int, default=0, help="use only N training examples")
ap.add_argument("--lr", type=float, default=1e-4)
ap.add_argument("--r", type=int, default=16)
ap.add_argument("--bs", type=int, default=2)
ap.add_argument("--ga", type=int, default=4)
ap.add_argument("--out", default=str(ROOT / "runs" / "bloxy"))
ap.add_argument("--hub_model_id", default=None, help="push LoRA checkpoints + final adapter here")
ap.add_argument("--save_steps", type=int, default=150)
ap.add_argument("--max_hours", type=float, default=0, help="stop cleanly after this many hours (budget guard)")
ap.add_argument("--resume", action="store_true", help="resume from the last checkpoint on the Hub/out dir")
ap.add_argument("--no_4bit", action="store_true")
return ap.parse_args()
# ---------------------------------------------------------------- data
def read_rows(path: str) -> list[dict]:
p = Path(path)
if not p.exists(): # treat as HF dataset repo
from huggingface_hub import hf_hub_download
p = Path(hf_hub_download(path, "train.jsonl.gz", repo_type="dataset"))
opener = gzip.open if str(p).endswith(".gz") else open
with opener(p, "rt", encoding="utf-8") as f:
return [json.loads(l) for l in f if l.strip()]
def find_val(args) -> list[dict]:
if args.val:
return read_rows(args.val)
p = Path(args.data)
cand = p.parent / "val.jsonl" if p.exists() else None
if cand and cand.exists():
return read_rows(str(cand))
if not p.exists():
try:
from huggingface_hub import hf_hub_download
return read_rows(hf_hub_download(args.data, "val.jsonl", repo_type="dataset"))
except Exception:
pass
return []
def render(tokenizer, rec: dict) -> str:
msgs = rec["messages"]
kwargs = {"tokenize": False, "add_generation_prompt": False}
if rec.get("tools"):
kwargs["tools"] = rec["tools"]
text = tokenizer.apply_chat_template(msgs, **kwargs)
# Inference with thinking off starts every model turn with an empty thought
# channel; train with the same prefix so formats match exactly.
return re.sub(re.escape(TURN_MODEL) + r"(?!<\|channel>)", TURN_MODEL + EMPTY_THOUGHT, text)
def train_spans(text: str) -> list[tuple[int, int]]:
"""Character spans the model is trained to produce."""
spans = []
for m in re.finditer(re.escape(TURN_MODEL), text):
start = m.end()
if text.startswith(EMPTY_THOUGHT, start):
start += len(EMPTY_THOUGHT)
end = text.find(TURN_END, start)
end = len(text) if end < 0 else end + len(TURN_END)
# cut out tool results (written by Studio, not by Bloxy), keep the opener token
pos = start
for t in re.finditer(re.escape(TOOL_RESP_OPEN), text[start:end]):
o = start + t.end()
c = text.find(TOOL_RESP_CLOSE, o)
c = end if c < 0 or c > end else c + len(TOOL_RESP_CLOSE)
if o > pos:
spans.append((pos, o))
pos = c
if end > pos:
spans.append((pos, end))
return spans
def tokenize_example(tok, text: str, max_len: int):
enc = tok(text, add_special_tokens=False, return_offsets_mapping=True)
ids, offs = enc["input_ids"], enc["offset_mapping"]
if len(ids) > max_len:
return None
spans = train_spans(text)
labels = []
si = 0
for (s, e), t in zip(offs, ids):
while si < len(spans) and s >= spans[si][1]:
si += 1
inside = si < len(spans) and spans[si][0] <= s < spans[si][1]
labels.append(t if inside else -100)
if sum(l != -100 for l in labels) < 4:
return None
return {"input_ids": ids, "attention_mask": [1] * len(ids), "labels": labels}
def build_dataset(tokenizer, tok, rows, max_len, desc):
from datasets import Dataset
out, dropped = [], 0
for r in rows:
try:
try:
text = render(tok, r)
except ValueError: # text tokenizer without a template: use the processor's
text = render(tokenizer, r)
ex = tokenize_example(tok, text, max_len)
except Exception as e: # malformed conversation for the template
ex = None
if dropped < 3:
print(f" skip ({desc}): {e!r}")
if ex is None:
dropped += 1
continue
out.append(ex)
n_tok = sum(len(x["input_ids"]) for x in out)
print(f"{desc}: {len(out)} examples, {n_tok:,} tokens, dropped {dropped} (too long / no target)")
return Dataset.from_list(out), n_tok
# ---------------------------------------------------------------- main
def main():
args = parse_args()
import torch
from unsloth import FastModel
from transformers import DataCollatorForSeq2Seq, Trainer, TrainerCallback, TrainingArguments
rows = read_rows(args.data)
random.Random(0).shuffle(rows)
if args.limit:
rows = rows[: args.limit]
val_rows = find_val(args)[:300]
print(f"loaded {len(rows)} train / {len(val_rows)} val rows")
model, tokenizer = FastModel.from_pretrained(
model_name=args.model,
max_seq_length=args.max_len,
load_in_4bit=not args.no_4bit,
full_finetuning=False,
)
# Use the chat template that ships with the Gemma 4 repo (the same one Ollama /
# llama.cpp will use). Unsloth's get_chat_template("gemma-4") rejects tool turns.
tok = getattr(tokenizer, "tokenizer", tokenizer) # processor -> text tokenizer
if tok.pad_token is None:
tok.pad_token = tok.eos_token
model = FastModel.get_peft_model(
model,
finetune_vision_layers=False,
finetune_language_layers=True,
finetune_attention_modules=True,
finetune_mlp_modules=True,
r=args.r,
lora_alpha=args.r,
lora_dropout=0,
bias="none",
random_state=3407,
use_gradient_checkpointing="unsloth",
)
train_ds, n_tok = build_dataset(tokenizer, tok, rows, args.max_len, "train")
val_ds, _ = build_dataset(tokenizer, tok, val_rows, args.max_len, "val") if val_rows else (None, 0)
# show one masked example so mistakes are visible in the log
ex = train_ds[0]
shown = "".join(tok.decode([t]) if l != -100 else "·" for t, l in zip(ex["input_ids"][:400], ex["labels"][:400]))
print("trained tokens shown, masked as '·':\n", shown[:1500])
steps_per_epoch = math.ceil(len(train_ds) / (args.bs * args.ga))
total_steps = args.max_steps if args.max_steps > 0 else int(steps_per_epoch * args.epochs)
print(f"{total_steps} optimizer steps, ~{n_tok * args.epochs / 1e6:.1f}M tokens")
bf16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported()
push = bool(args.hub_model_id)
import inspect
targ_kwargs = dict(
output_dir=args.out,
per_device_train_batch_size=args.bs,
per_device_eval_batch_size=args.bs,
gradient_accumulation_steps=args.ga,
num_train_epochs=args.epochs,
max_steps=args.max_steps,
learning_rate=args.lr,
lr_scheduler_type="cosine",
warmup_steps=max(1, int(total_steps * 0.03)),
weight_decay=0.01,
optim="adamw_8bit",
bf16=bf16,
fp16=not bf16,
logging_steps=10,
save_strategy="steps",
save_steps=args.save_steps,
save_total_limit=2,
eval_strategy="steps" if val_ds is not None else "no",
eval_steps=args.save_steps,
group_by_length=True,
report_to="none",
seed=3407,
push_to_hub=push,
hub_model_id=args.hub_model_id,
hub_strategy="checkpoint" if push else "every_save",
hub_private_repo=True,
remove_unused_columns=False,
)
accepted = set(inspect.signature(TrainingArguments.__init__).parameters)
if "eval_strategy" not in accepted and "evaluation_strategy" in accepted:
targ_kwargs["evaluation_strategy"] = targ_kwargs.pop("eval_strategy")
skipped = sorted(k for k in targ_kwargs if k not in accepted)
if skipped:
print(f"TrainingArguments: this transformers version has no {skipped}, skipping them")
targs = TrainingArguments(**{k: v for k, v in targ_kwargs.items() if k in accepted})
class Budget(TrainerCallback):
def __init__(self):
self.t0 = time.time()
def on_log(self, a, state, control, logs=None, **kw):
if state.global_step and state.global_step % 50 == 0:
el = time.time() - self.t0
eta = el / state.global_step * (state.max_steps - state.global_step)
print(f"[budget] step {state.global_step}/{state.max_steps} elapsed {el / 3600:.2f}h "
f"ETA {eta / 3600:.2f}h (~${(el + eta) / 3600 * 0.59:.2f} on an A6000)")
def on_step_end(self, a, state, control, **kw):
if args.max_hours and time.time() - self.t0 > args.max_hours * 3600:
print(f"[budget] max_hours={args.max_hours} reached, saving and stopping")
control.should_save = True
control.should_training_stop = True
trainer = Trainer(
model=model,
args=targs,
train_dataset=train_ds,
eval_dataset=val_ds,
data_collator=DataCollatorForSeq2Seq(tok, padding=True, label_pad_token_id=-100, pad_to_multiple_of=8),
callbacks=[Budget()],
)
resume = None
if args.resume:
last = sorted(Path(args.out).glob("checkpoint-*"), key=lambda p: int(p.name.split("-")[1]))
last = [p for p in last if (p / "trainer_state.json").exists()]
if last:
resume = str(last[-1])
elif push:
from huggingface_hub import snapshot_download
try:
d = snapshot_download(args.hub_model_id, allow_patterns=["last-checkpoint/*"])
ck = Path(d) / "last-checkpoint"
# only resume from a real checkpoint (first run: nothing there yet)
if (ck / "trainer_state.json").exists():
resume = str(ck)
else:
print("no checkpoint on the Hub yet, starting fresh")
except Exception as e:
print(f"no hub checkpoint to resume: {e!r}")
print(f"resume from: {resume}")
trainer.train(resume_from_checkpoint=resume)
final = Path(args.out) / "lora"
model.save_pretrained(str(final))
tokenizer.save_pretrained(str(final))
(final / "bloxy_train_args.json").write_text(json.dumps(vars(args), indent=2))
if push:
model.push_to_hub(args.hub_model_id, private=True)
tokenizer.push_to_hub(args.hub_model_id, private=True)
print(f"saved adapter to {final}" + (f" and https://huggingface.co/{args.hub_model_id}" if push else ""))
if __name__ == "__main__":
sys.exit(main())
|