
    sgeo                        d dl mZmZ d dlmZ d dlmZmZmZm	Z	m
Z
 d dlZd dlmZ d dlmZmZmZmZmZmZ d dlmZ g dZ G d d	e      Z G d
 de      Z G d de      Z G d de      Z G d de      Z G d de      Zy)    )ABCabstractmethod)partial)AnyDictOptionalTupleUnionN)
DeviceMeshdistribute_moduledistribute_tensorDTensor	ReplicateShard)	Placement)ParallelStyleRowwiseParallelSequenceParallelColwiseParallelPrepareModuleInputPrepareModuleOutputc                   V    e Zd ZdZedej                  dedej                  fd       Zy)r   z
    The parallel style contract defines how the module or submodule should be parallelized.

    It only defines the ``apply`` method for ``parallelize_module`` to use, this allows maximum
    flexibility for different kind of style implementations.
    moduledevice_meshreturnc                      y N selfr   r   s      Z/var/www/html/venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/style.py_applyzParallelStyle._apply&   s        N)	__name__
__module____qualname____doc__r   nnModuler   r"   r   r#   r!   r   r      s8     RYY Z BII  r#   r   c                        e Zd ZdZdddddee   dee   def fdZed	        Z	d
 Z
d Zed        Zdej                  dedej                  fdZ xZS )r   a6  
    Partition a compatible nn.Module in a column-wise fashion. Currently supports nn.Linear and nn.Embedding.
    Users can compose it together with RowwiseParallel 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 replicated.
        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 sharded on the last dimension.
        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 Colwise sharding of the nn.Module.

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

    .. note:: By default ``ColwiseParallel`` output is sharded on the last dimension if the ``output_layouts`` not
        specified, if there're operators that require specific tensor shape (i.e. before the paired ``RowwiseParallel``),
        keep in mind that if the output is sharded the operator might need to be adjusted to the sharded size.
    NTinput_layoutsoutput_layoutsuse_local_outputr,   r-   r.   c                    t         |           |xs
 t               f| _        |xs t	        d      f| _        t               f| _        || _        y N)super__init__r   r,   r   r-   desired_input_layoutsr.   r    r,   r-   r.   	__class__s       r!   r3   zColwiseParallel.__init__P   sL     	+:y{<-:r< '0k^" 0r#   c                     |d   }t        |t              st        j                  ||| d      }| |k7  r|j                  |d      }|S Nr   F	run_checkT
placementsasync_op
isinstancer   
from_localredistributer,   r4   modinputsr   input_tensors         r!   _prepare_input_fnz!ColwiseParallel._prepare_input_fn`   s]     ay,0"--k=EL
 11'4404 5 L r#   c           
          |j                         D ]A  \  }}t        j                  t        ||t	        d      g            }|j                  ||       C y Nr   named_parametersr(   	Parameterr   r   register_parameterr    namer   r   param
dist_params         r!   _partition_linear_fnz$ColwiseParallel._partition_linear_fnt   sO     "224 	8KD%&7{USTXJ&WXJ%%dJ7	8r#   c           
          |j                         D ]A  \  }}t        j                  t        ||t	        d      g            }|j                  ||       C y )N   rI   rM   s         r!   _partition_embedding_fnz'ColwiseParallel._partition_embedding_fn|   M    !224 	8KD%&7{USTXJ&WXJ%%dJ7	8r#   c                 n    |j                   | k7  r|j                  | d      }|r|j                         S |S NTr;   r<   rA   to_localr-   r.   rC   outputsr   s        r!   _prepare_output_fnz"ColwiseParallel._prepare_output_fn   s=     /**nt*TG%5w!B7Br#   r   r   r   c                 v   t        |t        j                        r| j                  }n2t        |t        j                        r| j
                  }nt        d      t        |||t        | j                  | j                  | j                        t        | j                  | j                  | j                              S )NzBColwiseParallel currently only support nn.Linear and nn.Embedding!)r?   r(   LinearrQ   	EmbeddingrT   NotImplementedErrorr   r   rF   r,   r4   r\   r-   r.   r    r   r   partition_fns       r!   r"   zColwiseParallel._apply   s    fbii(44L-77L%T  !&&(:(:D<V<V '')<)<d>S>S

 
	
r#   r$   r%   r&   r'   r   r   boolr3   staticmethodrF   rQ   rT   r\   r(   r)   r   r"   __classcell__r6   s   @r!   r   r   +   s    "N .2.2!%1  	*1 !+	1
 1   &88 C C
RYY 
Z 
BII 
r#   r   c                        e Zd ZdZdddddee   dee   def fdZed	        Z	d
 Z
d Zed        Zdej                  dedej                  fdZ xZS )r   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.

    Example::
        >>> # xdoctest: +SKIP(failing)
        >>> from torch.distributed.tensor.parallel import parallelize_module, RowwiseParallel
        >>> from torch.distributed.device_mesh import init_device_mesh
        >>> ...
        >>> m = Model(...)  # m is a nn.Module that contains a "w2" nn.Linear submodule
        >>> tp_mesh = init_device_mesh("cuda", (8,))
        >>>
        >>> # By default, the input of the "w2" Linear will be converted to DTensor that shards on the last dim
        >>> # and the output of "w2" will return a replicated :class:`torch.Tensor`.
        >>>
        >>> sharded_mod = parallelize_module(m, tp_mesh, {"w2": RowwiseParallel()}),
        >>> ...
    NTr+   r,   r-   r.   c                    t         |           |xs t        d      f| _        |xs
 t	               f| _        || _        y r0   )r2   r3   r   r,   r   r-   r.   r5   s       r!   r3   zRowwiseParallel.__init__   s>     	+8uRy:-<> 0r#   c                     |d   }t        |t              st        j                  ||| d      }| |k7  r|j                  |d      }|S r8   r>   rB   s         r!   rF   z!RowwiseParallel._prepare_input_fn   s]     ay,0"--k=EL 11'4404 5 L r#   c                 .   |j                  dt        j                  t        |j                  |t        d      g                   t        |dd       D|j                  dt        j                  t        |j                  |t               g                   y y )NweightrS   bias)	rL   r(   rK   r   rl   r   getattrrm   r   )r    rN   r   r   s       r!   rQ   z$RowwiseParallel._partition_linear_fn   s|     	!!LL*6==+azRS	
 664(4%%%fkk;N 5r#   c           
          |j                         D ]A  \  }}t        j                  t        ||t	        d      g            }|j                  ||       C y rH   rI   rM   s         r!   rT   z'RowwiseParallel._partition_embedding_fn   rU   r#   c                 n    |j                   | k7  r|j                  | d      }|r|j                         S |S rW   rX   rZ   s        r!   r\   z"RowwiseParallel._prepare_output_fn   s=    
 /**nt*TG%5w!B7Br#   r   r   r   c                    t        |t        j                        r| j                  }t	        d      f| _        nBt        |t        j                        r| j                  }t               f| _        nt        d      t        |||t        | j                  | j                  | j
                        t        | j                  | j                  | j                               S )Nr1   zBRowwiseParallel currently only support nn.Linear and nn.Embedding!)r?   r(   r^   rQ   r   r4   r_   rT   r   r`   r   r   rF   r,   r\   r-   r.   ra   s       r!   r"   zRowwiseParallel._apply   s    fbii(44LAFrD&-77L*3+D&%T  !&&(:(:D<V<V '')<)<d>S>S

 
	
r#   rc   rg   s   @r!   r   r      s    F .2.2!%
1  	*
1 !+	
1
 
1  "8 C C
RYY 
Z 
BII 
r#   r   c                        e Zd ZdZddddedef fdZded	ej                  d
e
fdZed        Zed        Zd	ej                  d
e
dej                  fdZ xZS )r   aa
  
    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.
    rS   F)sequence_dimr.   rs   r.   c                R    t         |           t        |      f| _        || _        y r   )r2   r3   r   sequence_shardingr.   )r    rs   r.   r6   s      r!   r3   zSequenceParallel.__init__G  s&    "'"5!7 0r#   rN   r   r   c           	          |j                         D ]V  \  }}t        j                  j                  t	        j
                  ||t               gd            }|j                  ||       X y )NFr9   )rJ   torchr(   rK   r   r@   r   rL   )r    rN   r   r   p_namerO   replicated_params          r!   _replicate_module_fnz%SequenceParallel._replicate_module_fnL  se     $446 	@MFE  %xx11""5+	}PUV  %%f.>?	@r#   c                     |d   }t        |t              r$|j                  | k7  r|j                  | d      }|S t        |t        j
                        rt        j                  ||| d      S t        d| d|       )Nr   Tr;   Fr9   zexpecting input of z* to be a torch.Tensor or DTensor, but got )r?   r   r<   rA   rw   Tensorr@   
