+
    &j                     b   ^ RI HtHtHtHtHt ^ RIHt ^ RI	H
t
 ^ RIHtHtHtHtHt  ! R R4      t ! R R]4      t ! R	 R
]4      t ! R R]4      t ! R R]4      t ! R R]4      t ! R R]4      t ! R R]4      t ! R R]4      t ! R R]4      t ! R R]4      t ! R R]4      tR tR# )    )CallableListOptionalTupleUnionN)Module)tree_flattentree_map
tree_mergetree_reducetree_unflattenc                   *  a  ] tR t^
t o RtRR ltV 3R lR ltV 3R lR ltV 3R lR	 ltV 3R
 lR lt	V 3R lR lt
]R 4       t]P                  V 3R lR l4       t]R 4       t]R 4       t]P                  V 3R lR l4       tV 3R lR ltRtV tR# )	OptimizerzThe base class for all optimizers. It allows us to implement an
optimizer on a per-parameter basis and apply it to a parameter tree.
Nc                    R V n         R\        P                  ! ^ \        P                  4      /V n        T;'       g    / P                  4        UUu/ uF  w  r#W#bK	  	  uppV n        R# u uppi )FstepN)_initializedmxarrayuint64_stateitems_schedulers)self
schedulerskvs   &&  q/Users/jameslopez/projects/CWCArchive/cwc-podcast/.venv/lib/python3.14/site-packages/mlx/optimizers/optimizers.py__init__Optimizer.__init__   sV    !rxx29956.8.>.>B-E-E-GH-GTQAD-GHHs   A)c                &   < V ^8  d   QhRS[ RS[/# )   model	gradients)r   dict)format__classdict__s   "r   __annotate__Optimizer.__annotate__   s     	= 	=F 	=t 	=    c                F    VP                  V P                  W!4      4       R# )a   Apply the gradients to the parameters of the model and update the
model with the new parameters.

Args:
    model (mlx.nn.Module): An mlx module to be updated.
    gradients (dict): A Python tree of gradients, most likely computed
                      via :func:`mlx.nn.value_and_grad`.
N)updateapply_gradients)r   r"   r#   s   &&&r   r+   Optimizer.update   s     	T)));<r)   c                    < V ^8  d   QhRS[ /# r!   
parametersr$   )r%   r&   s   "r   r'   r(      s     *! *!t *!r)   c                   a a V3R loS! VS P                   4       \        V 3R lVS P                   4       RS n        R# )a  Initialize the optimizer's state

This function can be used to initialize optimizers which have state
(like momentum in :class:`SGD`). Using this method is optional as the
optimizer will initialize itself if the state is not yet set. However,
there are some cases where explicit initialization is useful in order
to have access to the :attr:`Optimizer.state` before the first call to
:meth:`Optimizer.update`.

Args:
    model (dict): A Python tree of parameters.

Example:
    >>> optimizer = optim.SGD(learning_rate=1e-1, momentum=0.9)
    >>> model = nn.Linear(2, 2)
    >>> optimizer.init(model.trainable_parameters())
    >>> optimizer.state.keys()
    dict_keys(['step', 'learning_rate', 'weight', 'bias'])
c           	        < \        V \        \        34      '       d   \        V4      p\        \	        V4      4       F  pS! W,          W,          4      W&   K  	  \	        V4      \	        V 4      8w  d)   VP                  \        R  V \	        V4      R 4      4       \        V 4      ! V4      # \        V \        4      '       dD   V P                  4        F-  w  r4W19  d   \        R V4      W&   K  S! WAV,          4      W&   K/  	  V# V# )c                     / # N _s   &r   <lambda>6Optimizer.init.<locals>.update_state.<locals>.<lambda>;   s    Br)   Nc                     / # r5   r6   r7   s   &r   r9   r:   @   s    br)   )

isinstancelisttuplerangelenextendr
   typer$   r   )paramsstateir   r   update_states   &&   r   rF   $Optimizer.init.<locals>.update_state5   s    &4-00Us5z*A+FIux@EH +u:V,LL,s5z|8L!MNF|E**FD))"LLNDA~#+L!#<#/8#<	 +
 r)   c                 :   < T;'       g    SP                  W4      # r5   )init_single)psr   s   &&r   r9    Optimizer.init.<locals>.<lambda>H   s    a994#3#3A#99r)   TN)r   r
   r   )r   r0   rF   s   f&@r   initOptimizer.init   s1    ,	$ 	Z-9:t{{S r)   c                :   < V ^8  d   QhRS[ P                  RS[/# r!   	parameterrD   r   r   r$   )r%   r&   s   "r   r'   r(   K   s     $ $RXX $d $r)   c                    \        4       h)zTo be extended by the children classes to implement each optimizer's
state initialization.

Args:
    parameter (mx.array): A single parameter that will be optimized.
    state (dict): The optimizer's state.
NotImplementedErrorr   rQ   rD   s   &&&r   rI   Optimizer.init_singleK        "##r)   c                &   < V ^8  d   QhRS[ RS[ /# r!   r#   r0   r1   )r%   r&   s   "r   r'   r(   U   s     N N N4 Nr)   c                N   V P                   '       g   V P                  V4       V P                  P                  4        F$  w  r4V! V P                  4      V P
                  V&   K&  	  V P                  ^,           V P
                  R&   \        V P                  WV P
                  4      # )a  Apply the gradients to the parameters and return the updated parameters.

Can be used to update a model via
``model.update(opt.apply_gradients(grads, model))`` which is precisely
how :meth:`Optimizer.update` is implemented.

Args:
    gradients (dict): A Python tree of gradients.
    parameters (dict): A Python tree of parameters. It can be a
      superset of the gradients. In that case the returned python
      tree will be of the same structure as the gradients.
r   )r   rM   r   r   r   rD   r
   apply_single)r   r#   r0   param	schedulers   &&&  r   r,   Optimizer.apply_gradientsU   s        IIi  !% 0 0 6 6 8E )$)) 4DJJu !9 "YY]

6 ))9$**MMr)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# r!   gradientrQ   rD   rR   )r%   r&   s   "r   r'   r(   o   s*     $ $RXX $"(( $4 $r)   c                    \        4       h)zTo be extended by derived classes to implement the optimizer's update.

