File size: 7,728 Bytes
ee15e43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SFT для PP-He (instruct). Режимы: lora | partial | full.

Данные — шарды из sft_data.py: tokens.bin (uint16), labels.bin (int32, -100
на промпте). Loss считается только по ответам.
"""
from __future__ import annotations

import argparse
import json
import math
import os
import sys
import time

import numpy as np
import torch

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)


def pick_device(want: str):
    if want == "tpu":
        import torch_xla.core.xla_model as xm

        return xm.xla_device(), "bf16", True
    if torch.cuda.is_available():
        major = torch.cuda.get_device_capability(0)[0]
        return torch.device("cuda"), ("bf16" if major >= 8 else "fp16"), False
    return torch.device("cpu"), "fp32", False


class SFTData:
    def __init__(self, d: str, seq_len: int, seed: int = 1337):
        self.tokens = np.memmap(os.path.join(d, "tokens.bin"), dtype=np.uint16, mode="r")
        self.labels = np.memmap(os.path.join(d, "labels.bin"), dtype=np.int32, mode="r")
        self.meta = json.load(open(os.path.join(d, "meta.json"), encoding="utf-8"))
        self.seq_len = seq_len
        self.rng = np.random.default_rng(seed)

    def batch(self, n: int):
        L = self.seq_len
        max_start = len(self.tokens) - L - 1
        starts = self.rng.integers(0, max_start, size=n)
        x = np.stack([np.asarray(self.tokens[s:s + L], dtype=np.int64) for s in starts])
        y = np.stack([np.asarray(self.labels[s + 1:s + 1 + L], dtype=np.int64) for s in starts])
        return torch.from_numpy(x), torch.from_numpy(y)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", required=True)
    ap.add_argument("--token", default=os.environ.get("HF_TOKEN"))
    args = ap.parse_args()

    import yaml

    cfg = yaml.safe_load(open(args.config, encoding="utf-8"))
    root = cfg["root"]
    os.makedirs(root, exist_ok=True)
    device, dtype_name, is_tpu = pick_device(str(cfg["optim"].get("device", "auto")))
    amp = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[dtype_name]
    print(f"[sft] устройство {device}, dtype {dtype_name}, режим {cfg['train']['mode']}", flush=True)

    from transformers import AutoModelForCausalLM, AutoTokenizer

    base = cfg["model"]["base_dir"]
    tok = AutoTokenizer.from_pretrained(base, trust_remote_code=True, token=args.token)
    model = AutoModelForCausalLM.from_pretrained(
        base, trust_remote_code=True, torch_dtype=torch.float32, token=args.token
    ).to(device)
    total = sum(p.numel() for p in model.parameters())

    mode = str(cfg["train"]["mode"])
    if mode == "lora":
        from lora_ppai import attach

        attach(model, r=int(cfg["train"]["lora_r"]), alpha=int(cfg["train"]["lora_alpha"]))
    elif mode == "partial":
        for n, p in model.named_parameters():
            p.requires_grad = ("w13" not in n and "w2" not in n)
    train = sum(p.numel() for p in model.parameters() if p.requires_grad)
    print(f"[sft] всего {total/1e6:.1f}M, обучаемо {train/1e6:.2f}M", flush=True)

    data = SFTData(cfg["data"]["dir"], int(cfg["data"]["seq_len"]), int(cfg["seed"]))
    print(f"[sft] данных {data.meta['n_tokens']/1e6:.1f}M токенов, "
          f"ответов {data.meta['answer_tokens']/1e6:.1f}M", flush=True)

    params = [p for p in model.parameters() if p.requires_grad]
    opt = torch.optim.AdamW(params, lr=float(cfg["optim"]["lr"]),
                            betas=(float(cfg["optim"]["beta1"]), float(cfg["optim"]["beta2"])),
                            weight_decay=float(cfg["optim"]["weight_decay"]))
    scaler = torch.amp.GradScaler("cuda", enabled=(dtype_name == "fp16"))

    micro = int(cfg["optim"]["micro_batch"])
    accum = int(cfg["optim"]["grad_accum"])
    max_steps = int(cfg["train"]["max_steps"])
    warmup = int(cfg["optim"]["warmup_steps"])
    min_ratio = float(cfg["optim"]["min_lr_ratio"])
    lr0 = float(cfg["optim"]["lr"])

    def lr_at(s: int) -> float:
        if s < warmup:
            return lr0 * (s + 1) / max(warmup, 1)
        prog = min(1.0, (s - warmup) / max(1, max_steps - warmup))
        return lr0 * (min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * prog)))

    logs = os.path.join(root, "logs")
    os.makedirs(logs, exist_ok=True)
    mf = open(os.path.join(logs, "sft.csv"), "a", encoding="utf-8")
    if mf.tell() == 0:
        mf.write("step,loss,lr,elapsed_h\n")

    ckpt = os.path.join(root, "ckpt")
    os.makedirs(ckpt, exist_ok=True)
    last = os.path.join(ckpt, "sft_last.pt")
    start = 0
    if os.path.exists(last):
        blob = torch.load(last, map_location="cpu", weights_only=False)
        model.load_state_dict(blob["model"], strict=False)
        opt.load_state_dict(blob["optim"])
        start = int(blob["step"])
        print(f"[sft] резюм с шага {start}", flush=True)

    t0 = time.time()
    step = start
    for step in range(start, max_steps):
        lr = lr_at(step)
        for g in opt.param_groups:
            g["lr"] = lr
        opt.zero_grad(set_to_none=True)
        runv = 0.0
        for _ in range(accum):
            x, y = data.batch(micro)
            x = x.to(device)
            y = y.to(device)
            with torch.autocast("cuda", dtype=amp, enabled=(device.type == "cuda" and dtype_name != "fp32")):
                logits = model(input_ids=x, use_cache=False).logits
                loss = torch.nn.functional.cross_entropy(
                    logits.reshape(-1, logits.size(-1)).float(), y.reshape(-1), ignore_index=-100)
            if scaler.is_enabled():
                scaler.scale(loss / accum).backward()
            else:
                (loss / accum).backward()
            runv += float(loss.detach())
        if scaler.is_enabled():
            scaler.unscale_(opt)
            torch.nn.utils.clip_grad_norm_(params, float(cfg["optim"]["grad_clip"]))
            scaler.step(opt)
            scaler.update()
        else:
            torch.nn.utils.clip_grad_norm_(params, float(cfg["optim"]["grad_clip"]))
            opt.step()
        if is_tpu:
            import torch_xla.core.xla_model as xm

            xm.mark_step()

        if step % int(cfg["train"]["log_every"]) == 0:
            el = (time.time() - t0) / 3600
            mf.write(f"{step},{runv/accum:.5f},{lr:.2e},{el:.2f}\n")
            mf.flush()
            print(f"[sft] шаг {step:5d} | loss {runv/accum:.4f} | lr {lr:.2e} | {el:.2f} ч", flush=True)

        if (step + 1) % int(cfg["train"]["save_every"]) == 0:
            torch.save({"step": step + 1, "model": model.state_dict(), "optim": opt.state_dict()},
                       last + ".tmp")
            os.replace(last + ".tmp", last)
            print(f"[sft] чекпоинт {step+1}", flush=True)

        if (time.time() - t0) / 3600 >= float(cfg["train"]["max_hours"]):
            print("[sft] лимит времени", flush=True)
            break

    torch.save({"step": step + 1, "model": model.state_dict(), "optim": opt.state_dict()}, last)
    out = os.path.join(root, "export")
    os.makedirs(out, exist_ok=True)
    if mode == "lora":
        from lora_ppai import merge_and_save

        merge_and_save(model, out)
    else:
        model.save_pretrained(out, safe_serialization=True)
    tok.save_pretrained(out)
    for f in ("configuration_ppai.py", "modeling_ppai.py"):
        src = os.path.join(base, f)
        if os.path.exists(src):
            import shutil

            shutil.copy2(src, os.path.join(out, f))
    print(f"[sft] готово: {out}", flush=True)


if __name__ == "__main__":
    main()