Skip to main content

Understanding the Muon Optimizer : Explained and Tested against AdamW with NanoGPT

The Muon optimizer explained and tested against AdamW on NanoGPT: the Newton-Schulz iteration, parameter splitting, an RMS-scale sweep, and how DeepSeek-V4 uses Muon at scale.
Last updated: July 28, 2026
For years, if you were training a transformer, the optimizer question was already answered: you used AdamW and moved on. So when DeepSeek released V4 in April 2026, a 1.6-trillion-parameter model, the optimizer choice was a genuine surprise. For the bulk of the network, the hidden weight matrices that do most of the work, the team did not use AdamW at all. They used Muon. When a frontier lab swaps out the default that has held for half a decade, on a model at that scale, the optimizer is worth understanding.
The good news is that Muon is small enough to understand completely. The core idea fits in a paragraph, the implementation fits on a screen, and you can run the whole thing on a free GPU. This tutorial builds it from the ground up: you will write Muon into Andrej Karpathy's nanoGPT repository, run three optimizer configurations head to head on a free Colab T4, track every run in Weights & Biases, and evaluate the trained models with W&B Weave. By the end you will have seen what Muon changes about the geometry of a weight update, why a constant copied straight from the large-scale implementation quietly breaks training on a small model, and exactly how the DeepSeek-V4 recipe maps onto the code you ran.
One honest note before we start. This is a tutorial built around a 3-million-parameter model trained on Shakespeare, and nothing at that size can prove a claim about trillion-parameter behavior. What it can do is show the mechanism working, let you watch Muon and AdamW diverge under identical conditions, and connect what you see to the specific choices V4 made at scale. Every number reported here is what the runs actually produced, including the places where the result was smaller or messier.

Table of Contents



Why optimizers matter

Training a neural network comes down to 4 steps:
  1. Run a forward pass,
  2. Compute a loss,
  3. Backpropagate to get gradients, and
  4. Let an optimizer decide what to do with those gradients.
That last step is the one that tends to get glossed over. The gradient only tells you a direction, and only locally. It says which way to nudge a weight to reduce the loss, but nothing about how far to step, whether to trust this gradient or smooth it with past ones, or whether the step size should differ per weight. Those are the optimizer's decisions, and they are where AdamW and Muon diverge.
Vanilla stochastic gradient descent steps directly opposite the gradient, nothing more. Momentum keeps a running average of recent gradients so the optimizer builds speed through consistent directions rather than reacting to every noisy step.
Adam added per-parameter adaptive scaling: it tracks a running average of the gradient and of the gradient squared, and uses the second to shrink the step size for volatile weights and grow it for steady ones.
AdamW corrected a subtle flaw in Adam's weight decay, decoupling it from the adaptive step so it applies cleanly. That decoupled weight decay is what made AdamW the default for transformer training.
Muon goes in a different direction. Where AdamW treats each weight as an independent scalar coordinate, Muon treats a weight matrix as what it actually is: a linear operator that maps one vector space into another. Its central insight is that gradient updates to a matrix tend to concentrate along a few dominant directions. In the language of the singular value decomposition, which factors any matrix M into (U Sigma V^T) where Sigma holds the magnitudes of each principal direction, an unmodified update has a handful of large singular values and many small ones. Stepping on that update moves the weights hard in two or three directions and barely at all in the rest. Over many steps the matrix's learning collapses.

Muon's fix is to strip the update down to its directions only. Take the gradient matrix, find which directions it points in, throw away how strongly it points in each one, and rebuild the update so every direction gets exactly the same weight. The result is an update that moves the weight matrix a little bit along every useful direction at once, instead of hammering two or three and ignoring the rest.
Moonshot AI's Kimi models, which also train with Muon, measured what this looks like in practice. Weight matrices trained with Muon spread their learning across far more directions than those trained with AdamW. The update stays spread out rather than collapsing into a small corner of the space the matrix can represent. That is the whole point.
One limitation falls out naturally from this, you can only spread directions across a matrix. A single number has no directions to spread. So Muon only applies to the weight matrices inside the network, the ones in the attention layers and MLP blocks, and everything else stays on AdamW. Embeddings, the output head, the normalization layer weights, and biases are all one-dimensional or otherwise special, and they go to AdamW. Muon and AdamW run side by side, each handling the parameters it is designed for. DeepSeek-V4 uses exactly this split.



The Newton-Schulz iteration

