
    eTh                     z   S SK Jr  S SKrS SKJrJr  S SKJrJrJ	r	J
r
  S SKrS SKJr  SSKJrJr  \R                   /r\R$                  " \5      r\R*                  R-                  5       r\" S5      (       a  \(       a  S S	KJrJrJrJr  S(S
 jrS)S jr\R>                  \R@                  \RB                  \RD                  \RF                  \RH                  \RJ                  \RL                  \RN                  \RP                  \RR                  S.r*S r+ S*         S+S jjr,S r-   S,   S-S jjr. " S S5      r/ " S S\/5      r0 " S S\/5      r1 " S S\/5      r2 " S S\25      r3 " S S\/5      r4 " S S\45      r5 " S S \/5      r61 S!kr7\S.S" j5       r8        S/S# jr9      S0S$ jr:S% r;S& r<S1S' jr=g)2    )annotationsN)	lru_cachepartial)ListOptionalTupleUnion)nn   )is_torch_greater_or_equalloggingz2.5)DTensor	Placement	ReplicateShardc                    [        U[        5      (       a9  [        U5      nX-  S:X  d   SU  SU 35       eX-  nU Vs/ s H  oCU-  PM	     sn$ X-  S:X  d
   SU 35       eX-  nU/U-  $ s  snf )a  
Convert block count or proportions to block sizes.

This function accepts

- The number of blocks (int), in which case the block size is
  total_size//blocks; or
- A list of block sizes (List[int]).

