File size: 7,470 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
#!/usr/bin/env python3
"""After K=16 screening, sweep three learning rates over the top two methods."""
import json
import shutil
import time
from argparse import Namespace
from pathlib import Path

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

from run_distributed_idea_grid import (
    METHODS, SLUG, TokenCorpus, distributed_run, write_json, GPTConfig,
)

ROOT=Path("/workspace/experiments/distributed_idea_grid")
LR_VALUES=[1e-4,3e-4,9e-4]
K=16
SEED=16384

def read_json(path):
    return json.loads(path.read_text(encoding="utf-8"))

def plot_sweep(runs, baseline_loss, path):
    methods=list(dict.fromkeys(r["method"] for r in runs))
    fig,axes=plt.subplots(1,len(methods),figsize=(6*len(methods),5),sharey=True)
    if len(methods)==1: axes=[axes]
    for ax,method in zip(axes,methods):
        for run in runs:
            if run["method"]!=method: continue
            lr=run["learning_rate"]
            xs=[p["train_tokens"]/1e6 for p in run["val_points"]]
            ys=[p["val_loss"] for p in run["val_points"]]
            ax.plot(xs,ys,label=f"lr={lr:g}")
        ax.axhline(baseline_loss,color="black",ls="--",lw=1)
        ax.set_title(method); ax.set_xlabel("train tokens (millions)")
        ax.set_ylabel("val loss on val.u16"); ax.grid(alpha=.25); ax.legend()
    fig.tight_layout(); fig.savefig(path,dpi=150); plt.close(fig)

def wait_for_screening(results_path, summary_path):
    status=ROOT/"lr_sweep_progress.json"
    while True:
        if results_path.exists() and summary_path.exists():
            try:
                r=read_json(results_path); s=read_json(summary_path)
                if r.get("selection_complete") and len(s)>=5:
                    return r,s
            except (json.JSONDecodeError,OSError):
                pass
        write_json(status,{"stage":"waiting_for_k16_screening","checked_unix":time.time()})
        time.sleep(30)

