+
    _\i                         ^ RI HtHt ^ RIHtHtHt ^ RIHt	 ^RI
HtHtHt ^RIHt R R ltRR R	 lltRR
 R lltR# )    )reducewraps)AnyCallableOptionalN)tree_flattentree_maptree_unflatten)Modulec                0    V ^8  d   QhR\         R\        /# )   modelfn)r   r   )formats   "d/Users/agent/.cache/uv/archive-v0/6ZL4-8mCcRNgGE9wi6M6J/lib/python3.14/site-packages/mlx/nn/utils.py__annotate__r      s     ! !& !h !    c                p   a aa VV 3R lp\         P                  ! V4      o\        S4      V V3R l4       pV# )a  Transform the passed function ``fn`` to a function that computes the
gradients of ``fn`` wrt the model's trainable parameters and also its
value.

Args:
    model (mlx.nn.Module): The model whose trainable parameters to compute
                           gradients for
    fn (Callable): The scalar function to compute gradients for

Returns:
    A callable that returns the value of ``fn`` and the gradients wrt the
    trainable parameters of ``model``
c                 6   < SP                  V 4       S! V/ VB # Nupdate)paramsargskwargsr   r   s   &*,r   inner_fn value_and_grad.<locals>.inner_fn   s    V4"6""r   c                  B   < S! SP                  4       .V O5/ VB w  r#W#3# r   trainable_parameters)r   r   valuegradr   value_grad_fns   *,  r   wrapped_value_grad_fn-value_and_grad.<locals>.wrapped_value_grad_fn!   s*    #E$>$>$@R4R6R{r   )mxvalue_and_gradr   )r   r   r   r$   r#   s   ff  @r   r'   r'      s8    # %%h/M
2Y  ! r   c                F    V ^8  d   QhR\         R\        \        ,          /# )r   moduler   )r   r   r   )r   s   "r   r   r   )   s     # #v #8H#5 #r   c                |   a aa Sf   S oVV 3R lp\         P                  ! V4      o\        S4      VV 3R l4       pV# )a$  Transform the passed callable to one that performs gradient
checkpointing with respect to the trainable parameters of the module (and
the callable's inputs).

Args:
    module (mlx.nn.Module): The module for whose parameters we will be
        performing gradient checkpointing.
    fn (Callable, optional): The function to checkpoint. If not provided it
        defaults to the provided module.

Returns:
    A callable that saves the inputs and outputs during the forward pass
    and recomputes all intermediate states during the backward pass.
c                 6   < SP                  V 4       S! V/ VB # r   r   )r   r   r   r   r)   s   &*,r   r   checkpoint.<locals>.inner_fn=   s    f4"6""r   c                  8   < S! SP                  4       .V O5/ VB # r   r   )r   r   checkpointed_fnr)   s   *,r   wrapped_checkpointed_fn+checkpoint.<locals>.wrapped_checkpointed_fnC   s!    v::<NtNvNNr   )r&   
checkpointr   )r)   r   r   r/   r.   s   ff  @r   r1   r1   )   sF     
z # mmH-O
2YO O #"r   c                    V ^8  d   QhR\         R\        \        P                  P                  ,          R\
        R\        \        P                  ,          R\        \        P                  ,          /# )r   	gradientsgroupall_reduce_sizecommunication_typecommunication_stream)r   r   r&   distributedGroupintDtypeStream)r   s   "r   r   r   J   sb     [. [.[.BNN(()[. [. !*	[.
 #299-[.r   c           	     n  aaaaaaaa T;'       g    \         P                  P                  4       pVP                  4       oS^8X  d   V # VVV3R lpV^ 8:  d   \	        WP4      # \        V 4      p\        V4      ^ 8X  d   V # V UUu. uF  w  rxVNK	  	  uppoV UU	u. uF  w  rV	P                  NK  	  up	poV UU	u. uF  w  rV	P                  NK  	  up	poV UU	u. uF  w  rV	P                  NK  	  up	po\        ;QJ d    V3R lS 4       F  '       d   K   RM	  RM! V3R lS 4       4      '       g   \        W^ S4      # Se   SP                  MS^ ,          P                  p
