File size: 9,705 Bytes
bbf3a52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Train one small DiLoCo run and plot it against the saved plain B32 baseline."""
from __future__ import annotations

import copy
import json
import math
import time
from pathlib import Path
from typing import Any

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import torch

from run_distributed_idea_grid import TokenCorpus, build_model, eval_ids, train_step, write_json
from tiny_gpt import GPTConfig


def main() -> None:
    root = Path("/workspace")
    out = root / "experiments/distributed_idea_grid/diloco_comparison"
    out.mkdir(parents=True, exist_ok=True)
    base_results_path = root / "experiments/distributed_idea_grid/results.json"
    base_results = json.loads(base_results_path.read_text(encoding="utf-8"))
    baseline = base_results["baseline"]

    cfg = GPTConfig.from_json(str(root / "tiny_gpt_config.json"))
    clients, batch_size, seq_len, local_steps = 16, 32, 512, 4
    seed, inner_lr, outer_lr, outer_momentum = 16384, 3e-4, 0.7, 0.9
    eval_every_tokens, eval_batches = 5_000_000, 8
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    amp = device.type == "cuda"
    torch.manual_seed(seed)

    train = TokenCorpus(root / "data/fineweb_text/token_ids/train.u16", seq_len)
    val = TokenCorpus(root / "data/fineweb_text/token_ids/val.u16", seq_len)
    batch_count = train.n_sequences // batch_size
    order = np.random.default_rng(seed + 1).permutation(train.n_sequences)
    order = order[:batch_count * batch_size]
    subset = np.arange(min(eval_batches * batch_size, val.n_sequences), dtype=np.int64)
    full_ids = np.arange(val.n_sequences, dtype=np.int64)

    global_model = build_model(cfg, "plain", seed).to(device)
    global_params = list(global_model.parameters())
    # The replicas keep independent AdamW moments while the model parameters are
    # overwritten from the global model at each communication round, as in DiLoCo.
    workers = [copy.deepcopy(global_model).to(device) for _ in range(clients)]
    worker_opts = [
        torch.optim.AdamW(w.parameters(), lr=inner_lr, fused=(device.type == "cuda"))
        for w in workers
    ]
    outer_opt = torch.optim.SGD(
        global_params, lr=outer_lr, momentum=outer_momentum, nesterov=True
    )

    # Each worker receives every 16th baseline batch. Together they consume the
    # same shuffled batch sequence as the plain baseline, exactly once.
    points: list[dict[str, Any]] = []
    train_tokens = 0
    next_eval = eval_every_tokens
    actual_start = time.perf_counter()
    rounds = math.ceil(batch_count / (clients * local_steps))
    progress_path = out / "progress.json"

    for round_idx in range(rounds):
        base = [p.detach().clone() for p in global_params]
        delta_sum = [torch.zeros_like(p) for p in global_params]
        for cid, (worker, opt) in enumerate(zip(workers, worker_opts)):
            worker.load_state_dict(global_model.state_dict())
            for local_idx in range(local_steps):
                batch_idx = round_idx * clients * local_steps + local_idx * clients + cid
                if batch_idx >= batch_count:
                    break
                lo = batch_idx * batch_size
                ids = order[lo:lo + batch_size]
                x = train.batch(ids, device)
                train_step(worker, opt, list(worker.parameters()), x, amp)
                train_tokens += int(x.numel())
            # Delta is the pseudo-gradient used by DiLoCo's outer optimizer.
            with torch.no_grad():
                for i, (acc, global_p, local_p) in enumerate(zip(delta_sum, global_params, worker.parameters())):
                    # Use the round-start global parameters, not the current copy.
                    acc.add_(base[i] - local_p.detach())

        with torch.no_grad():
            for p, total_delta in zip(global_params, delta_sum):
                p.grad = (total_delta / clients).to(dtype=p.dtype)
        outer_opt.step()
        outer_opt.zero_grad(set_to_none=True)

        if train_tokens >= next_eval:
            loss, val_tokens = eval_ids(global_model, val, subset, batch_size, device, amp)
            points.append({
                "kind": "frequent_sample",
                "train_tokens": train_tokens,
                "val_loss": loss,
                "val_tokens_evaluated": val_tokens,
                "outer_round": round_idx + 1,
                "actual_wall_seconds": time.perf_counter() - actual_start,
            })
            next_eval += eval_every_tokens

        if (round_idx + 1) % 10 == 0 or round_idx + 1 == rounds:
            if device.type == "cuda":
                torch.cuda.synchronize()
            status = {
                "stage": "diloco",
                "round": round_idx + 1,
                "total_rounds": rounds,
                "train_tokens": train_tokens,
                "val_points": points,
                "actual_wall_seconds": time.perf_counter() - actual_start,
            }
            write_json(progress_path, status)
            print(
                f"DiLoCo round {round_idx + 1}/{rounds}: "
                f"{train_tokens / 1e6:.1f}M tokens, "
                f"latest sample val={points[-1]['val_loss']:.4f}" if points else
                f"DiLoCo round {round_idx + 1}/{rounds}: {train_tokens / 1e6:.1f}M tokens",
                flush=True,
            )

    full_loss, full_val_tokens = eval_ids(global_model, val, full_ids, batch_size, device, amp)
    points.append({
        "kind": "epoch1_full_val",
        "train_tokens": train_tokens,
        "val_loss": full_loss,
        "val_tokens_evaluated": full_val_tokens,
        "outer_round": rounds,
        "actual_wall_seconds": time.perf_counter() - actual_start,
    })
    if device.type == "cuda":
        torch.cuda.synchronize()
    elapsed = time.perf_counter() - actual_start

    run = {
        "method": "DiLoCo",
        "clients": clients,
        "batch_size_per_client": batch_size,
        "local_steps_per_sync": local_steps,
        "outer_rounds": rounds,
        "epochs": 1,
        "train_tokens": train_tokens,
        "inner_optimizer": "AdamW",
        "inner_learning_rate": inner_lr,
        "inner_weight_decay": 0.01,
        "inner_optimizer_state": "persistent per worker across synchronization rounds",
        "outer_optimizer": "Nesterov SGD",
        "outer_learning_rate": outer_lr,
        "outer_momentum": outer_momentum,
        "actual_wall_seconds": elapsed,
        "target_val_loss": baseline["target_val_loss"],
        "final_full_val_loss": full_loss,
        "val_points": points,
        "validation_corpus": "val.u16",
        "data_order": "same shuffled sequence order as plain B32 baseline; batches distributed round-robin across 16 clients",
        "initialization_seed": seed,
        "implementation_note": "Tiny-data DiLoCo-style run with H=4 to match the distributed experiment setup; paper's default H=500 is not practical for this one-epoch comparison.",
    }
    write_json(out / "diloco_results.json", run)
    torch.save({
        "state_dict": {k: v.detach().cpu() for k, v in global_model.state_dict().items()},
        "model_config": cfg.__dict__,
        "method": "DiLoCo",
        "clients": clients,
        "full_val_loss": full_loss,
    }, out / "diloco_model.pt")

    comparison = {
        "baseline": {
            "method": "Plain batch-32 baseline",
            "train_tokens": baseline["train_tokens"],
            "full_val_loss": baseline["target_val_loss"],
            "val_points": baseline["val_points"],
            "actual_wall_seconds": baseline["actual_wall_seconds"],
            "learning_rate": base_results["metadata"]["learning_rate"],
        },
        "diloco": run,
        "validation_note": "Frequent points use the fixed 8-batch val.u16 sample; epoch-end points use all val.u16.",
    }
    write_json(out / "diloco_vs_baseline.json", comparison)

    fig, ax = plt.subplots(figsize=(10.5, 6.2), constrained_layout=True)
    colors = {"baseline": "#2463a6", "diloco": "#d97706"}
    for key, label, data in (
        ("baseline", "Plain B32 baseline", baseline),
        ("diloco", "DiLoCo (K=16, H=4)", run),
    ):
        samples = [p for p in data["val_points"] if p["kind"] == "frequent_sample"]
        full = [p for p in data["val_points"] if p["kind"] in ("baseline_epoch1_full", "epoch1_full_val")]
        ax.plot(
            [p["train_tokens"] / 1e6 for p in samples],
            [p["val_loss"] for p in samples],
            color=colors[key], linewidth=1.8, marker="o", markersize=3.5,
            label=f"{label} (8-batch val sample)",
        )
        if full:
            ax.scatter(
                [full[0]["train_tokens"] / 1e6], [full[0]["val_loss"]],
                color=colors[key], edgecolor="black", linewidth=0.7, s=72, marker="D",
                zorder=5, label=f"{label} (full val: {full[0]['val_loss']:.3f})",
            )
    ax.set_title("DiLoCo vs Plain Batch-32 Baseline")
    ax.set_xlabel("Training tokens processed (millions)")
    ax.set_ylabel("Validation loss (val.u16)")
    ax.grid(alpha=0.25)
    ax.legend(fontsize=8, ncols=2)
    ax.text(
        0.01, 0.02,
        "Same initialization and shuffled data order 路 K=16 路 local batch=32 路 H=4 路 1 epoch",
        transform=ax.transAxes, fontsize=8, color="#444444",
    )
    fig.savefig(out / "diloco_vs_baseline.png", dpi=180)
    plt.close(fig)
    print(
        f"Completed: baseline full val={baseline['target_val_loss']:.6f}; "
        f"DiLoCo full val={full_loss:.6f}; elapsed={elapsed / 60:.1f} min",
        flush=True,
    )


if __name__ == "__main__":
    main()