Args:
    gradient (mx.array): The ``parameter`` gradient.
    parameter (mx.array): The ``parameter`` to update.
    state (dict): The optimizer's state.
rT   )r   rb   rQ   rD   s   &&&&r   r\   Optimizer.apply_singleo   rX   r)   c                    V P                   # )z!The optimizer's state dictionary.)r   r   s   &r   rD   Optimizer.statey   s     {{r)   c                    < V ^8  d   QhRS[ /# r!   rD   r1   )r%   r&   s   "r   r'   r(      s      4 r)   c                     R V n         Wn        R# )FN)r   r   )r   rD   s   &&r   rD   rg   ~   s    !r)   c                (    V P                   R ,          # )r   rD   rf   s   &r   r   Optimizer.step   s    zz&!!r)   c                (    V P                   R ,          # )learning_raterl   rf   s   &r   ro   Optimizer.learning_rate   s    zz/**r)   c                J   < V ^8  d   QhRS[ S[S[P                  3,          /# r!   ro   r   floatr   r   )r%   r&   s   "r   r'   r(      s!     > >5+A >r)   c                L    \         P                  ! V4      V P                  R &   R# ro   N)r   r   rD   )r   ro   s   &&r   ro   rp      s    &(hh}&=

?#r)   c                |   < V ^8  d   QhRS[ RS[S[S[S[P
                  .S[P
                  3,          3,          /# )r!   namer]   )strr   rt   r   r   r   )r%   r&   s   "r   r'   r(      s;     % %% %eXrxxj"((6J-K&K L%r)   c                    \        V\        4      '       d"   W P                  V&   V! V P                  4      pM\        P
                  ! V4      pW0P                  V&   R# )zL
To be used by derived classes to optionally put a parameter on a schedule.
N)r<   r   r   r   r   r   rD   )r   rx   r]   rQ   s   &&& r   _maybe_scheduleOptimizer._maybe_schedule   sF     eX&&%*T"dii(II$

4r)   )r   r   r   r5   )__name__
__module____qualname____firstlineno____doc__r   r+   rM   rI   r,   r\   propertyrD   setterr   ro   r{   __static_attributes____classdictcell__)r&   s   @r   r   r   
   s     I
	= 	=*! *!X$ $N N4$ $   \\  " " + + > >% %r)   r   c                      a a ] tR t^t oRt. 3V3R lV 3R llltV3R lR ltV3R lR ltV3R lR	 lt]	R
 4       t
]
P                  V3R lR l4       t
]	R 4       t]P                  V3R lR l4       tRtVtV ;t# )MultiOptimizeraD  Wraps a list of optimizers with corresponding weight predicates/filters
to make it easy to use different optimizers for different weights.

The predicates take the full "path" of the weight and the weight itself and
return True if it should be considered for this optimizer. The last
optimizer in the list is a fallback optimizer and no predicate should be
given for it.

Args:
    optimizers (list[Optimizer]): A list of optimizers to delegate to
    filters (list[Callable[[str, array], bool]): A list of predicates that
        should be one less than the provided optimizers.
c                    < V ^8  d   QhRS[ /# )r!   filters)r=   )r%   r&   s   "r   r'   MultiOptimizer.__annotate__   s     
@ 
@D 
@r)   c                   < \         SV `  4        / V n        \        V4      \        V4      ^,
          8w  d,   \	        R\        V4       R\        V4      ^,
           R24      hWn        VR .,           V n        R# )   zGiven z filters but z needed.c                      R # )Tr6   )argskwargss   *,r   r9   )MultiOptimizer.__init__.<locals>.<lambda>   s    $r)   N)superr   r   r@   
ValueError
optimizersr   )r   r   r   	__class__s   &&&r   r   MultiOptimizer.__init__   sn    w<3z?Q..WmC
OA4E3FhO  %">!??r)   c                    < V ^8  d   QhRS[ /# )r!   r#   r1   )r%   r&   s   "r   r'   r      s     2 24 2r)   c                   \        V P                  4      ^8X  d   V.# \        \        V P                  4      4       Uu. uF  p. NK  	  pp\        V4      pV FL  w  rV\	        V P
                  4       F.  w  rxV! WV4      '       g   K  W7,          P                  WV34        KJ  	  KN  	  V U	u. uF  p	\        V	4      NK  	  up	# u upi u up	i )r   )r@   r   r?   r	   	enumerater   appendr   )
r   r#   r8   partsflat_gradientsr   grE   fnrJ   s
   &&        r   _split_dictionary MultiOptimizer._split_dictionary   s    t1$;"3t#789889%i0"DA"4<<0a88HOOQF+ 1 # ,115aq!511 : 2s   C,Cc                    < V ^8  d   QhRS[ /# r/   r1   )r%   r&   s   "r   r'   r      s      t r)   c                    \        V P                  V P                  V4      4       F  w  r#VP                  V4       K  	  R # r5   )zipr   r   rM   )r   r0   orJ   s   &&  r   rM   MultiOptimizer.init   s0    )?)?
)KLDAFF1I Mr)   c                &   < V ^8  d   QhRS[ RS[ /# rZ   r1   )r%   r&   s   "r   r'   r      s       4 r)   c                    / p\        V P                  V P                  V4      4       F  w  rE\        W4P	                  WR4      4      pK!  	  V# r5   )r   r   r   r   r,   )r   r#   r0   treer   r   s   &&&   r   r,   MultiOptimizer.apply_gradients   sD    )?)?	)JKDAd$5$5a$DED Lr)   c                Z    R V P                    Uu. uF  qP                  NK  	  up/# u upi )states)r   rD   )r   r   s   & r   rD   MultiOptimizer.state   s%    DOO<Oq77O<==<s   (c                    < V ^8  d   QhRS[ /# ri   r1   )r%   r&   s   "r   r'   r      s      4 r)   c                    R V9  g+   \        VR ,          4      \        V P                  4      8w  d   \        R4      h\        V P                  VR ,          4       F  w  r#W2n        K  	  R# )r   zInvalid state providedN)r@   r   r   r   rD   )r   rD   r   rK   s   &&  r   rD   r      sO    5 Ch$8C<P$P566x9DAG :r)   c                <    V P                   ^ ,          P                  # )r   r   ro   rf   s   &r   ro   MultiOptimizer.learning_rate   s    q!///r)   c                J   < V ^8  d   QhRS[ S[S[P                  3,          /# rr   rs   )r%   r&   s   "r   r'   r      s!     , ,5+A ,r)   c                8    V P                    F	  pWn        K  	  R # r5   r   )r   ro   r   s   && r   ro   r      s    A+O !r)   )r   r   r   )r}   r~   r   r   r   r   r   rM   r,   r   rD   r   ro   r   r   __classcell__r   r&   s   @@r   r   r      s      46 
@ 
@2 2   > > \\  0 0 , , ,r)   r   c                   j   a a ] tR t^t oRtR	V3R lV 3R llltV3R lR ltV3R lR ltRtVt	V ;t
# )
SGDab  The stochastic gradient descent optimizer.

Updates a parameter :math:`w` with a gradient :math:`g` as follows

.. math::

    v_{t+1} &= \mu v_t + (1 - \tau) g_t \\
    w_{t+1} &= w_t - \lambda v_{t+1}

Args:
    learning_rate (float or callable): The learning rate :math:`\lambda`.
    momentum (float, optional): The momentum strength :math:`\mu`. Default: ``0``
    weight_decay (float, optional): The weight decay (L2 penalty). Default: ``0``
    dampening (float, optional): Dampening for momentum :math:`\tau`. Default: ``0``
    nesterov (bool, optional): Enables Nesterov momentum. Default: ``False``
c          
         < V ^8  d   QhRS[ S[S[S[P                  .S[P                  3,          3,          RS[RS[RS[RS[/# )r!   ro   momentumweight_decay	dampeningnesterov)r   rt   r   r   r   bool)r%   r&   s   "r   r'   SGD.__annotate__   s[     ! !UHbhhZ-A$BBC! ! 	!
 ! !r)   c                   < V'       d   V^ 8:  g   V^ 8w  d   \        R4      h\        SV `	  4        V P                  RV4       W n        W0n        W@n        WPn        R# )r   z9Nesterov momentum requires a momentum and zero dampening.ro   N)r   r   r   r{   r   r   r   r   )r   ro   r   r   r   r   r   s   &&&&&&r   r   SGD.__init__   sV     Q)q.K  	_m< (" r)   c                :   < V ^8  d   QhRS[ P                  RS[/# rP   rR   )r%   r&   s   "r   r'   r          . .RXX .d .r)   c                8    \         P                  ! V4      VR&   R# Initialize optimizer stater   Nr   
zeros_likerV   s   &&&r   rI   SGD.init_single      ]]9-c
r)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# ra   rR   )r%   r&   s   "r   r'   r     s/     N NRXX N"(( N4 Nr)   c                ^   V P                   ^ 8w  d   WP                   V,          ,          pV P                  ^ 8:  d3   W P                  P                  VP                  4      V,          ,
          # V P                  VP                  R4      ,          pV P                  ^ 8  d#   V^V P                  ,
          V,          ,          pMWA,          pV P                  '       d   WP                  V,          ,           pMTpWCR&   W P                  P                  VP                  4      V,          ,
          # )zNPerforms the SGD parameter update and stores :math:`v` in the