Orthogonalizing a matrix the proper way means computing its full singular value decomposition, and doing that on every weight matrix at every single optimizer step would make Muon far too slow to be useful. The Newton-Schulz iteration is the workaround. Instead of computing the SVD, it runs a short loop of matrix multiplications that nudges all the singular values toward 1 without ever finding out what they actually are.
Think of it like adjusting the temperature in a room without a thermometer. You do not measure the exact temperature; you just crack the window a little, wait, crack it a little more, and repeat until it feels right. Newton-Schulz does the same thing to singular values: it applies a small correction repeatedly until they land where they need to be.
Each step takes the current matrix X and produces a new one by running it through a fixed formula involving X and its transpose. The formula is shaped so that singular values far from 1 get pushed hard toward it, while singular values already close to 1 barely move. After five repetitions the matrix is close enough to orthogonal that the optimizer can use it as an update.
One thing has to be set up correctly before the loop starts. The formula only behaves reliably when the singular values of the input are already in a roughly sensible range, somewhere between 0 and 1. If you feed in a matrix with very large singular values the iteration can fly off in the wrong direction entirely. The fix is to divide the gradient matrix by its overall size before starting, which is one line of code but the whole thing breaks without it.
The specific numbers in the formula, (3.4445, -4.7750, 2.0315) were not derived mathematically. Keller Jordan found them by running an optimization search: treat the coefficients as unknowns, try many combinations, and keep the ones that converge fastest while still converging. They work well but they are aggressive, meaning five steps gets you close but can slightly overshoot, leaving a few singular values just above 1 rather than exactly at it.
DeepSeek-V4 handles this with a two-stage schedule. Instead of five identical aggressive steps, it runs five aggressive steps and then two gentler cleanup steps with softer coefficients, (2.0, -1.5, 0.5). Those last two do not push the singular values any further; they just smooth out the overshoot and leave the result cleaner. In the code this is the schedule argument: a list of coefficient triples, one per step, so switching between the single-stage and the two-stage version is a one-line change.



Step 0: Setup

The first cell clones the real nanoGPT repository, installs wandb and tiktoken, and asserts that a GPU is available.
# Runtime > Change runtime type > T4 GPU, then run.
!git clone https://github.com/karpathy/nanoGPT.git
%cd nanoGPT
!pip -q install wandb tiktoken
import torch
assert torch.cuda.is_available(), "Switch the runtime to a T4 GPU first."
print(torch.cuda.get_device_name(0))
One detail to get right before running: in Colab, go to Runtime, then Change runtime type, and select T4 GPU. The Newton-Schulz iteration in the next step will run in fp32 regardless, because bf16 is emulated on Turing-architecture cards like the T4, which makes it both slow and numerically unreliable. Production implementations on A100 or H100 hardware run in bf16 and would mislead you if copied here without that change.
💡




Step 1: Write the Muon optimizer

Rather than importing Muon from a package, we write it into the cloned repo so it sits beside model.py as a proper file. The cell below is the complete implementation.
import torch

@torch.no_grad()
def newtonschulz(G, schedule):
# Approximate the orthogonal factor of G (the UV^T from its SVD) without
# actually doing an SVD. Each step pushes the singular values toward 1.
# `schedule` is a list of (a, b, c) coeffs, one per step, so we can run the
# aggressive coeffs first and a couple of gentler ones after to settle it.
assert G.ndim == 2
X = G.float() # keep this in fp32, bf16 is emulated (and slow) on a T4
transposed = False
if X.size(0) < X.size(1):
X = X.T
transposed = True
X = X / (X.norm() + 1e-7)
for a, b, c in schedule:
A = X @ X.T
B = b * A + c * (A @ A)
X = a * X + B @ X
return X.T if transposed else X

# Aggressive coeffs from Keller's writeup. The hybrid adds two softer steps at
# the end, which is the shape of the schedule DeepSeek-V4 reports.
SINGLE = [(3.4445, -4.7750, 2.0315)] * 5
HYBRID = [(3.4445, -4.7750, 2.0315)] * 5 + [(2.0, -1.5, 0.5)] * 2

class Muon(torch.optim.Optimizer):
def __init__(self, params, lr=0.02, momentum=0.95, nesterov=True,
weight_decay=0.0, schedule=None, rms_rescale=False, rms_scale=0.2):
defaults = dict(lr=lr, momentum=momentum, nesterov=nesterov,
weight_decay=weight_decay, schedule=schedule or SINGLE,
rms_rescale=rms_rescale, rms_scale=rms_scale)
super().__init__(params, defaults)

@torch.no_grad()
def step(self, closure=None):
loss = closure() if closure is not None else None
self.update_rms = [] # grabbed by the training loop for logging
for group in self.param_groups:
lr, mom, nesterov = group["lr"], group["momentum"], group["nesterov"]
wd, schedule = group["weight_decay"], group["schedule"]
rms_rescale, rms_scale = group["rms_rescale"], group["rms_scale"]
for p in group["params"]:
if p.grad is None:
continue
g = p.grad
assert g.ndim == 2, "Muon is for 2D params, send the rest to AdamW"
state = self.state[p]
buf = state.setdefault("buf", torch.zeros_like(g))
buf.mul_(mom).add_(g)
d = g.add(buf, alpha=mom) if nesterov else buf