In the second case, if sum(blocks) < total_size, the ratios between
the block sizes will be preserved. For instance, if blocks is
[2, 1, 1] and total_size is 1024, the returned block sizes are
[512, 256, 256].
r   zCannot split z in proportional blocks: zPrepacked is not divisible by )
isinstancelistsum)
total_sizeblockstotal_blocks	part_sizeblocksingle_sizes         a/var/www/auris/envauris/lib/python3.13/site-packages/transformers/integrations/tensor_parallel.py_blocks_to_block_sizesr   &   s     &$6{(A-lzlJcdjck/ll-.	/56veE!v66"a'R+I&)RR' *}v%%	 7s   A+c                    [         R                  " SSU 5      nX!;   a  X   $ SU;   a0  UR                  SS5      S   U;   a  XR                  SS5      S      $ g)z
Get the TP style for a parameter from the TP plan.

The TP plan is a dictionary that maps parameter names to TP styles.
The parameter name can be a generic name with wildcards (e.g. "*.weight") or a specific name (e.g. "layer_1.weight").
\d+*.   r   N)resubrsplit)parameter_nametp_plangeneric_param_names      r   _get_parameter_tp_planr)   @   sg     ^<$**	"	"'9'@'@a'H'Kw'V00a8;<<    )BOOLU8I8I16F16BF16I32F32F64I64F8_E4M3c                   U nUR                   U   nUR                  5       n[        USS9n/ n	Sn
U H*  nX-  nX<-  nUS-   U-  nU	[        X-   X-   5      -  n	X-  n
M,     UR	                  5       nUS:X  a"  US   R                  [        R                  5      nUS:X  a  XYS4   nO:US:X  d  US:X  a  USS2U	S4   nO#US:X  d  US	:X  a  USU	4   nO[        S
U S35      eUR                  [        U   5      $ )u  
When weights are packed (gate_up_proj), we need to make sure each shard gets its correct share.
So if you have: gate_proj       ( 16, 5120, 8190)
and             up_proj         ( 16, 5120, 8190)
packed as       gate_up_proj    ( 16, 5120, 2 * 8190)
And you shard along the last dimension, you need to interleave the gate and up values:

Now, if we shard along the last dimension across TP_size (Tensor Parallelism size), we must interleave the values from gate and up projections correctly.

Let's take TP_size = 4 for an example:

Packed tensor `gate_up_proj`
---------------------------------------------------------------
[ G0  G1  G2  G3 | G4  G5  G6  G7 | ... | U0  U1  U2  U3 | U4  U5  U6  U7 | ... ]
 ↑─────────────↑   ↑─────────────↑        ↑─────────────↑  ↑─────────────↑
   Gate Slice 0      Gate Slice 1            Up Slice 0       Up Slice 1

Explanation:
- The first half of the tensor (left of the center) holds the gate_proj values.
- The second half (right of the center) holds the up_proj values.
- For TP=4, we divide each half into 4 slices. In this example, we show two slices for brevity.
- Each shard receives one slice from the gate part and the corresponding slice from the up part.

For instance:
• Shard 0 gets: [ Gate Slice 0, Up Slice 0 ] = [ G0, G1, G2, G3, U0, U1, U2, U3 ]
• Shard 1 gets: [ Gate Slice 1, Up Slice 1 ] = [ G4, G5, G6, G7, U4, U5, U6, U7 ]
• … and so on.

This ensures that each shard receives an equal portion of both gate and up projections, maintaining consistency across tensor parallelism.
r   )r   r   r   r"   r5   .NUnsupported dim ", only dim 0, 1 or 2 are supported)
shapesizer   range	get_dtypetotorchfloat16
ValueErrorstr_to_torch_dtype)paramempty_paramdevice_meshrankdimslice_r   
world_sizeblock_sizestensors_slicesblock_offset
block_sizeshard_block_sizestartstopslice_dtypetensors                    r   get_packed_weightsrT   _   s/   > F""3'J!!#J(JqIKNL!
%3'q,,% 4l6IJJ" " ""$K i.
ax+,	SBY>3./	SBY^+,+C50RSTT99'455r*   c                   US:w  a  [        S5      eUS:  a  UOXR                  -   nU R                  U   nXS-  nXb-  nU R                  SU nU R                  US-   S n	U R                  " / UQUPUPUPU	Q76 n
[	        U5      n[	        U5      S-   n[        [        U
R                  5      5      nX   X   sX'   X'   U
R                  " U6 nUR                  U 5      nU$ )a?  
Reorders a tensor that was reconstructed from sharded packed weights into its canonical packed format.

For example, if a weight was packed (e.g., gate_proj and up_proj) and then sharded,
DTensor.full_tensor() might produce an interleaved layout like [G0, U0, G1, U1, ...]
along the sharded dimension. This function reorders it to [G0, G1, ..., U0, U1, ...].
This is an inverse operation to get_packed_weights.

Args:
    reconstructed_tensor: The tensor reconstructed from DTensor (e.g., via .full_tensor().contiguous()).
    sharded_dim: The dimension index in the reconstructed_tensor that was originally sharded.
    world_size: The tensor parallel world size.
    num_packed_projs: The number of projections that were packed together (e.g., 2 for gate_up_proj).

Returns:
    The reordered tensor in canonical packed format.
r   zNum blocks different from 2 is not supported yet. This is most likely a bug in your implementation as we only pack gate and up projections together.r   Nr"   )	rB   ndimr;   viewlenr   r=   permute
reshape_as)packed_parametersharded_dimrJ   
num_blocksactual_sharded_dimtotal_size_on_sharded_dimoriginal_block_size_on_dimshard_chunk_sizeprefix_shapesuffix_shapetensor_viewaxis_ws_absaxis_npp_abspermute_ordertensor_permutedfinal_ordered_tensors                   r   repack_weightsrj      s:   0 Q c
 	
 )4q(8kLaLa>a 0 6 67I J!:!H1?#))*=+=>L#))*<q*@*BCL"'' 	 	 		
 
K l#K|$q(L{//01M>K>Y[h[u;M ;!))=9O +556FGr*   c                   US:X  aB  UR                   S   nXXRR                  5       -  -  US-   XRR                  5       -  -  2S4   n U $ US:X  d  US:X  aF  UR                   S   nU SX5UR                  5       -  -  US-   XRR                  5       -  -  2S S 24   n U $ US:X  d  US:X  aC  UR                   S   nU SX5UR                  5       -  -  US-   XRR                  5       -  -  24   n U $ [        SU S35      e)	Nr   r"   .r7   r   r8   r9   r:   )r;   r<   rB   )rD   rE   rF   rG   rH   size_s         r   get_tensor_shardrm      s6   
ax!!!$e'7'7'99:dQh5TdTdTfKf=ggillm L 
SBY!!"%c4K,<,<,>#>?4!8PUYiYiYkPkBllnoop L 
SBY!!"%c4K,<,<,>#>?4!8PUYiYiYkPkBlllm L +C50RSTTr*   c                   ^^^ [        U R                  5      S:X  a2  Tb  U R                  UU4S j5        Tb  U R                  UU4S j5        U $ )z
Copy pasted from torch's function but we remove the communications (partitioning)
as well as buffer registering that is similarly not efficient.
r   c                   > T" XT5      $ N )modinputsrF   input_fns     r   <lambda>#distribute_module.<locals>.<lambda>   s    #WbAcr*   c                   > T" XT5      $ rp   rq   )rr   rs   outputsrF   	output_fns      r   ru   rv      s    iPS^iFjr*   )rX   _forward_pre_hooksregister_forward_pre_hookregister_forward_hook)modulerF   rt   ry   s    ```r   distribute_moduler~      sG     6$$%*,,-cd (()jkMr*   c                  L    \ rS rSrSrSr\S 5       r\S 5       rS r	S
S jr
Srg	)TensorParallelLayer   1
General tensor parallel layer for transformers.
Tc                    g rp   rq   input_layoutsdesired_input_layoutsrr   rs   rF   s        r   _prepare_input_fn%TensorParallelLayer._prepare_input_fn  s    [^r*   c                    g rp   rq   output_layoutsuse_local_outputrr   rx   rF   s        r   _prepare_output_fn&TensorParallelLayer._prepare_output_fn	  s    Y\r*   c                    [         erp   )NotImplementedError)selfrD   rE   
param_typeparam_casting_dtypeto_contiguousrG   rF   s           r   partition_tensor$TensorParallelLayer.partition_tensor  s    !!r*   c           
         U R                   (       aa  [        UU[        U R                  U R                  U R
                  5      [        U R                  U R                  U R                  5      5        g g rp   )	use_dtensorr~   r   r   r   r   r   r   r   r   r}   rF   s      r   prepare_module_tp%TensorParallelLayer.prepare_module_tp  sZ    ..0B0BDD^D^_//1D1DdF[F[\	 r*   rq   Nr}   	nn.Modulereturnr   )__name__
__module____qualname____firstlineno____doc__r   staticmethodr   r   r   r   __static_attributes__rq   r*   r   r   r      s4     K^ ^\ \"r*   r   c                  f   ^  \ rS rSrSrSSSS.     S
U 4S jjjr\S 5       r\S 5       rS	r	U =r
$ )GatherParalleli  za
Simple class used to define the hooks to add to a layer when we just want to gather the outputs
NT)r   r   r   c                  > [         TU ]  5         U=(       d
    [        5       4U l        X l        [        5       4U l        X0l        g rp   )super__init__r   r   r   r   r   )r   r   r   r   	__class__s       r   r   GatherParallel.__init__   s:     	+:y{<,&/k^" 0r*   c                j    U(       a+  [        US   [        5      (       a  US   R                  5       nU$ Nr   r   r   to_localr   s        r   r    GatherParallel._prepare_input_fn-  s,    jG44AY'')Fr*   c                    [         R                  R                  US   [         R                  R                  R                  SS9  U$ )Nr   F)opasync_op)r@   distributed
all_reduceReduceOpSUMr   s        r   r   !GatherParallel._prepare_output_fn3  s;     	$$WQZE4E4E4N4N4R4R]b$cr*   )r   r   r   r   r   Optional[Placement]r   r   r   bool)r   r   r   r   r   r   r   r   r   r   __classcell__r   s   @r   r   r     sc     .2.2!%1 +1 ,	1
 1 1  
  r*   r   c                  J    \ rS rSrSr\SS j5       r\SS j5       rS	S jrSr	g)
IsolatedParalleli:  z
This class is used to isolate computation in a TP layer from the rest of the world.
Parameters need to be LOCAL, so not dtensors
Nc                Z    US   n[        U[        5      (       a  UR                  5       nU$ r   r   r   r   rr   rs   rF   input_tensors         r   r   "IsolatedParallel._prepare_input_fn@  s.     aylG,,'002Lr*   c                    U$ rp   rq   r   s        r   r   #IsolatedParallel._prepare_output_fnH  s	     r*   c           
     t    [        UU[        U R                  S S 5      [        U R                  S S 5      5        g rp   )r~   r   r   r   r   s      r   r   "IsolatedParallel.prepare_module_tpM  s4    D**D$7D++T48		
r*   rq   rp   r   )
r   r   r   r   r   r   r   r   r   r   rq   r*   r   r   r   :  s4    
    
r*   r   c                  n   ^  \ rS rSrSrSSSSS.     SU 4S jjjr\S 5       rS r\S	 5       r	S
r
U =r$ )ColwiseParalleliV  r   NTr   r   r   r   c                  > [         TU ]  5         U=(       d
    [        5       4U l        U=(       d    [	        S5      4U l        [        5       4U l        X0l        X@l        g Nr8   )	r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s        r   r   ColwiseParallel.__init__[  sN     	+:y{<-:r<&/k^" 0&r*   c                    US   n[        U[        5      (       d  [        R                  " XTU SS9nX:w  a  UR                  USS9nU$ )Nr   F	run_check
placementsr   r   r   
from_localredistributer   s         r   r   !ColwiseParallel._prepare_input_fnj  sT     ay,00"--lbghL 1'44@U`e4fLr*   c                V   US:X  a  [        XXvS5      n[        S5      /n	O[        S5      /n	[        XXvS5      nUR                  U5      nU(       a  UR                  5       nU R                  (       a  [
        R                  " XU	SS9n[        R                  " XR                  5       S9$ )Nbiasr8   r7   Fr   requires_grad)
rm   r   r?   
contiguousr   r   r   r
   	Parameteris_floating_point
r   rD   rE   r   r   r   rG   rF   	parametershards
             r   r    ColwiseParallel.partition_tensorw  s     ([PRSI2YKE2YKE([PRSILL!45	!,,.I**95TYZI||I5P5P5RSSr*   c                t    UR                   U :w  a  UR                  U SS9nU(       a  UR                  5       $ U$ )NFr   )r   r   r   r   s        r   r   "ColwiseParallel._prepare_output_fn  s=     /**nu*UG%5w!B7Br*   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   s   @r   r   r   V  sn     .2.2!%' +' ,	'
 ' ' 
 
T$ C Cr*   r   c                      \ rS rSrS rSrg)PackedColwiseParalleli  c                   [        XXvS5      nUR                  U5      nU(       a  UR                  5       nU R                  (       a   [        R
                  " X[        S5      /SS9n[        R                  " XR                  5       S9$ )Nr7   Fr   r   
rT   r?   r   r   r   r   r   r
   r   r   	r   rD   rE   r   r   r   rG   rF   r   s	            r   r   &PackedColwiseParallel.partition_tensor  n     'u;bQ	LL!45	!,,.I**9E"I;Z_`I||I5P5P5RSSr*   rq   Nr   r   r   r   r   r   rq   r*   r   r   r         
Tr*   r   c                  x   ^  \ rS rSrSrSSSSS.     SU 4S jjjrS r\S 5       r\S	 5       r	SS
 jr
SrU =r$ )RowwiseParalleli  a  
Partition a compatible nn.Module in a row-wise fashion. Currently supports nn.Linear and nn.Embedding.
Users can compose it with ColwiseParallel to achieve the sharding of more complicated modules.
(i.e. MLP, Attention)

Keyword Args:
    input_layouts (Placement, optional):
        The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
        become a DTensor. If not specified, we assume the input tensor to be sharded on the last dimension.
    output_layouts (Placement, optional):
        The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
        with the user desired layout. If not specified, the output tensor is replicated.
    use_local_output (bool, optional):
        Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True.
Returns:
    A :class:`ParallelStyle` object that represents Rowwise sharding of the nn.Module.
NTr   c                  > [         TU ]  5         U=(       d    [        S5      4U l        U=(       d
    [	        5       4U l        X0l        X@l        g r   )r   r   r   r   r   r   r   r   r   s        r   r   RowwiseParallel.__init__  sB     	+8uRy:-<> 0&r*   c                D   US:w  a  [        XXvS5      n[        S5      /n	O[        5       /n	US S  nUR                  U5      nU(       a  UR	                  5       nU R
                  (       a  [        R                  " XU	SS9n[        R                  " XR                  5       S9$ )Nr   r8   Fr   r   )rm   r   r   r?   r   r   r   r   r
   r   r   r   s
             r   r    RowwiseParallel.partition_tensor  s     ([PRSI2YKE[MEaILL!45	!,,.I**95TYZI||I5P5P5RSSr*   c                    [        US5      (       a%  UR                  b  UR                  Ul        S Ul        US   n[        U[        5      (       d  [        R
                  " XTU SS9nX:w  a  UR                  USS9nU$ )Nr   r   Fr   Tr   )hasattrr   _biasr   r   r   r   r   s         r   r   !RowwiseParallel._prepare_input_fn  sx    3CHH$8CICHay,00"--lbghL1'44@U`d4eLr*   c                    UR                   U :w  a  UR                  U SS9n[        US5      (       a  X2R                  -  nU(       a  UR	                  5       $ U$ )NTr   r   )r   r   r   r   r   r   s        r   r   "RowwiseParallel._prepare_output_fn  sV    
 /**nt*TG3  yy G%5w!B7Br*   c           
     0   SUl         U R                  (       a  [        U[        R                  5      (       a  [        S5      4U l        Ol[        U[        R                  5      (       a  [        5       4U l        O<[        U[        R                  5      (       a  [        S5      4U l        O[        S5      e[        UU[        U R                  U R                  U R                  5      [        U R                  U R                   U R"                  5      5        g g )NTr8   zBRowwiseParallel currently only support nn.Linear and nn.Embedding!)_distribute_module_appliedr   r   r
   Linearr   r   	Embeddingr   r   r   r~   r   r   r   r   r   r   r   s      r   r   !RowwiseParallel.prepare_module_tp  s    ,0)&")),,EJ2YL*FBLL11.7k^*FBLL11.3Bi\*)*noo..0B0BDD^D^_//1D1DdF[F[\	 r*   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   s   @r   r   r     sx    * .2.2!%' +' ,	'
 ' 'T$   	C 	C r*   r   c                      \ rS rSrS rSrg)PackedRowwiseParalleli  c                   [        XXvS5      nUR                  U5      nU(       a  UR                  5       nU R                  (       a   [        R
                  " X[        S5      /SS9n[        R                  " XR                  5       S9$ )Nr8   Fr   r   r   r   s	            r   r   &PackedRowwiseParallel.partition_tensor  r   r*   rq   Nr   rq   r*   r   r  r    r   r*   r  c                  b   ^  \ rS rSrSrSSSS.SU 4S jjjr\S 5       r\S 5       rS	 r	S
r
U =r$ )SequenceParalleli  a	  
SequenceParallel replicates a compatible ``nn.Module`` parameters and runs the sharded computation with
input sharded on the sequence dimension. This currently supports ``nn.LayerNorm``, ``nn.Dropout``, and the
`RMSNorm python implementation <https://github.com/facebookresearch/llama/blob/main/llama/model.py#L34>`__

This style implements the operation that is described in the paper
`Reducing Activation Recomputation in Large Transformer Models <https://arxiv.org/abs/2205.05198>`__

If the input passed in to this ``nn.Module`` is a :class:`torch.Tensor`, it assumes that the input is already sharded
on the sequence dimension and converts the input to a :class:`DTensor` sharded on the sequence dimension. If the input
passed in to this ``nn.Module`` is already a :class:`DTensor` but is not sharded on the sequence dimension, it would
redistribute the input to be sharded on the sequence dimension.

The output of the ``nn.Module`` will be sharded on the sequence dimension.

Keyword Args:
    sequence_dim (int, optional):
        The sequence dimension of the input tensor for the ``nn.Module``, this is used to annotate the input tensor to
        become a DTensor that is sharded on the sequence dimension, default: 1.
    use_local_output (bool, optional):
        Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: False.
Returns:
    A :class:`ParallelStyle` object that represents Sequence Parallel of the ``nn.Module``.

Example::
    >>> # xdoctest: +SKIP(failing)
    >>> from torch.distributed.tensor.parallel import parallelize_module, SequenceParallel
    >>> from torch.distributed.device_mesh import init_device_mesh
    >>> ...
    >>> m = Model(...)  # m is a nn.Module that contains a "norm" nn.LayerNorm submodule
    >>> tp_mesh = init_device_mesh("cuda", (8,))
    >>>
    >>> # By default, the input of the "norm" will be converted to DTensor that shards on the sequence dim
    >>> # and the output of "norm" will return a sharded on sequence dimension :class:`DTensor`.
    >>>
    >>> sharded_mod = parallelize_module(m, tp_mesh, {"norm": SequenceParallel()}),
    >>> ...

.. note:: SequenceParallel style assumes ones initialization if there are weights in the nn.Module (i.e.
    ``nn.LayerNorm`` or ``RMSNorm``, and they by default have ones initialization). If you have custom
    inits for the weights on those modules, you need to broadcast the weights before/after parallelizing
    to ensure that they are replicated.
r"   F)sequence_dimr   r   c                  > [         TU ]  5         [        5       4U l        [	        S5      4U l        [        5       4U l        X l        SU l        [	        U5      4U l	        X l        g )Nr"   T)
r   r   r   r   r   r   r   r   r   sequence_sharding)r   r  r   r   r   s       r   r   SequenceParallel.__init__?  sX    'k^&+Ah["({n 0"'"5!7 0r*   c                    US   n[        U[        5      (       d  [        R                  " XTU SS9nX:w  a  UR                  USS9nU$ )Nr   Fr   Tr   r   r   s         r   r   "SequenceParallel._prepare_input_fnI  sP    ay,00"--lbghL1'44@U`d4eLr*   c                T    UR                  [        5       4SS9nUR                  5       $ )NTr   )r   r   r   r   s        r   r   #SequenceParallel._prepare_output_fnR  s1    &&!~ ' 
 !!r*   c                    US   nUR                  U5      nU(       a  UR                  5       nU R                  (       a  [        R                  " X[        5       /SS9n[        R                  " XR                  5       S9$ )N.Fr   r   )	r?   r   r   r   r   r   r
   r   r   r   s	            r   r   !SequenceParallel.partition_tensorY  sg     #J	LL!45	!,,.I**9IK=\abI||I5P5P5RSSr*   )r   r   r   r	  r   r   )r  intr   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   s   @r   r  r    sQ    *X /0%]b 1 1   " "
T 
Tr*   r  >
   localgathercolwiserowwisecolwise_reprowwise_replocal_colwiselocal_rowwisesequence_parallellocal_packed_rowwisec                   [        U [        5      (       d  [        S[        U 5       S35      eU S:X  a
  [	        5       $ U S:X  a
  [        5       $ U S:X  a  [	        [        5       S9$ U S:X  a  [        [        5       S9$ U S	:X  a	  [	        S
S9$ U S:X  a	  [        S
S9$ U S:X  a
  [        5       $ U S:X  a
  [        5       $ U S:X  a	  [        S
S9$ U S:X  a
  [        5       $ [        SU  35      e)z
In model configurations, we use a neutral type (string) to specify parallel
styles, here we translate them into torch.distributed tensor-parallel
types.
z Unsupported parallel style type z, expected strr  r  r  )r   r  )r   r  F)r   r  r  r  r  r  z"Unsupported parallel style value: )r   strrB   typer   r   r   r   r   r  r  )styles    r   !translate_to_torch_parallel_styler   t  s     eS!!;DK=WXX	  	)	  	-	ik::	-	Y[99	/	!511	/	!511	'	!!	(		(	($77	%	%!!=eWEFFr*   c                X   SU;   a  UR                  SS5      OUu  pE[        X5      nU(       d  U $ US;  a  U $ US:X  a  [        S5      /nOJUS:X  a  US:X  a  [        5       /nO2[        S5      /nO%US:X  a  US:X  a  [        S5      /nO[        S	5      /n[        R
                  " XWS
S9$ )z
Converts a local variant of weights to a DTensor with corresponding placements. Shouldn't be done ever except of before saving the model.
r!   r"   )r  r  r  r  r8   r  r   r  r7   Fr   )r%   r)   r   r   r   r   )r   r&   rF   r'   _r   tp_styler   s           r   convert_local_tensor_to_dtensorr$    s     69N5JN))#q1P^MA%n>HQQ))Bi[
	_	$#+J)J	_	$)J)JijERRr*   c                    U R                  5        HK  u  p4[        U[        R                  5      (       d  M&  [        U[        5      (       a  M=  [        XCX!5      X'   MM     U $ )z}
Replaces all tensors that were sharded with `local_*` strategy with DTensor to make determining their proper size possible.
)itemsr   r@   Tensorr   r$  )
state_dictr'   rF   keyvalues        r   %replace_state_dict_local_with_dtensorr+    sL     !&&(
eU\\**:eW3M3M=e+_JO ) r*   c           	        Ub  [        U5      n UR                  X5        SU;   au  UR	                  SS5      S   n[
        R                  " SS	U5      n	UR                  U	S
5      =n
(       a.  [        U
5      nU R                  U5      nUR                  X5        ggg! [         a  n[        SU SU SU 35         SnANSnAff = f)ag  
Add hooks to the module holding the layer. Meaning:
```
class MyModel(nn.Module):
    def __init__(self):
        self.layer = nn.Linear(10, 10)
```
has state_dict like:
```
{
    "layer.weight": torch.Tensor,
    "layer.bias": torch.Tensor
}
```
we add hooks to `MyModel` as well as `layer` to make sure that the tensors are correctly sharded and gathered.
NTrying to prepare 0, but it's not supported. Corresponding module: z Fix it's TP plan: r!   r"   r   r   r    F)	r   r   r   printr%   r#   r$   getget_submodule)modelr}   r'   
layer_namecurrent_module_planrF   tp_layereparent_layer_namegeneric_namemodule_planmodule_to_tp_s               r   #add_tensor_parallel_hooks_to_moduler;    s    & &45HI	&&v; j&--c15a8vvfc+<=!++lE::;:8EH!//0ABM&&}B ;	  # 	$ZL0`ag`hh{|}{~ 	s   B 
C'C  Cc                   SU;   a  UR                  SS5      OUu  pU R                  n
U R                  U5      n[        U5      n[	        X:5      n[        USS5      (       d  [        XXX5        SUl        Ub!   [        U5      nUR                  XXXVU5      nO+US   R                  U5      nU(       a  UR                  5       n[        U[        R                   R"                  5      (       d+  [        R                   R#                  XR%                  5       S9n['        XU5        U$ ! [         a!  n[        SU SU S	W S
U 35         SnANSnAff = f)a  
Main uses cases:
- column / rowise parallelism, you just shard all the weights of the layer (weight and bias)
- packed layers: you slice the weights, then shard like above
- custom operation:
    - you want to add an all-gather at the end of a local layer.
    - you want to have a layer that is isolated from the rest of the world (because torch.DTensor does not work well with `.view` for instance)

r!   r"   
_is_hookedFTNr-  r.  z" Fix it's TP plan, current layer: z : .r   )r%   _tp_planr1  r  r)   getattrr;  r=  r   r   r   r/  r?   r   r   r@   r
   r   r   setattr)r2  rD   rE   r&   r   is_contiguousrG   rF   
param_namer   r'   module_to_tpr4  r5  r6  s                  r   shard_and_distribute_modulerD    su    ?B^>S^223:YgJnnG&&z2Lt9D0I <u55+EViw"&&	89LMH--J]ZeE c
12$$&E eUXX//00""58O8O8Q"RLe,L# # 	$^$44deqdr  sU  V^  U_  _b  cd  be  f 	s   :D' '
E1EEc                   Uc  gU  Vs1 s H  n[         R                  " SSU5      iM     nn[        U5      nUnU H  nSU;   a  UR                  SS5      OUu  pg[         R                  " SSU5      nX;   a$  UR	                  U5        UR                  U5        M`  SU;   a>  UR                  SS5      S   =o;   a$  UR	                  U	5        UR                  U5        M  M     [        U5      S:  a  [        R                  SU 35        [        U5      S:  a(  [        R                  SS	R                  U5       35        ggs  snf )
zy
Verify the TP plan of the model, log a warning if the layers that were not sharded and the rules that were not applied.
Nr   r    r!   r"   r   z>The following TP rules were not applied on any of the layers: z'The following layers were not sharded: z, )
r#   r$   setr%   popdiscardrX   loggerwarningjoin)
expected_keysr'   r)  generic_keysunsharded_layersunused_rulesrB  r"  r(   parent_param_names
             r   verify_tp_planrQ    s>   
 8EFBFF63,LF<(L.1Sj

3*c
VVFC<(/0$$S)&&ASAZAZ[^`aAbcdAe,e,=+q./$$S)  <1WXdWefg
q @K[A\@]^_ !' Gs   "E)r   r  r   zUnion[int, List[int]]r   z	List[int])r&   r  r'   dict[str, str]r   zOptional[str])r   )
r[   torch.Tensorr\   r  rJ   r  r]   r  r   rS  )NNNr   )r  r  )r   rS  r&   r  r'   rR  r   r   )r(  dict[str, torch.Tensor]r'   rR  r   rT  )rL  z	list[str]r'   zOptional[dict[str, str]])>
__future__r   r#   	functoolsr   r   typingr   r   r   r	   r@   r
   utilsr   r   	LayerNormALL_LAYERNORM_LAYERS
get_loggerr   rI  r   is_available_torch_distributed_availabletorch.distributed.tensorr   r   r   r   r   r)   r   uint8int8int16rA   bfloat16int32float32float64int64float8_e4m3fnrC   rT   rj   rm   r~   r   r   r   r   r   r   r  r  SUPPORTED_TP_STYLESr   r$  r+  r;  rD  rQ  rq   r*   r   <module>ri     s    # 	 ( / /   6 ~ 			H	%  %00==?  U##(DMM&4" JJ
++
**;;==NN;;====;;"" ;6D 	> "> >  >  	> 
 > B" 	
 $ 8( >
* 
89C) 9CxTO Ta) aHTO TQT* QTh  G GBSS-0SHVSS:' 	$CN0f`r*   