optimizer state.r   )r   r   ro   astypedtypegetr   r   )r   rb   rQ   rD   r   r+   s   &&&&  r   r\   SGD.apply_single  s     !))I55H==A1188H8SSSMMEIIcN*>>A!dnn$00AMA=== 11FFc
--44X^^DvMMMr)   )r   r   r   r   )        r   r   Fr}   r~   r   r   r   r   rI   r\   r   r   r   r   s   @@r   r   r      s0     "! !(. .N N Nr)   r   c                   j   a a ] tR tRt oRtR
V3R lV 3R llltV3R lR ltV3R lR ltR	tVt	V ;t
# )RMSpropi)  a;  The RMSprop optimizer [1].

[1]: Tieleman, T. and Hinton, G. 2012. Lecture 6.5-rmsprop, coursera: Neural networks for machine learning

.. math::

    v_{t+1} &= \alpha v_t + (1 - \alpha) g_t^2 \\
    w_{t+1} &= w_t - \lambda \frac{g_t}{\sqrt{v_{t+1}} + \epsilon}

Args:
    learning_rate (float or callable): The learning rate :math:`\lambda`.
    alpha (float, optional): The smoothing constant :math:`\alpha`.
      Default: ``0.99``
    eps (float, optional): The term :math:`\epsilon` added to the denominator
      to improve numerical stability. Default: ``1e-8``