ValueError)ru   rC   rD   r   rE   s        r!   rF   z"SequenceParallel._prepare_input_fnW  s    aylG,&&*;;+8804  9    ell3%%k+<  %cU*TUaTbc r#   c                 *    | r|j                         S |S r   )rY   )r.   rC   r[   r   s       r!   r\   z#SequenceParallel._prepare_output_fnk  s    %5w!B7Br#   r   c           
          t        ||| j                  t        | j                  | j                        t        | j
                  | j                              S r   )r   rz   r   rF   ru   r\   r.   r   s      r!   r"   zSequenceParallel._applyo  sJ     %%D**D,B,BCD++T-B-BC
 	
r#   )r$   r%   r&   r'   intrd   r3   strr(   r)   r   rz   re   rF   r\   r"   rf   rg   s   @r!   r   r     s    *X /0% 1 14 1
	@	@!#	@9C	@  & C C
RYY 
Z 
BII 
r#   r   c                       e Zd ZdZdddddddeeeeee      f      deeeeee      f      deee	ef      deee	ef      d	e
f
d
Zdededee   dee   fdZd Zd Zdej$                  dedej$                  fdZy)r   aW
  
    Configure the nn.Module's inputs to convert the input tensors of the nn.Module to DTensors at runtime according to
    ``input_layouts``, and perform layout redistribution according to the ``desired_input_layouts``.

    Keyword Args:
        input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
            The DTensor layouts of input tensors for the nn.Module, this is used to convert the input tensors to
            DTensors. If some inputs are not torch.Tensor or no need to convert to DTensors, ``None`` need to be specified
            as a placeholder. default: None.
        desired_input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
            The desired DTensor layout of input tensors for the nn.Module, this is used to ensure the inputs of the nn.Module
            have the desired DTensor layouts. This argument needs to have the same length with ``input_layouts``. default: None.
        input_kwarg_layouts (Dict[str, Placement]):
            The DTensor layouts of input kwargs for the nn.Module, this is used to convert the input kwarg tensors to DTensors.
            default: None
        desired_input_kwarg_layouts: (Dict[str, Placement]):
            The desired DTensor layout of input kwargs for the nn.Module, this is used to ensure the inputs of the nn.Module
            have the desired DTensor layouts. default: None.
        use_local_output (bool, optional):
            Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module inputs, default: False.
    Returns:
        A :class:`ParallelStyle` object that prepares the sharding layouts of the nn.Module's inputs.

    Example::
        >>> # xdoctest: +SKIP(failing)
        >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleInput
        >>> from torch.distributed.device_mesh import init_device_mesh
        >>> ...
        >>> block = TransformerBlock(...)  # block is a nn.Module that contains an "attn" Attention submodule
        >>> tp_mesh = init_device_mesh("cuda", (8,))
        >>>
        >>> # According to the style specified below, the first input of attn will be annotated to Sharded DTensor
        >>> # and then redistributed to Replicated DTensor.
        >>> parallelize_module(
        >>>     block, # this can be a submodule or module
        >>>     tp_mesh,
        >>>     parallelize_plan={
        >>>         "attn": PrepareModuleInput(
        >>>             input_layouts=(Shard(0), None, None, ...),
        >>>             desired_input_layouts=(Replicate(), None, None, ...)
        >>>         ),
        >>>     }
        >>> )
    NF)r,   r4   input_kwarg_layoutsdesired_input_kwarg_layoutsr.   r,   r4   r   r   r.   c                   t        |t              r|fn|| _        t        |t              r|fn|| _        || _        | j                  E| j                  J d       t        | j                        t        | j                        k(  sJ d       |d u| _        |xs i | _        |xs i | _        | j                  r3t        | j                        t        | j                        k(  sJ d       y y )N)desired module inputs should not be None!z@input_layouts and desired_input_layouts should have same length!zLinput_kwarg_layouts and desired_input_kwarg_layouts should have same length!)	r?   r   r,   r4   r.   lenwith_kwargsr   r   )r    r,   r4   r   r   r.   s         r!   r3   zPrepareModuleInput.__init__  s    !+=) D]- 	
 /; #$& 	"
 !1)**6;:;6t))*c**/  RQR  /d:#6#<" +F+L"(t//0C005  ^]^  r#   inputmeshinput_layoutdesired_layoutc                    |t        |t              r|}n;t        |t        j                        sJ d       t        j                  |||fd      }|||k7  r|j                  |f      }| j                  r|j                         S |S |S )Nz%expecting input to be a torch.Tensor!Fr9   r<   )r?   r   rw   r|   r@   rA   r.   rY   )r    r   r   r   r   dt_inps         r!   _prepare_input_argz%PrepareModuleInput._prepare_input_arg  s     #%) !5<< ;:;  !++4,E )ln.L,,8I,J(,(=(=6??$I6ILr#   c           	      v   | j                   |S g }t        |t              s|f}t        |      t        | j                         k7  rt	        d      | j
                  J d       t        || j                   | j
                        D ])  \  }}}|j                  | j                  ||||             + t        |      S )Nz8module inputs and input_layouts should have same length!r   )	r,   r?   tupler   r}   r4   zipappendr   )r    rD   r   prepared_inputsinpr   r   s          r!   rF   z$PrepareModuleInput._prepare_input_fn  s    %M&%(YFv;#d0011WXX &&2	76	7214D&&(B(B2
 	-C~ ""''[,W	 _%%r#   c                     | j                  ||      }i }|j                         D ]T  }||   }| j                  j                  |      }| j                  j                  |      }	| j                  ||||	      ||<   V ||fS r   )rF   keysr   getr   r   )
r    rD   kwarg_inputsr   prepared_arg_inputsprepared_kwarg_inputs	kwarg_key	kwarg_valr   desired_input_layouts
             r!   _prepare_input_kwarg_fnz*PrepareModuleInput._prepare_input_kwarg_fn  s    "44V[I "%**, 	I$Y/I3377	BL#'#C#C#G#G	#R /3/F/F;6J0!),	 $%:;;r#   r   r   r   c                 ~      j                   r|j                   fdd       |S |j                   fd       |S )Nc                 *    j                  ||      S r   )r   )_rD   kwargsr   r    s      r!   <lambda>z+PrepareModuleInput._apply.<locals>.<lambda>
  s    $*F*FFK+ r#   T)r   c                 (    j                  |      S r   )rF   )r   rD   r   r    s     r!   r   z+PrepareModuleInput._apply.<locals>.<lambda>  s    t?U?UV\^i?j r#   )r   register_forward_pre_hookr   s   ` `r!   r"   zPrepareModuleInput._apply  sF    ,, !	 -   ,,-jkr#   )r$   r%   r&   r'   r   r
   r   r	   r   r   rd   r3   r   r   r   rF   r   r(   r)   r"   r   r#   r!   r   r   y  s   +` QU >BFJ!&!^  ix	7J1K&K LM!^  ()U8I#6778 
	!^ &d3	>&:;!^ &.d3	>.B%C!^ !^F  y)	
 !+6&(<
RYY 
Z 
BII 
r#   r   c                       e Zd ZdZdddeeee   f   deeee   f   defdZd Z	d	e
j                  d
ede
j                  fdZy)r   a  
    Configure the nn.Module's outputs to convert the output tensors of the nn.Module to DTensors at runtime according to
    ``output_layouts``, and perform layout redistribution according to the ``desired_output_layouts``.

    Keyword Args:
        output_layouts (Union[Placement, Tuple[Placement]]):
            The DTensor layouts of output tensors for the nn.Module, this is used to convert the output tensors to
            DTensors if they are :class:`torch.Tensor`. If some outputs are not torch.Tensor or no need to convert to DTensors,
            ``None`` need to be specified as a placeholder.
        desired_output_layouts (Union[Placement, Tuple[Placement]]):
            The desired DTensor layouts of output tensors for the nn.Module, this is used to ensure the outputs of the nn.Module
            have the desired DTensor layouts.
        use_local_output (bool, optional):
            Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module outputs, default: True.
    Returns:
        A ParallelStyle object that prepares the sharding layouts of the nn.Module's outputs.

    Example::
        >>> # xdoctest: +SKIP(failing)
        >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleOutput
        >>> from torch.distributed.device_mesh import init_device_mesh
        >>> ...
        >>> block = TransformerBlock(...)  # block is a nn.Module that contains an "attn" Attention submodule
        >>> tp_mesh = init_device_mesh("cuda", (8,))
        >>>
        >>> # According to the style specified below, the output of the TransformerBlock will be converted to Replicated DTensor
        >>> # and then redistributed to Sharded DTensor.
        >>> parallelize_module(
        >>>     block, # this can be a submodule or module
        >>>     tp_mesh,
        >>>     parallelize_plan = PrepareModuleOutput(
        >>>         output_layouts=Replicate(),
        >>>         desired_output_layouts=Shard(0)
        >>>     )
        >>> )
    T)r.   r-   desired_output_layoutsr.   c                    t        |t              r|fn|| _        t        |t              r|fn|| _        || _        t        | j                        t        | j                        k(  sJ d       y )NzBoutput_layouts and desired_output_layouts should have same length!)r?   r   r-   r   r.   r   )r    r-   r   r.   s       r!   r3   zPrepareModuleOutput.__init__:  s     .)4  	 0)< $%' 	#
 !14&&'3'',
 
 	PO	P 