def main():
    results_path=ROOT/"results.json"
    screen_path=ROOT/"screening_summary.json"
    print("Waiting for K=16 screening to finish...",flush=True)
    screened,screen_summary=wait_for_screening(results_path,screen_path)
    top2=sorted(screen_summary,key=lambda x:x["best_full_val_loss"])[:2]
    methods=[item["method"] for item in top2]
    print("Top two:",methods,flush=True)
    sweep_dir=ROOT/"lr_sweep"
    run_root=sweep_dir/"runs"
    run_root.mkdir(parents=True,exist_ok=True)
    sweep_path=sweep_dir/"lr_sweep_results.json"
    sweep={"metadata":{
        "created_utc":time.time(),"selected_methods":top2,"clients":K,
        "max_epochs":1,"learning_rates":LR_VALUES,
        "server_lr_rule":"APR/RPPD server LR = local LR / 3; other methods have direct server aggregation",
        "selection_metric":"minimum full val.u16 loss within the one-epoch run",
        "ext_val":"method-specific sampled probe/replay only; excluded from validation and selection",
    },"runs":[]}
    if sweep_path.exists():
        old=read_json(sweep_path)
        if old.get("runs"):
            sweep=old
    done={(r["method"],r["learning_rate"]) for r in sweep["runs"]}

    config_path=Path("/workspace/tiny_gpt_config.json")
    cfg=GPTConfig.from_json(config_path)
    cfg.max_seq_len=512
    train_path=Path("/workspace/data/fineweb_text/token_ids/train.u16")
    val_path=Path("/workspace/data/fineweb_text/token_ids/val.u16")
    ext_path=Path("/workspace/data/fineweb_text/token_ids/ext_val.u16")
    train=TokenCorpus(train_path,512)
    val=TokenCorpus(val_path,512)
    ext=TokenCorpus(ext_path,128)
    device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
    target=float(screened["baseline"]["target_val_loss"])

    for method in methods:
        for lr in LR_VALUES:
            if (method,lr) in done:
                print("Skipping completed",method,lr,flush=True)
                continue
            server_lr=lr/3 if method in (
                "Anchored Probe Replay","Replayable Public-Probe Distillation"
            ) else 1e-4
            label=f"{SLUG[method]}_lr_{lr:g}".replace(".","p")
            one_run_dir=run_root/label
            one_run_dir.mkdir(parents=True,exist_ok=True)
            args=Namespace(
                batch_size=32,seq_len=512,local_steps=4,max_epochs=1,
                learning_rate=lr,server_learning_rate=server_lr,
                eval_every_tokens=5_000_000,eval_batches=8,
                probe_batch_size=4,probe_seq_len=128,probe_gate_every=8,
                probe_gate_tolerance=.02,retry_reserve=.03,control_bytes=128,
                measured_train_tokens_per_second=442_157.,
                server_tokens_per_second=442_157.,virtual_seed=2601,
                amp=(device.type=="cuda"),
                train_tokens=str(train_path),ext_val_tokens=str(ext_path),
            )
            print(f"LR sweep {method}, local={lr:g}, server={server_lr:g}",flush=True)
            run=distributed_run(
                method,K,target,args,cfg,train,val,ext,device,SEED,
                one_run_dir/"progress.json",
            )
            run["learning_rate"]=lr
            run["server_learning_rate"]=server_lr
            sweep["runs"].append(run)
            done.add((method,lr))
            write_json(sweep_path,sweep)
            plot_sweep(sweep["runs"],target,sweep_dir/"lr_sweep_val_loss.png")
            print("Finished",method,"lr",lr,
                  "best full val",run["best_full_val_loss"],
                  "tokens",run["train_tokens"],flush=True)

    ranked=sorted(sweep["runs"],key=lambda r:r["best_full_val_loss"])
    winner=ranked[0]
    source=Path(winner["checkpoint_path"])
    final_model=ROOT/"best_model.pt"
    temp=ROOT/"best_model.pt.tmp"
    shutil.copy2(source,temp)
    temp.replace(final_model)
    summary=[{
        "method":r["method"],"clients":r["clients"],
        "learning_rate":r["learning_rate"],
        "server_learning_rate":r["server_learning_rate"],
        "best_full_val_loss":r["best_full_val_loss"],
        "best_full_val_epoch":r["best_full_val_epoch"],
        "goal_reached":r["goal_reached"],
        "train_tokens":r["train_tokens"],
        "actual_wall_seconds":r["actual_wall_seconds"],
        "virtual_time_seconds":r["virtual_time_seconds"],
        "communication_bytes":r["communication"]["total_bytes"],
    } for r in ranked]
    for run in sweep["runs"]:
        if run["method"]==winner["method"] and run["learning_rate"]==winner["learning_rate"]:
            run["checkpoint_path"]=str(final_model)
        else:
            run["checkpoint_path"]=None
    sweep["best_run"]={"method":winner["method"],"clients":K,
        "learning_rate":winner["learning_rate"],
        "server_learning_rate":winner["server_learning_rate"],
        "best_full_val_loss":winner["best_full_val_loss"],
        "checkpoint_path":str(final_model)}
    sweep["selection_complete"]=True
    write_json(sweep_path,sweep)
    write_json(sweep_dir/"lr_sweep_summary.json",summary)

    screened["best_run"]=sweep["best_run"]
    screened["best_model_path"]=str(final_model)
    screened["lr_sweep_complete"]=True
    screened["lr_sweep_summary"]=summary
    screened["runs"]=[winner]
    screened["selection_complete"]=True
    write_json(results_path,screened)
    shutil.rmtree(run_root,ignore_errors=True)
    try:
        (ROOT/"lr_sweep_progress.json").unlink()
    except FileNotFoundError:
        pass
    print("LR sweep complete.",flush=True)

if __name__=="__main__":
    main()