o
    wiϜ                     @  s  U d dl mZ d dlZd dlZd dlZd dlmZmZ d dlm	Z	m
Z
 d dlZd dlmZ d dlmZ ddlmZmZ ddlmZ eeZej Zed	r]er]d d
lmZmZmZmZ dRddZdSddZ dTddZ!ej"ej#ej$ej%ej&ej'ej(ej)ej*ej+ej,dZ-dd Z.	dUdVd$d%Z/d&d' Z0			dWdXd*d+Z1G d,d- d-Z2G d.d/ d/e2Z3G d0d1 d1e2Z4G d2d3 d3e2Z5G d4d5 d5e2Z6G d6d7 d7e6Z7G d8d9 d9e2Z8G d:d; d;e8Z9G d<d= d=e2Z:G d>d? d?eZ;e; Z<d?e=d@< dYdCdDZ>dZdGdHZ?dIdJ Z@dKdL ZAd[dPdQZBdS )\    )annotationsN)partialreduce)OptionalUnion)nn   )is_torch_greater_or_equallogging)GeneralInterface2.5)DTensor	Placement	ReplicateShardc              
   C  s  | du rdS t dstdtj j}tt|}tj syzIt	t
jd }t	t
jd }t	t
jd }dd	d
dd}||}|dkrOt	t
jddrOd
}tjj|||d tt|}|dkrf|| W n tyx }	 ztd|	d}	~	ww |dkr|t	t
jd  |dkr| nd}
t||
}|
dur|
dkrddl}tt
jd|_tt
jd|_|}|dur|ntj }tj|j|f}|||fS )z
    Sets up the device mesh and initilized the backend for tensor parallelism.
    This function is called when the model is loaded and the TP plan is set to 'auto'.
    NNNNr   z3Tensor parallel is only supported for `torch>=2.5`.RANK
LOCAL_RANK
WORLD_SIZEncclgloocclhccl)cudacpuxpuhpur   CCL_WORKER_COUNTr   )backendrank
world_sizezWe tried to initialize torch.distributed for you, but it failed. Make sure you init torch distributed in your script to use `tp_plan='auto'`.w)r	   OSErrortorch_C_get_acceleratortypegetattrdistributedis_initializedintosenvirongetinit_process_group
set_device	Exceptioncurrent_devicedevicesysopendevnullstdoutstderrget_world_sizeinit_device_mesh)tp_plantp_sizedevice_typer1   r   
local_rankr    backend_mapr   eindex	tp_devicer3   
device_mapdevice_mesh rD   f/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/integrations/tensor_parallel.pyinitialize_tensor_parallelism(   sP   





rF   
total_sizer*   blocksUnion[int, list[int]]return	list[int]c                   sx   t |tr&t|}| | dksJ d|  d| | |   fdd|D S | | dks3J d| | | }|g| S )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: c                   s   g | ]} | qS rD   rD   ).0block	part_sizerD   rE   
<listcomp>q   s    z*_blocks_to_block_sizes.<locals>.<listcomp>zPrepacked is not divisible by )
isinstancelistsum)rG   rH   total_blockssingle_sizerD   rN   rE   _blocks_to_block_sizes^   s   
 
rV   parameter_namestrr:   dict[str, str]Optional[str]c                 C  sR   t dd| }||v r|| S d|v r'|ddd |v r'||ddd  S dS )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)rW   r:   generic_param_namerD   rD   rE   _get_parameter_tp_planx   s   rc   )BOOLU8I8I16F16BF16I32F32F64I64F8_E4M3c                 C  s  | }|j | }| }t|dd}g }	d}
|D ]}|| }|| }|d | }|	t|
| |
| 7 }	|
|7 }
q| }|dkrG|d tj}|dkrR||	df }n)|dksZ|dkrd|dd|	df }n|dksl|d	krs|d|	f }ntd
| d|t	| S )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   )rG   rH   r   r^   rn   .NzUnsupported dim z", only dim 0, 1 or 2 are supported)
shapesizerV   range	get_dtypetor#   float16
ValueErrorstr_to_torch_dtype)paramempty_paramrC   r   dimslice_rG   r    block_sizestensors_slicesblock_offset
block_sizeshard_block_sizestartstopslice_dtypetensorrD   rD   rE   get_packed_weights   s.   