u = newtonschulz(d, schedule)
if rms_rescale:
# An orthogonal n x m matrix has entry RMS ~ 1/sqrt(max(n,m)),
# so its element size depends on shape. Scale it back up so the
# update RMS is comparable across layers and to AdamW.
n, m = p.shape
u = u * (max(n, m) ** 0.5) * rms_scale
if wd:
p.mul_(1 - lr * wd)
p.add_(u, alpha=-lr)
self.update_rms.append(u.float().pow(2).mean().sqrt().item())
return loss
The newtonschulz function is where the orthogonalization happens. It approximates the nearest orthogonal matrix to G using a short loop of matrix multiplications, avoiding the full singular value decomposition that would make this too expensive to run every optimizer step. The normalization line at the top of the function is the prerequisite we covered: the polynomial only drives singular values toward 1 reliably when they start in a reasonable range, so we divide by the Frobenius norm first.
The SINGLE and HYBRID schedules at module level are the two coefficient sequences.
  • SINGLE runs five identical aggressive steps.
  • HYBRID runs those same five and adds two gentler stabilization steps after, which is the two-stage shape DeepSeek-V4 reports using.
Inside Muon.step, the update sequence is the same each time:
  • Accumulate a Nesterov momentum buffer,
  • Pass it through newtonschulz to get an orthogonalized direction
  • Optionally rescale to normalize the update magnitude across layers
  • Apply decoupled weight decay, and step.
  • The self.update_rms list is populated every step and picked up by the training loop for logging to Weights & Biases.
The two optional pieces, RMS rescaling and weight decay, are the Moonshot scaling fixes. A freshly orthogonalized matrix of shape n x m has a typical element size of roughly 1/sqrt(max(n, m)), which means the update magnitude depends on matrix shape. Without correction, attention matrices and MLP matrices of different shapes receive systematically different effective step sizes. Multiplying by sqrt(max(n, m)) and a tunable constant pulls every layer back to a comparable magnitude. We will see exactly why the constant matters, and why the published default of 0.2 breaks at small scale, in step 6.



Step 2: Prepare the data

!python data/shakespeare_char/prepare.py

nanoGPT ships a preparation script for character-level Shakespeare. Running it downloads the corpus, builds the character vocabulary (65 unique characters), and writes train.bin and val.bin as memory-mapped arrays alongside a meta.pkl file holding the vocabulary mappings. The training loop reads directly from these files using np.memmap, which avoids loading the full dataset into memory at once.



Step 3: Split the parameters

Deciding which parameters go to Muon and which to AdamW is the part of any Muon port that can go silently wrong. nanoGPT ties its weights: transformer.wte.weight and lm_head.weight are the same tensor in memory, a common technique that saves parameters and tends to improve results. If you loop over named parameters and route every 2D tensor to Muon, that shared tensor ends up in both optimizer groups, or you orthogonalize an embedding that should stay on AdamW. Either way the run is corrupted without any error message.
The fix is to deduplicate on tensor identity. The seen set tracks id(p) for every parameter already routed and skips any alias encountered later. Embeddings and the output head are excluded from Muon by name. Everything else that is two-dimensional goes to Muon, everything else to AdamW. The two assertions confirm the tied tensor landed in AdamW exactly once before we rely on this split for any actual training.
from model import GPTConfig, GPT
from muon import Muon, SINGLE, HYBRID

def split_params(model):
muon, adamw, seen = [], [], set()
for name, p in model.named_parameters():
if not p.requires_grad or id(p) in seen:
continue
seen.add(id(p))
emb = name.endswith("wte.weight") or name.endswith("wpe.weight")
head = name == "lm_head.weight"
(muon if (p.ndim == 2 and not emb and not head) else adamw).append(p)
return muon, adamw

# sanity check the split before we rely on it
_cfg = GPTConfig(block_size=256, vocab_size=65, n_layer=4, n_head=4,
n_embd=256, dropout=0.0, bias=False)
_m = GPT(_cfg)
_mp, _ap = split_params(_m)
assert id(_m.lm_head.weight) in {id(p) for p in _ap}
assert id(_m.lm_head.weight) not in {id(p) for p in _mp}
print(f"{len(_mp)} matrices to Muon, {len(_ap)} tensors to AdamW")
del _m

This mirrors the DeepSeek-V4 split: Muon for the hidden attention and MLP matrices, AdamW for embeddings, the prediction head, normalization weights, and static biases.



Step 4: Configure training

The model is a 4-layer, 4-head GPT with 256-dimensional embeddings, about 3.16 million parameters. Block size is 256, batch size 32, and we run 2000 iterations. These settings keep each run under five minutes on a T4 while producing curves stable enough to compare.
AdamW runs at a learning rate of 3e-4, which is nanoGPT's own default. Muon runs at 0.02, Keller Jordan's recommended starting point, which reflects that orthogonalized updates are already normalized so the effective step size behaves differently than for raw gradients.
build_model seeds PyTorch with 1337 before constructing each model, so every run starts from exactly the same initialization. make_opts handles the three configurations: for AdamW it calls nanoGPT's own configure_optimizers so the baseline is the repository's genuine default; for vanilla Muon it pairs a Muon optimizer on the matrix parameters with a plain AdamW on everything else; for the fixed configuration it adds weight decay of 0.1 and RMS rescaling with a scale of 0.05 to both optimizers, and switches to the hybrid Newton-Schulz schedule.
import os, time, pickle, math
import numpy as np

