+
    ˜°³j�:  ã                   ó  € R t ^ RIt^ RIHt ^ RIt^ RIHt ^RIHtHtH	t	H
t
Ht R.tRtRtRtRt^tR	 R
 ltR R lt ! R R]
4      tRR] R] R] R] R] R] R2,           ]n         R R lt]! ]R7      RR/R R ll4       tR# )z%Implementation of the Muon optimizer.N)ÚMutableMapping)ÚTensor)Ú_disable_dynamo_if_unsupportedÚ_params_docÚ
_to_scalarÚ	OptimizerÚParamsTÚMuongH¯¼šò×z>gu“VŽ@g�—nƒ@ @c          
      ó€   € V ^8„  d   QhR\         R\        \        \        \        3,          R\        R\        R\         /# )é   ÚgradÚns_coefficientsÚns_stepsÚepsÚreturn)r   ÚtupleÚfloatÚint)Úformats   "ÚR/home/luca/screen-checking/.venv/lib/python3.14/site-packages/torch/optim/_muon.pyÚ__annotate__r      s@   € ÷ 'ñ 'Ü
ð'Ü#(¬´´uÐ)<Õ#=ð'ÜILð'ÜSXð'äñ'ó    c           	     ó   € V^d8¼  d   \        R4      h\        V P                  4      ^8w  d   \        R4      h\        V4      ^8w  d   \        R4      hVw  rEpV P                  4       pV P	                  ^ 4      V P	                  ^4      8”  d   VP
                  pVP                  VP                  4       P                  VR7      4       \        V4       FF  pWwP
                  ,          p	\        P                  ! W™W•VR7      p
\        P                  ! WzWtR7      pKH  	  V P	                  ^ 4      V P	                  ^4      8”  d   VP
                  pV# )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.
zBNumber of steps must be less than 100 for computational efficiencyz)Input tensor gradient must be a 2D matrixz0Coefficients must be a tuple of exactly 3 values)Ú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   &&&&       r   Ú_zeropower_via_newtonschulzr/      s  € ð �3„ÜØPó
ð 	
ô ˆ4�:‰:ƒ˜!ÔÜÐDÓEÐEÜ
ˆ?Ó˜qÔ ÜÐKÓLÐLØ�G€Aˆ!Ø—‘“€JØ‡y�y�ƒ|�d—i‘i “lÔ"Ø—\‘\ˆ
à‡O�O�J—O‘OÓ%×+Ñ+°Ð+Ó4Ô5ä�8Ž_ˆØ §<¡<Õ/ˆÜ—k’kØ kÀô
ˆô —[’[ ¸*ÔMŠ
ñ ð ‡y�y�ƒ|�d—i‘i “lÔ"Ø—\‘\ˆ
ØÐr   c                ój   € V ^8„  d   QhR\         R\        R,          R\        P                  R\         /# )r   ÚlrÚadjust_lr_fnNÚparam_shaper   )r   Ústrr&   ÚSize)r   s   "r   r   r   I   s1   € ÷ ñ ”5ð ¬¨d­
ð ÄÇÁð ÔPUñ r   c                ó^  € VR,          w  r4Ve   VR8X  d/   \         P                  ! \        ^W4,          4      4      pW,          # VR8X  d/   R\         P                  ! \        W44      4      ,          pW,          # VR8X  d%   \         P                  ! W4,          4      pW,          # RpW,          # )z.Default learning rate adjustment used by Muon.:Nr   NÚoriginalÚmatch_rms_adamwgš™™™™™É?Úspectral_unclampedg      ð?)ÚmathÚsqrtÚmax)r1   r2   r3   ÚAÚBÚadjusted_ratios   &&&   r   Ú
_adjust_lrr@   I   sž   € à�r�?�D€AàÒ˜|¨zÔ9äŸš¤3 q¨!­%£=Ó1ˆð ÕÐð 
Ð*Ô	*ØœtŸyšy¬¨Q«Ó3Õ3ˆð
 ÕÐð	 
Ð-Ô	-ÜŸš 1¥5Ó)ˆð ÕÐð ˆØÕÐr   c                   óœ   a a€ ] tR t^Yt oRRRR]]]3]]R3V3R lV 3R lllt	V3R lR	 lt
]P                  ! 4       RR
 l4       tRtVtV ;t# )r	   gü©ñÒMbP?gš™™™™™¹?gffffffî?TNc                ó|   <€ V ^8„  d   QhRS[ RS[RS[RS[RS[RS[S[S[S[3,          RS[RS[R	S[R
