
    9i#5                        S r SSKrSSKJr  SSKJr  SSKrSSKJr  SSKJ	r	J
r
JrJrJr  S/rS	rS
rSrSrSrS\S\\\\4   S\S\S\4
S jrS\S\\   S\R2                  S\4S jr " S S\5      rSS\
 S\ S\ S\ S\ S\ S3-   \l         S \\   S!\\   S"\\   S\S#\S$\S%\S\\\\4   S\S\S\\   S&\SS4S' jr\	" \S(9SS).S \\   S!\\   S"\\   S*\\   S\S#\S$\S%\S\\\\4   S\S\S\\   S&\4S+ jj5       rg),z%Implementation of the Muon optimizer.    N)MutableMapping)Optional)Tensor   )_disable_dynamo_if_unsupported_params_doc
_to_scalar	OptimizerParamsTMuongHz>guV@ggn@ @   gradns_coefficientsns_stepsepsreturnc           	      |   US:  a  [        S5      e[        U R                  5      S:w  a  [        S5      e[        U5      S:w  a  [        S5      eUu  pEnU R                  5       nU R	                  S5      U R	                  S5      :  a  UR
                  nUR                  UR                  5       R                  US	95        [        U5       H<  nXwR
                  -  n	[        R                  " XXUS
9n
[        R                  " XzXtS9nM>     U R	                  S5      U R	                  S5      :  a  UR
                  nU$ )a  
Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a
quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose
of minimizing steps, it turns out to be empirically effective to keep increasing the slope at
zero even beyond the point where the iteration no longer converges all the way to one everywhere
on the interval. This iteration therefore does not produce UV^T but rather something like US'V^T
where S' is diagonal with S_{ii}' ~ Uniform(0.5, 1.5), which turns out not to hurt model
performance at all relative to UV^T, where USV^T = G is the SVD.

Implementation reference: https://github.com/KellerJordan/Muon/blob/master/muon.py
with suggestions by @jxbz, @leloykun, and @YouJiacheng.
d   zBNumber of steps must be less than 100 for computational efficiency   z)Input tensor gradient must be a 2D matrix   z0Coefficients must be a tuple of exactly 3 valuesr   r   )min)betaalpha)r   )
ValueErrorlenshapebfloat16sizeTdiv_normclamprangetorchaddmm)r   r   r   r   abc
ortho_grad_gram_matrixgram_updates              Q/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/torch/optim/_muon.py_zeropower_via_newtonschulzr.       s    3P
 	
 4::!DEE
?q KLLGA!Jyy|diil"\\
OOJOO%+++458_ <</kkk
 [[*M
  yy|diil"\\
    lradjust_lr_fnparam_shapec                     USS u  p4Ub  US:X  a&  [         R                  " [        SX4-  5      5      nX-  $ US:X  a&  S[         R                  " [        X45      5      -  nX-  $ SnX-  $ )z.Default learning rate adjustment used by Muon.Nr   originalr   match_rms_adamwg?g      ?)mathsqrtmax)r0   r1   r2   ABadjusted_ratios         r-   
_adjust_lrr<   J   s|     r?DA|z93q!%=1
 	 
*	*tyyQ33  r/   c                      ^  \ rS rSrSSSS\\\4\\S4S\	S\
S	\
S
\
S\S\\
\
\
4   S\
S\S\\   SS4U 4S jjjrS\S\\   S\\   S\\   4S jr\R,                  " 5       SS j5       rSrU =r$ )r   Y   gMbP?g?gffffff?TNparamsr0   weight_decaymomentumnesterovr   r   r   r1   r   c
           	        > [        U[        5      (       a  UR                  5       S:w  a  [        S5      eSU::  d  [        SU 35      eSU::  d  [        SU 35      eSU::  d  [        SU 35      eU	b  U	S;  a  [        SU	 S	35      eUUUUUUUU	S
.n
[        TU ]  X5        U R                   H;  nUS    H/  nUR                  S:w  d  M  [        SUR                  5        35      e   M=     g )Nr   zTensor lr must be 1-elementg        z%Learning rate should be >= 0 but is: z momentum should be >= 0 but is: z$weight decay should be >= 0 but is: )r4   r5   zAdjust learning rate function z is not supported)r0   r@   rA   rB   r   r   r   r1   r?   r   zIMuon only supports 2D parameters whereas we found a parameter with size: )	
isinstancer   numelr   super__init__param_groupsndimr   )selfr?   r0   r@   rA   rB   r   r   r   r1   defaultsgroupp	__class__s                r-   rG   Muon.__init__Z   s"    b&!!bhhjAo:;;byDRDIJJh?zJKKl"CL>RSS# =
 )
 0>OP 
 (  . (	
 	*&&E8_66Q;$cdedjdjdlcmn  % 'r/   rL   params_with_gradgradsmuon_momentum_bufsc                    US    H  nUR                   c  M  [        R                  " U5      (       a  [        S5      eUR                   R                  (       a  [        S5      eUR                  U5        UR                  UR                   5        U R                  U   nSU;  a0  [        R                  " UR                   [        R                  S9US'   UR                  US   5        M     g)Nr?   z(Muon does not support complex parametersz&Muon does not support sparse gradientsmomentum_buffer)memory_formatF)	r   r$   
is_complexRuntimeError	is_sparseappendstate
zeros_likepreserve_format)rJ   rL   rP   rQ   rR   rM   rZ   s          r-   _init_groupMuon._init_group   s     xAvv~"""#MNNvv"#KLL##A&LL JJqME -+0+;+;FF%*?*?,'( %%e,=&>?% !( r/   c                 :   SnUb%  [         R                  " 5          U" 5       nSSS5        U R                   HO  nUS   nUS   nUS   n/ n/ n/ n	U R                  UUUU	5      n
[	        UUU	UUUUS   US   US   US   US	   U
S
9  MQ     U$ ! , (       d  f       No= f)z$Performs a single optimization step.Nr0   r@   rA   rB   r   r   r   r1   )	r0   r@   rA   rB   r   r   r   r1   has_complex)r$   enable_gradrH   r]   muon)rJ   closurelossrL   r0   r@   rA   rP   rQ   rR   r`   s              r-   step	Muon.step   s     ""$y % &&EtB 0LZ(H-/"$E/1** "	K  ")!z* %&7 8%Lz*">2'! '< C %$s   B
B )N)__name__
__module____qualname____firstlineno__	DEFAULT_A	DEFAULT_B	DEFAULT_CEPSDEFAULT_NS_STEPSr   floatbooltupleintr   strrG   r   listr   r]   r$   no_gradre   __static_attributes____classcell__)rN   s   @r-   r   r   Y   s     !7@)Y6W(&*-- - 	-
 - - ueU23- - - sm- 
- -^ v, F|	
 !L: ]]_% %r/   u  Implements Muon algorithm.

    .. math::
       \begin{aligned}
            &\rule{110mm}{0.4pt} \\
            &\textbf{input}      : \gamma \text{ (lr)},\ \lambda \text{ (weight decay)},\
               \mu \text{ (momentum)},\ \textit{nesterov}\in\{True,False\},\\
            &\hspace{13mm}(a,b,c)\ \text{ (NS coefficients)},\
               \varepsilon \text{ (epsilon)},\ k \text{ (NS steps)},\
               \theta_0 \text{ (params)},\ f(\theta) \text{ (objective)} \\
            &\textbf{initialize} : B_0 \leftarrow 0 \text{ (momentum buffer)} \\[-1.ex]
            &\rule{110mm}{0.4pt} \\
            &\textbf{for}\ t=1\ \textbf{to}\ \ldots\ \textbf{do} \\[0.25ex]
            &\hspace{5mm} g_t \leftarrow \nabla_{\theta} f_t(\theta_{t-1}) \\[0.25ex]
            &\hspace{5mm} B_t \leftarrow \mu B_{t-1} + g_t \\[0.25ex]
            &\hspace{5mm} \widetilde{B}_t \leftarrow
                \begin{cases}
                   g_t + \mu B_t, & \text{if nesterov}=True \\
                   B_t,           & \text{if nesterov}=False
                \end{cases} \\[1.0ex]
            &\hspace{5mm} O_t \leftarrow \mathrm{NS}^{(a,b,c)}_{k}\!\big(\widetilde{B}_t;\ \varepsilon\big) \\[0.5ex]
            &\hspace{5mm} \theta_t \leftarrow \theta_{t-1} - \gamma\,\lambda\,\theta_{t-1}
               \quad\text{(decoupled weight decay)} \\[0.25ex]

            &\hspace{5mm} \gamma \leftarrow \mathrm{AdjustLR}\!\big(\gamma;\ \mathrm{shape}\!\big(\theta_t \big) \big) \\[0.25ex]
            &\hspace{5mm} \theta_t \leftarrow \theta_t - \gamma\, O_t \\
            &\rule{110mm}{0.4pt} \\[-1.ex]
            &\mathbf{return}\ \theta_t \\[-1.ex]
            &\rule{110mm}{0.4pt}s
       \end{aligned}

    Here, :math:`\mathrm{NS}^{(a,b,c)}_{k}(\cdot;\varepsilon)` denotes :math:`k` iterations of the
    Newton–Schulz orthogonalization operator parameterized by coefficients :math:`(a,b,c)`
    with numerical stabilization :math:`\varepsilon`.

    The purpose for :math:`\mathrm{AdjustLR}\!\big(\gamma;\ \mathrm{shape}\!\big(\theta_t \big) \big)`
    is to make the orthogonalized update have a consistent :math:`RMS` across rectangular matrices.

    Keller's original implementation scales the update by :math:`\sqrt{\max\!\left(1, \frac{A}{B}\right)}`,
    where :math:`A` and :math:`B` are dimension of the matrix being optimized.

    Moonshot's implementation also focuses on matching :math:`RMS` of AdamW. The adjustment is computed as:
    :math:`\gamma \leftarrow {0.2}\gamma\,\sqrt{\max\!\left({A}, {B}\right)}`
    The method is adopted from `Muon is Scalable for LLM Training`_. Research
    results show that with this adjustment Muon can directly reuse the learning rate
    and weight decay tuned for AdamW.

    We provide two options for the learning rate adjustment: "original", which follows Keller's
    implementation, and "match_rms_adamw", which refers to Moonshot's implementation. This gives users the
    flexibility to choose between the two. If `adjust_lr_fn` is not specified, the default is "original".

    For further details regarding the algorithm we refer to `Muon: An optimizer for hidden layers in neural networks`_
    and `Muon is Scalable for LLM Training`_.
    z
    Args:
        u  . Note that Muon is an optimizer for 2D parameters of neural network hidden layers. Other
            parameters, such as bias, and embedding, should be optimized by a standard method such as AdamW.
        lr (float, Tensor, optional): learning rate (default: 1e-3).
        weight_decay (float, optional): weight decay (L2 penalty). (default: 0.1)
        momentum (float, optional): momentum factor (default: 0.95)
        nesterov (bool, optional): enables Nesterov momentum. Only applicable
            when momentum is non-zero
        ns_coefficients (tuple of three floats, optional): coefficients \(a,b,c\) for the
            Newton–Schulz orthogonalization polynomial (default: (z, zc))
        eps (float, optional): term added to the denominator for numerical stability. (default: uY   )
        ns_steps (int, optional): number of Newton–Schulz iteration steps. (default: a  )
        adjust_lr_fn (str, optional): function to adjust learning rate. One of "original" and "match_rms_adamw".
            If not specified, we will default to use "original". (default: None)

    .. _Muon\: An optimizer for hidden layers in neural networks:
        https://kellerjordan.github.io/posts/muon/
    .. _Muon is Scalable for LLM Training:
        https://arxiv.org/pdf/2502.16982

    r?   rQ   rR   r@   rA   rB   r`   c       	            [        U5      nU(       a  [        S5      e[        U 5       H  u  pX   nUR                  S:w  a  [        S5      eX,   nUR	                  USU-
  5        U(       a  UR                  X5      OUn[        UXxU	5      n[        X:UR                  5      nUR                  SX4-  -
  5        UR                  UU* S9  M     g )Nz$Complex parameters are not supportedr   z"Param gradient must be a 2D matrixr   )r   )r	   r   	enumeraterI   lerp_lerpr.   r<   r   mul_add_)r?   rQ   rR   r0   r@   rA   rB   r   r   r   r1   r`   iparamr   bufupdateadjusted_lrs                     r-   _single_tensor_muonr     s     
BB?@@f%x99>ABB #		$H%-53)3,V_PST 5;;?

1r(()

6+
. &r/   )single_tensor_fn)foreachr   c       
         \    Ub  U(       a  [        S5      e[        nU" U UUUUUUUU	U
UUS9  g)zfFunctional API that performs Muon algorithm computation.

See :class:`~torch.optim.Muon` for details.
Nz%Foreach is not supported for Muon yet)	r0   r@   rA   rB   r   r   r   r1   r`   )rW   r   )r?   rQ   rR   r   r0   r@   rA   rB   r   r   r   r1   r`   funcs                 r-   rb   rb   C  sI    * wBCCD!'!r/   ) __doc__r6   collections.abcr   typingr   r$   r   	optimizerr   r   r	   r
   r   __all__ro   rl   rm   rn   rp   rs   rq   rt   r.   ru   Sizer<   r   rv   rr   r   rb   rg   r/   r-   <module>r      s   ,  *     ( 			 '
'#(u)<#='IL'SX''T%c]9>
s9 sn5l		 E FOKrR[Q\\^_h^i jaad`e fXXhWi 	jmK `!/L!/<!/ V!/
 	!/ !/ !/ !/ 5%./!/ !/ 
!/ 3-!/ !/ 
!/H  1DE #&L&<& V&
 d^& 	& & & & 5%./& & 
& 3-& & F&r/   