muonium 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- muonium-0.2.0/PKG-INFO +238 -0
- muonium-0.2.0/README.md +226 -0
- muonium-0.2.0/pyproject.toml +34 -0
- muonium-0.2.0/src/muonium/__init__.py +28 -0
- muonium-0.2.0/src/muonium/kernels/__init__.py +3 -0
- muonium-0.2.0/src/muonium/kernels/gram.py +165 -0
- muonium-0.2.0/src/muonium/optim/__init__.py +26 -0
- muonium-0.2.0/src/muonium/optim/algorithms/__init__.py +34 -0
- muonium-0.2.0/src/muonium/optim/algorithms/base.py +310 -0
- muonium-0.2.0/src/muonium/optim/algorithms/muon.py +140 -0
- muonium-0.2.0/src/muonium/optim/algorithms/normuon.py +203 -0
- muonium-0.2.0/src/muonium/optim/optim.py +719 -0
- muonium-0.2.0/src/muonium/optim/optim_lp.py +133 -0
- muonium-0.2.0/src/muonium/orthogonalize/__init__.py +15 -0
- muonium-0.2.0/src/muonium/orthogonalize/newton_schulz.py +107 -0
- muonium-0.2.0/src/muonium/orthogonalize/orthogonalize.py +204 -0
- muonium-0.2.0/src/muonium/orthogonalize/polar_express.py +115 -0
- muonium-0.2.0/src/muonium/py.typed +0 -0
- muonium-0.2.0/src/muonium/utils/__init__.py +8 -0
- muonium-0.2.0/src/muonium/utils/dtensor.py +9 -0
- muonium-0.2.0/src/muonium/utils/foreach.py +40 -0
muonium-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: muonium
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A performant, distributed-ready base for Muon optimizer research, built on PyTorch DTensor
|
|
5
|
+
Author: Tony Francis
|
|
6
|
+
Author-email: Tony Francis <tonyfrancisv@gmail.com>
|
|
7
|
+
Requires-Dist: torch
|
|
8
|
+
Requires-Dist: torchao ; extra == 'lp'
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Provides-Extra: lp
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# muonium
|
|
14
|
+
|
|
15
|
+
A performant, distributed-ready implementation of the **Muon** optimizer — and a base for
|
|
16
|
+
Muon research — built on PyTorch
|
|
17
|
+
[`DTensor`](https://docs.pytorch.org/docs/stable/distributed.tensor.html).
|
|
18
|
+
Formerly published as `dtensor-muon`.
|
|
19
|
+
|
|
20
|
+
- **Distributed by construction.** Orthogonalization runs across sharded parameters
|
|
21
|
+
(FSDP / tensor-parallel meshes), with a collective-free fast path when parameters are
|
|
22
|
+
sharded along dim 0 (the FSDP layout). For expert-parallel MoEs, orthogonalization runs
|
|
23
|
+
directly on the local sharded parameters with no collectives at all.
|
|
24
|
+
- **A base for Muon variants.** The update rule is pluggable per param group: baseline
|
|
25
|
+
Muon and [NorMuon](https://arxiv.org/abs/2510.05491) are built in, and third parties
|
|
26
|
+
register their own variants with a few dozen lines — the optimizer supplies state
|
|
27
|
+
allocation, batching, CPU offload, DTensor handling, and `torch.compile` around your
|
|
28
|
+
math. Variant names persist in checkpoints.
|
|
29
|
+
- **One optimizer for the whole model.** Weight matrices go to a Muon-family algorithm;
|
|
30
|
+
norms, biases, embeddings, and the LM head fall back to PyTorch's fused Adam/AdamW —
|
|
31
|
+
all selected per param group on a single optimizer instance.
|
|
32
|
+
- **Performant.** Compiled update kernels, a batched `foreach` driver, a fused Triton
|
|
33
|
+
Gram-matrix kernel inside Newton-Schulz, and optional 4-bit/8-bit/fp8 optimizer state
|
|
34
|
+
(`MuonLP`).
|
|
35
|
+
|
|
36
|
+
This is an open-sourcing of work done at Dream3D. This was implemented without AI tools originally. When copying the source over, Claude Fable 5 was used to audit the codebase, write tests and documentation, and fix a bug. Claude is tagged on all the commits he contributed to :)
|
|
37
|
+
|
|
38
|
+
## What is Muon?
|
|
39
|
+
|
|
40
|
+
Muon updates 2D+ parameters by replacing the momentum-smoothed gradient with its nearest
|
|
41
|
+
semi-orthogonal matrix (the matrix-sign, or "zero power", of the gradient) before applying
|
|
42
|
+
it. The orthogonalization is computed iteratively on the GPU, with two schemes available:
|
|
43
|
+
classic Newton-Schulz iteration (backed by a fused Triton Gram-matrix kernel) and
|
|
44
|
+
[Polar Express](https://arxiv.org/pdf/2505.16932), which uses precomputed coefficients for
|
|
45
|
+
faster convergence. Learning rates are scaled by each matrix's shape
|
|
46
|
+
(`sqrt(max(1, N/M))`) automatically.
|
|
47
|
+
|
|
48
|
+
Muon only applies to weight matrices. A single `Muon` instance handles the remaining
|
|
49
|
+
parameters (norms, biases, embeddings, the LM head) with PyTorch's fused Adam/AdamW,
|
|
50
|
+
selected per param group.
|
|
51
|
+
|
|
52
|
+
## Installation
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
uv pip install muonium
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Requires Python ≥ 3.12 and PyTorch ≥ 2.12.1. The `lp` extra (`muonium[lp]`) pulls in
|
|
59
|
+
[`torchao`](https://github.com/pytorch/ao), needed only for `MuonLP`.
|
|
60
|
+
|
|
61
|
+
## Usage
|
|
62
|
+
|
|
63
|
+
Route weight matrices to Muon and everything else to Adam with the `"algorithm"` key on
|
|
64
|
+
param groups:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
import torch
|
|
68
|
+
from muonium import Muon
|
|
69
|
+
|
|
70
|
+
model = ...
|
|
71
|
+
|
|
72
|
+
muon_params = [p for n, p in model.named_parameters() if p.ndim >= 2 and "embed" not in n]
|
|
73
|
+
adam_params = [p for n, p in model.named_parameters() if p.ndim < 2 or "embed" in n]
|
|
74
|
+
|
|
75
|
+
optimizer = Muon(
|
|
76
|
+
[
|
|
77
|
+
{"params": muon_params}, # "muon" is the default
|
|
78
|
+
{"params": adam_params, "algorithm": "adamw"},
|
|
79
|
+
],
|
|
80
|
+
lr=1e-3,
|
|
81
|
+
wd=0.1,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
for batch in dataloader:
|
|
85
|
+
loss = model(batch).loss
|
|
86
|
+
loss.backward()
|
|
87
|
+
optimizer.step()
|
|
88
|
+
optimizer.zero_grad()
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
The update runs through one of two drivers, selected by the `foreach` flag (constructor
|
|
92
|
+
default or per param group): the per-parameter reference loop, or a batched driver that
|
|
93
|
+
groups params by (device, dtype, shape) and uses `torch._foreach_*` ops for higher
|
|
94
|
+
throughput. The default (`None`) picks the batched driver automatically for groups whose
|
|
95
|
+
params all live on CUDA; passing `foreach=True` explicitly also opts CPU-offloaded params
|
|
96
|
+
into a per-batch CUDA round trip (`batch_size` caps how many tensors move at once).
|
|
97
|
+
|
|
98
|
+
`MuonLP` (experimental, requires the `lp` extra) stores momentum in 4-bit, 8-bit, or fp8 to
|
|
99
|
+
cut optimizer-state memory; it defaults to `foreach=False` because the quantized state
|
|
100
|
+
subclasses don't support the batched ops.
|
|
101
|
+
|
|
102
|
+
Weight decay is *cautious* by default — applied only where the update and the parameter
|
|
103
|
+
agree in sign (`u * p > 0`), following the Cautious Optimizers technique. The original Muon
|
|
104
|
+
has no cautious variant; set `use_cautious_wd=False` for plain decoupled weight decay.
|
|
105
|
+
|
|
106
|
+
The update kernels are compiled internally, so `optimizer.step()` needs no compile flag. It
|
|
107
|
+
can also sit inside a surrounding `torch.compile(fullgraph=False)` region like any PyTorch
|
|
108
|
+
optimizer; `fullgraph=True` through the step and differentiating through the update are not
|
|
109
|
+
supported.
|
|
110
|
+
|
|
111
|
+
### Options
|
|
112
|
+
|
|
113
|
+
| Option | Default | Description |
|
|
114
|
+
| --- | --- | --- |
|
|
115
|
+
| `lr` | `1e-3` | Learning rate. |
|
|
116
|
+
| `wd` | `0.1` | Weight decay. |
|
|
117
|
+
| `use_cautious_wd` | `True` | Apply decay only where update and param share a sign; `False` for plain decay. |
|
|
118
|
+
| `momentum` | `0.95` | Muon momentum. |
|
|
119
|
+
| `nesterov` | `True` | Use Nesterov momentum. |
|
|
120
|
+
| `ns_steps` | `5` | Orthogonalization iteration steps. |
|
|
121
|
+
| `orthogonalization_strategy` | `"polar_express"` | `"newton_schulz"` or `"polar_express"`. |
|
|
122
|
+
| `adam_betas` | `(0.9, 0.95)` | Betas for the Adam path. |
|
|
123
|
+
| `is_adamw` | `True` | Decoupled (AdamW) vs. coupled weight decay for the Adam path. |
|
|
124
|
+
| `fused_adam` | `None` | Select the fused Adam kernel explicitly; `None` uses PyTorch's default dispatch. |
|
|
125
|
+
| `foreach_adam` | `None` | Select the foreach Adam kernel explicitly; `None` uses PyTorch's default dispatch. |
|
|
126
|
+
| `foreach` | `None` | Batched Muon driver. `None` = auto (on for all-CUDA groups); `True` also opts CPU-offloaded groups into the CUDA round trip. |
|
|
127
|
+
| `batch_size` | `None` | Max tensors per foreach batch (`None` = unbounded). |
|
|
128
|
+
|
|
129
|
+
Most options can also be overridden per param group.
|
|
130
|
+
|
|
131
|
+
Muon groups additionally accept `flatten` (default `False`): 3D+ tensors are treated as
|
|
132
|
+
batches of 2D matrices, each orthogonalized independently (leading dims fold into the
|
|
133
|
+
batch). This is what you want for stacked/FSDP-sharded weights — it is also what lets them
|
|
134
|
+
take the sharded fast path (see Benchmarks). Set `flatten=True` — e.g. for convolutional
|
|
135
|
+
weights — to collapse them to a single `(dim0, -1)` matrix instead.
|
|
136
|
+
|
|
137
|
+
### Algorithm variants
|
|
138
|
+
|
|
139
|
+
The `"algorithm"` key selects the update rule per param group. `"muon"` (default) and the
|
|
140
|
+
`"adam"`/`"adamw"` fallback are built in, plus:
|
|
141
|
+
|
|
142
|
+
| Algorithm | Extra group options | Description |
|
|
143
|
+
| --- | --- | --- |
|
|
144
|
+
| `"normuon"` | `muon_beta2` (`0.95`) | [NorMuon](https://arxiv.org/abs/2510.05491): normalizes the orthogonalized update by a per-neuron second-moment EMA, then rescales to preserve its Frobenius norm. Adds a `variance_neuron` state buffer (one value per row). |
|
|
145
|
+
|
|
146
|
+
Variant-specific hyperparameters travel in the group dict, next to the `algorithm` key that
|
|
147
|
+
selects them:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
optimizer = Muon(
|
|
151
|
+
[
|
|
152
|
+
{"params": hidden_weights}, # baseline muon
|
|
153
|
+
{"params": qkv_weights, "algorithm": "normuon", "muon_beta2": 0.95},
|
|
154
|
+
{"params": adam_params, "algorithm": "adamw"},
|
|
155
|
+
]
|
|
156
|
+
)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Muon-family groups also accept `split_sizes` (2D params only): row blocks of a fused weight
|
|
160
|
+
(e.g. a QKV projection, `split_sizes=(q_rows, k_rows, v_rows)`) are orthogonalized — and,
|
|
161
|
+
for NorMuon, normalized — independently, matching the update separate per-block parameters
|
|
162
|
+
would receive, while the model keeps the single wide GEMM.
|
|
163
|
+
|
|
164
|
+
#### Registering your own variant
|
|
165
|
+
|
|
166
|
+
Third-party packages can add algorithms without forking: subclass `MuonAlgorithm`,
|
|
167
|
+
implement the per-tensor `update` (and optionally a batched `foreach_update` using
|
|
168
|
+
`torch._foreach_*` ops — the default loops the per-tensor reference), and register it. The
|
|
169
|
+
optimizer supplies everything around the math: state allocation from `state_spec`
|
|
170
|
+
(including `MuonLP` quantization), batching, CPU offload, DTensor orthogonalization via the
|
|
171
|
+
`orthogonalize_single` / `orthogonalize_batch` helpers, and `torch.compile`.
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
from muonium import BufferSpec, MuonAlgorithm, register_muon_algorithm
|
|
175
|
+
from muonium.optim.algorithms import orthogonalize_single
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@register_muon_algorithm
|
|
179
|
+
class MyVariant(MuonAlgorithm):
|
|
180
|
+
name = "my_variant"
|
|
181
|
+
options = {"alpha": 0.5} # per-group hyperparams and their defaults
|
|
182
|
+
state_spec = {
|
|
183
|
+
"momentum_buffer": BufferSpec(like="grad", signed=True),
|
|
184
|
+
# add extra per-param buffers here ("grad" or "grad_rows" shaped)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
def update(self, param, grad, state, lr_ratio, *, lr, alpha, ns_steps,
|
|
188
|
+
orthogonalization_strategy, split_sizes, **kwargs):
|
|
189
|
+
buf = state["momentum_buffer"]
|
|
190
|
+
... # your math; call orthogonalize_single(g, ns_steps=..., strategy=..., split_sizes=...)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
optimizer = Muon([{"params": params, "algorithm": "my_variant", "alpha": 0.7}])
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
The `algorithm` name is stored in checkpoints, so `load_state_dict` restores the right
|
|
197
|
+
variant (register it before loading).
|
|
198
|
+
|
|
199
|
+
## Benchmarks
|
|
200
|
+
|
|
201
|
+
The suite in [`benchmark/`](benchmark/) covers the kernels, single-device optimizers, and
|
|
202
|
+
the distributed orthogonalization paths; `uv run python benchmark/run.py` writes results and
|
|
203
|
+
methodology to [`benchmark/RESULTS.md`](benchmark/RESULTS.md) (`--quick` for a fast smoke
|
|
204
|
+
run).
|
|
205
|
+
|
|
206
|
+
Distributed orthogonalization, measured on 2× NVIDIA RTX PRO 6000 Blackwell
|
|
207
|
+
(PyTorch 2.12.1+cu130, NCCL, params sharded on dim 0):
|
|
208
|
+
|
|
209
|
+
| path | per-call (ms) | vs single-device |
|
|
210
|
+
| --- | --- | --- |
|
|
211
|
+
| single-device (replicated, no collectives) | 42.6 | 1.00× (ref) |
|
|
212
|
+
| FSDP fast path (`foreach_zeropower_3d_fsdp`) | 20.4 | 2.09× |
|
|
213
|
+
| general path (`foreach_zeropower` + redistribute) | 33.2 | 1.28× |
|
|
214
|
+
|
|
215
|
+
The fast path applies when parameters are sharded only along dim 0 (the FSDP layout): each
|
|
216
|
+
rank orthogonalizes its local shard with no collectives. The general path first
|
|
217
|
+
redistributes the stacked batch across the mesh, which costs communication but still beats
|
|
218
|
+
replicating.
|
|
219
|
+
|
|
220
|
+
## Development
|
|
221
|
+
|
|
222
|
+
```bash
|
|
223
|
+
git clone https://github.com/tonyf/muonium.git
|
|
224
|
+
cd muonium
|
|
225
|
+
uv sync --extra lp # --extra lp is only needed for MuonLP/torchao
|
|
226
|
+
|
|
227
|
+
uv run pytest # test suite
|
|
228
|
+
uv run ruff check # lint
|
|
229
|
+
uv run ty # type check
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
```
|
|
233
|
+
src/muonium/
|
|
234
|
+
├── optim/ # Muon (+ MuonLP) optimizers and the algorithm registry
|
|
235
|
+
├── orthogonalize/ # zeropower dispatch, Newton-Schulz & Polar Express, DTensor handling
|
|
236
|
+
├── kernels/ # Triton Gram-matrix kernel
|
|
237
|
+
└── utils/ # DTensor and foreach helpers
|
|
238
|
+
```
|
muonium-0.2.0/README.md
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
# muonium
|
|
2
|
+
|
|
3
|
+
A performant, distributed-ready implementation of the **Muon** optimizer — and a base for
|
|
4
|
+
Muon research — built on PyTorch
|
|
5
|
+
[`DTensor`](https://docs.pytorch.org/docs/stable/distributed.tensor.html).
|
|
6
|
+
Formerly published as `dtensor-muon`.
|
|
7
|
+
|
|
8
|
+
- **Distributed by construction.** Orthogonalization runs across sharded parameters
|
|
9
|
+
(FSDP / tensor-parallel meshes), with a collective-free fast path when parameters are
|
|
10
|
+
sharded along dim 0 (the FSDP layout). For expert-parallel MoEs, orthogonalization runs
|
|
11
|
+
directly on the local sharded parameters with no collectives at all.
|
|
12
|
+
- **A base for Muon variants.** The update rule is pluggable per param group: baseline
|
|
13
|
+
Muon and [NorMuon](https://arxiv.org/abs/2510.05491) are built in, and third parties
|
|
14
|
+
register their own variants with a few dozen lines — the optimizer supplies state
|
|
15
|
+
allocation, batching, CPU offload, DTensor handling, and `torch.compile` around your
|
|
16
|
+
math. Variant names persist in checkpoints.
|
|
17
|
+
- **One optimizer for the whole model.** Weight matrices go to a Muon-family algorithm;
|
|
18
|
+
norms, biases, embeddings, and the LM head fall back to PyTorch's fused Adam/AdamW —
|
|
19
|
+
all selected per param group on a single optimizer instance.
|
|
20
|
+
- **Performant.** Compiled update kernels, a batched `foreach` driver, a fused Triton
|
|
21
|
+
Gram-matrix kernel inside Newton-Schulz, and optional 4-bit/8-bit/fp8 optimizer state
|
|
22
|
+
(`MuonLP`).
|
|
23
|
+
|
|
24
|
+
This is an open-sourcing of work done at Dream3D. This was implemented without AI tools originally. When copying the source over, Claude Fable 5 was used to audit the codebase, write tests and documentation, and fix a bug. Claude is tagged on all the commits he contributed to :)
|
|
25
|
+
|
|
26
|
+
## What is Muon?
|
|
27
|
+
|
|
28
|
+
Muon updates 2D+ parameters by replacing the momentum-smoothed gradient with its nearest
|
|
29
|
+
semi-orthogonal matrix (the matrix-sign, or "zero power", of the gradient) before applying
|
|
30
|
+
it. The orthogonalization is computed iteratively on the GPU, with two schemes available:
|
|
31
|
+
classic Newton-Schulz iteration (backed by a fused Triton Gram-matrix kernel) and
|
|
32
|
+
[Polar Express](https://arxiv.org/pdf/2505.16932), which uses precomputed coefficients for
|
|
33
|
+
faster convergence. Learning rates are scaled by each matrix's shape
|
|
34
|
+
(`sqrt(max(1, N/M))`) automatically.
|
|
35
|
+
|
|
36
|
+
Muon only applies to weight matrices. A single `Muon` instance handles the remaining
|
|
37
|
+
parameters (norms, biases, embeddings, the LM head) with PyTorch's fused Adam/AdamW,
|
|
38
|
+
selected per param group.
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
uv pip install muonium
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Requires Python ≥ 3.12 and PyTorch ≥ 2.12.1. The `lp` extra (`muonium[lp]`) pulls in
|
|
47
|
+
[`torchao`](https://github.com/pytorch/ao), needed only for `MuonLP`.
|
|
48
|
+
|
|
49
|
+
## Usage
|
|
50
|
+
|
|
51
|
+
Route weight matrices to Muon and everything else to Adam with the `"algorithm"` key on
|
|
52
|
+
param groups:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import torch
|
|
56
|
+
from muonium import Muon
|
|
57
|
+
|
|
58
|
+
model = ...
|
|
59
|
+
|
|
60
|
+
muon_params = [p for n, p in model.named_parameters() if p.ndim >= 2 and "embed" not in n]
|
|
61
|
+
adam_params = [p for n, p in model.named_parameters() if p.ndim < 2 or "embed" in n]
|
|
62
|
+
|
|
63
|
+
optimizer = Muon(
|
|
64
|
+
[
|
|
65
|
+
{"params": muon_params}, # "muon" is the default
|
|
66
|
+
{"params": adam_params, "algorithm": "adamw"},
|
|
67
|
+
],
|
|
68
|
+
lr=1e-3,
|
|
69
|
+
wd=0.1,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
for batch in dataloader:
|
|
73
|
+
loss = model(batch).loss
|
|
74
|
+
loss.backward()
|
|
75
|
+
optimizer.step()
|
|
76
|
+
optimizer.zero_grad()
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The update runs through one of two drivers, selected by the `foreach` flag (constructor
|
|
80
|
+
default or per param group): the per-parameter reference loop, or a batched driver that
|
|
81
|
+
groups params by (device, dtype, shape) and uses `torch._foreach_*` ops for higher
|
|
82
|
+
throughput. The default (`None`) picks the batched driver automatically for groups whose
|
|
83
|
+
params all live on CUDA; passing `foreach=True` explicitly also opts CPU-offloaded params
|
|
84
|
+
into a per-batch CUDA round trip (`batch_size` caps how many tensors move at once).
|
|
85
|
+
|
|
86
|
+
`MuonLP` (experimental, requires the `lp` extra) stores momentum in 4-bit, 8-bit, or fp8 to
|
|
87
|
+
cut optimizer-state memory; it defaults to `foreach=False` because the quantized state
|
|
88
|
+
subclasses don't support the batched ops.
|
|
89
|
+
|
|
90
|
+
Weight decay is *cautious* by default — applied only where the update and the parameter
|
|
91
|
+
agree in sign (`u * p > 0`), following the Cautious Optimizers technique. The original Muon
|
|
92
|
+
has no cautious variant; set `use_cautious_wd=False` for plain decoupled weight decay.
|
|
93
|
+
|
|
94
|
+
The update kernels are compiled internally, so `optimizer.step()` needs no compile flag. It
|
|
95
|
+
can also sit inside a surrounding `torch.compile(fullgraph=False)` region like any PyTorch
|
|
96
|
+
optimizer; `fullgraph=True` through the step and differentiating through the update are not
|
|
97
|
+
supported.
|
|
98
|
+
|
|
99
|
+
### Options
|
|
100
|
+
|
|
101
|
+
| Option | Default | Description |
|
|
102
|
+
| --- | --- | --- |
|
|
103
|
+
| `lr` | `1e-3` | Learning rate. |
|
|
104
|
+
| `wd` | `0.1` | Weight decay. |
|
|
105
|
+
| `use_cautious_wd` | `True` | Apply decay only where update and param share a sign; `False` for plain decay. |
|
|
106
|
+
| `momentum` | `0.95` | Muon momentum. |
|
|
107
|
+
| `nesterov` | `True` | Use Nesterov momentum. |
|
|
108
|
+
| `ns_steps` | `5` | Orthogonalization iteration steps. |
|
|
109
|
+
| `orthogonalization_strategy` | `"polar_express"` | `"newton_schulz"` or `"polar_express"`. |
|
|
110
|
+
| `adam_betas` | `(0.9, 0.95)` | Betas for the Adam path. |
|
|
111
|
+
| `is_adamw` | `True` | Decoupled (AdamW) vs. coupled weight decay for the Adam path. |
|
|
112
|
+
| `fused_adam` | `None` | Select the fused Adam kernel explicitly; `None` uses PyTorch's default dispatch. |
|
|
113
|
+
| `foreach_adam` | `None` | Select the foreach Adam kernel explicitly; `None` uses PyTorch's default dispatch. |
|
|
114
|
+
| `foreach` | `None` | Batched Muon driver. `None` = auto (on for all-CUDA groups); `True` also opts CPU-offloaded groups into the CUDA round trip. |
|
|
115
|
+
| `batch_size` | `None` | Max tensors per foreach batch (`None` = unbounded). |
|
|
116
|
+
|
|
117
|
+
Most options can also be overridden per param group.
|
|
118
|
+
|
|
119
|
+
Muon groups additionally accept `flatten` (default `False`): 3D+ tensors are treated as
|
|
120
|
+
batches of 2D matrices, each orthogonalized independently (leading dims fold into the
|
|
121
|
+
batch). This is what you want for stacked/FSDP-sharded weights — it is also what lets them
|
|
122
|
+
take the sharded fast path (see Benchmarks). Set `flatten=True` — e.g. for convolutional
|
|
123
|
+
weights — to collapse them to a single `(dim0, -1)` matrix instead.
|
|
124
|
+
|
|
125
|
+
### Algorithm variants
|
|
126
|
+
|
|
127
|
+
The `"algorithm"` key selects the update rule per param group. `"muon"` (default) and the
|
|
128
|
+
`"adam"`/`"adamw"` fallback are built in, plus:
|
|
129
|
+
|
|
130
|
+
| Algorithm | Extra group options | Description |
|
|
131
|
+
| --- | --- | --- |
|
|
132
|
+
| `"normuon"` | `muon_beta2` (`0.95`) | [NorMuon](https://arxiv.org/abs/2510.05491): normalizes the orthogonalized update by a per-neuron second-moment EMA, then rescales to preserve its Frobenius norm. Adds a `variance_neuron` state buffer (one value per row). |
|
|
133
|
+
|
|
134
|
+
Variant-specific hyperparameters travel in the group dict, next to the `algorithm` key that
|
|
135
|
+
selects them:
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
optimizer = Muon(
|
|
139
|
+
[
|
|
140
|
+
{"params": hidden_weights}, # baseline muon
|
|
141
|
+
{"params": qkv_weights, "algorithm": "normuon", "muon_beta2": 0.95},
|
|
142
|
+
{"params": adam_params, "algorithm": "adamw"},
|
|
143
|
+
]
|
|
144
|
+
)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Muon-family groups also accept `split_sizes` (2D params only): row blocks of a fused weight
|
|
148
|
+
(e.g. a QKV projection, `split_sizes=(q_rows, k_rows, v_rows)`) are orthogonalized — and,
|
|
149
|
+
for NorMuon, normalized — independently, matching the update separate per-block parameters
|
|
150
|
+
would receive, while the model keeps the single wide GEMM.
|
|
151
|
+
|
|
152
|
+
#### Registering your own variant
|
|
153
|
+
|
|
154
|
+
Third-party packages can add algorithms without forking: subclass `MuonAlgorithm`,
|
|
155
|
+
implement the per-tensor `update` (and optionally a batched `foreach_update` using
|
|
156
|
+
`torch._foreach_*` ops — the default loops the per-tensor reference), and register it. The
|
|
157
|
+
optimizer supplies everything around the math: state allocation from `state_spec`
|
|
158
|
+
(including `MuonLP` quantization), batching, CPU offload, DTensor orthogonalization via the
|
|
159
|
+
`orthogonalize_single` / `orthogonalize_batch` helpers, and `torch.compile`.
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
from muonium import BufferSpec, MuonAlgorithm, register_muon_algorithm
|
|
163
|
+
from muonium.optim.algorithms import orthogonalize_single
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@register_muon_algorithm
|
|
167
|
+
class MyVariant(MuonAlgorithm):
|
|
168
|
+
name = "my_variant"
|
|
169
|
+
options = {"alpha": 0.5} # per-group hyperparams and their defaults
|
|
170
|
+
state_spec = {
|
|
171
|
+
"momentum_buffer": BufferSpec(like="grad", signed=True),
|
|
172
|
+
# add extra per-param buffers here ("grad" or "grad_rows" shaped)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
def update(self, param, grad, state, lr_ratio, *, lr, alpha, ns_steps,
|
|
176
|
+
orthogonalization_strategy, split_sizes, **kwargs):
|
|
177
|
+
buf = state["momentum_buffer"]
|
|
178
|
+
... # your math; call orthogonalize_single(g, ns_steps=..., strategy=..., split_sizes=...)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
optimizer = Muon([{"params": params, "algorithm": "my_variant", "alpha": 0.7}])
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
The `algorithm` name is stored in checkpoints, so `load_state_dict` restores the right
|
|
185
|
+
variant (register it before loading).
|
|
186
|
+
|
|
187
|
+
## Benchmarks
|
|
188
|
+
|
|
189
|
+
The suite in [`benchmark/`](benchmark/) covers the kernels, single-device optimizers, and
|
|
190
|
+
the distributed orthogonalization paths; `uv run python benchmark/run.py` writes results and
|
|
191
|
+
methodology to [`benchmark/RESULTS.md`](benchmark/RESULTS.md) (`--quick` for a fast smoke
|
|
192
|
+
run).
|
|
193
|
+
|
|
194
|
+
Distributed orthogonalization, measured on 2× NVIDIA RTX PRO 6000 Blackwell
|
|
195
|
+
(PyTorch 2.12.1+cu130, NCCL, params sharded on dim 0):
|
|
196
|
+
|
|
197
|
+
| path | per-call (ms) | vs single-device |
|
|
198
|
+
| --- | --- | --- |
|
|
199
|
+
| single-device (replicated, no collectives) | 42.6 | 1.00× (ref) |
|
|
200
|
+
| FSDP fast path (`foreach_zeropower_3d_fsdp`) | 20.4 | 2.09× |
|
|
201
|
+
| general path (`foreach_zeropower` + redistribute) | 33.2 | 1.28× |
|
|
202
|
+
|
|
203
|
+
The fast path applies when parameters are sharded only along dim 0 (the FSDP layout): each
|
|
204
|
+
rank orthogonalizes its local shard with no collectives. The general path first
|
|
205
|
+
redistributes the stacked batch across the mesh, which costs communication but still beats
|
|
206
|
+
replicating.
|
|
207
|
+
|
|
208
|
+
## Development
|
|
209
|
+
|
|
210
|
+
```bash
|
|
211
|
+
git clone https://github.com/tonyf/muonium.git
|
|
212
|
+
cd muonium
|
|
213
|
+
uv sync --extra lp # --extra lp is only needed for MuonLP/torchao
|
|
214
|
+
|
|
215
|
+
uv run pytest # test suite
|
|
216
|
+
uv run ruff check # lint
|
|
217
|
+
uv run ty # type check
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
```
|
|
221
|
+
src/muonium/
|
|
222
|
+
├── optim/ # Muon (+ MuonLP) optimizers and the algorithm registry
|
|
223
|
+
├── orthogonalize/ # zeropower dispatch, Newton-Schulz & Polar Express, DTensor handling
|
|
224
|
+
├── kernels/ # Triton Gram-matrix kernel
|
|
225
|
+
└── utils/ # DTensor and foreach helpers
|
|
226
|
+
```
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "muonium"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "A performant, distributed-ready base for Muon optimizer research, built on PyTorch DTensor"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Tony Francis", email = "tonyfrancisv@gmail.com" }
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"torch",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[project.optional-dependencies]
|
|
15
|
+
lp = [
|
|
16
|
+
"torchao",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["uv_build>=0.11.7,<0.12.0"]
|
|
21
|
+
build-backend = "uv_build"
|
|
22
|
+
|
|
23
|
+
[dependency-groups]
|
|
24
|
+
dev = [
|
|
25
|
+
"pytest>=9.1.1",
|
|
26
|
+
"ruff>=0.15.18",
|
|
27
|
+
"ty>=0.0.51",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[tool.ruff]
|
|
31
|
+
line-length = 96
|
|
32
|
+
indent-width = 4
|
|
33
|
+
lint.dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
|
|
34
|
+
lint.ignore = ["F722", "E731", "F821", "E741"]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""muonium: a distributed-ready Muon optimizer built on PyTorch DTensor."""
|
|
2
|
+
|
|
3
|
+
from .optim import (
|
|
4
|
+
BufferSpec,
|
|
5
|
+
Muon,
|
|
6
|
+
MuonAlgorithm,
|
|
7
|
+
get_algorithm,
|
|
8
|
+
register_muon_algorithm,
|
|
9
|
+
registered_algorithms,
|
|
10
|
+
)
|
|
11
|
+
from .orthogonalize import OrthogonalizationStrategy
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"BufferSpec",
|
|
15
|
+
"Muon",
|
|
16
|
+
"MuonAlgorithm",
|
|
17
|
+
"OrthogonalizationStrategy",
|
|
18
|
+
"get_algorithm",
|
|
19
|
+
"register_muon_algorithm",
|
|
20
|
+
"registered_algorithms",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from .optim import MuonLP
|
|
25
|
+
|
|
26
|
+
__all__ += ["MuonLP"]
|
|
27
|
+
except ImportError:
|
|
28
|
+
pass
|