File size: 6,455 Bytes
84af0a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Inventory and integrity-check the Orbax checkpoints written by a pi0.5 training run.

    python3 scripts/check_checkpoints.py /data/checkpoints/pi05_g1_pickplace/pickplace_full_v1

Pure stdlib, no GPU, no JAX -- safe to run while training still holds the A100. It answers the
questions you cannot answer from `ls` alone:

  * which steps exist, and which are resumable (train_state present) vs params-only (pruned)
  * whether any save is INCOMPLETE -- an aborted or in-flight write leaves a
    `.orbax-checkpoint-tmp-*` directory, or a step dir with no commit marker
  * whether `assets/norm_stats.json` is present, because a checkpoint without it serves
    garbage actions while looking perfectly healthy
  * zero-byte files, which is what a checkpoint written into a full disk looks like

Exit code is 0 only if every complete checkpoint passes. `--json` emits machine-readable output.
"""
import argparse
import json
import pathlib
import sys

# Orbax drops one of these in a step directory once the write has been committed. Which one
# depends on the version, so presence of ANY is treated as "committed".
COMMIT_MARKERS = ("commit_success.txt", "_CHECKPOINT_METADATA", "_METADATA")
GIB = 1024**3


def human(n: int) -> str:
    """Adaptive units -- a 12.5 GiB params dir and a 4 KiB assets dir both need to read."""
    for unit, div in (("T", 1024**4), ("G", GIB), ("M", 1024**2), ("K", 1024)):
        if n >= div:
            return f"{n / div:.1f}{unit}"
    return f"{n}B"


def dir_stats(path: pathlib.Path) -> tuple[int, int, int]:
    """(total bytes, file count, zero-byte file count) over a directory tree."""
    total = files = empty = 0
    for f in path.rglob("*"):
        if not f.is_file():
            continue
        try:
            size = f.stat().st_size
        except OSError:
            continue
        total += size
        files += 1
        empty += size == 0
    return total, files, empty


def inspect(step_dir: pathlib.Path) -> dict:
    r: dict = {"step": int(step_dir.name), "path": str(step_dir), "problems": []}

    r["committed"] = any((step_dir / m).exists() for m in COMMIT_MARKERS) or any(
        (step_dir / sub / m).exists() for sub in ("params",) for m in COMMIT_MARKERS
    )

    for sub in ("params", "train_state", "assets"):
        d = step_dir / sub
        if d.is_dir():
            size, files, empty = dir_stats(d)
            r[sub] = {"bytes": size, "files": files, "empty_files": empty}
            if empty:
                r["problems"].append(f"{sub}/ has {empty} zero-byte file(s) -- disk full?")
            if files == 0:
                r["problems"].append(f"{sub}/ exists but is empty")
        else:
            r[sub] = None

    if r["params"] is None:
        r["problems"].append("no params/ -- nothing deployable here")

    # assets/ carries norm_stats.json. Without it the policy denormalises with the wrong
    # statistics and the robot does nothing while every log looks fine.
    hits = list((step_dir / "assets").rglob("norm_stats.json")) if (step_dir / "assets").is_dir() else []
    r["norm_stats"] = str(hits[0].relative_to(step_dir)) if hits else None
    if not hits:
        r["problems"].append("no assets/**/norm_stats.json -- served policy would emit garbage")

    r["resumable"] = r["train_state"] is not None
    return r


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("root", type=pathlib.Path, help="the exp directory, e.g. .../pickplace_full_v1")
    ap.add_argument("--frames", type=int, default=161_440, help="dataset frames, for the epoch column")
    ap.add_argument("--batch-size", type=int, default=32)
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()

    if not a.root.is_dir():
        print(f"FAIL: {a.root} is not a directory", file=sys.stderr)
        return 2

    partial = sorted({p.name for p in a.root.glob("*orbax-checkpoint-tmp-*")})
    steps = sorted((p for p in a.root.iterdir() if p.is_dir() and p.name.isdigit()),
                   key=lambda p: int(p.name))

    if not steps and not partial:
        print(f"No checkpoints in {a.root} yet.")
        return 0

    rows = [inspect(s) for s in steps]
    spe = a.frames / a.batch_size  # steps per epoch

    if a.json:
        print(json.dumps({"root": str(a.root), "in_flight": partial, "checkpoints": rows}, indent=2))
    else:
        print(f"{a.root}\n")
        hdr = f"{'step':>7}  {'epoch':>5}  {'params':>8}  {'tstate':>8}  {'norm_stats':>10}  state"
        print(hdr)
        print("-" * len(hdr))
        for r in rows:
            p = human(r["params"]["bytes"]) if r["params"] else "--"
            t = human(r["train_state"]["bytes"]) if r["train_state"] else "--"
            n = "yes" if r["norm_stats"] else "NO"
            state = "resumable" if r["resumable"] else "params only"
            if r["problems"]:
                state = "PROBLEM"
            print(f"{r['step']:>7}  {r['step']/spe:>5.2f}  {p:>8}  {t:>8}  {n:>10}  {state}")

        total = sum((r["params"]["bytes"] if r["params"] else 0)
                    + (r["train_state"]["bytes"] if r["train_state"] else 0) for r in rows)
        print(f"\n{len(rows)} checkpoint(s), {human(total)} total")
        if partial:
            print(f"\n{len(partial)} save(s) IN FLIGHT or aborted (Orbax temp dirs):")
            for p in partial:
                print(f"  {p}")
            print("  A save in progress is normal. One that persists after training exits is not --")
            print("  delete it, that step never committed.")

        uncommitted = [r["step"] for r in rows if not r["committed"]]
        if uncommitted:
            print(f"\nNOTE: no commit marker found for step(s) {uncommitted}. Orbax layout varies by")
            print("version, so this is weak evidence on its own -- trust the load test instead.")

        bad = [r for r in rows if r["problems"]]
        if bad:
            print("\nPROBLEMS")
            for r in bad:
                for p in r["problems"]:
                    print(f"  step {r['step']}: {p}")
        else:
            print("\nAll checkpoints structurally OK. Structure is not the same as loadable --")
            print("run the load test in the runbook (Step 11.1) on at least one of them.")

    return 1 if any(r["problems"] for r in rows) else 0


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