c                   < V ^8  d   QhRS[ S[S[S[P                  .S[P                  3,          3,          RS[RS[/# )r!   ro   alphaepsr   rt   r   r   r   )r%   r&   s   "r   r'   RMSprop.__annotate__;  sG      UHbhhZ-A$BBC  	r)   c                  < \         SV `  4        V P                  R V4       W n        W0n        V P                  R8  d   \        RV P                   R24      hV P                  R8  d   \        RV P                   R24      hR# )ro   r   zRMSprop alpha should be >=0,  was provided insteadzRMSprop epsilon should be >0, N)r   r   r{   r   r   r   )r   ro   r   r   r   s   &&&&r   r   RMSprop.__init__;  s     	_m<
::/

|;PQ  88c>0
:OP  r)   c                :   < V ^8  d   QhRS[ P                  RS[/# rP   rR   )r%   r&   s   "r   r'   r   P  r   r)   c                8    \         P                  ! V4      VR&   R# r   r   rV   s   &&&r   rI   RMSprop.init_singleP  r   r)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# ra   rR   )r%   r&   s   "r   r'   r   T  s*     
> 
>RXX 
>"(( 
>4 
>r)   c                Z   V P                   P                  VP                  4      pV P                  pV P                  pVR,          pWW,          ^V,
          \
        P                  ! V4      ,          ,           pWsR&   W$V,          \
        P                  ! V4      V,           ,          ,
          # )zRPerforms the RMSprop parameter update and stores :math:`v` in the optimizer state.r   )ro   r   r   r   r   r   squaresqrt)r   rb   rQ   rD   lrr   r   r   s   &&&&    r   r\   RMSprop.apply_singleT  s{    &&x~~6

hh#JIUbii&999c
=BGGAJ,<===r)   )r   r   )Gz?:0yE>r   r   s   @@r   r   r   )  s-     " *. .
> 
> 
>r)   r   c                   j   a a ] tR tRt oRtR
V3R lV 3R llltV3R lR ltV3R lR ltR	tVt	V ;t
# )Adagradia  a,  The Adagrad optimizer [1].

Our Adagrad implementation follows the original paper. In detail,

[1]: Duchi, J., Hazan, E. and Singer, Y., 2011. Adaptive subgradient methods
for online learning and stochastic optimization. JMLR 2011.

.. math::

    v_{t+1} &= v_t + g_t^2 \\
    w_{t+1} &= w_t - \lambda \frac{g_t}{\sqrt{v_{t+1}} + \epsilon}

Args:
    learning_rate (float or callable): The learning rate :math:`\lambda`.
    eps (float, optional): The term :math:`\epsilon` added to the
      denominator to improve numerical stability. Default: ``1e-8``
c                |   < V ^8  d   QhRS[ S[S[S[P                  .S[P                  3,          3,          RS[/# )r!   ro   r   r   )r%   r&   s   "r   r'   Adagrad.__annotate__t  s=      UHbhhZ-A$BBC r)   c                   < \         SV `  4        V P                  R V4       W n        V P                  R8  d   \	        RV P                   R24      hR# )ro   r   zAdagrad epsilon should be >0, r   N)r   r   r{   r   r   )r   ro   r   r   s   &&&r   r   Adagrad.__init__t  sS    
 	_m<88c>0
:OP  r)   c                :   < V ^8  d   QhRS[ P                  RS[/# rP   rR   )r%   r&   s   "r   r'   r     r   r)   c                8    \         P                  ! V4      VR&   R# r   r   rV   s   &&&r   rI   Adagrad.init_single  r   r)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# ra   rR   )r%   r&   s   "r   r'   r     s*     	> 	>RXX 	>"(( 	>4 	>r)   c                   V P                   P                  VP                  4      pV P                  pVR,          \        P
                  ! V4      ,           pWcR&   W$V,          \        P                  ! V4      V,           ,          ,
          # )zRPerforms the Adagrad parameter update and stores :math:`v` in the
optimizer state.r   )ro   r   r   r   r   r   r   )r   rb   rQ   rD   r   r   r   s   &&&&   r   r\   Adagrad.apply_single  sd     &&x~~6hh#J8,,c
=BGGAJ,<===r)   )r   )r   r   r   s   @@r   r   r   a  s-     $ . .	> 	> 	>r)   r   c                   j   a a ] tR tRt oRtR
V3R lV 3R llltV3R lR ltV3R lR ltR	tVt	V ;t
# )AdaDeltai  a0  The AdaDelta optimizer with a learning rate [1].

Our AdaDelta implementation follows the original paper. In detail,

[1]: Zeiler, M.D., 2012. ADADELTA: an adaptive learning rate method. arXiv preprint arXiv:1212.5701.

.. math::

    v_{t+1} &= \rho v_t + (1 - \rho) g_t^2 \\
    \Delta w_{t+1} &= \frac{\sqrt{u_t + \epsilon}}{\sqrt{v_{t+1} + \epsilon}} g_t \\
    u_{t+1} &= \rho u_t + (1 - \rho) \Delta w_{t+1}^2 \\
    w_{t+1} &= w_t - \lambda \Delta w_{t+1}

Args:
    learning_rate (float or callable): The learning rate :math:`\lambda`.
    rho (float, optional): The coefficient :math:`\rho` used for computing a
        running average of squared gradients. Default: ``0.9``
    eps (float, optional): The term :math:`\epsilon` added to the denominator to improve
      numerical stability. Default: `1e-8`
c                   < V ^8  d   QhRS[ S[S[S[P                  .S[P                  3,          3,          RS[RS[/# )r!   ro   rhor   r   )r%   r&   s   "r   r'   AdaDelta.__annotate__  sG      UHbhhZ-A$BBC  	r)   c                  < \         SV `  4        V P                  R V4       W n        W0n        V P                  R8  d   \        RV P                   R24      hV P                  R8  d   \        RV P                   R24      hR# )ro   r   zAdaDelta rho should be >=0, r   zAdaDelta epsilon should be >0, N)r   r   r{   r   r   r   )r   ro   r   r   r   s   &&&&r   r   AdaDelta.__init__  s     	_m<88c>.txxj8MN  88c>1$((;PQ  r)   c                :   < V ^8  d   QhRS[ P                  RS[/# rP   rR   )r%   r&   s   "r   r'   r          . .RXX .d .r)   c                j    \         P                  ! V4      VR&   \         P                  ! V4      VR&   R# )r   r   uNr   rV   s   &&&r   rI   AdaDelta.init_single  &    ]]9-c
]]9-c
r)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# ra   rR   )r%   r&   s   "r   r'   r     s*     " "RXX ""(( "4 "r)   c                   V P                   P                  VP                  4      pV P                  pV P                  pVR,          pVR,          pWW,          ^V,
          \
        P                  ! V4      ,          ,           p\
        P                  ! W,           4      \
        P                  ! Wv,           4      ,          V,          p	WX,          ^V,
          \
        P                  ! V	4      ,          ,           pWsR&   WR&   W$V	,          ,
          # )zaPerforms the AdaDelta parameter update and stores :math:`v` and
:math:`u` in the optimizer state.r   r   )ro   r   r   r   r   r   r   r   )
r   rb   rQ   rD   r   r   r   r   r   ds
   &&&&      r   r\   AdaDelta.apply_single  s     &&x~~6hhhh#J#JGq3w"))H"555GGAGrwwqw//(:Gq3w"))A,..c
c
6!!r)   )r   r   )?ư>r   r   s   @@r   r   r     s-     * (. .
" " "r)   r   c                   t   a a ] tR tRt oRtRR.RR3V3R lV 3R llltV3R	 lR
 ltV3R lR ltRtVt	V ;t
# )Adami  a?  The Adam optimizer [1]. In detail,

[1]: Kingma, D.P. and Ba, J., 2015. Adam: A method for stochastic
optimization. ICLR 2015.

.. math::

    m_{t+1} &= \beta_1 m_t + (1 - \beta_1) g_t \\
    v_{t+1} &= \beta_2 v_t + (1 - \beta_2) g_t^2 \\
    w_{t+1} &= w_t - \lambda \frac{m_{t+1}}{\sqrt{v_{t+1}} + \epsilon}

Args:
    learning_rate (float or callable): The learning rate :math:`\lambda`.
    betas (Tuple[float, float], optional): The coefficients
      :math:`(\beta_1, \beta_2)` used for computing running averages of the
      gradient and its square. Default: ``(0.9, 0.999)``
    eps (float, optional): The term :math:`\epsilon` added to the
      denominator to improve numerical stability. Default: ``1e-8``
    bias_correction (bool, optional): If set to ``True``, bias correction
      is applied. Default: ``False``
r  +?r   Fc                   < V ^8  d   QhRS[ S[S[S[P                  .S[P                  3,          3,          RS[S[,          RS[RS[/# )r!   ro   betasr   bias_correctionr   rt   r   r   r   r   r   )r%   r&   s   "r   r'   Adam.__annotate__  sU     / /UHbhhZ-A$BBC/ E{/ 	/
 /r)   c                l   < \         SV `  4        V P                  R V4       W n        W0n        W@n        R# rv   )r   r   r{   r	  r   r
  )r   ro   r	  r   r
  r   s   &&&&&r   r   Adam.__init__  s0     	_m<
.r)   c                :   < V ^8  d   QhRS[ P                  RS[/# rP   rR   )r%   r&   s   "r   r'   r    r   r)   c                j    \         P                  ! V4      VR&   \         P                  ! V4      VR&   R# r   mr   Nr   rV   s   &&&r   rI   Adam.init_single  r   r)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# ra   rR   )r%   r&   s   "r   r'   r     s*     ; ;RXX ;"(( ;4 ;r)   c                >   V P                   P                  VP                  4      pV P                  w  rVV P                  pV P
                  pV P                  p	VR,          p
VR,          pWZ,          ^V,
          V,          ,           p
Wk,          ^V,
          \        P                  ! V4      ,          ,           pWR&   WR&   V'       d   V^WY,          ,
          ,          P                  VP                  4      p\        P                  ! ^Wi,          ,
          4      P                  VP                  4      pW,          p\        P                  ! V4      V,          V,           pW.V,          ,
          # W$V
,          \        P                  ! V4      V,           ,          ,
          # )z]Performs the Adam parameter update and stores :math:`v` and
:math:`m` in the optimizer state.r  r   )ro   r   r   r	  r   r
  r   r   r   rsqrtr   )r   rb   rQ   rD   r   b1b2r   r
  r   r  r   c1c2	numeratordenominators   &&&&            r   r\   Adam.apply_single   s(    &&x~~6hh..yy#J#JFa"f((Fa"f		( 333c
c
BH%--hnn=B!bh,'..x~~>BI''!*r/C/K;666Avc)9:::r)   )r	  r
  r   r   r   s   @@r   r  r    s<     2 "5\ %/ /. .
; ; ;r)   r  c                   j   a a ] tR tRt oRtRR.RRR3V3R lV 3R	 llltV3R
 lV 3R lltRtVtV ;t	# )AdamWi  a  The AdamW optimizer [1]. We update the weights with a weight_decay
(:math:`\lambda`) value:

[1]: Loshchilov, I. and Hutter, F., 2019. Decoupled weight decay
regularization. ICLR 2019.

.. math::

    m_{t+1} &= \beta_1 m_t + (1 - \beta_1) g_t \\
    v_{t+1} &= \beta_2 v_t + (1 - \beta_2) g_t^2 \\
    w_{t+1} &= w_t - \alpha (\frac{m_{t+1}}{\sqrt{v_{t+1}} + \epsilon} + \lambda w_t)

Args:
    learning_rate (float or callable): The learning rate :math:`\alpha`.
    betas (Tuple[float, float], optional): The coefficients
      :math:`(\beta_1, \beta_2)` used for computing running averages of the
      gradient and its square. Default: ``(0.9, 0.999)``
    eps (float, optional): The term :math:`\epsilon` added to the
      denominator to improve numerical stability. Default: ``1e-8``
    weight_decay (float, optional): The weight decay :math:`\lambda`.
      Default: ``0.01``.
    bias_correction (bool, optional): If set to ``True``, bias correction
      is applied. Default: ``False``
r  r  r   {Gz?Fc          
         < V ^8  d   QhRS[ S[S[S[P                  .S[P                  3,          3,          RS[S[,          RS[RS[RS[/# )r!   ro   r	  r   r   r
  r  )r%   r&   s   "r   r'   AdamW.__annotate__4  s_     ) )UHbhhZ-A$BBC) E{) 	)
 ) )r)   c                :   < \         SV `  VVVVR 7       W@n        R# ))ro   r	  r   r
  N)r   r   r   )r   ro   r	  r   r   r
  r   s   &&&&&&r   r   AdamW.__init__4  s+     	'+	 	 	
 )r)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# ra   rR   )r%   r&   s   "r   r'   r"  D  s*     
 
RXX 
"(( 
4 
r)   c                   < V P                   P                  VP                  4      p\        SV `  W^W@P
                  ,          ,
          ,          V4      # )zRPerforms the AdamW parameter update by modifying the parameters
passed into Adam.
)ro   r   r   r   r\   r   )r   rb   rQ   rD   r   r   s   &&&& r   r\   AdamW.apply_singleD  sI    
 &&x~~6w#1r,=,='=#=>
 	
r)   )r   )
r}   r~   r   r   r   r   r\   r   r   r   r   s   @@r   r  r    s5     8 "5\" %) ) 
 
 
r)   r  c                   r   a a ] tR tRt oRtRR.R3V3R lV 3R llltV3R lR	 ltV3R
 lR ltRtVt	V ;t
# )AdamaxiO  al  The Adamax optimizer, a variant of Adam based on the infinity norm [1].

Our Adam implementation follows the original paper and omits the bias
correction in the first and second moment estimates. In detail,

[1]: Kingma, D.P. and Ba, J., 2015. Adam: A method for stochastic
optimization. ICLR 2015.

.. math::

    m_{t+1} &= \beta_1 m_t + (1 - \beta_1) g_t \\
    v_{t+1} &= \max(\beta_2 v_t, |g_t|) \\
    w_{t+1} &= w_t - \lambda \frac{m_{t+1}}{v_{t+1} + \epsilon}

Args:
    learning_rate (float or callable): The learning rate :math:`\lambda`.
    betas (Tuple[float, float], optional): The coefficients
      :math:`(\beta_1, \beta_2)` used for computing running averages of the
      gradient and its square. Default: ``(0.9, 0.999)``
    eps (float, optional): The term :math:`\epsilon` added to the
      denominator to improve numerical stability. Default: ``1e-8``
r  r  r   c                   < V ^8  d   QhRS[ S[S[S[P                  .S[P                  3,          3,          RS[S[,          RS[/# )r!   ro   r	  r   r   rt   r   r   r   r   )r%   r&   s   "r   r'   Adamax.__annotate__g  sK     
 
UHbhhZ-A$BBC
 E{
 	
r)   c                h   < \         SV `  WV4       R V8:  g   \        RV P                   R24      hR# )r   zEpsilon value should be >=0, r   N)r   r   r   r   )r   ro   r	  r   r   s   &&&&r   r   Adamax.__init__g  s>     	s3cz/z9NO  r)   c                :   < V ^8  d   QhRS[ P                  RS[/# rP   rR   )r%   r&   s   "r   r'   r,  s  r   r)   c                j    \         P                  ! V4      VR&   \         P                  ! V4      VR&   R# r  r   rV   s   &&&r   rI   Adamax.init_singles  r   r)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# ra   rR   )r%   r&   s   "r   r'   r,  x  s*     . .RXX ."(( .4 .r)   c                   V P                   P                  VP                  4      pV P                  w  rVV P                  pVR,          pVR,          p	WX,          ^V,
          V,          ,           p\
        P                  ! Wi,          \
        P                  ! V4      4      p	WR&   WR&   W$V,          W,           ,          ,
          # )z_Performs the Adamax parameter update and stores :math:`v` and
:math:`m` in the optimizer state.r  r   )ro   r   r   r	  r   r   maximumabs)
r   rb   rQ   rD   r   r  r  r   r  r   s
   &&&&      r   r\   Adamax.apply_singlex  s     &&x~~6hh#J#JFa"f((JJrvrvvh/0c
c
6QW---r)   r6   r   r   s   @@r   r)  r)  O  s9     4 "5\	
 