block_size, batch_size = 256, 32
n_layer, n_head, n_embd = 4, 4, 256
max_iters, eval_interval, eval_iters = 2000, 200, 50
adamw_lr, muon_lr = 3e-4, 0.02
device = "cuda"

d = "data/shakespeare_char"
train_data = np.memmap(os.path.join(d, "train.bin"), dtype=np.uint16, mode="r")
val_data = np.memmap(os.path.join(d, "val.bin"), dtype=np.uint16, mode="r")
vocab_size = pickle.load(open(os.path.join(d, "meta.pkl"), "rb"))["vocab_size"]

def get_batch(split):
data = train_data if split == "train" else val_data
ix = torch.randint(len(data) - block_size, (batch_size,))
x = torch.stack([torch.from_numpy(data[i:i+block_size].astype(np.int64)) for i in ix])
y = torch.stack([torch.from_numpy(data[i+1:i+block_size+1].astype(np.int64)) for i in ix])
return x.to(device), y.to(device)

@torch.no_grad()
def estimate_loss(model):
out = {}
model.eval()
for split in ("train", "val"):
losses = torch.zeros(eval_iters)
for k in range(eval_iters):
x, y = get_batch(split)
_, loss = model(x, y)
losses[k] = loss.item()
out[split] = losses.mean().item()
model.train()
return out

def grad_norm(model):
total = sum(p.grad.detach().float().norm().item() ** 2
for p in model.parameters() if p.grad is not None)
return total ** 0.5

def build_model():
torch.manual_seed(1337)
cfg = GPTConfig(block_size=block_size, vocab_size=vocab_size, n_layer=n_layer,
n_head=n_head, n_embd=n_embd, dropout=0.0, bias=False)
return GPT(cfg).to(device)

def make_opts(model, config, rms_scale=0.05):
mp, ap = split_params(model)
if config == "adamw":
return [model.configure_optimizers(0.0, adamw_lr, (0.9, 0.95), "cuda")], None
if config == "muon_vanilla":
muon = Muon(mp, lr=muon_lr, schedule=SINGLE)
return [muon, torch.optim.AdamW(ap, lr=adamw_lr)], muon
if config == "muon_fixed":
muon = Muon(mp, lr=muon_lr, weight_decay=0.1, schedule=HYBRID,
rms_rescale=True, rms_scale=rms_scale)
return [muon, torch.optim.AdamW(ap, lr=adamw_lr, weight_decay=0.1)], muon
raise ValueError(config)



Step 5: Run the three configurations

Add your W&B API key as a Colab secret named WANDB_API_KEY via the key icon in the left sidebar, then run. The train function runs the standard nanoGPT forward-backward loop, evaluating every 200 iterations and logging train loss, validation loss, and gradient norm to Weights & Biases. For the Muon configurations it also logs update_rms_mean, update_rms_min, and update_rms_max every ten steps, the minimum, mean, and maximum of the per-layer update RMS collected by self.update_rms during each optimizer step. At the end of each run it saves a checkpoint to ckpts/{config}.pt for the Weave evaluation in step 7.
import wandb
from google.colab import userdata

wandb.login(key=userdata.get("WANDB_API_KEY"))
PROJECT = "muon-nanogpt"

def train(config, rms_scale=0.05, name=None):
model = build_model()
opts, muon = make_opts(model, config, rms_scale)
run = wandb.init(project=PROJECT, name=name or config, reinit="finish_previous",
config=dict(config=config, n_embd=n_embd, n_layer=n_layer,
max_iters=max_iters, muon_lr=muon_lr, rms_scale=rms_scale))
t0 = time.time()
for it in range(max_iters + 1):
if it % eval_interval == 0:
L = estimate_loss(model)
wandb.log({"train_loss": L["train"], "val_loss": L["val"]}, step=it)
print(f"[{config}] {it:4d} train {L['train']:.4f} val {L['val']:.4f}")
x, y = get_batch("train")
_, loss = model(x, y)
for o in opts:
o.zero_grad(set_to_none=True)
loss.backward()
gn = grad_norm(model)
for o in opts:
o.step()
if it % 10 == 0:
log = {"batch_loss": loss.item(), "grad_norm": gn}
if muon is not None and getattr(muon, "update_rms", None):
r = muon.update_rms
log["update_rms_mean"] = float(np.mean(r))
log["update_rms_min"] = float(np.min(r))
log["update_rms_max"] = float(np.max(r))
wandb.log(log, step=it)
wandb.log({"wallclock_sec": time.time() - t0}, step=max_iters)
# save a checkpoint so the Weave eval can reload this exact model
os.makedirs("ckpts", exist_ok=True)
torch.save({"model": model.state_dict(),
"config": dict(block_size=block_size, vocab_size=vocab_size,
n_layer=n_layer, n_head=n_head, n_embd=n_embd,
dropout=0.0, bias=False)},
f"ckpts/{config}.pt")
run.finish()

