File size: 6,533 Bytes
7f1e014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Training utilities: LR schedule, checkpointing, logging."""

import math
import os
import time
from pathlib import Path
from typing import Any

import torch

from .config import Config, TrainingConfig


# ── Learning Rate Schedule ────────────────────────────────────────────


def get_lr(step: int, config: TrainingConfig) -> float:
    """Cosine decay with linear warmup.

    Returns the learning rate at step `step`.
    """
    # Linear warmup
    if step < config.warmup_steps:
        return config.peak_lr * (step + 1) / config.warmup_steps

    # After max_steps, hold at min_lr
    if step >= config.max_steps:
        return config.min_lr

    # Cosine decay from peak_lr to min_lr
    decay_steps = config.max_steps - config.warmup_steps
    decay_ratio = (step - config.warmup_steps) / decay_steps
    assert 0.0 <= decay_ratio <= 1.0
    coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
    return config.min_lr + coeff * (config.peak_lr - config.min_lr)


# ── Checkpointing ─────────────────────────────────────────────────────


def save_checkpoint(
    model: torch.nn.Module,
    optimizer: torch.optim.Optimizer,
    step: int,
    config: Config,
    checkpoint_dir: str | Path,
) -> Path:
    """Save a training checkpoint.

    Saves model state, optimizer state, step, config, and RNG states.
    Uses .tmp suffix to avoid corruption from interrupted writes.
    """
    checkpoint_dir = Path(checkpoint_dir)
    checkpoint_dir.mkdir(parents=True, exist_ok=True)

    checkpoint_path = checkpoint_dir / f"step_{step:06d}.pt"
    tmp_path = checkpoint_dir / f"step_{step:06d}.pt.tmp"

    # Gather state
    state = {
        "model": model.state_dict(),
        "optimizer": optimizer.state_dict(),
        "step": step,
        "config": config,
        "rng_state": torch.get_rng_state(),
    }

    if torch.cuda.is_available():
        state["cuda_rng_state"] = torch.cuda.get_rng_state()

    # Write to temp file first, then rename (atomic-ish on same filesystem)
    torch.save(state, tmp_path)
    os.replace(tmp_path, checkpoint_path)

    return checkpoint_path


def load_checkpoint(
    path: str | Path,
    model: torch.nn.Module,
    optimizer: torch.optim.Optimizer | None = None,
    map_location: str = "cuda",
) -> int:
    """Load a training checkpoint. Returns the step number."""
    checkpoint = torch.load(str(path), map_location=map_location, weights_only=False)

    model.load_state_dict(checkpoint["model"])

    if optimizer is not None and "optimizer" in checkpoint:
        optimizer.load_state_dict(checkpoint["optimizer"])

    # Restore RNG state (non-critical; skip if format is incompatible)
    try:
        if "rng_state" in checkpoint:
            torch.set_rng_state(checkpoint["rng_state"])
        if "cuda_rng_state" in checkpoint and torch.cuda.is_available():
            torch.cuda.set_rng_state(checkpoint["cuda_rng_state"])
    except (TypeError, RuntimeError) as e:
        print(f"  Warning: could not restore RNG state ({e}), continuing anyway.")

    return checkpoint["step"]


def cleanup_checkpoints(checkpoint_dir: str | Path, max_keep: int) -> None:
    """Remove old checkpoints, keeping only the `max_keep` most recent."""
    if max_keep <= 0:
        return
    checkpoint_dir = Path(checkpoint_dir)
    checkpoints = sorted(
        checkpoint_dir.glob("step_*.pt"),
        key=lambda p: p.stat().st_mtime,
        reverse=True,
    )
    for cp in checkpoints[max_keep:]:
        cp.unlink()


# ── Logging ────────────────────────────────────────────────────────────


class Logger:
    """Simple console logger with timing and optional TensorBoard support."""

    def __init__(self, config: Config, use_tensorboard: bool = False):
        self.config = config
        self.start_time = time.time()
        self.step_start_time = time.time()
        self.tokens_processed = 0

        self.writer = None
        if use_tensorboard:
            try:
                from torch.utils.tensorboard import SummaryWriter

                self.writer = SummaryWriter(log_dir="runs")
                print("TensorBoard logging enabled (runs/)")
            except ImportError:
                print("TensorBoard not installed, skipping.")

    def log_step(
        self,
        step: int,
        train_loss: float,
        lr: float,
        tokens_per_step: int,
        val_loss: float | None = None,
    ):
        """Log a training step to console and optionally TensorBoard."""
        elapsed = time.time() - self.start_time
        step_time = time.time() - self.step_start_time
        self.tokens_processed += tokens_per_step
        tokens_per_sec = tokens_per_step / step_time if step_time > 0 else 0

        vals = [
            f"step {step:>6d}/{self.config.training.max_steps}",
            f"loss {train_loss:.4f}",
            f"lr {lr:.2e}",
            f"tok/s {tokens_per_sec:,.0f}",
            f"elapsed {elapsed/60:.1f}m",
        ]
        if val_loss is not None:
            vals.insert(2, f"val {val_loss:.4f}")

        print(" | ".join(vals))

        if self.writer is not None:
            self.writer.add_scalar("train/loss", train_loss, step)
            self.writer.add_scalar("train/lr", lr, step)
            self.writer.add_scalar("train/tokens_per_sec", tokens_per_sec, step)
            if val_loss is not None:
                self.writer.add_scalar("val/loss", val_loss, step)

        self.step_start_time = time.time()

    def finalize(self, step: int) -> dict[str, Any]:
        """Print final stats and close writer."""
        total_time = time.time() - self.start_time
        tokens_per_sec = (
            self.tokens_processed / total_time if total_time > 0 else 0
        )
        stats = {
            "total_steps": step,
            "total_time_minutes": round(total_time / 60, 1),
            "tokens_processed": self.tokens_processed,
            "tokens_per_sec": round(tokens_per_sec, 1),
        }
        print(f"\nTraining complete!")
        print(f"  Total time: {total_time/60:.1f} min")
        print(f"  Average throughput: {tokens_per_sec:,.0f} tok/s")

        if self.writer is not None:
            self.writer.close()

        return stats