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94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
import math
from typing import List, Tuple

import torch
from pytorch_optimizer.base.exception import (
    NoComplexParameterError,
    NoSparseGradientError,
)
from pytorch_optimizer.base.optimizer import BaseOptimizer
from pytorch_optimizer.base.type import Betas, Closure, Loss, Parameters, ParamGroup
from pytorch_optimizer.optimizer.shampoo_utils import zero_power_via_newton_schulz_5
from torch import nn
from torch.distributed import all_gather, get_rank, get_world_size
from torch.optim import Optimizer


def get_adjusted_lr(
    lr: float, param_shape: Tuple[float, ...], use_adjusted_lr: bool = False
) -> float:
    r"""Get the adjust learning rate."""
    output_shape, *input_shape = param_shape
    input_shape = math.prod(input_shape)

    ratio: float = (
        math.pow(max(1.0, output_shape / input_shape), 0.5)
        if use_adjusted_lr
        else 0.2 * math.sqrt(max(output_shape, input_shape))
    )

    return lr * ratio


class Muon(BaseOptimizer):
    """Momentum Orthogonalized by Newton-schulz.

    Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-processing step, in which
    each 2D parameter's update is replaced with the nearest orthogonal matrix. To efficiently orthogonalize each
    update, we use a Newton-Schulz iteration, which has the advantage that it can be stably run in bfloat16 on the GPU.

    Muon is intended to optimize only the internal ≥2D parameters of a network. Embeddings, classifier heads, and
    scalar or vector parameters should be optimized using AdamW.

    Some warnings:
    - We believe this optimizer is unlikely to work well for training with small batch size.
    - We believe it may not work well for fine-tuning pretrained models, but we haven't tested this.

    Args:
        params (Parameters): The parameters to be optimized by Muon.
        lr (float): Learning rate.
        momentum (float): The momentum used by the internal SGD.
        weight_decay (float): Weight decay (L2 penalty).
        weight_decouple (bool): The optimizer uses decoupled weight decay as in AdamW.
        nesterov (bool): Whether to use nesterov momentum.
        ns_steps (int): The number of Newton-Schulz iterations to run. (5 is probably always enough)
        use_adjusted_lr (bool): Whether to use adjusted learning rate, which is from the Moonlight.
            Reference: https://github.com/MoonshotAI/Moonlight/blob/master/examples/toy_train.py
        adamw_lr (float): The learning rate for the internal AdamW.
        adamw_betas (tuple): The betas for the internal AdamW.
        adamw_wd (float): The weight decay for the internal AdamW.
        adamw_eps (float): The epsilon for the internal AdamW.
        maximize (bool): Maximize the objective with respect to the params, instead of minimizing.

    Example:
        from pytorch_optimizer import Muon

        hidden_weights = [p for p in model.body.parameters() if p.ndim >= 2]
        hidden_gains_biases = [p for p in model.body.parameters() if p.ndim < 2]
        non_hidden_params = [*model.head.parameters(), *model.embed.parameters()]

        param_groups = [
            dict(params=hidden_weights, lr=0.02, weight_decay=0.01, use_muon=True),
            dict(
                params=hidden_gains_biases + non_hidden_params,
                lr=3e-4,
                betas=(0.9, 0.95),
                weight_decay=0.01,
                use_muon=False,
            ),
        ]

        optimizer = Muon(param_groups)
    """

    def __init__(
        self,
        params: Parameters,
        lr: float = 2e-2,
        momentum: float = 0.95,
        weight_decay: float = 0.0,
        weight_decouple: bool = True,
        nesterov: bool = True,
        ns_steps: int = 5,
        use_adjusted_lr: bool = False,
        adamw_lr: float = 3e-4,
        adamw_betas: Betas = (0.9, 0.95),
        adamw_wd: float = 0.0,
        adamw_eps: float = 1e-10,
        maximize: bool = False,
        **kwargs,
    ):
        self.validate_learning_rate(lr)
        self.validate_learning_rate(adamw_lr)
        self.validate_non_negative(weight_decay, "weight_decay")
        self.validate_range(momentum, "momentum", 0.0, 1.0, range_type="[)")
        self.validate_positive(ns_steps, "ns_steps")
        self.validate_betas(adamw_betas)
        self.validate_non_negative(adamw_wd, "adamw_wd")
        self.validate_non_negative(adamw_eps, "adamw_eps")

        self.maximize = maximize

        for group in params:
            if "use_muon" not in group:
                raise ValueError("`use_muon` must be set.")

            if group["use_muon"]:
                group["lr"] = group.get("lr", lr)
                group["momentum"] = group.get("momentum", momentum)
                group["nesterov"] = group.get("nesterov", nesterov)
                group["weight_decay"] = group.get("weight_decay", weight_decay)
                group["ns_steps"] = group.get("ns_steps", ns_steps)
                group["use_adjusted_lr"] = group.get("use_adjusted_lr", use_adjusted_lr)
            else:
                group["lr"] = group.get("lr", adamw_lr)
                group["betas"] = group.get("betas", adamw_betas)
                group["eps"] = group.get("eps", adamw_eps)
                group["weight_decay"] = group.get("weight_decay", adamw_wd)

            group["weight_decouple"] = group.get("weight_decouple", weight_decouple)

        super().__init__(params, kwargs)

    def __str__(self) -> str:
        return "Muon"

    def init_group(self, group: ParamGroup, **kwargs) -> None:
        for p in group["params"]:
            if p.grad is None:
                continue

            grad = p.grad
            if grad.is_sparse:
                raise NoSparseGradientError(str(self))

            if torch.is_complex(p):
                raise NoComplexParameterError(str(self))

            state = self.state[p]

            if len(state) == 0:
                if group["use_muon"]:
                    state["momentum_buffer"] = torch.zeros_like(p)
                else:
                    state["exp_avg"] = torch.zeros_like(p)
                    state["exp_avg_sq"] = torch.zeros_like(p)

    @torch.no_grad()
    def step(self, closure: Closure = None) -> Loss:
        loss: Loss = None
        if closure is not None:
            with torch.enable_grad():
                loss = closure()

        for group in self.param_groups:
            if "step" not in group:
                self.init_group(group)
                group["step"] = 1
            else:
                group["step"] += 1

            for p in group["params"]:
                if p.grad is None:
                    continue

                grad = p.grad

                self.maximize_gradient(grad, maximize=self.maximize)

                state = self.state[p]

                self.apply_weight_decay(
                    p,
                    grad=grad,
                    lr=group["lr"],
                    weight_decay=group["weight_decay"],
                    weight_decouple=group["weight_decouple"],
                    fixed_decay=False,
                )

                if group["use_muon"]:
                    buf = state["momentum_buffer"]
                    buf.lerp_(grad, weight=1.0 - group["momentum"])

                    update = (
                        grad.lerp_(buf, weight=group["momentum"])
                        if group["nesterov"]
                        else buf
                    )
                    if update.ndim > 2:
                        update = update.view(len(update), -1)

                    update = zero_power_via_newton_schulz_5(
                        update, num_steps=group["ns_steps"]
                    )

                    if group.get("cautious"):
                        self.apply_cautious(update, grad)

                    lr: float = get_adjusted_lr(
                        group["lr"], p.size(), use_adjusted_lr=group["use_adjusted_lr"]
                    )

                    p.add_(update.reshape(p.shape), alpha=-lr)
                else:
                    exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"]

                    beta1, beta2 = group["betas"]

                    bias_correction1: float = self.debias(beta1, group["step"])
                    bias_correction2_sq: float = math.sqrt(
                        self.debias(beta2, group["step"])
                    )

                    exp_avg.lerp_(grad, weight=1.0 - beta1)
                    exp_avg_sq.lerp_(grad.square(), weight=1.0 - beta2)

                    de_nom = (
                        exp_avg_sq.sqrt().add_(group["eps"]).div_(bias_correction2_sq)
                    )

                    p.addcdiv_(exp_avg / bias_correction1, de_nom, value=-group["lr"])

        return loss