train("adamw", name="adamw-baseline")
train("muon_vanilla", name="muon-vanilla")
train("muon_fixed", rms_scale=0.05, name="muon-moonshot-fixes")
Output :





The three runs take roughly 165, 310, and 355 seconds respectively on a T4. All three start from the same model initialization, the same data loader, and the same number of steps. The only variable is the optimizer.
The headline result from the W&B workspace is that both Muon variants beat AdamW and do it early. By iteration 200, both Muon configurations are near 1.85 validation loss while AdamW is still at 2.44. That early convergence gap is the clearest signal in the comparison. By the end of training, both Muon variants reach a final validation loss around 1.50, versus 1.57 for AdamW.
The more interesting story is the difference between the two Muon runs. Vanilla Muon drives training loss to 0.97 by the final iteration, far below either other run. Its validation loss bottoms out near iteration 1200 and then drifts back up to 1.61. That train-val gap is overfitting: the model is memorizing rather than generalizing, and without weight decay there is nothing to discourage it. The fixed configuration, with weight decay of 0.1, holds training loss at 1.22 and keeps validation loss flat through to the end, finishing at 1.50. So the weight decay did exactly what it is supposed to do.
The update_rms panels make the RMS rescaling visible in a way the loss curves cannot. Vanilla Muon's per-layer update RMS is spread: the minimum, mean, and maximum sit at roughly 0.027, 0.036, and 0.057, three distinct lines reflecting the shape-dependent magnitudes we covered earlier. The fixed configuration's three lines collapse onto a single value near 0.050. That collapse is the rescaling working as designed, forcing every layer to a common update magnitude regardless of shape.

3 selected runs




Step 6: Sweep the RMS scale constant

results = []
for s in (0.02, 0.05, 0.1, 0.2):
model = build_model()
opts, muon = make_opts(model, "muon_fixed", rms_scale=s)
for _ in range(800):
x, y = get_batch("train")
_, loss = model(x, y)
for o in opts:
o.zero_grad(set_to_none=True)
loss.backward()
for o in opts:
o.step()
L = estimate_loss(model)
results.append((s, L["val"], float(np.mean(muon.update_rms))))
print(f"rms_scale {s:<5} val {L['val']:.4f} update_rms_mean {np.mean(muon.update_rms):.4f}")

print("best by val loss:", min(results, key=lambda r: r[1])[0])

The default rms_scale in Keller Jordan's implementation is 0.2. That number was calibrated for large models, and on this one it breaks things badly.
Here is what happens at rms_scale=0.2: the rescaling forces every layer's update to a magnitude of roughly 0.2. Vanilla Muon, left alone, naturally produces updates in the range of 0.027 to 0.057 on this model. So the rescaling is not normalizing anything; it is turning up the volume four to six times louder than the signal needs to be. The updates override the actual learning signal and the model stops improving.
Final validation loss: 2.22, worse than plain AdamW. The update RMS sits pinned at 0.197 for the entire run, a flat line that tells you nothing is being learned, just overdriven.
At rms_scale=0.05, the forced magnitude lands at 0.050, which is close to what vanilla Muon produces naturally. The model trains normally and reaches a validation loss of 1.54 after 800 iterations, the best result in the sweep. That is the value used in step 5.
The lesson here is about what the RMS rescaling fix is actually for-
It exists to solve a problem that shows up in large models. Differently shaped matrices get systematically different update magnitudes, and at scale that imbalance matters enough to hurt training. On a 3-million-parameter model that problem barely exists, so applying the large-scale constant does not fix anything; it just introduces a much bigger problem of its own. The right approach is to run a short sweep like this one, find where the rescaled update magnitude matches vanilla Muon's natural range on your specific model, and use that value. Do not assume a published default will transfer.



Step 7: Evaluate with W&B Weave

The loss curves tell us one Muon configuration overfit. The question the curves cannot answer is whether that overfitting shows up in what the models actually generate. Loading the three checkpoints and comparing their outputs directly is what evaluation tooling is for.
!pip -q install weave
import weave
import torch, math, string
import torch.nn.functional as F
import numpy as np
from model import GPTConfig, GPT

weave.init("muon-nanogpt") # uses the W&B key already set above
def load_model(config):
ckpt = torch.load(f"ckpts/{config}.pt", map_location=device)
m = GPT(GPTConfig(**ckpt["config"]))
m.load_state_dict(ckpt["model"])
return m.to(device).eval()