. .
. . .r)   r)  c                   r   a a ] tR tRt oRtRR.R3V3R lV 3R llltV3R lR	 ltV3R
 lR ltRtVt	V ;t
# )Lioni  a  The Lion optimizer [1].

Since updates are computed through the sign operation, they tend to
have larger norm than for other optimizers such as SGD and Adam.
We recommend a learning rate that is 3-10x smaller than AdamW and a
weight decay 3-10x larger than AdamW to maintain the strength
(lr * wd). Our Lion implementation follows the original paper. In
detail,

[1]: Chen, X. Symbolic Discovery of Optimization Algorithms. arXiv
preprint arXiv:2302.06675.

.. math::

    c_{t + 1} &= \beta_1 m_t + (1 - \beta_1) g_t \\
    m_{t + 1} &= \beta_2 m_t + (1 - \beta_2) g_t \\
    w_{t + 1} &= w_t - \eta (\text{sign}(c_t) + \lambda w_t)

Args:
    learning_rate (float or callable): The learning rate :math:`\eta`.
    betas (Tuple[float, float], optional): The coefficients
      :math:`(\beta_1, \beta_2)` used for computing the gradient
      momentum and update direction. Default: ``(0.9, 0.99)``
    weight_decay (float, optional): The weight decay :math:`\lambda`. Default: ``0.0``