r   packed_parametertorch.Tensorsharded_dimr    
num_blocksc                 C  s   |dkrt d|dkr|n|| j }| j| }|| }|| }| jd| }| j|d d }	| jg |||||	R  }
t|}t|d }tt|
j}|| || ||< ||< |
j| }|| }|S )as  
    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^   )	rw   ndimrq   viewlenrR   rs   permute
reshape_as)r   r   r    r   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_tensorrD   rD   rE   repack_weights   s8   


r   c                 C  s   |  }|dk r|| }||krtd| d| |j}ttj|}||kr1td| d| |j| | }|| }	|	| }
tdg| }t|	|
||< | t| S )a  
    Generalized tensor sharding across a multi-dimensional device mesh.

    Args:
        param (torch.Tensor): The tensor to shard.
        empty_param (torch.Tensor): A tensor used for shape reference.
        device_mesh (torch.Tensor): Shape [d_0, ..., d_n] representing the mesh.
        rank (int): Global rank of the current process/device.
        dim (int): Dimension along which to shard the tensor.
    r   zdim z* is out of bounds for tensor of dimension zRank z  is out of bounds for mesh size N)r{   rw   rq   r   operatormulslicetuple)ry   rz   rC   r   r{   	param_dim
mesh_shaper    
shard_sizer   endslice_indicesrD   rD   rE   get_tensor_shard  s   r   module	nn.Modulec                   sJ   t | jdkr#dur|  fdd dur#|  fdd | S )z
    Copy pasted from torch's function but we remove the communications (partitioning)
    as well as buffer registering that is similarly not efficient.
    r   Nc                   s   | | S NrD   )modinputs)rC   input_fnrD   rE   <lambda>E      z#distribute_module.<locals>.<lambda>c                   s   | | S r   rD   )r   r   outputs)rC   	output_fnrD   rE   r   G  r   )r   _forward_pre_hooksregister_forward_pre_hookregister_forward_hook)r   rC   r   r   rD   )rC   r   r   rE   distribute_module9  s   
r   c                   @  s>   e Zd ZdZdZedd Zedd Zdd ZdddZ	dS )TensorParallelLayer9
    General tensor parallel layer for transformers.
    Tc                 C     d S r   rD   input_layoutsdesired_input_layoutsr   r   rC   rD   rD   rE   _prepare_input_fnR     z%TensorParallelLayer._prepare_input_fnc                 C  r   r   rD   output_layoutsuse_local_outputr   r   rC   rD   rD   rE   _prepare_output_fnU  r   z&TensorParallelLayer._prepare_output_fnc                 C  s   t r   )NotImplementedErrorselfry   rz   
param_typeparam_casting_dtypeto_contiguousr   rC   rD   rD   rE   partition_tensorX  r   z$TensorParallelLayer.partition_tensorr   r   rJ   c                 C  s8   | j rt||t| j| j| jt| j| j| j d S d S r   )	use_dtensorr   r   r   r   r   r   r   r   r   r   rC   rD   rD   rE   prepare_module_tp[  s   z%TensorParallelLayer.prepare_module_tpNr   r   rJ   r   )
__name__
__module____qualname____doc__r   staticmethodr   r   r   r   rD   rD   rD   rE   r   K  s    

r   c                      sD   e Zd ZdZddddd fd
dZedd Zedd Z  ZS )GatherParallelzi
    Simple class used to define the hooks to add to a layer when we just want to gather the outputs
    NT)r   r   r   r   Optional[Placement]r   r   boolc                  s2   t    |p	t f| _|| _t f| _|| _d S r   )super__init__r   r   r   r   r   )r   r   r   r   	__class__rD   rE   r   l  s
   