,          RR
/
# )r   Úparamsr1   Úweight_decayÚmomentumÚnesterovr   r   r   r2   Nr   )r   r   Úboolr   r   r4   )r   Ú__classdict__s   "€r   r   ÚMuon.__annotate__Z   s   ø€ ÷ .ñ .áð.ñ ð.ñ ð	.ñ
 ð.ñ ð.ñ ™u¡e©UÐ2Õ3ð.ñ ð.ñ ð.ñ ˜D•jð.ð 
ñ.r   c
                ó  <€ \        V\        4      '       d!   VP                  4       ^8w  d   \        R4      hRV8:  g   \        RV 24      hRV8:  g   \        RV 24      hRV8:  g   \        RV 24      hV	e   V	R9  d   \        RV	 R24      hR	VR
VRVRVRVRVRVRV	/p
\        SV `  W4       V P                   F@  pVR,           F0  pVP                  ^8w  g   K  \        RVP                  4        24      h	  KB  	  R# )é   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: NzAdjust learning rate function z is not supportedr1   rD   rE   rF   r   r   r   r2   rC   zIMuon only supports 2D parameters whereas we found a parameter with size: )r7   r8   r9   )	Ú
isinstancer   Únumelr   ÚsuperÚ__init__Úparam_groupsÚndimr    )ÚselfrC   r1   rD   rE   rF   r   r   r   r2   ÚdefaultsÚgroupÚpÚ	__class__s   &&&&&&&&&&   €r   rO   ÚMuon.__init__Z   s4  ø€ ô �bœ&×!Ò! b§h¡h£j°A¤oÜÐ:Ó;Ð;Ø�bŒyÜÐDÀRÀDÐIÓJÐJØ�hŒÜÐ?À¸zÐJÓKÐKØ�lÔ"ÜÐCÀLÀ>ÐRÓSÐSØÒ#¨ð =
ô )
ô
 Ø0°°Ð>OÐPóð ð
 �"Ø˜LØ˜Ø˜Ø˜Ø�3Ø˜Ø˜Lð	
ˆô 	‰Ñ˜Ô*à×&Ô&ˆEØ˜8—_�_�Ø—6‘6˜Q–;Ü$ØcÐde×djÑdjÓdlÐcmÐnóð ó %ó 'r   c          
      óh   <€ V ^8„  d   QhRS[ RS[S[,          RS[S[,          RS[S[,          RS[/# )r   rT   Úparams_with_gradÚgradsÚmuon_momentum_bufsr   )r   Úlistr   rG   )r   rH   s   "€r   r   rI   Š   sI   ø€ ÷ ñ áðñ ™v�,ðñ ‘F�|ð	ñ
 !¡�Lðñ 
ñr   c                ó  € VR ,           Fò  pVP                   f   K  \        P                  ! V4      '       d   \        R4      hVP                   P                  '       d   \        R4      hVP                  V4       VP                  VP                   4       V P                  V,          pRV9  d4   \        P                  ! VP                   \        P                  R7      VR&   VP                  VR,          4       Kô  	  R# )rC   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)rR   rT   rY   rZ   r[   rU   rd   s   &&&&&  r   Ú_init_groupÚMuon._init_groupŠ   sÌ   € ð �x—�ˆAØ�v‰vŠ~Ùä×Ò ×"Ò"Ü"Ð#MÓNÐNØ�v‰v××ÐÜ"Ð#KÓLÐLà×#Ñ# AÔ&Ø�L‰L˜Ÿ™Ô à—J‘J˜q•MˆEà ¨Ô-Ü+0×+;Ò+;Ø—F‘F¬%×*?Ñ*?ô,�Ð'Ñ(ð ×%Ñ% eÐ,=Õ&>Ö?ñ% !ñ( r   c                ó–  € RpVe.   \         P                  ! 4       ;_uu_ 4        V! 4       pRRR4       V P                   Fr  pVR,          pVR,          pVR,          p. p. p. p	V P                  VVVV	4      p
\	        VVV	VVVVR,          VR,          VR,          VR,          VR	,          V
R
7       Kt  	  V#   + '       g   i     L”; i)z$Performs a single optimization step.Nr1   rD   rE   rF   r   r   r   r2   )	r1   rD   rE   rF   r   r   r   r2   Úhas_complex)r&   Úenable_gradrP   rg   Úmuon)rR   ÚclosureÚlossrT   r1   rD   rE   rY   rZ   r[   rj   s   &&         r   ÚstepÚ	Muon.step§   sÞ   € ð ˆØÒÜ×"Ò"×$Õ$Ù“y�÷ %ð ×&Ô&ˆEØ�t•ˆBØ  Õ0ˆLØ˜ZÕ(ˆHà-/ÐØ"$ˆEØ/1Ðà×*Ñ*ØØ ØØ"ó	ˆKô Ø ØØ"ØØ)Ø!Ø˜zÕ*Ø %Ð&7Õ 8Ø˜%•LØ˜zÕ*Ø" >Õ2Ø'÷ñ! 'ð< ˆ÷C %×$ús   ¤B8Â8C	© )N)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú	DEFAULT_AÚ	DEFAULT_BÚ	DEFAULT_CÚEPSÚDEFAULT_NS_STEPSrO   rg   r&   Úno_gradro   Ú__static_attributes__Ú__classdictcell__Ú__classcell__)rV   rH   s   @@r   r	   r	   Y   sZ   ù‡ € ð Ø!ØØØ7@À)ÈYÐ6WØØ(Ø#'÷.õ .÷`ð ð: ‡]‚]ƒ_ó%ó ÷%ð %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 scale consistently 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 dimensions of the matrix being optimized, which represent fan-out
    and fan-in for a Linear weight matrix.

    Moonshot's implementation 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.

    Jeremy Bernstein in `Deriving Muon`_ proposes a scaling condition on the spectral norm, which
    scales the update by :math:`\sqrt{\frac{A}{B}}`. This is similar to the Keller's "original"
    implementation but removes clamping down to 1.

    We provide these options for the learning rate adjustment: "original", which follows Keller's
    implementation, "match_rms_adamw", which refers to Moonshot's implementation, and "spectral_unclamped",
    which matches Bernstein's implementation. 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`_,
    `Muon is Scalable for LLM Training`_, and `Deriving Muon`_.
    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: a1  )
        adjust_lr_fn (str, optional): function to adjust learning rate. One of "original", "match_rms_adamw", and "spectral_unclamped".
            If not specified, we will default to use "original". (default: None)

    Example:
        >>> # xdoctest: +SKIP
        >>> # Muon only supports 2D params; use a standard optimizer
        >>> # such as AdamW for biases, embeddings, and other non-2D
        >>> # parameters.
        >>> muon_params = [
        ...     p for p in model.parameters() if p.ndim == 2
        ... ]
        >>> other_params = [
        ...     p for p in model.parameters() if p.ndim != 2
        ... ]
        >>> optim_muon = torch.optim.Muon(
        ...     muon_params, lr=0.02, momentum=0.95
        ... )
        >>> optim_adamw = torch.optim.AdamW(
        ...     other_params, lr=3e-4, weight_decay=0.01
        ... )
        >>> optim_muon.zero_grad()
        >>> optim_adamw.zero_grad()
        >>> loss_fn(model(input), target).backward()
        >>> optim_muon.step()
        >>> optim_adamw.step()

    .. _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
    .. _Deriving Muon:
        https://jeremybernste.in/writing/deriving-muon

    c                ó(  € V ^8„  d   QhR\         \        ,          R\         \        ,          R\         \        ,          R\        R\        R\        R\        R\        \        \        \        3,          R	\
        R
\        R\        R,          R\        RR/# )r   rC   rZ   r[   r1   rD   rE   rF   r   r   r   r2   Nrj   r   )r\   r   r   rG   r   r   r4   )r   s   "r   r   r   >  s¦   € ÷ !/ñ !/Ü”�Lð!/ä”�<ð!/ô œV�ð!/ô
 	ð!/ô ð!/ô ð!/ô ð!/ô œ5¤%¬Ð.Õ/ð!/ô ð!/ô 
ð!/ô ˜•*ð!/ô ð!/ð 
ñ!/r   c       	         óÔ  € \        V4      pV'       d   \        R 4      h\        V 4       Fº  w  rÍW,          pVP                  ^8w  d   \        R4      hW,,          pVP	                  V^V,
          4       V'       d   VP                  Wõ4      MTp\        VWxV	4      p\        W:VP                  4      pVP                  ^W4,          ,
          4       VP                  VV) R7       K¼  	  R# )z$Complex parameters are not supportedz"Param gradient must be a 2D matrix)r   N)r   r   Ú	enumeraterQ   Úlerp_Úlerpr/   r@   r   Úmul_Úadd_)rC   rZ   r[   r1   rD   rE   rF   r   r   r   r2   rj   ÚiÚparamr   ÚbufÚupdateÚadjusted_lrs   &&&$$$$$$$$$      r   Ú_single_tensor_muonr‹   >  s¼   € ô 