. p. p^ p\        \        S4      4       FH  pVP                  V4       VSV,          V
,          ,          pW8  g   K3  VP                  V4       . p^ pKJ  	  V'       d   VP                  V4       . p. pV F  p\        V3R lV^ .4      p\         P                  ! V Uu. uF!  qV,          ^,          P                  R4      NK#  	  up4      oV! S4      o\         P                   ! SV^R 4      oVP#                  VVV3R l\%        V4       4       4       K  	  \'        V4      # u uppi u up	pi u up	pi u up	pi u upi )a  Average the gradients across the distributed processes in the passed group.

This helper enables concatenating several gradients of small arrays to one
big all reduce call for better networking performance.

Args:
    gradients (Any): The Python tree containing the gradients (it should
        have the same structure across processes)
    group (Optional[mlx.core.distributed.Group]): The group of processes to
        average the gradients. If set to ``None`` the global group is used.
        Default: ``None``.
    all_reduce_size (int): Group arrays until their size in bytes exceeds
        this number. Perform one communication step per group of arrays. If
        less or equal to 0 array grouping is disabled. Default: ``32MiB``.
    communication_type (Optional[mlx.core.Dtype]): If provided cast to this
        type before performing the communication. Typically cast to a
        smaller float to reduce the communication size. Default: ``None``.
    communication_stream (Optional[mlx.core.Stream]): The stream to usse
        for the communication. If unspecified the default communication
        stream is used which can vary by back-end. Default: ``None``.
c                    < V P                   pSe   V P                  S4      MT p \        P                  P	                  V SR7      P                  V4      S,          # )N)stream)dtypeastyper&   r8   all_sum)xdtNr7   r6   s   & r   _average#average_gradients.<locals>._averagel   sO    WW,>,JAHH'(PQ~~%%a0D%ELLRPSTTTr   c              3   :   <"   T F  qS^ ,          8H  x  K  	  R# 5i)r   N ).0rD   dtypess   & r   	<genexpr>$average_gradients.<locals>.<genexpr>   s     4Vr?Vs   FTc                 @   < W R,          SV,          ,           .,           # )   rI   )rC   ysizess   &&r   <lambda>#average_gradients.<locals>.<lambda>   s    !uuQx/?.@*@r   c              3   x   <"   T F/  w  rSV,          SV,          P                  SV,          4      3x  K1  	  R # 5ir   )reshape)rJ   ijbig_gradkeysshapess   &  r   rL   rM      s6      "1DA a(1+--fQi891s   7:rP   )r&   r8   initsizer	   r   lenshaper@   allaverage_gradientsrangeappendr   concatenaterV   splitextend	enumerater
   )r3   r4   r5   r6   r7   rF   
flat_gradsk_vitemsizegrad_groups
grad_groupgrad_group_sizerW   new_flat_gradsindicesrE   rY   rK   rZ   r[   rR   s   &&&ff            @@@@@@r   ra   ra   J   s_   8 **R^^((*E

AAvU
 !,, "),
z?a ))jdaj)&01jda!''j1$./JDAJ/&01jda!''j1 s4V4sss4V444$Yq:LMM "- ## 	 
s4y!Aa uQx(22O1"":.
"# " z*J %J@*qcRG~~7ABz!Aq!))"-zBH  )Hxx'!B-8H!! "%j1"  & n--W *1/1> Cs   JJ <J&J,'J2
r   )Ni   NN)	functoolsr   r   typingr   r   r   mlx.corecorer&   utilsr   r	   r
   layers.baser   r'   r1   ra   rI   r   r   <module>rx      s3    $ * *  : : !:#B[. [.r   