# held-out text for perplexity: decode a slice of the val split back to characters
itos = pickle.load(open(os.path.join(d, "meta.pkl"), "rb"))["itos"]
stoi = pickle.load(open(os.path.join(d, "meta.pkl"), "rb"))["stoi"]
encode = lambda s: [stoi[c] for c in s]
decode = lambda l: "".join(itos[i] for i in l)
held_out_ids = torch.tensor(val_data[:2000].astype(np.int64), device=device)

@torch.no_grad()
def perplexity(model, ids):
nlls, n = [], 0
for i in range(0, len(ids) - 1, block_size):
chunk = ids[i:i+block_size+1]
if len(chunk) < 2:
break
x = chunk[:-1].unsqueeze(0); y = chunk[1:].unsqueeze(0)
logits, _ = model(x, y)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), y.view(-1))
nlls.append(loss.item() * y.numel()); n += y.numel()
return math.exp(sum(nlls) / n)

@torch.no_grad()
def generate_text(model, prompt, n=200):
idx = torch.tensor([encode(prompt)], device=device)
out = model.generate(idx, max_new_tokens=n, temperature=0.8, top_k=40)
return decode(out[0].tolist())

def printable_ratio(text):
ok = sum(ch in string.printable for ch in text)
return ok / max(len(text), 1)
Each checkpoint is loaded into a fresh GPT instance using the config dictionary that was saved alongside the weights at the end of training. This means the model is rebuilt from scratch with the exact same architecture, then the saved weights are loaded in. Nothing carries over from the training session; the model is reconstructed cleanly from the file alone.
The perplexity helper is worth understanding because it is the main quality signal in this evaluation, and the number it produces is easy to misread if you have not seen it before.
Perplexity measures how surprised a language model is by text it has not seen. Feed the model a sequence of characters one at a time, ask it to predict each next character, and measure how confident it was on average. A model that is very confident and mostly correct will have low perplexity. A model that is uncertain or frequently wrong will have high perplexity. Lower is better.
The specific version here computes the average negative log-likelihood per character over a fixed 2000-character slice of the validation text, then exponentiates it. That exponentiation is what converts the raw loss number into perplexity. A model that had no idea what was coming and assigned equal probability to all 65 characters in the vocabulary every single time would score a perplexity of exactly 65. So 65 is the floor for a completely untrained model on this dataset. Anything well below that means the model has genuinely learned something about the structure of the text. Our trained models come in around 3.68 to 4.11, which means they are roughly ten times less surprised by the validation text than a model that learned nothing.
One thing to keep in mind when reading these numbers: this is character-level perplexity on Shakespeare, not word-level perplexity on a standard benchmark. The two are not directly comparable, so the numbers here should only be read relative to each other, not against perplexity figures you might see elsewhere.
prompts = ["ROMEO:", "To be, or not", "What say you", "O God,", "The king"]
configs = ["adamw", "muon_vanilla", "muon_fixed"]

for config in configs:
model = load_model(config)
ppl = perplexity(model, held_out_ids)

ev = weave.EvaluationLogger(model=config, dataset="shakespeare_char_prompts")
for p in prompts:
gen = generate_text(model, p)
pred = ev.log_prediction(inputs={"prompt": p}, output=gen)
pred.log_score("perplexity", ppl) # model-level, same for each prompt
pred.log_score("printable_ratio", printable_ratio(gen))
pred.finish()
ev.log_summary({"perplexity": ppl})
print(f"{config:14s} perplexity {ppl:.3f}")

Evaluation Comparison on Weave

EvaluationLogger fits this setup cleanly because it logs predictions and scores inline with existing code rather than requiring a dataset class or a model wrapper. For each of five seed prompts we generate a continuation and attach two scores:
  1. Perplexity on the held-out text and
  2. Printable ratio as a readability sanity check.
The results confirm and extend the loss-curve story. AdamW scores a held-out perplexity of 4.11. Vanilla Muon scores 3.70 and the fixed configuration 3.68, both clearly better than AdamW. The gap between the two Muon variants is 0.014 perplexity points. Vanilla Muon's overfitting, which was visible in the training curve, translates into almost no penalty on held-out perplexity at this scale. The weight-decay fix bought a clean validation curve and training stability, but the final model quality difference is marginal.
Printable ratio came back at 1.0 for all three models, functioning as a sanity check that passed rather than a discriminating metric. The side-by-side generations in the Weave compare view are equally readable across all three.
For the prompt "To be, or not," AdamW continues with "man is wantonel," the fixed Muon with "whitherween and will," and vanilla Muon with "the widness of thee." All three produce Shakespeare-shaped text with plausible rhythm and character names wrapped around words that are not real. The perplexity advantage of Muon is real and measurable; at 3 million parameters it is below what the human eye can resolve in a sample.

How DeepSeek-V4 uses Muon at scale

