File size: 21,216 Bytes
44dc92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
"""Цикл обучения: continued pretraining для Aurora2.

Особенности под Kaggle:
  * мягкий стоп по времени (max_hours) — успеть сохраниться до обрыва сессии;
  * чекпоинт каждые save_every шагов + авторезюм (локально или с HF Hub);
  * периодический пуш на Hub, чтобы прогресс пережил смерть сессии;
  * fp16 + GradScaler на T4 (bf16 там не аппаратный), bf16 на Ampere+.
"""
from __future__ import annotations

import contextlib
import csv
import json
import math
import os
import time
from typing import Any

import numpy as np
import torch

from . import data as data_mod
from . import model as model_mod
from .config import config_snapshot, paths


# ------------------------------------------------------------------ утилиты ---


def set_seed(seed: int) -> None:
    import random

    random.seed(seed)
    np.random.seed(seed % (2**32))
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)


def pick_dtype(cfg: dict, device: torch.device) -> str:
    want = cfg["optim"]["dtype"]
    if want != "auto":
        return want
    if device.type != "cuda":
        return "fp32"
    # на T4 (sm_75) bf16 только эмуляцией — заметно медленнее fp16
    major = torch.cuda.get_device_capability(device)[0]
    return "bf16" if major >= 8 else "fp16"