zGatherParallel.__init__c                 C  s"   |rt |d tr|d  }|S Nr   rQ   r   to_localr   rD   rD   rE   r   y  s   z GatherParallel._prepare_input_fnc                 C  s    t jj|d t jjjdd |S )Nr   F)opasync_op)r#   r(   
all_reduceReduceOpSUMr   rD   rD   rE   r     s   z!GatherParallel._prepare_output_fnr   r   r   r   r   r   )	r   r   r   r   r   r   r   r   __classcell__rD   rD   r   rE   r   g  s    
r   c                   @  s6   e Zd ZdZedddZedddZdd
dZdS )IsolatedParallelz
    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                 C  s   |d }t |tr| }|S r   r   r   r   r   r   rC   input_tensorrD   rD   rE   r     s   
z"IsolatedParallel._prepare_input_fnc                 C  s   |S r   rD   r   rD   rD   rE   r     s   z#IsolatedParallel._prepare_output_fnr   r   rJ   c                 C  s&   t ||t| jd d t| jd d  d S r   )r   r   r   r   r   rD   rD   rE   r     s   z"IsolatedParallel.prepare_module_tpr   r   )r   r   r   r   r   r   r   r   rD   rD   rD   rE   r     s    r   c                      sH   e Zd ZdZddd fdd
Zedd Zedd	 Zd
d Z  Z	S )ReplicateParallelz
    This class is used to replicate computation in a TP layer (used in SP regions when we don't use sequence parallelism for example)
    T)r   r   c                  s8   t    t f| _t f| _t f| _|| _|| _d S r   )r   r   r   r   r   r   r   r   )r   r   r   r   rD   rE   r     s   




zReplicateParallel.__init__c                 C  s(   |d }t |tstj||| dd}|S )Nr   F	run_check)rQ   r   
from_localr   rD   rD   rE   r     s   
z#ReplicateParallel._prepare_input_fnc                 C  s   |r|  S |S r   )r   r   rD   rD   rE   r     s   z$ReplicateParallel._prepare_output_fnc                 C  s4   |d  |}|r| }tj||t gdd}|S )N.Fr   )ru   
contiguousr   r   r   r   rD   rD   rE   r     s
   z"ReplicateParallel.partition_tensor
r   r   r   r   r   r   r   r   r   r   rD   rD   r   rE   r     s    
	
r   c                      sN   e Zd ZdZdddddd fd
dZedd Zdd Zedd Z  Z	S )ColwiseParallelr   NTr   r   r   r   r   r   r   r   r   c                  sB   t    |p	t f| _|ptdf| _t f| _|| _|| _d S Nrp   )	r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rD   rE   r     s   


zColwiseParallel.__init__c                 C  s>   |d }t |tstj||| dd}| |kr|j|dd}|S )Nr   Fr   
placementsr   rQ   r   r   redistributer   rD   rD   rE   r     s   
z!ColwiseParallel._prepare_input_fnc           
      C  s~   |dkrt ||||d}tdg}	ntdg}	t ||||d}||}|r*| }| jr6tj|||	dd}tj||	 dS )Nbiasrp   ro   Fr   requires_grad)
r   r   ru   r   r   r   r   r   	Parameteris_floating_point
r   ry   rz   r   r   r   r   rC   	parametershardrD   rD   rE   r     s   

z ColwiseParallel.partition_tensorc                 C  s(   |j | kr|j| dd}|r| S |S )NFr   )r   r   r   r   rD   rD   rE   r     s   
z"ColwiseParallel._prepare_output_fnr   )
r   r   r   r   r   r   r   r   r   r   rD   rD   r   rE   r     s    
r   c                   @     e Zd Zdd ZdS )PackedColwiseParallelc           	      C  V   t ||||d}||}|r| }| jr"tj||tdgdd}tj||	 dS )Nro   Fr   r   
r   ru   r   r   r   r   r   r   r   r   	r   ry   rz   r   r   r   r   rC   r   rD   rD   rE   r        
z&PackedColwiseParallel.partition_tensorNr   r   r   r   rD   rD   rD   rE   r         r   c                      sX   e Zd ZdZdddddd fd
dZdd Zedd Zedd ZdddZ	  Z
S )RowwiseParallela  
    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   r   r   r   r   r   c                  s8   t    |p