class DistributedMuon(BaseOptimizer):  # pragma: no cover
    """Momentum Orthogonalized by Newton-schulz.

    Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-processing step, in which
    each 2D parameter's update is replaced with the nearest orthogonal matrix. To efficiently orthogonalize each
    update, we use a Newton-Schulz iteration, which has the advantage that it can be stably run in bfloat16 on the GPU.

    Muon is intended to optimize only the internal ≥2D parameters of a network. Embeddings, classifier heads, and
    scalar or vector parameters should be optimized using AdamW.

    Some warnings:
    - We believe this optimizer is unlikely to work well for training with small batch size.
    - We believe it may not work well for fine-tuning pretrained models, but we haven't tested this.

    Args:
        params (Parameters): The parameters to be optimized by Muon.
        lr (float): Learning rate.
        momentum (float): The momentum used by the internal SGD.
        weight_decay (float): Weight decay (L2 penalty).
        weight_decouple (bool): The optimizer uses decoupled weight decay as in AdamW.
        nesterov (bool): Whether to use nesterov momentum.
        ns_steps (int): The number of Newton-Schulz iterations to run. (5 is probably always enough)
        use_adjusted_lr (bool): Whether to use adjusted learning rate, which is from the Moonlight.
            Reference: https://github.com/MoonshotAI/Moonlight/blob/master/examples/toy_train.py
        adamw_lr (float): The learning rate for the internal AdamW.
        adamw_betas (tuple): The betas for the internal AdamW.
        adamw_wd (float): The weight decay for the internal AdamW.
        adamw_eps (float): The epsilon for the internal AdamW.
        maximize (bool): Maximize the objective with respect to the params, instead of minimizing.

    Example:
        from pytorch_optimizer import DistributedMuon

        hidden_weights = [p for p in model.body.parameters() if p.ndim >= 2]
        hidden_gains_biases = [p for p in model.body.parameters() if p.ndim < 2]
        non_hidden_params = [*model.head.parameters(), *model.embed.parameters()]

        param_groups = [
            dict(params=hidden_weights, lr=0.02, weight_decay=0.01, use_muon=True),
            dict(
                params=hidden_gains_biases + non_hidden_params,
                lr=3e-4,
                betas=(0.9, 0.95),
                weight_decay=0.01,
                use_muon=False,
            ),
        ]

        optimizer = DistributedMuon(param_groups)
    """

    def __init__(
        self,
        params: Parameters,
        lr: float = 2e-2,
        momentum: float = 0.95,
        weight_decay: float = 0.0,
        weight_decouple: bool = True,
        nesterov: bool = True,
        ns_steps: int = 5,
        use_adjusted_lr: bool = False,
        adamw_lr: float = 3e-4,
        adamw_betas: Betas = (0.9, 0.95),
        adamw_wd: float = 0.0,
        adamw_eps: float = 1e-10,
        maximize: bool = False,
        **kwargs,
    ):
        self.validate_learning_rate(lr)
        self.validate_learning_rate(adamw_lr)
        self.validate_non_negative(weight_decay, "weight_decay")
        self.validate_range(momentum, "momentum", 0.0, 1.0, range_type="[)")
        self.validate_positive(ns_steps, "ns_steps")
        self.validate_betas(adamw_betas)
        self.validate_non_negative(adamw_wd, "adamw_wd")
        self.validate_non_negative(adamw_eps, "adamw_eps")

        self.maximize = maximize

        self.world_size: int = get_world_size()
        self.rank: int = get_rank()

        for group in params:
            if "use_muon" not in group:
                raise ValueError("`use_muon` must be set.")

            if group["use_muon"]:
                group["lr"] = group.get("lr", lr)
                group["momentum"] = group.get("momentum", momentum)
                group["nesterov"] = group.get("nesterov", nesterov)
                group["weight_decay"] = group.get("weight_decay", weight_decay)
                group["ns_steps"] = group.get("ns_steps", ns_steps)
                group["use_adjusted_lr"] = group.get("use_adjusted_lr", use_adjusted_lr)
            else:
                group["lr"] = group.get("lr", adamw_lr)
                group["betas"] = group.get("betas", adamw_betas)
                group["eps"] = group.get("eps", adamw_eps)
                group["weight_decay"] = group.get("weight_decay", adamw_wd)

            group["weight_decouple"] = group.get("weight_decouple", weight_decouple)

        super().__init__(params, kwargs)

    def __str__(self) -> str:
        return "DistributedMuon"

    def init_group(self, group: ParamGroup, **kwargs) -> None:
        for p in group["params"]:
            if p.grad is None:
                p.grad = torch.zeros_like(p)

            grad = p.grad
            if grad.is_sparse:
                raise NoSparseGradientError(str(self))

            if torch.is_complex(p):
                raise NoComplexParameterError(str(self))

            state = self.state[p]

            if len(state) == 0 and not group["use_muon"]:
                state["exp_avg"] = torch.zeros_like(p)
                state["exp_avg_sq"] = torch.zeros_like(p)

    @torch.no_grad()
    def step(self, closure: Closure = None) -> Loss:
        loss: Loss = None
        if closure is not None:
            with torch.enable_grad():
                loss = closure()

        for group in self.param_groups:
            if "step" not in group:
                self.init_group(group)
                group["step"] = 1
            else:
                group["step"] += 1

            if group["use_muon"]:
                params = group["params"]
                padded_params = params + [torch.empty_like(params[-1])] * (
                    self.world_size - len(params) % self.world_size
                )

                for i in range(len(params))[:: self.world_size]:
                    if i + self.rank < len(params):
                        p = params[i + self.rank]

                        grad = p.grad

                        self.maximize_gradient(grad, maximize=self.maximize)

                        state = self.state[p]
                        if len(state) == 0:
                            state["momentum_buffer"] = torch.zeros_like(p)

                        self.apply_weight_decay(
                            p,
                            grad=grad,
                            lr=group["lr"],
                            weight_decay=group["weight_decay"],
                            weight_decouple=group["weight_decouple"],
                            fixed_decay=False,
                        )

                        buf = state["momentum_buffer"]
                        buf.lerp_(grad, weight=1.0 - group["momentum"])

                        update = (
                            grad.lerp_(buf, weight=group["momentum"])
                            if group["nesterov"]
                            else buf
                        )
                        if update.ndim > 2:
                            update = update.view(len(update), -1)

                        update = zero_power_via_newton_schulz_5(
                            update, num_steps=group["ns_steps"]
                        )

                        if group.get("cautious"):
                            self.apply_cautious(update, grad)

                        lr: float = get_adjusted_lr(
                            group["lr"],
                            p.size(),
                            use_adjusted_lr=group["use_adjusted_lr"],
                        )

                        p.add_(update.reshape(p.shape), alpha=-lr)

                    all_gather(padded_params[i:i + self.world_size], padded_params[i:i + self.rank])  # fmt: skip
            else:
                for p in group["params"]:
                    grad = p.grad

                    exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"]

                    beta1, beta2 = group["betas"]

                    bias_correction1: float = self.debias(beta1, group["step"])
                    bias_correction2_sq: float = math.sqrt(
                        self.debias(beta2, group["step"])
                    )

                    exp_avg.lerp_(grad, weight=1.0 - beta1)
                    exp_avg_sq.lerp_(grad.square(), weight=1.0 - beta2)

                    de_nom = (
                        exp_avg_sq.sqrt().add_(group["eps"]).div_(bias_correction2_sq)
                    )

                    p.addcdiv_(exp_avg / bias_correction1, de_nom, value=-group["lr"])

        return loss


