Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions ext/OptimisersReactantExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,11 @@ Optimisers._norm(dx::Union{ConcretePJRTArray,ConcreteIFRTArray}, p::Real) =
# While tracing `apply!` with an untyped gradient, inference reaches this method, and on
# Julia 1.10 optimising the inferred `@jit` crashes (φ node not at the start of a block).
# `invokelatest` keeps it out of inference.
Optimisers._newton_schulz5(G::Union{ConcretePJRTArray{<:Any,2},ConcreteIFRTArray{<:Any,2}}) =
Base.invokelatest(_compiled_newton_schulz5, G)
_compiled_newton_schulz5(G) = Reactant.@jit Optimisers._newton_schulz5(G)
Optimisers._newton_schulz(G::Union{ConcretePJRTArray{<:Any,2},ConcreteIFRTArray{<:Any,2}},
coefficients, steps::Int, epsilon) =
Base.invokelatest(_compiled_newton_schulz, G, coefficients, steps, epsilon)
_compiled_newton_schulz(G, coefficients, steps, epsilon) =
Reactant.@jit Optimisers._newton_schulz(G, coefficients, steps, epsilon)

const ReactantStyle = Union{
Broadcast.ArrayStyle{ConcretePJRTArray}, Broadcast.ArrayStyle{ConcreteIFRTArray},
Expand Down
116 changes: 96 additions & 20 deletions src/rules.jl
Original file line number Diff line number Diff line change
Expand Up @@ -628,23 +628,27 @@ function apply!(o::AdaBelief, state, x::AbstractArray{T}, dx) where T
end

"""
Muon(η = 0.02, μ = 0.95, λ = 0; nesterov = true)
Muon(; [eta, mu, lambda, nesterov])
Muon(η = 0.02, μ = 0.95, λ = 0, ϵ = 1e-7; nesterov = true, adjust_lr_fn = :original,
ns_coefficients = (3.4445, -4.7750, 2.0315), ns_steps = 5)
Muon(; [eta, mu, lambda, epsilon, nesterov, adjust_lr_fn, ns_coefficients, ns_steps])

[Muon](https://kellerjordan.github.io/posts/muon/) optimiser for matrix parameters,
following Keller Jordan's [reference implementation](https://github.com/KellerJordan/Muon).

Each step updates the momentum `m = μ * m + (1 - μ) * dx`, then orthogonalises it: `O` has
the same singular vectors as `m`, but singular values close to one. (With `nesterov = true`,
the default, this acts on `μ * m + (1 - μ) * dx` instead.) A parameter `x` of size `(r, c)`
then changes by `x .-= η .* (sqrt(max(1, r / c)) .* O .+ λ .* x)`.
then changes by `x .-= η .* (γ .* O .+ λ .* x)`, where the scaling `γ` depends on the
shape, and by default is `sqrt(max(1, r / c))`.
For Flux's `Dense`, whose weight is `(out, in)` like that of PyTorch's `Linear`,
this is the same scaling as in the reference.
this is the same scaling as in the reference. Note that `γ` multiplies only `O`:
the weight decay uses `η` alone, as in the reference and in PyTorch.

`O` comes from five steps of a quintic Newton-Schulz iteration, starting from `m / norm(m)`.
Its coefficients are tuned for speed rather than convergence: singular values of
`m / norm(m)` above about `0.003` end up between `0.68` and `1.2`, and smaller ones stay smaller.
This runs in the element type of `x`, while the reference uses `BFloat16`.
`O` comes from `ns_steps` steps of a quintic Newton-Schulz iteration, starting from
`m / (norm(m) + ϵ)`. The default coefficients are tuned for speed rather than convergence:
after five steps, singular values of `m / norm(m)` above about `0.003` end up between
`0.68` and `1.2`, and smaller ones stay smaller. This runs in the element type of `x`,
while the reference uses `BFloat16`.

# Parameters
- Learning rate (`η == eta`): Amount by which gradients are discounted before updating
Expand All @@ -653,8 +657,33 @@ This runs in the element type of `x`, while the reference uses `BFloat16`.
with `0 ≤ μ < 1`.
- Weight decay (`λ == lambda`): Decoupled weight decay, multiplied by the learning rate,
as in the reference and in [`AdamW`](@ref).
- Machine epsilon (`ϵ == epsilon`): Constant added to `norm(m)` before dividing by it,
to prevent division by zero when the momentum is zero.
- Keyword `nesterov`: If `true`, orthogonalise `μ * m + (1 - μ) * dx` (with the new `m`)
instead of `m`.
- Keyword `adjust_lr_fn`: Which shape-dependent scaling `γ` to apply to `O`, one of
`:original`, `:match_rms_adamw`, or `:spectral_unclamped`, described below.
- Keyword `ns_coefficients`: The three coefficients `(a, b, c)` of the quintic iteration,
which acts on each singular value as `σ ↦ a * σ + b * σ^3 + c * σ^5`.
- Keyword `ns_steps`: How many times to apply that iteration, with `ns_steps ≥ 1`.

# Scaling by shape

For a parameter of size `(r, c)`, the keyword `adjust_lr_fn` selects `γ` as in PyTorch's
`Muon`:

| `adjust_lr_fn` | `γ` | |
|:---|:---|:---|
| `:original` | `sqrt(max(1, r / c))` | the default, as in the reference |
| `:match_rms_adamw` | `0.2 * sqrt(max(r, c))` | so that learning rates transfer from `AdamW` |
| `:spectral_unclamped` | `sqrt(r / c)` | like `:original`, without the clamp at one |

!!! warning
These differ by more than a little: for a `(1024, 1024)` parameter, `:original` gives
`γ = 1` while `:match_rms_adamw` gives `γ = 6.4`. The point of the latter is that it
rescales the update to the size `AdamW` would take, so that a learning rate tuned for
`AdamW` can be reused. Changing `adjust_lr_fn` without also changing `η` will not
give a comparable step.

# Which parameters

Expand Down Expand Up @@ -682,7 +711,7 @@ julia> fmap(s -> nameof(typeof(s.rule)), state; exclude = s -> s isa Optimisers.
(embed = :AdamW, hidden = (weight = :Muon, bias = :AdamW), head = :AdamW)

julia> state.hidden.weight
Leaf(Muon(eta=0.02, mu=0.95, lambda=0.0, nesterov=true), [0.0, 0.0, 0.0, …])
Leaf(Muon(eta=0.02, mu=0.95, lambda=0.0, epsilon=1.0e-7, nesterov=true, adjust_lr_fn=:original, ns_coefficients=(3.4445, -4.775, 2.0315), ns_steps=5), [0.0, 0.0, 0.0, …])
```

As Muon's learning rate is much larger than AdamW's, a schedule should change each
Expand All @@ -697,20 +726,49 @@ julia> state.hidden.weight.rule.eta, state.hidden.bias.rule.eta
(0.01, 0.0003)
```
"""
struct Muon{Teta,Tmu,Tlambda} <: AbstractRule
struct Muon{Teta,Tmu,Tlambda,Teps,Tcoef} <: AbstractRule
eta::Teta
mu::Tmu
lambda::Tlambda
epsilon::Teps
nesterov::Bool
adjust_lr_fn::Symbol
ns_coefficients::Tcoef
ns_steps::Int
end

function Muon(η, μ = 0.95, λ = 0.0, ϵ = 1e-7; nesterov::Bool = true,
adjust_lr_fn::Symbol = :original,
ns_coefficients = (3.4445, -4.7750, 2.0315), ns_steps::Integer = 5)
_muon_check(η, μ, adjust_lr_fn, ns_coefficients, ns_steps)
return Muon(float(η), float(μ), float(λ), float(ϵ), nesterov, adjust_lr_fn,
map(float, Tuple(ns_coefficients)), Int(ns_steps))
end

function Muon(η, μ = 0.95, λ = 0.0; nesterov::Bool = true)
const _MUON_ADJUST_LR_FNS = (:original, :match_rms_adamw, :spectral_unclamped)

Muon(; eta = 0.02, mu = 0.95, lambda = 0.0, epsilon = 1e-7, kw...) =
Muon(eta, mu, lambda, epsilon; kw...)

function _muon_check(η, μ, adjust_lr_fn, ns_coefficients, ns_steps)
η < 0 && throw(DomainError(η, "the learning rate cannot be negative"))
0 <= μ < 1 || throw(DomainError(μ, "the momentum must satisfy 0 ≤ μ < 1"))
return Muon(float(η), float(μ), float(λ), nesterov)
adjust_lr_fn in _MUON_ADJUST_LR_FNS || _muon_bad_adjust_lr_fn(adjust_lr_fn)
length(ns_coefficients) == 3 || throw(ArgumentError(
"Muon needs three Newton-Schulz coefficients, got $(length(ns_coefficients))"))
ns_steps > 0 || throw(DomainError(ns_steps, "the number of Newton-Schulz steps must be positive"))
return nothing
end

Muon(; eta = 0.02, mu = 0.95, lambda = 0.0, kw...) = Muon(eta, mu, lambda; kw...)
# `_adjust` rebuilds a rule field by field, skipping the keyword constructor above, so
# repeat its checks here. Every path into `adjust` for one rule reaches one of these two.
adjust(r::Muon, eta::Real) = _muon_checked(_adjust(r, (; eta)))
adjust(r::Muon; kw...) = _muon_checked(_adjust(r, NamedTuple(kw)))

function _muon_checked(r::Muon)
_muon_check(r.eta, r.mu, r.adjust_lr_fn, r.ns_coefficients, r.ns_steps)
return r # unchanged, so that `adjust!` can store it back in the same `Leaf`
end

init(o::Muon, x::AbstractMatrix) = zero(x)
init(o::Muon, x::AbstractArray) = _muon_matrix_only(x)
Expand All @@ -719,8 +777,9 @@ function apply!(o::Muon, mom, x::AbstractMatrix{T}, dx) where T
η, μ, λ = T(o.eta), T(o.mu), T(o.lambda)

@.. mom = μ * mom + (1 - μ) * dx
O = _newton_schulz5(o.nesterov ? (@. μ * mom + (1 - μ) * dx) : mom)
γ = real(T)(sqrt(max(1, size(x, 1) / size(x, 2))))
O = _newton_schulz(o.nesterov ? (@. μ * mom + (1 - μ) * dx) : mom,
o.ns_coefficients, o.ns_steps, o.epsilon)
γ = real(T)(_muon_lr_scale(o.adjust_lr_fn, size(x, 1), size(x, 2)))

return mom, @lazy η * (γ * O + λ * x)
end
Expand All @@ -729,20 +788,37 @@ apply!(o::Muon, state, x::AbstractArray, dx) = _muon_matrix_only(x)
_muon_matrix_only(x) = throw(ArgumentError("Muon only accepts matrices, not $(summary(x)). " *
"Use another rule such as AdamW for this parameter, as explained in the docstring of Muon."))

# The shape-dependent scaling of `O`, named as in PyTorch's `Muon`. Not applied to the
# weight decay, which uses `η` alone. Branching beats dispatching on `Val(name)`, which
# inference cannot resolve from a field, leaving `apply!` returning `Any`.
function _muon_lr_scale(name::Symbol, r, c)
name === :original && return sqrt(max(1, r / c))
name === :match_rms_adamw && return 0.2 * sqrt(max(r, c))
name === :spectral_unclamped && return sqrt(r / c)
# Not reachable through the constructor or `adjust`, both of which check. Still needed:
# without it an unknown name falls through to `false`, making γ zero without complaint.
return _muon_bad_adjust_lr_fn(name)
end

_muon_bad_adjust_lr_fn(name) = throw(ArgumentError("Muon's adjust_lr_fn must be one of " *
"$(join(repr.(_MUON_ADJUST_LR_FNS), ", ")), not $(repr(name))"))

function Base.show(io::IO, o::Muon)
print(io, "Muon(eta=$(o.eta), mu=$(o.mu), lambda=$(o.lambda), nesterov=$(o.nesterov))")
print(io, "Muon(eta=$(o.eta), mu=$(o.mu), lambda=$(o.lambda), epsilon=$(o.epsilon), ",
"nesterov=$(o.nesterov), adjust_lr_fn=$(repr(o.adjust_lr_fn)), ",
"ns_coefficients=$(o.ns_coefficients), ns_steps=$(o.ns_steps))")
end

# Keller Jordan's quintic iteration, X ← a X + (b A + c A²) X with A = X X', from X = G / ‖G‖.
# The Gram matrix is taken on the shorter side, and the buffers are reused across steps.
function _newton_schulz5(G::AbstractMatrix{T}) where T
a, b, c = real(T).((3.4445, -4.7750, 2.0315))
function _newton_schulz(G::AbstractMatrix{T}, coefficients, steps::Int, epsilon) where T
a, b, c = real(T).(coefficients)
X = similar(G)
X .= G ./ (sqrt.(_sumabs2(G)) .+ _eps(T, 1e-7)) # reduces with dims to avoid a GPU readback
X .= G ./ (sqrt.(_sumabs2(G)) .+ _eps(T, epsilon)) # reduces with dims to avoid a GPU readback
tall = size(X, 1) > size(X, 2)
k = min(size(X)...)
A, B, Y = similar(X, k, k), similar(X, k, k), similar(X)
for _ in 1:5
for _ in 1:steps
tall ? mul!(A, X', X) : mul!(A, X, X')
copyto!(B, A)
mul!(B, A, A, c, b)
Expand Down
84 changes: 71 additions & 13 deletions test/rules.jl
Original file line number Diff line number Diff line change
Expand Up @@ -424,12 +424,50 @@ end

@testset "Muon" begin
@testset "constructors" begin
@test Muon(0.1, 0.9, 0.01; nesterov = false) === Muon(eta = 0.1, mu = 0.9, lambda = 0.01, nesterov = false)
@test Muon(0.1, 0.9, 0.01, 1e-6; nesterov = false) ===
Muon(eta = 0.1, mu = 0.9, lambda = 0.01, epsilon = 1e-6, nesterov = false)
@test Optimisers.adjust(Muon(nesterov = false), 0.1) === Muon(0.1; nesterov = false)
@test_throws DomainError Muon(-0.1)
@test_throws DomainError Muon(0.02, 1)
@test_throws TypeError Muon(nesterov = 1)
@test sprint(show, Muon()) == "Muon(eta=0.02, mu=0.95, lambda=0.0, nesterov=true)"
@test Muon(ns_coefficients = [3, -4, 2], ns_steps = 3) === Muon(ns_coefficients = (3.0, -4.0, 2.0), ns_steps = 3)
@test Optimisers.adjust(Muon(ns_steps = 3); ns_coefficients = (3, -4, 2)) === Muon(ns_coefficients = (3.0, -4.0, 2.0), ns_steps = 3)
@test_throws ArgumentError Muon(ns_coefficients = (3.4445, -4.7750))
@test_throws DomainError Muon(ns_steps = 0)
@test_throws DomainError Muon(ns_steps = -1)
@test_throws ArgumentError Muon(adjust_lr_fn = :bogus)

# `adjust` rebuilds field by field, skipping the keyword constructor, so it checks too:
@test_throws ArgumentError Optimisers.adjust(Muon(); adjust_lr_fn = :bogus)
@test_throws ArgumentError Optimisers.adjust(Muon(); ns_coefficients = (1.0, 2.0))
@test_throws DomainError Optimisers.adjust(Muon(); ns_steps = 0)
@test_throws DomainError Optimisers.adjust(Muon(); mu = 1.0)
@test_throws DomainError Optimisers.adjust(Muon(), -0.1) # the positional `eta` path
# Which covers `adjust!` on a tree, the filter and rule-type forms, and a wrapped Muon,
# all of which reach those methods through `_adjust_rule`:
@test_throws DomainError Optimisers.adjust!(Optimisers.setup(Muon(), rand(2, 2)), -0.1)
@test_throws DomainError Optimisers.adjust!(Optimisers.setup(Muon(), rand(2, 2)), Muon; mu = 1.0)
@test_throws DomainError Optimisers.adjust(OptimiserChain(ClipNorm(), Muon()); mu = 1.0)
@test_throws DomainError Optimisers.adjust(MixedPrecision(Float64, Muon()); ns_steps = 0)
# An unrecognised keyword is still silently ignored, as it is for every rule:
@test Optimisers.adjust(Muon(); zeta = "this does nothing") === Muon()
# Valid adjustments still go through, keeping the rule type so `adjust!` can store them:
@test Optimisers.adjust(Muon(), 0.1) === Muon(0.1)
@test Optimisers.adjust(Muon(); adjust_lr_fn = :match_rms_adamw) ===
Muon(adjust_lr_fn = :match_rms_adamw)
@test sprint(show, Muon()) == "Muon(eta=0.02, mu=0.95, lambda=0.0, epsilon=1.0e-7, " *
"nesterov=true, adjust_lr_fn=:original, ns_coefficients=(3.4445, -4.775, 2.0315), ns_steps=5)"
end

@testset "scaling by shape" begin
# The three variants of PyTorch's `adjust_lr_fn`, on square, tall and wide matrices.
@test Optimisers._muon_lr_scale(:original, 1024, 1024) == 1
@test Optimisers._muon_lr_scale(:original, 8, 2) ≈ 2
@test Optimisers._muon_lr_scale(:original, 2, 8) == 1 # clamped at one
@test Optimisers._muon_lr_scale(:spectral_unclamped, 2, 8) ≈ 0.5 # not clamped
@test Optimisers._muon_lr_scale(:spectral_unclamped, 8, 2) ≈ 2 # agrees above one
@test Optimisers._muon_lr_scale(:match_rms_adamw, 1024, 1024) ≈ 6.4
@test Optimisers._muon_lr_scale(:match_rms_adamw, 2, 8) ≈ 0.2 * sqrt(8)
end

@testset "only matrices" begin
Expand All @@ -438,29 +476,49 @@ end
@test_throws ArgumentError Optimisers.apply!(Muon(), nothing, rand(3), rand(3))
end

# Five steps of X ← a X + b (X X') X + c (X X')² X act on each singular value of X
# as σ ↦ a σ + b σ³ + c σ⁵, here with Keller Jordan's coefficients:
p5(σ) = foldl((σ, _) -> 3.4445σ - 4.7750σ^3 + 2.0315σ^5, 1:5; init = σ)
orthogonalise(G) = (F = svd(G); F.U * Diagonal(p5.(F.S ./ (norm(G) + 1e-7))) * F.Vt)
# Each step of X ← a X + b (X X') X + c (X X')² X acts on every singular value of X
# as σ ↦ a σ + b σ³ + c σ⁵, with Keller Jordan's coefficients by default:
KELLER = (3.4445, -4.7750, 2.0315)
function orthogonalise(G, (a, b, c) = KELLER, steps = 5, ϵ = 1e-7)
F = svd(G)
p(σ) = foldl((σ, _) -> a * σ + b * σ^3 + c * σ^5, 1:steps; init = σ)
return F.U * Diagonal(p.(F.S ./ (norm(G) + ϵ))) * F.Vt
end

@testset "Newton-Schulz, $T, size $sz" for T in (Float64, ComplexF64), sz in ((6, 4), (4, 6), (5, 5))
@testset "Newton-Schulz, $T, size $sz, $steps steps of $coef, eps $ϵ" for
T in (Float64, ComplexF64), sz in ((6, 4), (4, 6), (5, 5)),
(coef, steps) in ((KELLER, 5), (KELLER, 1), ((3, -4, 2), 3), ((1.5, -0.5, 0.0), 7)),
ϵ in (1e-7, 0.1)
G = randn(T, sz)
@test Optimisers._newton_schulz5(G) ≈ orthogonalise(G)
@test Optimisers._newton_schulz(G, coef, steps, ϵ) ≈ orthogonalise(G, coef, steps, ϵ)
end

@testset "epsilon prevents dividing by zero, $T" for T in (Float32, Float64)
# A zero gradient leaves the momentum zero, so `norm(m)` is zero on the first step.
x = randn(T, 4, 3)
st, x′ = Optimisers.update(Optimisers.setup(Muon(), x), x, zeros(T, 4, 3))
@test x′ ≈ x # no NaNs: the update is zero, as `0 / ϵ == 0`
@test !any(isnan, st.state)
end

@testset "reference algorithm, nesterov = $nesterov, size $sz" for nesterov in (true, false),
sz in ((6, 4), (4, 6))
@testset "reference algorithm, nesterov = $nesterov, size $sz, $steps steps of $coef, $fn" for
nesterov in (true, false), sz in ((6, 4), (4, 6)),
(coef, steps) in ((KELLER, 5), ((3, -4, 2), 3)),
fn in (:original, :match_rms_adamw, :spectral_unclamped)
# Keller Jordan's `muon_update` and `Muon.step`. From zero momentum the first two
# orthogonalised inputs are parallel with or without `nesterov`, so take three steps.
# Note that γ multiplies only the orthogonalised update, never the weight decay.
η, μ, λ = 0.02, 0.9, 0.1
γ = Optimisers._muon_lr_scale(fn, sz...)
x = randn(sz)
st = Optimisers.setup(Muon(η, μ, λ; nesterov), x)
st = Optimisers.setup(
Muon(η, μ, λ; nesterov, adjust_lr_fn = fn, ns_coefficients = coef, ns_steps = steps), x)
x_ref, m = copy(x), zero(x)
for _ in 1:3
g = randn(sz)
m = μ * m + (1 - μ) * g
u = nesterov ? μ * m + (1 - μ) * g : m
x_ref = (1 - η * λ) * x_ref - η * sqrt(max(1, sz[1] / sz[2])) * orthogonalise(u)
x_ref = (1 - η * λ) * x_ref - η * γ * orthogonalise(u, coef, steps)
st, x = Optimisers.update(st, x, g)
end
@test x ≈ x_ref
Expand All @@ -476,7 +534,7 @@ end

@testset "type stability, size $sz" for sz in ((8, 4), (4, 8))
x = randn(Float32, sz)
@inferred Optimisers._newton_schulz5(x)
@inferred Optimisers._newton_schulz(x, KELLER, 5, 1e-7)
@inferred Optimisers.apply!(Muon(), zero(x), x, x)
end

Expand Down
Loading