r#   c                     g }t        |t              s|f}t        |      t        | j                        k7  rt	        d      t        || j                  | j                        D ]  \  }}}|st        |t              r|}nt        j                  |||fd      }||k7  r|j                  |f      }|j                  | j                  r|j                         n|       ||j                  |        t        |      dk(  r|d   S t        |      S )Nz:module outputs and output_layouts should have same length!Fr9   r   rS   r   )r?   r   r   r-   r}   r   r   r   r@   rA   r   r.   rY   )r    r[   r   prepared_outputsout
out_layoutdesired_out_layoutdt_outs           r!   _prepare_out_fnz#PrepareModuleOutput._prepare_out_fnP  s    '5)jGw<3t2233L  47T(($*E*E4
 	-/C/ %c7+ !F$//[:-5F !33#00=O<Q0RF '')-)>)>FOO%F !'','	-(  A%#A&&)**r#   r   r   r   c                 4     |j                   fd       |S )Nc                 (    j                  |      S r   )r   )r   rD   r[   r   r    s      r!   r   z,PrepareModuleOutput._apply.<locals>.<lambda>r  s    @T@TU\^i@j r#   )register_forward_hookr   s   ` `r!   r"   zPrepareModuleOutput._applyq  s    $$%jkr#   N)r$   r%   r&   r'   r
   r   r	   rd   r3   r   r(   r)   r   r"   r   r#   r!   r   r     sz    #T "&P iy)99:P !&iy1A&A B	P
 P,+BRYY Z BII r#   r   )abcr   r   	functoolsr   typingr   r   r   r	   r
   rw   torch.nnr(   torch.distributed.tensorr   r   r   r   r   r   (torch.distributed.tensor.placement_typesr   __all__r   r   r   r   r   r   r   r#   r!   <module>r      s    $  4 4    ?
C 
s
m s
lv
m v
r\
} \
~X Xv_- _r#   