File size: 6,070 Bytes
8f25722
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db7db52
8f25722
 
db7db52
8f25722
 
655c6db
 
8f25722
 
 
 
 
655c6db
 
 
 
 
 
 
 
8f25722
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db7db52
 
8f25722
db7db52
 
8f25722
db7db52
 
 
 
 
 
 
 
 
 
 
 
8f25722
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c930f3
 
 
 
 
8f25722
db7db52
8f25722
 
db7db52
 
 
 
 
 
 
 
 
 
 
8f25722
 
 
 
 
 
 
 
 
 
 
 
 
db7db52
 
 
 
 
 
 
 
 
 
8f25722
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Sync the working tree to the HuggingFace dataset repo.

Usage:
    python scripts/upload_hf.py --dry-run
    python scripts/upload_hf.py --include-runs main_ abl_ loao_ de_

Checkpoints (``model.pt``) are only uploaded for the tags listed in
``KEEP_CKPT`` to keep the repo small; metrics/history/curves/predictions for
every run are always uploaded.
"""
from __future__ import annotations

import argparse
import os
from pathlib import Path

from huggingface_hub import HfApi

REPO = "eduzrh/training-model-material"
REPO_TYPE = "dataset"
ROOT = Path(__file__).resolve().parents[1]

# directories uploaded verbatim (relative to repo root)
DIRS = ["code", "docs", "scripts", "data", "results/tables", "results/figures",
        "report", "configs", "logs"]

IGNORE = ["**/__pycache__/**", "**/*.pyc", "**/.ipynb_checkpoints/**",
          "**/*.pt", "**/predictions.npz", "**/_tables_ro/**", "**/_figures_ro/**"]

KEEP_CKPT: tuple[str, ...] = ("main_pimamba_f0_s0", "main_mamba_f0_s0",
                              "main_gru_f0_s0", "abl_pimamba_f0_s0",
                              "next_hymba_f0_s0", "v2_pimamba2_f0_s0")


def _token(explicit: str | None) -> str:
    tok = explicit or os.environ.get("HF_TOKEN")
    if not tok:
        # fall back to the credential saved by `huggingface-cli login`
        try:
            from huggingface_hub import get_token
            tok = get_token()
        except Exception:  # noqa: BLE001
            tok = None
    if not tok:
        raise SystemExit("no HF token: pass --token, set HF_TOKEN or run hf login")
    return tok


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--token", default=None)
    ap.add_argument("--repo", default=REPO)
    ap.add_argument("--include-runs", nargs="*", default=None,
                    help="only upload results/runs tags starting with these prefixes")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--private", action="store_true")
    a = ap.parse_args()

    tok = _token(a.token)
    api = HfApi(token=tok)
    api.create_repo(a.repo, repo_type=REPO_TYPE, exist_ok=True,
                    private=a.private)

    targets: list[Path] = []
    for d in DIRS:
        p = ROOT / d
        if p.exists():
            targets.append(p)

    # run folders: bulk upload in ONE commit when possible (250+ folders would
    # otherwise mean 250+ commits), with stale/debug tags filtered out.
    run_root = ROOT / "results" / "runs"
    keep_tags = _summary_tags()
    extra_ignore = list(IGNORE)
    if run_root.exists():
        if a.include_runs:
            for p in sorted(run_root.iterdir()):
                if p.is_dir() and any(p.name.startswith(x) for x in a.include_runs):
                    targets.append(p)
        else:
            drop = {d.name for d in run_root.iterdir() if d.is_dir()} - keep_tags
            extra_ignore += [f"{t}/**" for t in sorted(drop)]
            targets.append(run_root)
            print(f"bulk runs: keeping {len(keep_tags)} tags, skipping {len(drop)}")

    for f in ["README.md", "requirements.txt", ".gitignore",
              "results/RESULTS.md", "results/summary.csv"]:
        p = ROOT / f
        if p.exists():
            targets.append(p)

    n_files = 0
    total = 0
    for p in targets:
        rel = p.relative_to(ROOT).as_posix()
        files = [p] if p.is_file() else [q for q in p.rglob("*") if q.is_file()]
        files = [q for q in files if not _ignored(q.relative_to(ROOT).as_posix())]
        if not files:
            continue
        size = sum(q.stat().st_size for q in files)
        n_files += len(files)
        total += size
        print(f"{rel:45s} {len(files):5d} files  {size/1e6:8.2f} MB")
        if a.dry_run:
            continue
        if p.is_file():
            api.upload_file(path_or_fileobj=str(p), path_in_repo=rel,
                            repo_id=a.repo, repo_type=REPO_TYPE,
                            commit_message=f"sync {rel}")
            continue
        api.upload_folder(folder_path=str(p), path_in_repo=rel, repo_id=a.repo,
                          repo_type=REPO_TYPE, ignore_patterns=extra_ignore,
                          commit_message=f"sync {rel}")

    # fold predictions of the seed-0 main runs: needed to reproduce pooled OOF
    if not a.dry_run:
        for m in ["mlp", "gru", "lstm", "transformer", "mamba", "mamba2", "pimamba"]:
            for f in range(5):
                pf = run_root / f"main_{m}_f{f}_s0" / "predictions.npz"
                if pf.exists():
                    api.upload_file(path_or_fileobj=str(pf),
                                    path_in_repo=f"results/runs/main_{m}_f{f}_s0/predictions.npz",
                                    repo_id=a.repo, repo_type=REPO_TYPE,
                                    commit_message=f"oof predictions {m} f{f}")

    # checkpoints worth keeping
    for tag in KEEP_CKPT:
        ck = run_root / tag / "model.pt"
        if ck.exists():
            print(f"checkpoint {tag} ({ck.stat().st_size/1e6:.1f} MB)")
            if not a.dry_run:
                api.upload_file(path_or_fileobj=str(ck),
                                path_in_repo=f"results/runs/{tag}/model.pt",
                                repo_id=a.repo, repo_type=REPO_TYPE,
                                commit_message=f"checkpoint {tag}")
    print(f"\ntotal {n_files} files, {total/1e6:.1f} MB")


def _summary_tags() -> set[str]:
    """Only publish runs that actually appear in results/summary.csv."""
    import csv
    f = ROOT / "results" / "summary.csv"
    if not f.exists():
        return set()
    with f.open(encoding="utf-8") as fh:
        return {r["tag"] for r in csv.DictReader(fh) if r.get("tag")}


def _ignored(rel: str) -> bool:
    import fnmatch
    for pat in IGNORE:
        p = pat.replace("**/", "").replace("/**", "")
        if fnmatch.fnmatch(rel, pat) or fnmatch.fnmatch(rel.split("/")[-1], p):
            return True
        if "/__pycache__/" in rel:
            return True
    return False


if __name__ == "__main__":
    main()