File size: 4,899 Bytes
8a2fc36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcd21d
8a2fc36
 
 
 
 
2bcd21d
 
8a2fc36
2bcd21d
8a2fc36
 
 
 
 
 
eb5e663
 
8a2fc36
 
 
 
2bcd21d
 
 
 
 
 
 
 
8a2fc36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcd21d
 
 
 
 
 
 
 
 
 
 
 
 
 
8a2fc36
2bcd21d
 
 
eb5e663
 
8a2fc36
2bcd21d
 
8a2fc36
eb5e663
8a2fc36
2bcd21d
 
 
8a2fc36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "transformers>=4.44",
#   "trl>=0.19,<0.20",
#   "peft>=0.7",
#   "datasets",
#   "accelerate",
#   "bitsandbytes>=0.43",
#   "huggingface_hub",
# ]
# ///
"""
SakThai 1.5B v2 — improved tool-calling fine-tune.
QLoRA + rsLoRA + all-linear targets + completion-only loss.
Trains on v11 (bench-aligned schemas) + irrelevance supplement.

Usage on HF Jobs:
  hf jobs uv run --flavor a10g-small --timeout 6h --secrets HF_TOKEN train-sakthai-1.5b-v2.py
"""
import os
import json
import urllib.request
import torch
from datasets import Dataset, concatenate_datasets
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from trl import SFTConfig, SFTTrainer

BASE_MODEL   = "Qwen/Qwen2.5-1.5B-Instruct"
HF_USER      = "Nanthasit"
ADAPTER_REPO = f"{HF_USER}/sakthai-plus-1.5b-lora"
MERGED_REPO  = f"{HF_USER}/sakthai-plus-1.5b"
MAX_SEQ_LEN  = 2048
HF_TOKEN     = os.environ.get("HF_TOKEN")
assert HF_TOKEN, "Set HF_TOKEN secret: --secrets HF_TOKEN"

def load_jsonl(url):
    with urllib.request.urlopen(url) as f:
        return [json.loads(l) for l in f.read().decode().strip().splitlines()]

def load_raw(repo, path="data/train.jsonl"):
    url = f"https://huggingface.co/datasets/{HF_USER}/{repo}/resolve/main/{path}"
    return load_jsonl(url)

bnb = BitsAndBytesConfig(
    load_in_4bit=True, bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True,
)

tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL, quantization_config=bnb, device_map="auto", torch_dtype=torch.bfloat16,
)
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
model.config.use_cache = False

lora_config = LoraConfig(
    r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                    "gate_proj", "up_proj", "down_proj"],
    use_rslora=True,
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()

def rows_to_text(rows):
    texts = []
    skipped = 0
    for row in rows:
        msgs = row["messages"]
        tools = row.get("tools") or None
        try:
            t = tokenizer.apply_chat_template(msgs, tools=tools, tokenize=False, add_generation_prompt=False)
            texts.append({"text": t})
        except Exception:
            skipped += 1
    if skipped:
        print(f"skipped {skipped} rows (template render failed)")
    return Dataset.from_list(texts)

# v11: bench-aligned schemas (canonical param names, bench-exact schemas)
main_rows = load_raw("sakthai-combined-v11")
train_data = rows_to_text(main_rows)

# irrelevance supplement
try:
    supp_rows = load_raw("sakthai-irrelevance-supplement")
    train_data = concatenate_datasets([train_data, rows_to_text(supp_rows)])
except Exception as e:
    print("irrelevance-supplement unavailable:", e)

# v7 test split for eval
eval_rows = load_raw("sakthai-combined-v7", "data/test.jsonl")
eval_data = rows_to_text(eval_rows)
print(f"train={len(train_data)}  eval={len(eval_data)}")

args = SFTConfig(
    output_dir="./sakthai-1.5b-lora",
    num_train_epochs=3,
    per_device_train_batch_size=2,
    per_device_eval_batch_size=1,
    eval_accumulation_steps=1,
    gradient_accumulation_steps=8,
    gradient_checkpointing=True,
    optim="adamw_8bit",
    learning_rate=2e-4, lr_scheduler_type="cosine", warmup_ratio=0.03,
    logging_steps=10, eval_strategy="steps", eval_steps=50,
    save_strategy="steps", save_steps=100, save_total_limit=2,
    load_best_model_at_end=True, metric_for_best_model="eval_loss",
    bf16=True, tf32=True, report_to="none",
    dataset_text_field="text",
    max_seq_length=MAX_SEQ_LEN,
    completion_only_loss=True,
    push_to_hub=True,
    hub_model_id=ADAPTER_REPO,
    hub_strategy="every_save",
)
trainer = SFTTrainer(
    model=model, processing_class=tokenizer, args=args,
    train_dataset=train_data, eval_dataset=eval_data,
)
trainer.train()
trainer.save_model("./sakthai-1.5b-lora-best")
tokenizer.save_pretrained("./sakthai-1.5b-lora-best")

from huggingface_hub import login
login(token=HF_TOKEN)
trainer.model.push_to_hub(ADAPTER_REPO)
tokenizer.push_to_hub(ADAPTER_REPO)

from peft import PeftModel
del model, trainer
torch.cuda.empty_cache()

base = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL, torch_dtype=torch.bfloat16, device_map="auto",
)
merged = PeftModel.from_pretrained(base, "./sakthai-1.5b-lora-best").merge_and_unload()
merged.push_to_hub(MERGED_REPO)
tokenizer.push_to_hub(MERGED_REPO)
print(f"Done. Adapter: {ADAPTER_REPO}  Merged: {MERGED_REPO}")