#!/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()