File size: 5,866 Bytes
74b7543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Aggregate checkpoint accuracies and optionally log curves to Weights & Biases.
Reimplements notebooks/training_dynamics.ipynb as a CLI script.
"""
from __future__ import annotations

import argparse
import json
import re
from pathlib import Path
from typing import Dict, List, Tuple

import matplotlib.pyplot as plt


def calculate_accuracy(file_path: Path) -> Dict[str, Dict[str, float]]:
    with file_path.open("r", encoding="utf-8") as f:
        data = json.load(f)

    type_data: Dict[str, Dict[str, float]] = {}
    for entry in data:
        entry_type = entry["type"]
        type_data.setdefault(entry_type, {"total": 0, "correct": 0})
        if entry["model_output"] == entry["target_text"]:
            type_data[entry_type]["correct"] += 1
        type_data[entry_type]["total"] += 1

    results = {}
    for entry_type, stats in type_data.items():
        total = stats["total"]
        correct = stats["correct"]
        acc = (correct / total) * 100 if total else 0.0
        results[entry_type] = {"total": total, "correct": correct, "accuracy": acc}
    return results


def collect_checkpoints(base_dir: Path, max_checkpoint: int | None, min_interval: int) -> List[Tuple[int, Path]]:
    pattern = re.compile(r"checkpoint-(\d+)")
    tuples: List[Tuple[int, Path]] = []
    for d in sorted(base_dir.iterdir()):
        if not d.is_dir():
            continue
        m = pattern.fullmatch(d.name)
        if not m:
            continue
        step = int(m.group(1))
        if max_checkpoint is not None and step > max_checkpoint:
            continue
        tuples.append((step, d))
    tuples.sort()

    filtered: List[Tuple[int, Path]] = []
    last_step = -min_interval
    for step, path in tuples:
        if step - last_step >= min_interval:
            filtered.append((step, path))
            last_step = step
    return filtered


def aggregate(base_dir: Path, max_checkpoint: int | None, min_interval: int) -> Tuple[List[int], Dict[str, List[float]]]:
    ckpts = collect_checkpoints(base_dir, max_checkpoint, min_interval)
    if not ckpts:
        raise ValueError(f"No checkpoints found in {base_dir}")

    accuracy_dict: Dict[str, List[float]] = {}
    steps = []
    for step, path in ckpts:
        all_items = path / "all_items.json"
        if not all_items.exists():
            continue
        steps.append(step)
        res = calculate_accuracy(all_items)
        for metric, vals in res.items():
            accuracy_dict.setdefault(metric, [])
            accuracy_dict[metric].append(vals["accuracy"])
    return steps, accuracy_dict


def plot_curves(steps: List[int], accuracy_dict: Dict[str, List[float]], output: Path, x_log: bool):
    plt.figure(figsize=(10, 6))
    colormap = plt.get_cmap("tab20")
    colors = [colormap(i / max(1, len(accuracy_dict))) for i in range(len(accuracy_dict))]

    for idx, (metric, accuracies) in enumerate(accuracy_dict.items()):
        plt.plot(steps, accuracies, label=metric, color=colors[idx], linestyle="-", linewidth=3)

    plt.xlabel("Checkpoints (Training Steps)")
    plt.ylabel("Accuracy (%)")
    if x_log:
        plt.xscale("log")
    plt.ylim(0, 110)
    plt.grid(True)
    plt.legend()
    plt.tight_layout()

    output.parent.mkdir(parents=True, exist_ok=True)
    plt.savefig(output, dpi=200)
    return output


def maybe_log_wandb(args, steps: List[int], accuracy_dict: Dict[str, List[float]], plot_path: Path):
    if not args.wandb_project:
        return
    try:
        import wandb
    except ImportError as exc:
        raise SystemExit("wandb is not installed. Install with `pip install wandb` or omit --wandb-project.") from exc

    run = wandb.init(
        project=args.wandb_project,
        entity=args.wandb_entity,
        name=args.wandb_run_name,
        config={
            "base_dir": str(args.base_dir),
            "max_checkpoint": args.max_checkpoint,
            "min_interval": args.min_interval,
            "x_log": args.x_log,
        },
    )

    rows = []
    for metric, values in accuracy_dict.items():
        for step, acc in zip(steps, values):
            rows.append([step, metric, acc])
    table = wandb.Table(data=rows, columns=["step", "metric", "accuracy"])
    run.log({"accuracy_table": table})
    run.log({"training_dynamics": wandb.Image(str(plot_path))})
    run.finish()


def parse_args():
    parser = argparse.ArgumentParser(description="Aggregate checkpoint accuracies and plot training dynamics.")
    parser.add_argument("--base-dir", type=Path, required=True, help="Directory containing checkpoint-* subfolders.")
    parser.add_argument("--max-checkpoint", type=int, default=None, help="Only include checkpoints up to this step.")
    parser.add_argument("--min-interval", type=int, default=0, help="Minimum step spacing between sampled checkpoints.")
    parser.add_argument("--x-log", action="store_true", default=False, help="Plot x-axis in log scale.")
    parser.add_argument("--output", type=Path, default=Path("training_dynamics.png"), help="Where to save the plot image.")
    parser.add_argument("--wandb-project", type=str, default=None, help="Weights & Biases project name to log results.")
    parser.add_argument("--wandb-entity", type=str, default=None, help="W&B entity (optional).")
    parser.add_argument("--wandb-run-name", type=str, default=None, help="Custom W&B run name.")
    return parser.parse_args()


def main():
    args = parse_args()
    steps, accuracy_dict = aggregate(args.base_dir, args.max_checkpoint, args.min_interval)
    if not steps:
        raise SystemExit("No checkpoints with all_items.json found.")
    output_path = plot_curves(steps, accuracy_dict, args.output, args.x_log)
    print(f"Saved plot to {output_path}")
    maybe_log_wandb(args, steps, accuracy_dict, output_path)


if __name__ == "__main__":
    main()