Everything we just built is the small-scale version of what DeepSeek-V4 does on a trillion-parameter model. The V4 series comes in two sizes, a 1.6-trillion-parameter Pro model with 49 billion parameters activated per token and a 284-billion-parameter Flash model with 13 billion activated, and both are Mixture-of-Experts models, meaning only a fraction of the network runs for any given token. The paper lists three headline upgrades over the previous generation, and the third one is simply "the Muon optimizer for faster convergence and greater training stability." That is the same optimizer you implemented in step 1. Now that the mechanism is concrete, the choices V4 makes around it connect directly to what you ran.
The clearest way to see the correspondence is the optimizer pseudocode from the paper, Algorithm 1, reproduced here in the paper's own notation:

If you read that against the Muon.step method we wrote, it is line for line the same optimizer.
  • The momentum buffer M_t = μ M_{t-1} + G_t is your buf.mul_(mom).add_(g).
  • The μ M_t + G_t passed into the orthogonalizer is your Nesterov term g.add(buf, alpha=mom).
  • HybridNewtonSchulz is your newtonschulz called with the HYBRID schedule.
  • The rescaling line sqrt(max(n, m)) · γ is exactly your u * (max(n, m) ** 0.5) * rms_scale, with the paper's γ being your rms_scale.
  • And the final line, which multiplies the weight by (1 − ηλ) before subtracting the update, is your decoupled weight decay followed by the parameter step.
The optimizer we ran on a 3-million-parameter Shakespeare model is the optimizer that trained a 1.6-trillion-parameter model, with the only differences being the constants. The rest of this section walks through how the paper sets those constants and why.

The parameter split

In Step 3 we wrote split_params to route the 2D attention and MLP weights to Muon while sending the tied embedding, the output head, and the norms to AdamW. The paper describes the identical decision: it keeps the AdamW optimizer for the embedding module, the prediction head, the static biases and gating factors of the mHC modules, and the weights of all RMSNorm modules, and updates all other modules with Muon.
2 of those exceptions are worth a quick definition, because they are V4-specific and do not appear in nanoGPT.
  • RMSNorm is a normalization layer, a per-feature scaling step that keeps activations in a stable range, and its learnable weights are one-dimensional, so orthogonalization does not apply, the same reason your split_params routed LayerNorm weights to AdamW.
  • The mHC modules are V4's Manifold-Constrained Hyper-Connections, an upgrade to the standard residual connections between transformer blocks, and their gating factors are small scalar parameters that control how much signal flows through each connection.
Scalars and one-dimensional parameters have no matrix structure to orthogonalize, so they stay on AdamW. The principle we applied to 16 matrices in a 4-layer model is exactly the principle V4 applies across its 61 layers: Muon is for matrix operators, and everything that is not a matrix operator goes to AdamW.

The hybrid Newton-Schulz schedule

In step 1 you defined HYBRID as five aggressive steps followed by two gentler stabilization steps. The paper uses the same two-stage idea, scaled up slightly. Its hybrid Newton-Schulz performs 10 iterations across two stages:
  1. During the first 8 steps it uses coefficients (a, b, c) = (3.4445, −4.7750, 2.0315) to drive rapid convergence and bring the singular values close to 1,
  2. In the final 2 steps it switches to (a, b, c) = (2, −1.5, 0.5) to stabilize the singular values precisely at 1.
Those are the exact coefficients in your muon.py. The only difference is the count: V4 runs 8 aggressive steps plus 2 stabilization steps where your tutorial runs 5 plus 2, a reasonable reduction given that you are orthogonalizing much smaller matrices on a single T4.
The structure is identical, and so is the stated reason for the second stage, which is to settle the singular values precisely at 1 after the aggressive steps bring them close. This is the part of the recipe that is genuinely distinctive to V4. The paper notes it diverges from the earlier Moonshot work specifically here, stating that different from them, it uses hybrid Newton-Schulz iterations for orthogonalization. When you switched your schedule from SINGLE to HYBRID, you were making the same change V4 made relative to its predecessors.

RMS rescaling and weight decay

