
    ΑiE<                        S SK Jr  S SKJr  S SKrS SKrS SKJr  SSK	J
r
Jr  SSKJr  SSKJr  SS	KJr  SS
KJrJrJr  SS jr SS jrSqS rS r0 r " S S5      rS rSS jrSS jrSq SS jr!SS jr"SS jr#g)    )annotations)reduceN)core   )ProcessMeshget_current_process_mesh)get_default_distributed_context)DistributedOperatorHelper)DistributedTensor)__no_shape_var_type__convert_to_dims_mappingverify_shard_specc           
        Ub+  [        U[        R                  5      (       d   SU S35       eO[        5       nUc   S5       e[        U[        5      (       d   SU S35       e[        U [
        5      (       aG  [        R                  R                  5       R                  5       R                  U 5      n [        U 5      nO[        U 5      nUR                  nXR                  l        UR                  [         ;   a  / nOUR"                  nUb  [%        US5      (       a  UR'                  5       OUR(                  n[+        U5       H9  u  pxUc  M
  [        U[
        5      (       a  X;  d  M&  [-        SU SU S	U S
35      e   [/        X%U5      (       d   SUR0                   SU SU SU S
3	5       e[3        X!5      UR                  l        Ub  UR                  R7                  S5        Ub  UR                  R7                  S5        [9        5       n	U	R;                  U5        U	R=                  U 5      nU	R?                  U5        U $ )ap  
Shard a tensor on a process mesh according to the shard specification.

Args:
    x (Tensor): the tensor to be sharded.
    process_mesh (ProcessMesh, optional): An instance of ProcessMesh describes a mesh
        topology of the used logical processes where the tensor is sharded. If it is None,
        the found current process mesh will be used. And an error will be raised if the
        current process mesh cannot be found. Default: None.
    shard_spec (list, optional): a list to describe the sharding mapping between `x` and `process_mesh`,
        which means the dimension `i` of `x` is split across the dimension `shard_spec[i]` of `process_mesh`,
        where `None` means that tensor dimension is not split. For example, given a tensor with
        the shape [6, 12] and a process mesh with the shape [2, 3] and the dimension names ["x", "y"]:
            If `shard_spec=["x", "y"]`, each shard of the tensor will have a shape [3, 4];
            If `shard_spec=["y", "x"]`, each shard of the tensor will have a shape [2, 6];
            If `shard_spec=["x", None]`, each shard of the tensor will have a shape [3, 12];
            If `shard_spec=[None, "x"]`, each shard of the tensor will have a shape [6, 4];
            If `shard_spec=["y", None]`, each shard of the tensor will have a shape [2, 12];
            If `shard_spec=[None, "y"]`, each shard of the tensor will have a shape [6, 4];
            If `shard_spec=[None, None]`, each shard of the tensor will have a shape [6, 12];
    If the `shard_spec` is None, the tensor will be replicated across all the processes of `process_mesh`.
    In the above example, the `shard_spec=None` is same as 'shard_spec=[None, None]'. Defaults: None.

Returns:
    Tensor: the tensor `x` annotated with sharding information.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:DISTRIBUTED)
        >>> import paddle
        >>> from paddle.distributed.fleet import auto

        >>> mesh = auto.ProcessMesh([[0, 1], [2, 3]], dim_names=["x", "y"])
        >>> x = paddle.ones([4, 6])
        >>> shard_spec = ["x", "y"]
        >>> auto.shard_tensor(x, mesh, shard_spec)

Argument process_mesh " is not an instance of ProcessMeshKSpecify the process mesh argument or use ProcessMesh context manager first.zArgument shard_spec z is not an instance of listget_dim_nameszInvalid shard_spec at index z: 'z0' is not a valid dimension name in process_mesh .zFor tensor z, shard_spec z is invalid with tensor_shape z and process_mesh process_meshdims_mapping) 
isinstancer   r   r   liststrpaddlestaticdefault_main_programglobal_block_var_recursiver   serial_tensor	dist_attrr   typer   shapehasattrr   	dim_names	enumerate
ValueErrorr   namer   r   mark_annotatedr	   add_dist_tensor_for_programget_dist_tensor_for_programadd_process_mesh)
xr   
shard_specdist_tensorr   tensor_shape
valid_dimsidimdefault_dist_ctxs
             j/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/distributed/auto_parallel/interface.pyshard_tensorr5   "   so   R ,(8(899 	
$\N2TU	
9 01' 	
Y	
' j$'' 
zl*EF' !SMM..0\^^A 	

 (*'*--M)5&22$** |_55 &&('' 	
  
+FAsC((C,A 21#S >EEOLPQS 	 , !<HH 	
-,,-]:,Fdeqdr  sE  FR  ES  ST  U	
H .E.
* ,,^<,,^<6800=">>qAK%%l3H    c                   Ub!  [        U[        5      (       d   SU S35       eO[        5       nUc   S5       e/ nUb[  [        S U 5       5      (       d   SU S35       eU H3  nUb  UR	                  [        Xa5      5        M"  UR	                  S5        M5     / nUb[  [        S U 5       5      (       d   S	U S35       eU H3  nUb  UR	                  [        Xa5      5        M"  UR	                  S5        M5     [        XXWU5      n U $ )
a  
Shard an operation on a process mesh according to its input and output shard specification.

Args:
    op (Callable): a callable operator or module to be sharded.
    process_mesh (ProcessMesh, optional): An instance of ProcessMesh describes a mesh
        topology of the used logical processes where the op is sharded. All of its inputs and
        outputs are sharded by this process mesh. If it is None, the found current process mesh
        will be used. And an error will be raised if the current process mesh cannot be found.
        Default: None.
    in_shard_specs (list of list, optional): a list of list to describe the sharding specifications
        for the inputs. Each item of `in_shard_specs` is a `shard_spec` between the corresponding input
        and `process_mesh`. If one item is None, the corresponding input is replicated across all processes
        If it is None, all inputs are replicated across all processes. Note that the length of the
        `in_shard_specs` should be equal to the actual number of inputs when calling this operation.
        Default: None.
    out_shard_specs (list of list, optional): a list of list to describe the sharding specifications
        for the outputs. Each item of `out_shard_specs` is a `shard_spec` between the corresponding output
        and `process_mesh`. If one item is None, the corresponding output is replicated across all processes
        If it is None, all outputs are replicated across all processes. Note that the length of the
        `in_shard_specs` should be equal to the actual number of inputs when calling this operation.
        Default: None. Default: None.

Returns:
    Outputs of `op`, each of which is annotated with sharding information.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> from paddle.distributed.fleet import auto

        >>> x = paddle.ones([4, 6])
        >>> y = paddle.zeros([4, 6])
        >>> mesh = auto.ProcessMesh([[0, 1], [2, 3]], dim_names=["x", "y"])
        >>> dist_add = auto.shard_op(paddle.add,
        ...                          mesh,
        ...                          in_shard_specs=[["x", "y"], ["y", None]],
        ...                          out_shard_specs=[[None, "x"]])
        >>> dist_add(x, y)

Nr   r   r   c              3  X   #    U  H   n[        U[        5      =(       d    US L v   M"     g 7fNr   r   .0r-   s     r4   	<genexpr>shard_op.<locals>.<genexpr>   s+      
,
 
D)?Z4-??,   (*zin_shard_spec z is not a list of list or Nonec              3  X   #    U  H   n[        U[        5      =(       d    US L v   M"     g 7fr9   r:   r;   s     r4   r=   r>      s+      
-
 
D)?Z4-??-r?   zout_shard_spec )r   r   r   allappendr   r
   )opr   in_shard_specsout_shard_specskwargsin_dims_mappingsr-   out_dims_mappingss           r4   shard_oprI      so   \ ,44 	
$\N2TU	
4 01' 	
Y	
' ! 
,
 
 
 	K N++IJ	K 
 )J% ''+JE !''- ) " 
-
 
 
 	M _--KL	M 
 *J%!((+JE "((. * 
#
*v
B Ir6   c                8    [         S-  q  " S S5      nU" U 5      $ )Nr   c                       \ rS rSrS rS rSrg)$recompute.<locals>.RecomputeOperator   c                    Xl         g r9   _op)selfrC   s     r4   __init__-recompute.<locals>.RecomputeOperator.__init__   s    Hr6   c                X   [         R                  R                  5       R                  5       n[	        UR
                  5      n[         R                  R                  S[         35         [         R                  R                  R                  R                  5       (       aD  [         R                  R                  R                  R                  U R                  5      " U0 UD6nOU R                  " U0 UD6nS S S 5        [         R                   R#                  5       (       ax  [         R                  R                  5       R                  5       n[	        UR
                  5      n[%        XF5       H(  nUR
                  U   nUR'                  S[        5        M*     W$ ! , (       d  f       N= f)Nz/auto_parallel/rc_fwd_recompute_id)r   r   r   r   lenops
name_scope_g_recompute_idxbasedygraphin_to_static_modejit	dy2staticconvert_call_funcconvert_callrQ   	frameworkin_pir_moderangeset_int_attr)	rR   argsrF   blockrc_begin_idoutput	rc_end_ididxrc_ops	            r4   __call__-recompute.<locals>.RecomputeOperator.__call__   s<   MM668EEGEeii.K))$%5$67 ;;&&++==??

,,>>KK HH+#)+  "XXt6v6F ++--::<IIK		N	 8C!IIcNE&&'9;KL 9 M' s   (BF
F)rP   N__name__
__module____qualname____firstlineno__rS   rm   __static_attributes__ r6   r4   RecomputeOperatorrM      s    		r6   rv   )rZ   )rC   rv   s     r4   	recomputerw      s$     : R  r6   c                &     " S S5      nU" U 5      $ )z
Exclude some operators in recompute segments.
    Args:
    run_function (callable): The callable function to be excluded.

Returns:
    ExcludeOperator: The callable object.

c                       \ rS rSrS rS rSrg)1exclude_ops_in_recompute.<locals>.ExcludeOperatori  c                    Xl         g r9   _run_function)rR   run_functions     r4   rS   :exclude_ops_in_recompute.<locals>.ExcludeOperator.__init__  s    !-r6   c                   [         R                  R                  S5         [         R                  R                  R                  R                  5       (       aD  [         R                  R                  R                  R                  U R                  5      " U0 UD6nOU R                  " U0 UD6nS S S 5        U$ ! , (       d  f       W$ = f)Nz/exclude_rc)r   r   rY   r[   r\   r]   r^   r_   r`   ra   r}   )rR   rf   rF   ri   s       r4   rm   :exclude_ops_in_recompute.<locals>.ExcludeOperator.__call__  s    ))-8;;&&++==??

,,>>KK ..+#)+  "//@@F 9 M 98 Ms   BB88
Cr|   Nro   ru   r6   r4   ExcludeOperatorrz     s    	.	r6   r   ru   )r~   r   s     r4   exclude_ops_in_recomputer     s     " <((r6   c                      \ rS rSrSrSrSrg)CollectionNamesi%  fetchesloggingru   N)rp   rq   rr   rs   FETCHESLOGGINGrt   ru   r6   r4   r   r   %  s    GGr6   r   c                \    [         R                  U S 5      nUc  / nU[         U '   [         U    $ r9   )_g_collectionsget)r'   
collections     r4   get_collectionr   *  s4    ##D$/J
)t$r6   c                    U [         ;  a	  / [         U '   Ub3  [         U     H  u  p4XA:X  d  M    g    [         U    R                  X!45        g [         U     H  u  p4XA:X  d  M    g    [         U    R                  S U45        g r9   )r   rB   )collection_namevaluer'   _vs        r4   add_to_collectionr   2  s|    n,*,'"?3DAz 4 	'..}="?3DAz 4 	'..e}=r6   c                H   [        U [        R                  R                  5      (       a  U R                  n O0[        U [
        5      (       a  U n O[        S[        U 5       S35      e[        [        R                  X5        U(       a  [        [        R                  X5        g g )NzDOnly support fetch `Variable` or `str`[`Variable`'s name], but got ``)r   r   r   Variabler'   r   	TypeErrorr!   r   r   r   r   )tensorr'   r   s      r4   fetchr   A  s    &&--0011	FC	 	 RSWX^S_R``ab
 	
 o--v</116@ r6   c                     [         $ )ar  
Get the global mesh set by set_mesh.

Returns:
    mesh (paddle.distributed.ProcessMesh): the global mesh.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.distributed as dist
        >>> mesh = dist.ProcessMesh([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dim_names=["dp", "mp", "pp"])
        >>> # doctest: +REQUIRES(env:DISTRIBUTED)
        >>> dist.auto_parallel.set_mesh(mesh)
        >>> mesh = dist.auto_parallel.get_mesh()
        >>> # This case need to be executed in multi-card environment
        >>> # python -m paddle.distributed.launch --gpus=0,1,2,3,4,5,6,7 {test_case}.py
_g_meshru   r6   r4   get_meshr   R  s	    ( Nr6   c                    U q g)aG  
Set the global mesh.

Args:
    mesh (paddle.distributed.ProcessMesh): global mesh to be set.

Returns:
    None

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.distributed as dist
        >>> mesh = dist.ProcessMesh([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dim_names=["dp", "mp", "pp"])
        >>> # doctest: +REQUIRES(env:DISTRIBUTED)
        >>> dist.auto_parallel.set_mesh(mesh)
        >>> # This case need to be executed in multi-card environment
        >>> # python -m paddle.distributed.launch --gpus=0,1,2,3,4,5,6,7 {test_case}.py
Nr   )meshs    r4   set_meshr   i  s	    , Gr6   c                    U  Vs/ s H  oS   PM	     nnU  Vs/ s H  oS   PM	     nn[         R                  " S[        S US5      5      R                  U5      n[	        XB5      q[
        $ s  snf s  snf )z
Create a global process_mesh for auto parallel.

Args:
    mesh_dims (list[tuple[str, int]]): A list of tuple, each element is (dim_name, dim_degree).
r   r   c                
    X-  $ r9   ru   )r,   ys     r4   <lambda>create_mesh.<locals>.<lambda>  s    r6   )nparanger   reshaper   r   )	mesh_dimsmesh_dimr$   
mesh_shapemesh_arrs        r4   create_meshr     sq     .77Y!YI7.78i(1+iJ8yyF#5z1EFNNH (.GN 88s
   A,A1)NN)NNNr9   )NF)returnpaddle.distributed.ProcessMesh)r   r   r   None)r   zlist[tuple[str, int]])$
__future__r   	functoolsr   numpyr   r   paddle.frameworkr   r   r   r   static.dist_contextr	   static.dist_opr
   static.dist_tensorr   static.utilsr   r   r   r5   rI   rZ   rw   r   r   r   r   r   r   r   r   r   r   ru   r6   r4   <module>r      s    #    ! ? @ 5 1 `H AETn  !!H)>  
 >A .2r6   