File size: 7,090 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
"""Обучение PP-OSR-H (картинка → подпись). Работает на TPU, CUDA и CPU.

Запуск:
    python train_vl.py --config /kaggle/input/.../configs/osr-h.yaml
"""
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)

from vl_data import VLData  # noqa: E402


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


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"[vl] устройство {device}, dtype {dtype_name}", 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)
    n_par = sum(p.numel() for p in model.parameters())
    print(f"[vl] параметров {n_par/1e6:.2f}M", flush=True)

    data = VLData(cfg["data"]["dir"], seed=int(cfg["seed"]), max_len=int(cfg["data"]["max_len"]))
    print(f"[vl] данных: {data.meta['n_images']} картинок, {data.meta['n_captions']} подписей", flush=True)

    decay, no_decay = [], []
    for n, p in model.named_parameters():
        (decay if p.ndim >= 2 else no_decay).append(p)
    opt = torch.optim.AdamW([{"params": decay, "weight_decay": float(cfg["optim"]["weight_decay"])},
                             {"params": no_decay, "weight_decay": 0.0}],
                            lr=float(cfg["optim"]["lr"]),
                            betas=(float(cfg["optim"]["beta1"]), float(cfg["optim"]["beta2"])))
    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"])

    def lr_at(step: int) -> float:
        if step < warmup:
            return float(cfg["optim"]["lr"]) * (step + 1) / max(warmup, 1)
        prog = min(1.0, (step - warmup) / max(1, max_steps - warmup))
        return float(cfg["optim"]["lr"]) * (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)
    mfile = open(os.path.join(logs, "metrics.csv"), "a", encoding="utf-8")
    if mfile.tell() == 0:
        mfile.write("step,loss,lr,tok_s,elapsed_h\n")

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

    print(f"[vl] шагов {start} → {max_steps}, батч {micro}x{accum}", 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)
        run = 0.0
        for _ in range(accum):
            px, ids, labels = data.batch(micro)
            px = px.to(device)
            ids = ids.to(device)
            labels = labels.to(device)
            with torch.autocast("cuda", dtype=amp, enabled=(device.type == "cuda" and dtype_name != "fp32")):
                out = model(input_ids=ids, pixel_values=px, labels=labels)
                loss = out.loss
            if scaler.is_enabled():
                scaler.scale(loss / accum).backward()
            else:
                (loss / accum).backward()
            run += float(loss.detach())
        if scaler.is_enabled():
            scaler.unscale_(opt)
            torch.nn.utils.clip_grad_norm_(model.parameters(), float(cfg["optim"]["grad_clip"]))
            scaler.step(opt)
            scaler.update()
        else:
            torch.nn.utils.clip_grad_norm_(model.parameters(), 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
            loss_v = run / accum
            mfile.write(f"{step},{loss_v:.5f},{lr:.2e},{micro*accum/ max(time.time()-t0,1e-6):.0f},{el:.2f}\n")
            mfile.flush()
            print(f"[vl] шаг {step:6d} | loss {loss_v:.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"[vl] чекпоинт на шаге {step+1}", flush=True)
            repo = cfg["train"].get("hub_repo")
            if repo and args.token:
                try:
                    from huggingface_hub import HfApi

                    api = HfApi(token=args.token)
                    api.create_repo(repo, repo_type="model", private=True, exist_ok=True)
                    api.upload_file(path_or_fileobj=last, path_in_repo="ckpt/last.pt", repo_id=repo)
                    print(f"[vl] пуш на {repo}", flush=True)
                except Exception as exc:  # noqa: BLE001
                    print(f"[vl] пуш не удался: {str(exc)[:120]}", flush=True)

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

    torch.save({"step": step + 1, "model": model.state_dict(), "optim": opt.state_dict()}, last)
    out_dir = os.path.join(root, "export")
    os.makedirs(out_dir, exist_ok=True)
    model.save_pretrained(out_dir, safe_serialization=True)
    tok.save_pretrained(out_dir)
    print(f"[vl] готово, модель в {out_dir}", flush=True)


if __name__ == "__main__":
    main()