Skip to content

A TTS that fits in your CPU (and pocket)

Python

Training: Muon as an optional optimizer (#314)

manu-lme023ae935c83
diff --git a/training/args.py b/training/args.py
index cacf3a5..987b9af 100644
--- a/training/args.py
+++ b/training/args.py
@@ -63,6 +63,20 @@ class OptimArgs:
# a cosine fine-tune.
schedule: str = "constant"
lr_min_ratio: float = 0.0
+ # "adamw", or "muon": Newton-Schulz orthogonalized momentum on the backbone's 2D
+ # weights (the fused q/k/v projection orthogonalized as three blocks), AdamW on
+ # everything else. muon_lr is the Muon step size; the AdamW groups keep `lr`, and
+ # the schedule applies to both. muon_head also puts the sampler head's 2D weights
+ # under Muon (useful for head-only fine-tunes).
+ type: str = "adamw"
+ muon_lr: float = 0.005
+ muon_momentum: float = 0.95
+ muon_head: bool = False
+ # Scale the orthogonal update by 0.2 * sqrt(max(rows, cols)) so its RMS matches AdamW's
+ # (Liu et al. 2025) instead of sqrt(max(1, rows / cols)); with it, muon_lr should equal lr.
+ muon_rms_match: bool = False
+ # Polar Express iterations; 6 reaches singular values within 1%, fewer is cheaper but looser.
+ muon_polar_steps: int = 6
@dataclass
diff --git a/training/modules/muon.py b/training/modules/muon.py
new file mode 100644
index 0000000..a064ed0
--- /dev/null
+++ b/training/modules/muon.py
@@ -0,0 +1,244 @@
+"""Muon optimizer (orthogonalized momentum) with an aux AdamW.
+
+Muon applies to 2D hidden weights only; embeddings, heads, gains and 1D
+params need AdamW, so a single optimizer instance carries both update rules
+selected per param group via `use_muon` (keeps checkpointing's single
+`optimizer.state_dict()` contract).
+
+The orthogonalization is the Polar Express polynomial iteration (Amsel et al.,
+arXiv 2505.16932): a composition of degree-5 polynomials whose coefficients are
+optimal per step, evaluated in bfloat16 with matrix products only. Fused
+weights (q/k/v projections, adaLN modulations) are orthogonalized per logical
+block through the group's `split_sizes`.
+
+References: Jordan et al., "Muon: An optimizer for hidden layers in neural
+networks" (github.com/KellerJordan/Muon); Liu et al., "Muon is scalable for
+LLM training" (arXiv 2502.16982) for the RMS-matched update scale.
+"""
+
+from collections.abc import Callable
+from itertools import repeat
+from typing import Any
+
+import torch
+from torch.optim.adamw import adamw as functional_adamw
+
+# Optimal degree-5 coefficients per iteration (l=1e-3, safety 1e-2, cushion 0.02),
+# from github.com/NoahAmsel/PolarExpress; the last one is the fixed point.
+_POLAR_EXPRESS_RAW = [
+ (8.287212018145630, -23.595886519098837, 17.300387312530933),
+ (4.107059111542203, -2.947849916737911, 0.544843108292660),
+ (3.948690853482295, -2.908902115962949, 0.551819139437014),
+ (3.318419657370602, -2.488488024314874, 0.510048940123720),
+ (2.300652019954817, -1.668903984574749, 0.418807311952567),
+ (1.891301407787398, -1.267995827194587, 0.376804089485248),
+ (1.875001480853448, -1.250001645399949, 0.375000164547425),
+ (1.875, -1.25, 0.375),
+]
+_POLAR_EXPRESS = [(a / 1.01, b / 1.01**3, c / 1.01**5) for a, b, c in _POLAR_EXPRESS_RAW[:-1]] + [
+ _POLAR_EXPRESS_RAW[-1]
+]
+
+
+def polar_express(G: torch.Tensor, steps: int = 6) -> torch.Tensor:
+ """Approximate polar factor of G (semi-orthogonal, same shape), batched over leading dims.
+
+ Polar Express applies `steps` degree-5 polynomials X <- aX + bX^3 + cX^5 to the
+ normalized input; bf16 throughout, matrix products only.
+ """
+ assert G.ndim >= 2
+ X = G.bfloat16()
+ transposed = G.size(-2) > G.size(-1)
+ if transposed:
+ X = X.mT
+ X = X / (X.norm(dim=(-2, -1), keepdim=True) * 1.01 + 1e-7)
+ coeffs = _POLAR_EXPRESS[:steps] + list(
+ repeat(_POLAR_EXPRESS[-1], max(0, steps - len(_POLAR_EXPRESS)))
+ )
+ for a, b, c in coeffs:
+ A = X @ X.mT
+ B = b * A + c * A @ A
+ X = a * X + B @ X
+ if transposed:
+ X = X.mT
+ return X
+
+
+_polar_express_compiled = torch.compile(polar_express, dynamic=False)
+
+
+def _orthogonalize(G: torch.Tensor, steps: int) -> torch.Tensor:
+ if G.is_cuda:
+ return _polar_express_compiled(G, steps)
+ return polar_express(G, steps)
+
+
+class MuonWithAuxAdam(torch.optim.Optimizer):
+ """Param groups with use_muon=True get Muon; the rest get AdamW.
+
+ Muon group keys: lr, momentum, polar_steps, weight_decay, split_sizes
+ (row block sizes of a fused weight; default one block), rms_match (scale
+ the orthogonal update by 0.2 * sqrt(max(rows, cols)) so its RMS matches an
+ AdamW update, instead of sqrt(max(1, rows / cols))). AdamW group keys: lr,
+ betas, eps, weight_decay. The training loop rescales each group's lr through
+ group["lr_scale"].
+ """
+
+ def __init__(self, param_groups: list[dict[str, Any]]):
+ for g in param_groups:
+ if g.get("use_muon"):
+ g.setdefault("lr", 0.02)
+ g.setdefault("momentum", 0.95)
+ g.setdefault("polar_steps", 6)
+ g.setdefault("weight_decay", 0.01)
+ g.setdefault("split_sizes", None)
+ g.setdefault("rms_match", False)
+ else:
+ g.setdefault("lr", 2e-4)
+ g.setdefault("betas", (0.9, 0.95))
+ g.setdefault("eps", 1e-8)
+ g.setdefault("weight_decay", 0.1)
+ g["initial_lr"] = g["lr"]
+ super().__init__(param_groups, {})
+ self._adamw_steps: dict[int, torch.Tensor] = {}
+
+ def load_state_dict(self, state_dict: dict[str, Any]) -> None:
+ super().load_state_dict(state_dict)
+ self._adamw_steps.clear()
+ for state in self.state.values():
+ if "step" in state:
+ state["step"] = int(state["step"])
+
+ @torch.no_grad()
+ def step(self, closure: Callable[[], float] | None = None) -> float | None: # ty: ignore[invalid-method-override]
+ assert closure is None
+ for group in self.param_groups:
+ if group.get("use_muon"):
+ self._muon_step(group)
+ else:
+ self._adamw_step(group)
+ return None
+
+ @staticmethod
+ def _blocks(p: torch.Tensor, g: torch.Tensor, sizes: list[int] | None) -> list[torch.Tensor]:
+ """Logical matrices of a (possibly fused) weight, as views of its lookahead grad."""
+ g = g.view(p.size(0), -1)
+ if not sizes:
+ return [g]
+ assert sum(sizes) == g.size(0), (sizes, g.shape)
+ return list(torch.split(g, sizes, dim=0))
+
+ def _muon_step(self, group: dict[str, Any]) -> None:
+ # Nesterov lookahead per param (multi-tensor ops), then one batched polar
+ # iteration per distinct block shape: sequential small iterations are
+ # launch-bound, stacked they are a handful of large bmm calls.
+ params = [p for p in group["params"] if p.grad is not None]
+ if not params:
+ return
+ grads = [p.grad for p in params]
+ bufs = []
+ for p, g in zip(params, grads):
+ state = self.state[p]
+ if "momentum_buffer" not in state:
+ state["momentum_buffer"] = torch.zeros_like(g)
+ bufs.append(state["momentum_buffer"])
+ torch._foreach_lerp_(bufs, grads, 1 - group["momentum"])
+ looks = torch._foreach_lerp(grads, bufs, group["momentum"])
+ # (param index, block index) -> block; batched per block shape
+ by_shape: dict[tuple[int, ...], list[tuple[int, int, torch.Tensor]]] = {}
+ blocks_of: list[list[torch.Tensor]] = []
+ for i, (p, g) in enumerate(zip(params, looks)):
+ blocks = self._blocks(p, g, group["split_sizes"])
+ blocks_of.append(blocks)
+ for j, b in enumerate(blocks):
+ by_shape.setdefault(tuple(b.shape), []).append((i, j, b))
+ # Under DDP every rank holds identical grads and momentum, so the orthogonalization
+ # is sharded: rank r computes a contiguous slice of each shape's blocks, then one
+ # all_gather per shape puts every orthogonalized block on every rank.
+ dist = torch.distributed
+ world = dist.get_world_size() if dist.is_available() and dist.is_initialized() else 1
+ rank = dist.get_rank() if world > 1 else 0
+ out: dict[tuple[int, int], torch.Tensor] = {}
+ for shape, items in by_shape.items():
+ rows, cols = int(shape[0]), int(shape[1])
+ n = len(items)
+ per = -(-n // world)
+ mine = [b for k, (_, _, b) in enumerate(items) if k // per == rank]
+ if mine:
+ ortho = _orthogonalize(torch.stack(mine), group["polar_steps"])
+ else:
+ ortho = torch.empty(
+ (0, rows, cols), dtype=torch.bfloat16, device=items[0][2].device
+ )
+ if world > 1:
+ pad = per - ortho.size(0)
+ if pad:
+ ortho = torch.cat(
+ [
+ ortho,
+ torch.zeros((pad, rows, cols), dtype=ortho.dtype, device=ortho.device),
+ ]
+ )
+ gathered = torch.empty(
+ (per * world, rows, cols), dtype=ortho.dtype, device=ortho.device
+ )
+ dist.all_gather_into_tensor(gathered, ortho.contiguous())
+ ortho = gathered[:n]
+ if group["rms_match"]:
+ scale = 0.2 * max(rows, cols) ** 0.5
+ else:
+ scale = (
+ max(1.0, rows / cols) ** 0.5
+ ) # keeps update RMS ~constant across aspect ratios
+ for (i, j, _), o in zip(items, ortho):
+ out[(i, j)] = o * scale
+ lr, wd = group["lr"], group["weight_decay"]
+ torch._foreach_mul_(params, 1 - lr * wd)
+ updates = [
+ torch.cat([out[(i, j)] for j in range(len(blocks_of[i]))], dim=0)
+ .reshape(p.shape)
+ .to(p.dtype)
+ for i, p in enumerate(params)
+ ]
+ torch._foreach_add_(params, updates, alpha=-lr)
+
+ def _adamw_step(self, group: dict[str, Any]) -> None:
+ params = [p for p in group["params"] if p.grad is not None]
+ if not params:
+ return
+ fused = all(p.is_cuda for p in params)
+ grads, avgs, squares, counters = [], [], [], []
+ for p in params:
+ state = self.state[p]
+ if "exp_avg" not in state:
+ state["step"] = 0
+ state["exp_avg"] = torch.zeros_like(p)
+ state["exp_avg_sq"] = torch.zeros_like(p)
+ device = p.device if fused else torch.device("cpu")
+ counter = self._adamw_steps.get(id(p))
+ if counter is None or counter.device != device:
+ counter = torch.tensor(float(state["step"]), dtype=torch.float32, device=device)
+ self._adamw_steps[id(p)] = counter
+ state["step"] += 1
+ grads.append(p.grad)
+ avgs.append(state["exp_avg"])
+ squares.append(state["exp_avg_sq"])
+ counters.append(counter)
+ beta1, beta2 = group["betas"]
+ functional_adamw(
+ params,
+ grads,
+ avgs,
+ squares,
+ [],
+ counters,
+ amsgrad=False,
+ beta1=beta1,
+ beta2=beta2,
+ lr=group["lr"],
+ weight_decay=group["weight_decay"],
+ eps=group["eps"],
+ maximize=False,
+ foreach=not fused,
+ fused=fused,
+ )
diff --git a/training/tests/test_muon.py b/training/tests/test_muon.py
new file mode 100644
index 0000000..3e69f51
--- /dev/null
+++ b/training/tests/test_muon.py
@@ -0,0 +1,62 @@
+import torch
+
+from training.modules.muon import MuonWithAuxAdam, polar_express
+
+
+def test_polar_express_is_near_orthogonal():
+ g = torch.randn(4, 64, 128)
+ sv = torch.linalg.svdvals(polar_express(g, 6).float())
+ assert sv.min() > 0.9 and sv.max() < 1.1
+
+
+def test_split_sizes_orthogonalize_each_block():
+ # a fused q/k/v weight with GQA-sized k and v blocks: each block is a polar factor
+ torch.manual_seed(0)
+ w = torch.nn.Parameter(torch.randn(64 + 16 + 16, 64))
+ opt = MuonWithAuxAdam(
+ [
+ {
+ "params": [w],
+ "use_muon": True,
+ "lr": 1.0,
+ "weight_decay": 0.0,
+ "split_sizes": [64, 16, 16],
+ }
+ ]
+ )
+ w.grad = torch.randn_like(w)
+ before = w.detach().clone()
+ opt.step()
+ update = (before - w.detach()).float() # lr 1: update = scale * polar(block) per block
+ for block, scale in zip(torch.split(update, [64, 16, 16], dim=0), (1.0, 1.0, 1.0)):
+ sv = torch.linalg.svdvals(block / scale)
+ assert sv.min() > 0.8 and sv.max() < 1.2
+
+
+def test_muon_with_aux_adam_updates_every_group():
+ torch.manual_seed(0)
+ h = torch.nn.Parameter(torch.randn(32, 16))
+ gain = torch.nn.Parameter(torch.ones(16))
+ opt = MuonWithAuxAdam(
+ [
+ {"params": [h], "use_muon": True, "lr": 0.005, "weight_decay": 0.0},
+ {"params": [gain], "lr": 1e-3, "weight_decay": 0.0},
+ ]
+ )
+ before = [p.detach().clone() for p in (h, gain)]
+ for _ in range(2):
+ loss = (h.sum() + gain.sum()) * 0.1
+ opt.zero_grad()
+ loss.backward()
+ opt.step()
+ for p, b in zip((h, gain), before):
+ assert not torch.allclose(p, b)
+ state = opt.state_dict()
+ opt2 = MuonWithAuxAdam(
+ [
+ {"params": [h], "use_muon": True, "lr": 0.005, "weight_decay": 0.0},
+ {"params": [gain], "lr": 1e-3, "weight_decay": 0.0},
+ ]
+ )
+ opt2.load_state_dict(state)
+ assert isinstance(opt2.state[gain]["step"], int)
diff --git a/training/train.py b/training/train.py
index 5ccbc37..60e054a 100644
--- a/training/train.py
+++ b/training/train.py
@@ -43,6 +43,7 @@ from training.train_utils import (
ProgressLog,
_compile_models,
add_file_logging,
+ build_optimizer,
ensure_train_latents,
git_commit,
lr_at,
@@ -123,14 +124,7 @@ def setup(config_path: str) -> Run:
if rank == 0:
logger.info(f"flow_lm + objective: {n_params / 1e6:.1f}M trainable params")
- optimizer = torch.optim.AdamW(
- model.parameters(),
- lr=args.optim.lr,
- betas=args.optim.betas,
- eps=args.optim.eps,
- weight_decay=args.optim.weight_decay,
- fused=device.type == "cuda",
- )
+ optimizer = build_optimizer(model, args, device, rank)
ema = EMA(model, args.ema_decay) if args.ema_decay > 0 else None
start_step = 0
@@ -222,7 +216,7 @@ def main(config_path: str):
step_start = time.time()
lr = lr_at(step, args)
for group in optimizer.param_groups:
- group["lr"] = lr
+ group["lr"] = lr * group.get("lr_scale", 1.0)
optimizer.zero_grad()
for micro in range(args.grad_accum_steps):
batch = next(train_loader)
diff --git a/training/train_utils.py b/training/train_utils.py
index c579757..54919c7 100644
--- a/training/train_utils.py
+++ b/training/train_utils.py
@@ -14,10 +14,12 @@ import torch
from pocket_tts.models.flow_lm import FlowLMModel
from pocket_tts.models.mimi import MimiModel
+from pocket_tts.modules.attention import StreamingMultiheadAttention
from pocket_tts.modules.stateful_module import init_states
from training.args import TrainArgs
from training.modules.builders import load_model_config
from training.modules.model import TrainableTTS
+from training.modules.muon import MuonWithAuxAdam
logger = logging.getLogger("train")
@@ -229,3 +231,78 @@ def ensure_train_latents(
if waited > 24 * 3600:
raise SystemExit("gave up waiting for the latents precompute to finish")
args.data.train_jsonl = str(latents_manifest)
+
+
+def build_optimizer(
+ model: TrainableTTS, args: TrainArgs, device: torch.device, rank: int
+) -> torch.optim.Optimizer:
+ if args.optim.type == "adamw":
+ return torch.optim.AdamW(
+ model.parameters(),
+ lr=args.optim.lr,
+ betas=args.optim.betas,
+ eps=args.optim.eps,
+ weight_decay=args.optim.weight_decay,
+ fused=device.type == "cuda",
+ )
+ assert args.optim.type == "muon", args.optim.type
+ # Muon on the backbone's 2D weights; fused weights are orthogonalized per logical block
+ # (q, k and v of the attention projection, the chunks of an adaLN modulation). AdamW for
+ # embeddings, gains, 1D params and (unless muon_head) the sampler head.
+ blocks: dict[tuple[int, ...], list[torch.Tensor]] = {}
+
+ def add(p: torch.Tensor, sizes: tuple[int, ...] = ()) -> None:
+ if p.ndim == 2 and p.requires_grad:
+ if sizes not in blocks:
+ blocks[sizes] = []
+ blocks[sizes].append(p)
+
+ for layer in model.flow_lm.transformer.layers:
+ fused: dict[int, tuple[int, ...]] = {}
+ for module in layer.modules():
+ if isinstance(module, StreamingMultiheadAttention):
+ kv_dim = (module.in_proj.weight.size(0) - module.embed_dim) // 2
+ fused[id(module.in_proj.weight)] = (module.embed_dim, kv_dim, kv_dim)
+ for p in layer.parameters():
+ add(p, fused.get(id(p), ()))
+ if args.optim.muon_head:
+ for p in model.flow_lm.flow_net.parameters():
+ if p.ndim == 2 and p.size(0) in (2 * p.size(1), 3 * p.size(1)):
+ add(p, (p.size(1),) * (p.size(0) // p.size(1))) # adaLN shift/scale(/gate) chunks
+ else:
+ add(p)
+ muon_params = {id(p) for ps in blocks.values() for p in ps}
+ rest = [p for p in model.parameters() if p.requires_grad and id(p) not in muon_params]
+ muon_scale = 1.0 if args.optim.muon_rms_match else args.optim.muon_lr / args.optim.lr
+ # Decoupled decay multiplies by (1 - lr * wd) per step; at muon_lr the same wd would
+ # decay muon_scale times faster, so rescale it to the AdamW per-step decay.
+ groups: list[dict[str, Any]] = [
+ {
+ "params": ps,
+ "use_muon": True,
+ "lr_scale": muon_scale,
+ "weight_decay": args.optim.weight_decay / muon_scale,
+ "momentum": args.optim.muon_momentum,
+ "split_sizes": list(sizes) or None,
+ "rms_match": args.optim.muon_rms_match,
+ "polar_steps": args.optim.muon_polar_steps,
+ }
+ for sizes, ps in blocks.items()
+ ]
+ groups.append(
+ {
+ "params": rest,
+ "lr_scale": 1.0,
+ "betas": args.optim.betas,
+ "eps": args.optim.eps,
+ "weight_decay": args.optim.weight_decay,
+ }
+ )
+ groups = [g for g in groups if g["params"]]
+ if rank == 0:
+ n_split = sum(len(ps) for sizes, ps in blocks.items() if sizes)
+ logger.info(
+ f"muon on {sum(p.numel() for ps in blocks.values() for p in ps) / 1e6:.1f}M params "
+ f"({n_split} fused weights orthogonalized per block), adamw on the rest"
+ )
+ return MuonWithAuxAdam(groups)