+
    &jN                     *   ^ RI t ^ RIHt ^ RIHtHtHt ^ RIHt	 ^ RI
Ht ^ RIHt ^ RIHt ^ RIHt ]R 4       tR	 tRR
 R lltR tR tR tR^RR/R R lltR^RR/R R llt ! R R]4      t ! R R]4      t ! R R]4      t ! R R]4      tR# )    N)	lru_cache)CallableOptionalUnion)Module)Linear)QuantizedLinear)tree_map_with_pathc                    a  S P                  4       ^8X  d   R # \        P                  R 4       pVP                  V 3R l4       pV# )   c                     V # N xs   &q/Users/jameslopez/projects/CWCArchive/cwc-podcast/.venv/lib/python3.14/site-packages/mlx/nn/layers/distributed.py<lambda>sum_gradients.<locals>.<lambda>   s        c                     V # r   r   r   s   &r   fsum_gradients.<locals>.f   s    r   c                 F   < \         P                  P                  VSR 7      # )group)mxdistributedall_sum)r   dx_r   s   &&&r   r   r      s    ~~%%b%66r   )sizer   custom_functionvjp)r   r   s   f r   sum_gradientsr$      sN    zz|q  UU7 7 Hr   c                8   \        V\        4      '       g   \        V^ ,          \        4      '       d   \        P                  ! WVR7      # V P                  V,          pV Uu. uF  p\        WC,          4      NK  	  pp\        P                  ! WVR7      # u upi )z:Equivalent to mx.split but allows for fractional segments.axis)
isinstanceintr   splitshape)weightsegmentsr'   Nsindicess   &&&   r   _splitr1      sn    (C  Jx{C$@$@xxt44TA#+,8as15z8G,88F$// -s   #Bc                z    V ^8  d   QhR\         R\        R\        \        P                  P
                  ,          /# )   
parameterssharding_predicater   )dictr   r   r   r   Group)formats   "r   __annotate__r9   (   s5     )5 )5)5 )5 BNN(())5r   c                   aaa T;'       g    \         P                  P                  4       pVP                  4       oVP	                  4       oVVV3R lp\        W04      # )zReturns a new parameter tree with the weights sharded according to the
sharding_predicate.

The sharding predicate should return the sharding axis and optionally also
the segments that comprise the weight.
c                   < \        V\        P                  4      '       g   V# S! W4      pVf   V# R p^p\        V\        4      '       d   TpM&\        V\        4      '       d   Vw  r4M\        R4      h\        P                  ! \        P                  ! \        WV4       Uu. uF  p\        VSV4      S,          NK  	  upVR7      4      # u upi )Nz;The sharding function should return int or tuple[int, list]r&   )	r(   r   arrayr)   tuple
ValueError
contiguousconcatenater1   )	pathr,   r/   r'   r-   partr.   rr5   s	   &&    r   	_shard_fn_shard.<locals>._shard_fn7   s    &"((++Mt,9MaD5!!ND(M  }}NN6<Vt6TU6Tda&q))6TU
 	