r  r   r   c                   < V ^8  d   QhRS[ S[S[S[P                  .S[P                  3,          3,          RS[S[,          RS[/# )r!   ro   r	  r   r+  )r%   r&   s   "r   r'   Lion.__annotate__  sK     
) 
)UHbhhZ-A$BBC
) E{
) 	
)r)   c                `   < \         SV `  4        V P                  R V4       W n        W0n        R# rv   )r   r   r{   r	  r   )r   ro   r	  r   r   s   &&&&r   r   Lion.__init__  s+     	_m<
(r)   c                :   < V ^8  d   QhRS[ P                  RS[/# rP   rR   )r%   r&   s   "r   r'   r:    r   r)   c                8    \         P                  ! V4      VR&   R# )r   r  Nr   rV   s   &&&r   rI   Lion.init_single  r   r)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# ra   rR   )r%   r&   s   "r   r'   r:    s*     + +RXX +"(( +4 +r)   c                   V P                   P                  VP                  4      pV P                  w  rVV P                  pVR,          pWX,          ^V,
          V,          ,           p	Wh,          ^V,
          V,          ,           VR&   V^ 8  d   ^WG,          ,
          V,          pW$\
        P                  ! V	4      ,          ,
          # )zOPerforms the Lion parameter update and stores :math:`m`
in the optimizer state.r  )ro   r   r   r	  r   r   sign)
r   rb   rQ   rD   r   r  r  r   r  cs
   &&&&      r   r\   Lion.apply_single  s     &&x~~6((#JFa"f((Vq2v11c
!R..);I
?**r)   )r	  r   r   r   s   @@r   r8  r8    s9     : "4[!	
) 
). .+ + +r)   r8  c                   |   a a ] tR tRt oRtRV3R lV 3R llltV3R lR ltR tR tR	 t	V3R
 lR lt
RtVtV ;t# )	Adafactori  a  The Adafactor optimizer.

Our Adafactor implementation follows the original paper: `Adafactor:
Adaptive Learning Rates with Sublinear Memory Cost
<https://arxiv.org/abs/1804.04235>`_