class AdaMuon(BaseOptimizer):
    """Adaptive Muon optimizer.

    Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-processing step, in which
    each 2D parameter's update is replaced with the nearest orthogonal matrix. To efficiently orthogonalize each
    update, we use a Newton-Schulz iteration, which has the advantage that it can be stably run in bfloat16 on the GPU.

    Muon is intended to optimize only the internal ≥2D parameters of a network. Embeddings, classifier heads, and
    scalar or vector parameters should be optimized using AdamW.

    Some warnings:
    - We believe this optimizer is unlikely to work well for training with small batch size.
    - We believe it may not work well for fine-tuning pretrained models, but we haven't tested this.

    Args:
        params (Parameters): The parameters to be optimized by Muon.
        lr (float): Learning rate.
        betas (tuple): Coefficients used for computing running averages of gradient and the squared Hessian trace.
        weight_decay (float): Weight decay (L2 penalty).
        weight_decouple (bool): The optimizer uses decoupled weight decay as in AdamW.
        ns_steps (int): The number of Newton-Schulz iterations to run. (5 is probably always enough)
        use_adjusted_lr (bool): Whether to use adjusted learning rate, which is from the Moonlight.
            Reference: https://github.com/MoonshotAI/Moonlight/blob/master/examples/toy_train.py
        adamw_lr (float): The learning rate for the internal AdamW.
        adamw_betas (tuple): The betas for the internal AdamW.
        adamw_wd (float): The weight decay for the internal AdamW.
        eps (float): Term added to the denominator to improve numerical stability.
        maximize (bool): Maximize the objective with respect to the params, instead of minimizing.

    Example:
        from pytorch_optimizer import AdaMuon

        hidden_weights = [p for p in model.body.parameters() if p.ndim >= 2]
        hidden_gains_biases = [p for p in model.body.parameters() if p.ndim < 2]
        non_hidden_params = [*model.head.parameters(), *model.embed.parameters()]

        param_groups = [
            dict(params=hidden_weights, lr=0.02, weight_decay=0.01, use_muon=True),
            dict(
                params=hidden_gains_biases + non_hidden_params,
                lr=3e-4,
                betas=(0.9, 0.95),
                weight_decay=0.01,
                use_muon=False,
            ),
        ]

        optimizer = AdaMuon(param_groups)
    """

    def __init__(
        self,
        params: Parameters,
        lr: float = 2e-2,
        betas: Betas = (0.9, 0.95),
        weight_decay: float = 0.0,
        weight_decouple: bool = True,
        ns_steps: int = 5,
        use_adjusted_lr: bool = False,
        adamw_lr: float = 3e-4,
        adamw_betas: Betas = (0.9, 0.999),
        adamw_wd: float = 0.0,
        eps: float = 1e-10,
        maximize: bool = False,
        **kwargs,
    ):
        self.validate_learning_rate(lr)
        self.validate_learning_rate(adamw_lr)
        self.validate_non_negative(weight_decay, "weight_decay")
        self.validate_positive(ns_steps, "ns_steps")
        self.validate_betas(betas)
        self.validate_betas(adamw_betas)
        self.validate_non_negative(adamw_wd, "adamw_wd")
        self.validate_non_negative(eps, "eps")

        self.maximize = maximize

        for group in params:
            if "use_muon" not in group:
                raise ValueError("`use_muon` must be set.")

            if group["use_muon"]:
                group["lr"] = group.get("lr", lr)
                group["betas"] = group.get("betas", betas)
                group["weight_decay"] = group.get("weight_decay", weight_decay)
                group["ns_steps"] = group.get("ns_steps", ns_steps)
                group["use_adjusted_lr"] = group.get("use_adjusted_lr", use_adjusted_lr)
            else:
                group["lr"] = group.get("lr", adamw_lr)
                group["betas"] = group.get("betas", adamw_betas)
                group["weight_decay"] = group.get("weight_decay", adamw_wd)

            group["weight_decouple"] = group.get("weight_decouple", weight_decouple)
            group["eps"] = group.get("eps", eps)

        super().__init__(params, kwargs)

    def __str__(self) -> str:
        return "AdaMuon"

    def init_group(self, group: ParamGroup, **kwargs) -> None:
        for p in group["params"]:
            if p.grad is None:
                continue

            grad = p.grad
            if grad.is_sparse:
                raise NoSparseGradientError(str(self))

            if torch.is_complex(p):
                raise NoComplexParameterError(str(self))

            state = self.state[p]

            if len(state) == 0:
                if group["use_muon"]:
                    state["m"] = torch.zeros_like(p)
                    state["v"] = torch.zeros_like(p.flatten())
                else:
                    state["exp_avg"] = torch.zeros_like(p)
                    state["exp_avg_sq"] = torch.zeros_like(p)

    @torch.no_grad()
    def step(self, closure: Closure = None) -> Loss:
        loss: Loss = None
        if closure is not None:
            with torch.enable_grad():
                loss = closure()

        for group in self.param_groups:
            if "step" not in group:
                self.init_group(group)
                group["step"] = 1
            else:
                group["step"] += 1

            beta1, beta2 = group["betas"]

            bias_correction1: float = self.debias(beta1, group["step"])
            bias_correction2: float = self.debias(beta2, group["step"])

            for p in group["params"]:
                if p.grad is None:
                    continue

                grad = p.grad

                self.maximize_gradient(grad, maximize=self.maximize)

                state = self.state[p]

                self.apply_weight_decay(
                    p,
                    grad=grad,
                    lr=group["lr"],
                    weight_decay=group["weight_decay"],
                    weight_decouple=group["weight_decouple"],
                    fixed_decay=False,
                )

                if group["use_muon"]:
                    m = state["m"]
                    m.lerp_(grad, weight=1.0 - beta1)

                    update = m.clone()

                    if update.ndim > 2:
                        update = update.view(len(update), -1)

                    update = zero_power_via_newton_schulz_5(
                        update, num_steps=group["ns_steps"]
                    ).flatten()

                    v = state["v"]
                    v.mul_(beta2).addcmul_(update, update, value=1.0 - beta2)

                    update.div_((v / bias_correction2).sqrt_().add_(group["eps"]))
                    update = update.reshape(p.size())

                    update.mul_(0.2 * math.sqrt(p.numel())).div_(
                        update.norm().add_(group["eps"])
                    )

                    lr: float = get_adjusted_lr(
                        group["lr"], p.size(), use_adjusted_lr=group["use_adjusted_lr"]
                    )

                    p.add_(update, alpha=-lr)
                else:
                    exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"]

                    exp_avg.lerp_(grad, weight=1.0 - beta1)
                    exp_avg_sq.lerp_(grad.square(), weight=1.0 - beta2)

                    de_nom = (
                        exp_avg_sq.sqrt()
                        .add_(group["eps"])
                        .div_(math.sqrt(bias_correction2))
                    )

                    p.addcdiv_(exp_avg / bias_correction1, de_nom, value=-group["lr"])

        return loss