Us   #C)r   r   initr!   rankr
   )r4   r5   r   rD   r.   rC   s   &f& @@r   _shardrH   (   sG     **R^^((*E

A

A
4 i44r   c                   a  V 3R lpV# )ztSimple predicate to shard fully connected layers such that a common
representation becomes a sharded representation.c                 x   < V P                  R 4      '       d   RS3# \        VP                  ^,
          ^ 4      S3# )bias)endswithmaxndimrA   r,   r-   s   &&r   rD   "_all_to_sharded.<locals>._shard_fnX   s6    ==  x<6;;?A&00r   r   r-   rD   s   f r   _all_to_shardedrS   T   s    1
 r   c                   a  V 3R lpV# )ztSimple predicate to shard fully connected layers such that a sharded
representation becomes a common representation.c                 >   < V P                  R 4      '       d   R# RS3# )rK   NrL   )rM   rP   s   &&r   rD   "_sharded_to_all.<locals>._shard_fnd   s    ==  8|r   r   rR   s   f r   _sharded_to_allrW   `   s    
 r   c                 4    V R9  d   \        RV : R24      hR# )all-to-shardedzSharding type sharding=zB not supported, choose one of 'all-to-sharded' or 'sharded-to-all'N)rY   sharded-to-all)r>   )shardings   &r   _check_shardingr\   l   s0    ;;* ,E E
 	
 <r   r-   r   c          	          V ^8  d   QhR\         R\        \        \        3,          R\        \        \
        3,          R\        \        P                  P                  ,          /# r3   moduler[   r-   r   )
r   r   strr   r)   listr   r   r   r7   )r8   s   "r   r9   r9   v   sW     %@ %@%@CM"%@ CI	%@
 BNN(()%@r   c                   \        V\        4      '       d)   \        V4       VR8X  d   \        V4      M
\	        V4      pV P                  \        V P                  4       W4      4       R# )a  Shard a module in-place by updating its parameter dictionary with the
sharded parameter dictionary.

The ``sharding`` argument can be any callable that given the path and the
weight returns the sharding axis and optionally also the segments that
comprise the unsharded weight. For instance if the weight is a fused QKV
matrix the segments should be 3.

.. note::
    The module doesn't change so in order for distributed communication to
    happen the module needs to natively support it and for it to be enabled.

Args:
    module (mlx.nn.Module): The parameters of this module will be sharded
        in-place.
    sharding (str or callable): One of "all-to-sharded" and
        "sharded-to-all" or a callable that returns the sharding axis and
        segments.
    segments (int or list): The segments to use if ``sharding`` is a
        string. Default: ``1``.
    group (mlx.core.distributed.Group): The distributed group to shard
        across. If not set, the global group will be used. Default: ``None``.
rY   N)r(   r`   r\   rS   rW   updaterH   r4   )r_   r[   r-   r   s   &&$$r   shard_inplacerd   v   sY    < (C  ! ++ H% * 	
 MM&**,h>?r   c          	          V ^8  d   QhR\         R\        R\        \        \        3,          R\
        \        P                  P                  ,          /# r^   )	r   r`   r   r)   ra   r   r   r   r7   )r8   s   "r   r9   r9      sH           CI	 
 BNN(() r   c                   \        V4       R\        P                  R\        P                  R\
        P                  R\        P                  /pWA\        V \        4      3,          ! WVR7      # )a  Create a new linear layer that has its parameters sharded and also
performs distributed communication either in the forward or backward
pass.

.. note::
    Contrary to ``shard_inplace``, the original layer is not changed but a
    new layer is returned.

Args:
    module (mlx.nn.Module): The linear layer to be sharded.
    sharding (str): One of "all-to-sharded" and
        "sharded-to-all" that defines the type of sharding to perform.
    segments (int or list): The segments to use. Default: ``1``.
    group (mlx.core.distributed.Group): The distributed group to shard
        across. If not set, the global group will be used. Default: ``None``.
)r-   r   )rY   T)rY   F)rZ   T)rZ   F)	r\   AllToShardedLinearfrom_linearQuantizedAllToShardedLinearfrom_quantized_linearShardedToAllLinearQuantizedShardedToAllLinearr(   r   )r_   r[   r-   r   fnss   &&$$ r   shard_linearrn      sf    . H "4"@"@!#>#T#T "4"@"@!#>#T#T	C FF334 r   c                      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	^R
R/V3R lR ll4       t	Rt
VtV ;t# )rg   a]  Each member of the group applies part of the affine transformation such
that the result is sharded across the group.

The gradients are automatically aggregated from each member of the group.

Args:
    input_dims (int): The dimensionality of the input features
    output_dims (int): The dimensionality of the output features
    bias (bool, optional): If set to ``False`` the the layer will not use a
        bias. Default is ``True``.
    group (mx.distributed.Group, optional): The sharding will happen across
        this group. If not set then the global group is used. Default is
        ``None``.
Nc          	      j   < V ^8  d   QhRS[ RS[ RS[RS[S[P                  P
                  ,          /# r3   
input_dimsoutput_dimsrK   r   r)   boolr   r   r   r7   )r8   __classdict__s   "r   r9   AllToShardedLinear.__annotate__   B        	
 ,,-r   c                  < \         SV `  4        \        P                  ! R V,          4      pT;'       g    \        P
                  P                  4       V n        V P                  P                  4       pW&,          ^ 8w  d   \        RV RV R24      h\        P                  P                  V) VW&,          V3R7      V n        V'       d2   \        P                  P                  V) VW&,          3R7      V n        R# R# )      ? Cannot shard the output of size  across 	 devices.lowhighr+   Nsuper__init__mathsqrtr   r   rF   r   r!   r>   randomuniformr,   rK   selfrr   rs   rK   r   scaler.   	__class__s   &&&&&  r   r   AllToShardedLinear.__init__   s     	 		#
*+33bnn113
JJOOO!2;-xs)T  ii''#Z0 ( 

 		))F"') * DI r   c                    < V ^8  d   QhRS[ /# r3   returnr`   )r8   rv   s   "r   r9   rw           V VS Vr   c                    V P                   P                  w  rV P                  P                  4       pW,          pR V RV RRV 9    2# input_dims=, output_dims=, bias=rK   )r,   r+   r   r!   )r   out_dimsin_dimsr.   s   &   r   _extra_reprAllToShardedLinear._extra_repr   sI     KK--JJOOWI^H:WVt^DTUUr   c                N   < V ^8  d   QhRS[ P                  RS[ P                  /# r3   r   r   r   r<   )r8   rv   s   "r   r9   rw      s#     	 	"(( 	rxx 	r   c                    \        V P                  4      ! V4      pR V 9   d2   \        P                  ! V R ,          WR,          P                  4      pV# WR,          P                  ,          pV# )rK   r,   )r$   r   r   addmmTr   r   s   &&r   __call__AllToShardedLinear.__call__   s\    $**%a( T>fqx.*:*:;A  N$$$Ar   r-   r   c                z   < V ^8  d   QhRS[ RS[S[S[3,          RS[S[P                  P                  ,          /# r3   linear_layerr-   r   r   r   r)   ra   r   r   r   r7   )r8   rv   s   "r   r9   rw     A       T	"	
 ,,-r   c                  T;'       g    \         P                  P                  4       pVP                  P                  w  rEV ! WT\        VR 4      V4      pVP                  \        VP                  4       \        V4      V4      4       V# rK   )
r   r   rF   r,   r+   hasattrrc   rH   r4   rS   clsr   r-   r   rs   rr   sls   &&$$   r   rh   AllToShardedLinear.from_linear  o     ..,,."."5"5";";',*GO
		&002OH4MuUV	r   rK   r   r,   TN__name__
__module____qualname____firstlineno____doc__r   r   r   classmethodrh   __static_attributes____classdictcell____classcell__r   rv   s   @@r   rg   rg      s\      >V V	 	  &'	
 15   r   rg   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]R
^RR/V3R lR ll4       t	Rt
VtV ;t# )rk   i  a  Each member of the group applies part of the affine transformation and
then aggregates the results.

All nodes will have the same exact result after this layer.

:class:`ShardedToAllLinear` provides a classmethod :meth:`from_linear` to
convert linear layers to sharded :obj:`ShardedToAllLinear` layers.

Args:
    input_dims (int): The dimensionality of the input features
    output_dims (int): The dimensionality of the output features
    bias (bool, optional): If set to ``False`` the the layer will not use a
        bias. Default is ``True``.
    group (mx.distributed.Group, optional): The sharding will happen across
        this group. If not set then the global group is used. Default is
        ``None``.
Nc          	      j   < V ^8  d   QhRS[ RS[ RS[RS[S[P                  P
                  ,          /# rq   rt   )r8   rv   s   "r   r9   ShardedToAllLinear.__annotate__%  rx   r   c                  < \         SV `  4        \        P                  ! R V,          4      pT;'       g    \        P
                  P                  4       V n        V P                  P                  4       pW,          ^ 8w  d   \        RV RV R24      h\        P                  P                  V) VW!V,          3R7      V n        V'       d,   \        P                  P                  V) VV3R7      V n        R# R# )rz   The input of size  cannot be sharded across r}   r~   Nr   r   s   &&&&&  r   r   ShardedToAllLinear.__init__%  s     	 		#
*+33bnn113
JJOONq $ZL0J1#YW  ii''a0 ( 

 		))F"n * DI r   c                    < V ^8  d   QhRS[ /# r   r   )r8   rv   s   "r   r9   r   D  r   r   c                    V P                   P                  4       pV P                  P                  w  r#W1,          pR V RV RRV 9    2# r   )r   r!   r,   r+   )r   r.   r   r   s   &   r   r   ShardedToAllLinear._extra_reprD  sI    JJOO KK--WI^H:WVt^DTUUr   c                N   < V ^8  d   QhRS[ P                  RS[ P                  /# r   r   )r8   rv   s   "r   r9   r   J  s#      "(( rxx r   c                    WR ,          P                   ,          p\        P                  P                  WP                  R7      pRV 9   d   WR,          ,           pV# )r,   r   rK   )r   r   r   r   r   r   s   &&r   r   ShardedToAllLinear.__call__J  sG    X   NN""1JJ"7T>L Ar   r-   r   c                z   < V ^8  d   QhRS[ RS[S[S[3,          RS[S[P                  P                  ,          /# r   r   )r8   rv   s   "r   r9   r   U  r   r   c                  T;'       g    \         P                  P                  4       pVP                  P                  w  rEV ! WT\        VR 4      V4      pVP                  \        VP                  4       \        V4      V4      4       V# r   )
r   r   rF   r,   r+   r   rc   rH   r4   rW   r   s   &&$$   r   rh   ShardedToAllLinear.from_linearT  r   r   r   r   r   r   s   @@r   rk   rk     s\     $ >V V   &'	
 15   r   rk   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tV3R lR ltV3R	 lR
 lt]	R^RR/V3R lR ll4       t
RtVtV ;t# )ri   ie  aq  Each member of the group applies part of the affine transformation with
a quantized matrix such that the result is sharded across the group.

It is the quantized equivalent of :class:`mlx.nn.AllToShardedLinear`.
Similar to :class:`mlx.nn.QuantizedLinear` its parameters are frozen and
will not be included in any gradient computation.

Args:
    input_dims (int): The dimensionality of the input features.
    output_dims (int): The dimensionality of the output features.
    bias (bool, optional): If set to ``False`` then the layer will not use
        a bias. Default: ``True``.
    group_size (int, optional): The group size to use for the quantized
        weight. See :func:`~mlx.core.quantize`. Default: ``64``.
    bits (int, optional): The bit width to use for the quantized weight.
        See :func:`~mlx.core.quantize`. Default: ``4``.
    mode (str, optional): The quantization method to use (see
        :func:`~mlx.core.quantize`). Default: ``"affine"``.
    group (mx.distributed.Group, optional): The sharding will happen across
        this group. If not set then the global group is used. Default is
        ``None``.
Nc                |   < V ^8  d   QhRS[ RS[ RS[RS[ RS[ RS[RS[S[P
                  P                  ,          /# r3   rr   rs   rK   
group_sizebitsmoder   r)   ru   r`   r   r   r   r7   )r8   rv   s   "r   r9   (QuantizedAllToShardedLinear.__annotate__}  `     * ** * 	*
 * * * ,,-*r   c                  < \         SV `  4        W@n        WPn        W`n        \
        P                  ! R V,          4      pT;'       g    \        P                  P                  4       V n
        V P                  P                  4       p	W),          ^ 8w  d   \        RV RV	 R24      h\        P                  P                  V) VW),          V3R7      p
\        P                  ! WWVR7      vV n        V n        pV'       d
   V^ ,          MRV n        V'       d#   \        P&                  ! W),          34      V n        V P+                  4        R# )rz   r{   r|   r}   r~   r   Nr   r   r   r   r   r   r   r   r   rF   r   r!   r>   r   r   quantizer,   scalesbiaseszerosrK   freezer   rr   rs   rK   r   r   r   r   r   r.   r,   r   r   s   &&&&&&&&    r   r   $QuantizedAllToShardedLinear.__init__}  s    	 %		 		#
*+33bnn113
JJOOO!2;-xs)T  ""#Z0 # 

 -/KK-
)T[6 $*fQit +"2!45DI 	r   c                L   < \         SV `  ! V/ VB  V P                  RR7       R# zdWrap unfreeze so that we unfreeze any layers we might contain but
our parameters will remain frozen.F)recurseNr   unfreezer   r   argskwargsr   s   &*,r   r   $QuantizedAllToShardedLinear.unfreeze  %     	$)&)E"r   c                    < V ^8  d   QhRS[ /# r   r   )r8   rv   s   "r   r9   r     s     
 
S 
r   c                   V P                   P                  w  rV^ ,          V P                  ,          pWP                  P	                  4       ,          pRV RV RRV 9    RV P
                   RV P                   RV P                   2#     r   r   r   rK   z, group_size=z, bits=z, mode=r,   r+   r   r   r!   r   r   r   r   r   s   &  r   r   'QuantizedAllToShardedLinear._extra_repr  s     KK--R<DII-JJOO%%'.
'&D.AQ R//*'$))GDII;P	
r   c                N   < V ^8  d   QhRS[ P                  RS[ P                  /# r   r   )r8   rv   s   "r   r9   r     s#      "(( rxx r   c                   \        V P                  4      ! V4      p\        P                  ! VV R ,          V R,          V P	                  R4      RV P
                  V P                  V P                  R7      pRV 9   d   WR,          ,           pV# )r,   r   r   Tr   r   	transposer   r   r   rK   )r$   r   r   quantized_matmulgetr   r   r   r   s   &&r   r   $QuantizedAllToShardedLinear.__call__  st    $**%a(N>88H%	
 T>L Ar   r-   r   c                z   < V ^8  d   QhRS[ RS[S[S[3,          RS[S[P                  P                  ,          /# r3   quantized_linear_layerr-   r   r   )r8   rv   s   "r   r9   r     A       & T	"	
 ,,-r   c                  T;'       g    \         P                  P                  4       pVP                  P                  w  rEV^ ,          VP
                  ,          pV ! VV\        VR4      VP                  VP
                  \        VRR4      VR7      pVP                  \        VP                  4       \        V4      V4      4       V# r   rK   r   affine)r   r   r   r   )r   r   rF   r,   r+   r   r   r   getattrrc   rH   r4   rS   r   r   r-   r   rs   rr   r   s   &&$$   r   rj   1QuantizedAllToShardedLinear.from_quantized_linear       ..,,."8"?"?"E"E 2o*@*E*EE
*F3-88',,/B
 			&113)	
 	r   rK   r   r   r   r   r   r   r,   T@      r   Nr   r   r   r   r   r   r   r   r   r   rj   r   r   r   r   s   @@r   ri   ri   e  s`     .* *X#
 
 $  &'	
 15   r   ri   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tV3R lR ltV3R	 lR
 lt]	R^RR/V3R lR ll4       t
RtVtV ;t# )rl   i  a  Each member of the group applies part of the affine transformation using
the quantized matrix and then aggregates the results.

All nodes will have the same exact result after this layer.

It is the quantized equivalent of :class:`mlx.nn.ShardedToAllLinear`.
Similar to :class:`mlx.nn.QuantizedLinear` its parameters are frozen and
will not be included in any gradient computation.

Args:
    input_dims (int): The dimensionality of the input features.
    output_dims (int): The dimensionality of the output features.
    bias (bool, optional): If set to ``False`` then the layer will not use
        a bias. Default: ``True``.
    group_size (int, optional): The group size to use for the quantized
        weight. See :func:`~mlx.core.quantize`. Default: ``64``.
    bits (int, optional): The bit width to use for the quantized weight.
        See :func:`~mlx.core.quantize`. Default: ``4``.
    mode (str, optional): The quantization method to use (see
        :func:`~mlx.core.quantize`). Default: ``"affine"``.
    group (mx.distributed.Group, optional): The sharding will happen across
        this group. If not set then the global group is used. Default is
        ``None``.
Nc                |   < V ^8  d   QhRS[ RS[ RS[RS[ RS[ RS[RS[S[P
                  P                  ,          /# r   r   )r8   rv   s   "r   r9   (QuantizedShardedToAllLinear.__annotate__  r   r   c                  < \         SV `  4        W@n        WPn        W`n        \
        P                  ! R V,          4      pT;'       g    \        P                  P                  4       V n
        V P                  P                  4       p	W,          ^ 8w  d   \        RV RV	 R24      h\        P                  P                  V) VW!V	,          3R7      p
\        P                  ! WWVR7      vV n        V n        pV'       d
   V^ ,          MRV n        V'       d   \        P&                  ! V34      V n        V P+                  4        R# )rz   r   r   r}   r~   r   Nr   r   s   &&&&&&&&    r   r   $QuantizedShardedToAllLinear.__init__  s    	 %		 		#
*+33bnn113
JJOONq $ZL0J1#YW  ""a0 # 

 -/KK-
)T[6 $*fQit +0DI 	r   c                L   < \         SV `  ! V/ VB  V P                  RR7       R# r   r   r   s   &*,r   r   $QuantizedShardedToAllLinear.unfreeze0  r   r   c                    < V ^8  d   QhRS[ /# r   r   )r8   rv   s   "r   r9   r  6  s     
 
S 
r   c                   V P                   P                  w  rV^ ,          V P                  ,          V P                  P	                  4       ,          pRV RV RRV 9    RV P
                   RV P                   RV P                   2# r   r   r   s   &  r   r   'QuantizedShardedToAllLinear._extra_repr6  s}     KK--R<DII-

0AA'.
'&D.AQ R//*'$))GDII;P	
r   c                N   < V ^8  d   QhRS[ P                  RS[ P                  /# r   r   )r8   rv   s   "r   r9   r  >  s#      "(( rxx r   c                8   \         P                  ! VV R ,          V R,          V P                  R4      RV P                  V P                  V P
                  R7      p\         P                  P                  WP                  R7      pRV 9   d   WR,          ,           pV# )r,   r   r   Tr   r   rK   )	r   r   r   r   r   r   r   r   r   r   s   &&r   r   $QuantizedShardedToAllLinear.__call__>  s|    N>88H%	
 NN""1JJ"7T>L Ar   r-   r   c                z   < V ^8  d   QhRS[ RS[S[S[3,          RS[S[P                  P                  ,          /# r   r   )r8   rv   s   "r   r9   r  O  r   r   c                  T;'       g    \         P                  P                  4       pVP                  P                  w  rEV^ ,          VP
                  ,          pV ! VV\        VR4      VP                  VP
                  \        VRR4      VR7      pVP                  \        VP                  4       \        V4      V4      4       V# r   )r   r   rF   r,   r+   r   r   r   r   rc   rH   r4   rW   r  s   &&$$   r   rj   1QuantizedShardedToAllLinear.from_quantized_linearN  r  r   r  r  r  r   s   @@r   rl   rl     s`     2* *X#
 
    &'	
 15   r   rl   r   )r   	functoolsr   typingr   r   r   mlx.corecorer   mlx.nn.layers.baser   mlx.nn.layers.linearr   mlx.nn.layers.quantizedr	   	mlx.utilsr
   r$   r1   rH   rS   rW   r\   rd   rn   rg   rk   ri   rl   r   r   r   <module>r!     s      , ,  % ' 3 (  0)5X		
%@ "#	%@
 -1%@P  "#	 
 -1 FN NbP PfB& BJA& Ar   