File size: 12,540 Bytes
9475836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41f1384
 
 
 
 
 
 
 
 
 
 
 
 
9475836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41f1384
 
 
9475836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41f1384
9475836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41f1384
 
 
 
 
9475836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41f1384
9475836
 
 
 
 
 
 
 
 
 
 
 
 
41f1384
9475836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41f1384
 
 
 
9475836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Checkpoint management with metadata tracking, best-model selection, and pruning.

Provides a central manager for training checkpoints that:
- Tracks per-checkpoint metadata (step, metrics, timestamps)
- Maintains symlinks to best/latest checkpoints
- Prunes old checkpoints to save disk space
- Supports multiple ranking metrics (loss, FID, SSIM, etc.)

Usage:
    manager = CheckpointManager(
        output_dir="checkpoints/phaseA",
        keep_best=3,
        keep_latest=5,
        metric="loss",
        lower_is_better=True,
    )

    # During training loop:
    manager.save(
        step=1000,
        controlnet=controlnet,
        ema_controlnet=ema_controlnet,
        optimizer=optimizer,
        scheduler=scheduler,
        metrics={"loss": 0.0123, "val_ssim": 0.87},
    )
"""

from __future__ import annotations

import json
import shutil
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any

import torch


@dataclass
class CheckpointMetadata:
    """Metadata for a single checkpoint."""

    step: int
    timestamp: float
    metrics: dict[str, float] = field(default_factory=dict)
    epoch: int | None = None
    phase: str = ""
    is_best: bool = False
    size_mb: float = 0.0

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, d: dict[str, Any]) -> CheckpointMetadata:
        return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__})


class CheckpointManager:
    """Manages training checkpoints with pruning and best-model tracking.

    Args:
        output_dir: Base directory for checkpoints.
        keep_best: Number of best checkpoints to retain.
        keep_latest: Number of most recent checkpoints to retain.
        metric: Metric name used to determine "best" checkpoint.
        lower_is_better: If True, lower metric values are better (e.g. loss, FID).
        prefix: Checkpoint directory prefix (default: "checkpoint").
    """

    INDEX_FILE = "checkpoint_index.json"

    def __init__(
        self,
        output_dir: str | Path,
        keep_best: int = 3,
        keep_latest: int = 5,
        metric: str = "loss",
        lower_is_better: bool = True,
        prefix: str = "checkpoint",
    ) -> None:
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.keep_best = keep_best
        self.keep_latest = keep_latest
        self.metric = metric
        self.lower_is_better = lower_is_better
        self.prefix = prefix

        self._index: dict[str, Any] = {"checkpoints": {}}
        self._load_index()

    # ------------------------------------------------------------------
    # Index persistence
    # ------------------------------------------------------------------

    def _index_path(self) -> Path:
        return self.output_dir / self.INDEX_FILE

    def _load_index(self) -> None:
        path = self._index_path()
        if path.exists():
            with open(path) as f:
                self._index = json.load(f)
            if "checkpoints" not in self._index:
                self._index["checkpoints"] = {}
            # Remove entries whose directories no longer exist on disk
            # (can happen after a crash during pruning)
            missing = [
                name
                for name in list(self._index["checkpoints"])
                if not (self.output_dir / name).exists()
            ]
            if missing:
                for name in missing:
                    self._index["checkpoints"].pop(name, None)
                self._update_best()
                self._save_index()
                self._update_symlinks()

    def _save_index(self) -> None:
        with open(self._index_path(), "w") as f:
            json.dump(self._index, f, indent=2)

    # ------------------------------------------------------------------
    # Save checkpoint
    # ------------------------------------------------------------------

    def save(
        self,
        step: int,
        controlnet: torch.nn.Module,
        ema_controlnet: torch.nn.Module,
        optimizer: torch.optim.Optimizer,
        scheduler: Any = None,
        metrics: dict[str, float] | None = None,
        epoch: int | None = None,
        phase: str = "",
        extra_state: dict[str, Any] | None = None,
    ) -> Path:
        """Save a checkpoint with metadata.

        Args:
            step: Current training step.
            controlnet: ControlNet model (or any nn.Module).
            ema_controlnet: EMA copy of the model.
            optimizer: Optimizer state.
            scheduler: Optional LR scheduler.
            metrics: Dict of metric values at this step.
            epoch: Optional epoch number.
            phase: Training phase label (e.g. "A", "B").
            extra_state: Any additional state to save.

        Returns:
            Path to the saved checkpoint directory.
        """
        ckpt_name = f"{self.prefix}-{step}"
        ckpt_dir = self.output_dir / ckpt_name
        ckpt_dir.mkdir(exist_ok=True)

        # Save EMA weights (used for inference)
        if hasattr(ema_controlnet, "save_pretrained"):
            ema_controlnet.save_pretrained(ckpt_dir / "controlnet_ema")

        # Save training state for resume
        state = {
            "controlnet": _get_state_dict(controlnet),
            "ema_controlnet": _get_state_dict(ema_controlnet),
            "optimizer": optimizer.state_dict(),
            "global_step": step,
        }
        if scheduler is not None:
            state["scheduler"] = scheduler.state_dict()
        if extra_state:
            state.update(extra_state)

        torch.save(state, ckpt_dir / "training_state.pt")

        # Compute checkpoint size
        size_mb = sum(
            f.stat().st_size for f in ckpt_dir.rglob("*") if f.is_file()
        ) / (1024 * 1024)

        # Create metadata
        meta = CheckpointMetadata(
            step=step,
            timestamp=time.time(),
            metrics=metrics or {},
            epoch=epoch,
            phase=phase,
            size_mb=round(size_mb, 1),
        )

        # Save metadata alongside checkpoint
        with open(ckpt_dir / "metadata.json", "w") as f:
            json.dump(meta.to_dict(), f, indent=2)

        # Update index
        self._index["checkpoints"][ckpt_name] = meta.to_dict()
        self._update_best()
        self._save_index()

        # Update symlinks
        self._update_symlinks()

        # Prune old checkpoints
        self._prune()

        return ckpt_dir

    # ------------------------------------------------------------------
    # Best / latest tracking
    # ------------------------------------------------------------------

    def _update_best(self) -> None:
        """Recompute which checkpoints are 'best'."""
        entries = []
        for name, meta in self._index["checkpoints"].items():
            val = meta.get("metrics", {}).get(self.metric)
            if val is not None:
                entries.append((name, val, meta))

        if not entries:
            return

        # Sort by metric
        entries.sort(key=lambda x: x[1], reverse=not self.lower_is_better)

        # Mark best
        best_names = {e[0] for e in entries[:self.keep_best]}
        for name, meta in self._index["checkpoints"].items():
            meta["is_best"] = name in best_names

    def _update_symlinks(self) -> None:
        """Update 'latest' and 'best' symlinks."""
        checkpoints = self._sorted_by_step()
        if not checkpoints:
            return

        # Latest symlink
        latest_name = checkpoints[-1]
        latest_link = self.output_dir / "latest"
        _force_symlink(self.output_dir / latest_name, latest_link)

        # Best symlink
        best_name = self.get_best_checkpoint_name()
        if best_name:
            best_link = self.output_dir / "best"
            _force_symlink(self.output_dir / best_name, best_link)

    def get_best_checkpoint_name(self) -> str | None:
        """Return the name of the best checkpoint by tracked metric."""
        best = None
        best_val = None
        for name, meta in self._index["checkpoints"].items():
            val = meta.get("metrics", {}).get(self.metric)
            if val is None:
                continue
            if best_val is None:
                best, best_val = name, val
            elif self.lower_is_better and val < best_val:
                best, best_val = name, val
            elif not self.lower_is_better and val > best_val:
                best, best_val = name, val
        return best

    def get_best_metric_value(self) -> float | None:
        """Return the best value of the tracked metric."""
        name = self.get_best_checkpoint_name()
        if name is None:
            return None
        return self._index["checkpoints"][name]["metrics"].get(self.metric)

    # ------------------------------------------------------------------
    # Pruning
    # ------------------------------------------------------------------

    def _sorted_by_step(self) -> list[str]:
        """Return checkpoint names sorted by step (ascending)."""
        items = list(self._index["checkpoints"].items())
        items.sort(key=lambda x: x[1].get("step", 0))
        return [name for name, _ in items]

    def _prune(self) -> None:
        """Remove old checkpoints, keeping best N and latest M."""
        all_names = self._sorted_by_step()
        if len(all_names) <= self.keep_latest:
            return

        # Determine which to keep
        keep = set()

        # Keep latest
        for name in all_names[-self.keep_latest:]:
            keep.add(name)

        # Keep best
        for name, meta in self._index["checkpoints"].items():
            if meta.get("is_best", False):
                keep.add(name)

        # Delete the rest
        for name in all_names:
            if name not in keep:
                ckpt_dir = self.output_dir / name
                if ckpt_dir.exists():
                    shutil.rmtree(ckpt_dir)
                self._index["checkpoints"].pop(name, None)

        self._save_index()

    # ------------------------------------------------------------------
    # Queries
    # ------------------------------------------------------------------

    def list_checkpoints(self) -> list[dict[str, Any]]:
        """Return metadata for all tracked checkpoints, sorted by step."""
        result = []
        for name in self._sorted_by_step():
            meta = self._index["checkpoints"][name]
            result.append({"name": name, **meta})
        return result

    def get_checkpoint_path(self, name: str) -> Path:
        """Return the filesystem path for a checkpoint by name."""
        return self.output_dir / name

    def get_latest_step(self) -> int:
        """Return the step of the most recent checkpoint, or 0."""
        names = self._sorted_by_step()
        if not names:
            return 0
        return self._index["checkpoints"][names[-1]].get("step", 0)

    def total_size_mb(self) -> float:
        """Return total disk size of all tracked checkpoints."""
        return sum(
            meta.get("size_mb", 0.0)
            for meta in self._index["checkpoints"].values()
        )

    def summary(self) -> str:
        """Return a human-readable summary of checkpoint state."""
        ckpts = self.list_checkpoints()
        if not ckpts:
            return "No checkpoints saved."

        lines = [
            f"Checkpoints: {len(ckpts)} saved ({self.total_size_mb():.0f} MB total)",
            f"Latest: step {self.get_latest_step()}",
        ]

        best_name = self.get_best_checkpoint_name()
        best_val = self.get_best_metric_value()
        if best_name and best_val is not None:
            lines.append(f"Best ({self.metric}): {best_val:.6f} @ {best_name}")

        return "\n".join(lines)


# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------

def _get_state_dict(module: torch.nn.Module) -> dict:
    """Extract state dict, handling DDP wrapper."""
    if hasattr(module, "module"):
        return module.module.state_dict()
    return module.state_dict()


def _force_symlink(target: Path, link: Path) -> None:
    """Create or replace a symlink."""
    if link.is_symlink() or link.exists():
        link.unlink()
    link.symlink_to(target.name)