class AdaGO(BaseOptimizer):
    """AdaGrad Meets Muon: Adaptive Stepsizes for Orthogonal Updates.

    Args:
        params (Parameters): The parameters to be optimized by Muon.
        lr (float): Learning rate.
        momentum (float): The momentum used by the internal SGD.
        weight_decay (float): Weight decay (L2 penalty).
        weight_decouple (bool): The optimizer uses decoupled weight decay as in AdamW.
        nesterov (bool): Whether to use nesterov momentum.
        gamma (float): Gamma factor. Empirically, AdaGO performs robustly across a wide range of gamma values.
        eps (float): Epsilon value. Lower bound eps > 0 on the stepsizes.
        ns_steps (int): The number of Newton-Schulz iterations to run. (5 is probably always enough)
        use_adjusted_lr (bool): Whether to use adjusted learning rate, which is from the Moonlight.
            Reference: https://github.com/MoonshotAI/Moonlight/blob/master/examples/toy_train.py
        adamw_lr (float): The learning rate for the internal AdamW.
        adamw_betas (tuple): The betas for the internal AdamW.
        adamw_wd (float): The weight decay for the internal AdamW.
        adamw_eps (float): The epsilon for the internal AdamW.
        maximize (bool): Maximize the objective with respect to the params, instead of minimizing.

    Example:
        from pytorch_optimizer import AdaGO

        hidden_weights = [p for p in model.body.parameters() if p.ndim >= 2]
        hidden_gains_biases = [p for p in model.body.parameters() if p.ndim < 2]
        non_hidden_params = [*model.head.parameters(), *model.embed.parameters()]

        param_groups = [
            dict(params=hidden_weights, lr=0.02, weight_decay=0.01, use_muon=True),
            dict(
                params=hidden_gains_biases + non_hidden_params,
                lr=3e-4,
                betas=(0.9, 0.95),
                weight_decay=0.01,
                use_muon=False,
            ),
        ]

        optimizer = AdaGO(param_groups)
    """

    def __init__(
        self,
        params: Parameters,
        lr: float = 5e-2,
        momentum: float = 0.95,
        weight_decay: float = 0.0,
        weight_decouple: bool = True,
        gamma: float = 10.0,
        eps: float = 5e-4,
        v: float = 1e-6,
        nesterov: bool = False,
        ns_steps: int = 5,
        use_adjusted_lr: bool = False,
        adamw_lr: float = 3e-4,
        adamw_betas: Betas = (0.9, 0.95),
        adamw_wd: float = 0.0,
        adamw_eps: float = 1e-10,
        maximize: bool = False,
        **kwargs,
    ):
        self.validate_learning_rate(lr)
        self.validate_learning_rate(adamw_lr)
        self.validate_non_negative(weight_decay, "weight_decay")
        self.validate_range(momentum, "momentum", 0.0, 1.0, range_type="[)")
        self.validate_positive(ns_steps, "ns_steps")
        self.validate_positive(gamma, "gamma")
        self.validate_positive(eps, "eps")
        self.validate_positive(v, "v")
        self.validate_betas(adamw_betas)
        self.validate_non_negative(adamw_wd, "adamw_wd")
        self.validate_non_negative(adamw_eps, "adamw_eps")

        self.maximize = maximize

        for group in params:
            if "use_muon" not in group:
                raise ValueError("`use_muon` must be set.")

            if group["use_muon"]:
                group["lr"] = group.get("lr", lr)
                group["momentum"] = group.get("momentum", momentum)
                group["nesterov"] = group.get("nesterov", nesterov)
                group["weight_decay"] = group.get("weight_decay", weight_decay)
                group["ns_steps"] = group.get("ns_steps", ns_steps)
                group["gamma"] = group.get("gamma", gamma)
                group["eps"] = group.get("eps", eps)
                group["v"] = group.get("v", v)
                group["use_adjusted_lr"] = group.get("use_adjusted_lr", use_adjusted_lr)
            else:
                group["lr"] = group.get("lr", adamw_lr)
                group["betas"] = group.get("betas", adamw_betas)
                group["eps"] = group.get("eps", adamw_eps)
                group["weight_decay"] = group.get("weight_decay", adamw_wd)

            group["weight_decouple"] = group.get("weight_decouple", weight_decouple)

        super().__init__(params, kwargs)

    def __str__(self) -> str:
        return "AdaGO"

    def init_group(self, group: ParamGroup, **kwargs) -> None:
        for p in group["params"]:
            if p.grad is None:
                continue

            grad = p.grad
            if grad.is_sparse:
                raise NoSparseGradientError(str(self))

            if torch.is_complex(p):
                raise NoComplexParameterError(str(self))

            state = self.state[p]

            if len(state) == 0:
                if group["use_muon"]:
                    state["momentum_buffer"] = torch.zeros_like(p)
                    state["v"] = torch.tensor(
                        group["v"], dtype=p.dtype, device=p.device
                    )
                else:
                    state["exp_avg"] = torch.zeros_like(p)
                    state["exp_avg_sq"] = torch.zeros_like(p)

    @torch.no_grad()
    def step(self, closure: Closure = None) -> Loss:
        loss: Loss = None
        if closure is not None:
            with torch.enable_grad():
                loss = closure()

        for group in self.param_groups:
            if "step" not in group:
                self.init_group(group)
                group["step"] = 1
            else:
                group["step"] += 1

            for p in group["params"]:
                if p.grad is None:
                    continue

                grad = p.grad

                self.maximize_gradient(grad, maximize=self.maximize)

                state = self.state[p]

                self.apply_weight_decay(
                    p,
                    grad=grad,
                    lr=group["lr"],
                    weight_decay=group["weight_decay"],
                    weight_decouple=group["weight_decouple"],
                    fixed_decay=False,
                )

                if group["use_muon"]:
                    buf, v = state["momentum_buffer"], state["v"]
                    buf.lerp_(grad, weight=1.0 - group["momentum"])

                    v.add_(min(grad.norm(p=2.0).pow(2), group["gamma"] ** 2))

                    update = (
                        grad.lerp_(buf, weight=group["momentum"])
                        if group["nesterov"]
                        else buf
                    )
                    if update.ndim > 2:
                        update = update.view(len(update), -1)

                    update = zero_power_via_newton_schulz_5(
                        update, num_steps=group["ns_steps"]
                    )

                    if group.get("cautious"):
                        self.apply_cautious(update, grad)

                    lr: float = get_adjusted_lr(
                        group["lr"], p.size(), use_adjusted_lr=group["use_adjusted_lr"]
                    )

                    p.add_(
                        update.reshape(p.shape),
                        alpha=-max(
                            group["eps"],
                            (lr * min(grad.norm(2), group["gamma"]) / v).item(),
                        ),
                    )
                else:
                    exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"]

                    beta1, beta2 = group["betas"]

                    bias_correction1: float = self.debias(beta1, group["step"])
                    bias_correction2_sq: float = math.sqrt(
                        self.debias(beta2, group["step"])
                    )

                    exp_avg.lerp_(grad, weight=1.0 - beta1)
                    exp_avg_sq.lerp_(grad.square(), weight=1.0 - beta2)

                    de_nom = (
                        exp_avg_sq.sqrt().add_(group["eps"]).div_(bias_correction2_sq)
                    )

                    p.addcdiv_(exp_avg / bias_correction1, de_nom, value=-group["lr"])

        return loss