tdf| _|pt f| _|| _|| _d S r   )r   r   r   r   r   r   r   r   r   r   rD   rE   r   "  s
   

zRowwiseParallel.__init__c           
      C  sx   |dkrt ||||d}tdg}	n
t g}	|d d  }||}|r'| }| jr3tj|||	dd}tj	||
 dS )Nr   rp   Fr   r   )r   r   r   ru   r   r   r   r   r   r   r   r   rD   rD   rE   r   0  s   
z RowwiseParallel.partition_tensorc                 C  s`   t |dr|jd ur|j|_d |_|d }t|ts#tj||| dd}| |kr.|j|dd}|S )Nr   r   Fr   Tr   )hasattrr   _biasrQ   r   r   r   r   rD   rD   rE   r   B  s   
z!RowwiseParallel._prepare_input_fnc                 C  s<   |j | kr|j| dd}t|dr||j7 }|r| S |S )NTr   r  )r   r   r  r  r   r   rD   rD   rE   r   P  s
   


z"RowwiseParallel._prepare_output_fnr   r   rJ   c                 C  s   d|_ | jrGt|tjrtdf| _nt|tjrt f| _nt|tj	r,tdf| _nt
dt||t| j| j| jt| j| j| j d S d S )NTrp   zBRowwiseParallel currently only support nn.Linear and nn.Embedding!)_distribute_module_appliedr   rQ   r   Linearr   r   	Embeddingr   r   r   r   r   r   r   r   r   r   r   rD   rD   rE   r   \  s    z!RowwiseParallel.prepare_module_tpr   r   )r   r   r   r   r   r   r   r   r   r   r   rD   rD   r   rE   r    s    

r  c                   @  r   )PackedRowwiseParallelc           	      C  r   )Nrp   Fr   r   r   r   rD   rD   rE   r   t  r   z&PackedRowwiseParallel.partition_tensorNr  rD   rD   rD   rE   r	  s  r  r	  c                      sL   e Zd ZdZddddd fd	d
Zedd Zedd Zdd Z  Z	S )SequenceParallelai
  
    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://huggingface.co/papers/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   r  r*   r   r   c                  sL   t    t f| _tdf| _t f| _|| _d| _t|f| _	|| _d S )Nr^   T)
r   r   r   r   r   r   r   r   r   sequence_sharding)r   r  r   r   r   rD   rE   r     s   



zSequenceParallel.__init__c                 C  s>   |d }t |tstj||| dd}| |kr|j|dd}|S )Nr   Fr   Tr   r   r   rD   rD   rE   r     s   
z"SequenceParallel._prepare_input_fnc                 C  s   |j t fdd}| S )NTr   )r   r   r   r   rD   rD   rE   r     s   z#SequenceParallel._prepare_output_fnc           	      C  sL   |d }| |}|r| }| jrtj||t gdd}tj|| dS )N.Fr   r   )	ru   r   r   r   r   r   r   r   r   r   rD   rD   rE   r     s   
z!SequenceParallel.partition_tensor)r  r*   r   r   r   rD   rD   r   rE   r
    s    ,


r
  c                   @  sj   e Zd Zedr1er1e e ee dee deddedde e	 e
dde e dZdS i ZdS )ParallelInterfacer   )r   )r   F)r   )colwiserowwisecolwise_reprowwise_replocal_colwiselocal_rowwiselocalgatherlocal_packed_rowwisesequence_parallel	replicateN)r   r   r   r	   _torch_distributed_availabler   r  r   r   r   r	  r
  r   _global_mappingrD   rD   rD   rE   r    s(    

r  ALL_PARALLEL_STYLESr   r   c                 C  s   d|v r
| ddn|\}}t||}|s| S |dvr| S |dkr'tdg}n&|dkr:|dkr4t g}ntdg}n|dkrM|dkrHtdg}ntd	g}tj| ||d
dS )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  rp   r  r   r  ro   Fr   )ra   rc   r   r   r   r   )r   rW   rC   r:   _r   tp_styler   rD   rD   rE   convert_local_tensor_to_dtensor  s"   


r  
state_dictdict[str, torch.Tensor]c                 C  s>   |   D ]\}}t|tjrt|tst||||| |< q| S )z
    Replaces all tensors that were sharded with `local_*` strategy with DTensor to make determining their proper size possible.
    )itemsrQ   r#   Tensorr   r  )r  r:   rC   keyvaluerD   rD   rE   %replace_state_dict_local_with_dtensor  s
   r%  c              
     s    dur;t   }z|| W n ty/ } ztd| d d|  W Y d}~nd}~ww  _ fdd_d|v rr|ddd	 }td
d|}	|	|	d }
rtt |
 }| 
|||  _ fdd_dS dS dS )a  
    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: c                           d  S Nz

TP Plan: __repr__rD   )current_module_planr   rD   rE   r   5      z5add_tensor_parallel_hooks_to_module.<locals>.<lambda>r]   r^   r   r[   r\   Fc                     r(  r)  r*  rD   )r,  module_to_tp_rD   rE   r   A  r-  )r  r   r   print_hf_tp_planr+  ra   r_   r`   r-   get_submodule)modelr   r:   
layer_namer,  rC   tp_layerr?   parent_layer_namegeneric_namemodule_planrD   )r,  r   r.  rE   #add_tensor_parallel_hooks_to_module  s.   
r8  c                 C  sJ  d|v r
| ddn|\}}	| j}
| |}t|}t||
}|du r5d}t dkr4td| d nt dkrFtd| d|  t	|d	d
sXt
| ||
||| d|_zt| }||||	||||}W n" ty } ztd| d| d| d|  W Y d}~nd}~ww t|tjjstjj|| d}t||	| |S )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^   Nr  r   zTensor parallel plan for z+ not found, using default 'replicate' plan.z: 
_is_hookedFTr&  r'  z" Fix it's TP plan, current layer: z : r   )ra   _tp_planr1  r*   rc   distget_rankloggerinfor'   r8  r9  r  r   r   r/  rQ   r#   r   r   r   setattr)r2  ry   rz   rW   r   is_contiguousr   rC   
param_namer   r:   module_to_tpr,  r4  r?   rD   rD   rE   shard_and_distribute_moduleD  s<   

