Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

feat(optim): Muon optimizer and WSD / linear schedules

FareedKhan-dev4b52229f4502
diff --git a/src/optim/__init__.py b/src/optim/__init__.py
new file mode 100644
index 0000000..b5651e4
--- /dev/null
+++ b/src/optim/__init__.py
@@ -0,0 +1,48 @@
+"""Optimizers and learning-rate schedules: AdamW (with the GPT weight-decay split) and Muon."""
+
+from __future__ import annotations
+
+import torch
+import torch.nn as nn
+
+from src.optim.muon import Muon, muon_param_groups, newton_schulz
+from src.optim.schedules import cosine_lr, linear_lr, lr_at, set_lr, wsd_lr
+
+
+def adamw_param_groups(model: nn.Module, weight_decay: float) -> list[dict]:
+ """Decay the >=2D weight matrices, not biases / norms / 1D params (the standard GPT recipe)."""
+ decay, no_decay = [], []
+ for p in model.parameters():
+ if not p.requires_grad:
+ continue
+ (decay if p.dim() >= 2 else no_decay).append(p)
+ return [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0.0}]
+
+
+def build_optimizer(
+ model: nn.Module,
+ name: str = "adamw",
+ lr: float = 3e-4,
+ weight_decay: float = 0.1,
+ betas: tuple[float, float] = (0.9, 0.95),
+) -> torch.optim.Optimizer:
+ """``"adamw"`` or ``"muon"`` (Muon on hidden matrices, AdamW on everything else)."""
+ if name == "adamw":
+ return torch.optim.AdamW(adamw_param_groups(model, weight_decay), lr=lr, betas=betas)
+ if name == "muon":
+ return Muon(muon_param_groups(model, weight_decay), lr=lr, weight_decay=weight_decay, betas=betas)
+ raise ValueError(f"unknown optimizer {name!r}; expected 'adamw' or 'muon'")
+
+
+__all__ = [
+ "Muon",
+ "adamw_param_groups",
+ "build_optimizer",
+ "cosine_lr",
+ "linear_lr",
+ "lr_at",
+ "muon_param_groups",
+ "newton_schulz",
+ "set_lr",
+ "wsd_lr",
+]
diff --git a/src/optim/muon.py b/src/optim/muon.py
new file mode 100644
index 0000000..b258018
--- /dev/null
+++ b/src/optim/muon.py
@@ -0,0 +1,170 @@
+"""
+Muon: momentum + orthogonalized updates (Jordan et al. 2024), written from scratch.
+
+Adam treats every number of a weight matrix independently. Muon treats a weight matrix as a
+matrix. It keeps an ordinary momentum buffer ``M`` of the gradient, but instead of stepping
+along ``M`` it steps along the *orthogonalized* ``M``: the closest matrix whose singular
+values are all 1 (``U V^T`` if ``M = U S V^T``). Every direction the gradient points in gets
+the same step size, so rare but useful directions are not drowned out by a few dominant ones.
+
+Computing an SVD every step would be slow, so Muon uses a few Newton-Schulz iterations,
+cheap matrix multiplications that push all singular values toward 1:
+
+ X <- a X + b (X X^T) X + c (X X^T)^2 X (a, b, c) = (3.4445, -4.7750, 2.0315)
+
+Muon trained nanoGPT speedruns faster than AdamW and was scaled to a 1T parameter model
+(Kimi K2, with "MuonClip"). It only makes sense for 2D hidden matrices; embeddings, the
+output layer, norms and biases keep using AdamW. This class does both, so it drops into any
+training loop that expects one optimizer.
+
+Learning-rate scale: with ``adjust_lr="match_rms_adamw"`` (Liu et al. 2025, "Muon is
+Scalable for LLM Training") the Muon update is rescaled to the size of a typical AdamW
+update, so the *same* learning rate and weight decay work for both parameter groups. That is
+the default here, because it lets the existing LR schedules drive Muon unchanged.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Iterable
+from typing import Any, Literal
+
+import torch
+import torch.nn as nn
+from jaxtyping import Float
+from torch import Tensor
+
+NS_COEFFICIENTS = (3.4445, -4.7750, 2.0315)
+AdjustLR = Literal["match_rms_adamw", "original"]
+
+
+def newton_schulz(
+ G: Float[Tensor, "rows cols"],
+ steps: int = 5,
+ eps: float = 1e-7,
+ coefficients: tuple[float, float, float] = NS_COEFFICIENTS,
+ dtype: torch.dtype = torch.bfloat16,
+) -> Float[Tensor, "rows cols"]:
+ """Approximately orthogonalize ``G`` (all singular values pushed to about 1)."""
+ a, b, c = coefficients
+ X = G.to(dtype)
+ transposed = G.size(0) > G.size(1)
+ if transposed: # iterate on the wide orientation, so X @ X.T is the small Gram matrix
+ X = X.T
+ X = X / X.norm().clamp(min=eps) # the Frobenius norm bounds the spectral norm: start <= 1
+ for _ in range(steps):
+ A = X @ X.T
+ B = b * A + c * (A @ A)
+ X = a * X + B @ X
+ return X.T if transposed else X
+
+
+def adjusted_lr(lr: float, shape: torch.Size, mode: AdjustLR) -> float:
+ rows, cols = shape[0], shape[1]
+ if mode == "match_rms_adamw":
+ return lr * 0.2 * math.sqrt(max(rows, cols))
+ return lr * math.sqrt(max(1.0, rows / cols))
+
+
+class Muon(torch.optim.Optimizer):
+ """
+ Muon for parameter groups with ``use_muon=True``, AdamW for the others.
+
+ Build the groups with :func:`muon_param_groups`, or pass your own list of dicts.
+ """
+
+ def __init__(
+ self,
+ params: Iterable[dict[str, Any]],
+ lr: float = 3e-4,
+ weight_decay: float = 0.0,
+ momentum: float = 0.95,
+ nesterov: bool = True,
+ ns_steps: int = 5,
+ adjust_lr: AdjustLR = "match_rms_adamw",
+ betas: tuple[float, float] = (0.9, 0.95),
+ eps: float = 1e-8,
+ ) -> None:
+ defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, nesterov=nesterov,
+ ns_steps=ns_steps, adjust_lr=adjust_lr, betas=betas, eps=eps, use_muon=True)
+ super().__init__(params, defaults)
+ for group in self.param_groups:
+ if group["use_muon"] and any(p.ndim != 2 for p in group["params"]):
+ raise ValueError("Muon groups may only hold 2D weight matrices; put the rest in an AdamW group")
+
+ @torch.no_grad()
+ def step(self, closure: Callable[[], float] | None = None) -> float | None: # type: ignore[override]
+ loss = None
+ if closure is not None:
+ with torch.enable_grad():
+ loss = closure()
+ for group in self.param_groups:
+ if group["use_muon"]:
+ self._muon_step(group)
+ else:
+ self._adamw_step(group)
+ return loss
+
+ def _muon_step(self, group: dict[str, Any]) -> None:
+ for p in group["params"]:
+ if p.grad is None:
+ continue
+ state = self.state[p]
+ if "momentum_buffer" not in state:
+ state["momentum_buffer"] = torch.zeros_like(p.grad)
+ buf = state["momentum_buffer"]
+ buf.lerp_(p.grad, 1 - group["momentum"]) # buf = momentum * buf + (1 - momentum) * grad
+ update = p.grad.lerp(buf, group["momentum"]) if group["nesterov"] else buf
+ update = newton_schulz(update, group["ns_steps"]).to(p.dtype)
+ p.mul_(1 - group["lr"] * group["weight_decay"]) # decoupled weight decay, as in AdamW
+ p.add_(update, alpha=-adjusted_lr(group["lr"], p.shape, group["adjust_lr"]))
+
+ def _adamw_step(self, group: dict[str, Any]) -> None:
+ beta1, beta2 = group["betas"]
+ for p in group["params"]:
+ if p.grad is None:
+ continue
+ state = self.state[p]
+ if "step" not in state:
+ state["step"] = 0
+ state["exp_avg"] = torch.zeros_like(p)
+ state["exp_avg_sq"] = torch.zeros_like(p)
+ state["step"] += 1
+ m, v = state["exp_avg"], state["exp_avg_sq"]
+ m.lerp_(p.grad, 1 - beta1)
+ v.mul_(beta2).addcmul_(p.grad, p.grad, value=1 - beta2)
+ bias1 = 1 - beta1 ** state["step"]
+ bias2 = 1 - beta2 ** state["step"]
+ p.mul_(1 - group["lr"] * group["weight_decay"])
+ denom = (v / bias2).sqrt_().add_(group["eps"])
+ p.addcdiv_(m, denom, value=-group["lr"] / bias1)
+
+
+def muon_param_groups(model: nn.Module, weight_decay: float) -> list[dict[str, Any]]:
+ """
+ Split ``model`` into a Muon group (2D hidden weight matrices) and an AdamW group
+ (embeddings, the output layer, norms, biases). Matches the usual Muon recipe.
+ """
+ skip: set[int] = set()
+ for module in model.modules():
+ if isinstance(module, nn.Embedding):
+ skip.update(id(p) for p in module.parameters())
+ lm_head = getattr(model, "lm_head", None)
+ if isinstance(lm_head, nn.Module):
+ skip.update(id(p) for p in lm_head.parameters())
+
+ muon, adam_decay, adam_no_decay = [], [], []
+ for p in model.parameters():
+ if not p.requires_grad:
+ continue
+ if p.ndim == 2 and id(p) not in skip:
+ muon.append(p)
+ elif p.ndim >= 2:
+ adam_decay.append(p)
+ else:
+ adam_no_decay.append(p)
+ return [
+ {"params": muon, "use_muon": True, "weight_decay": weight_decay},
+ {"params": adam_decay, "use_muon": False, "weight_decay": weight_decay},
+ {"params": adam_no_decay, "use_muon": False, "weight_decay": 0.0},
+ ]
diff --git a/src/optim/schedules.py b/src/optim/schedules.py
new file mode 100644
index 0000000..9e199af
--- /dev/null
+++ b/src/optim/schedules.py
@@ -0,0 +1,81 @@
+"""
+Learning-rate schedules. Each one is a pure function ``step -> learning rate``.
+
+- ``cosine``: linear warmup, then a cosine curve down to ``min_lr`` (GPT-3, Llama 2).
+- ``wsd``: warmup, then a long *stable* phase at the peak rate, then a short linear *decay*
+ over the last ``decay_frac`` of training (MiniCPM, DeepSeek, OLMo 2 annealing). The big
+ practical win: a checkpoint from the stable phase can be annealed at any time, so you do
+ not need to fix the training length in advance.
+- ``linear``: warmup, then a straight line to ``min_lr``. Decaying all the way to zero this
+ way matches or beats cosine in recent studies ("Straight to Zero", Bergsma et al. 2025).
+
+Every schedule warms up linearly for ``warmup_steps``: Adam's second-moment estimates are
+poor in the first steps, and a full-size step then can wreck a fresh model.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Literal
+
+import torch
+
+Schedule = Literal["cosine", "wsd", "linear"]
+
+
+def _warmup(step: int, warmup_steps: int, lr: float) -> float | None:
+ return lr * (step + 1) / max(1, warmup_steps) if step < warmup_steps else None
+
+
+def cosine_lr(step: int, *, warmup_steps: int, max_steps: int, lr: float, min_lr: float) -> float:
+ """Linear warmup to ``lr`` over ``warmup_steps``, then cosine decay to ``min_lr`` by
+ ``max_steps`` (constant ``min_lr`` afterwards)."""
+ warm = _warmup(step, warmup_steps, lr)
+ if warm is not None:
+ return warm
+ if step >= max_steps:
+ return min_lr
+ progress = (step - warmup_steps) / max(1, max_steps - warmup_steps)
+ coeff = 0.5 * (1.0 + math.cos(math.pi * progress))
+ return min_lr + coeff * (lr - min_lr)
+
+
+def wsd_lr(
+ step: int, *, warmup_steps: int, max_steps: int, lr: float, min_lr: float, decay_frac: float = 0.2
+) -> float:
+ """Warmup, stay at ``lr``, then decay linearly to ``min_lr`` over the last ``decay_frac``."""
+ warm = _warmup(step, warmup_steps, lr)
+ if warm is not None:
+ return warm
+ decay_start = max(warmup_steps, int(max_steps * (1.0 - decay_frac)))
+ if step < decay_start:
+ return lr
+ if step >= max_steps:
+ return min_lr
+ progress = (step - decay_start) / max(1, max_steps - decay_start)
+ return lr + progress * (min_lr - lr)
+
+
+def linear_lr(step: int, *, warmup_steps: int, max_steps: int, lr: float, min_lr: float) -> float:
+ """Warmup, then a straight line from ``lr`` to ``min_lr`` at ``max_steps``."""
+ warm = _warmup(step, warmup_steps, lr)
+ if warm is not None:
+ return warm
+ if step >= max_steps:
+ return min_lr
+ progress = (step - warmup_steps) / max(1, max_steps - warmup_steps)
+ return lr + progress * (min_lr - lr)
+
+
+def lr_at(schedule: Schedule, step: int, *, warmup_steps: int, max_steps: int, lr: float, min_lr: float) -> float:
+ """Dispatch to the schedule called ``schedule``."""
+ fn = {"cosine": cosine_lr, "wsd": wsd_lr, "linear": linear_lr}.get(schedule)
+ if fn is None:
+ raise ValueError(f"unknown lr schedule {schedule!r}")
+ return fn(step, warmup_steps=warmup_steps, max_steps=max_steps, lr=lr, min_lr=min_lr)
+
+
+def set_lr(optimizer: torch.optim.Optimizer, lr: float) -> None:
+ """Set the learning rate of every parameter group (respecting an optional ``lr_scale``)."""
+ for group in optimizer.param_groups:
+ group["lr"] = lr * group.get("lr_scale", 1.0)
diff --git a/src/post_training/optim.py b/src/post_training/optim.py
index 567f512..904ae49 100644
--- a/src/post_training/optim.py
+++ b/src/post_training/optim.py
@@ -2,17 +2,23 @@
Optimizer and learning-rate-schedule helpers shared across stages.
- ``configure_optimizer`` builds AdamW with the standard weight-decay split (decay the 2D
- weight matrices, don't decay biases / LayerNorm / embeddings).
+ weight matrices, don't decay biases / LayerNorm / 1D params).
- ``cosine_lr`` is a linear-warmup + cosine-decay schedule returning the LR for a step.
+
+Both now live in :mod:`src.optim` (next to Muon and the WSD / linear schedules) and are
+re-exported here so existing imports keep working.
"""
from __future__ import annotations
-import math
-
import torch
import torch.nn as nn
+from src.optim import adamw_param_groups, build_optimizer, lr_at, set_lr
+from src.optim.schedules import cosine_lr
+
+__all__ = ["build_optimizer", "configure_optimizer", "cosine_lr", "lr_at", "set_lr"]
+
def configure_optimizer(
model: nn.Module,
@@ -22,28 +28,4 @@ def configure_optimizer(
) -> torch.optim.AdamW:
"""AdamW with weight decay applied only to >=2D parameters (matrices), not to
biases / norms / 1D params. Standard GPT recipe."""
- decay, no_decay = [], []
- for name, p in model.named_parameters():
- if not p.requires_grad:
- continue
- if p.dim() >= 2:
- decay.append(p)
- else:
- no_decay.append(p)
- groups = [
- {"params": decay, "weight_decay": weight_decay},
- {"params": no_decay, "weight_decay": 0.0},
- ]
- return torch.optim.AdamW(groups, lr=lr, betas=betas)
-
-
-def cosine_lr(step: int, *, warmup_steps: int, max_steps: int, lr: float, min_lr: float) -> float:
- """Linear warmup to ``lr`` over ``warmup_steps``, then cosine decay to ``min_lr`` by
- ``max_steps`` (constant ``min_lr`` afterwards)."""
- if step < warmup_steps:
- return lr * (step + 1) / max(1, warmup_steps)
- if step >= max_steps:
- return min_lr
- progress = (step - warmup_steps) / max(1, max_steps - warmup_steps)
- coeff = 0.5 * (1.0 + math.cos(math.pi * progress))
- return min_lr + coeff * (lr - min_lr)
+ return torch.optim.AdamW(adamw_param_groups(model, weight_decay), lr=lr, betas=betas)
diff --git a/tests/test_optim.py b/tests/test_optim.py
new file mode 100644
index 0000000..321c780
--- /dev/null
+++ b/tests/test_optim.py
@@ -0,0 +1,97 @@
+"""Muon, the AdamW fallback inside it, and the learning-rate schedules."""
+
+from __future__ import annotations
+
+import pytest
+import torch
+
+from src.models.modern import ModernConfig, ModernTransformer
+from src.models.transformer import Transformer
+from src.optim import Muon, build_optimizer, cosine_lr, linear_lr, lr_at, muon_param_groups, newton_schulz, wsd_lr
+
+
+def test_newton_schulz_flattens_the_singular_values() -> None:
+ torch.manual_seed(0)
+ G = torch.randn(32, 64) @ torch.diag(torch.logspace(-2, 1, 64)) # badly conditioned
+ s_before = torch.linalg.svdvals(G)
+ s_after = torch.linalg.svdvals(newton_schulz(G, steps=5, dtype=torch.float32))
+ assert s_before.max() / s_before.min() > 50
+ assert s_after.min() > 0.3 and s_after.max() < 1.3 # Muon's quintic lands in roughly [0.5, 1.5]
+ tall = newton_schulz(torch.randn(64, 16), dtype=torch.float32)
+ assert tall.shape == (64, 16)
+
+
[email protected](not hasattr(torch.optim, "Muon"), reason="torch.optim.Muon needs PyTorch >= 2.9")
+def test_muon_matches_pytorch_reference() -> None:
+ torch.manual_seed(0)
+ start = torch.randn(24, 40)
+ w_ours = torch.nn.Parameter(start.clone())
+ w_ref = torch.nn.Parameter(start.clone())
+ ours = Muon([{"params": [w_ours], "use_muon": True}], lr=0.01, weight_decay=0.1)
+ ref = torch.optim.Muon([w_ref], lr=0.01, weight_decay=0.1, adjust_lr_fn="match_rms_adamw")
+ for _ in range(3):
+ g = torch.randn(24, 40)
+ for w, opt in ((w_ours, ours), (w_ref, ref)):
+ w.grad = g.clone()
+ opt.step()
+ # Both run Newton-Schulz in bfloat16, but PyTorch fuses the steps into addmm, so rounding
+ # differs slightly. Compare the total update: same direction and the same size within 1%.
+ d_ours, d_ref = (w_ours - start).flatten(), (w_ref - start).flatten()
+ assert torch.nn.functional.cosine_similarity(d_ours, d_ref, dim=0) > 0.999
+ assert abs(d_ours.norm() / d_ref.norm() - 1) < 0.01
+
+
+def test_muon_adamw_groups_match_torch_adamw() -> None:
+ torch.manual_seed(0)
+ p_ours = torch.nn.Parameter(torch.randn(10))
+ p_ref = torch.nn.Parameter(p_ours.detach().clone())
+ ours = Muon([{"params": [p_ours], "use_muon": False}], lr=1e-2, weight_decay=0.1, betas=(0.9, 0.95))
+ ref = torch.optim.AdamW([p_ref], lr=1e-2, weight_decay=0.1, betas=(0.9, 0.95), eps=1e-8)
+ for _ in range(5):
+ g = torch.randn(10)
+ for p, opt in ((p_ours, ours), (p_ref, ref)):
+ p.grad = g.clone()
+ opt.step()
+ assert torch.allclose(p_ours, p_ref, atol=1e-6)
+
+
+def test_muon_groups_keep_embeddings_and_head_on_adamw() -> None:
+ model = ModernTransformer(ModernConfig(vocab_size=64, context_length=16, n_embed=32, n_head=4, n_blocks=2))
+ muon, adam_decay, adam_no_decay = muon_param_groups(model, weight_decay=0.1)
+ embed_id = id(model.token_embed.weight)
+ assert embed_id not in {id(p) for p in muon["params"]}
+ assert embed_id in {id(p) for p in adam_decay["params"]}
+ assert all(p.ndim == 2 for p in muon["params"]) and all(p.ndim == 1 for p in adam_no_decay["params"])
+ n_grouped = sum(len(g["params"]) for g in (muon, adam_decay, adam_no_decay))
+ assert n_grouped == len(list(model.parameters()))
+
+
[email protected]("name", ["adamw", "muon"])
+def test_both_optimizers_train_a_tiny_model(name: str) -> None:
+ torch.manual_seed(0)
+ model = Transformer(n_head=4, n_embed=32, context_length=16, vocab_size=50, N_BLOCKS=2)
+ opt = build_optimizer(model, name, lr=3e-3, weight_decay=0.0)
+ data = torch.randint(0, 50, (8, 17))
+ losses = []
+ for _ in range(40):
+ _, loss = model(data[:, :-1], data[:, 1:])
+ opt.zero_grad()
+ loss.backward()
+ opt.step()
+ losses.append(loss.item())
+ assert losses[-1] < 0.6 * losses[0] # memorizes the fixed batch
+
+
+def test_schedules_hit_their_anchor_points() -> None:
+ kw = dict(warmup_steps=10, max_steps=110, lr=1.0, min_lr=0.1)
+ for fn in (cosine_lr, wsd_lr, linear_lr):
+ assert fn(0, **kw) == pytest.approx(0.1) # first warmup step
+ assert fn(9, **kw) == pytest.approx(1.0) # end of warmup
+ assert fn(110, **kw) == pytest.approx(0.1) and fn(500, **kw) == pytest.approx(0.1)
+ assert cosine_lr(60, **kw) == pytest.approx(0.55) # halfway down the cosine
+ assert linear_lr(60, **kw) == pytest.approx(0.55)
+ assert wsd_lr(80, **kw) == pytest.approx(1.0) # still in the stable phase
+ assert wsd_lr(99, **kw) == pytest.approx(0.55, abs=0.03) # halfway through the final 20%
+ assert lr_at("wsd", 80, **kw) == wsd_lr(80, **kw)
+ with pytest.raises(ValueError):
+ lr_at("constant", 0, **kw) # type: ignore[arg-type]