def amp_dtype(name: str) -> torch.dtype:
    return {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[name]


def lr_at(step: int, total: int, warmup: int, min_ratio: float) -> float:
    if warmup > 0 and step < warmup:
        return (step + 1) / warmup
    span = max(1, total - warmup)
    progress = min(1.0, (step - warmup) / span)
    return min_ratio + (1.0 - min_ratio) * 0.5 * (1.0 + math.cos(math.pi * progress))


# -------------------------------------------------------------- чекпоинты ---


def save_ckpt(cfg: dict, model, opt, scaler, step: int, tokens: int, extra: dict) -> str:
    p = paths(cfg)
    path = os.path.join(p["ckpt"], "last.pt")
    tmp = path + ".tmp"
    torch.save(
        {
            "step": step,
            "tokens": tokens,
            "model": unwrap(model).state_dict(),
            "optim": opt.state_dict(),
            "scaler": scaler.state_dict() if scaler is not None else None,
            "cfg": cfg,
            "extra": extra,
        },
        tmp,
    )
    os.replace(tmp, path)

    keep = int(cfg["train"]["keep_step_ckpts"])
    if keep > 0 and step > 0:
        step_path = os.path.join(p["ckpt"], f"step_{step:07d}.pt")
        try:
            os.link(path, step_path)
        except OSError:
            torch.save({"step": step}, step_path)  # заглушка, если hardlink нельзя
        olds = sorted(f for f in os.listdir(p["ckpt"]) if f.startswith("step_"))
        for name in olds[:-keep]:
            try:
                os.remove(os.path.join(p["ckpt"], name))
            except OSError:
                pass
    config_snapshot(cfg, os.path.join(p["ckpt"], "config.json"))
    return path


SMALL_ARTIFACTS = (
    "ckpt/config.json",
    "logs/metrics.csv",
    "logs/config_used.yaml",
    "model/ext/extend_meta.json",
    "model/ext/tokenizer.json",
    "model/ext/tokenizer_config.json",
    "model/ext/config.json",
)


def _try_pull(repo: str, filename: str, dst: str, token: str | None) -> bool:
    try:
        import shutil

        from huggingface_hub import hf_hub_download

        print(f"[ckpt] пробую взять {filename} из {repo}")
        got = hf_hub_download(repo_id=repo, filename=filename, repo_type="model", token=token)
        if os.path.abspath(got) != os.path.abspath(dst):
            try:
                os.replace(got, dst)          # один и тот же ФС
            except OSError:
                # кеш HF на другом диске — переносим копированием
                if os.path.exists(dst):
                    os.remove(dst)
                shutil.copy2(got, dst)
        print(f"[ckpt] {filename}: получен ({os.path.getsize(dst)/1e6:.0f} МБ)")
        return os.path.exists(dst)
    except Exception as exc:  # noqa: BLE001
        print(f"[ckpt] {filename}: {str(exc).splitlines()[0][:160]}")
        return False


def load_ckpt(cfg: dict, model, opt, scaler, token: str | None) -> tuple[int, int] | None:
    p = paths(cfg)
    path = os.path.join(p["ckpt"], "last.pt")
    repo = cfg["train"].get("hub_repo")
    if not cfg["train"]["resume"]:
        return None

    if not os.path.exists(path) and repo:
        _try_pull(repo, "ckpt/last.pt", path, token)

    if os.path.exists(path):
        print(f"[ckpt] резюм с {path}")
        blob = torch.load(path, map_location="cpu", weights_only=False)
        model.load_state_dict(blob["model"])
        try:
            opt.load_state_dict(blob["optim"])
            if scaler is not None and blob.get("scaler"):
                scaler.load_state_dict(blob["scaler"])
        except Exception as exc:  # noqa: BLE001
            print(f"[ckpt] состояние оптимизатора не совпало, стартую с чистого: {exc}")
        return int(blob["step"]), int(blob.get("tokens", 0))

    # запасной путь: только веса (оптимизатор потерян — это нормально)
    wpath = os.path.join(p["ckpt"], "weights_bf16.pt")
    if repo and not os.path.exists(wpath):
        _try_pull(repo, "ckpt/weights_bf16.pt", wpath, token)
    if os.path.exists(wpath):
        print(f"[ckpt] резюм по весам {wpath} (без оптимизатора)")
        blob = torch.load(wpath, map_location="cpu", weights_only=False)
        model.load_state_dict(blob["model"])
        return int(blob.get("step", 0)), int(blob.get("tokens", 0))
    return None


def push_to_hub(cfg: dict, token: str | None, step: int, model=None,
                full_ckpt: bool = False, tokens: int = 0) -> None:
    """Залить состояние на Hub.

    По умолчанию — только веса в bf16 (800 МБ), а не last.pt (~5 ГБ).
    full_ckpt=True добавляет и полный чекпоинт с оптимизатором.
    """
    repo = cfg["train"].get("hub_repo")
    if not repo or not token:
        return
    from huggingface_hub import HfApi

    api = HfApi(token=token)
    api.create_repo(repo_id=repo, repo_type="model",
                    private=bool(cfg["train"].get("hub_private", True)), exist_ok=True)
    p = paths(cfg)

    if model is not None:
        wpath = os.path.join(p["ckpt"], "weights_bf16.pt")
        state = {k: v.detach().to("cpu", torch.bfloat16) for k, v in unwrap(model).state_dict().items()}
        torch.save({"step": step, "tokens": tokens, "model": state}, wpath)
        del state
        api.upload_file(path_or_fileobj=wpath, path_in_repo="ckpt/weights_bf16.pt", repo_id=repo)

    if full_ckpt and os.path.exists(os.path.join(p["ckpt"], "last.pt")):
        api.upload_file(path_or_fileobj=os.path.join(p["ckpt"], "last.pt"),
                        path_in_repo="ckpt/last.pt", repo_id=repo)

    for extra in SMALL_ARTIFACTS:
        local = os.path.join(p["root"], extra)
        if os.path.exists(local):
            api.upload_file(path_or_fileobj=local, path_in_repo=extra, repo_id=repo)
    print(f"[hub] залито на {repo} (шаг {step})")


# --------------------------------------------------------------------- eval ---


@torch.no_grad()
def evaluate(cfg: dict, model, manifest: dict, device: torch.device, dtype_name: str,
             tokenizer_dir: str, max_tokens_per_source: int = 200_000) -> dict[str, float]:
    p = paths(cfg)
    seq_len = int(cfg["data"]["seq_len"])
    batch = int(cfg["optim"]["micro_batch"])
    model.eval()
    out: dict[str, float] = {}
    for shard in manifest.get("val", []):
        path = os.path.join(p["data_val"], shard["path"])
        if not os.path.exists(path):
            continue
        arr = np.memmap(path, dtype=np.uint16, mode="r")
        n_tok = min(len(arr), max_tokens_per_source)
        if n_tok < seq_len + 1:
            continue
        nll, count = 0.0, 0
        for start in range(0, n_tok - seq_len - 1, seq_len * batch):
            rows = []
            for b in range(batch):
                off = start + b * seq_len
                if off + seq_len + 1 > len(arr):
                    break
                rows.append(np.asarray(arr[off:off + seq_len + 1], dtype=np.int64))
            if not rows:
                break
            x = torch.from_numpy(np.stack(rows)).to(device)
            with torch.autocast("cuda", dtype=amp_dtype(dtype_name),
                                enabled=(device.type == "cuda" and dtype_name != "fp32")):
                logits = model(input_ids=x[:, :-1], use_cache=False).logits
            loss = torch.nn.functional.cross_entropy(
                logits.reshape(-1, logits.size(-1)).float(),
                x[:, 1:].reshape(-1),
                reduction="sum",
            )
            nll += float(loss)
            count += x[:, 1:].numel()
        if count:
            out[shard["source"]] = math.exp(nll / count)
    model.train()
    return out


# -------------------------------------------------------------------- train ---


def init_dist() -> dict:
    """DDP включается сам, если процесс запущен через torchrun."""
    import torch.distributed as dist

    world = int(os.environ.get("WORLD_SIZE") or 1)
    if world <= 1:
        return {"enabled": False, "rank": 0, "local_rank": 0, "world": 1}
    if not dist.is_initialized():
        dist.init_process_group(backend="nccl")
    local_rank = int(os.environ.get("LOCAL_RANK") or 0)
    torch.cuda.set_device(local_rank)
    return {"enabled": True, "rank": dist.get_rank(),
            "local_rank": local_rank, "world": dist.get_world_size()}


def unwrap(model):
    return model.module if hasattr(model, "module") else model


def sync(ddp: dict) -> None:
    if ddp["enabled"]:
        torch.distributed.barrier()


def run(cfg: dict, token: str | None = None, manifest: dict | None = None) -> dict[str, Any]:
    p = paths(cfg)
    ddp = init_dist()
    is_main = ddp["rank"] == 0
    set_seed(int(cfg["seed"]) + 1000 * ddp["rank"])
    want_device = str(cfg["optim"].get("device", "auto")).lower()
    xm = None
    if want_device == "tpu":
        import torch_xla.core.xla_model as xm  # noqa: N813

        device = xm.xla_device()
        dtype_name = "bf16"
    elif ddp["enabled"]:
        device = torch.device(f"cuda:{ddp['local_rank']}")
        dtype_name = pick_dtype(cfg, device)
    else:
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        dtype_name = pick_dtype(cfg, device)
    dev_idx = device.index if device.index is not None else 0

    if is_main:
        print(f"[train] устройство {device}, compute dtype {dtype_name}, "
              f"процессов {ddp['world']}")
        if device.type == "cuda":
            print(f"[train] GPU: {torch.cuda.get_device_name(dev_idx)}, "
                  f"{torch.cuda.get_device_properties(dev_idx).total_memory/1e9:.1f} GB")
        elif device.type == "xla":
            print("[train] TPU через torch_xla (PJRT)")
        else:
            print("[train] ВНИМАНИЕ: ускорителя нет, обучение будет очень медленным")

    if not manifest:
        with open(os.path.join(p["data"], "manifest.json"), encoding="utf-8") as fh:
            manifest = json.load(fh)

    model, tok = model_mod.load(cfg, token)
    info = model_mod.configure_trainable(model, cfg)
    model.to(device)

    groups = model_mod.param_groups(model, float(cfg["optim"]["weight_decay"]))
    opt = torch.optim.AdamW(groups, 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"])
    seq_len = int(cfg["data"]["seq_len"])
    tokens_per_step = micro * accum * seq_len * ddp["world"]
    target = cfg["train"].get("target_tokens")
    if target:
        max_steps = math.ceil(float(target) / tokens_per_step)
    else:
        max_steps = int(cfg["train"]["max_steps"])
    warmup = int(cfg["optim"]["warmup_steps"])
    min_ratio = float(cfg["optim"]["min_lr_ratio"])
    grad_clip = float(cfg["optim"]["grad_clip"])

    # чекпоинт грузим в обычную (не DDP) модель — ключи без префикса module.
    start_step, tokens_done = 0, 0
    resumed = load_ckpt(cfg, model, opt, scaler, token)
    if resumed:
        start_step, tokens_done = resumed
    elif cfg["train"].get("require_resume"):
        raise SystemExit(
            "[ckpt] require_resume=true, но чекпоинт не найден. "
            "Останавливаюсь, иначе обучение пойдёт со случайных весов."
        )
    sched = torch.optim.lr_scheduler.LambdaLR(
        opt, lambda s: lr_at(s, max_steps, warmup, min_ratio))
    for _ in range(start_step):
        sched.step()

    if ddp["enabled"]:
        model = torch.nn.parallel.DistributedDataParallel(
            model, device_ids=[ddp["local_rank"]], find_unused_parameters=False)

    train_data = data_mod.PackedTrainData(cfg, manifest, "train")
    if ddp["enabled"]:  # каждый процесс берёт свои окна
        train_data.rng = np.random.default_rng(int(cfg["data"]["seed"]) + 7919 * ddp["rank"])

    if is_main:
        print(f"[train] данных: {train_data.total/1e6:.1f}M токенов в {len(train_data.arrays)} шардах")
        print(f"[train] шагов: {start_step} → {max_steps}, батч {micro}x{accum}x{seq_len}"
              f"{' x' + str(ddp['world']) + ' GPU' if ddp['enabled'] else ''} "
              f"= {tokens_per_step} ток./шаг")

    os.makedirs(p["logs"], exist_ok=True)
    metrics_path = os.path.join(p["logs"], "metrics.csv")
    mfile = None
    writer = None
    if is_main:
        is_new = not os.path.exists(metrics_path)
        mfile = open(metrics_path, "a", newline="", encoding="utf-8")
        writer = csv.writer(mfile)
        if is_new:
            writer.writerow(["step", "tokens", "loss", "lr", "tok_s", "vram_gb", "elapsed_h"])

    started = time.time()
    best_loss = float("inf")
    last_loss = float("nan")
    step = start_step

    for step in range(start_step, max_steps):
        lr = lr_at(step, max_steps, warmup, min_ratio) * float(cfg["optim"]["lr"])
        for group in opt.param_groups:
            group["lr"] = lr

        opt.zero_grad(set_to_none=True)
        running = 0.0
        t0 = time.time()
        for i in range(accum):
            x, y = train_data.batch(micro)
            xb = torch.from_numpy(x).to(device, non_blocking=True)
            yb = torch.from_numpy(y).to(device, non_blocking=True)
            # градиенты синхронизируем только на последнем микро-батче
            no_sync = model.no_sync() if (ddp["enabled"] and i < accum - 1) else contextlib.nullcontext()
            with no_sync, torch.autocast("cuda", dtype=amp_dtype(dtype_name),
                                         enabled=(device.type == "cuda" and dtype_name != "fp32")):
                logits = model(input_ids=xb, use_cache=False).logits
                loss = torch.nn.functional.cross_entropy(
                    logits.reshape(-1, logits.size(-1)).float(),
                    yb.reshape(-1),
                )
            if scaler.is_enabled():
                scaler.scale(loss / accum).backward()
            else:
                (loss / accum).backward()
            running += float(loss.detach())
            del logits, loss, xb, yb

        if scaler.is_enabled():
            scaler.unscale_(opt)
            torch.nn.utils.clip_grad_norm_(
                [q for q in model.parameters() if q.requires_grad], grad_clip)
            scaler.step(opt)
            scaler.update()
        else:
            torch.nn.utils.clip_grad_norm_(
                [q for q in model.parameters() if q.requires_grad], grad_clip)
            opt.step()
        sched.step()
        if xm is not None:  # TPU: сбрасываем граф
            xm.mark_step()

        tokens_done += tokens_per_step
        last_loss = running / accum
        best_loss = min(best_loss, last_loss)
        dt = time.time() - t0
        elapsed_h = (time.time() - started) / 3600.0

        if is_main and (step % int(cfg["train"]["log_every"]) == 0 or step == max_steps - 1):
            vram = (torch.cuda.max_memory_allocated(dev_idx) / 1e9) if device.type == "cuda" else 0.0
            writer.writerow([step, tokens_done, f"{last_loss:.5f}", f"{lr:.2e}",
                             f"{tokens_per_step/dt:.0f}", f"{vram:.2f}", f"{elapsed_h:.2f}"])
            mfile.flush()
            print(f"[train] шаг {step:6d} | loss {last_loss:.4f} | lr {lr:.2e} | "
                  f"{tokens_per_step/dt:6.0f} ток/с | {vram:4.1f} GB | {elapsed_h:4.2f} ч")

        if (step + 1) % int(cfg["train"]["save_every"]) == 0:
            if is_main:
                save_ckpt(cfg, model, opt, scaler, step + 1, tokens_done, info)
                push_n = int(cfg["train"].get("push_every") or 0)
                if push_n and (step + 1) % push_n == 0:
                    try:
                        push_to_hub(cfg, token, step + 1, model, tokens=tokens_done)
                    except Exception as exc:  # noqa: BLE001 — сеть не должна убивать обучение
                        print(f"[hub] пуш не удался, продолжаю: {str(exc)[:160]}")
            sync(ddp)

        if (step + 1) % int(cfg["train"]["eval_every"]) == 0:
            if is_main:
                try:
                    ppl = evaluate(cfg, model, manifest, device, dtype_name, p["model_ext"])
                    print("[eval] ppl: " + ", ".join(f"{k}={v:.2f}" for k, v in ppl.items()))
                except Exception as exc:  # noqa: BLE001
                    print(f"[eval] не удалось: {str(exc).splitlines()[0][:160]}")
            sync(ddp)

        if elapsed_h >= float(cfg["train"]["max_hours"]):
            if is_main:
                print(f"[train] лимит времени {cfg['train']['max_hours']} ч — останавливаюсь")
                save_ckpt(cfg, model, opt, scaler, step + 1, tokens_done, info)
            sync(ddp)
            break

    if is_main:
        save_ckpt(cfg, model, opt, scaler, step + 1, tokens_done, info)
        if mfile:
            mfile.close()
        print(f"[train] готово: шаг {step+1}, токенов {tokens_done/1e6:.1f}M, loss {last_loss:.4f}")
        try:
            if cfg["train"].get("hub_repo") and token:
                push_to_hub(cfg, token, step + 1, model, full_ckpt=True, tokens=tokens_done)
            export_model(cfg, model, tok, token if cfg["train"].get("hub_repo") else None)
        except Exception as exc:  # noqa: BLE001 — не терять прогон из-за сети
            print(f"[export] финальный экспорт/пуш упал: {str(exc)[:200]}")
            try:
                export_model(cfg, model, tok, None)
            except Exception as exc2:  # noqa: BLE001
                print(f"[export] локально тоже не вышло: {str(exc2)[:200]}")
    sync(ddp)
    if ddp["enabled"]:
        torch.distributed.destroy_process_group()
    return {"step": step + 1, "tokens": tokens_done, "loss": last_loss}


def export_model(cfg: dict, model, tok, token: str | None = None) -> str:
    """Сохранить готовую модель (HF-совместимо) и залить на Hub."""
    p = paths(cfg)
    out = p["export"]
    os.makedirs(out, exist_ok=True)
    unwrap(model).save_pretrained(out, safe_serialization=True)
    tok.save_pretrained(out)
    for name in os.listdir(p["model_work"]):
        if not (name.startswith("modeling_") or name.startswith("configuration_")):
            continue
        if not name.endswith(".py"):
            continue
        src = os.path.join(p["model_work"], name)
        if os.path.exists(src):
            import shutil

            shutil.copy2(src, os.path.join(out, name))
    print(f"[export] модель сохранена: {out}")

    repo = cfg["train"].get("hub_repo")
    if repo and token:
        from huggingface_hub import HfApi

        api = HfApi(token=token)
        api.create_repo(repo_id=repo, repo_type="model",
                        private=bool(cfg["train"].get("hub_private", True)), exist_ok=True)
        api.upload_folder(folder_path=out, repo_id=repo)
        print(f"[export] залито на https://huggingface.co/{repo}")
    return out