bird-of-paradise commited on
Commit
812db4f
·
verified ·
1 Parent(s): 65ce2fe

first commit

Browse files
Assets/Muon_performence_comparison_CIFAR10.png ADDED

Git LFS Details

  • SHA256: e22a3f589fb5f347368d94930cd45107df6843509c77ac7c7c94b5ebe95650cb
  • Pointer size: 131 Bytes
  • Size of remote file: 503 kB
Assets/Muon_performence_comparison_MNIST.png ADDED

Git LFS Details

  • SHA256: 1e67bca781d1342655a77a29dad768ef6acf50be8ded64a1e2249f86ffc7c899
  • Pointer size: 131 Bytes
  • Size of remote file: 311 kB
Assets/Newton-Schulz_Orthogonalization_on_Singular_Values.png ADDED

Git LFS Details

  • SHA256: 10d62d5d16479faab3c66da422ea267972d983f8ea077638db416c372eb06eb2
  • Pointer size: 131 Bytes
  • Size of remote file: 252 kB
Muon.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
README.md CHANGED
@@ -1,3 +1,273 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ tags:
6
+ - optimization
7
+ - muon
8
+ - deep-learning
9
+ - pytorch
10
+ - neural-networks
11
+ - tutorial
12
+ datasets:
13
+ - mnist
14
+ - cifar10
15
+ ---
16
+
17
+ # Understanding the Muon Optimizer: Theory and Implementation
18
+ ## 📘 Contents
19
+
20
+ 1. [Introduction to Muon](#Introduction)
21
+ 2. [The Problem: Skewed Singular Values](#1.-The-Problem:-Skewed-SingularValue-Distributions)
22
+ 3. [Newton-Schulz Orthogonalization](#The-Newton-Schulz-Iteration)
23
+ 4. [Implementation Details](#Implementation-Deep-Dive)
24
+ 5. [Practical Performance Analysis](#Performance-Evaluation)
25
+ 6. [Lessons Learned](#Lessons-Learned-from-Implementing-Muon)
26
+ 7. [When to Use Muon](#When-to-Use-Muon)
27
+
28
+ ## 🧪 Try It Yourself
29
+
30
+ The included [Colab notebook](./Muon.ipynb) allows you to run all experiments and implement Muon from scratch.
31
+
32
+
33
+
34
+ ## Introduction
35
+
36
+ The Muon optimizer, introduced by Keller Jordan in October 2024, represents a significant advancement in neural network optimization. Unlike traditional optimizers that treat all parameters equally, Muon is specifically designed to optimize the hidden layers of neural networks through matrix orthogonalization.
37
+
38
+ This tutorial demystifies Muon by explaining:
39
+ - The theoretical foundations behind Muon
40
+ - How Muon differs from traditional optimizers
41
+ - A clean, educational implementation of Muon
42
+ - Performance comparisons with standard optimizers
43
+ - Optimization techniques for practical use
44
+
45
+ ---
46
+
47
+ ## 1. The Problem: Skewed Singular Value Distributions
48
+
49
+ Traditional optimizers like SGD and Adam have a fundamental limitation: they apply updates that tend to be dominated by a few singular directions in parameter space.
50
+
51
+
52
+ When we decompose a typical gradient update matrix using Singular Value Decomposition (SVD), we find that:
53
+ - A few singular values are very large
54
+ - Most singular values are extremely small
55
+ - This skewed distribution means we're effectively only learning in a small subspace
56
+
57
+ This is like having a 256×128 weight matrix (32,768 parameters) but only effectively using about 10-20 dimensions for learning. The rest of the parameter space receives such small updates that it's essentially "wasted capacity."
58
+
59
+ ## 2. Muon's Solution: Matrix Orthogonalization
60
+
61
+ Muon addresses this problem through a technique called matrix orthogonalization. For matrix parameters, Muon:
62
+ 1. Computes standard momentum updates
63
+ 2. Orthogonalizes these updates using Newton-Schulz iteration
64
+ 3. Applies the orthogonalized updates to the parameters
65
+
66
+
67
+ After orthogonalization:
68
+ - Singular values become more uniform
69
+ - Updates act across all directions in parameter space
70
+ - The neural network can utilize its full parameter capacity
71
+
72
+ ![Singular Value Distribution Before and After Orthogonalization](Assets/Newton-Schulz_Orthogonalization_on_Singular_Values.png)
73
+
74
+
75
+ This is why Muon performs so well - it enables learning across the entire parameter space rather than just a few dominant directions.
76
+
77
+ ## 3. The Newton-Schulz Iteration
78
+
79
+ The core of Muon is the Newton-Schulz iteration, an efficient algorithm for approximate matrix orthogonalization. Instead of using expensive SVD operations, Newton-Schulz provides a fast approximation using only matrix multiplications.
80
+
81
+ The algorithm iteratively transforms a matrix X using the following update rule:
82
+ ```
83
+ X_{t+1} = a*X_t + b*(X_t @ X_t^T) @ X_t + c*(X_t @ X_t^T) @ (X_t @ X_t^T) @ X_t
84
+ ```
85
+
86
+ where a=3.4445, b=-4.7750, c=2.0315 are carefully tuned coefficients that maximize convergence speed.
87
+
88
+ After just 5 iterations, this process transforms a matrix with skewed singular values into one with more uniform singular values, enabling more balanced parameter updates.
89
+
90
+ ## 4. Muon vs. AdamW: Complementary, Not Competitive
91
+
92
+ A common misconception is that Muon competes with AdamW. In reality, they're complementary:
93
+
94
+ - **Muon** excels at optimizing matrix parameters (hidden layers)
95
+ - **AdamW** works well for scalar parameters and embeddings
96
+
97
+ In practice, a hybrid approach is often used:
98
+ - Muon for hidden layer matrices
99
+ - AdamW for embeddings, biases, and output layers
100
+
101
+ This hybrid approach gets the best of both worlds: Muon's efficient matrix updates and AdamW's adaptive learning rates for other parameters.
102
+
103
+ ## 5. When to Use Muon
104
+
105
+ ### Parameter Types
106
+ - ✅ Hidden layer weight matrices
107
+ - ✅ Convolutional filters (reshaped to matrices)
108
+ - ❌ Embedding layers
109
+ - ❌ Output/classifier layers
110
+ - ❌ Bias terms and gains
111
+
112
+ ### Training Stages
113
+ - ✅ Pre-training from scratch
114
+ - ✅ Domain adaptation
115
+ - ❌ Fine-tuning (low-rank updates like LoRA are preferable)
116
+ - ❌ Alignment stages (RLHF/DPO)
117
+
118
+ Use Muon when building new capabilities, and standard optimizers when adjusting existing ones.
119
+
120
+ ### Batch Size
121
+ - ❌ Muon is unlikely to work well for training with small batch size.
122
+
123
+ ## 6. Implementation Deep Dive
124
+
125
+ Our educational implementation consists of two key components:
126
+
127
+ ### The Newton-Schulz Orthogonalization
128
+
129
+ ```python
130
+ def zeropower_via_newtonschulz5(G, steps=5, eps=1e-7):
131
+ # Save original shape
132
+ original_shape = G.shape
133
+
134
+ # Handle higher dimensional tensors
135
+ if G.ndim > 2:
136
+ G = G.view(G.size(0), -1)
137
+
138
+ a, b, c = (3.4445, -4.7750, 2.0315)
139
+ X = G.clone()
140
+
141
+ # Ensure spectral norm is at most 1
142
+ X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps)
143
+
144
+ # Handle tall matrices
145
+ is_tall = X.size(0) > X.size(1)
146
+ if is_tall:
147
+ X = X.transpose(0, 1)
148
+
149
+ # Newton-Schulz iterations
150
+ for _ in range(steps):
151
+ A = X @ X.transpose(0, 1)
152
+ B = b * A + c * A @ A
153
+ X = a * X + B @ X
154
+
155
+ # Transpose back if needed
156
+ if is_tall:
157
+ X = X.transpose(0, 1)
158
+
159
+ # Restore original shape
160
+ if G.ndim > 2:
161
+ X = X.view(original_shape)
162
+
163
+ return X
164
+ ```
165
+
166
+ ### The Muon Optimizer
167
+
168
+ ```python
169
+ class Muon(optim.Optimizer):
170
+ def __init__(self, params, lr=0.01, momentum=0.95, steps=5,
171
+ weight_decay=0, nesterov=True):
172
+ defaults = dict(lr=lr, momentum=momentum, steps=steps,
173
+ weight_decay=weight_decay, nesterov=nesterov)
174
+ super().__init__(params, defaults)
175
+
176
+ @torch.no_grad()
177
+ def step(self, closure=None):
178
+ # ... optimizer implementation ...
179
+ ```
180
+
181
+ See the accompanying [Colab notebook](./Muon.ipynb) for the sudo code and complete implementation.
182
+
183
+ ## 7. Performance Evaluation
184
+
185
+ We tested our Muon implementation against standard optimizers on the MNIST dataset:
186
+
187
+ ![Loss vs Epoch for on **MNIST** Different Optimizers](Assets/Muon_performence_comparison_MNIST.png)
188
+ --- Performance Summary ---
189
+ Optimizer | Final Loss | Total Time (s) | Relative Speed
190
+ Muon | 0.0475 | 28.86 | 1.32x
191
+ SGD | 0.3931 | 21.84 | 1.00x
192
+ AdamW | 0.0717 | 22.71 | 1.04x
193
+
194
+
195
+ Muon achieves ~34% lower loss than AdamW after just 3 epochs, demonstrating its superior optimization efficiency.
196
+
197
+ </br>
198
+
199
+ ![Loss/Accuracy vs Epoch for on **CIFAR10** For Different Optimizers](Assets/Muon_performence_comparison_CIFAR10.png)
200
+
201
+ --- Performance Summary ---
202
+ Optimizer | Final Loss | Final Acc (%) | Total Time (s) | Relative Speed
203
+ Muon | 0.6279 | 80.79 | 49.47 | 1.00x
204
+ SGD | 1.1023 | 64.40 | 49.30 | 1.00x
205
+ AdamW | 0.8955 | 71.66 | 50.25 | 1.02x
206
+
207
+ Muon achieves ~13% higher test accuracy than AdamW after just 5 epochs, with no overhead time cost. Demonstrating both sample efficiency and wallclock time efficiency.
208
+
209
+ ## 8. Optimization Techniques
210
+
211
+ While our educational implementation prioritizes clarity, several techniques can improve performance:
212
+
213
+ 1. **Lower Precision**: Running Newton-Schulz in bfloat16 reduces computation time
214
+ 2. **In-place Operations**: Reducing memory allocations improves efficiency
215
+ 3. **Consistent Update Scale**: Adjusting updates based on matrix dimensions ensures balanced learning
216
+
217
+ Our optimized implementation shows these techniques in action, maintaining the same performance while potentially improving speed.
218
+
219
+
220
+ ## 9. Lessons Learned from Implementing Muon
221
+
222
+ 1. **Mathematical foundations matter**: Performance improvements often require mathematical innovations, not just engineering tricks. Muon's approach of orthogonalizing gradient updates through Newton-Schulz iterations represents a fundamental mathematical insight that can't be replaced by simple hyperparameter tuning.
223
+
224
+ 2. **Hardware significantly impacts performance evaluation**: Our initial tests on T-series GPUs showed Muon to be 30-40x slower than standard optimizers, while on A-series GPUs the difference was merely 3%. Always evaluate optimizers on appropriate hardware before drawing conclusions about performance.
225
+
226
+ 3. **Learning rate dynamics change with different optimizers**: Muon often performs best with higher learning rates than traditional optimizers. In our experiments, Muon with lr=1e-2 dramatically outperformed AdamW with lr=1e-3. This aligns with Muon's orthogonalized updates allowing for more aggressive learning without instability.
227
+
228
+ 4. **JIT compilation isn't always beneficial**: Techniques like `@torch.jit.script` and `@torch.compile` can introduce significant overhead for small experiments or models. In our case, the "optimized" version with JIT was actually much slower due to compilation overhead that wasn't amortized over the small workload.
229
+
230
+ 5. **Optimizer performance varies across architectures**: What works best for MLPs might not be optimal for CNNs or transformers. Always benchmark multiple optimizers on your specific architecture and dataset before making a final selection.
231
+
232
+ 6. **Implementation simplicity has value**: Our educational implementation of Muon performed very well without complex optimizations. Sometimes a clear, understandable implementation is more valuable than a highly optimized but opaque one, especially for learning and experimentation.
233
+
234
+
235
+ ## 10. Conclusion
236
+
237
+ Muon represents a significant advancement in neural network optimization by addressing the fundamental limitation of skewed singular value distributions. By enabling learning across the full parameter space, Muon achieves better sample efficiency than traditional optimizers.
238
+
239
+ As you build and train your own models, consider Muon for hidden layer optimization, especially during pre-training phases where building new capabilities is the priority.
240
+
241
+ ---
242
+ ## 📖 Citation
243
+
244
+ If you use this tutorial or implementation in your work, please cite:
245
+
246
+ ```bibtex
247
+ @misc{wei2025muontutorial,
248
+ author = {Wei, Jen},
249
+ title = {Understanding and Implementing the Muon Optimizer},
250
+ year = {2025},
251
+ howpublished = {\url{https://huggingface.co/datasets/bird-of-paradise/muon-tutorial}}
252
+ }
253
+ ```
254
+
255
+ ```bibtex
256
+ @misc{jordan2024muon,
257
+ author = {Jordan, Keller and Jin, Yuchen and Boza, Vlado and You, Jiacheng and Cesista, Franz and Newhouse, Laker and Bernstein, Jeremy},
258
+ title = {Muon: An optimizer for hidden layers in neural networks},
259
+ year = {2024},
260
+ url = {https://kellerjordan.github.io/posts/muon/}
261
+ }
262
+ ```
263
+
264
+
265
+ ## Acknowledgments
266
+
267
+ This tutorial is based on Keller Jordan's original Muon implementation and paper. Special thanks to the researchers who contributed to the development and understanding of matrix orthogonalization techniques in deep learning optimization.
268
+
269
+ ## References
270
+
271
+ 1. Jordan, K., et al. (2024). Muon: An optimizer for hidden layers in neural networks. [Link](https://kellerjordan.github.io/posts/muon/)
272
+ 2. Bernstein, J. (2024). Deriving Muon. [Link](https://jeremybernste.in/writing/deriving-muon)
273
+ 3. Liu, J., et al. (2025). Muon is Scalable for LLM Training. [Link](https://arxiv.org/abs/2502.16982)