def prepare_muon_parameters(
    model: nn.Module,
    optimizer_name: str,
    lr: float,
    weight_decay: float,
    adamw_lr: float = 3e-4,
    adamw_wd: float = 0.0,
    **kwargs,
) -> Optimizer:
    """Prepare the parameters for Muon optimizer.

    Be careful at using this function to prepare the parameters for Muon optimizer. It's not likely acting perfectly
    for all cases. So, highly recommend you to create the Muon optimizer manually following by the given example in the
    docstring.
    """
    muon_parameters: List[str] = []
    non_muon_params: List[str] = []

    for _, module in model.named_modules():
        for name, param in module.named_parameters(recurse=False):
            if (
                isinstance(module, (nn.Linear, nn.Conv1d, nn.LSTM, nn.Conv2d))
                and param.ndim >= 2
                and "head" not in name
            ):
                muon_parameters.append(param)
            else:
                non_muon_params.append(param)

    param_groups: Parameters = [
        {
            "params": muon_parameters,
            "lr": lr,
            "weight_decay": weight_decay,
            "use_muon": True,
        },
        {
            "params": non_muon_params,
            "lr": adamw_lr,
            "weight_decay": adamw_wd,
            "use_muon": False,
        },
    ]

    optimizer_name = optimizer_name.lower()

    if optimizer_name == "adamuon":
        return AdaMuon(param_groups, **kwargs)
    if optimizer_name == "adago":
        return AdaGO(param_groups, **kwargs)

    return Muon(param_groups, **kwargs)