Args:
    learning_rate (float or callable, optional): The learning rate.
        Default: ``None``.
    eps (tuple(float, float), optional): The first term :math:`\epsilon_1`
        added to the square of the gradients to improve numerical
        stability and the second term :math:`\epsilon_2` is used for
        parameter scaling if ``parameter_scale`` is set to ``True``.
        Default: ``(1e-30, 1e-3)``.
    clip_threshold (float, optional): Clips the unscaled update at
        ``clip_threshold``. Default: ``1.0``.
    decay_rate (float, optional): Coefficient for the running average
        of the squared gradient. Default: ``-0.8``.
    beta_1 (float, optional): If set to a value bigger than zero
        then first moment will be used. Default: ``None``.
    weight_decay (float, optional): The weight decay :math:`\lambda`.
        Default: ``0.0``.
    scale_parameter (bool, optional): If set to ``True`` the learning rate
        will be scaled by :math:`\max(\epsilon_1, \text{RMS}(w_{t-1}))`.
        Default: ``True``.
    relative_step (bool, optional): If set to ``True`` the ``learning_rate``
        will be ignored and relative step size will be computed.
        Default: ``True``.
    warmup_init (bool, optional): If set to ``True`` then the relative
        step size will be calculated by the current step. Default:
        ``False``.
