dist_methods / code /run_distributed_idea_muon.py
Ilikemechuri's picture
Add distributed training experiment code and results
bbf3a52 verified
Raw History Blame Contribute Delete
7.14 kB
#!/usr/bin/env python3
"""After LR screening, compare the top two methods with PyTorch Muon."""
import json
import shutil
import time
from argparse import Namespace
from pathlib import Path
import torch
from run_distributed_idea_grid import (
SLUG, TokenCorpus, distributed_run, write_json, GPTConfig,
)
ROOT=Path("/workspace/experiments/distributed_idea_grid")
K=16
SEED=16384
MUON_LR=0.02
def read_json(path):
return json.loads(path.read_text(encoding="utf-8"))
def wait_for_lr_sweep():
root_results=ROOT/"results.json"
lr_results=ROOT/"lr_sweep"/"lr_sweep_results.json"
status=ROOT/"muon_progress.json"
while True:
if root_results.exists() and lr_results.exists():
try:
root=read_json(root_results)
sweep=read_json(lr_results)
if root.get("lr_sweep_complete") and sweep.get("selection_complete"):
return root,sweep
except (json.JSONDecodeError,OSError):
pass
write_json(status,{"stage":"waiting_for_lr_sweep","checked_unix":time.time()})
time.sleep(30)
def main():
print("Waiting for LR sweep to finish...",flush=True)
root_results,sweep=wait_for_lr_sweep()
by_method={}
for row in sweep["runs"]:
current=by_method.get(row["method"])
if current is None or row["best_full_val_loss"]<current["best_full_val_loss"]:
by_method[row["method"]]=row
selected=sorted(by_method.values(),key=lambda r:r["best_full_val_loss"])[:2]
print("Muon methods:",[r["method"] for r in selected],flush=True)
out=ROOT/"muon_stage"
run_root=out/"runs"
run_root.mkdir(parents=True,exist_ok=True)
result_path=out/"muon_results.json"
target=float(root_results["baseline"]["target_val_loss"])
if result_path.exists():
results=read_json(result_path)
else:
results={"metadata":{
"clients":K,"max_epochs":1,"optimizer":"torch.optim.Muon for hidden-layer matrices; AdamW for embeddings, biases and norms",
"muon_lr":MUON_LR,"adamw_lr_source":"best local LR per method from prior LR sweep",
"early_stop":"full val.u16 confirmation at baseline one-epoch loss; otherwise one-epoch cap",
},"runs":[]}
done={r["method"] for r in results["runs"]}
cfg=GPTConfig.from_json("/workspace/tiny_gpt_config.json")
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")
for chosen in selected:
method=chosen["method"]
if method in done:
print("Skipping completed Muon method",method,flush=True)
continue
local_lr=float(chosen["learning_rate"])
server_lr=float(chosen["server_learning_rate"])
label=SLUG[method]+"_muon"
run_dir=run_root/label
run_dir.mkdir(parents=True,exist_ok=True)
args=Namespace(
batch_size=32,seq_len=512,local_steps=4,max_epochs=1,
learning_rate=local_lr,server_learning_rate=server_lr,
optimizer_mode="muon",
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("Muon run",method,"local AdamW LR",local_lr,"server AdamW LR",server_lr,flush=True)
run=distributed_run(
method,K,target,args,cfg,train,val,ext,device,SEED,run_dir/"progress.json"
)
run["local_adamw_fallback_lr"]=local_lr
run["server_adamw_fallback_lr"]=server_lr
run["muon_matrix_lr"]=MUON_LR
results["runs"].append(run)
done.add(method)
write_json(result_path,results)
print("Finished Muon",method,"best full val",run["best_full_val_loss"],flush=True)
best_muon=min(results["runs"],key=lambda r:r["best_full_val_loss"])
prior_best=root_results["best_run"]
prior_loss=float(prior_best["best_full_val_loss"])
final_model=ROOT/"best_model.pt"
muon_beats=best_muon["best_full_val_loss"]<prior_loss
if muon_beats:
source=Path(best_muon["checkpoint_path"])
temp=ROOT/"best_model.pt.tmp"
shutil.copy2(source,temp)
temp.replace(final_model)
summary=[{
"method":r["method"],"clients":K,"optimizer":"Muon+AdamW",
"muon_matrix_lr":MUON_LR,
"local_adamw_fallback_lr":r["local_adamw_fallback_lr"],
"server_adamw_fallback_lr":r["server_adamw_fallback_lr"],
"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 sorted(results["runs"],key=lambda x:x["best_full_val_loss"])]
for r in results["runs"]:
if muon_beats and r["method"]==best_muon["method"]:
r["checkpoint_path"]=str(final_model)
else:
r["checkpoint_path"]=None
results["summary"]=summary
results["best_muon_run"]={
"method":best_muon["method"],"clients":K,
"best_full_val_loss":best_muon["best_full_val_loss"],
"muon_matrix_lr":MUON_LR,
"local_adamw_fallback_lr":best_muon["local_adamw_fallback_lr"],
}
results["muon_beats_previous_best"]=muon_beats
results["selection_complete"]=True
write_json(result_path,results)
write_json(out/"muon_summary.json",summary)
root_results["muon_stage_complete"]=True
root_results["muon_summary"]=summary
root_results["muon_beats_previous_best"]=muon_beats
if muon_beats:
best_muon["checkpoint_path"]=str(final_model)
root_results["best_run"]={
"method":best_muon["method"],"clients":K,
"best_full_val_loss":best_muon["best_full_val_loss"],
"best_full_val_epoch":best_muon["best_full_val_epoch"],
"optimizer":"Muon+AdamW",
"muon_matrix_lr":MUON_LR,
"local_adamw_fallback_lr":best_muon["local_adamw_fallback_lr"],
"checkpoint_path":str(final_model),
}
root_results["runs"]=[best_muon]
write_json(ROOT/"results.json",root_results)
shutil.rmtree(run_root,ignore_errors=True)
try:
(ROOT/"muon_progress.json").unlink()
except FileNotFoundError:
pass
print("Muon stage complete; improved previous best:",muon_beats,flush=True)
if __name__=="__main__":
main()