File size: 6,193 Bytes
17cb132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""day2_sft.py -- LoRA SFT on the bootstrap's verified pairs (Gate B/C).

Runs on the cloud pod (transformers + peft; no unsloth -- its wheels target
torch 2.4-2.6 and the pod runs torch 2.11). bf16 base + LoRA (no
bitsandbytes): a 4B base needs ~8GB, a 7B ~15GB -- both fit 24GB.

Usage (on the pod):
    python3 day2_sft.py --base Qwen/Qwen3-VL-4B-Instruct \
        --data bootstrap_output/sft_dataset.jsonl \
        --out adapters/gate_b_4b \
        --epochs 2 --lr 2e-4
    python3 day2_sft.py --merge --base <base> --adapter adapters/gate_b_4b \
        --out models/gate_b_4b_merged
Then benchmark with PI_OFFICE_NLG_MODEL=models/gate_b_4b_merged.
"""
import argparse
import json
import os
import time


def build_dataset(path: str, out_dir: str) -> tuple[str, str]:
    """Split messages-format pairs into train/valid jsonl."""
    os.makedirs(out_dir, exist_ok=True)
    rows = [json.loads(l) for l in open(path)]
    # deterministic 5% holdout (same seed as the check-split convention)
    valid_idx = set(
        i for i in range(len(rows)) if hash(f"gate-{i}") % 20 == 0)
    train_path = os.path.join(out_dir, "train.jsonl")
    valid_path = os.path.join(out_dir, "valid.jsonl")
    with open(train_path, "w") as tf, open(valid_path, "w") as vf:
        for i, row in enumerate(rows):
            line = json.dumps(row) + "\n"
            (vf if i in valid_idx else tf).write(line)
    print(f"dataset: {len(rows)} rows -> train {len(rows) - len(valid_idx)}, "
          f"valid {len(valid_idx)}")
    return train_path, valid_path


def train(args) -> int:
    import torch
    from datasets import load_dataset
    from peft import LoraConfig, get_peft_model
    from transformers import (AutoConfig, AutoTokenizer,
                              DataCollatorForSeq2Seq, Trainer,
                              TrainingArguments)

    train_path, valid_path = build_dataset(args.data, args.out)
    train_ds = load_dataset("json", data_files=train_path, split="train")
    valid_ds = load_dataset("json", data_files=valid_path, split="train")
    tokenizer = AutoTokenizer.from_pretrained(
        args.base, trust_remote_code=True)
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token

    def _template(messages):
        # VL models sometimes keep the chat template in the processor only
        try:
            return tokenizer.apply_chat_template(messages, tokenize=False,
                                                 add_generation_prompt=False)
        except AttributeError:
            from transformers import AutoProcessor
            proc = AutoProcessor.from_pretrained(
                args.base, trust_remote_code=True)
            return proc.apply_chat_template(messages, tokenize=False,
                                            add_generation_prompt=False)

    def tokenize(batch):
        texts = [_template(m) for m in batch["messages"]]
        enc = tokenizer(texts, truncation=True, max_length=1024,
                        padding=False)
        enc["labels"] = enc["input_ids"].copy()
        return enc

    train_ds = train_ds.map(tokenize, batched=True, remove_columns=["messages"])
    valid_ds = valid_ds.map(tokenize, batched=True, remove_columns=["messages"])

    cfg = AutoConfig.from_pretrained(args.base, trust_remote_code=True)
    cls = getattr(__import__("transformers"), cfg.architectures[0])
    model = cls.from_pretrained(
        args.base, dtype=torch.bfloat16, trust_remote_code=True)
    peft = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                      target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                                      "gate_proj", "up_proj", "down_proj"],
                      task_type="CAUSAL_LM")
    model = get_peft_model(model, peft)
    model.print_trainable_parameters()

    training_args = TrainingArguments(
        output_dir=args.out,
        per_device_train_batch_size=1,
        per_device_eval_batch_size=1,
        gradient_accumulation_steps=8,
        learning_rate=args.lr,
        num_train_epochs=args.epochs,
        logging_steps=50,
        save_strategy="epoch",
        eval_strategy="epoch",
        bf16=True,
        report_to=[],
        dataloader_num_workers=4,
        remove_unused_columns=False,
        seed=0,
    )
    trainer = Trainer(
        model=model,
        args=training_args,
        train_dataset=train_ds,
        eval_dataset=valid_ds,
        data_collator=DataCollatorForSeq2Seq(
            tokenizer, pad_to_multiple_of=8, padding=True),
    )
    started = time.time()
    trainer.train()
    trainer.save_model(args.out)
    print(f"training done in {time.time() - started:.0f}s -> {args.out}")
    return 0


def merge(args) -> int:
    import torch
    from peft import PeftModel
    from transformers import AutoConfig, AutoTokenizer

    os.makedirs(args.out, exist_ok=True)
    cfg = AutoConfig.from_pretrained(args.base, trust_remote_code=True)
    cls = getattr(__import__("transformers"), cfg.architectures[0])
    model = cls.from_pretrained(
        args.base, dtype=torch.bfloat16, trust_remote_code=True)
    model = PeftModel.from_pretrained(model, args.adapter)
    merged = model.merge_and_unload()
    merged.save_pretrained(args.out, safe_serialization=True)
    tokenizer = AutoTokenizer.from_pretrained(
        args.base, trust_remote_code=True)
    tokenizer.save_pretrained(args.out)
    print(f"merged -> {args.out}")
    return 0


def main() -> int:
    parser = argparse.ArgumentParser()
    sub = parser.add_subparsers(dest="mode", required=True)
    t = sub.add_parser("train")
    t.add_argument("--base", required=True)
    t.add_argument("--data", required=True)
    t.add_argument("--out", required=True)
    t.add_argument("--epochs", type=int, default=2)
    t.add_argument("--lr", type=float, default=2e-4)
    m = sub.add_parser("merge")
    m.add_argument("--base", required=True)
    m.add_argument("--adapter", required=True)
    m.add_argument("--out", required=True)
    args = parser.parse_args()
    if args.mode == "train":
        return train(args)
    return merge(args)


if __name__ == "__main__":
    import sys
    sys.exit(main())