c                   < V ^8  d   QhRS[ S[S[S[P                  .S[P                  3,          R3,          RS[S[S[3,          RS[RS[RS[S[,          RS[RS[R	S[R
S[/	# )r!   ro   Nr   clip_threshold
decay_ratebeta_1r   scale_parameterrelative_stepwarmup_init)r   rt   r   r   r   r   r   r   )r%   r&   s   "r   r'   Adafactor.__annotate__  s     ' 'UHbhhZ-A$BDHI' 5%< ' 	'
 ' ' ' ' ' 'r)   c
                   < \         S
V `  4        Ve   V P                  RV4       W n        W0n        W@n        WPn        W`n        Wpn        Wn	        Wn
        R # )Nro   )r   r   r{   r   rH  rI  rJ  r   rK  rL  rM  )r   ro   r   rH  rI  rJ  r   rK  rL  rM  r   s   &&&&&&&&&&r   r   Adafactor.__init__  sS     	$  -@,$(.*&r)   c                :   < V ^8  d   QhRS[ P                  RS[/# rP   rR   )r%   r&   s   "r   r'   rN    s     8 8RXX 8d 8r)   c                j   VP                   ^8  d`   VP                  pVP                  p\        P                  ! VRR VR7      VR&   \        P                  ! VRR VRR ,           VR7      VR&   M\        P
                  ! V4      VR&   V P                  e   \        P
                  ! V4      VR&   R# R# )	r   N)r   exp_avg_sq_rowexp_avg_sq_col
exp_avg_sqexp_avg)ndimshaper   r   zerosr   rJ  )r   rQ   rD   rZ  r   s   &&&  r   rI   Adafactor.init_single  s    >>QOOEOOE&(hhuSbz&GE"#&(hhuSbzE"#J/Fe&TE"#"$--	":E,;;"!}}Y7E) #r)   c                ~    \         P                  ! \         P                  ! \         P                  ! V4      4      4      # r5   )r   r   meanr   )r   inputss   &&r   _compute_rmsAdafactor._compute_rms  s#    wwrwwryy0122r)   c                   V P                   '       dJ   V P                  '       d
   R V,          MRp\        P                  ! V\        P                  ! V4      4      pMV P
                  pVP                  VP                  4      pRpV P                  '       d)   \        P                  ! V P                  ^,          V4      pWT,          # )r  r         ?)rL  rM  r   minimumr  ro   r   r   rK  r4  r   )r   r   parameter_rmsmin_steprelative_step_sizeparameter_scales   &&&   r   _compute_learning_rate Adafactor._compute_learning_rate  s    &*&6&6&6td{DH!#Hbhhtn!E!%!3!3/66}7J7JK jj!mDO33r)   c           	        \         P                  ! V\         P                  ! VRRR7      ,          4      p\         P                  ! V4      p\         P                  ! \         P                  ! VRR7      \         P                  ! V^ R7      4      # )r   T)axiskeepdimsrl  rW  )r   r  r^  matmulexpand_dims)r   rS  rT  r_factorc_factors   &&&  r   _approximate_exp_moving_avg%Adafactor._approximate_exp_moving_avg  sa    88RWW^"tLL
 88N+yyNN8"-r~~hQ/O
 	
r)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# ra   rR   )r%   r&   s   "r   r'   rN  $  s*     ," ,"RXX ,""(( ,"4 ,"r)   c                   VP                   ^8  pV P                  pV P                  RJpV P                  V4      pV P	                  WW4      pRWPP
                  ,          P                  VP                  4      ,
          p	\        P                  ! V4      V P                  ^ ,          ,           p
V'       d   VR,          pVR,          pW,          ^V	,
          \        P                  ! V
RR7      ,          ,           pW,          ^V	,
          \        P                  ! V
R	R7      ,          ,           pWR&   WR&   V P                  W4      p
W,          p
MGVR,          pW,          ^V	,
          V
,          ,           pWR&   \        P                  ! V4      V,          p
V
\        P                  ! RV P                  V
4      V P                  ,          4      ,          p
W,          p
V'       dB   VR,          pV P                  V,          ^V P                  ,
          V
,          ,           pWR&   Tp
V P                   ^ 8w  d"   W"V P                   ) V,          ,          ,          pW*,
          # )
z2Performs the Adafactor parameter and state update.Nrc  rS  rT  rn  rU  rV  rW  rX  )rY  r   rJ  r`  ri  rI  r   r   r   r   r   r^  rs  r  r4  rH  r   )r   rb   rQ   rD   factoredr   use_first_momentre  ro   beta_2r+   rS  rT  rU  rV  s   &&&&           r   r\   Adafactor.apply_single$  s   ==A%yy;;d2)))433DHoo-55m6I6IJJ8$txx{2"#34N"#34N$5VrwwvB77N %5VrwwvB77N '5"#&4"#55nUF&F|,J -1v:2GHJ",,XXj)H4F"**""6*T-@-@@
 
 'I&G{{W,!dkk/V1KLG&)F!t'8'8&8=&HIII!!r)   )rJ  rH  rI  r   rL  rK  rM  r   )	N)gKH9gMbP?rc  gNr   TTF)r}   r~   r   r   r   r   rI   r`  ri  rs  r\   r   r   r   r   s   @@r   rF  rF    s=     B' '08 834
," ," ,"r)   rF  c                   |   a a ] tR tRt oRtRV3R lV 3R llltV3R lR ltV3R lR ltV3R	 lR
 ltRt	Vt
V ;t# )MuoniS  a  The Muon optimizer.

Our Muon (MomentUm Orthogonalized by Newton-schulz) optimizer follows the
original implementation: `Muon: An optimizer for hidden layers in neural
networks <https://kellerjordan.github.io/posts/muon/>`_

Note:
    - Muon may be sub-optimal for the embedding layer, the final fully
      connected layer, or any 0D/1D parameters. Those should be optimized
      by a different method (e.g., :class:`AdamW`).
    - For 4D convolutional filters, it works by flattening their last
      dimensions.

Args:
    learning_rate (float or callable): The learning rate.
    momentum (float, optional): The momentum strength. Default: ``0.95``
    weight_decay (float, optional): The weight decay (L2 penalty).
        Default: ``0.01``
    nesterov (bool, optional): Enables Nesterov momentum. Recommended for
        better performance.  Default: ``True``
    ns_steps (int, optional): Number of Newton-Schulz iteration steps for
        orthogonalization.  Default: ``5``
c          
         < V ^8  d   QhRS[ S[S[S[P                  .S[P                  3,          3,          RS[RS[RS[RS[/# )r!   ro   r   r   r   ns_steps)r   rt   r   r   r   r   int)r%   r&   s   "r   r'   Muon.__annotate__l  s[     ! !UHbhhZ-A$BBC! ! 	!
 ! !r)   c                x   < \         SV `  4        V P                  R V4       W n        W0n        W@n        WPn        R# rv   )r   r   r{   r   r   r   r~  )r   ro   r   r   r   r~  r   s   &&&&&&r   r   Muon.__init__l  s5     	_m< (  r)   c                :   < V ^8  d   QhRS[ P                  RS[/# rP   rR   )r%   r&   s   "r   r'   r  |  r   r)   c                8    \         P                  ! V4      VR&   R# r   r   rV   s   &&&r   rI   Muon.init_single|  r   r)   c                    < V ^8  d   QhRS[ /# )r!   steps)r  )r%   r&   s   "r   r'   r    s      S r)   c           	         VP                   ^8X  g   Q RVP                   R24       hRR
RrTpVP                  R,          VP                  R,          8  pV'       d   VP                  pV\        P                  P                  VRR7      R,           ,          p\        V4       FU  pWP                  ,          p\        P                  ! WH,          WRVR	7      p	\        P                  ! W1,          WRRR	7      pKW  	  V'       d   VP                  pV# )r!   z;Expected a 2D array for Newton-Schulz iteration, got shape z	 instead.guV@gn@ @T)rm  gHz>rc  )betar   grX  rW  )rY  rZ  Tr   linalgnormr?   addmm)
r   Xr  abrC  transpose_neededr8   ABs
   &&&       r   _zeropower_via_newtonschulz5!Muon._zeropower_via_newtonschulz5  s    FFaK	\H	QZ[	\7Fa772;4AD1D89uACCA3a8A3c:A 
 Ar)   c                T   < V ^8  d   QhRS[ P                  RS[ P                  RS[/# ra   rR   )r%   r&   s   "r   r'   r    s*     ' 'RXX '"(( '4 'r)   c                |   V P                   ^ 8w  d   WP                   V,          ,           pV P                  VR,          ,          pV^V P                  ,
          V,          ,           pWCR&   V P                  '       d3   V^V P                  ,
          ,          W@P                  ,          ,           pMTpV P                  P	                  VP
                  4      pVP                  ^8  d   VP                  pVP                  ^8  pV'       d*   \        P                  ! WUP                  ^ ,          R34      pV P                  WPP                  R7      pV'       d   \        P                  ! WW4      pV\        ^VP                  R,          VP                  R,          ,          4      R,          ,          pW&V,          ,
          # )z"Performs the Muon parameter updater   )r  g      ?rW  rX  )r   r   r   ro   r   r   rY  rZ  r   reshaper  r~  max)	r   rb   rQ   rD   r   r+   r   original_shapereshape_neededs	   &&&&     r   r\   Muon.apply_single  s?    !"3"3i"??HMME#J&T]]"h..c
===T]]!23a--6GGFF&&x~~6;;!#\\N#[[1_NF\\!_b,AB66v]]6SFF;#ab)FLL,<<=DDB;&&r)   )r   r   r~  r   )gffffff?r   T   )r}   r~   r   r   r   r   rI   r  r\   r   r   r   r   s   @@r   r|  r|  S  s7     0! ! . . *' ' 'r)   r|  c                   a \        R V R4      p\        P                  ! V4      p\        P                  ! WR,           ,          R4      o\	        V3R lV 4      pWC3# )a  Clips the global norm of the gradients.

This function ensures that the global norm of the gradients does not exceed
``max_norm``. It scales down the gradients proportionally if their norm is
greater than ``max_norm``.

Example:
    >>> grads = {"w1": mx.array([2, 3]), "w2": mx.array([1])}
    >>> clipped_grads, total_norm = clip_grad_norm(grads, max_norm=2.0)
    >>> print(clipped_grads)
    {"w1": mx.array([...]), "w2": mx.array([...])}

Args:
    grads (dict): A dictionary containing the gradient arrays.
    max_norm (float): The maximum allowed global norm of the gradients.

Returns:
    (dict, float): The possibly rescaled gradients and the original
    gradient norm.
c                 J    WP                  4       P                  4       ,           # r5   )r   sum)accr   s   &&r   r9    clip_grad_norm.<locals>.<lambda>  s    cHHJNN4D.Dr)   r   r  rc  c                    < V S,          # r5   r6   )r   
normalizers   &r   r9   r    s	    q:~r)   )r   r   r   rd  r
   )gradsmax_normnorm_squared
total_normclipped_gradsr  s   &&   @r   clip_grad_normr    sP    * DeSQL&JHT(9:C@J5u=M$$r)   )typingr   r   r   r   r   mlx.corecorer   mlx.nnr   	mlx.utilsr	   r
   r   r   r   r   r   r   r   r   r   r  r  r)  r8  rF  r|  r  r6   r)   r   <module>r     s    : 9   U UP% P%fF,Y F,R@N) @NF5>i 5>p/>i />d@"y @"FA;9 A;H2
D 2
j8.T 8.v7+9 7+tL"	 L"^a'9 a'H%r)   