These are the two pieces you toggled on for the fixed configuration, and they map directly onto the paper's hyperparameters. For the rescaling factor, the paper states that it rescales the RMS of each update matrix to 0.18 so that the AdamW learning rate can be reused. That number, 0.18, is the production value of the same rms_scale constant you swept in Step 6. It is worth pausing on how close that is to what our own sweep landed on.
We found that rms_scale=0.05 worked best on our 3-million-parameter model and that the large-scale default of 0.2 actively damaged training. V4's chosen value of 0.18 sits right near that 0.2 that broke your small model, which is the entire point of Step 6: the constant is calibrated to the scale of the model, and a value tuned for a trillion parameters is the wrong value for three million. Your sweep was a miniature version of the calibration the DeepSeek team did at full scale.
The reason the rescaling exists at all, reusing the AdamW learning rate, matches the behavior behind the update_rms panels you watched. Rescaling forces every Muon update to a magnitude comparable to what AdamW produces, which lets the team use a single learning rate across both optimizers rather than tuning two separately. In our run, we saw this as the collapse of the per-layer update RMS onto a single value when rescaling was on. At V4's scale, with attention and MLP matrices of widely varying shapes across 61 layers, that magnitude equalization is what makes a shared learning rate viable.
For weight decay, the paper sets it to 0.1 for the Muon parameters, the same value we used in your fixed configuration's weight_decay=0.1. The effect we observed at small scale, where vanilla Muon overfit and the weight-decay version held its validation curve flat, is the same regularization that keeps a trillion-parameter model's weights bounded over a 33-trillion-token training run. Momentum is shared too, the paper sets Muon momentum to 0.95, which is the default in our Muon class.

Avoiding exploding attention logits

There is one part of V4's recipe our demo could not show, and the paper is explicit about it. In a large transformer, the dot products between queries and keys inside the attention mechanism can grow very large, which saturates the softmax and stops gradients from flowing, destabilizing training. This is the exploding-attention-logits problem. Some models address it with a technique called QK-Clip, which hard-clamps those dot products. V4 takes a different route: its attention architecture lets it apply RMSNorm directly to the attention queries and the KV entries, which keeps the logits bounded and prevents them from exploding, and as a result it does not use QK-Clip at all.
In other words, V4 normalizes the queries and keys before attention so their products stay bounded from the start, which removes the need for any clamp. This problem only emerges at scale, and your 3-million-parameter model never approaches the regime where attention logits explode, which is why the tutorial did not surface it. It is a good illustration of the general pattern: several of V4's choices exist to solve problems that only appear once the model is large enough to create them.

What scales and what does not

Putting it together, the V4 recipe is the configuration we built, with constants tuned for scale and one architectural addition our demo could not reach. The optimizer is identical line for line, as Algorithm 1 shows. The parameter split is the same matrix-versus-everything-else rule.
The hybrid Newton-Schulz schedule uses our exact coefficients, with 8 plus 2 steps rather than 5 plus 2. The rescaling factor is 0.18 where our sweep found 0.05, and the gap between those two numbers is precisely the lesson of Step 6. The weight decay and momentum match your defaults. The one piece beyond the demo is the RMSNorm-on-queries-and-keys trick for attention stability, which matters only at a scale that produces exploding logits in the first place.
This is the payoff of building it small first. When the DeepSeek-V4 paper says it uses Muon with hybrid Newton-Schulz, RMS rescaling to 0.18, weight decay of 0.1, and AdamW retained for embeddings, the head, the norms, and the mHC gating factors, you are not reading a list of unfamiliar tricks. You are reading the configuration you already ran, line by line, with the constants set for a trillion parameters instead of three million. The mechanism is the same. Only the scale, and the consequences that emerge at that scale, are different.

Conclusion

The thing worth holding onto from all of this is what Muon actually changes.
AdamW looks at each weight on its own and scales its step by that weight's gradient history. Muon looks at a weight matrix as a whole, takes the momentum-smoothed gradient, and orthogonalizes it so the update moves the matrix evenly in every direction instead of piling into the few the raw gradient happens to favor.
The Newton-Schulz iteration is what makes that affordable, approximating the orthogonalization with a handful of matrix multiplies rather than a full singular value decomposition on every step. Keep AdamW for the embeddings, the head, and the one-dimensional parameters that have no matrix structure to orthogonalize, layer on weight decay and RMS rescaling once the model is large enough to need them, and what you are left with is the recipe DeepSeek-V4 trains on.
Running it on nanoGPT taught us more than a clean win would have. Both Muon configurations beat AdamW on validation loss and held-out perplexity, and both pulled ahead noticeably in the first 200 iterations, so the faster-convergence claim holds even at this scale.
But the interesting results were the ones that complicate the story. Vanilla Muon drove training loss far lower than anything else and then overfit, its validation curve drifting back up while the weight-decay version stayed flat, a textbook demonstration of why the Moonshot fix exists.
The rescaling constant tuned for a trillion-parameter model actively hurt a three-million-parameter one, and the sweep in Step 6 showed exactly where it stopped overdriving the updates, which is the kind of lesson you only learn by watching a published default fail. And the perplexity gap between the two Muon variants turned out to be tiny, which means at this size the weight-decay fix buys you stability rather than a better model, and saying so plainly is more useful than pretending the gap was large.
If there is one thing to actually look at in the Weights & Biases workspace, it is the per-layer update RMS. Vanilla Muon spreads it across distinct minimum, mean, and maximum lines, and turning on RMS rescaling collapses those lines onto a single value. That collapse is the whole mechanism made visible, differently-shaped matrices getting pulled to a common update magnitude.
Iterate on AI agents and models faster. Try Weights & Biases today.