�B‹€BßÜÐ?Ó@Ð@ä˜fÖ%‰ˆØ�xˆØ�9‰9˜Œ>ÜÐAÓBÐBà Õ#ˆØ�	‰	�$˜˜H�Ô%ß-5�—‘˜3Ô)¸3ˆä,¨V°_ÐPSÓTˆä  °5·;±;Ó?ˆà�
‰
�1�rÕ(Õ(Ô)Ø�
‰
�6 + ˆ
Ö.ó &r   )Úsingle_tensor_fnÚforeachc                óB  € V ^8„  d   QhR\         \        ,          R\         \        ,          R\         \        ,          R\        R,          R\        R\        R\        R	\        R
\        \        \        \        3,          R\
        R\        R\        R,          R\        RR/# )r   rC   rZ   r[   r�   Nr1   rD   rE   rF   r   r   r   r2   rj   r   )r\   r   rG   r   r   r   r4   )r   s   "r   r   r   c  s´   € ÷ &ñ &Ü”�Lð&ä”�<ð&ô œV�ð&ô
 �D�[ð&ô 	ð&ô ð&ô ð&ô ð&ô œ5¤%¬Ð.Õ/ð&ô ð&ô 
ð&ô ˜•*ð&ô ð&ð 
ñ&r   c       
        óh   € Ve   V'       d   \        R4      h\        pV! V VVVVVVVV	V
VVR7       R# )zfFunctional API that performs Muon algorithm computation.

See :class:`~torch.optim.Muon` for details.
Nz%Foreach is not supported for Muon yet)	r1   rD   rE   rF   r   r   r   r2   rj   )ra   r‹   )rC   rZ   r[   r�   r1   rD   rE   rF   r   r   r   r2   rj   Úfuncs   &&&$$$$$$$$$$ r   rl   rl   b  sI   € ð* ÒŸwÜÐBÓCÐCä€DáØØØØØ!ØØØ'ØØØ!Ø÷r   gš™™™™À)Ú__doc__r:   Úcollections.abcr   r&   r   Ú	optimizerr   r   r   r   r   Ú__all__ry   rv   rw   rx   rz   r/   r@   r	   r‹   rl   rq   r   r   Ú<module>r•      sî   ðñ ,ã Ý *ã Ý ÷õ ð ˆ(€ð €Ø€	Ø€	Ø€	ØÐ õ'õTô tˆ9ô tðp:ðv	à	ˆð Eð FOÀKÈrÐR[ÐQ\Ð\^Ð_hÐ^ið jaØadÐ`eð fXØXhÐWið "jð.õwið „õ\!/ñH  Ð1DÔEð&ð
  ö&ó Fò&r   