rC  expected_keys	list[str]Optional[dict[str, str]]c           	      C  s   |du rdS dd | D }t |}|}|D ]B}d|v r#|ddd n|}tdd|}||v r;|| || qd|v rV|ddd  }|v rV|| || q	 qt|dkrftd	|  t|dkrytd
d	|  dS dS )z
    Verify the TP plan of the model, log a warning if the layers that were not sharded and the rules that were not applied.
    Nc                 S  s   h | ]	}t d d|qS )r[   r\   )r_   r`   )rL   r#  rD   rD   rE   	<setcomp>  s    z!verify_tp_plan.<locals>.<setcomp>r]   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, )
setra   r_   r`   popdiscardr   r=  warningjoin)	rD  r:   generic_keysunsharded_layersunused_rulesr#  rA  rb   parent_param_namerD   rD   rE   verify_tp_planx  s(   
 
rQ  r   )rG   r*   rH   rI   rJ   rK   )rW   rX   r:   rY   rJ   rZ   )r   )
r   r   r   r*   r    r*   r   r*   rJ   r   r   r   )r   r   rW   rX   r:   rY   rJ   r   )r  r   r:   rY   rJ   r   )rD  rE  r:   rF  )C
__future__r   r   r+   r_   	functoolsr   r   typingr   r   r#   torch.distributedr(   r;  r   utilsr	   r
   utils.genericr   
get_loggerr   r=  is_availabler  torch.distributed.tensorr   r   r   r   rF   rV   rc   r   uint8int8int16rv   bfloat16int32float32float64int64float8_e4m3fnrx   r   r   r   r   r   r   r   r   r   r   r  r	  r
  r  r  __annotations__r  r%  r8  rC  rQ  rD   rD   rD   rE   <module>   sl   



6
BA%#<dT

+4