
    ͑i                      S SK Jr  S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	r	S SK
r
S SKrS SKrS SKrS SKJr  S SKJ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rSS	KJ r   S
SKJ!r!J"r"  S
SK#J$r$  S
SK%J&r&J'r'  S
SK(J)r)J*r*  S
SK+J,r,J-r-  \" S5      r.\" S5      r/\(       a  S SKJ0r0J1r1  S SK2J3r3  / r4\!Rj                  " 5       r6\!Rn                  " 5       r8\!Rr                  " 5       r:\!Rv                  " 5       r<\!Rz                  " 5       r>\!R~                  " 5       r@0 SSS/_SSS/_SSS/_SSS/_SSS/_SSS/_SSS/_SSS/_SSS/_SSS/_S SS/_S!SS/_S"SS/_S#SS/_S$SS/_S%SS/_S&SS/_0 S'SS/_S(SS/_S)SS/_S*SS/_S+SS/_S,SS/_S-SS/_S.SS/_S/SS/_S0SS/_S1SS/_S2SS/_S3SS/_S4SS/_S5SS/_S6SS/_S7SS/_ESS/S8S9/S:S;/S:S;/S<.ErA/ S=QrBS> rCSS? jrDSS@ jrE\SA 5       rF " SB SC\R                  5      rHSqI\H" 5       rJSqKSqLS qMSqNSrOSDqP0 SSESF0/_SSESF0/_SSESF0/_SSESF0/_S1SESF0/_S3SESF0/_S SESF0/_S5SESF0/_SSESF0/_S&SESF0/_S'SESF0/_S(SESF0/_S)SESF0/_S$SESF0/_S%SESF0/_SGSHSD0/_SISHSD0/_SHSD0/SHSD0/SHSD0/SHSD0/SHSD0/SHSD0/SHSD0/SHSD0/SJ.ErQSK/SL/SM/SN/SO/SP/SQ/SR/SS/ST.	rR\$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  \$R                  \!R                  R                  R                  0rjSSU jrkSSV jrlSSW jrmSSX jrnSSY jroSSZ jrpSS[ jrqSFqrSFqsS\rtS]ru\, S     SS^ jj5       rv\ S       SS_ jj5       rw\ S       SS` jj5       rwSSa jrwSSSb jjrx    SSc jrySSd jrz    SSe jr{SSf jr|Sg r}    SSh jr~    SSi jr\-" \y5      r\-" \z5      r\-" \|5      r\-" \~5      r\-" \{5      rSj rSk rSl rSm rSn rSo rSp rSq rSr rSSs jrSSt jrSSu jrSSv jrSSw jrSSx jr S   SSy jjrSSSz jjrSSS{ jjr S   SS| jjr S   SS} jjr " S~ S5      r\" 5       q\,SSS jj5       r " S S5      r\" 5       q\,SS j5       rS rS rS rS r    SS jr    SS jrS rS rSS jr\!R                  R                  GRP                  SSSS4S jrS rS rS rS rS r " S S\5      r " S S\5      r " S S\S9rS r " S S5      r " S S5      r\,S 5       rS rS r " S S5      r0 0 4S jr " S S5      r " S S\5      r " S S\5      r " S S5      r " S S5      r " S S\\S9r " S S\!GR                  GR                  5      r\" 5       q\" 5       qSG[        l        SS jrSS jrSS jrSS jr\, S     SS jj5       rSS jr\,S 5       r\,S 5       r\,S 5       rS r\,SSS jj5       rS rS rS rS rS rS r\,S 5       r\,SS j5       r\,SS j5       r\,SS j5       r\,SS j5       r\,SS j5       rg)    )annotationsN)Iterable)contextmanager)FunctionType
MethodType)TYPE_CHECKINGCallableTypeVaroverload)	ParamSpec   )pir   )coreunique_name)DataType)data_feed_pb2framework_pb2)_getitem_static_setitem_static)signature_safe_contextmanagerwrap_decorator_InputT_RetT)	GeneratorSequence)
AmpOptionselementwise_addXYelementwise_add_gradelementwise_subelementwise_sub_gradelementwise_mulelementwise_mul_gradelementwise_divelementwise_div_gradelementwise_floordivelementwise_floordiv_gradelementwise_powelementwise_pow_gradwhere
where_gradequal	not_equal	less_than
less_equalgreater_thangreater_equallogical_and
logical_orlogical_xorelementwise_fmaxelementwise_fmax_gradelementwise_fminelementwise_fmin_gradelementwise_maxelementwise_max_gradelementwise_minelementwise_min_gradelementwise_modelementwise_mod_grad
huber_lossxyX1X2)huber_loss_grad	nextafteratan2
atan2_grad)zpd_op.slicezpd_op.strided_slicezpd_op.index_selectzpd_op.splitzpd_op.unsqueezezpd_op.unsqueeze2zpd_op.squeezezpd_op.squeeze2zpd_op.transposezpd_op.transpose2zpd_op.unbindzpd_op.diagonalzpd_op.flattenz
pd_op.imagz
pd_op.realzpd_op.reshapezpd_op.reshape2zpd_op.as_realc                     [         $ N)_global_flags_     U/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/base/framework.py_global_flagsrP      s    rN   c                |   [        U [        5      (       d  [        S5      eU R                  5        H  u  p[	        5       R                  U5      (       aX  U[	        5       U'   SnUR                  U5      (       a1  [	        5       R                  U[        U5      S [        U5      5        My  M{  [        SU S35      e   g)a6  
This function sets the GFlags value in Paddle.
For FLAGS please refer to :ref:`en_guides_flags_flags`

Args:
    flags (dict): A dict contains flags and its value.

Examples:
        .. code-block:: python

            >>> import paddle
            >>> paddle.set_flags({'FLAGS_eager_delete_tensor_gb': 1.0})
z#flags in set_flags should be a dictFLAGS_NFlag z, cannot set its value through this function.)
isinstancedict	TypeErroritemsrP   	is_public
startswithupdate_linked_varslenstr
ValueError)flagskeyvalueprefixs       rO   	set_flagsrb      s     eT""=>>kkm
?$$S))#(MOC F~~f%%22F&E
 &
 uHI  $rN   c                   0 n[        U [        [        45      (       aY  U  HQ  n[        5       R	                  U5      (       a#  [        5       U   nX#0nUR                  U5        MD  [        SU S35      e   U$ [        U [        5      (       aP  [        5       R	                  U 5      (       a#  [        5       U    nX0nUR                  U5        U$ [        SU  S35      e[        S5      e)a  
This function gets the GFlags value in Paddle.
For FLAGS please refer to :ref:`en_guides_flags_flags`

Args:
    flags(list|tuple|str): A list/tuple of string or a string which is the flag's name.

Returns:
    flag's value in Paddle.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> flags = ['FLAGS_eager_delete_tensor_gb', 'FLAGS_check_nan_inf']
        >>> res = paddle.get_flags(flags)
        >>> print(res)
        {'FLAGS_eager_delete_tensor_gb': 0.0, 'FLAGS_check_nan_inf': False}
rS   z, cannot get its value through this function.z5Flags in get_flags should be a list, tuple or string.)	rT   listtuplerP   rX   updater]   r\   rV   )r^   flags_valuer_   r`   temps        rO   	get_flagsri      s    * K%$''C((--%,|""4( C5 LM  (  
E3		?$$U++!OE*E>Dt$  wJK  OPPrN   c              #     #    [         R                  " U 5      U    n[         R                  " X05         S v   [         R                  " X05        g ! [         R                  " X05        f = f7frK   )paddleri   rb   )	flag_name
flag_value	old_values      rO   
flag_guardro      sU       +I6I
i,-1)/0)/0s   1A,A A,A))A,c                  &    \ rS rSrS rS rS rSrg)GlobalThreadLocal   c                    SU l         SU l        [        U l        [        R                  R                  S5      nUb   UR                  5       S;  n[        SU05        [        S5      S   U l	        g)zW
init the thread local data.
TODO(xiongkun): how to access another thread local data ?
FNFLAGS_enable_pir_api)nnoffalseoff0)
_in_to_static_mode_#_functional_dygraph_context_manager_dygraph_tracer_osenvirongetlowerrb   ri   _use_pir_api_)selfenv_pir_enabledpir_enableds      rO   __init__GlobalThreadLocal.__init__   ss     $) 370 0**..)?@&)//1 : K -{;<&'=>"
rN   c                   / nUR                  S[        U R                  5      -   5        UR                  S[        U R                  5      -   5        UR                  S[        U R                  5      -   5        SR                  U5      $ )Nz_in_to_static_mode_:z$_functional_dygraph_context_manager:z_dygraph_tracer_:
)appendr\   r{   r|   r}   join)r   stringss     rO   __str__GlobalThreadLocal.__str__   st    -D4L4L0MMN2$::;<	
 	*S1F1F-GGHyy!!rN   c                \    US:X  a  Uq [        R                  " U5        X R                  U'   g )Nr}   )r}   r   _switch_tracer__dict__r   namevals      rO   __setattr__GlobalThreadLocal.__setattr__   s+    %%"$!drN   )r}   r|   r{   r   N)__name__
__module____qualname____firstlineno__r   r   r   __static_attributes__rM   rN   rO   rq   rq      s    
2""rN   rq   Faxisamax
reduce_allamin)anyfrobenius_norm	logsumexp
reduce_max
reduce_minreduce_meanreduce_prod
reduce_sum	overwriteflag_buffer_hashtableflag_perm_buffer	thresholdbetaremote_prefetchglobal_poolingdiag_num	is_sorted)	gathergraph_reindexgraph_sample_neighborsrelu6swishhsigmoid_lossmax_pool2d_with_indexuniformuniquec                 &    [         R                  SL$ )a:  

.. note::
    Dynamic graph mode is turn ON by default since paddle 2.0.0

This API checks whether paddle runs in dynamic graph mode.

You can turn ON static graph mode by `enable_static <../dygraph/base/disable_dygraph_en.html>`_ ,
and turn OFF static graph mode by `disable_static <../dygraph/base/enable_dygraph_en.html>`_  .

Returns:
    bool: Whether paddle runs in dynamic graph mode.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> print(paddle.in_dynamic_mode())  # dynamic mode is turn ON by default since paddle 2.0.
        True

        >>> paddle.enable_static()
        >>> print(paddle.in_dynamic_mode())  # Now we are in static graph mode
        False

        >>> paddle.disable_static()
        >>> print(paddle.in_dynamic_mode())  # Now we are in dynamic mode
        True

N
global_varr}   rM   rN   rO   in_dygraph_moder   O  s    < &&d22rN   c                 N    [         R                  =(       a    [        5       (       + $ )a  

This API checks whether paddle runs in static graph mode and use pir api.

Returns:
    bool: Whether paddle runs in static graph mode and use pir api.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> print(paddle.framework.in_pir_mode())
        False

        >>> paddle.enable_static()
        >>> with paddle.pir_utils.IrGuard():
        ...     print(paddle.framework.in_pir_mode())
        True

)r   r   r   rM   rN   rO   in_pir_moder   p  s    , ##=O,=(==rN   c                 "    [         R                  $ rK   )r   r   rM   rN   rO   use_pir_apir     s    ###rN   c                 T    [         R                  SL=(       d    [         R                  $ )a
  

This API checks whether paddle runs in dynamic graph or pir mode.

Returns:
    bool: Whether paddle runs in static graph mode and use pir api.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> print(paddle.framework.in_dynamic_or_pir_mode())
        True

        >>> paddle.enable_static()
        >>> print(paddle.framework.in_dynamic_or_pir_mode())
        False

        >>> with paddle.pir_utils.IrGuard():
        ...     print(paddle.framework.in_dynamic_or_pir_mode())
        True

N)r   r}   r   rM   rN   rO   in_dynamic_or_pir_moder     s     2 &&d2Nj6N6NNrN   c                 x    [        [        R                  R                  S5      5      R	                  5       n U S;   $ )z{

This API checks whether paddle runs in pir executor mode.

Returns:
    bool: Whether paddle runs in pir executor mode.

FLAGS_enable_pir_in_executor)true1)r\   r~   r   r   r   )flags    rO   in_pir_executor_moder     s0     rzz~~<=>DDFD=  rN   c                 X    Sn [        5       (       d  g[        R                  " U 5      U    $ )zk

This API checks whether paddle runs in cinn mode.

Returns:
    bool: Whether paddle runs in cinn mode.

FLAGS_use_cinnFis_compiled_with_cinnrk   ri   )CINN_FLAG_NAMEs    rO   in_cinn_moder     s+     &N ""N+N;;rN   c                 X    Sn [        5       (       d  g[        R                  " U 5      U    $ )NFLAGS_cinn_debugFr   )CINN_DEBUG_FLAG_NAMEs    rO   in_cinn_debug_moder     s,    - ""012FGGrN   	ipu_index	ipu_stagec              #     #    [         R                  " 5       (       d  [        S5      e[        n[        nU qUq Sv   UqUqg! UqUqf = f7f)a  
Used to shard the graph on IPUs. Set each Op run on which IPU in the sharding and which stage in the pipelining.

Args:
    index(int, optional): Specify which ipu the Tensor is computed on, (such as '0, 1, 2, 3').
        The default value is -1, which means the Op only run on IPU 0.
    stage(int, optional): Specify the computation order of the sharded model(such as '0, 1, 2, 3').
        The sharded model will be computed from small to large. The default value is -1,
        which means no pipelining computation order and run Ops in terms of graph.

Note:
    Only if the enable_manual_shard=True, the 'index' is able to be set not -1. Please refer
    to :ref:`api_paddle_static_IpuStrategy`.
    Only if the enable_pipelining=True, the 'stage' is able to be set not -1. Please refer
    to :ref:`api_paddle_static_IpuStrategy`.
    A index is allowed to match none stage or a stage. A stage is only allowed to match a new or
    duplicated index.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)
        >>> import paddle
        >>> paddle.device.set_device('ipu')
        >>> paddle.enable_static()
        >>> a = paddle.static.data(name='data', shape=[None, 1], dtype='int32')
        >>> with paddle.static.ipu_shard_guard(index=0, stage=0):
        ...     b = a + 1
        >>> with paddle.static.ipu_shard_guard(index=1, stage=1):
        ...     c = b + 1
        >>> with paddle.static.ipu_shard_guard(index=0, stage=2):
        ...     d = c + 1
zECan not use this function since PaddlePaddle is not compiled with IPUN)r   is_compiled_with_ipur]   global_ipu_indexglobal_ipu_stage)indexstageprev_ipu_indexprev_ipu_stages       rO   ipu_shard_guardr     sb     J $$&&S
 	
 &N%N*)) *)s   6AA AAAc                    g rK   rM   	call_funcr   r   s      rO   set_ipu_shardr     s      #rN   c                    g rK   rM   r   s      rO   r   r     s     rN   c                   ^^ SUU4S jjnSSK Jn  [        X5      (       d#  [        U 5      (       a  U" U 5      $ [	        S5      e " UU4S jS[        U 5      5      n[        U 5      R                  Ul        XPl        U $ )a  
Shard the ipu with the given call function. Set every ops in call function to the given ipu sharding.

Note:
    Only when enable_manual_shard=True to set the index to a value other than -1. please refer to :ref:`api_paddle_static_IpuStrategy` .
    Only when enable_pipelining=True to set stage to a value other than -1. please refer to :ref:`api_paddle_static_IpuStrategy` .
    An index supports a corresponding None stage or a stage, and a stage only supports a new index or a duplicate index.

Args:
    call_func(Layer|function): Specify the call function to be wrapped.
    index(int, optional): Specify which ipu the Tensor is computed on, (such as '0, 1, 2, 3').
        The default value is -1, which means the Op only run on IPU 0.
    stage(int, optional): Specify the computation order of the sharded model(such as '0, 1, 2, 3').
        The sharded model will be computed from small to large. The default value is -1,
        which means no pipelining computation order and run Ops in terms of graph.

Returns:
    The wrapped call function.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)
        >>> import paddle
        >>> paddle.device.set_device('ipu')
        >>> paddle.enable_static()
        >>> a = paddle.static.data(name='data', shape=[None, 1], dtype='float32')
        >>> relu = paddle.nn.ReLU()
        >>> relu = paddle.static.set_ipu_shard(relu, index=1, stage=1)
        >>> relu(a)
c                   >^  SU UU4S jjnU$ )Nc                 ^   > [        TTS9   T" U 0 UD6sS S S 5        $ ! , (       d  f       g = fN)r   r   )r   )argskwargsfuncr   r   s     rO   wrapper0set_ipu_shard.<locals>.decorate.<locals>.wrapper9  s&     uE:T,V, ;::s   
,r   z_InputT.argsr   z_InputT.kwargsreturnr   rM   )r   r   r   r   s   ` rO   decorateset_ipu_shard.<locals>.decorate8  s    	- 	- rN   r   )Layerz:Unsupported type. Only accept paddle.nn.Layer or function.c                  .   >^  \ rS rSrU UU4S jrSrU =r$ )set_ipu_shard.<locals>.BlockFniJ  c                n   > [        TTS9   [        TU ]  " U0 UD6sS S S 5        $ ! , (       d  f       g = fr   )r   super__call__)r   r   r   	__class__r   r   s      rO   r   'set_ipu_shard.<locals>.BlockFn.__call__K  s+     uE:w'88 ;::s   &
4rM   )r   r   r   r   r   r   __classcell__)r   r   r   s   @rO   BlockFnr   J  s    	9 	9rN   r   r   Callable[_InputT, _RetT]r   r   )	paddle.nnr   rT   callablerV   typer   r   )r   r   r   r   r   r   s    ``   rO   r   r     sy    B   i''II&&L 
9 9$y/ 9
 I//G!rN   c           	     "   [        U [        5      (       d  [        S[        U 5       S35      e[        U[        [        S5      45      (       d  [        S[        U5       S35      e[        R
                  " SU 5      nUb  UR                  5       U :w  a  [        SU  35      eUb<  [        R
                  " SU5      nUb  UR                  5       U:w  a  [        SU 35      e[        R                  R                  [        R                  R                  [        R                  R                  [        R                  R                  /n/ SQnS	 nU" X45      S
:X  ar  Ub9  [        R                  " SU  SU S[        R                  R                    S35        g[        R                  " SU  S[        R                  R                    S35        gU R#                  S5      nXd[%        U5      S -   nUbg  UR#                  S5      nX[%        U5      S -   n	U" X95      S
:  d  U" X75      S
:  a-  ['        SU  SU S[        R                  R                    S35      egU" X75      S
:  a-  ['        SU  S[        R                  R                    SU  S35      eg)a  
Check if the installed version of PaddlePaddle is in [min_version, max_version],
if the installed version is lower than ``min_version`` or higher than ``max_version``,
an exception will be thrown, NO returns if the installed version is satisfied.

Args:
    min_version (str): the minimum version required (like '1.4.0').
    max_version (str, optional): the max version required (like '1.6.0'), default is None,
        meaning any version equal or higher than ``min_version`` is acceptable.

Returns:
    None.

Raises:
    TypeError: if the type of ``min_version`` is not str.
    TypeError: if the type of ``max_version`` is not str or type(None).
    ValueError: if the value of ``min_version`` is not in version format.
    ValueError: if the value of ``max_version`` is not in version format or None.
    Exception: if the installed version is lower than ``min_version`` or higher than ``max_version``.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> # any version >= 0.1.0 is acceptable.
        >>> paddle.utils.require_version('0.1.0')

        >>> # if 0.1.0 <= version <= 10.0.0, it is acceptable.
        >>> paddle.utils.require_version(min_version='0.1.0', max_version='10.0.0')
zGThe type of 'min_version' in require_version must be str, but received .NzUThe type of 'max_version' in require_version must be str or type(None), but received z\d+(\.\d+){0,3}zpThe value of 'min_version' in require_version must be in format '\d+(\.\d+){0,3}', like '1.5.2.0', but received zpThe value of 'max_version' in require_version must be in format '\d+(\.\d+){0,3}', like '1.5.2.0', but received )rz   rz   rz   rz   c                    [        [        U 5      5       H?  n[        X   5      [        X   5      :  a    g[        X   5      [        X   5      :  d  M?    g   g)Nr   r   r   )ranger[   int)ver_aver_bis      rO   version_cmp$require_version.<locals>.version_cmp  sH    s5z"A58}s58},UXUX.	 #
 rN   r   zPaddlePaddle version in [, z] required, but zg installed. Maybe you are using a develop version, please make sure the version is good with your code.zPaddlePaddle version z or higher is required, but zg installed, Maybe you are using a develop version, please make sure the version is good with your code.z'VersionError: PaddlePaddle version in [z installed.z#VersionError: PaddlePaddle version z0 installed, please upgrade your PaddlePaddle to z or other higher version.)rT   r\   rV   r   rematchgroupr]   rk   versionmajorminorpatchrcwarningswarnfull_versionsplitr[   	Exception)
min_versionmax_versioncheck_formatversion_installedzero_versionr	  min_version_splitmin_version_to_checkmax_version_splitmax_version_to_checks
             rO   require_versionr"  T  s   @ k3''UVZ[fVgUhhij
 	
 kCd#455cdhitducvvwx
 	
 88.<L|113{B,,7=:
 	

 xx 2K@<#5#5#7;#F00;}>  		 (L $3q8"MM+K=;-GWX^XfXfXsXsWt uG G 	 MM'}4PQWQ_Q_QlQlPm nG G
 	#))#.->)?)ABB  '--c2S1B-C-E FF 	
 )@1D,CaG9+bUeflftft  gB  gB  fC  CN  O  H (?!C5k]B^_e_m_m_z_z^{ |77BmC\^  DrN   c                   ^  SU 4S jjnU$ )Nc                 \   > [        5       (       a   STR                   S35       eT" U 0 UD6$ )NzWe don't support z in dynamic graph moder   r   r   r   r   s     rO   __impl__'_dygraph_not_support_.<locals>.__impl__  s<    "$$ 	
.DE	
$ T$V$$rN   r   rM   r   r'  s   ` rO   _dygraph_not_support_r*    s    % OrN   c                   ^  SU 4S jjnU$ )Nc                 \   > [        5       (       d   STR                   S35       eT" U 0 UD6$ )NWe only support ']()' in dynamic graph mode, please call 'paddle.disable_static()' to enter dynamic graph mode.r%  r&  s     rO   r'   _dygraph_only_.<locals>.__impl__  sB       	
  /L  M	
  T$V$$rN   r   rM   r)  s   ` rO   _dygraph_only_r0        % OrN   c                   ^  SU 4S jjnU$ )Nc                    > SSK Jn  [        5       (       d!  U" 5       (       d   STR                   S35       eT" U 0 UD6$ )Nr   in_to_static_moder-  r.  )dygraph.baser5  r   r   )r   r   r5  r   s      rO   r'  #_non_static_only_.<locals>.__impl__  sN    3  $5$7$7 	
  /L  M	
7 T$V$$rN   r   rM   r)  s   ` rO   _non_static_only_r8    s    % OrN   c                   ^  SU 4S jjnU$ )Nc                 \   > [        5       (       a   STR                   S35       eT" U 0 UD6$ )NzDIn PaddlePaddle 2.x, we turn on dynamic graph mode by default, and 'z()' is only supported in static graph mode. So if you want to use this api, please call 'paddle.enable_static()' before this api to enter static graph mode.r%  r&  s     rO   r'  _static_only_.<locals>.__impl__  sG    "$$ 	
RSWS`S`Ra  b~  	
$ T$V$$rN   r   rM   r)  s   ` rO   _static_only_r<    r1  rN   c                    U q g rK   )_current_pipeline_stage)r   s    rO   _set_pipeline_stager?    s    #rN   c                   ^  SU 4S jjnU$ )Nc                 P   > [        STR                   STR                   S35      e)N'a  ' only can be called by `paddle.Tensor` in dynamic graph mode. Suggestions:
  1. If you are in static graph mode, you can switch to dynamic graph mode by turning off `paddle.enable_static()` or calling `paddle.disable_static()`.
  2. If you are using `@paddle.jit.to_static`, you can call `paddle.jit.enable_to_static(False)`. If you have to translate dynamic graph to static graph, please use other API to replace 'z'.)AssertionErrorr   r&  s     rO   r'  '_fake_interface_only_.<locals>.__impl__  s:     h imhuhugvvxz
 	
rN   r   rM   r)  s   ` rO   _fake_interface_only_rE     s    
 OrN   c                J   ^  [         R                  " T 5      SU 4S jj5       nU$ )Nc                    > SU;   a4  [         R                  " S[        5        US   US'   UR                  S5        T" U 0 UD6$ )N	stat_dictzJThe argument `stat_dict` has deprecated, please change it to `state_dict`.
state_dict)r  r  DeprecationWarningpopr&  s     rO   r   $deprecate_stat_dict.<locals>.wrapper  sJ    & MM\" $*+#6F< JJ{#T$V$$rN   r   )	functoolswraps)r   r   s   ` rO   deprecate_stat_dictrO    s'     __T% % NrN   c                 "    [         R                  $ rK   r   rM   rN   rO   _dygraph_tracerrQ  +  s    &&&rN   c                    [         b!  [        [         5      [        R                  L Ga  [        R                  " 5       (       au   [        R
                  " 5       n U S:  a'  [        R                  " [        5       S   5      q [         $ [        R                  " S5        [        R                  " 5       q  [         $ [        R                  " 5       (       au   [        R                  " 5       n U S:  a'  [        R                  " [        5       S   5      q [         $ [        R                  " S5        [        R                  " 5       q  [         $ [!        [        R"                  " 5       5      S:  a  [        R"                  " 5       S   n [        R$                  " U5      n U S:  a)  [        R&                  " U[)        U5      S   5      q [         $ [        R                  " S5        [        R                  " 5       q  [         $ [        R                  " 5       q [         $ ! [         a  nSn  S nAGNS nAff = f! [         a  nSn  S nAGNXS nAff = f! [         a  nSn  S nANS nAff = f)Nr   zoYou are using GPU version Paddle, but your CUDA device is not set properly. CPU device will be used by default.znYou are using XPU version Paddle, but your XPU device is not set properly. CPU device will be used by default.z{You are using CUSTOM_DEVICE version Paddle, but your custom device is not set properly. CPU device will be used by default.)_global_expected_place_r   r   Placeis_compiled_with_cudaget_cuda_device_countr  	CUDAPlace	_cuda_idsr  r  CPUPlaceis_compiled_with_xpuget_xpu_device_countXPUPlace_xpu_idsr[   get_all_custom_device_typeget_custom_device_countCustomPlace_custom_device_ids)device_countedev_types      rO   _current_expected_place_re  /  s    	 ''(DJJ6%%''!#99; a*...Q*H'H #"E  F +/--/'> #"= &&((!#88: a*.--
1*F'0 #"-  E +/--/'& #"% 0023a7668;H!#;;HE a*.*:*:0:1=+' #"  R +/--/' #" '+mmo#""O  ! !  ! !  ! !sH   H H. I 
H+H&&H+.
I8I  I
IIIc                 ^    [        5       (       a  [        R                  " 5       $ [        5       $ rK   )r   r   rT  re  rM   rN   rO   _current_expected_placerg  b  s    }}zz|#%%rN   c                R    [         R                  b  U [         R                  l        g g rK   )r   r}   _expected_placeplaces    rO   "_set_dygraph_tracer_expected_placerl  h  s!    "".6;
##3 /rN   c                    U q [        U 5        g rK   rS  rl  rj  s    rO   _set_expected_placero  m  s    #&u-rN   c                    S[         R                  R                  5       ;  a  [        R                  " 5       S:  aL  [
        R                  R                  S[        R                  " 5        S[        R                  " 5        S35        [        S5      [         R                  S'   [         R                  R                  S5      n [        U 5      $ )NCPU_NUMr   a  !!! The CPU_NUM is not specified, you should set CPU_NUM in the environment variable list.
CPU_NUM indicates that how many CPUPlace are used in the current task.
And if this parameter are set as N (equal to the number of physical CPU core) the program may be faster.

export CPU_NUM=zD # for example, set CPU_NUM as number of physical CPU core which is z(.

!!! The default number of CPU_NUM=1.
)r~   r   keysmultiprocessing	cpu_countsysstderrwriter\   r   r  )cpu_nums    rO   _cpu_numry  s  s    

))$$&*JJ" #2";";"=!>  ?C  DS  D]  D]  D_  C` `99 !$A

9jjnnY'Gw<rN   c                     [         R                  " S5      n U (       a,  U R                  S5       Vs/ s H  n[        U5      PM     nnU$ [	        [
        R                  " 5       5      nU$ s  snf )NFLAGS_selected_gpus,)r~   getenvr  r  r  r   rV  )gpus_envs
device_idss      rO   rX  rX    s_    yy./H&.nnS&9:&9c!f&9
:  45578
 ;   A*c                     [         R                  " S5      n U (       a,  U R                  S5       Vs/ s H  n[        U5      PM     nnU$ [	        [
        R                  " 5       5      nU$ s  snf )NFLAGS_selected_xpusr|  )r~   r}  r  r  r  r   r[  )xpus_envr  r  s      rO   r]  r]    s_    yy./H&.nnS&9:&9c!f&9
:  44467
 ;r  c                    [         R                  " SU -   S-   5      nU(       a,  UR                  S5       Vs/ s H  n[        U5      PM     nnU$ [	        [
        R                  " U 5      5      nU$ s  snf )NFLAGS_selected_r  r|  )r~   r}  r  r  r  r   r_  )device_typecustom_devices_envr  r  s       rO   ra  ra    so    #4{#BS#HI&8&>&>s&CD&Cc!f&C
D  477DE
 Es   A1c                 ,    [         R                  " 5       $ )z
Whether this whl package can be used to run the model on XPU.

Returns (bool): support xpu or not.

Examples:
    .. code-block:: python

        >>> import paddle.base as base
        >>> support_xpu = base.is_compiled_with_xpu()
)r   rZ  rM   rN   rO   rZ  rZ    s     $$&&rN   c                 .    [         R                  " 5         g)aV  
Reset signal handler registered by Paddle.

Paddle installs signal handlers at C++ level to log debug information upon failing.
However, conflicts can happen if another python module is making use of such signal.
Such being the case, one may disable paddle signal handler via this interface.

Known frameworks that require disabling signal handler includes:
1. TVM
2. ADLIK

Make sure you called paddle.disable_signal_handler() before using above mentioned frameworks.

Returns:
    None

Examples:
    .. code-block:: python

        >>> import paddle
        >>> paddle.disable_signal_handler()
N)r   disable_signal_handlerrM   rN   rO   r  r    s    . 	!rN   c                 ,    [         R                  " 5       $ )a  
Whether this whl package can be used to run the model on CINN.

Returns:
    Bool: `True` if CINN is currently available, otherwise `False`.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> support_cinn = paddle.device.is_compiled_with_cinn()
)r   r   rM   rN   rO   r   r          %%''rN   c                 ,    [         R                  " 5       $ )a  
Whether this whl package can be used to run the model on GPU.

Returns:
    Bool: `True` if CUDA is currently available, otherwise `False`.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> support_gpu = paddle.device.is_compiled_with_cuda()
)r   rU  rM   rN   rO   rU  rU    r  rN   c                 ,    [         R                  " 5       $ )a*  
Whether this whl package can be used to run the model with distribute.

Returns:
    Bool: `True` if distribute is currently available, otherwise `False`.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> support_distribute = paddle.device.is_compiled_with_distribute()
)r   is_compiled_with_distributerM   rN   rO   r  r    s     ++--rN   c                 ,    [         R                  " 5       $ )a!  
Whether this whl package can be used to run the model on AMD or Hygon GPU(ROCm).

Returns:
    Bool: `True` if ROCm is currently available, otherwise `False`.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> support_gpu = paddle.device.is_compiled_with_rocm()
)r   is_compiled_with_rocmrM   rN   rO   r  r    r  rN   c                    [         R                  " 5       (       d   S5       eU c  [        5       n O[        U [        [
        45      (       d  U /n U  Vs/ s H  n[         R                  " U5      PM     sn$ s  snf )a,  
Note:
    For multi-card tasks, please use `FLAGS_selected_gpus` environment variable to set the visible GPU device.
    The next version will fix the problem with `CUDA_VISIBLE_DEVICES` environment variable.

This function creates a list of :code:`paddle.CUDAPlace` objects.

If :code:`device_ids` is None, environment variable of
:code:`FLAGS_selected_gpus` would be checked first. For example, if
:code:`FLAGS_selected_gpus=0,1,2`, the returned list would
be [paddle.CUDAPlace(0), paddle.CUDAPlace(1), paddle.CUDAPlace(2)].
If :code:`FLAGS_selected_gpus` is not set, all visible
gpu places would be returned according to the :code:`CUDA_VISIBLE_DEVICES` environment variable.

If :code:`device_ids` is not None, it should be the device
ids of GPUs. For example, if :code:`device_ids=[0,1,2]`,
the returned list would be
[paddle.CUDAPlace(0), paddle.CUDAPlace(1), paddle.CUDAPlace(2)].

Parameters:
    device_ids (list|tuple, optional): A list/tuple of int of GPU device ids.

Returns:
    list of paddle.CUDAPlace: Created GPU place list.

Examples:

    .. code-block:: python

        >>> # doctest: +REQUIRES(env:GPU)
        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.device.set_device('gpu')
        >>> paddle.enable_static()

        >>> cuda_places = static.cuda_places()

Not compiled with CUDA)r   rU  rX  rT   rd   re   rW  r  dev_ids     rO   cuda_placesr    sf    T %%''A)AA'[

T5M22 \
1;<vDNN6"<<<    A5c                    [         R                  " 5       (       d   S5       eU c  [        5       n O[        U [        [
        45      (       d  U /n U  Vs/ s H  n[         R                  " U5      PM     sn$ s  snf )a  
**Note**:
    For multi-card tasks, please use `FLAGS_selected_xpus` environment variable to set the visible XPU device.
    This function creates a list of :code:`paddle.XPUPlace` objects.
    If :code:`device_ids` is None, environment variable of
    :code:`FLAGS_selected_xpus` would be checked first. For example, if
    :code:`FLAGS_selected_xpus=0,1,2`, the returned list would
    be [paddle.XPUPlace(0), paddle.XPUPlace(1), paddle.XPUPlace(2)].
    If :code:`FLAGS_selected_xpus` is not set, all visible
    xpu places would be returned.
    If :code:`device_ids` is not None, it should be the device
    ids of XPUs. For example, if :code:`device_ids=[0,1,2]`,
    the returned list would be
    [paddle.XPUPlace(0), paddle.XPUPlace(1), paddle.XPUPlace(2)].

Parameters:
    device_ids (list or tuple of int, optional): list of XPU device ids.
Returns:
    list of paddle.XPUPlace: Created XPU place list.
Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:XPU)
        >>> import paddle
        >>> import paddle.static as static
        >>> paddle.device.set_device('xpu')

        >>> paddle.enable_static()
        >>> xpu_places = static.xpu_places()
zNot compiled with XPU)r   rZ  r]  rT   rd   re   r\  r  s     rO   
xpu_placesr  8  se    > $$&&?(??&Z

T5M22 \
0:;
fDMM&!
;;;r  c                N    U c
  [        5       n [        R                  " 5       /U -  $ )a  
This function creates a list of :code:`paddle.CPUPlace` objects, and returns the created list.

If :code:`device_count` is None, the device count would
be determined by environment variable :code:`CPU_NUM`.
If :code:`CPU_NUM` is not set, the default value is 1,
i.e. CPU_NUM=1.
:code:`CPU_NUM` indicates the number of devices used in the current task.
The running of the program can be accelerated if :code:`CPU_NUM` is the same as the number of physical cores.

Parameters:
    device_count (int, optional): device number. Default: None.

Returns:
    list of paddle.CPUPlace: Created list of CPU places.

Examples:

    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> cpu_places = static.cpu_places()
)ry  r   rY  rb  s    rO   
cpu_placesr  _  s%    : zMMO|++rN   c                    [         R                  " 5       (       d   S5       eU c  [        [        5       5      n [         R                  " 5       /U -  $ )a\  
This function creates a list of :code:`base.CUDAPinnedPlace` objects.

If :code:`device_count` is None, the device count would
be determined by environment variable :code:`CPU_NUM`.
If :code:`CPU_NUM` is not set, the default value is 1,
i.e. CPU_NUM=1.
:code:`CPU_NUM` indicates the number of devices used in the current task.
The running of the program can be accelerated if :code:`CPU_NUM` is the same as the number of physical cores.

Parameters:
    device_count (int, optional): device number. Default: None.

Returns:
    list of base.CUDAPinnedPlace: Created list of CUDA pinned places.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:GPU)
        >>> import paddle.base as base
        >>> cuda_pinned_places_cpu_num = base.cuda_pinned_places()
        >>> # or
        >>> cuda_pinned_places = base.cuda_pinned_places(1)

r  )r   rU  r[   rX  CUDAPinnedPlacer  s    rO   cuda_pinned_placesr    sH    : %%''A)AA'9;'  "#l22rN   c                    [         R                  " 5       (       d   S5       eU c  [        [        5       5      n [         R                  " 5       /U -  $ )aU  
This function creates a list of :code:`base.XPUPinnedPlace` objects.

If :code:`device_count` is None, the device count would
be determined by environment variable :code:`CPU_NUM`.
If :code:`CPU_NUM` is not set, the default value is 1,
i.e. CPU_NUM=1.
:code:`CPU_NUM` indicates the number of devices used in the current task.
The running of the program can be accelerated if :code:`CPU_NUM` is the same as the number of physical cores.

Parameters:
    device_count (int, optional): device number. Default: None.

Returns:
    list of base.XPUPinnedPlace: Created list of XPU pinned places.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:GPU)
        >>> import paddle.base as base
        >>> xpu_pinned_places_cpu_num = base.xpu_pinned_places()
        >>> # or
        >>> xpu_pinned_places = base.xpu_pinned_places(1)

r  )r   rU  r[   rX  XPUPinnedPlacer  s    rO   xpu_pinned_placesr    sH    : %%''A)AA'9;'!"\11rN   c                  0    \ rS rSrSS jrS rS rS rSrg)		NameScopei  Nc                *    0 U l         Xl        X l        g rK   	_children_name_parentr   r   parents      rO   r   NameScope.__init__      
rN   c                    XR                   ;  a  [        X5      nU/U R                   U'   U$ [        U S[        U R                   U   5       3U 5      nU R                   U   R                  U5        U$ N_)r  r  r[   r   r   ra   	new_childs      rO   childNameScope.child  sx    '!&/I&/[DNN6" 	 "(!Cv 67894I NN6")))4rN   c                    U R                   $ rK   r  r   s    rO   r  NameScope.parent      ||rN   c                    U R                   $ rK   r  r  s    rO   r   NameScope.name      zzrN   r   N	r   r   r   r   r   r  r  r   r   rM   rN   rO   r  r        
	rN   r  c              #     #    [        5       (       a  Sv   gU (       d   S5       e[        R                  U 5      q Sv   [        R                  5       qg! [        R                  5       qf = f7f)a  

Generate hierarchical name prefix for the operators in Static Graph.

Note:
    This should only used for debugging and visualization purpose.
    Don't use it for serious analysis such as graph/program transformations.
    Don't use it in dygraph, since it will cause memory leak.

Args:
    prefix(str, optional): prefix. Default is none.

Examples:

    .. code-block:: python

        >>> import paddle
        >>> paddle.enable_static()
        >>> with paddle.static.name_scope("s1"):
        ...     a = paddle.static.data(name='data', shape=[None, 1], dtype='int32')
        ...     b = a + paddle.to_tensor(1)
        ...     with paddle.static.name_scope("s2"):
        ...         c = b * paddle.to_tensor(1)
        ...     with paddle.static.name_scope("s3"):
        ...         d = c / paddle.to_tensor(1)
        >>> with paddle.static.name_scope("s1"):
        ...     f = paddle.tensor.pow(d, paddle.to_tensor(2.0))
        >>> with paddle.static.name_scope("s4"):
        ...     g = f - paddle.to_tensor(1)

        >>> # Op are created in the default main program.
        >>> for op in paddle.static.default_main_program().block(0).ops:
        ...     # elementwise_add is created in /s1/
        ...     if op.type == 'elementwise_add':
        ...         assert op.desc.attr("op_namescope") == '/s1/'
        ...     # elementwise_mul is created in '/s1/s2'
        ...     elif op.type == 'elementwise_mul':
        ...         assert op.desc.attr("op_namescope") == '/s1/s2/'
        ...     # elementwise_div is created in '/s1/s3'
        ...     elif op.type == 'elementwise_div':
        ...         assert op.desc.attr("op_namescope") == '/s1/s3/'
        ...     # elementwise_sum is created in '/s4'
        ...     elif op.type == 'elementwise_sub':
        ...         assert op.desc.attr("op_namescope") == '/s4/'
        ...     # pow is created in /s1_1/
        ...     elif op.type == 'pow':
        ...         assert op.desc.attr("op_namescope") == '/s1_1/'
N"namescope prefix can not be empty.)r   _name_scoper  r  )ra   s    rO   
name_scoper    sV     h ;;;v!''/	/%,,.K+,,.Ks   8A-A A-A**A-c                  0    \ rS rSrSS jrS rS rS rSrg)	
NameStructi"  Nc                *    0 U l         Xl        X l        g rK   r  r  s      rO   r   NameStruct.__init__#  r  rN   c                    XR                   ;  a  [        X5      nU/U R                   U'   U$ [        U S[        U R                   U   5       3U 5      nU R                   U   R                  U5        U$ r  )r  r  r[   r   r  s      rO   r  NameStruct.child(  sx    '"60I&/[DNN6" 	 #(!Cv 67894I NN6")))4rN   c                    U R                   $ rK   r  r  s    rO   r  NameStruct.parent3  r  rN   c                    U R                   $ rK   r  r  s    rO   r   NameStruct.name6  r  rN   r  r  r  rM   rN   rO   r  r  "  r  rN   r  c              #    #    [        5       (       a  Sv   gU (       d   S5       e[        R                  U 5      q[        5       (       a?  [	        [
        R                  R                  5       R                  5       R                  5      n Sv   [        5       (       a  [
        R                  R                  5       R                  5       R                  n[	        U5      n[        [        WU5      5       H9  nX$   nUR                  S5      (       a  M  UR                  S[        5       5        M;     [        R                  5       qg! [        5       (       a  [
        R                  R                  5       R                  5       R                  n[	        U5      n[        [        WU5      5       H9  nX$   nUR                  S5      (       a  M  UR                  S[        5       5        M;     [        R                  5       qf = f7f)z
Note: This should only used in Paddle/python/paddle/nn/layer/layers.py
to record the call path for the operators in Static Graph of AutoParallel.

Args:
    prefix(str, optional): prefix. Default is none.
Nr  struct_name)r   _name_structr  r   r[   rk   staticdefault_main_programglobal_blockopsreversedr  has_attrset_str_attr_full_name_structr  )ra   op_num_beforeall_opsop_numidxops         rO   name_structr  =  s|     ;;;v#))&1==224AACGGM	1}}MM668EEGKK  W#E-$@AC B{{=11 OOM3D3FG	 B (..0L }}MM668EEGKK  W#E-$@AC B{{=11 OOM3D3FG	 B (..0Ls    BG?	E B7G?B8G<<G?c                     [         n SnU (       a/  U R                  5       S-   U-   nU R                  5       n U (       a  M/  U$ Nr  /)r  r   r  )structr   s     rO   r  r  d  s=    FD
{{}s"T) & KrN   c                     [         n SnU (       a/  U R                  5       S-   U-   nU R                  5       n U (       a  M/  U$ r  )r  r   r  )scoper   s     rO   _full_name_scoper  n  s=    ED
zz|c!D( % KrN   c                 P    SS K n [        S-   [        U R                  5       5      -   $ )Nr   @)randomCONTROL_DEP_VAR_PREFIXr\   )r  s    rO   generate_control_dev_var_namer  x  s     !C'#fmmo*>>>rN   c                    U [         -   $ )z8
Returns:
    str: gradient name for a certain var name
)GRAD_VAR_SUFFIX)var_names    rO   grad_var_namer  ~  s    
 o%%rN   c                   [         R                  R                  R                  [         R                  R                  R                  [         R                  R                  R
                  [         R                  R                  R                  [         R                  R                  R                  [         R                  R                  R                  [         R                  R                  R                  [         R                  R                  R                  [         R                  R                  R                  [         R                  R                  R                  [         R                  R                  R                  [         R                  R                  R                  [         R                  R                  R                  [         R                  R                  R                   S.n0 ["        R$                  " S5      [         R                  R                  R                  _["        R$                  " S5      [         R                  R                  R                  _["        R$                  " S5      [         R                  R                  R
                  _["        R$                  " S5      [         R                  R                  R                  _["        R$                  " S5      [         R                  R                  R                  _["        R$                  " S5      [         R                  R                  R                  _["        R$                  " S5      [         R                  R                  R                  _["        R$                  " S	5      [         R                  R                  R                  _["        R$                  " S
5      [         R                  R                  R                  _["        R$                  " S5      [         R                  R                  R                  _["        R$                  " S5      [         R                  R                  R                  _["        R$                  " S5      [         R                  R                  R                  _["        R&                  [         R                  R                  R                  _["        R(                  [         R                  R                  R                  _["        R*                  [         R                  R                  R
                  _["        R,                  [         R                  R                  R                  _["        R.                  [         R                  R                  R                  _["        R0                  [         R                  R                  R                  ["        R2                  [         R                  R                  R                  ["        R4                  [         R                  R                  R                  ["        R6                  [         R                  R                  R                  ["        R8                  [         R                  R                  R                  ["        R:                  [         R                  R                  R                  ["        R<                  [         R                  R                  R                  0En[?        U [@        5      (       a	  X;   a  X   $ ["        R$                  " U 5      nX2;   a  X#   $ [C        SU 35      e)z
Convert the data type in numpy to the data type in Paddle.

Args:
    np_dtype (np.dtype|str): The data type in numpy or valid data type
        string.

Returns:
    core.VarDesc.VarType : The data type in Paddle.

)float32float64float16int32int16int64booluint8int8	complex64
complex128bfloat16float8_e4m3fnfloat8_e5m2r  r  r  r  r  r  bool_uint16r  r  r  r  zNot supported numpy dtype )"r   VarDescVarTypeFP32FP64FP16INT32INT16INT64BOOLUINT8INT8	COMPLEX64
COMPLEX128BF16
FP8_E4M3FNFP8_E5M2npdtyper  r  r  r  r  r  r  r  r  r  r  r  rT   r\   r]   )np_dtypestr_to_var_typenp_dtype_to_var_typer  s       rO   convert_np_dtype_to_proto_typer    sy   $ <<'',,<<'',,<<'',,%%++%%++%%++$$))%%++$$))\\))33ll**55LL((----88||++44O"
T\\1166
T\\1166 	T\\1166 	4<<//55	
 	4<<//55 	4<<//55 	4<<//44 	DLL0055 	4<<//55 	$,,..33 	t||33== 	 4 4 ? ? 	

DLL((-- 	

DLL((-- 	

DLL((--  	$,,&&,,!" 	$,,&&,,#$ 	$,,&&,,
$,,&&++
$,,&&,,
%%**
		4<<'',,
dll**44
t||++6616 (C  &",,HHXE$#**5eW=>>rN   c                   [        5       (       a@  [        U [        R                  5      (       a  U $ [        R                  R                  U 5      $ [        U [        R                  R                  5      (       a  U $ [        U 5      $ )z
Convert the data type in numpy to the data type in Paddle.

Args:
    np_dtype (np.dtype|str): The data type in numpy or valid data type
        string.

Returns:
    core.VarDesc.VarType / core.DataType : The data type in Paddle.

)	r   rT   r   r   r   convert_np_dtype_to_dtype_r  r  r  )r  s    rO   r  r    s]     }}h..Oxx228<<(DLL0011)(33rN   c                    [        U [        R                  R                  5      (       a  U $ [        U [        R                  5      (       a	  [
        U    $ [        U 5      $ )a  
Convert the data type in numpy to the data type in Paddle.

Args:
    dtype (np.dtype|str|core.DataType|core.VarDesc.VarType): The data type in numpy, valid data type
        string or paddle dtype.

Returns:
    core.VarDesc.VarType : The data type in Paddle.

)rT   r   r  r  r   paddle_type_to_proto_typer  r  s    rO   convert_to_proto_typer    sG     %--..	E4==	)	)(//-e44rN   c                F   [        U [        R                  R                  5      (       d  [	        U 5      n U [        R                  R                  R
                  [        R                  R                  R                  [        R                  R                  R                  4;   $ )z
Check the data type is floating or not.
Args:
    dtype(np.dtype|core.VarDesc.VarType): data type.
        Could be numpy format or Paddle format

Returns(bool): True if data type is a float value

)rT   r   r  r  r  r  r  r  r  s    rO   dtype_is_floatingr     sp     eT\\1122*51!!!!!!  rN   Tc                    / nU R                  U5      (       d  U(       a  [        U SU  S35      eU R                  5       $ )a:  
Get the debug string of a protobuf message. The message could be not
initialized.
Args:
    proto(google.protobuf.message.Message): The protobuf message
    throw_on_error(bool): True if raise an error when the protobuf message
        is not initialized.

Returns(str): The debug string of the protobuf message

z% are not initialized.
The message is z:
)IsInitializedr]   r   )protothrow_on_errorerror_fieldss      rO   _debug_string_r&    sH     L|,,nB5'M
 	
 ==?rN   c                ^   Ub  [        U5      nO$[        R                  R                  R                  n[        R
                  R                  UU(       a  [        U5      O/ UU (       a  U O#[        R                  R                  R                  U(       a  SOS5      nUR                  5         U$ NTF)
r  r   r  r  r  eagerTensorrd   DENSE_TENSORretain_grads)r   r   shaper  persistabler   eager_tensors          rO   _create_tensorr0  "  s     %e,$$))::$$U"$,,..;;L rN   c                x   ^ [        U [        [        45      (       d   eU (       d  g[        U4S jU  5       5      $ )zv
Return True if type of each element is expected_type.

NOTE: BuiltIn all() will always return True if vals is empty.
Fc              3  <   >#    U  H  n[        UT5      v   M     g 7frK   )rT   ).0vexpected_types     rO   	<genexpr>_all_is_type.<locals>.<genexpr>C  s     :Tz!]++Ts   )rT   rd   re   all)valsr5  s    `rO   _all_is_typer:  :  s3     dT5M****:T:::rN   c                ^   [        U [        R                  5      (       a  U $ [        U [        [        [
        [        45      (       a  [        R                  " U 5      $ [        U [        R                  5      (       a$  [        R                  " U R                  5       5      $ [        SU  S35      e)zWrap a number(either python scalar or numpy scalar) as core.Scalar if
it is not a scalar.


Args:
    number (Number): number

Returns:
    Scalar: A Scalar that contains the value.
zCannot wrap z as core.Scalar)rT   r   Scalarr  r  floatcomplexr  numberitemrV   )r?  s    rO   wrap_as_scalarrA  F  sy     &$++&&&4eW566{{6""&"))$${{6;;=)),vho>??rN   c                    [        U [        R                  5      (       a  U R                  5       R	                  5       n U  Vs/ s H  n[        U5      PM     sn$ s  snf )ah  This function is used to convert flat list, or numpy array(not
necessarily flat) to list of core.Scalar, which correspond to
std::vector<paddle::experimental::Scalar> in operator runtime.

Args:
    array (List | np.ndarray): array of numbers

Returns:
    List: list of core.Scalar, of which each element is a Scalar containing
      the corresponding value.
)rT   r  ndarrayraveltolistrA  arrayr@  s     rO   wrap_as_scalarsrH  \  sF     %$$$$&-23UTN4 U333s   Ac                L    U  Vs/ s H  oR                  5       PM     sn$ s  snf )zextract value from a list of core.Scalar.

Args:
    array (list): Scalars

Returns:
    list: values extracted from the scalars.
)r`   rF  s     rO   extract_plain_listrJ  m  s      &++UTJJLU+++s   !c                   U R                  5       nUR                   GH4  nUR                  nUR                  nX@;  d  X   c  M(  X   n[	        U[
        5      (       a  MC  [	        U[        5      (       a  [        U[
        5      (       a  Mo  U[        R                  R                  :X  a  [        R                  " U5      X$'   M  U[        R                  R                  :X  d  M  [        U5      S:  d  M  [        R                  " U5      R!                  5       R#                  5       nU Vs/ s H  n[        R                  " U5      PM     nnXbU'   GM7     U$ s  snf )a|  This function is used to canonicalize attributes(as a string->any dict)
according to the type specification in the OpProto. This is especially
important for operators that has any attributes of type Scalar or Scalars.

Though various frontends of phi kernels & paddle operators can wrap variables
of concrete types into Scalars(a tagged union of several numeric types) or
vector of Scalars. Paddle operator requires strict type matching.

Args:
    attrs (Dict[str, Any]): attribute dict intended to pass to an operator.
    op_proto (OpProto): Proto (signature) of the operator.

Returns:
    Dict[str, Any]: canonicalized attributes.
r   )copyattrsr   r   rT   Variablerd   r:  r   AttrTypeSCALARr<  SCALARSr[   r  rG  rD  rE  )rM  op_protocanonicalized_attrsattr	attr_name
type_indexattr_valrB   s           rO   canonicalize_attrsrX  y  s      **,II	YY
"(8(@# h))h%%,x*J*J ----1[[-B*4==0008}q 88H-335<<>4<=HqDKKNH=19I.- 0  >s   + Ec                  $    \ rS rSr\S 5       rSrg)VariableMetaClassi  c                    [        U5      n[        5       (       a$  [        U[        R                  R
                  5      $ [        U[        5      $ rK   )r   r   
issubclassr   r)  r*  rN  clsinstancets      rO   __instancecheck__#VariableMetaClass.__instancecheck__  s8    Na!2!233a**rN   rM   Nr   r   r   r   classmethodra  r   rM   rN   rO   rZ  rZ    s    + +rN   rZ  c                  $    \ rS rSr\S 5       rSrg)ParameterMetaClassi  c                v    [        U5      n[        5       (       a  [        U[        5      $ [        U[        5      $ rK   )r   r   r\  EagerParamBase	Parameterr]  s      rO   ra  $ParameterMetaClass.__instancecheck__  s.    Na00a++rN   rM   Nrc  rM   rN   rO   rf  rf    s    , ,rN   rf  c                     \ rS rSrSr\R                  R                  R                  SSSSSSSSSSS4S jr	S r
\S 5       r\S9S j5       r\S	 5       r\S
 5       rS rS rS rS rS9S jr\rS r\S 5       r\R4                  S 5       r\S 5       r\R4                  S 5       r\S 5       r\R4                  S 5       r\S 5       r\S 5       r\R4                  S 5       r\S 5       r\S 5       r \S 5       r!\S 5       r"\S 5       r#S r$S  r%S! r&S" r'S# r(S$ r)S% r*S& r+S9S' jr,S( r-S) r.S* r/S+ r0S, r1S:S- jr2S:S. jr3S/ r4S0 r5S1 r6S2 r7S3 r8\S4 5       r9S5 r:\S6 5       r;\;R4                  S7 5       r;S8r<g);rN  i  a  

Notes:
    The constructor of Variable should not be invoked directly.

    In Static Graph Mode: Please use ** `Block.create_var` ** to create a Static variable which has no data until being feed.

    In Dygraph Mode: Please use ** :ref:`api_paddle_to_tensor` ** to create a dygraph variable with real data.

In Fluid, every input and output of an OP is a variable. In most
cases, variables are used for holding different kinds of data or training
labels. A variable belongs to a :ref:`api_guide_Block_en` . All variable has its own name and
two variables in different :ref:`api_guide_Block_en` could have the same name.

There are many kinds of variables. Each kind of them has its own attributes
and usages. Please refer to the `framework.proto <https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/phi/core/framework/framework.proto>`_ for details.

Most of a Variable's member variables can be set to be None. It mean
it is not available or will be specified later.

Examples:
    In Static Graph Mode:

    .. code-block:: python
        :name: code-example-1

        >>> import paddle.base as base
        >>> cur_program = base.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_variable = cur_block.create_var(name="X",
        ...                                     shape=[-1, 23, 48],
        ...                                     dtype='float32')

    In Dygraph  Mode:

    .. code-block:: python
        :name: code-example-2

        >>> import paddle.base as base
        >>> import numpy as np
        >>> import paddle

        >>> with base.dygraph.guard():
        ...     new_variable = paddle.to_tensor(np.arange(10))

NFc           	     "   Xl         Uc  U R                   R                  R                  S5      nU R                   R                  U5      bC  U R                   R                  R                  S5      nU R                   R                  U5      b  MC  Ub  [	        U5      nU[
        R                  R                  R                  :X  a&  [
        R                  R                  R                  nS nU[
        R                  R                  R                  :X  a  S nXl
        Xl        SnU R                   R                  R                  UR                  5       5      U l        U R                  c:  U R                   R                  R                  UR                  5       5      U l        SnU(       a  U R                  R!                  U5        OUU R                  R#                  5       U:w  a7  [%        SU R&                   SU R                  R#                  5        SU S35      eUb_  U(       a  U R                  R)                  U5        O<U R*                  n[-        U5      nUU:w  a  [%        SU R&                   SU S	U S
35      eUbT  U(       a  U R                  R/                  U5        O1U R0                  nUU:w  a  [%        SU R&                   SU SU S
35      eUb[  U(       a  U R                  R3                  U5        O8X`R4                  :w  a)  [%        SU R&                   SU R4                   SU S35      eUb[  U(       a  U R                  R7                  U5        O8XR8                  :w  a)  [%        SU R&                   SU R8                   SU S35      eU(       a"  U(       a  U R                  R;                  U5        Ub$  U(       a  U R                  R=                  U5        O X R                   R>                  U'   S U l         Xl!        Xl"        SU l#        g )N_generated_varFTz
Variable 'z0' has been created before. The previous type is z, the new type is z. They are not matchedz1' has been created before. The previous shape is z, the new shape is z. They are not matched.z5' has been created before. The previous data type is z, the new data type is z5' has been created before. The previous lod_level is z, the new lod_level is z6' has been created before.The previous persistable is z, the new persistable is )$blockprogram_name_generator_find_var_recursiver  r   r  r  STRINGS
SPARSE_COObelong_to_optimizer
error_clipdescfind_varencodevarset_typer   r]   r   	set_shaper-  re   	set_dtyper  set_lod_level	lod_levelset_persistabler.  set_need_check_feedset_capacityvarsr  stop_gradientis_datais_view_var)r   rn  r   r   r-  r  r~  capacityr.  ru  r  r  need_check_feedrt  r   
is_new_var	old_shape	old_dtypes                     rO   r   Variable.__init__  s   " 
<::%%556FGD**006Bzz))99:JK **006B )%0EDLL((000<<''//DI4<<''222I#6 $
JJOO,,T[[];	99

++DKKM:DIJIIt$YY^^%TYYK ($$(IINN$4#55Gv N##  		##E* JJ	eI%$$TYYK 0$$-;.A% I## 
 		##E* JJ	I%$$TYYK 055>K @((-w /##   		''	2.$$TYYK 0559^^4D E((1{ 3""  "		))+6"2"22$$TYYK 077;7G7G6H I**56LN  zII))/:		&&x0  $

* rN   c           	     r   U R                   [        R                  R                  R                  :X  d9  U R                   [        R                  R                  R
                  :X  d   S5       e[        R                  " U R                  R                  R                  5         U R                  R                  [        R                  " SU R                  -   5      U R                  U R                   U R                  SS9nSSS5        U R                  R!                  SSU /0SW/0S	9  U$ ! , (       d  f       N1= f)
aA  

Returns a new Variable, detached from the current graph.
It will share data with origin Variable and without tensor copy.
In addition, the detached Variable doesn't provide gradient propagation.

Returns:
     ( :ref:`api_guide_Variable_en` | dtype is same as current Variable), The detached Variable.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()

        >>> # create a static Variable
        >>> x = paddle.static.data(name='x', shape=[3, 2, 1])

        >>> # create a detached Variable
        >>> y = x.detach()

zIonly support a variable with SELECTED_ROWS or DENSE_TENSOR to be detacheddetach_Tr   r  r   r.  r  N
share_datar   Outr   inputsoutputs)r   r   r  r  SELECTED_ROWSr+  r   guardrn  ro  rp  
create_vargenerate_with_ignorable_keyr   r  r.  	append_opr   outputs     rO   detachVariable.detach_  s   4 II--;;;yyDLL00===	
 X		
> tzz11AABZZ** <<		) jjYY ,," + F C 	

$=VH% 	 	

 ! CBs    AD((
D6c                    g)a  
**Notes**:
    **This API is ONLY available in Dygraph mode**

Returns a numpy array shows the value of current :ref:`api_guide_Variable_en`

Returns:
    ndarray: The numpy value of current Variable.

Returns type:
    ndarray: dtype is same as current Variable

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.base as base
        >>> from paddle.nn import Linear
        >>> import numpy as np

        >>> data = np.random.uniform(-1, 1, [30, 10, 32]).astype('float32')
        >>> with base.dygraph.guard():
        ...     linear = Linear(32, 64)
        ...     data_tensor = paddle.to_tensor(data)
        ...     x = linear(data_tensor)
        ...     print(x.numpy())

NrM   r  s    rO   numpyVariable.numpy  s    < 	rN   c                b    SSK Jn  USL a  [        S5      eU" U 5      nU H  u  pEXTl        M     g)a  
**Notes**:
    **This API is ONLY available in Dygraph mode**

Run backward of current Graph which starts from current Tensor.

Args:
    retain_graph(bool, optional): If False, the graph used to compute grads will be freed. If you would
        like to add more ops to the built graph after calling this method( :code:`backward` ), set the parameter
        :code:`retain_graph` to True, then the grads will be retained. Thus, setting it to False is much more memory-efficient.
        Defaults to False.

Returns:
    NoneType: None

Examples:
    .. code-block:: python

        >>> import numpy as np
        >>> import paddle
        >>> paddle.disable_static()

        >>> x = np.ones([2, 2], np.float32)
        >>> inputs = []
        >>> for _ in range(10):
        ...     tmp = paddle.to_tensor(x)
        ...     # if we don't set tmp's stop_gradient as False then, all path to loss will has no gradient since
        ...     # there is no one need gradient on it.
        ...     tmp.stop_gradient=False
        ...     inputs.append(tmp)
        >>> ret = paddle.add_n(inputs)
        >>> loss = paddle.sum(ret)
        >>> loss.backward()

r   )append_backwardTz_`retain_graph` == True is not supported in @to_static function.please set retain_graph = False.N)backwardr  rC  grad)r   retain_graphr  param_grad_listparam
param_grads         rO   r  Variable.backward  s@    J 	.4 3  *$/!0E#J "1rN   c                    g)aq  
**Notes**:
    **This API is ONLY available in Dygraph mode**

Get the Gradient of Current Variable

Returns:
    ndarray or tuple of ndarray: if Variable's type is DenseTensor, return numpy value of the gradient of current Variable, if Variable's type is SelectedRows, return tuple of ndarray, first element of tuple is numpy value of the gradient of current Variable, second element of tuple is numpy value of the rows of current Variable.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.base as base
        >>> import numpy as np

        >>> # example1: return ndarray
        >>> x = np.ones([2, 2], np.float32)
        >>> with base.dygraph.guard():
        ...     inputs2 = []
        ...     for _ in range(10):
        ...         tmp = paddle.to_tensor(x)
        ...         tmp.stop_gradient=False
        ...         inputs2.append(tmp)
        ...     ret2 = paddle.add_n(inputs2)
        ...     loss2 = paddle.sum(ret2)
        ...     loss2.retain_grads()
        ...     loss2.backward()
        ...     print(loss2.gradient())

        >>> # example2: return tuple of ndarray
        >>> with base.dygraph.guard():
        ...     embedding = paddle.nn.Embedding(
        ...         20,
        ...         32,
        ...         weight_attr='emb.w',
        ...         sparse=True)
        ...     x_data = np.arange(12).reshape(4, 3).astype('int64')
        ...     x_data = x_data.reshape((-1, 3, 1))
        ...     x_tensor = paddle.to_tensor(x_data)
        ...     out = embedding(x_tensor)
        ...     out.backward()
        ...     print(embedding.weight.gradient())

NrM   r  s    rO   gradientVariable.gradient  s    ^ 	rN   c                    g)a  
**Notes**:
    **1. This API is ONLY available in Dygraph mode**

    **2. Use it only Variable has gradient, normally we use this for Parameters since other temporal Variable will be deleted by Python's GC**

Clear  (set to ``0`` ) the Gradient of Current Variable

Returns:  None

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.base as base
        >>> import numpy as np

        >>> x = np.ones([2, 2], np.float32)
        >>> inputs2 = []
        >>> for _ in range(10):
        >>>     tmp = paddle.to_tensor(x)
        >>>     tmp.stop_gradient=False
        >>>     inputs2.append(tmp)
        >>> ret2 = paddle.add_n(inputs2)
        >>> loss2 = paddle.sum(ret2)
        >>> loss2.retain_grads()
        >>> loss2.backward()
        >>> print(loss2.gradient())
        >>> loss2.clear_gradient()
        >>> print("After clear {}".format(loss2.gradient()))
        1.0
        After clear 0.0
NrM   r  s    rO   clear_gradientVariable.clear_gradient  s    F 	rN   c                \   ^ SS K nU4S jnS nUR                  R                  UU U UU /S9  g )Nr   c                <   > T" [         R                  " U 5      5      $ )zcall the backward hook in .)r  rG  )dyhooks    rO   backward_hook_wrapper5Variable.register_hook.<locals>.backward_hook_wrapper;  s    %%rN   c                    U $ )z%do nothing but return a new variable.rM   )rB   s    rO   forward_hook_wrapper4Variable.register_hook.<locals>.forward_hook_wrapper?  s    HrN   )r   rB   outbackward_funcskip_vars_in_backward_input)rk   r  py_func)r   r  rk   r  r  s    `   rO   register_hookVariable.register_hook8  s:    	&	 	%/)- 	 	
rN   c                    U R                   (       d  [        S5      e U" U 5      $ !   [        SUR                   S35      e= f)Nz9Cannot apply function on a tensor that required gradient.zThe PyFunc z could not be applied)r  RuntimeErrorr]   r   )r   r   s     rO   applyVariable.applyK  sL    !!K 	Q:	Q{4==/9NOPPs	   & Ac                "    U R                  5       $ rK   _to_readable_coder  s    rO   r   Variable.__str__U      %%''rN   c           
        [        U R                  5      R                  S5      S   nU R                  [        R                  R
                  R                  :X  d2  U R                  [        R                  R
                  R                  :X  aW  [        U R                  5      R                  S5      S   nU R                   SU SU R                   SU SU R                   S3
nOU R                   SU S3nU R                  (       a  U R                  (       a  SU-   nOS	U-   nOS
U-   nU R                  (       a  SU-   nSSKJn  U" 5       nUR#                  U 5      nUb  USR%                  SUS9-  nU$ )aA  
Get readable debug string of Variable.

.. note::
    If you want to get the debug string in protobuf format,
    please use :code:`to_string` method.

Returns:
    string: The formatted Variable string.

Examples:
    .. code-block:: python

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> cur_program = static.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_variable = cur_block.create_var(name="X",
        ...                                     shape=[-1, 23, 48],
        ...                                     dtype='float32')
        >>> print(new_variable._to_readable_code())
        var X : DENSE_TENSOR.shape(-1, 23, 48).dtype(float32).stop_gradient(False)
r  r   z : z.shapez.dtype(z).stop_gradient()ztrainable param param var zpersist r   get_default_distributed_context, {name} = {value}	dist_attrr   r`   )r\   r   r  r   r  r  r  r+  r  r   r-  r  is_parameter	trainabler.  4paddle.distributed.auto_parallel.static.dist_contextr  get_dist_tensor_for_programformat)r   type_str	dtype_strvar_strr  dist_contextdist_tensors          rO   r  Variable._to_readable_codeX  sQ   : tyy>'',Q/II--;;;yyDLL00===DJJ--c215I3xjtzzl')TdeiewewdxxyzG3xj2G~~,w6"W,w&G 7*G	
 78">>tD"+22  3  G rN   c                B   [        U[        5      (       a  [        U[        5      (       d   eU R                  R                  5       n[        R
                  R                  [        U5      5      n[        XA5      nU(       a  SnU H  nXW S[        X5       S3-  nM     U$ )a  
Get debug string.

Args:

    throw_on_error (bool): True if raise an exception when self is not initialized.

    with_details (bool): more details about variables and parameters (e.g. trainable, optimize_attr, ...) will be printed when with_details is True. Default value is False;

Returns:
    str: The debug string.

Examples:
    .. code-block:: python

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> import paddle.base as base
        >>> import paddle

        >>> paddle.enable_static()
        >>> cur_program = base.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_variable = cur_block.create_var(name="X",
        ...                                     shape=[-1, 23, 48],
        ...                                     dtype='float32')
        >>> print(new_variable.to_string(True))
        >>> print("=============with detail===============")
        >>> print(new_variable.to_string(True, True))
        name: "X"
        type {
          type: DENSE_TENSOR
          lod_tensor {
            tensor {
              data_type: FP32
              dims: -1
              dims: 23
              dims: 48
            }
          }
        }
        stop_gradient: false
        error_clip: None
ru  : r   )
rT   r  rv  serialize_to_stringr   r  
FromStringbytesr&  getattr)r   r$  with_detailsprotostrr#  res_stradditional_attrrU  s           rO   	to_stringVariable.to_string  s    X .$//J$5
 5
 	
 
 99002%%00xA 7-O,	[74+C*DBGG - rN   c                6    U R                   R                  5       $ )a  
Returns the size in bytes of an element in the Tensor.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> paddle.enable_static()

        >>> x = paddle.static.data(name='x1', shape=[3, 2], dtype='bool')
        >>> print(x.element_size())
        1

        >>> x = paddle.static.data(name='x2', shape=[3, 2], dtype='int16')
        >>> print(x.element_size())
        2

        >>> x = paddle.static.data(name='x3', shape=[3, 2], dtype='float16')
        >>> print(x.element_size())
        2

        >>> x = paddle.static.data(name='x4', shape=[3, 2], dtype='float32')
        >>> print(x.element_size())
        4

        >>> x = paddle.static.data(name='x5', shape=[3, 2], dtype='float64')
        >>> print(x.element_size())
        8
)rv  element_sizer  s    rO   r  Variable.element_size  s    < yy%%''rN   c                6    U R                   R                  5       $ )a  
Indicating if we stop gradient from current Variable

**Notes: This Property has default value as** ``True`` **in** Dygraph **mode, while Parameter's default value is False. However, in Static Graph Mode all Variable's default stop_gradient value is** ``False``

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.base as base
        >>> import numpy as np

        >>> with base.dygraph.guard():
        ...     value0 = np.arange(26).reshape(2, 13).astype("float32")
        ...     value1 = np.arange(6).reshape(2, 3).astype("float32")
        ...     value2 = np.arange(10).reshape(2, 5).astype("float32")
        ...     linear = paddle.nn.Linear(13, 5)
        ...     linear2 = paddle.nn.Linear(3, 3)
        ...     a = paddle.to_tensor(value0)
        ...     b = paddle.to_tensor(value1)
        ...     c = paddle.to_tensor(value2)
        ...     out1 = linear(a)
        ...     out2 = linear2(b)
        ...     out1.stop_gradient = True
        ...     out = paddle.concat(x=[out1, out2, c], axis=1)
        ...     out.backward()
        ...     assert linear.weight.gradient() is None
        ...     assert out1.gradient() is None
)rv  r  r  s    rO   r  Variable.stop_gradient  s    > yy&&((rN   c                :    U R                   R                  U5        g rK   )rv  set_stop_gradient)r   r  s     rO   r  r  	  s    		##A&rN   c                6    U R                   R                  5       $ )a  
Indicating if we current Variable should be long-term alive


**Notes: This Property will be deprecated and this API is just to help user understand concept**

    **1. All Variable's persistable is** ``False`` **except Parameters.**

    **2. In** Dygraph **mode, this property should not be changed**

Examples:
    .. code-block:: python

        >>> import paddle.base as base
        >>> cur_program = base.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_variable = cur_block.create_var(name="X",
        ...                                     shape=[-1, 23, 48],
        ...                                     dtype='float32')
        >>> print("persistable of current Var is: {}".format(new_variable.persistable))
        persistable of current Var is: False
)rv  r.  r  s    rO   r.  Variable.persistable	  s    0 yy$$&&rN   c                :    U R                   R                  U5        g rK   )rv  r  r   ps     rO   r.  r  1	  s    		!!!$rN   c                6    U R                   R                  5       $ )a)  
Indicating if current Variable is a Parameter

Examples:
    .. code-block:: python

        >>> import paddle
        >>> paddle.enable_static()
        >>> new_parameter = paddle.static.create_parameter(name="X",
        ...                                     shape=[10, 23, 48],
        ...                                     dtype='float32')
        >>> if new_parameter.is_parameter:
        ...     print("Current var is a Parameter")
        ... else:
        ...     print("Current var is not a Parameter")
        Current var is a Parameter
)rv  r  r  s    rO   r  Variable.is_parameter5	  s    & yy%%''rN   c                :    U R                   R                  U5        g rK   )rv  set_is_parameterr  s     rO   r  r  J	  s    		""1%rN   c                6    U R                   R                  5       $ )a  
Indicating name of current Variable

**Notes: If it has two or more Variable share the same name in the same** :ref:`api_guide_Block_en` **, it means these Variable will share content in no-** Dygraph **mode. This is how we achieve Parameter sharing**

Examples:
    .. code-block:: python

        >>> import paddle.base as base
        >>> cur_program = base.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_variable = cur_block.create_var(name="X",
        ...                                     shape=[-1, 23, 48],
        ...                                     dtype='float32')
        >>> print("name of current Var is: {}".format(new_variable.name))
        name of current Var is: X
)rv  r   r  s    rO   r   Variable.nameN	  s    & yy~~rN   c                     U R                   S-   $ )a  
Indicating name of the gradient Variable of current Variable.

**Notes: This is a read-only property. It simply returns name of
gradient Variable from a naming convention but doesn't guarantee
the gradient exists.**

Examples:
    .. code-block:: python

        >>> import paddle
        >>> paddle.enable_static()
        >>> x = paddle.static.data(name="x", shape=[-1, 23, 48], dtype='float32')
        >>> print(x.grad_name)
        x@GRAD

z@GRADr   r  s    rO   	grad_nameVariable.grad_namec	  s    & yy7""rN   c                :    U R                   R                  U5        g rK   )rv  set_name)r   new_names     rO   r   r  x	  s    		8$rN   c                H    [        U R                  R                  5       5      $ )a3  
Indicating shape of current Variable

**Notes: This is a read-only property**

Examples:
    .. code-block:: python

        >>> import paddle.base as base
        >>> cur_program = base.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_variable = cur_block.create_var(name="X",
        ...                                     shape=[-1, 23, 48],
        ...                                     dtype='float32')
        >>> print("shape of current Var is: {}".format(new_variable.shape))
        shape of current Var is: [-1, 23, 48]
)re   rv  r-  r  s    rO   r-  Variable.shape|	  s    ( TYY__&''rN   c                6    U R                   R                  5       $ )a9  
Indicating data type of current Variable

**Notes: This is a read-only property**

Examples:
    .. code-block:: python

        >>> import paddle.base as base
        >>> cur_program = base.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_variable = cur_block.create_var(name="X",
        ...                                     shape=[-1, 23, 48],
        ...                                     dtype='float32')
        >>> print("Dtype of current Var is: {}".format(new_variable.dtype))
        Dtype of current Var is: paddle.float32
)rv  r  r  s    rO   r  Variable.dtype	  s    & yy  rN   c                   U R                   [        R                  R                  R                  :X  a  [        S5      eU R                   [        R                  R                  R                  :X  a  gU R                  R                  5       $ )a-  
Indicating ``LoD`` info of current Variable, please refer to  :ref:`api_paddle_Tensor` to check the meaning
of ``LoD``

**Notes**:

    **1. This is a read-only property**

    **2. Don't support this property in** Dygraph **mode, it's value should be** ``0(int)``

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.base as base

        >>> paddle.enable_static()
        >>> cur_program = base.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_variable = cur_block.create_var(name="X",
        ...                                     shape=[-1, 23, 48],
        ...                                     dtype='float32')
        >>> print("LoD Level of current Var is: {}".format(new_variable.lod_level))
        LoD Level of current Var is: 0
zSelectedRows DO NOT support lodN)	r   r   r  r  r  NotImplementedErrorrr  rv  r~  r  s    rO   r~  Variable.lod_level	  s^    6 99,,:::%&GHH99,,444yy""$$rN   c                6    U R                   R                  5       $ )au  
Indicating Type of current Variable

**Notes: This is a read-only property**

Examples:
    .. code-block:: python

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> import paddle.base as base
        >>> cur_program = base.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_variable = cur_block.create_var(name="X",
        ...                                     shape=[-1, 23, 48],
        ...                                     dtype='float32')
        >>> print("Type of current Var is: {}".format(new_variable.type))
        Type of current Var is: VarType.DENSE_TENSOR
rv  r   r  s    rO   r   Variable.type	  s    ( yy~~rN   c           	        [        U R                  5      S:X  a  U $ / n[        [        U R                  5      5       H  nUR                  SU5        M     [        R
                  " U R                  R                  R                  5         U R                  R                  [        R                  " U R                  S-   5      U R                  U R                  SSS9nU R                  R                  [        R                  " U R                  S-   5      U R                  [        R                  R                   R"                  SSS9nU R                  R%                  SSU /0U/U/S.S	U0S
9  UsSSS5        $ ! , (       d  f       g= f)a  

Permute current Variable with its dimensions reversed.

If `n` is the dimensions of `x` , `x.T` is equivalent to `x.transpose([n-1, n-2, ..., 0])`.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> paddle.enable_static()

        >>> x = paddle.ones(shape=[2, 3, 5])
        >>> x_T = x.T

        >>> exe = paddle.static.Executor()
        >>> x_T_np = exe.run(paddle.static.default_main_program(), fetch_list=[x_T])[0]
        >>> print(x_T_np.shape)
        (5, 3, 2)

r   r   z.tmpFr  
transpose2r   )r  XShaper   r   r  r  rM  N)r[   r-  r  insertr   r  rn  ro  rp  r  r  r   r  r   r   r  r  r+  r  )r   permr  r  input_shapes        rO   T
Variable.T	  sM   . tzz?aKs4::'AKK1 ( tzz11AAB**'' <<II& jjYY!# ( C **// <<II& jj\\))66!# 0 K JJ  !dV}!$+?tn	 !  5 CBBs   	C$E77
Fc           	        [         R                  " U R                  R                  R                  5         U R                  R                  [         R                  " U R                  S-   5      U R                  U R                  U R                  U R                  S9nU R                  R                  SSU /0SU/0S9  UsSSS5        $ ! , (       d  f       g= f)a2  
Returns a new static Variable, which is the clone of the original static
Variable. It remains in the current graph, that is, the cloned Variable
provides gradient propagation. Calling ``out = tensor.clone()`` is same
as ``out = assign(tensor)`` .

Returns:
    Variable, The cloned Variable.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()

        >>> # create a static Variable
        >>> x = paddle.static.data(name='x', shape=[3, 2, 1])
        >>> # create a cloned Variable
        >>> y = x.clone()

_cloner  assignr   r  r  N)r   r  rn  ro  rp  r  r  r   r  r   r.  r  r  r  s     rO   cloneVariable.clone
  s    . tzz11AABZZ** <<II( jjYY ,,"00 + F JJ  dV}) ! 
 ! CBBs   B	C
Cc                    Xl         g)zi

Set the error_clip.

Args:
    error_clip(BaseErrorClipAttr) : The new error_clip.

Returns:
    None

Nr  )r   ru  s     rO   _set_error_clipVariable._set_error_clip@
  s	     %rN   c                P    [        U S5      (       d  0 U l        X R                  U'   g)z

Set key-value information for this variable.

Args:
    key(str): Key for this information.
    value(object): The value associated to the key.

Returns:
    None

_infoNhasattrr  )r   r_   r`   s      rO   	_set_infoVariable._set_infoN
  s#     tW%%DJ

3rN   c                b    [        U S5      (       a  XR                  ;   a  U R                  U   $ g)z

Get the information of this variable corresponding to key.

Args:
    key(str): Key for this information.

Returns:
    object

r  Nr  )r   r_   s     rO   	_get_infoVariable._get_info_
  s+     4!!cZZ&7::c?"rN   c                   UR                   c  SOUR                   nUS:  a  [        S5      eUS:X  a  [        S5      eUS:  a  SOSnUS:  a  US-
  OUnUR                  c  US:  a  UOUnO+UR                  nUS:  a  [        Xb-   U5      O
[	        Xe5      nUR
                  c  US:  a  UOUnO+UR
                  nUS:  a  [        Xr-   U5      O
[	        Xu5      nXgU4$ )z:

Reference implementation for the slice.indices method.

r   r   zlength should not be negativezslice step can not be zeror   )stepr]   startmaxminstop)r   slicelengthr&  r   upperr'  r*  s           rO   _slice_indicesVariable._slice_indiceso
  s     JJ&qEJJ A:<==199:: QhA"Qh
F ;;!AXE5EKKE.3aiENE*S=N 
 :: 1H5%D::D04q3t}e,c$>NDD  rN   c                    SnSn[        U R                  5      n[        U5       H1  u  pVU[        L a  U(       a  [	        S5      eSnUnM&  U(       d  M/  UnM3     X#U4$ )NFr   z!Index can have one ellipsis only.T)r[   r-  	enumerateEllipsisr]   )r   r@  has_ellipsisr'  endr   os          rO   _detectEllipsisVariable._detectEllipsis
  s`    $**o!$HEH}$%HII#<C ( C''rN   c                F   U R                  U5      u  p#nU(       a  / n[        U5       H  nUR                  X   5        M     [        X45       H  nUR                  [        S S S 5      5        M!     [        U[	        U5      5       H  nUR                  X   5        M     U$ g rK   )r6  r  r   r+  r[   )r   r@  r3  r'  r4  newitemr  s          rO   _reconstructSliceinfoVariable._reconstructSliceinfo
  s    #'#7#7#= SG5\tw' "5&uT467 '3D	*tw' +NrN   c                   / n/ n[        U5       GH5  u  pE[        U[        5      (       a  [        U5      nUS:  a  X@R                  U   :  d  US:  a   X@R                  U   -   S:  a  [	        S5      eUS:  a  [        X`R                  U   -   S5      O[        X`R                  U   5      nUR                  U5        UR                  US-   5        M  [        U[        5      (       aT  U R                  XPR                  U   5      u  pgnUS:X  d  US:X  a%  UR                  U5        UR                  U5        GM+    g[	        S5      e   SX#/4$ )Nr   invalid indexr   r   )FNz+Valid index accept int or slice or ellipsisT)
r1  rT   r  r-  
IndexErrorr(  r)  r   r+  r.  )	r   r@  startsendsr   r5  r'  r*  r&  s	            rO   _detectContinuesSliceVariable._detectContinuesSlice
  s/   !$HE!S!!AAI%::e+<"<AI5::e+<#<"A$_55 qy 

5 1115UJJu$56 
 e$EAI&Au%%$($7$7::e;L$M!T19
MM%(KK%& !NOO- (. f^##rN   c                H   [         R                  " U R                  R                  R                  5         U(       dK  U R                  R                  [         R                  " U R                  5      U R                  S9sS S S 5        $ U sS S S 5        $ ! , (       d  f       g = f)Nr   r  )	r   r  rn  ro  rp  r  r  r   r  )r   rL  s     rO   	_cloneVarVariable._cloneVar
  sn    tzz11AABzz,,$@@K** -  CB  CBBs   A	BB
B!c           	     p    U R                  5       nU R                  R                  SSU /0SU/0XUS.S9  U$ )Nr+  Inputr  )axesr?  r@  r  rE  rn  r  )r   rI  r?  r@  new_vars        rO   	_sliceVarVariable._sliceVar
  sK    .."

dV$WI&4@	 	 	
 rN   c                l    U R                  5       nU R                  R                  SSU0SU/0SU0S9  U$ )Nconcatr   r  r   r  rJ  )r   r  r   rK  s       rO   
_concatVarVariable._concatVar
  sJ    .."

=WI&	 	 	
 rN   c                N   [        U[        5      (       a  U R                  U   S:  a  U R                  S5      $ U R	                  XR                  U   5      u  p4nUS:X  a  U R                  U/U/U/5      $ / nUS:  a9  X4:  a3  UR                  U R                  U/U/US-   /5      5        X5-  nX4:  a  M3  O8X4:  a3  UR                  U R                  U/U/US-   /5      5        X5-  nX4:  a  M3  U R                  Xb5      $ [        U[        5      (       a  U R                  U   S:  a  U R                  S5      $ [        U5      nUS:  a  XpR                  U   :  d  US:  a   XpR                  U   -   S:  a  [        S5      eU R                  U/U/US-   /5      $ [        S5      e)Nr   Tr   r=  z(Valid index accept int or slice or tuple)
rT   r+  r-  rE  r.  rL  r   rP  r  r>  )r   r@  r   r'  r*  r&  r  r   s           rO   _sliceAndConcatVarVariable._sliceAndConcatVar
  s   dE""zz$!#~~d++ $ 3 3D**T:J KEqy~~tfugv>>!8, NND6E7UQYKH 	  ,  , NND6E7UQYKH 	  ,
 t22c""zz$!#~~d++IE	ezz$'77	uzz$'771< 11>>4&5'EAI;??GHHrN   c                    [        X5      $ rK   )r   )r   r@  s     rO   __getitem__Variable.__getitem__  s    t**rN   c                T    SSK Jn  U" 5       (       a  [        XU5      $ [        S5      e)Nr   r4  zIn static mode, the __setitem__ (looks like: x[indices] = values) should not be used. Please use x = paddle.static.setitem(x, indices, values))r6  r5  r   r  )r   r@  r`   r5  s       rO   __setitem__Variable.__setitem__  s.    3"4u55 a rN   c                (   SSK Jn  Ub7  [        U[        R                  5      (       d  [        S[        U5       S35      eUc  U" 5       nUR                  U R                  5      nUc  [        SU R                   S35      eUR                  5       nU$ )a  
Get the value of variable in given scope.

Args:
    scope(Scope, optional) : If `scope` is None, it will be set to global scope
        obtained through 'paddle.static.global_scope()'. Otherwise, use `scope`.
        Default: None

Returns:
    Tensor, the value in given scope.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static
        >>> import numpy as np

        >>> paddle.enable_static()

        >>> x = static.data(name="x", shape=[10, 10], dtype='float32')

        >>> y = static.nn.fc(x, 10, name='fc')
        >>> place = paddle.CPUPlace()
        >>> exe = static.Executor(place)
        >>> prog = paddle.static.default_main_program()
        >>> exe.run(static.default_startup_program())
        >>> inputs = np.ones((10, 10), dtype='float32')
        >>> exe.run(prog, feed={'x': inputs}, fetch_list=[y, ])
        >>> path = 'temp/tensor_'
        >>> for var in prog.list_vars():
        ...     if var.persistable:
        ...         t = var.get_value()
        ...         paddle.save(t, path+var.name+'.pdtensor')

        >>> for var in prog.list_vars():
        ...     if var.persistable:
        ...         t_load = paddle.load(path+var.name+'.pdtensor')
        ...         var.set_value(t_load)
r   global_scopeC`scope` should be None or `paddle.static.Scope` type, but received r  Can not find Variable '' in the Scope.)executorr]  rT   r   _ScoperV   r   rw  r   r]   
get_tensor)r   r  r]  var_tempr`  s        rO   	get_valueVariable.get_value  s    X 	+Zt{{%C%CUVZ[`VaUbbcd  = NE>>$)),)$))OD  !rN   c           	        SSK Jn  [        U[        R                  5      (       d)  [        US5      (       d  [        S[        U5       S35      eUb7  [        U[        R                  5      (       d  [        S[        U5       S35      eUc  U" 5       nUR                  U R                  5      nUc  [        SU R                   S	35      eUR                  5       n[        US
5      (       a  [        UR                  [        [         45      (       a  UR                  5       nOUR                  n[#        UR                  5       5      [#        U5      :w  a>  [        U R                   S[#        UR                  5       5       S[#        U5       S35      eUR%                  5       nUR'                  5       (       a  [        R(                  " 5       nGOUR+                  5       (       a  [        R,                  " 5       nGOoUR/                  5       (       a  [        R0                  " 5       nGOCUR3                  5       (       aY  [        R4                  " 5       nUR7                  UR%                  5       5        [        R8                  " UR;                  5       5      nOUR=                  5       (       ah  [        R4                  " 5       nUR7                  UR%                  5       5        [        R>                  " URA                  5       URC                  5       5      nOX[        R4                  " 5       nUR7                  UR%                  5       5        [        RD                  " URG                  5       5      nURI                  X5        g)a  

Set the value to the tensor in given scope.

Args:
    value(Tensor/ndarray) : The value to be set.
    scope(Scope, optional) : If `scope` is None, it will be set to global scope
        obtained through 'paddle.static.global_scope()'. Otherwise, use `scope`.
        Default: None

Returns:
    None

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static
        >>> import numpy as np

        >>> paddle.enable_static()

        >>> x = static.data(name="x", shape=[10, 10], dtype='float32')

        >>> y = static.nn.fc(x, 10, name='fc')
        >>> place = paddle.CPUPlace()
        >>> exe = static.Executor(place)
        >>> prog = paddle.static.default_main_program()
        >>> exe.run(static.default_startup_program())
        >>> inputs = np.ones((10, 10), dtype='float32')
        >>> exe.run(prog, feed={'x': inputs}, fetch_list=[y, ])
        >>> path = 'temp/tensor_'
        >>> for var in prog.list_vars():
        ...     if var.persistable:
        ...         t = var.get_value()
        ...         paddle.save(t, path+var.name+'.pdtensor')

        >>> for var in prog.list_vars():
        ...     if var.persistable:
        ...         t_load = paddle.load(path+var.name+'.pdtensor')
        ...         var.set_value(t_load)

r   r\  	__array__zA`value` should be `numpy.ndarray` or `DenseTensor`, but received r  Nr^  r_  r`  r-  z expected a shape z, but the received shape is )%ra  r]  rT   r  rC  r  rV   r   r   rb  rw  r   r]   rc  r-  r   r   rd   _placeis_cpu_placerY  is_cuda_pinned_placer  is_xpu_pinned_placer  is_xpu_placerT  	set_placer\  xpu_device_idis_custom_placer`  custom_device_typecustom_device_idrW  gpu_device_idset)	r   r`   r  r]  rd  r`  value_shaper  rk  s	            rO   	set_valueVariable.set_valueY  s   ` 	+5"**--1L1LSTXY^T_S``ab  Zt{{%C%CUVZ[`VaUbbcd  = NE>>$)),)$))OD  !5'""%++
L'ABB#kkm#kkAGGI${"33 yyk!3DO3DD`aefqar`sstu  HHJ>>MMOE##%%((*E""$$'')E^^

AKK
#MM!//"34E  

AKK
#$$$$&(:(:(<E 

AKK
#NN1??#45E	erN   c                   [         R                  " U R                  R                  R                  5         U R                  R                  [         R                  " U R                  S-   5      [        R                  R                  R                  S9nU R                  R                  SSU /0SU/0S9  UsSSS5        $ ! , (       d  f       g= f)a  

Returns the number of elements for current Variable, which is a int64 Variable with shape [] .

Returns:
    Variable, the number of elements for current Variable

Examples:
    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()

        >>> # create a static Variable
        >>> x = paddle.static.data(name='x', shape=[3, 2, 1])

        >>> # get the number of elements of the Variable
        >>> y = x.size

_sizerD  sizerH  r  r  N)r   r  rn  ro  rp  r  r  r   r   r  r  r
  r  r  s     rO   rz  Variable.size  s    . tzz11AABZZ** <<II' ll**00	 + F JJ  $() ! 
  CBBs   B B??
Cc                &    U R                  X5        g)z

Set the value of attribute by attribute's name.

Args:
    name(str): the attribute name.
    val(int|str|list): the value of the attribute.

N_update_desc_attrr   s      rO   	_set_attrVariable._set_attr  s     	t)rN   c                8    U R                   R                  U5      $ )z

Whether this Variable has the attribute with the name `name` or not.

Args:
    name(str): the attribute name.

Returns:
    bool, True if has this attribute.

rv  r  r   r   s     rO   	_has_attrVariable._has_attr  s     yy!!$''rN   c                :    U R                   R                  U5        g rK   rv  remove_attrr  s     rO   _remove_attrVariable._remove_attr      		d#rN   c                :    U R                   R                  X5        g)z
Update the value of desc's attribute by attribute's name.

Args:
    name(str): the attribute name.
    val(int|str|list): the value of the attribute.
N)rv  r  r   s      rO   r~  Variable._update_desc_attr  s     			D&rN   c                6    U R                   R                  5       $ )z(Get the names of all attributes defined.rv  
attr_namesr  s    rO   r  Variable.attr_names  s     yy##%%rN   c                8    U R                   R                  U5      $ )z
Get the attribute by name.

Args:
    name(str): the attribute name.

Returns:
    int|str|list, The attribute value. The return value
    can be any valid attribute type.
rv  rT  r  s     rO   rT  Variable.attr       yy~~d##rN   c                .    U R                   R                  $ z-
Get distributed attribute of this Variable.
rv  r  r  s    rO   r  Variable.dist_attr!      
 yy"""rN   c                $    XR                   l        gz-
Set distributed attribute of this Variable.
Nr  r   r  s     rO   r  r  (      
 (		rN   )	r  rt  rn  rv  ru  r  r  r  r  FrK   )=r   r   r   r   __doc__r   r  r  r+  r   r  fake_interface_onlyr  non_static_onlyr  r  r  r  r  r   r  r  __repr__r  propertyr  setterr.  r  r   r  r-  r  r~  r   r  r  r  r   r#  r.  r6  r:  rA  rE  rL  rP  rS  rV  rY  re  rv  rz  r  r  r  r~  r  rT  r  r   rM   rN   rO   rN  rN    s   -d \\!!..!t!l0d  > .$ .$` . .` " "H
&Q(=~7r H(@ ) )@ ' ' ' '2 % % ( (( & &    ( # #( 
[[% % ( (* ! !( % %@    * 6 6p'R% " #!J($8
 ID+;zgR$L
*($' & &$ # # ( (rN   rN  )	metaclassc                     [         R                  " 5       n / nU  H<  n[        R                  R	                  [        U5      5      nUR                  U5        M>     U$ )z\
Get all registered op proto from PaddlePaddle C++ end.

Returns:
   list: list of OpProto.
)r   get_all_op_protosr   OpProtor  r  r   )	protostrs
ret_valuespbstrrR  s       rO   r  r  0  sQ     &&(IJ ((33E%LA(#  rN   c                  P    \ rS rSrSr\S 5       rS rS rS r	S r
\S 5       rS	rg
)OpProtoHolderi?  z:
A global variable to hold all OpProtos from C++ as a map
c                T    [        U S5      (       d  U " 5       U l        U R                  $ )N	_instance)r  r  )r^  s    rO   r_  OpProtoHolder.instanceD  s"    sK((ECM}}rN   c                    [        U R                  S5      (       a   S5       e[        5       n0 U l        U H  nX R                  UR                  '   M     g )Nr  z4Please use `instance()` to get OpProtoHolder object!)r  r   r  op_proto_mapr   )r   	op_protosr#  s      rO   r   OpProtoHolder.__init__J  sQ    4>>;77 	
B	
7 &'	E,1ejj) rN   c                \    XR                   ;  a  [        SU S35      eU R                   U   $ )z
Get OpProto by a type string.
Args:
    type(str): The type that operator registered in C++ side.

Returns(framework_pb2.OpProto): The OpProto

z
Operator "z" has not been registered.)r  r]   r   r   s     rO   get_op_protoOpProtoHolder.get_op_protoS  s6     (((z$/IJKK  &&rN   c                &   [        5       n/ nU HR  nUR                  U R                  ;  d  M  X@R                  UR                  '   UR                  UR                  5        MT     [	        [        U5      R                  [        U5      5      5      nU$ rK   )r  r   r  r   rd   rt  union)r   new_op_listr  custom_op_namesr#  s        rO   update_op_protoOpProtoHolder.update_op_proto`  sv    %'	Ezz!2!2205!!%**-&&uzz2  s?399#k:JKLrN   c                    XR                   ;   $ rK   r  r  s     rO   has_op_protoOpProtoHolder.has_op_protoj  s    ((((rN   c                 (   [         R                  R                  5       [         R                  R                  5       [         R                  R	                  5       [         R                  R                  5       [         R                  R                  5       1$ rK   )r   op_proto_and_checker_makerkOpRoleAttrNamekOpRoleVarAttrNamekOpNameScopeAttrNamekOpCreationCallstackAttrNamekOpDeviceAttrNamerM   rN   rO   generated_op_attr_names%OpProtoHolder.generated_op_attr_namesm  sh     ++;;=++>>@++@@B++HHJ++==?
 	
rN   r  N)r   r   r   r   r  rd  r_  r   r  r  r  staticmethodr  r   rM   rN   rO   r  r  ?  sC      
2') 
 
rN   r  c                     \ rS rSrSr1 Skr S,S jrS rS rS-S jr	S	 r
\
r\S
 5       rS rS rS r\S 5       r\S 5       r\S 5       rS r\S 5       r\S 5       rS rS rS rS rS rS r\S 5       rS rS rS r S r!S r"S  r#S! r$S" r%S# r&S$ r'\S% 5       r(\(RR                  S& 5       r(S' r*\S( 5       r+\S) 5       r,\,RR                  S* 5       r,S+r-g).Operatorix  a  
In Fluid, all the operation are represented by Operator, and Operator
is regarded as a build in an instruction of a Block. Users can use the
build in instructions to describe their neural network.

Args:
    block(Block): The block has the current operator.
    desc(core.OpDesc): The protobuf description of Operator.
    type(str): The type of operator. Default None.
    inputs(dict): The input of this Operator. it is a dictionary, for every
        element, key is the input parameter name, and value is a list of
        variables. Default None.
    outputs(dict): The output of this Operator. it is a dictionary, for
        every element, key is the input parameter name, and value is a list
        of variables. Default None.
    attrs(dict): The attributes of this Operator. it is a dictionary, for
        every element, key is attribute name, and value is the attribute value.
        The attribute type should be as same as the type registered in C++ side.
        Default None.

Returns:
    Operator: The initialized Operator.

Raises:
    ValueError: If the passed input, output and attrs doesn't match the
        initializing Operator's that registered in C++ side.

Notes:
    The constructor of operator should not be invoked directly. Use
    Block.append_op or Block._prepend_op instead.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()
        >>> cur_program = paddle.static.Program()
        >>> cur_block = cur_program.current_block()
        >>> var1 = cur_block.create_var(name="var1", shape=[-1, 23, 48], dtype='float32')
        >>> var2 = cur_block.create_var(name="var2", shape=[-1, 23, 48], dtype='float32')
        >>> var3 = cur_block.create_var(name="var3", shape=[-1, 23, 48], dtype='float32')
        >>> var1 += var2 + var3
        >>> cur_block.append_op(type="sum",
        ...                     inputs={"X": [var1, var2, var3]},
        ...                     outputs={"Out": [var1]})
>   gofeedrecvsendfetchwhileselectpylayerc_comm_initc_wait_commgen_bkcl_idgen_nccl_idc_gen_bkcl_idc_gen_nccl_idc_wait_computelisten_and_servcheckpoint_notifyconditional_blockc_sync_calc_streamc_sync_comm_streamfl_listen_and_servheter_listen_and_servNc                r    [         R                  5       R                  U5      n0 U l        UR                   H&  nUR
                  U R                  UR                  '   M(     [        5       (       a%  Uc  [        S5      eX0l	        U(       a  UO0 U l        g Xl
        X l        Un	U	c  0 n	A[        U l        SSKJn
  Xl        [#        5       U l        [&        R(                  nUR+                  5       U	;  a0  U R                  R,                  R.                  XR+                  5       '   UR1                  5       n[3        U R                  R,                  R4                  5      S:w  a'  X;  a"  U R                  R,                  R4                  X'   X;   a  [3        X   5      S:X  a  X	 [3        U R                  R                  5       5      S:w  am  U R                  R7                  5        HN  nUR9                  U5      (       d  M  UR;                  U5      R<                  b  M9  XR;                  U5      l        MP     g Uc  [        S5      eUR?                  5       n/ X'   [@        RB                  " 5        HA  nX   RE                  SUS    SUS    SUS    35        X   RE                  S	US
    35        MC     U R                  RG                  U5        [         R                  5       R                  U5      nURI                  5       n[K        5       U	U'   [L        b~  U RO                  U5      (       a  URQ                  5       n[L        U	U'   O[R        RT                  " SU S35        SU	;   a.  US:X  a  U	S   c  U	S   SLa  [R        RT                  " SU S35        [V        b.  S[&        RX                  " 5       -   nU R[                  U[V        5        S nUGb  UR\                   GH  nU" UUR                  5      nU(       d&  UR^                  (       d   SUR                   S35       eU(       Gax  UUR                     n[a        U[b        [d        45      (       d  U/nURf                  (       d4  [3        U5      S:  a%  [        SUR                   S[3        U5       S35      e/ n[i        U5       H  u  nn[a        U[j        5      (       a  URE                  U5        M.  [a        U[l        5      (       a!  URE                  URo                  5       5        Md  [a        U[p        [&        Rr                  Rt                  45      (       a  URE                  UR                  5        M  [w        SUR                   SU SU 35      e   U R                  Ry                  UR                  U5        GM  U R                  Ry                  UR                  / 5        GM     UGb,  URz                   H  nUR                  U;  a  UR^                  (       a  M&  [&        R|                  " 5       (       aT  UR                  U;   dB  UR^                  (       d/  UR~                  (       d  [        SU SUR                   S35      eM  M  M  UR                  U;   a  M  UR^                  (       a  M  [        SU SUR                   S35      e   URz                   GH8  nUR                  U;  a  M  UUR                     n[a        U[b        5      (       d  U/nURf                  (       d4  [3        U5      S:  a%  [        SUR                   S[3        U5       S35      e/ nU H  n[a        U[j        5      (       a  URE                  U5        OURE                  UR                  5        [        5       (       a  MV  [a        U[j        5      (       a  XR;                  U5      l        M  Xl        M     U R                  R                  UR                  U5        GM;     [&        R                  " U5      nU	Gb%  [a        U	[        5      (       d  [w        S 5      eUR                   H4  nUR                  nUU	;  d  U	U   c  M  U	U   nU R[                  UU5        M6     UR                  5        H{  n[        R                  R                  S!S"5      S#:X  a  [R        RT                  " S$U S%U 35        UU	;  d  U	U   c  U R[                  UUU   5        Mf  U R[                  UU	U   5        M}     [        R                  R                  S!S"5      S#:X  Ga  U[        ;   aP  [        R                  U/ 5      nU H4  nXR                  5       ;   d  M  [R        RT                  " S$U S%U 35        M6     U[        ;   a  [        R                  U/ 5      nU H  n[        [        UR                  5       5      5      n [        [        UR                  5       5      5      n!U U	R                  5       ;   d  M]  U!U	U    :w  d  Mh  [R        RT                  " S$U S&U  S'U	U     S(U! 35        M     [&        R                  " 5       (       aH  [        S:  a  U R[                  [        [        5        [        S:  a  U R[                  [        [        5        U R                  R                  5         U RO                  U5      (       a_  U R                  R                  U R                  R                  5        U R                  R                  U R                  R                  5        g g ! [         a     G
Nf = f))Nz2`type` to initialized an Operator can not be None.r   )DEFAULT_AMP_OPTIONSz  File "z", line r   z, in r          zThe Op(z) is not support to set device.	force_cpur0   FzThe Attr(force_cpu) of Op(z) will be deprecated in the future, please use 'device_guard' instead. 'device_guard' has higher priority when they are used at the same time.pipeline_stagec                2    U  H  nX   c  M
  X!:X  d  M    g   gr(  rM   )var_listr   r  s      rO   	find_name$Operator.__init__.<locals>.find_name4  s"     (H)5(:J# !) rN   zInput z
 not foundz expects only one input, but z are given.zThe type of '%z' in operator z9 should be one of [str, bytes, Variable]. but received : z-Incorrect setting for output(s) of operator "z", should set: [z].zOutput z expects only one output, but z'attrs' should be a dict.FLAGS_print_extra_attrsrz   r   zop z use extra_attr: z's attr  = z is not the default value: )Tr  r_  r  _attr_typesrM  r   r   r]   r   _typern  rv  _current_cuda_graph_mode_cuda_graph_attrpaddle.static.amp.fp16_utilsr  _amp_optionsr  _struct_namer   r  r  ro  _op_roler  r[   _op_role_varoutput_arg_nameshas_varry  r  r  	tracebackextract_stackr   rz  r  r  _current_device_has_kernelr  r  r  r>  kAutoParallelSuffixr~  r  dispensablerT   rd   re   
duplicabler1  r\   r  decoderN  r)  r*  rV   	set_inputr  _is_bwd_prim_enabledintermediate
set_outputget_op_extra_attrsrU   rr  r~   r   r   extra_op_attrsspecial_op_attrsnextitervaluesr   r   ipu_index_attr_namer   ipu_stage_attr_namecheck_attrsinfer_var_typeinfer_shape)"r   rn  rv  r   r  r  rM  r#  rT  op_attrsr  op_makerrole_var_nameargcallstack_var_nameframenamescope_var_name	op_devicepipeline_attr_namer  in_protofoundin_argsin_arg_namesr   m	out_protoout_argsout_arg_namesextra_attrs_maprU  rW  a_namedefault_values"                                     rO   r   Operator.__init__  s	   
	!**,99$?E!D.2ii  + $
 | H  J"'RDJJI H %=D! I,? !2 3D66H'')9JJ&&// 1134 %779MDJJ&&3349!1*.***<*<*I*I'(S1H-IQ-N+499>>#$)  99557C}}S))eiin.?.?.G,0		#) 8 | H  &.%J%J%L"/1,&446E077"58*HU1XJeE!H:N 077$uQxj8IJ	 7 IIt$!**,99$?E!)!>!>!@+;+=H'(
 *##D)) ( : : <I*9HY'MM!$'FG (*+$[1=!+.e; 8 ?5 5
 '2$t'?'?'AA # &&&(? ! %H%fhmm<E H$8$8  z:8 "("7)'D%=AA'.iG'22s7|a7G","(7TUXY`UaTbbm n#  (**3G*<JE3)#s33 , 3 3C 8!+C!7!7 , 3 3CJJL A!+C(DJJ<M<M1N!O!O , 3 3CHH =&/&4X]]O>RVQW XUUXTY%['" !" += 		++HMM<H		++HMM2>9 !-< "Ag-1==  0022VVw. }} ~~",!--1F2B166("!N#   .  - / "#7!2q}}}",!--1F2B166("!N# + '4 "'I ~~W4 &y~~6H%h55$,:$//CMA4E(%inn%55STWX`TaSbbmn  %'M'%c3//)005)00:.00)#s3348		# 1)-  ( II((G- "/0 #55d;O#!(D11#$?@@!KKD $		I!1 +3 '	2H**9h? ( "1!5!5!7Izz~~&?EL D61B9+&NO!1 +3..%y'A ..y(9:MN "8 ::>>";SASH~- . 2 24 <$)D#}}6 (&)$/@$G!" %* // 0 4 4T2 >$)D%)$tyy{*;%<F,0dkkm1D,EM &(--/ 9$1Xf5E$E (&)$xxs8FCSBTTop}o~$!" %* ((**#q(**+-= $q(**+-= II!!#%%		((9		%%djjoo6 &y  		s   A l( (
l65l6c                    XR                   ;  $ rK   )OP_WITHOUT_KERNEL_SET)r   op_types     rO   r   Operator._has_kernel  s    8888rN   c                    U R                   R                  5       n[        R                  R	                  [        U5      5      n[        X15      $ )z
Get debug string.

Args:
    throw_on_error(bool): Whether to raise exception if self is not
        initialized.

Returns:
    str: The debug string.

)rv  r  r   OpDescr  r  r&  )r   r$  r  r#  s       rO   r  Operator.to_string  s;     99002$$//h@e44rN   c                p	   [        U[        5      (       d   S[        U5       35       eSn[        S[	        U R
                  5      5       H]  nX R
                  U    S3-  nU R                  U R
                  U   5      nX$ -  nU[	        U R
                  5      S-
  :w  d  MX  US-  nM_     US-  nSn[        S[	        U R                  5      5       H]  nXPR                  U    S3-  nU R                  U R                  U   5      nXT -  nU[	        U R                  5      S-
  :w  d  MX  US-  nM_     US-  n[        U R                  5      nSn[        S[	        U5      5       GH  nXc   nU(       a  US	:X  a  M  U R                  R                  US
5      n	U	[        R                  R                  :X  aO  U R                  R!                  US
5      R#                  5       n
U SU
 S3nX{-  nU[	        U5      S-
  :w  a  US-  nM  U	[        R                  R$                  :X  a{  U R                  R!                  US
5       Vs/ s H  nSUR#                  5        S3PM     nnSR'                  USR)                  U5      S9nX{-  nU[	        U5      S-
  :w  a  US-  nGM9  U	[        R                  R*                  :X  a5  U SU R-                  U5       S3nX{-  nU[	        U5      S-
  :w  a  US-  nGM  U	[        R                  R.                  :X  a4  U SU R1                  U5       3nX{-  nU[	        U5      S-
  :w  a  US-  nGM  [3        5       (       a  U R                  S:X  a  US:X  a  U R                  R!                  U5      n[        R4                  " U5      n[7        5       nUR9                  U5      nUR;                  5       nUR=                  S5      nSR)                  U Vs/ s H  nSU-   PM
     sn5      nSU-   nOU R                  R!                  U5      nU SU 3nX{-  nU[	        U5      S-
  :w  d  GM  US-  nGM     SSKJ n  U" 5       nURC                  U 5      nUb  USR'                  SUS9-  nUS:w  a  U SU R                   SU SU S3nU$ U R                   SU SU S3nU$ s  snf s  snf )a  
Get readable debug string of Operator.

.. note::
    If you want to get the debug string in protobuf format,
    please use :code:`to_string` method.

Args:
    skip_op_callstack(bool): whether to skip parsing Operator's attribute
        op_callstack, default value is True

Returns:
    string: The formatted Operator string.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()
        >>> cur_program = paddle.static.Program()
        >>> cur_block = cur_program.current_block()
        >>> var = cur_block.create_var(name="X",
        ...                            shape=[-1, 23, 48],
        ...                            dtype='float32')
        >>> new_op = cur_block.append_op(type="abs",
        ...                              inputs={"X": [var]},
        ...                              outputs={"Out": [var]})
        >>> print(new_op._to_readable_code())
Cskip_op_callstack parameter's type is error, expect bool, received {r   =r   r  }r  op_callstackTz = Var['z']rB  z{name} = Vars[{value}]r|  r  z	 = block[]z	 = blockscinn_launchcompilation_keyr   z      r  r  r  r  z{}z(inputs=r  )"rT   r  r   r  r[   output_namesr  input_namesinputsortedr  rv  	attr_typer   rO  VARrT  r   VARSr  r   BLOCK_block_attr_idBLOCKS_blocks_attr_idsr   get_serialize_compile_keyProgramparse_from_stringr  r  r  r  get_dist_op_for_program)r   skip_op_callstackoutputs_strr  r5  
inputs_strr  	attrs_strr   r=  attr_var_nameary  attr_var_namesr_   r4  progr  linesliner`   r  r  dist_opop_strs                            rO   r  Operator._to_readable_code  s   > +T22 	
QRVWhRiQjk	
2 q#d//01A//23155KD--a01AS!KC))*Q..t# 2 	s
q#d../0A--a0133J

4++A./AC JC(()A--d"
 1 	c
DOO,
	q#j/*A=D T^%;		++D$7IDMM--- $		tT : ? ? AfH]O26	J!++%IDMM...15d1K"1K#a
|1%1K  " -33SXXn%= 4  	J!++%IDMM///fId&9&9$&?%@B	J!++%IDMM000fId&;&;D&A%BC	J!++%I &''II.--iinnT*2237y--a0**,		u"Eut8d?u"EFu		t,&E7#ANIC
Oa''T!	{ +~	
 7866t<-44  5  I $-s499+Xj\I;aP 
  		{(:,b1EFC"J #Fs   ?R."R3
c                "    U R                  5       $ rK   r  r  s    rO   r   Operator.__str__h  r  rN   c                6    U R                   R                  5       $ rK   r	  r  s    rO   r   Operator.typem  s    yy~~rN   c                8    U R                   R                  U5      $ )z

Get the input arguments according to the input parameter name.

Args:
    name(str): The input parameter name.

Returns:
    list, return the list of argument names that associated with \
        the specific parameter name.

)rv  r;  r  s     rO   r;  Operator.inputq  s     yyt$$rN   c                :    U R                   R                  X5        g)z
Rename the `old_name` to `new_name`.

Args:
    old_name(str): The old name of the Operator's input.
    new_name(str): The new name of the Operator's input.

Returns:
    None
N)rv  _rename_inputr   old_namer   s      rO   r\  Operator._rename_input  s     			3rN   c                :    U R                   R                  X5        g)z
Rename the `old_name` to `new_name`.

Args:
    old_name(str): The old name of the Operator's output.
    new_name(str): The new name of the Operator's output.

Returns:
    None
N)rv  _rename_outputr]  s      rO   ra  Operator._rename_output  s     			  4rN   c                6    U R                   R                  5       $ rK   )rv  r:  r  s    rO   r:  Operator.input_names  s    yy$$&&rN   c                6    U R                   R                  5       $ rK   )rv  input_arg_namesr  s    rO   rf  Operator.input_arg_names  s    yy((**rN   c                6    U R                   R                  5       $ rK   )rv  r  r  s    rO   r  Operator.output_arg_names  s    yy))++rN   c                8    U R                   R                  U5      $ )z
Get output arguments by the output parameter name.

Args:
    name(str): The output parameter name.

Returns:
    list: return the list of argument names associated with \
        the specific parameter name.
)rv  r  r  s     rO   r  Operator.output  s     yy%%rN   c                6    U R                   R                  5       $ rK   )rv  r9  r  s    rO   r9  Operator.output_names  s    yy%%''rN   c                z    [        U R                  R                  5       H  u  pX :X  d  M  Us  $    [        S5      e)Nz@Can't find op itself in it's block. It could be a bug of Paddle.)r1  rn  r  r]   )r   r  r  s      rO   r  Operator.idx  s7    tzz~~.EAz / N
 	
rN   c                8    U R                   R                  U5      $ )z
Whether this Operator has the attribute with name or not.

Args:
    name(str): the attribute name.

Returns:
    bool: True if has this attribute.

r  r  s     rO   r  Operator.has_attr  s     yy!!$''rN   c                :    U R                   R                  US5      $ )z
Get the type of attribute by attribute's name.

Args:
    name(str): the attribute name.

Returns:
    core.AttrType: the attribute type.
T)rv  r=  r  s     rO   r=  Operator.attr_type  s     yy""4..rN   c                &    U R                  X5        g)z
Set the value of attribute by attribute's name.

Args:
    name(str): the attribute name.
    val(bool|int|str|float|list): the value of the attribute.

Raises:
    ValueError: If the type of value doesn't match with desc.attr_type(name).
Nr}  r   s      rO   r  Operator._set_attr  s     	t)rN   c                :    U R                   R                  U5        g rK   r  r  s     rO   r  Operator._remove_attr  r  rN   c                f   [        U[        5      (       a&  U R                  R                  XR                  5        g[        U[        5      (       aK  [        U[        5      (       a6  U R                  R                  X Vs/ s H  o3R                  PM     sn5        g[        U[        5      (       a&  U R                  R                  XR                  5        g[        U[        5      (       aR  U(       aK  [        U[        5      (       a6  U R                  R                  X Vs/ s H  o3R                  PM     sn5        g[        U[        R                  [        R                  45      (       a*  U R                  R                  XR                  5       5        gU R                  X5        gs  snf s  snf )z
Update the value of desc's attribute by attribute's name.

Args:
    name(str): the attribute name.
    val(bool|int|str|float|list): the value of the attribute.

Raises:
    ValueError: If the type of value doesn't match with desc.attr_type(name).
N)rT   rN  rv  set_var_attrrd   r:  set_vars_attrBlockset_block_attrset_blocks_attrr   	BlockDescProgramDescset_serialized_attrr  _update_desc_plain_attr)r   r   r   r4  s       rO   r~  Operator._update_desc_attr  s    c8$$II""42T""|C'B'BII##D3*?3a663*?@U##II$$T884T""s|C/G/GII%%dS,ASVVS,ABdnnd.>.>?@@II))$0G0G0IJ((3 +@ -Bs   ?F)
!F.
c                (   U R                   n[        U S5      (       a  XR                  ;  a  UR                  X5        g U R                  U   nU[        R
                  R                  :X  a  UR                  U[        U5      5        g U[        R
                  R                  :X  a  UR                  U[        U5      5        g U[        R
                  R                  :X  a  UR                  X5        g U[        R
                  R                  :X  a  UR                  X5        g U[        R
                  R                   :X  a  UR#                  X5        g U[        R
                  R$                  :X  a  UR'                  X5        g U[        R
                  R(                  :X  a  UR+                  X5        g U[        R
                  R,                  :X  a  UR/                  X5        g U[        R
                  R0                  :X  a  UR3                  X5        g U[        R
                  R4                  :X  a  UR7                  X5        g U[        R
                  R8                  :X  a  UR;                  X5        g U[        R
                  R<                  :X  a  UR?                  X5        g U[        R
                  R@                  :X  a  URC                  X5        g U[        R
                  RD                  :X  a  URG                  X5        g UR                  X5        g )Nr  )$rv  r  r  r  r   rO  rP  _set_scalar_attrrA  rQ  _set_scalars_attrrH  r  _set_bool_attrINT_set_int32_attrLONG_set_int64_attrFLOAT_set_float32_attrFLOAT64_set_float64_attrSTRING_set_str_attrBOOLS_set_bools_attrINTS_set_int32s_attrLONGS_set_int64s_attrFLOATS_set_float32s_attrFLOAT64S_set_float64s_attrrr  _set_strs_attr)r   r   r   rv  rV  s        rO   r   Operator._update_desc_plain_attr  s   yyt]++<L<L0LNN4%%%d+
---!!$s(;<4==000""4)=>4==---*4==,,,  +4==---  +4==...""4-4==000""4-4==///t)4==...  +4==---!!$,4==...!!$,4==///##D.4==111##D.4==000* NN4%rN   c                8    U R                   R                  S5      $ NTr  r  s    rO   r  Operator.attr_names)  s    yy##D))rN   c                8    U R                   R                  U5      $ )z
Get the attribute by name.

Args:
    name(str): the attribute name.

Returns:
    bool|int|str|float|list: The attribute value. The return value
    can be any valid attribute type.
r  r  s     rO   rT  Operator.attr-  r  rN   c                8    U R                   R                  U5      $ )zu
Get the block attribute's id by name.

Args:
    name(str): the attribute name.

Returns:
    int: the block index.
)rv  rA  r  s     rO   rA  Operator._block_attr_id:  s     yy''--rN   c                    U R                  U5      nUS:  a-  U[        U R                  R                  R                  5      :  d   eU R                  R                  R                  U   $ )zw
Get the block attribute  by name.

Args:
    name(str): the attribute name.

Returns:
    block: the block attribute.
r   )rA  r[   rn  ro  blocks)r   r   ids      rO   _block_attrOperator._block_attrF  sX       &Qw2DJJ$6$6$=$= >>>>zz!!((,,rN   c                   / nU R                  U5       Hj  nUS:  a-  U[        U R                  R                  R                  5      :  d   eUR                  U R                  R                  R                  U   5        Ml     U$ )z
Get the blocks attribute  by name.

Args:
    name(str): the attribute name.

Returns:
    list: list of the blocks attribute.
r   )rC  r[   rn  ro  r  r   )r   r   rM  r  s       rO   _blocks_attrOperator._blocks_attrU  so     &&t,A6a#djj&8&8&?&?"@@@@LL++22156 - rN   c                8    U R                   R                  U5      $ )z
Get the blocks attribute's ids by name.

Args:
    name(str): the attribute name.

Returns:
    list: list of the blocks ids.
)rv  rC  r  s     rO   rC  Operator._blocks_attr_idsf  s     yy))$//rN   c                   U R                   R                  US5      nU[        R                  R                  :X  d   SU SU 35       eU R                   R                  US5      R                  5       nU R                  R                  U5      $ )z
Get the Variable attribute  by name.

Args:
    name(str): the attribute name.

Returns:
    Variable: the Variable attribute.
TRequired type attr(z) is Variable, but received )	rv  r=  r   rO  r>  rT  r   rn  _var_recursive)r   r   r=  rL  s       rO   	_var_attrOperator._var_attrs  s~     II''d3	DMM--- 	
!$'CI;O	
- 		tT2779zz((77rN   c                D   U R                   R                  US5      nU[        R                  R                  :X  d   SU SU 35       eU R                   R                  US5       Vs/ s H,  nU R                  R                  UR                  5       5      PM.     nnU$ s  snf )z
Get the Variables attribute  by name.

Args:
    name(str): the attribute name.

Returns:
    Variables: the Variables attribute.
Tr  z") is list[Variable], but received )	rv  r=  r   rO  r?  rT  rn  r  r   )r   r   r=  ry  	attr_varss        rO   
_vars_attrOperator._vars_attr  s     II''d3	DMM... 	
!$'I)U	
.
 yy~~dD1
1 JJ%%chhj11 	 
 	
s   &3Bc                ,   U R                   n0 nU H  nU R                  R                  US5      nU[        R                  R
                  :X  a  U R                  U5      X#'   MR  U[        R                  R                  :X  a  U R                  U5      X#'   M  U[        R                  R                  :X  a  U R                  U5      X#'   M  U[        R                  R                  :X  a  U R                  U5      X#'   M  U R                  U5      X#'   GM     U$ )zX
Get the attribute dict.

Returns:
    dict: The Operator's attribute dict, name->attr.
T)r  rv  r=  r   rO  r@  r  rB  r  r>  r  r?  r  rT  )r   r  attr_mapru   r=  s        rO   	all_attrsOperator.all_attrs  s     __
A		++At4IDMM///"..q1dmm222"//2dmm///"nnQ/dmm000"ooa0"iil  rN   c                D   [         R                  n[         R                  R                  R                  nU R                  R                  UR                  5       5      (       d  gU R                  R                  UR                  5       5      nU[        U5      -  (       a  ggNFT)	r   r  OpRoleOptimizerv  r  r  rT  r  )r   r  OPTIMIZEop_roles       rO   _is_optimize_opOperator._is_optimize_op  r    222299BByy!!(":":"<==))..!9!9!;<S]"rN   c                D   [         R                  n[         R                  R                  R                  nU R                  R                  UR                  5       5      (       d  gU R                  R                  UR                  5       5      nU[        U5      -  (       a  ggr  )	r   r  r  Backwardrv  r  r  rT  r  )r   r  BACKWARDr  s       rO   _is_backward_opOperator._is_backward_op  r  rN   c                .    U R                   R                  $ r  r  r  s    rO   r  Operator.dist_attr  r  rN   c                $    XR                   l        gr  r  r  s     rO   r  r    r  rN   c                    Xl         g)zm
Set auto cast attribute of this Operator.

Args:
    amp_options (AmpOptions): AmpOptions of this Operator.
Nr  )r   amp_optionss     rO   set_amp_optionsOperator.set_amp_options  s
     (rN   c                    U R                   $ )z\
Get auto cast attribute of this Operator.

Returns:
    bool: AmpOptions of this Operator.
r  r  s    rO   r  Operator.amp_options  s        rN   c                    U R                   $ rK   r  r  s    rO   r  Operator.struct_name  s       rN   c                    Xl         g rK   r  )r   r  s     rO   r  r    s    'rN   )r  r  r  r  r  rM  rn  rv  )NNNNT).r   r   r   r   r  r*  r   r   r  r  r   r  r  r   r;  r\  ra  r:  rf  r  r  r9  r  r  r=  r  r  r~  r  r  rT  rA  r  r  rC  r  r  r  r  r  r  r  r  r  r  r   rM   rN   rO   r  r  x  s   .`4 HLH7T95 GR( H   %45 ' ' + + , ,& ( ( 
 
(
/*$40&&P * *$
.-"08"(0 # # ( (( ! ! ! ! ( (rN   r  c               #  ,   #    Sq  S v   Sq g ! Sq f = f7fr(  )#_stride_in_no_check_dy2st_diff_moderM   rN   rO   _stride_in_no_check_dy2st_diffr    s!      +/'4.3+e+s    c           	        U S;   a  g Ub  UR                  5        H  u  p4[        U[        5      (       aC  UR                  (       a0  U S:X  a  UR	                  SS 5      S:X  d  [        SU  SU S35      eM[  M]  [        U[        5      (       d  Mt  U H[  n[        U[        5      (       d  M  UR                  (       d  M-  U S:X  a  UR	                  SS 5      S:X  a  MK  [        SU  SU S35      e   M     g g )N>   r  r  rv  rH  r  z0Sorry about what's happened. In to_static mode, z's output variable z is a viewed Tensor in dygraph. This will result in inconsistent calculation behavior between dynamic and static graphs. If you are sure it is safe, you can call with paddle.base.framework._stride_in_no_check_dy2st_diff() in your safe code block.)rW   rT   rN  r  r   r]   rd   )r+  inplace_mapr  kr4  ry  s         rO   $check_if_to_static_diff_with_dygraphr    s   00 	MMODA!X&&=={*#6%?$J7)Sfghfi  j`  a  @ ! At$$C!#x00???#{2 + >% G","RSZR[[nopnq  rh  !i#   $ rN   c                T   U S:X  a  Ub=  [        US   [        5      (       a%  [        US   S   S5      (       a  SUS   S   l        O[        US   S5      (       a
  SUS   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  a  Ub=  [        US   [        5      (       a%  [        US   S   S5      (       a  SUS   S   l        O[        US   S5      (       a
  SUS   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S
:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub'  US    H  n[        US5      (       d  M  SUl        M     g g U S:X  d  U S:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  d  U S:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  d  U S:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  a  Ub=  [        US   [        5      (       a%  [        US   S   S5      (       a  SUS   S   l        O[        US   S5      (       a
  SUS   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  d  U S:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g U S:X  a  Ub=  [        US	   [        5      (       a%  [        US	   S   S5      (       a  SUS	   S   l        O[        US	   S5      (       a
  SUS	   l        Ub>  [        US   [        5      (       a&  [        US   S   S5      (       a  SUS   S   l        g g [        US   S5      (       a  SUS   l        g g g )Nr+  rH  r   r  Tr  strided_sliceindex_selectr   r  	unsqueeze
unsqueeze2squeezesqueeze2	transposer  unbinddiagonalflattenimagrealreshapereshape2as_real)rT   rd   r  r  )r+  r  r  r  s       rO   record_is_view_varr    s
   '*VG_d"C"Cvgq)=9915w".vg66.2w+:gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	O	#*VG_d"C"Cvgq)=9915w".vg66.2w+:gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	N	"*VC[$"?"?vc{1~}55-1sA*vc{M22*.s':gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	G	*VC[$"?"?vc{1~}55-1sA*vc{M22*.s'u~3..&*CO &  
K	7l#:*VC[$"?"?vc{1~}55-1sA*vc{M22*.s':gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	I	J!6*VC[$"?"?vc{1~}55-1sA*vc{M22*.s':gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	K	7l#:*VC[$"?"?vc{1~}55-1sA*vc{M22*.s':gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	H	*VC[$"?"?vc{1~}55-1sA*vc{M22*.s':gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	J	*VG_d"C"Cvgq)=9915w".vg66.2w+:gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	I	*VC[$"?"?vc{1~}55-1sA*vc{M22*.s':gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	F	*VC[$"?"?vc{1~}55-1sA*vc{M22*.s':gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	F	*VC[$"?"?vc{1~}55-1sA*vc{M22*.s':gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	I	J!6*VC[$"?"?vc{1~}55-1sA*vc{M22*.s':gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6	I	*VC[$"?"?vc{1~}55-1sA*vc{M22*.s':gend#C#Cwu~a(-8804q!- 9 wu~}55-1* 6 
rN   c                      \ rS rSrSrS rS rS!S jrS"S jr\r	\
S 5       r\
S 5       rS	 r\
S
 5       r\
S 5       rS rS rS rS rS rS rS rS rS!S jrS rS rS rS rS!S jrS rS rS r S r!S!S jr"Sr#g )#r{  i  at  
In Fluid, a Program is consistence of multi-Block, and Block stores
VarDesc and OpDesc. In a specific Block, a VarDesc have a unique name.
One block could have some child blocks, and child block's name scopes
should inherit the parent's so that OpDesc in child block can reference
a VarDesc that is stored in the parent block.
Please reference the framework.proto for details.

Args:
    program(Program): The Program that the Block belongs to.
    idx(int): The block's id in the Program.

Notes:
    The constructor of Block should not be invoked directly. Please
    use `Program._create_block()` to create a block.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()
        >>> cur_program = paddle.static.Program()
        >>> cur_block = cur_program.current_block()
        >>> var = cur_block.create_var(name="X",
        ...                            shape=[-1, 23, 48],
        ...                            dtype='float32')
        >>> cur_block.append_op(type="abs",
        ...                     inputs={"X": [var]},
        ...                     outputs={"Out": [var]})
c                    UR                   R                  U5      U l         [        R                  " 5       U l        / U l        Xl        g rK   )rv  rn  collectionsOrderedDictr  r  ro  )r   ro  r  s      rO   r   Block.__init__  s4    LL&&s+	++-	rN   c                "    U R                  5       $ rK   r  r  s    rO   r   Block.__str__  r  rN   c           	        [        U[        5      (       d   S[        U5       35       eSU R                   SU R                   SU R
                   SU R                   S3	n[        U R                  R                  5       5       H  nUSUR                  5        S3-  nM     US-  nU R                   H  nUSUR                  U5       S3-  nM     US-  nU$ )	a  
Get readable debug string of Block.

.. note::
    If you want to get the debug string in protobuf format,
    please use :code:`to_string` method.

Args:
    skip_op_callstack(bool): whether to skip parsing Operator's attribute
        op_callstack, default value is True

Returns:
    string: The formatted Block string.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()
        >>> cur_program = paddle.static.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_var = cur_block.create_var(name="X",
        ...                                shape=[-1, 23, 48],
        ...                                dtype='float32')
        >>> new_op = cur_block.append_op(type="abs",
        ...                     inputs={"X": [new_var]},
        ...                     outputs={"Out": [new_var]})
        >>> print(cur_block._to_readable_code())
r1  z{ // block_idx:z  parent_idx:z  forward_idx:z  backward_idx:r   r  r4  )rT   r  r   r  
parent_idxforward_block_idxbackward_block_idxrd   r  r  r  r  )r   rH  	block_strry  r  s        rO   r  Block._to_readable_code  s
   > +T22 	
QRVWhRiQjk	
2 'txxjdoo=Nn]a]s]s\t  uD  EI  E\  E\  D]  ]_  `			((*+C4 5 5 78;;I ,T	((B4 4 45F GHKKI S	rN   c                   [        U[        5      (       a  [        U[        5      (       d   eU(       a  [        R                  " S5      nSU R                   SU R
                   3n[        U R                  R                  5       5       H6  nUSR                  UR                  SUR                  X5      5      5      -  nM8     U R                   H6  nUSR                  UR                  SUR                  U5      5      5      -  nM8     US-  nU$ U R                  R                  5       n[        R                   R#                  [%        U5      5      n['        X5      nU$ )a^  
Get debug string.

Args:
    throw_on_error(bool): raise exception when self is not initialized
        when throw_on_error is True.
    with_details(bool): more details about variables and parameters
        (e.g. trainable, optimize_attr, ...) will be printed when
        with_details is True. Default False.

Returns:
    str: The debug string.
z\n(.)zblocks {
  idx: z
  parent_idx: z
  vars {{
    {}  }}z\n    \1z
  ops {{
    {}  }}z
})rT   r  r  compiler  r  rd   r  r  r  subr  r  rv  r  r   r~  r  r  r&  )	r   r$  r  re_add_indentr  ry  r  r  r#  s	            rO   r  Block.to_string%  sA    .$//J$5
 5
 	
 
 JJx0M$TXXJ.>t>OP  DII,,./4;;!%%#S]]>%P  0 hh3::!%%k2<<3OP   uG
  yy446H!++66uXGE$U;GrN   c                .    U R                   R                  $ rK   )rv  r  r  s    rO   r  Block.parent_idxN  s    yyrN   c                6    U R                   R                  5       $ rK   )rv  get_forward_block_idxr  s    rO   r  Block.forward_block_idxR  s    yy..00rN   c                :    U R                   R                  U5        g)zU
Set the forward block Idx.

Args:
    idx(int): the block index.

Returns:
    None
N)rv  _set_forward_block_idx)r   r  s     rO   r  Block._set_forward_block_idxV  s     			((-rN   c                    U R                   nU R                  R                   H!  nUR                  U:X  d  M  UR                   s  $    gNr   )r  ro  r  r  )r   cur_block_idxrn  s      rO   r  Block.backward_block_idxb  s<    \\((E&&-7yy  ) rN   c                .    U R                   R                  $ rK   )rv  r  r  s    rO   r  	Block.idxj  s    yy||rN   c                    [        U[        5      (       d  [        S[        U5       S35      eU R                  R                  US5      nUc  [        SU S35      eU$ )a  
Get a Variable by name from this block.

Args:
    name(str): the Variable's name.

Raises:
    ValueError: The If input's type is not str, or this block
        doesn't have a Variable with the giving name.

Returns:
    Variable: the Variable with the giving name.
z)var require string as parameter, but get z	 instead.Nr  z not in this block)rT   r\   rV   r   r  r   r]   )r   r   r4  s      rO   ry  	Block.varn  sc     $$$;DJ<yQ  IIMM$%9tD6);<==rN   c                6   / n[        5       nUR                  U 5        U R                  n[        U5      S:w  a  US   nUSS n[	        U5      U;   a  M*  UR                  U5      (       a  UR                  U5      $ UR                  S:w  a*  UR                  UR                  UR                  5      5        UR                  S:w  a*  UR                  UR                  UR                  5      5        UR                  [	        U5      5        [        U5      S:w  a  M  g)z
Get a Variable by name from this block recursively.

Args:
    name(str): the Variable's name.

Returns:
    Variable: the Variable with the giving name. Or None if not found.
r   r   Nr   )rt  r   ro  r[   r  r  ry  r  rn  r  add)r   r   frontiervisitedrO  curs         rO   rq  Block._find_var_recursive  s     %||(mq 1+C|H#w'!{{4  wwt}$~~#

3>> :;$$*

3+@+@ ABKK3 ! (mq " rN   c                T    U R                  U5      nU(       a  U$ [        SU S35      e)a  
Get a Variable by name from this block recursively.

Args:
    name(str): the Variable's name.

Raises:
    ValueError: this block and this parent block doesn't
        have a Variable with the giving name.

Returns:
    Variable: the Variable with the giving name.
zVar z is not found recursively)rq  r]   )r   r   ry  s      rO   r  Block._var_recursive  s1     &&t,JtD6)BCDDrN   c                4    [        U R                  5       5      $ rK   )rd   iter_parametersr  s    rO   all_parametersBlock.all_parameters  s    D((*++rN   c                D    S U R                   R                  5        5       $ )Nc              3  `   #    U  H$  n[        US    [        5      (       d  M  US    v   M&     g7f)r   NrT   ri  )r3  r@  s     rO   r6  (Block.iter_parameters.<locals>.<genexpr>  s+      
)$q'9- DG)s   ..)r  rW   r  s    rO   r  Block.iter_parameters  s    
		)
 	
rN   c                z    [        5       (       a  [        U0 UD6nU$ [        USU 0UD6nSU;   a  US   " X05        U$ )Nrn  initializer)r   r0  rN  )r   r   r   ry  s       rO   r  Block.create_var  sQ     $1&1C
 
 777C&}%c0
rN   c                    XR                   ;   $ rK   )r  r  s     rO   r  Block.has_var  s    yy  rN   c                x   [        U[        5      (       a  UR                  5       OUn[        U[        5      (       a  UR                  5       OUnU R                  U5      (       d  [	        SU S35      eU R                  U5      n[        U5      [        :X  a?  SnUR                  nUR                  nUR                  nUR                  nUR                  n	OE[        U5      [        :X  a  SnUR                  n	UR                  nO[	        S[        U5       35      eUR                  n
U R                  R                  UR!                  5       UR!                  5       5        U R                  R#                  UR!                  5       5      nUS:X  al  [%        5       (       a.  ['        UR)                  5       UR+                  5       U
UUWWWU	S9	nOB[        U UR)                  5       UR+                  5       U
UUWWWU	S9
nOUS:X  a  [        U U
UU	US9nWU R,                  U'   U R,                  U	 U R/                  5         U$ )a  
Rename variable in vars and ops' inputs and outputs

Args:
    name(str|bytes): the name that need to be renamed.
    new_name(str|bytes): the name that need to rename to.

Raises:
    ValueError: If this block doesn't have this the giving name,
        or the type of the var with the giving name is not Parameter
        or Variable.

Returns:
    Variable: the Variable with the giving name.
r  z is not in current blockri  rN  zunsupported var type: )r   r   r  r  optimize_attrregularizerru  )r   r   ru  r  )rT   r  r  r  r]   ry  r   ri  r  r  r)  r*  ru  rN  rv  _rename_varrx  rw  r   rh  r-  r  r  _sync_with_cpp)r   r   r   r4  var_typer  r  r)  r*  ru  orig_var_typedry  s                rO   r+  Block._rename_var  s   " !+4 7 7t{{}T!+He!<!<HOO( 	 ||D!!tD6)ABCCHHTN7i"HOOMIOOM--KJ!W !HJOOM5d1gY?@@		dkkmX__->?IIx01{"  $GGIGGI&!"/'"/ +)
  GGIGGI&!"/'"/ +) #"%+C "		(IIdO
rN   c                    USL a  U R                  5         U R                  R                  UR                  5       5        U R                  U	 g r  )r,  rv  _remove_varrx  r  )r   r   syncs      rO   r2  Block._remove_var'  s8    4<!		dkkm,IIdOrN   c                p   U R                   R                  5       nS n[        5       (       a  [        U0 UD6nO[	        U/UQ70 UD6nUR
                  nSU;   aW  S nUS   nU" X45      n[        U5      n	U	S:  a'  [        SUR                  -   S-   [        U5      -   5      eU	S:X  a  OU" X@5        XTl        U$ )Nr$  c                    / nU R                    HB  nUR                  UR                  ;   d  M  UR                  S;   a  M1  UR	                  U5        MD     U$ )N)	broadcastr  coalesce_tensor)r  r   r  r   r   )rn  ry  init_opsr  s       rO   _is_inited_by-Block.create_parameter.<locals>._is_inited_by:  sR    ))Bxx2#6#66
 77 ' 
 % + $  rN   r   r  z  is inited by multiple init ops )
ro  r  r   rh  ri  r  r[   r  r   r\   )
r   r   r   r  r  r  r:  r$  r9  init_ops_lens
             rO   create_parameterBlock.create_parameter-  s    ||002"D3F3El<T<V<E ++F" " !/K$\9Hx=La"jj!89 (m$  "E(+rN   c                  ^ UR                  SS5      nUR                  SS5      n[        5       (       a  UR                  S0 5      n[        R                  " SU S3[        5        [        U SUSSUS9n[        5       R                  UUR                  S0 5      UR                  S	0 5      U(       a  UO0 UR                  S
S5      U5        U$ SSKJ	n  SSK
Jm  U4S jnU R                  R                  5       n	UR                  SS5      n
UR                  S	S5      n1 SknSSKJn  U" 5       (       a  [         (       d  [#        XCU5        XL;  a  U" X5        U" U
5         U" U5         [        U U	UU
UUR                  SS5      S9nSSS5        SSS5        U R$                  R'                  W5        U" 5       (       a  [)        XJU5        U$ ! , (       d  f       NK= f! , (       d  f       NT= f)zh
Appends a new Operator according to the giving arguments.

Returns:
    Operator: the append Operator.
r  Nr   rM  zOp `z` is executed through `append_op` under the dynamic mode, the corresponding API implementation needs to be upgraded to using `_C_ops` method.)rn  rv  r   r  r  rM  r  r  r  Fr   )param_guard)r  c                   > SnT" U 5       H  n[        USS5      SL d  M  Sn  O   U(       a.  T" U5       H!  n[        U[        5      (       d  M  SUl        M#     gg)zC
Set out.stop_gradient = True if all inputs stop_gradient is True.
Tr  NF)r  rT   rN  r  )insouts
need_resetry  r  s       rO   pass_stop_gradient+Block.append_op.<locals>.pass_stop_gradient  s^     "
"3<CsOT:eC%*
 ( &t}%c84404C-  - rN   >   r  r  
while_gradpylayer_gradr  conditional_block_gradr   r4  )r   r   r  r  rJ  r  rQ  trace_oppaddle.base.dygraph.baser@  paddle.utilsr  rv  r  r6  r5  r  r  r  r   r  )r   r   r   r  r+  rM  r  r@  rE  op_descr  r  
ignore_opsr5  r  s                 @rO   r  Block.append_op]  s    jj5**VT*JJw+EMMwi  ) ) #	 B &&

8R(

9b)B

?E2| 	k =,5 ii))+GZZ$/FjjD1GJ 8 ""+N+N4' ("63V$k'&:  !# **Wd3 ';$ HHOOB """7G<	 ';&:$$s$   	G(GG
G	G
G+c                N    U R                  5         U R                  " U/UQ70 UD6$ )z
Insert a Operator according to the giving arguments.

Args:
    index(int): the place that the operator to insert.

Returns:
    Operator: the insert Operator.
)r,  _insert_op_without_sync)r   r   r   r   s       rO   
_insert_opBlock._insert_op  s+     	++ECDCFCCrN   c                    U R                   R                  U5      n[        X US.UD6nU R                  R	                  X5        U$ )z
Insert an Operator according to the giving arguments,
without sync_with_cpp to make the compilation faster.

Args:
    index(int): the place that the operator to insert.

Returns:
    Operator: the insert Operator.
rn  rv  )rv  rR  r  r  r  )r   r   r   r   rM  r  s         rO   rQ  Block._insert_op_without_sync  s>     ))&&u-w@@"	rN   c                    USL a  U R                  5         U R                  R                  XS-   5        U R                  U	 g)z|
Remove the specific position operator.

Args:
    index(int): the position that the operator to insert.

Returns:
    None
Tr   N)r,  rv  
_remove_opr  )r   r   r3  s      rO   rX  Block._remove_op  s8     4<!		UAI.HHUOrN   c                    U R                   X $ )z
Return the Operator between start and end.

Args:
    start(int): the start position.
    end(int): the end position.

Returns:
    list: the Operators between start and end.
)r  )r   r'  r4  s      rO   
_slice_opsBlock._slice_ops  s     xx""rN   c                @   [        5       (       a  UR                  SS 5      nUR                  S0 5      n[        U S US S US9n[        5       R	                  UUR                  S0 5      UR                  S0 5      U(       a  UO0 UR                  SS5      5        U$ U R
                  R                  5       n[        U UUR                  SS 5      UR                  SS 5      UR                  SS 5      UR                  SS 5      S9nU R                  R                  SU5        U$ )	Nr   rM  r  r  r  r  Fr   )	r   r   r  rQ  rJ  rv  _prepend_opr  r  )r   r   r   r   rM  r  rM  s          rO   r^  Block._prepend_op  s   ::fd+DJJw+EddDB &&

8R(

9b)B

?E2& 	 ii++-GZZ-zz(D1

9d3jj$/B HHOOAr"	rN   c           
     d   U R                   R                  5        H  nU R                  UR                  5       5      (       a  M)  SnUR	                  5       (       a  UR                  5       nUR                  5       (       ac  UR                  5       (       aN  U R                  UR                  5       UUR                  5       UR                  5       UR                  5       US9  M  U R                  UR                  5       UUR                  5       US9  M     [        U R                  R                  5       5       HN  nU R                   R!                  UR#                  5       5      (       a  M3  U R                  R%                  U5        MP     / n['        SU R                   R)                  5       5       H-  nUR+                  U R                   R-                  U5      5        M/     [/        U R0                  5      S:w  a  U R0                  S   R                   nU R0                  [/        U R0                  5      S-
     R                   nSnSn['        [/        U5      5       H  n	XSU	   :X  a  U	nXcU	   :X  d  M  U	nM     Uc   eUc   eXx::  d   eOSnSn['        US-
  S-
  SS5       H.  n	X9   n
[3        X
5      nU R0                  R5                  SU5        M0     ['        US-   [/        U5      5       H-  n	X9   n
[3        X
5      nU R0                  R+                  U5        M/     US:w  a  U[/        U R0                  5      :  a  SnSnU[/        U R0                  5      :  ap  U[/        U5      :  aa  U R0                  U   R                   X<   :w  a  U R0                  U	 O
US-  nUS-  nU[/        U R0                  5      :  a  U[/        U5      :  a  Ma  [/        U R0                  5      [/        U5      :X  d   e['        [/        U R0                  5      5       H$  n	U R0                  U	   R                   X9   :X  a  M$   e   g)zt
Sync from the desc on the c++ end. This method is used to synchronize
the c++ desc instance generated by backward.
F)r   rv  r   r-  r  r  )r   rv  r   r  r   r   Nr   )rv  all_varsr  r   has_stop_gradientr  has_is_parameterr  r=  r   r-  r  r  rd   r  rr  rw  rx  rK  r  op_sizer   r  r[   r  r  r  )r   ry  is_stop_gradient
ops_in_cppop_idxfirst_op_in_pythonlast_op_in_pythonstart_index	end_indexr   rM  r  ops_in_cpp_indexops_in_python_indexs                 rO   r,  Block._sync_with_cpp  s    99%%'C<<
++#( ((**'*'8'8':$''))c.>.>.@.@)) XXZ  XXZ!iik!iik&6 *  OO XXZ  XXZ&6	 $  (. 		()C99%%cjjl33		c" *
 
Atyy0023Fdiill623 4 txx=A!%!!1!1 $TXX): ; @ @KIs:/%E)::"'K$5(99 %I	 0
 ***(((+++KI K!Oa/"b9E 'G$(BHHOOAr" : IMC
O<E 'G$(BHHOOB = ?y3txx=8 "#%) "S_4HH0166!34 !45$)$'1,' &) "S_4 488}J///3txx=)E88E?'':+<<<< *rN   c                   [        U[        5      (       d  [        S5      eUR                  5        GH  n[        U[        5      (       d   eU R
                  R                  UR                  S5      nUc  MF  [        U[        5      (       d   eSn[        5       (       aw  [        UR                  UR                  UR                  UR                  UR                  UR                   UR"                  UR$                  UR&                  UR                  S9
nO[	        U UR                  UR                  UR                  UR                  [(        R*                  R,                  R.                  :X  a  UR                  OSUR                  UR                   UR"                  UR$                  UR&                  UR                  S9nX@R
                  UR                  '   GM     g)z
Copy the information of parameters from the other block.

Args:
    other(Block): the other block.

Raises:
    ValueError: If type of input is not Block, or the `other` and this
        block is not in the same topology.

Returns:
    None
z2_copy_param_info_from should be invoked with BlockN)
r-  r  r   r~  r  r  r)  r*  ru  r   )rn  r-  r  r   r~  r  r  r)  r*  ru  r   )rT   r{  rV   r  ri  r  r   r   rN  r   rh  r-  r  r   r~  r  r  r)  r*  ru  r   r  r  r+  )r   otherr  r4  new_ps        rO   _copy_param_info_fromBlock._copy_param_info_fromi  se    %''D  &&(Aa++++		affd+Aya****E  &''''kk"#//kk"#// ! || "'''' 66T\\%9%9%F%FF !"#//kk"#// ! ||" %*IIejj!O )rN   c                
   [        U[        5      (       d   eSnUR                  [        R                  R
                  R                  :X  a1  U R                  UR                  UR                  UR                  S9nU$ UR                  [        R                  R
                  R                  :X  a1  U R                  UR                  UR                  UR                  S9nU$ UR                  [        R                  R
                  R                  :X  at  U R                  UR                  UR                  UR                  UR                  U(       a  SOUR                  UR                  UR                  R!                  5       S9nU$ U R                  UR                  UR                  UR                  UR                  UR"                  U(       a  SOUR                  UR                  UR                  R!                  5       S9nU$ )a  
Clone a variable into current block.

Args:
    var: the variable to be cloned.
    force_persistable(bool): True means setting the result variable to being persistable.
                             False means setting the persistable the same with that of input var.
                             default: True.

Returns:
    Variable: the new  variable cloned from 'var' in current block.
N)r   r.  r   T)r   r-  r  r   r.  r  r  )r   r-  r  r   r~  r.  r  r  )rT   rN  r   r   r  r  STEP_SCOPESr  r   r.  RAWr  r-  r  r  rv  r  r~  )r   ry  force_persistableret_vars       rO   _clone_variableBlock._clone_variable  s    #x((((88t||++777ooXX3?? & G8 3 XX--111ooXX3?? & G0 + XX--;;;ooXXiiiiXX$5D3?? # 8 8 : & G(  ooXXiiiiXX--$5D3?? # 8 8 : & 	G rN   )rv  r  ro  r  Nr  r  )$r   r   r   r   r  r   r   r  r  r  r  r  r  r  r  r  ry  rq  r  r  r  r  r  r+  r2  r=  r  rR  rQ  rX  r[  r^  r,  rr  ry  r   rM   rN   rO   r{  r{    s    @()V%N H    1 1
.    ."HE(,
!Rh.`]~D #:U=n9*v-rN   r{  c                n   [        U[        5      (       d   S5       e[        U[        5      (       d   S5       e[        R                  " U R                  5      n[        R                  " UR                  5      n[        R
                  " UUUUU5      nU R                  U5        UR                  U5        U$ )Nzpass_attrs must be dictzpass_attr_types must be dict)rT   rU   r   r  rv  
apply_pass_rebuild_from_desc)main_programstartup_program	pass_name
pass_attrspass_attr_typestmp_main_programtmp_startup_programrM  s           rO   _apply_passr    s     j$''B)BB'ot,,L.LL,''(9(9:**?+?+?@OOE ##$45&&':;LrN   c                      \ rS rSrSrS rS rS rS rS r	S r
S	 rS
 rS rS rS rS rS rS rS rS rS r\S 5       r\S 5       rSrg)IrNodei  zF
Python IrNode. Beneath it is a core.Node, which is used for Ir Pass.
c                \    [        U[        R                  5      (       d   S5       eXl        g)zL
Construct an IrNode using core.Node.

Args:
    node(core.Node): C++ Node.
z'node must be the instance of core.Node.N)rT   r   Nodenoder   r  s     rO   r   IrNode.__init__  s,     $		** 	
5	
* 	rN   c                6    U R                   R                  5       $ )z5
Return the node name.

Returns:
    str: node name.
)r  r   r  s    rO   r   IrNode.name  s     yy~~rN   c                6    U R                   R                  5       $ )zu
Return the node type.

Returns:
    core.Node.Type: node type(core.Node.Type.Operation or core.Node.Type.Variable).
)r  	node_typer  s    rO   r  IrNode.node_type  s     yy""$$rN   c                6    U R                   R                  5       $ )z^
Return the node variable description.

Returns:
    core.VarDesc: node variable description.
)r  ry  r  s    rO   ry  
IrNode.var  s     yy}}rN   c                6    U R                   R                  5       $ )z]
Return the node operator description.

Returns:
    core.OpDesc: node operator description.
)r  r  r  s    rO   r  	IrNode.op       yy||~rN   c                6    U R                   R                  5       $ )z1
Return the node id.

Returns:
    int: node id.
)r  r  r  s    rO   r  	IrNode.id"  r  rN   c                6    U R                   R                  5       $ )zm
If the node is an operator, then return true.

Returns:
    bool: indicate whether the node is an operator.
)r  is_opr  s    rO   r  IrNode.is_op+  s     yy  rN   c                6    U R                   R                  5       $ )zk
If the node is a variable, then return true.

Returns:
    bool: indicate whether the node is a variable.
)r  is_varr  s    rO   r  IrNode.is_var4  s     yy!!rN   c                6    U R                   R                  5       $ )z
If the node is a control dependence variable, then return true.

Returns:
    bool: indicate whether the node is a control dependence variable.
)r  is_ctrl_varr  s    rO   r  IrNode.is_ctrl_var=  s     yy$$&&rN   c                8    U R                   R                  5         g)zd
Clear the node inputs. After executing the `clear_inputs` function,
the node inputs will be empty.
N)r  clear_inputsr  s    rO   r  IrNode.clear_inputsF  s    
 			 rN   c                :    U R                   R                  U5        g)z]
Remove a node from inputs by the given node id.

Args:
    node_id(int): the given node id.
Nr  remove_inputr   node_ids     rO   remove_input_by_idIrNode.remove_input_by_idM  s     			w'rN   c                N    U R                   R                  UR                   5        g)zM
Remove a node from inputs.

Args:
    node(IrNode): the node being removed.
Nr  r  s     rO   r  IrNode.remove_inputV       			tyy)rN   c                N    U R                   R                  UR                   5        g)zL
Append a node in inputs.

Args:
    node(IrNode): the node being appended.
N)r  append_inputr  s     rO   r  IrNode.append_input_  r  rN   c                8    U R                   R                  5         g)zg
Clear the node outputs. After executing the `clear_outputs` function,
the node outputs will be empty.
N)r  clear_outputsr  s    rO   r  IrNode.clear_outputsh  s    
 			!rN   c                :    U R                   R                  U5        g)z^
Remove a node from outputs by the given node id.

Args:
    node_id(int): the given node id.
Nr  remove_outputr  s     rO   remove_output_by_idIrNode.remove_output_by_ido  s     			(rN   c                N    U R                   R                  UR                   5        g)zN
Remove a node from outputs.

Args:
    node(IrNode): the node being removed.
Nr  r  s     rO   r  IrNode.remove_outputx       					*rN   c                N    U R                   R                  UR                   5        g)zM
Append a node in outputs.

Args:
    node(IrNode): the node being appended.
N)r  append_outputr  s     rO   r  IrNode.append_output  r  rN   c                l    U R                   R                   Vs/ s H  n[        U5      PM     sn$ s  snf )zT
Return the node inputs.

Returns:
    list(IrNode): node inputs wrapped by IrNode.
)r  r  r  r   ru   s     rO   r  IrNode.inputs  s,     $(99#3#34#3aq	#3444   1c                l    U R                   R                   Vs/ s H  n[        U5      PM     sn$ s  snf )zV
Return the node outputs.

Returns:
    list(IrNode): node outputs wrapped by IrNode.
)r  r  r  r  s     rO   r  IrNode.outputs  s,     $(99#4#45#4aq	#4555r  r  N)r   r   r   r   r  r   r   r  ry  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   rM   rN   rO   r  r    s    
 %!"'!(**")++ 5 5 6 6rN   r  c                  j   ^  \ rS rSrSrU 4S jrS rS rS rS r	S r
\S	 5       r\S
 5       rSrU =r$ )	IrVarNodei  zG
Python IrVarNode. Beneath it is a core.Node, it inherits from IrNode.
c                   > [        U[        R                  5      (       a  UR                  5       (       d   S5       e[        TU ]  U5        Xl        g)zO
Construct an IrVarNode using core.Node.

Args:
    node(core.Node): C++ Node.
zFnode must be the instance of core.Node and it must be a variable node.N)rT   r   r  r  r   r   r  r   r  r   s     rO   r   IrVarNode.__init__  sD     $		**t{{}} 	
T	
< 		rN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  U5        g)zG
Set the node variable shape.

Args:
    shape(list): shape to be set.
N.The node variable description can not be None.)r  ry  r{  )r   r-  s     rO   r{  IrVarNode.set_shape  s>     yy}}* 	
<	
* 			!!%(rN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  5       $ )z
If the variable node is a persistable variable, then return true.

Returns:
    bool: indicate whether the variable is persistable.
r  )r  ry  r.  r  s    rO   r.  IrVarNode.persistable  s?     yy}}* 	
<	
* yy}}**,,rN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  5       $ )zR
Return the variable type.

Returns:
    core.VarDesc.VarType: the variable type.
r  )r  ry  r   r  s    rO   r   IrVarNode.type  s?     yy}}* 	
<	
* yy}}##%%rN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  5       $ )z\
Return the variable data type.

Returns:
    core.VarDesc.VarType: the variable data type.
r  )r  ry  r  r  s    rO   r  IrVarNode.dtype  ?     yy}}* 	
<	
* yy}}$$&&rN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  5       $ )zD
Return the variable shape.

Returns:
    list: the variable shape.
r  )r  ry  r-  r  s    rO   r-  IrVarNode.shape  r  rN   c                l    U R                   R                   Vs/ s H  n[        U5      PM     sn$ s  snf )zX
Return the node inputs.

Returns:
    list(IrOpNode): node inputs wrapped by IrOpNode.
)r  r  IrOpNoder  s     rO   r  IrVarNode.inputs  s,     &*YY%5%56%5%5666r  c                l    U R                   R                   Vs/ s H  n[        U5      PM     sn$ s  snf )zZ
Return the node outputs.

Returns:
    list(IrOpNode): node outputs wrapped by IrOpNode.
)r  r  r  r  s     rO   r  IrVarNode.outputs  s,     &*YY%6%67%6%6777r  r  )r   r   r   r   r  r   r{  r.  r   r  r-  r  r  r  r   r   r   s   @rO   r  r    sN    
)
-
&
'
' 7 7 8 8rN   r  c                     ^  \ rS rSrSrU 4S jrS rS rS rS r	S r
S	 rS
 rS rS r\S 5       r\S 5       rSrU =r$ )r  i  zF
Python IrOpNode. Beneath it is a core.Node, it inherits from IrNode.
c                   > [        U[        R                  5      (       a  UR                  5       (       d   S5       e[        TU ]  U5        Xl        g)zN
Construct an IrOpNode using core.Node.

Args:
    node(core.Node): C++ Node.
zFnode must be the instance of core.Node and it must be a operator node.N)rT   r   r  r  r   r   r  r  s     rO   r   IrOpNode.__init__  sD     $		**tzz|| 	
T	
; 		rN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  X5        g)z
Rename the input of this node.

Args:
    old_input_name(str): the old input name.
    new_input_name(str): the new input name.
N.The node operator description can not be None.)r  r  r\  )r   old_input_namenew_input_names      rO   rename_inputIrOpNode.rename_input  s>     yy||~) 	
<	
) 			$$^DrN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  X5        g)z
Rename the output of this node.

Args:
    old_output_name(str): the old output name.
    new_output_name(str): the new output name.
Nr  )r  r  ra  )r   old_output_namenew_output_names      rO   rename_outputIrOpNode.rename_output!  s>     yy||~) 	
<	
) 			%%oGrN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  U5      $ )z
Get the argument name list by the parameter name for input.

Args:
    name(str): the parameter name.

Returns:
    list(str): the argument name list.
r  )r  r  r;  r  s     rO   r;  IrOpNode.input.  sA     yy||~) 	
<	
) yy||~##D))rN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  U5      $ )z
Get the argument name list by the parameter name for output.

Args:
    name(str): the parameter name.

Returns:
    list(str): the argument name list.
r  )r  r  r  r  s     rO   r  IrOpNode.output=  sA     yy||~) 	
<	
) yy||~$$T**rN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  U5      $ )z`
Change the operator type into new type.

Args:
    new_type(str): new operator type to be set.
r  )r  r  rz  )r   new_types     rO   rz  IrOpNode.set_typeL  sA     yy||~) 	
<	
) yy||~&&x00rN   c                &    U R                  X5        g)z
Set the value of attribute by attribute's name.

Args:
    name(str): the attribute name.
    val(bool|int|str|float|list): the value of the attribute.
Nr}  r   s      rO   set_attrIrOpNode.set_attrX  s     	t)rN   c                z   U R                   R                  5       c   S5       eU R                   R                  5       n[        U[        5      (       a  UR	                  XR
                  5        g[        U[        5      (       aA  [        U[        5      (       a,  UR                  X Vs/ s H  oDR
                  PM     sn5        g[        U[        5      (       a  UR                  XR
                  5        g[        U[        5      (       aH  U(       aA  [        U[        5      (       a,  UR                  X Vs/ s H  oDR
                  PM     sn5        g[        U[        R                  [        R                  45      (       a   UR                  XR!                  5       5        gUR#                  X5        gs  snf s  snf )zB
Update the value of the op desc's attribute by attribute's name.
Nr  )r  r  rT   rN  ry  rv  rd   r:  rz  r{  r|  r}  r   r~  r  r  r  r  )r   r   r   rv  r4  s        rO   r~  IrOpNode._update_desc_attrb  s2    yy||~) 	
<	
) yy||~c8$$dHH-T""|C'B'Btc%:cffc%:;U##hh/T""s|C/G/G  '<1'<=dnnd.>.>?@@$$T+B+B+DENN4% &; (=s   'F3
5F8
c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  5       $ )zq
Return input arguments' names of this op node.

Returns:
    list(str): input arguments' names of this op node.
r  )r  r  rf  r  s    rO   rf  IrOpNode.input_arg_namesw  s?     yy||~) 	
<	
) yy||~--//rN   c                    U R                   R                  5       c   S5       eU R                   R                  5       R                  5       $ )zs
Return output arguments' names of this op node.

Returns:
    list(str): output arguments' names of this op node.
r  )r  r  r  r  s    rO   r  IrOpNode.output_arg_names  s?     yy||~) 	
<	
) yy||~..00rN   c                l    U R                   R                   Vs/ s H  n[        U5      PM     sn$ s  snf )zZ
Return the node inputs.

Returns:
    list(IrVarNode): node inputs wrapped by IrVarNode.
)r  r  r  r  s     rO   r  IrOpNode.inputs  s,     '+ii&6&67&6	!&6777r  c                l    U R                   R                   Vs/ s H  n[        U5      PM     sn$ s  snf )z\
Return the node outputs.

Returns:
    list(IrVarNode): node outputs wrapped by IrVarNode.
)r  r  r  r  s     rO   r  IrOpNode.outputs  s,     '+ii&7&78&7	!&7888r  r  )r   r   r   r   r  r   r  r  r;  r  rz  r  r~  rf  r  r  r  r  r   r   r  s   @rO   r  r    sd    EH*+
1*&*
0
1 8 8 9 9rN   r  c                      \ rS rSrSrS!S jrS rS rS rS r	S r
S	 rS!S
 jrS!S jrS rS rS rS rS rS rS rS rS rS rS rS rS rS rS rS"S jrS rS rS r S r!g)#IrGraphi  z
Python IrGraph. Beneath it is a core.Graph, which is used for
creating a c++ Ir Pass Graph. An IrGraph is just a graph view of
a Program. In an IrGraph, both Variables and Operators are graph
nodes.
c                h    [        U[        R                  5      (       d   S5       eXl        X l        g)z
Construct an IrGraph using core.Graph.

Args:
    graph(core.Graph): C++ Graph.
    for_test(bool): True for the test graph and false for the train graph.
z)graph must be the instance of core.Graph.N)rT   r   Graphgraph	_for_test)r   r  for_tests      rO   r   IrGraph.__init__  s1     %,, 	
7	
, 
!rN   c                `    U R                   R                  5       n[        XR                  5      $ )z
Create a new and duplicated IrGraph.

Warns:
    The method only clones the graph structure, not its attributes.

Returns:
    IrGraph: A new and duplicated graph.
)r  r  r  r  )r   gs     rO   r  IrGraph.clone  s%     JJq..))rN   c                    U R                   $ )zX
If the graph is used for testing, the function returns true. Otherwise, returns false.
)r  r  s    rO   is_testIrGraph.is_test  s     ~~rN   c                t    U R                   R                  5        Vs1 s H  n[        U5      iM     sn$ s  snf )z2
Return all nodes included in the graph as a set.
)r  nodesr  r  s     rO   	all_nodesIrGraph.all_nodes  s/     *.)9)9);<);t);<<<s   5c                    U R                   R                  5        Vs1 s H$  oR                  5       (       d  M  [        U5      iM&     sn$ s  snf )z;
Return all variable nodes included in the graph as a set.
)r  r  r  r  r  s     rO   all_var_nodesIrGraph.all_var_nodes  s7     -1JJ,<,<,>P,>D++-	$,>PPP
   AAc                Z   [        5       nU R                  R                  5        Hc  nUR                  5       (       d  M  UR	                  5       c  M-  UR	                  5       R                  5       (       d  MR  UR                  U5        Me     U Vs1 s H  n[        U5      iM     sn$ s  snf )zG
Return all persistable variable nodes included in the graph as a set.
)rt  r  r  r  ry  r.  r  r  )r   persistable_nodesr  r  s       rO   all_persistable_nodesIrGraph.all_persistable_nodes  s}      EJJ$$&DHHJ*HHJ**,,!%%d+ ' '88&7	!&7888s   B(c                    U R                   R                  5        Vs1 s H$  oR                  5       (       d  M  [        U5      iM&     sn$ s  snf )z;
Return all operator nodes included in the graph as a set.
)r  r  r  r  r  s     rO   all_op_nodesIrGraph.all_op_nodes  s7     ,0::+;+;+=N+=4+=NNNr  c                    [        U R                  R                  5       5       Vs/ s H&  n[        U R                  R	                  U5      US9PM(     sn$ s  snf )z<
Return all sub_graphs included in the main graph as a set.
r  )r  r  sub_graph_sizer  get_sub_graph)r   r  r  s      rO   all_sub_graphsIrGraph.all_sub_graphs  sQ     4::4467
7 DJJ,,Q/(C7
 	
 
s   -Ac                H    [        U R                  R                  U5      US9$ )z*
Return i-th sub_graph in the main graph.
r  )r  r  r   )r   r  r  s      rO   r   IrGraph.get_sub_graph  s      tzz//2XFFrN   c                    [         R                  " U5      nUR                  U5        UR                  U5        UR	                  U5        UR                  S5        [        U R                  R                  U5      5      $ )a  
Create a persistable variable node in the graph. In IrGraph,
it can not distinguish between persistable variables and parameters.

Args:
    name(str): the name of the persistable variable node.
    var_type(core.VarDesc.VarType): the type of the persistable variable node.
    shape(list): the shape of the persistable variable node.
    var_dtype(core.VarDesc.VarType): the data type of the persistable variable node.

Returns:
    IrVarNode: the created persistable variable node.
T)	r   r  rz  r{  r|  r  r  r  create_var_noder   r   r-  r-  	var_dtypevar_descs         rO   create_persistable_nodeIrGraph.create_persistable_node  sd     <<%(#5!9%  &33H=>>rN   c                    [         R                  " U5      nUR                  U5        UR                  U5        UR	                  U5        [        U R                  R                  U5      5      $ )az  
Create a variable node in the graph. The created variable node is
not persistable.

Args:
    name(str): the name of the variable node.
    var_type(core.VarDesc.VarType): the type of the variable node.
    shape(list): the shape of the variable node.
    var_dtype(core.VarDesc.VarType): the data type of the variable node.

Returns:
    IrVarNode: the created variable node.
)r   r  rz  r{  r|  r  r  r&  r'  s         rO   r&  IrGraph.create_var_node  sV     <<%(#5!9%33H=>>rN   c                H    [        U R                  R                  5       5      $ )z
create a control var
)r  r  create_control_dep_varr  s    rO   r/  IrGraph.create_control_dep_var'  s     ::<==rN   c                J    [        U R                  R                  U5      5      $ )a  
Create a variable node by using an existing VarDesc in the graph.
Depend on the giving VarDesc, the created variable node may be persistable.

Args:
    var_desc(core.VarDesc): the giving variable description.

Returns:
    IrVarNode: the created variable node.
)r  r  r&  )r   r)  s     rO   create_var_node_from_desc!IrGraph.create_var_node_from_desc-  s     33H=>>rN   c           	        [         R                  " 5       nUR                  U5        UR                  5        H  u  pgU R	                  XVU5        M     UR                  5        HL  u  p[        U	[        5      (       d  U	/n	UR                  X V
s/ s H  oR                  5       PM     sn
5        MN     UR                  5        HL  u  p[        U	[        5      (       d  U	/n	UR                  X V
s/ s H  oR                  5       PM     sn
5        MN     [        U R                  R                  U5      5      $ s  sn
f s  sn
f )a/  
Create a operator node in the graph.

Args:
    op_type(str): the type of the operator node.
    attrs(dict): the attributes of the operator node.
    inputs(dict): the inputs of the operator node.
    outputs(dict): the outputs of the operator node.

Returns:
    IrOpNode: the created operator node.
)r   r.  rz  rW   r~  rT   rd   r  r   r  r  r  create_op_node)r   r+  rM  r  r  rM  rT  r`   
input_name	var_nodesvar_nodeoutput_names               rO   r5  IrGraph.create_op_node:  s    ++-! ;;=KD""7%8 )%+\\^!Ji..&K	YGY]]_YG &4 '.mmo"Ki..&K	iHi(mmoiH '6 

11':;; H Is   D6.D;c                J    [        U R                  R                  U5      5      $ )z
Create a operator node by using an existing OpDesc in the graph.

Args:
    op_desc(core.VarDesc): the giving operator description.

Returns:
    IrOpNode: the created operator node.
)r  r  r5  )r   rM  s     rO   create_op_node_from_desc IrGraph.create_op_node_from_descY  s     

11':;;rN   c                   UR                   U R                  R                  5       ;   aP  UR                   U R                  R                  5       ;   a(  UR                   U R                  R                  5       ;   d   S5       eUR                  U5        UR	                  U5        UR                  U5        UR                  U5        UR                  UR                  5       UR                  5       5        g)a  
Update the input's link of a operator node.

Args:
    old_input_node(IrNode): the old input node of the giving op_node.
    new_input_node(IrNode): the new input node of the giving op_node.
    op_node(IrOpNode): the operator node that is needed to update input's link.
zVThe three arguments(old_input_node&new_input_node&op_node) must be in the graph nodes.N)	r  r  r  r  r  r  r  r  r   )r   old_input_nodenew_input_nodeop_nodes       rO   update_input_linkIrGraph.update_input_linke  s     4::#3#3#55##tzz'7'7'99

 0 0 22	

 e	
3 	$$W-^,$$W-^,^002N4G4G4IJrN   c                   UR                   U R                  R                  5       ;   aP  UR                   U R                  R                  5       ;   a(  UR                   U R                  R                  5       ;   d   S5       eUR                  U5        UR	                  U5        UR                  U5        UR                  U5        UR                  UR                  5       UR                  5       5        g)a  
Update the output's link of an operator node.

Args:
    old_output_node(IrNode): the old output node of the giving op_node.
    new_output_node(IrNode): the new output node of the giving op_node.
    op_node(IrOpNode): the operator node that is needed to update input's link.
zZThe three arguments(old_output_node &new_output_node &op_node) must be in the graph nodes.N)	r  r  r  r  r  r  r  r  r   )r   old_output_nodenew_output_noderA  s       rO   update_output_linkIrGraph.update_output_link{  s       DJJ$4$4$66$$

(8(8(::

 0 0 22	

 i	
3 	$$W-o.$$W-o.o224o6J6J6LMrN   c                t   UR                   U R                  R                  5       ;   d#   SUR                   R                  5        S35       eUR                   U R                  R                  5       ;   d#   SUR                   R                  5        S35       eUR	                  U5        UR                  U5        g)zg
Connect two nodes.

Args:
    node_in(IrNode): the input node.
    node_out(IrNode): the output node.
znode_in(z) must be in the graph nodes.z	node_out(N)r  r  r  r   r  r  )r   node_innode_outs      rO   link_toIrGraph.link_to  s     ||tzz//11 	
w||((*++HI	
1 }}

 0 0 22 	
**,--JK	
2 	h'g&rN   c                    [        U[        5      (       d$  [        U[        5      (       a  [        U5      nOU1nU Vs1 s H  o"R                  iM     nn[        R
                  " U R                  U5        gs  snf )z
Remove nodes safely since links connected to these removed nodes are
also removed.

Args:
    remove_nodes(set): the nodes prepared to be removed.
N)rT   rt  r   r  r   graph_safe_remove_nodesr  )r   remove_nodesru   original_nodess       rO   safe_remove_nodesIrGraph.safe_remove_nodes  s^     ,,,,11"<0 ,~*67,Q&&,7$$TZZ@ 8s   A7c                j   [         R                  " U R                  5      n0 nU H  nUR                  5       (       d  M  UR	                  5       c  M-  UR	                  5       R                  5        H)  nXB;  d  M
  U R                  UR                  U5      /X$'   M+     UR	                  5       R                  5        HV  nXB;  a!  U R                  UR                  U5      /X$'   M)  X$   R                  U R                  UR                  U5      5        MX     M     U R                  R                  U5        g rK   )r   topology_sortr  r  r  rf  _find_node_by_namer  r  r  r   resolve_hazard)r   ordered_nodesr7  r  each_var_names        rO   rW  IrGraph.resolve_hazard  s    **4::6	!Dzz||	 5%)WWY%>%>%@M$5 33DKKO4	0 &A
 &*WWY%?%?%AM$5 33DLL-P4	0 "077 33DLL-P &B "  	

!!),rN   c                B    [         R                  " U R                  5      $ )za
Check if the graph has a circle.

Returns:
    bool: True if the graph has a circle else False.
)r   
has_circler  r  s    rO   r\  IrGraph.has_circle  s     tzz**rN   c                B    [         R                  " U R                  5      $ )zl
Count the number of unconnected graphs in this graph.

Returns:
    int: the number of unconnected graphs.
)r   	graph_numr  r  s    rO   r_  IrGraph.graph_num  s     ~~djj))rN   c                    [         R                  " U R                  5      nU Vs/ s H  n[        U5      PM     sn$ s  snf )z
Perform the topology sort operation on the graph.

Notes: the `graph` can not contain a circle.

Returns:
    list(IrNode): nodes in topology order.
)r   rU  r  r  )r   rX  ru   s      rO   rU  IrGraph.topology_sort  s4     **4::6#01=aq	=111s   =c                    [         R                  " U R                  5      n0 nUR                  5        H-  u  p4U Vs1 s H  n[	        U5      iM     snU[	        U5      '   M/     U$ s  snf )zu
Build an adjacency list of operations for the `graph`.

Returns:
    dict{IrNode: set(IrNode)}: the adjacency list.
)r   build_adjacency_listr  rW   r  )r   adj_listwrapped_adj_listr  r4  ru   s         rO   rd  IrGraph.build_adjacency_list  s_     ,,TZZ8NN$DA>?*@a6!9a*@VAY' % +As   A&Nc                   S n[        5       nU(       aP  U R                  5        H+  nUR                  5       (       d  M  UR                  U5        M-     U R	                  U5        [        S[        U R                  5       5       S35        Ub  [        U[         5      (       d$  [        U[        5      (       a  [        U5      nOU1nU Vs1 s H  oR                  iM     nnU Vs1 s H  oR                  iM     nnX6-
  nU R                  R                  S5      (       a  U R                  R                  S5        U R                  R                  SU5        [        R                  R!                  U5      (       d  [        R"                  " U5        [        R                  R%                  X5      S-   n	[&        R(                  " S5      n
U
R                  SU	5        U
R+                  U R                  5        U" U	5        gs  snf s  snf )	a  
Draw the graph. If `dot` command is installed, the drawn graph
will be saved as pdf file type, otherwise dot file type is used.

Args:
    save_path(str): the save path of drawn graph.
    name(str): the name of drawn graph.
    marked_nodes(set(IrNode)): nodes that are needed to be marked.
    Default value is None.
    remove_ctr_var(bool): If it is set True, all control variable nodes
    in the graph will be removed. Default value is True.
c                    [         R                  R                  U 5      S   S-   n[        R                  " SSU SU/5      nUS:w  a  [        S5        [        SU  S35        g g )	Nr   z.pdfdotz-Tpdfz-oz1The dot command is needed for creating pdf files.zThe z is saved as the dot filetype.)r~   pathsplitext
subprocesscallprint)dot_file_pathpdf_save_pathexited_codes      rO   _convert_to_pdf%IrGraph.draw.<locals>._convert_to_pdf   sf    GG,,];A>GM$//mDK aIJ]O+IJK  rN   zTotal ops num = r  N__graphviz__marked_node__z.dotgraph_viz_passgraph_viz_path)rt  r  r  r  rR  ro  r[   r  rT   r   r  r  haseraser~   rk  existsmakedirsr   r   get_passr  )r   	save_pathr   marked_nodesremove_ctr_varrs  remove_ctr_varsr  ru   viz_dot_pathviz_passs              rO   drawIrGraph.draw  s   	L %**,##%%#''- - ""?3 T%6%6%8!9 :!<=#lC00lH55#&|#4L$0>L,89LqFFLL9/>?!vvO?'9Lzz~~9::

  !<=JJNN6Eww~~i((KK	"ww||I4v===!12%|4tzz"% :?s   H &Hc                    [         R                  " S5      n[         R                  " 5       nUR                  SU5        UR	                  U R
                  5        [        R                  U5      nU$ )z
Convert the graph into a Program.

WARN: When the graph includes backward operator nodes, the
conversion process may be failed. Usually, this function is
only used to convert a test graph.

Returns:
    Program: a program converted from the graph.
graph_to_program_passro  )r   r|  r  set_not_ownedr  r  rE  _construct_from_desc)r   convert_passrv  ro  s       rO   
to_programIrGraph.to_program%  sX     }}%<=!""9d34::&..t4rN   c                h    SnU H  nUR                  5       U:X  d  M  UnM     Uc   SU S35       eU$ )z2
Find a node in the giving nodes set by the name.
NzCannot find the target node (z)in the giving set.r  )r   r  	node_nametarget_noderu   s        rO   rV  IrGraph._find_node_by_name7  sP     Avvx9$  & 	
+I;6IJ	
& rN   c                   [        U[        5      (       a  UR                  X#R                  5        g[        U[        5      (       aA  [        U[        5      (       a,  UR                  X# Vs/ s H  oDR                  PM     sn5        g[        U[        5      (       a  UR                  X#R                  5        g[        U[        5      (       aH  U(       aA  [        U[        5      (       a,  UR                  X# Vs/ s H  oDR                  PM     sn5        g[        U[        R                  [        R                  45      (       a   UR                  X#R                  5       5        gUR                  X#5        gs  snf s  snf )z;
Update the value of desc's attribute by attribute's name.
N)rT   rN  ry  rv  rd   r:  rz  r{  r|  r}  r   r~  r  r  r  r  )r   rv  r   r   r4  s        rO   r~  IrGraph._update_desc_attrD  s    c8$$dHH-T""|C'B'Btc%:cffc%:;U##hh/T""s|C/G/G  '<1'<=dnnd.>.>?@@$$T+B+B+DENN4% &; (=s   +E7
9E<
)r  r  r  r  )"r   r   r   r   r  r   r  r  r  r  r  r  r!  r   r*  r&  r/  r2  r5  r<  rB  rG  rL  rR  rW  r\  r_  rU  rd  r  r  rV  r~  r   rM   rN   rO   r  r    s    "*=Q9O
G?*?*>?<>
<K,N,'"A -*+*
2 1&f$&rN   r  c                     \ rS rSrSrS rS rS rS/S jr\	S 5       r
\
R                  S 5       r
\	S	 5       r\S
 5       r\S 5       r\S0S j5       rS rS1S jrS0S jrS rS rS0S jr\S 5       rS rS rS1S jrS1S jr\S 5       r\S 5       r\	S 5       r\	S 5       r \R                  S 5       rS r!S r"S r#S  r$S2S" jr%S# r&S$ r'S% r(S& r)S' r*S2S( jr+S3S) jr,S* r-S+ r.S4S, jr/S2S- jr0S.r1g!)5rE  iV  a  
Create Python Program.  It has at least one :ref:`api_guide_Block_en`, when the
control flow op like conditional_block, while :ref:`api_paddle_base_layers_While` is included,
it will contain nested block.

Please reference the
`framework.proto <https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/phi/core/framework/framework.proto>`_
for details.

A set of Program usually contains startup program and main program.
A startup program is set to contain some initial work, eg. initialize the ``Parameter``, and the main
program will contain the network structure and vars for train.

A set of Program can be used for test or train, in train program ,
Paddle will contain all content to build a train network,  in test
program Paddle will prune some content which is irrelevant to test, eg.
backward ops and vars.

**Notes**:
    **we have** :ref:`api_paddle_base_framework_default_startup_program` **and** :ref:`api_paddle_base_framework_default_main_program`
    **by default, a pair of them will shared the parameters. The** :ref:`api_paddle_base_framework_default_startup_program` **only run once to initialize parameters,**
    :ref:`api_paddle_base_framework_default_main_program` **run in every mini batch and adjust the weights.**

Returns:
    Program: An empty Program.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> main_program = static.Program()
        >>> startup_program = static.Program()
        >>> with static.program_guard(main_program=main_program, startup_program=startup_program):
        ...     x = static.data(name="x", shape=[-1, 784], dtype='float32')
        ...     y = static.data(name="y", shape=[-1, 1], dtype='int32')
        ...     z = static.nn.fc(name="fc", x=x, size=10, activation="relu")

        >>> print("main program is: {}".format(main_program))
        >>> print("start up program is: {}".format(startup_program))

c                   [         R                  " 5       U l        [        U S5      /U l        SU l        [        U l        [         R                  R                  R                  U l        / U l        SU l        SU l        S U l        / U l        S U l        / U l        S U l        SU l        SU l        SU l        SU l        SU l        S U l        S U l        S U l        S U l        S U l        S U l        SU l        [@        RB                  " 5       U l"        U RE                  S5      U l#        S U l$        SU l%        SU l&        S U l'        g )Nr   Fr   __auto_checkpoint_program__)(r   r  rv  r{  r  current_block_idxglobal_prog_seed_seedr  r  Forward_current_role_Program__op_role_var_is_distributed	_is_chief_parameters_on_pservers
_endpoints_ps_endpoint_trainers_endpoints_distributed_lookup_table_enable_dgc	_use_lamb_nccl_comm_num_use_hierarchical_allreduce$_hierarchical_allreduce_inter_nranks
_fleet_opt_program_config_pass_applied_pipeline_opt	_pass_opt_heter_pipeline_opt_appending_grad_timesr   UniqueNameGeneratorrp  _auto_checkpoint_name_graph_is_start_up_program__need_decomp_grad_var_to_varr  s    rO   r   Program.__init__  s>   $$&	T1~&!"%
!<<CCKK  %'+$ #% )-& !+0(451 #! " $(  &'"  +>>@%)%9%9)&
"
 %*"
 " $rN   c                   S nU R                   n/ nUR                  5       n[        U5       GHU  nU[        U R                  5      S-
  :  a  U R                  5         UR                  U5      nUR                  / 5        US   nUR                  5        GH  n	U R                  U   R                  U	R                  5       5      (       a-  U R                  U   R                  U	R                  5       5      n
OS n
U	R                  5       U	R                  5       U" U	S[        R                  R                  R                   [        R                  R                  R"                  [        R                  R                  R$                  /5      U" U	S[        R                  R                  R                   [        R                  R                  R"                  [        R                  R                  R$                  /5      U" U	S[        R                  R                  R                   [        R                  R                  R$                  /5      U
b  U
R&                  OS U
b  U
R(                  OSU
b  U
R*                  OSU	R-                  5       U
b  U
R.                  OSS.
n[1        U
[2        5      (       a  UR5                  U
R6                  U
R8                  U
R:                  U
R<                  U
R>                  U
R@                  U
RB                  S	.5        UR                  [2        [D        RF                  " U5      S
.5        GM  U	RI                  5       US'   UR                  [J        [D        RF                  " U5      S
.5        GM     GMX     U$ )Nc                L    U R                  5       U;   a  [        X5      " 5       $ g rK   )r   r  )r)  rU  allowed_typess      rO   get_var_desc_attr_or_noneAProgram._find_var_class_kwargs.<locals>.get_var_desc_attr_or_none  s!    }}-/x355rN   r   r   r-  r  r~  F)
r   r   r-  r  r~  ru  r  r  r  rt  )r  r)  r*  do_model_average	need_clipis_distributedr  )classr   r.  )&rv  
num_blocksr  r[   r  _create_blockrn  r   ra  r  r   ry  r   r   r  r  r+  r  DENSE_TENSOR_ARRAYru  r  r  r  rt  rT   ri  rf   r  r)  r*  r  r  r  r  rL  deepcopyr.  rN  )r   new_descr  old_descall_new_vars	block_numr  new_block_descblock_new_varsnew_var_descold_varr   s               rO   _find_var_class_kwargsProgram._find_var_class_kwargs  s   	 99'')	#Cc$++&*+""$%^^C0N#)"-N . 7 7 9;;s#++L,=,=,?@@"kk#.22<3D3D3FGG"G )--/(--/6$ LL00== LL00>> LL00CC 7$ LL00== LL00>> LL00CC ";$# LL00== LL00CC" /6.A**t 291D--% ,3+>E'3'C'C'E #.  33"U,\ gy11MM)0):):-4-B-B+2+>+>070H0H)0):):.5.D.D,3,@,@
 #))%.&*mmF&; -9,D,D,FF=)"))%-&*mmF&;Q !: $j rN   c                   U R                  U5      nUR                  5       nU[        U5      :X  d   eX0R                  R                  5       :X  d   e[	        U5       HF  nU R
                  U   nUR                  R                  5         UR                  R                  5         MH     [	        U5       H>  nU R
                  U   R                  nUR                  U5      nUR                  U5        M@     A[	        U5       H3  nU R
                  U   nX$    H  nUS   n	US   n
XZS'   U	" S0 U
D6  M     M5     [	        U5       H  nU R
                  U   nU R                  R                  U5      n[	        UR                  5       5       H8  nUR                  U5      n[        X\S9nUR                  R                  U5        M:     M     g )Nr  r   rn  rU  rM   )r  r  r[   rv  r  r  r  clearr  rn  
_move_fromrd  r  r  r   )r   rv  r  r  r  rn  
block_descr  rK  clazzr   rg  rM  r  s                 rO   r}  Program._rebuild_from_desc,  s   2248OO%	C----II002222 #CKK$EJJIIOO $
 #CS)..J!ZZ_N!!.1 $
  #CKK$E',( *"'w	 - $ #CKK$E-J
 2 2 45$--/E8		  $ 6 $rN   c                    Uq [         U l        g)a  
Set global seed for Program

Returns:
    None.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> prog = static.default_main_program()
        >>> print(prog.random_seed)
        0
        >>> ## the default random seed is 0

        >>> prog.global_seed(102)
        >>> prog1 = static.default_main_program()
        >>> print(prog1.random_seed)
        102
        >>> ## the random seed is 102
N)r  r  r   seeds     rO   global_seedProgram.global_seedQ  s    6  %
rN   c                    U R                   $ )aI  
The operator role. In a enum {Forward, Backward, Optimize}.

Notes: this is a low level API. It is used only for ParallelExecutor to
duplicate or schedule operator to devices.

For example, the forward operator should be executed on every device.
The backward operator should be executed on every device and the
parameter gradient of backward (use :code:`_op_role_var` to get this
variable) operator should be merged to one device. The optimization
operators should be executed on only one device and broadcast the
optimization result, i.e., the new parameter, to every other device.
r  r  s    rO   r  Program._op_roleo  s     !!!rN   c                    Xl         g rK   r  )r   roles     rO   r  r    s    !rN   c                    U R                   $ )z
The auxiliary variables for :code:`_op_role` property.

See Also: :code:`Program._op_role`'s documentation for details.

Notes: This is a very low-level API. Users should not use it directly.
)r  r  s    rO   r  Program._op_role_var  s     !!!rN   c              #     #    U R                   n[        R                  R                  nUR                  U l          S v   Xl         g ! Xl         f = f7frK   )r  r   r  r  r  )r   tmp_roler  s      rO   _backward_role_guardProgram._backward_role_guard  sA     %%0077#__	*!)s   8AA AAAc              #  R  #    U R                   nU R                  n[        R                  R                  nUR
                  U l         U Vs/ s H&  n[        U[        5      (       a  UR                  OUPM(     snU l         Sv   X0l        X l         gs  snf ! X0l        X l         f = f7f)a  
A with guard to set :code:`Optimization` :code:`OpRole` and
:code:`OpRoleVar` automatically.

Notes: This is a very low level API. Users should not use it directly.

Args:
    param_and_grads(list): The variables (names) to be optimized.

Examples:

    >>> import paddle.base as base
    >>> p, g = backward(...)
    >>> with program._optimized_guard([p,g]):
    >>>     p = p - 0.001 * g
N)	r  r  r   r  r  r  rT   rN  r   )r   param_and_gradsr  tmp_varr  ry  s         rO   _optimized_guardProgram._optimized_guard  s     $ %%$$0077#__ '
& #311CHHs:&
	*!(!)
 ")!)s*   AB'
-B7B' B B'B$$B'c              #  R  #    U R                   nU R                  n[        R                  R                  nUR
                  U l         U(       a0  [        UR
                  5      [        UR                  5      -  U l         / U l         Sv   X0l        X l         g! X0l        X l         f = f7f)a/  
A with guard to set :code:`LRSched` :code:`OpRole` and
:code:`OpRoleVar` automatically. The :code:`OpRoleVar` is
set to the target learning rate.

Notes: This is a very low level API. Users should not use it directly.

Args:
    is_with_opt: Only set to true if these ops a in the middle
         of a bunch of optimize ops so that it can be treated
         correctly. For example, sgd->lr_op->sgd->lr_op->sgd.

Examples:

    >>> import paddle.base as base
    >>> p, g = backward(...)
    >>> with program.lr_schedule_guard():
    >>>     lr = lr * decay
N)r  r  r   r  r  LRSchedr  r  )r   is_with_optr  r  r  s        rO   _lr_schedule_guardProgram._lr_schedule_guard  s     , %%$$0077#^^!$V^^!4s6??7K!KD	*!(!) ")!)s   BB'B 	B'B$$B'c                "    U R                  5       $ )z
Get the protobuf debug string of this Program.

Returns:
    (str): The protobuf debug string.

Raises:
    ValueError: If any of required fields is not set.
r  r  s    rO   r   Program.__str__  s     %%''rN   c                    [        U[        5      (       d   S[        U5       35       eSnU R                   H  nX#R	                  U5      -  nUS-  nM     U$ )a  
Get readable debug string of Program.

.. note::
    If you want to get the debug string in protobuf format,
    please use :code:`to_string` method.

Args:
    skip_op_callstack(bool): whether to skip parsing Operator's attribute
        op_callstack, default value is True

Returns:
    string: The formatted Program string.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> cur_program = static.Program()
        >>> cur_block = cur_program.current_block()
        >>> new_var = cur_block.create_var(name="X",
        ...                                shape=[-1, 23, 48],
        ...                                dtype='float32')
        >>> new_op = cur_block.append_op(type="abs",
        ...                     inputs={"X": [new_var]},
        ...                     outputs={"Out": [new_var]})
        >>> print(cur_program._to_readable_code())
r1  r  r   )rT   r  r   r  r  )r   rH  program_strrn  s       rO   r  Program._to_readable_code  sm    B +T22 	
QRVWhRiQjk	
2 [[E223DEEK4K ! rN   c                   [        U[        5      (       d   S[        U5       S35       e[        U[        5      (       d   S[        U5       S35       eU(       a  SnU R                   H  nX4R	                  X5      -  nM     U R
                  R                  5       n[        R                  R                  [        U5      5      nUS[        R                  " [        UR                  U5      S5      -   S-   -  nUS[        R                  " [        UR                  U5      S5      -   S-   -  nU$ U R
                  R                  5       n[        R                  R                  [        U5      5      n[        Xa5      nU$ )	a  
To debug string.

Args:

    throw_on_error (bool): raise Value error when any of required fields is not set.

    with_details (bool): True if more details about variables and parameters, e.g., :code:`trainable`, :code:`optimize_attr`, need to print.

Returns:
    str: The debug string describe current Program.

Raises:
    ValueError: If any of required fields is not set and throw_on_error is True.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> prog = static.default_main_program()
        >>> x = static.data(name="X", shape=[2,3], dtype="float32")
        >>> pred = static.nn.fc(x, size=3)
        >>> prog_string = prog.to_string(throw_on_error=True, with_details=False)
        >>> prog_string_with_details = prog.to_string(throw_on_error=False, with_details=True)
        >>> print("program string without detail: {}".format(prog_string))
        >>> print("program string with detail: {}".format(prog_string_with_details))
zKThe type of throw_on_error parameter is wrong, expected bool, but received r  zIThe type of with_details parameter is wrong, expected bool, but received r  zversion {
  z  z}
zop_version_map {
  )rT   r  r   r  r  rv  r  r   r  r  r  textwrapindentr&  r  op_version_map)r   r$  r  r  rn  r  r#  s          rO   r  Program.to_string  sr   @ .$// 	
YZ^_mZnYoopq	
/ ,-- 	
WX\]iXjWkklm	
- G??>HH %yy446H!--88xIE//"5==.A4 	G &//"5#7#7H$ 	G  yy446H!--88xIE$U;GrN   c                    U R                   $ )z
Get the C++ side of `ProgramDesc` object pointer. The C++ object is
exposed by :code:`pybind`.

Notes: This is a very low level API. Users should not use this API
directly.
)rv  r  s    rO   	_get_descProgram._get_descW  s     yyrN   c                6    U R                   R                  5       $ rK   )rv  _versionr  s    rO   r  Program._versiona  s    yy!!##rN   c                <   U R                  5         SnU(       a  [        5       n[        R                  " U R                  5      u  Ul        n[        UR                  R                  5       5       Vs/ s H  n[        X45      PM     snUl        UR                  5         UR                  SS9nGO[        5       nU R                  Ul
        U R                  Ul        [        R                  " U R                  5      Ul        [        U R                  R                  5       5       Vs/ s H  n[        XT5      PM     snUl        U R                  Ul        U R                  Ul        U R                  Ul        [!        U S5      (       a  U R"                  Ul        [!        U S5      (       a  U R$                  Ul        [!        U S5      (       a  U R&                  Ul        [!        U S5      (       a  U R(                  Ul        [!        U S5      (       a  U R*                  Ul        UR                  5         UR-                  U 5        UR/                  X5        UR1                  U 5        UR3                  U 5        U R4                  R7                  5       Ul        U$ s  snf s  snf )	a   
.. note:::
    1. :code:`Program.clone()` method DOES NOT clone :ref:`api_paddle_io_DataLoader` .
    2. Recommend you to use :code:`clone` before using :code:`Optimizer.minimize` .
    3. This API has no effect in Dygraph Mode.

Create a new Program with forward content of original one when ``for_test=True``.
Create a new Program as same as the original one when ``for_test=False``.

Some operators, e.g., :ref:`api_paddle_base_layers_batch_norm` , behave differently between
training and testing. They have an attribute, :code:`is_test`, to
control this behaviour. This method will change the :code:`is_test`
attribute of them to :code:`True` when :code:`for_test=True`.

* Set for_test to False when you want to clone the program for training.
* Set for_test to True when you want to clone the program for testing.
  We will prune the backward and optimize part of the program when you
  use :code:`clone` after :code:`Optimizer.minimize`, but we still
  recommend you to use :code:`clone` before using :code:`Optimizer.minimize`.

Examples:
    .. code-block:: python
        :name: code-example-1

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> img = static.data(name='image', shape=[None, 784])
        >>> pred = static.nn.fc(x=img, size=10, activation='relu')
        >>> loss = paddle.mean(pred)
        >>> # Here we use clone before Momentum
        >>> test_program = static.default_main_program().clone(for_test=True)
        >>> optimizer = paddle.optimizer.Momentum(learning_rate=0.01, momentum=0.9)
        >>> optimizer.minimize(loss)

Args:

    for_test (bool): True if change the :code:`is_test` attribute of operators to :code:`True`
        and prune the backward and optimize part of the program. The default value is :code:`False` .

Returns:
    Program: A new Program with forward content of original one when ``for_test=True``.  A new Program as same as the original one when ``for_test=False``


Examples:

    .. note::
        The Program's order maybe different after :code:`clone` and
        this will not affect your training or testing progress. In the following
        example we give you an simple method :code:`print_prog(program)` to
        print Program Descs inorder to make sure you have same print result
        after :code:`clone`:

    .. code-block:: python
        :name: code-example-2

        >>> import paddle

        >>> def print_prog(prog):
        ...     for name, value in sorted(prog.block(0).vars.items()):
        ...         print(value)
        ...     for op in prog.block(0).ops:
        ...         print("op type is {}".format(op.type))
        ...         print("op inputs are {}".format(op.input_arg_names))
        ...         print("op outputs are {}".format(op.output_arg_names))
        ...         for key, value in sorted(op.all_attrs().items()):
        ...             if key not in ['op_callstack', 'op_role_var']:
        ...                 print(" [ attrs: {}:   {} ]".format(key, value))


    1. To clone a test program, the sample code is:
        .. code-block:: python
            :name: code-example-3

            >>> import paddle
            >>> import paddle.static as static
            >>> import paddle.utils as utils
            >>> import paddle.nn.functional as F

            >>> paddle.enable_static()

            >>> def print_prog(prog):
            ...     for name, value in sorted(prog.block(0).vars.items()):
            ...         print(value)
            ...     for op in prog.block(0).ops:
            ...         print("op type is {}".format(op.type))
            ...         print("op inputs are {}".format(op.input_arg_names))
            ...         print("op outputs are {}".format(op.output_arg_names))
            ...         for key, value in sorted(op.all_attrs().items()):
            ...             if key not in ['op_callstack', 'op_role_var']:
            ...                 print(" [ attrs: {}:   {} ]".format(key, value))

            >>> train_program = static.Program()
            >>> startup_program = static.Program()

            >>> # startup_program is used to do some parameter init work,
            >>> # and main program is used to hold the network
            >>> with static.program_guard(train_program, startup_program):
            ...     with utils.unique_name.guard():
            ...         img = static.data(name='image', shape=[None, 784])
            ...         hidden = static.nn.fc(x=img, size=200, activation='relu')
            ...         hidden = F.dropout(hidden, p=0.5)
            ...         loss = F.cross_entropy(
            ...             input=static.nn.fc(x=hidden, size=10, activation='softmax'),
            ...             label=static.data(name='label', shape=[1], dtype='int64'))
            ...         avg_loss = paddle.mean(loss)
            ...         test_program = train_program.clone(for_test=True)
            >>> print_prog(test_program)

            >>> # Due to parameter sharing usage for train and test, so we need to use startup program of train
            >>> # instead of using test startup program, while nothing is in test's startup program

            >>> # In Paddle we will share weights by using the same Tensor name. In train and test program
            >>> # all parameters will have the same name and this can make train and test program sharing parameters,
            >>> # that's why we need to use startup program of train. And for startup program of test, it has nothing,
            >>> # since it is a new program.

            >>> with static.program_guard(train_program, startup_program):
            ...     with utils.unique_name.guard():
            ...         sgd = paddle.optimizer.SGD(learning_rate=1e-3)
            ...         sgd.minimize(avg_loss)


    2. The clone method can be avoid if you create program for training and program for testing individually.
        .. code-block:: python
            :name: code-example-4

            >>> import paddle
            >>> import paddle.static as static
            >>> import paddle.utils as utils
            >>> import paddle.nn.functional as F

            >>> paddle.enable_static()

            >>> def print_prog(prog):
            ...     for name, value in sorted(prog.block(0).vars.items()):
            ...         print(value)
            ...     for op in prog.block(0).ops:
            ...         print("op type is {}".format(op.type))
            ...         print("op inputs are {}".format(op.input_arg_names))
            ...         print("op outputs are {}".format(op.output_arg_names))
            ...         for key, value in sorted(op.all_attrs().items()):
            ...             if key not in ['op_callstack', 'op_role_var']:
            ...                 print(" [ attrs: {}:   {} ]".format(key, value))

            >>> def network():
            ...     img = static.data(name='image', shape=[None, 784])
            ...     hidden = static.nn.fc(x=img, size=200, activation='relu')
            ...     hidden = F.dropout(hidden, p=0.5)
            ...     loss = F.cross_entropy(
            ...         input=static.nn.fc(x=hidden, size=10, activation='softmax'),
            ...         label=static.data(name='label', shape=[1], dtype='int64'))
            ...     avg_loss = paddle.mean(loss)
            ...     return avg_loss

            >>> train_program_2 = static.Program()
            >>> startup_program_2 = static.Program()
            >>> test_program_2 = static.Program()
            >>> with static.program_guard(train_program_2, startup_program_2):
            ...     with utils.unique_name.guard():
            ...         avg_loss = network()
            ...         sgd = paddle.optimizer.SGD(learning_rate=1e-3)
            ...         sgd.minimize(avg_loss)
            >>> # the test startup program is not used.
            >>> with static.program_guard(test_program_2, startup_program_2):
            ...     with utils.unique_name.guard():
            ...         avg_loss = network()
            >>> print_prog(test_program_2)

    The two code snippets above will generate and print same programs.
NF)prune_read_oplr_schedulerr  r  r  r  )r,  rE  r   prune_backwardrv  r  r  r{  r  _inference_optimizer  r  r  r  r  r  r  r  r  r  r  r  rr  _copy_data_info_from_copy_dist_param_info_from_copy_operator_info_fromrp  r  )r   r  pruned_origin_block_id_mapforward_progr  r  s         rO   r  Program.cloned  s   b 	%)""9L<@<O<O		=9L9
 |00;;=>#>A l&>#L '')00u0EA	A"&"8"8AjjAG%%dii0AF-24993G3G3I-JK-Ja-JKAH"00AO"00AO&*&@&@A#t^,,!%!2!2t_--"&"4"4t[))"nnt^,,!%!2!2t/00%)%:%:" 	%	t@	$$T*	""4( 00668G# Ls   1J%Jc              #  &  #    [        U[        5      (       a  [        R                  " U5      nO9[        U[        5      (       a$  [        R                  " UR                  5       5      nU R                  nXl         S v   X l        g ! X l        f = f7frK   )rT   r\   r   r  r  r  rp  )r   new_generatorold_generators      rO   switch_name_generator_guard#Program.switch_name_generator_guardB  sr     mS))';;MJMu--';;$$&M ,,,	1#0 = s   A8B;B ?BBBc                &    U R                  / U5      $ )aj  
Prune operators and variables which are not needed to generate
:code:`targets`.

Notes: This is a very low level API. Users should not use this API
directly. This API is in flux and not stable.

Args:
    targets(list|Variable|Operator): A list of variables, operators, or variable names
        need to be pruned

Returns:
    Program:  A new, pruned program.
)_prune_with_input)r   targetss     rO   _pruneProgram._pruneR  s     %%b'22rN   c                   U R                  5         [        U[        5      (       d  U/n[        U[        5      (       d  U/nU H0  n[        U[        5      (       a  M  [	        S[        U5       S35      e   [        5       n[        U R                  5       R                  5       H  u  pVSnUR                   Hq  nU R                  5       R                  U5      (       d  M)  U R                  5       R                  U5      R                  (       a  MY  XR                  U5      ;  d  Mo  Sn  O   U(       d  M  UR                  UR                  5      nM     / n	U GHK  n
[        U
[         5      (       Gd   [        U
["        5      (       a  U
R$                  nO9[        U
[        5      (       a  [        U
5      nO[	        S[        U
5       S35      eX;   a  X;  a  M  SnU R                  5       n[        UR                  5       H4  u  pVXR                  ;   d  M  UR'                  5       (       a  Xb;  a  M2  UnM6     Ub4  U	R)                  UR*                  R,                  UR,                  /5        GM  GM  U	R)                  U
R*                  R,                  U
R,                  /5        GMN     [/        5       n[0        R2                  " U R4                  [        U5      U	5      u  Ul        n[7        UR4                  R9                  5       5       Vs/ s H  n[;        X5      PM     snUl        UR                  5         UR?                  U 5        URA                  X5        URC                  U 5        URE                  U 5        U$ s  snf )aA  
Prune operators and variables which are not needed to generate
:code:`targets`. Prune operators and variables which are needed
to generate feeded_var

Notes: This is a very low level API. Users should not use this API
directly. This API is in flux and not stable.

Args:
    feeded_var_names(list|str): A list of variable names from where
        pruning start. If it is set as [], this API works just like _prune()
    targets(list|Variable|Operator): A list of variables, operators, or variable names
        need to be pruned

Returns:
    Program:  A new, pruned program.
zRAll feeded_var_names of Program._prune_with_input() can only be str, but received r  TFzZAll targets of Program._prune_with_input() can only be Variable or Operator, but received N)#r,  rT   rd   r\   r]   r   rt  r1  r  r  rf  r  ry  r.  r  r  r  rN  r   r  r   rn  r  rE  r   prunerv  r  r  r{  r  rr  r  r  r  )r   feeded_var_namesr  ry  generatable_varsr  r  runnable_opr   targets_idxr`  	target_opr  resr  r  s                   rO   r  Program._prune_with_inputc  s   * 	*D11 01'4((iG#Cc3'' ))-c16  $ 5 !2!2!4!8!89GCK**((*22488$$&**40<<556FGG"'K + {#3#9#9":M:M#N  : Aa**a**66D3''q6D$>>B1gYaI  +3  !	#002()9)9:GC222 --//B4E$(*I  ; (&&	(;(;Y]]'KL ) ""AGGKK#78Q T i/3zzIIs+,k0
,, .33883F3F3H-IJ-IeCm-IJ
!!$'  B&&t,$$T*
 Ks   
M=c                   [        5       n[        R                  " U R                  5      Ul        SnUR                  R	                  S5      nU(       a   X4R                  5       :  d#  UR                  U5      R                  5       S:X  a  OUS-  nM>  X4R                  5       :  a  UR                  SUS-   5        UR                  5        Hh  nUR                  5       [        R                  R                  R                  :X  d  M;  UR                  UR                  5       R                  5       5        Mj     [!        UR                  R#                  5       5       H  nUR                  R	                  U5      n[!        UR                  5       5       Hc  nUR                  U5      n	U	R%                  S5      (       a  U	R'                  SS5        U	R                  5       S:X  d  MR  U	R)                  S5        Me     M     [!        UR                  R#                  5       5       Vs/ s H  n[+        X&5      PM     snUl        UR/                  5         U$ s  snf )a6  
This method will create a new program and do following adjustments on it:
1. Remove all reader variables and their creator ops if exist.

2. Remove the :code:`read_op` if exists.

3. change the :code:`is_test`
attribute of operators to :code:`True`. All the :code:`Parameter`
information will be lost.

Args:
    prune_read_op(bool): remove the read ops that are added by py_reader
                         for cpp inference library

Notes: This API is a very low level API. Use
:code:`Program.clone(for_test=True)` instead.

Returns:
    Program: The new program.
r   Treadr   r  
batch_normReserveSpace)rE  r   r  rv  rn  rd  r  r   rX  ra  r  r  READERr2  r   rx  r  r  r  r  r  r{  r  r,  )
r   r  r  read_op_idx
root_blockry  r  rn  jr  s
             rO   r   Program._inference_optimize  s   * i##DII. XX^^A&
#5#5#77!}}[1668FBq   //11%%aq9!**,88:!5!5!<!<<**388:+<+<+>? -
 sxx**,-AHHNN1%E5==?+XXa[;;y))%%i6779,$$^4 , . .33883F3F3H-IJ-IeCm-IJ

 Ks   !Ic           	     P   [        5       n[        R                  " U R                  5      Ul        [	        UR                  R                  5       5       Vs/ s H  n[        X#5      PM     snUl        UR                  5         SS/n[	        UR                  R                  5       5       GHs  nUR                  R                  U5      nUR                  5        H#  nUR                  5         UR                  5         M%     U(       d  M_  [	        SUR                  5       5       GH  nUR                  U5      nUR                  5       [         R#                  5       R$                  ;  a  MG  [        R&                  " UR                  5       5      n	[         R#                  5       R)                  UR                  5       5      n
/ nUR+                  5        Hh  nSnU
R,                   H9  nUR.                  U:w  a  M  UR0                  (       a  UR3                  U5        Sn  O   U(       a  MW  UR3                  U5        Mj     / nUR5                  5        Hh  nSnU
R6                   H9  nUR.                  U:w  a  M  UR0                  (       a  UR3                  U5        Sn  O   U(       a  MW  UR3                  U5        Mj     U H  nUR9                  U5        M     [        R:                  R=                  5       nUUR?                  5       ;   a  [A        URC                  U5      5      OSnUSSSS	S
S/nU	RE                  5        H  nURG                  U5        M     / nUR?                  5        H  nU(       a   UU;   a  M  URI                  S5      (       a  M*  [K        U	5      S:  a  X;   a  URG                  U5        MQ  SnU
RL                   H  nUR.                  U:w  a  M  Sn  O   U(       a  M  UR3                  U5        M     U H  nURG                  U5        M     GM     GMv     U$ s  snf )a  
This method will create a new program and do following adjustments on it:
1. Remove all variable's `is_parameter` attribute if exist.

2. Remove all variable's `stop_gradient` attribute if exist.

Notes: This API is a very low level API.

Returns:
    Program: The new program.
r5  with_quant_attrr   FTquantization_type
skip_quantactivation_bits
bit_lengthquantize_weight_bitsweight_quant_scale
_threshold)'rE  r   r  rv  r  r  r{  r  r,  rn  ra  clear_is_parameterclear_stop_gradientrd  r  r   r  r_  r  r	  r  r:  r  r   extrar   r9  r  r  r  kOpWithQuantAttrNamer  r  rT  rr  r  endswithr[   rM  )r   
clip_extrar  r  common_clipped_attrs_listrn  ry  rg  r  r%  r#  remove_input_listr   findinput_protoremove_output_listoutput_protoop_quant_namequantquant_attrsextra_attr_nameremove_attr_list
attr_protos                          rO   _remove_training_infoProgram._remove_training_info  s~    i##DII.-23883F3F3H-IJ-IeCm-IJ
 &45F$G!sxx**,-AHHNN1%E~~'&&('') ( 5==?3XXf%779M$:$:$<$I$II"&"9"9"'')"D%..0==bggiH$&!NN,D D',||&++t3$&,,-44T:# (4  4)006 - &("OO-D D(-',,4$'--.55d;# )6  4*11$7 . /D$$T* / 33HHJ 
 %7 /0  "' % *( (7';';'=ONN?3 (>#% MMOD;.$==66$?+a/<NN40  D&+kk
%??d2$#	 '2
  4(//5# ,$ -DNN4( -] 4 .n 
} Ks   P#c                    [        5       n[        R                  " U 5      Ul        [	        UR                  R                  5       5       Vs/ s H  n[        X5      PM     snUl        UR                  5         U$ s  snf )a  
.. note::
    1. All information about parameters will be lost after serialization;
    2. This API has no effect in Dygraph mode.

Deserialize a Program from  `protobuf <https://en.wikipedia.org/wiki/Protocol_Buffers>`_  binary string.
This method always use to save and load model

Args:

    binary_str_type (str): the binary protobuf string.

Returns:
    Program: A deserialized Program.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> startup_prog = static.Program()
        >>> main_prog = static.Program()
        >>> with static.program_guard(startup_prog, main_prog):
        ...     x = static.data(name='X', shape=[1000, 784], dtype='float32')
        ...     y = static.data(name='Y', shape=[784, 100], dtype='float32')
        ...     z = paddle.matmul(x=x, y=y)
        ...     binary_str = static.default_main_program().desc.serialize_to_string()
        ...     prog_restored = static.default_main_program().parse_from_string(binary_str)
        ...     print(static.default_main_program())
        ...     print(prog_restored)
)	rE  r   r  rv  r  r  r{  r  r,  )
binary_strr  r  s      rO   rF  Program.parse_from_stringu  sc    H I!!*-).qvv/@/@/B)CD)CAE!K)CD	 Es   A:c                    [        5       nXl        [        UR                  R                  5       5       Vs/ s H  n[	        X5      PM     snUl        UR                  5         U$ s  snf )z
Construct a program from program desc.

Args:
    desc(core.ProgramDesc): The program desc for constructing.

Returns:
    Program: A program.
)rE  rv  r  r  r{  r  r,  )rv  r  r  s      rO   r  Program._construct_from_desc  sU     I).qvv/@/@/B)CD)CAE!K)CD	 Es   A%c                    U R                   $ )a  
The default random seed for random operators in Program. ``0`` means get
the random seed from random device.

.. note::
    It must be set before the operators have been added.

Returns:
    int64: Random seed in current Program


Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static
        >>> import paddle.nn.functional as F

        >>> paddle.enable_static()

        >>> prog = static.default_main_program()
        >>> random_seed = prog.random_seed
        >>> x_var = static.data(name="X", shape=[3,3], dtype="float32")
        >>> print(random_seed)
        0
        >>> ## the default random seed is 0

        >>> # Here we need to set random seed before we use paddle.nn.functional.dropout
        >>> prog.random_seed = 1
        >>> z_var = F.dropout(x_var, 0.7)

        >>> print(prog.random_seed)
        1
        >>> ## the random seed is change to 1
)r  r  s    rO   random_seedProgram.random_seed  s    J zzrN   c                6    U R                   R                  5       $ )a  
The number of :ref:`api_guide_Block_en`  in this Program.

.. note::
    This API has no effect in Dygraph mode.

Returns:
    int(Platform-dependent size): num of :ref:`api_guide_Block_en`  in current Program


Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> prog = static.default_main_program()
        >>> num_blocks = prog.num_blocks
        >>> print(num_blocks)
        1
)rv  r  r  s    rO   r  Program.num_blocks  s    2 yy##%%rN   c                j    [        U[        5      (       d  [        S[        U5       S35      eXl        g )NzBProgram.random_seed's input seed must be an integer, but received r  )rT   r  r]   r   r  r  s     rO   rF  rG    s8    $$$TUYZ^U_T``ab  
rN   c                "    U R                  5       $ rK   )r   r  s    rO   r  Program.__repr__  s    ||~rN   c                     U R                   S   $ )a  
.. note::
    This API has no effect in Dygraph mode.

Get the first :ref:`api_guide_Block_en` of this Program.

Returns:
    :ref:`api_guide_Block_en`: The first :ref:`api_guide_Block_en`  of this Program.


Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> prog = static.default_main_program()
        >>> gb_block = prog.global_block()
        >>> print(gb_block)

r   r  r  s    rO   r  Program.global_block  s    0 {{1~rN   c                     U R                   U   $ )a  
.. note::
    This API has no effect in Dygraph mode.

Get the :code:`index`  :ref:`api_guide_Block_en`  of this Program

Args:
    index (int): The index of  :ref:`api_guide_Block_en`  to get

Returns:
    :ref:`api_guide_Block_en`: The :code:`index` block

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> prog = static.default_main_program()
        >>> block_0 = prog.block(0)
        >>> print(block_0)
rN  )r   r   s     rO   rn  Program.block  s    2 {{5!!rN   c                4    U R                   U R                     $ )a3  
.. note::
    This API has no effect in Dygraph mode.

Get the current  :ref:`api_guide_Block_en` . The :code:`current`  :ref:`api_guide_Block_en`
is the  :ref:`api_guide_Block_en`  to append operators.

Returns:
     :ref:`api_guide_Block_en`: The :code:`index`  :ref:`api_guide_Block_en`

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> prog = static.default_main_program()
        >>> current_blk = prog.current_block()
        >>> print(current_blk)
)r  r  r  s    rO   current_blockProgram.current_block2  s    . {{41122rN   Nc                F   [        U R                  5      nUc  U R                  5       OU R                  U5      nU R                  R                  UR                  5        X l        U R                  R                  [        X R                  5      5        U R                  5       $ )z
Create a new block with the :code:`parent_idx` and change the current block
to new block.

Args:

    parent_idx(int): The parent block index.

Returns:
    Block: The new block.
)	r[   r  rS  rn  rv  append_blockr  r   r{  )r   r  new_block_idxr  s       rO   r  Program._create_blockK  s     DKK( !  J' 	
 			v{{+!.5'='=>?!!##rN   c                    SU l         g )Nr   )r  r  s    rO   _roll_to_global_blockProgram._roll_to_global_blockb  s
    !"rN   c                B    U R                  5       R                  U l        g)zK
Exit a code block, i.e., roll back to the parent block.
Returns:
    None
N)rS  r  r  r  s    rO   	_rollbackProgram._rollbacke  s     "&!3!3!5!@!@rN   c                   [        [        U R                  5      U R                  R	                  5       5       H'  nU R                  R                  [        X5      5        M)     U R                   H  nUR                  5         M     g)z
Synchronize Python instance to its binding C++ object instance.
If the program is modified in C++ space, this method should be invoked.

Notes: This is a very low level API. Users should not invoke it
directly.

Returns:
    None
N)r  r[   r  rv  r  r   r{  r,  )r   	block_idxrn  s      rO   r,  Program._sync_with_cppm  s]     s4;;/1E1E1GHIKKuT56 I[[E  " !rN   c                    [        U[        5      (       d  [        S[        U5       35      eU R	                  5       R                  UR	                  5       5        g)z
Copy the information of parameters from other program.

Notes: This is a very low level API. Users should not invoke it
directly.

Args:
    other(Program): Other program

Returns:
    None
YFunction Program._copy_param_info_from() needs to pass in a source Program, but received N)rT   rE  rV   r   r  rr  r   rp  s     rO   rr  Program._copy_param_info_from}  sR     %))klpqvlwkxy  	11%2D2D2FGrN   c                (   [        U[        5      (       d  [        S[        U5       35      eUR                  U l        UR
                  U l        UR                  U l        UR                  U l        UR                  U l        UR                  U l	        g)z
Copy the information of distributed information from other program.

Args:
    other(Program): Other program

Returns:
    None
rc  N)
rT   rE  rV   r   r  r  r  r  r  r  rd  s     rO   r  "Program._copy_dist_param_info_from  s     %))klpqvlwkxy   %44','D'D$**!..).)H)H&rN   c                   [        U[        5      (       d  [        S[        U5       35      eU(       d3  [	        U R
                  R                  5       5       Vs0 s H  o3U_M     nn[        U R                  5       H  u  p4UR                  X#      n[        UR                  R                  5       5       H  nUR                  UR                  5      nUR                  (       a  SUl        UR
                  R                  5       (       a  UR
                  R!                  S5        UR"                  (       d  M  SUl        M     M     gs  snf )a  
Copy the information of data variables from other program.

Notes: This is a very low level API. Users should not invoke it
directly.

Args:
    other(Program): Other program
    pruned_origin_block_id_map(dict{int:int}): A dict which maps the block id in program
    self to the block id in program other. For example, {0:0, 1:1, 2:3} means block 0 in self is
    cloned from block 0 in other, etc. Default is None, which means default mapped,
    {0:0, 1:1,..., n:n}.

Returns:
    None
rc  TN)rT   rE  rV   r   r  rv  r  r1  r  rd   r  r  ry  r   r  r  r  r  )r   rp  r  r  rn  other_blockry  	other_vars           rO   r  Program._copy_data_info_from  s   " %))klpqvlwkxy  *#DII$8$8$:;*;1; ' * "$++.HA,,'A'DEKEJJ--/0'OOCHH5	$$"&CK>>1133HH006***(,C% 1 /*s   Ec                X   [        U[        5      (       d  [        S[        U5       35      e[	        U R
                  UR
                  5       HZ  u  p#[	        UR                  UR                  5       H1  u  pEUR                  UR                  5        UR                  Ul	        M3     M\     g)z~
Copy the information of Operator information from other program.

Args:
    other(Program): Other program

Returns:
    None
z\Function Program._copy_operator_info_from() needs to pass in a source Program, but received N)
rT   rE  rV   r   zipr  r  r  r  r  )r   rp  	dst_block	src_blockdst_opsrc_ops         rO   r   Program._copy_operator_info_from  s     %))nostyozn{|  %(U\\$B I"%immY]]"C&&v'9'9:%+%7%7" #D %CrN   c              #     #    U R                    H.  n[        UR                  R                  5       5       Sh  vN   M0     g N	7f)a0  
Get all Tensors from this Program. A iterable object is returned.

Returns:
    iterable Tensors: The Generator will yield every Tensor in this program.

Examples:
    .. code-block:: python

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> prog = static.default_main_program()
        >>> img = static.data(name='img', shape=[None, 1,28,28], dtype='float32')
        >>> label = static.data(name='label', shape=[None,1], dtype='int64')
        >>> for var in prog.list_vars():
        ...     print(var)

        >>> # var img : DENSE_TENSOR.shape(-1, 1, 28, 28).dtype(float32).stop_gradient(True)
        >>> # var label : DENSE_TENSOR.shape(-1, 1).dtype(int64).stop_gradient(True)
N)r  rd   r  r  )r   
each_blocks     rO   	list_varsProgram.list_vars  s3     2 ++JJOO224555 &5s   6AA
Ac                n    / nU R                    H"  nUR                  UR                  5       5        M$     U$ )aO  
Get all :ref:`api_guide_parameter_en` from this Program. A list object is returned.

Returns:
    list[ :ref:`api_guide_parameter_en` ]: The list contains all parameters in this program.

Examples:
    .. code-block:: python

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> program = static.default_main_program()
        >>> data = static.data(name='x', shape=[None, 13], dtype='float32')
        >>> hidden = static.nn.fc(x=data, size=10)
        >>> loss = paddle.mean(hidden)
        >>> paddle.optimizer.SGD(learning_rate=0.01).minimize(loss)

        >>> for param in program.all_parameters():
        ...     print(param)

        >>> # Here will print all parameters in current program, in this example,
        >>> # the result is like:
        >>> #
        >>> # persist trainable param fc_0.w_0 : DENSE_TENSOR.shape(13, 10).dtype(float32).stop_gradient(False)
        >>> # persist trainable param fc_0.b_0 : DENSE_TENSOR.shape(10,).dtype(float32).stop_gradient(False)
        >>> #
        >>> # Here print(param) will print out all the properties of a parameter,
        >>> # including name, type and persistable, you can access to specific
        >>> # property of a parameter, such as param.name, param.type
)r  extendr  )r   
parametersrt  s      rO   r  Program.all_parameters  s5    F 
++Jj779: &rN   c                  ^^	^
^ SSK Jn  Ub7  [        U[        R                  5      (       d  [        S[        U5       S35      eUc  U" 5       n[        T[        5      (       d  [        S[        T5       S35      eS m
S mU4S jm	U	U
U4S	 jn[        X@R                  5       5      n0 nU HV  nUR                  UR                  5      nUc  [        S
UR                   S35      eUR                  5       XgR                  '   MX     U$ )a  
Get parameters and persistable buffers of program as a dict. The key is the name of the parameter or the name of the buffer.
The value is the tensor of this variable in the given scope.

.. note::
    This function MUST called after run start_up_program

Args:
    mode(str, optional): Source of the obtained parameters and buffers.
            'opt' :  The return value only contains the variable in the optimizer.
            'param' : The return value only contains the variable in the network, not the variable in the optimizer.
            'all' : The return value contains the variable in the network and optimizer.
            Default: 'all'
    scope(Scope, optional) : If scope is None, state_dict will be set to global scope
        obtained through 'paddle.static.global_scope()'. Otherwise, value will be set to scope.
        Default: None

Returns:
    dict: a dict contains the parameters and persistable buffers.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> x = static.data(name="x", shape=[10, 10], dtype='float32')
        >>> y = static.nn.fc(x, 10)
        >>> z = static.nn.fc(y, 10)

        >>> place = paddle.CPUPlace()
        >>> exe = static.Executor(place)
        >>> exe.run(static.default_startup_program())
        >>> prog = static.default_main_program()

        >>> path = "./temp/model.pdparams"
        >>> paddle.save(prog.state_dict(), path)
r   r\  zD`scope` should be None or `paddle.static.Scope'` type, but received r  z.Type of `mode` should be string, but received c                "    [        U [        5      $ rK   r   ry  s    rO   r  (Program.state_dict.<locals>.is_parameter`  s    c9--rN   c                   U R                   R                  5       [        R                  R                  R
                  :X  d  U R                   R                  5       [        R                  R                  R                  :X  d@  U R                   R                  5       [        R                  R                  R                  :X  a  gU R                  $ NF)	rv  r   r   r  r  FEED_MINIBATCH
FETCH_LISTr  r.  r}  s    rO   is_persistable*Program.state_dict.<locals>.is_persistablec  su    4<<#7#7#F#FF88==?dll&:&:&E&EE88==?dll&:&:&A&AA??"rN   c                ~   > [        U [        5      (       d'  U R                  R                  5       (       d  T" U 5      $ gr  )rT   ri  rv  r  )ry  r  s    rO   is_belong_to_optimizer2Program.state_dict.<locals>.is_belong_to_optimizerl  s0    sI..#((2J2J2L2L%c**rN   c                   > TS:X  a  T" U 5      $ TS:X  a  T" U 5      $ TS:X  a  T" U 5      =(       d    T" U 5      $ [        ST S35      e)Nr  optr8  z>`mode` string should be 'param', 'opt' or 'all', but received r  )r]   )ry  r  r  modes    rO   	condition%Program.state_dict.<locals>.conditionq  s`    w#C((-c22#C(G,B3,GG TUYTZZ[\ rN   r_  z+' in the scope. Make sure it is initialized)ra  r]  rT   r   rb  rV   r   r\   filterru  rw  r   r]   rc  )r   r  r  r]  r  r  rI  ry  rd  r  r  r  s    `       @@@rO   rI  Program.state_dict%  s   X 	+Zt{{%C%CVW[\aWbVccde  = NE$$$@dAN 	.	#	

	 )^^%56
C~~chh/H -chhZ7bc  $,#6#6#8Jxx   rN   c                   [        U[        5      (       d  [        S[        U5       S35      eU R	                  5        Vs0 s H  o3R
                  U_M     nnSU;   a  SOSnUR                  5        H\  u  pgU(       a  US:X  a  M  XaS   ;   a  US   U   nXd;   a   XF   R                  Xr5        M?  [        R                  " SU S	U S
35        M^     gs  snf ! [         a1  n[        R                  " SU S3[        U5      -   5         SnAM  SnAf[         a1  n[        R                  " SU S3[        U5      -   5         SnAM  SnAff = f)a!  
Set parameters and persistable buffers in state_dict to program.
An exception will throw if shape or dtype of the parameters is not match.

.. note::
    This function MUST called after run start_up_program

Args:
    state_dict(dict): the dict store parameters and persistable buffers.
        The key is the name of the parameter or the name of the buffer.
        The value is the tensor of this variable in the given scope.
    scope(Scope, optional) : If scope is None, state_dict will be set to global scope
        obtained through 'paddle.static.global_scope()'. Otherwise, value will be set to scope.
        Default: None

Returns:
    None

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> x = static.data(name="x", shape=[10, 10], dtype='float32')
        >>> y = static.nn.fc(x, 10)
        >>> z = static.nn.fc(y, 10)

        >>> place = paddle.CPUPlace()
        >>> exe = static.Executor(place)
        >>> exe.run(static.default_startup_program())
        >>> prog = static.default_main_program()

        >>> path = "./temp/model.pdparams"
        >>> paddle.save(prog.state_dict(), path)
        >>> state_dict_load = paddle.load(path)
        >>> prog.set_state_dict(state_dict_load)
z2Type of `state_dict` should be dict, but received r  zStructuredToParameterName@@TFzSkip loading for 'z'. Nz'. Because 'z' not in the program.)rT   rU   rV   r   ru  r   rW   rv  r]   r  r  r\   )	r   rI  r  ry  	vars_dictr  r   r`   errs	            rO   set_state_dictProgram.set_state_dict  sO   T *d++DT*EUDVVWX  /3nn.>?.>sXXs].>	?1Z?DU 	 &++-KD88&CDD%&CDTJD MO--e; (l4&@UV .	 @ " MMM$6tfC"@3s8"KLL  MMM$6tfC"@3s8"KLLMs*    CC
E"&DE&EE)__op_role_varr  r  r  r  r  r  r  r  r  r  r  r  r  r  rp  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rv  )r   r  r  rK   )rp  rE  )r8  N)2r   r   r   r   r  r   r  r}  r  r  r  r  r  r   r  r  r  r   r  r  r  r  r  r
  r  r  r   r>  r  rF  r  rF  r  r  r  rn  rS  r  rZ  r]  r,  rr  r  r  r  ru  r  rI  r  r   rM   rN   rO   rE  rE  V  s   ,\B%HaF#%J&< " "  __" " " " #* #* #* #*@ #"* #"*H
((T?B$\| #1 #13"jX5nm^ ' 'R    $ $L & &4  4"632$.#A# H(I*&-P8&68&PcJCrN   rE  c                  t    \ rS rSrSr\R                  R                  R                  4S jr	S r
SS jr\
rSrg)	ri  i  ay  
Parameter is derived from Variable. A parameter is a persistable
Variable, and will be updated by optimizers after each iteration.
The training of a neural network is essentially the updating of
its parameters.

Relative to a general Variable, a Parameter has several its own
member variables:

Args:
    trainable(bool): True if the parameter need to be updated after
        iterations.
    optimize_attr(map): Parameter attributes related with optimizing.
        Currently, it only contains 'learning_rate'.
        Default: {'learning_rate': 1.0}
    regularizer(WeightDecayRegularizer): The Regularizer which will
        be applied on the parameter. Default: None
    do_model_average(bool): True if the model average strategy will
        be applied on this parameter.
    need_clip (bool): Whether the parameter gradient need to be clipped
        in optimizer. Default is True.
c                   Uc  [        S5      eUc  [        S5      eU H   nUS:  d  M  [        S[        U5       35      e   [        R                  " U U4SUUUS.UD6  UR	                  SS5      U l        U R
                  (       + U l        UR	                  SS	S
05      U l        UR	                  SS 5      U l        UR	                  SS 5      U l	        UR	                  SS5      U l
        SU l        SU l        g )N)The shape of Parameter should not be None)The dtype of Parameter should not be Noner   KEach dimension of shape for Parameter must be greater than 0, but received T)r.  r-  r  r   r  r)  learning_rate      ?r*  r  r  F)r]   rd   rN  r   r   r  r  r)  r*  r  r  r  r  )r   rn  r-  r  r   r   eachs          rO   r   Parameter.__init__  s    =HII=HIIDax abfglbmano   		
 	
 	
  K6!%/#ZZ/39OP!::mT: &

+=t DK6# rN   c                "    U R                  5       $ rK   r  r  s    rO   r   Parameter.__str__  r  rN   c                   [        U[        5      (       a  [        U[        5      (       d   eU(       a6  [        R                  XS5      nSnU H  nX5 S[	        X5       S3-  nM     U$ [        R                  XS5      nU$ )a  
To debug string.

Args:
    throw_on_error(bool): raise exception when self is not initialized
        when throw_on_error is True
    with_details(bool): more details about variables and parameters
        (e.g. trainable, optimize_attr, ...) will be printed when with_details is True

Returns(str): The debug string.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> paddle.enable_static()
        >>> prog = paddle.static.default_main_program()
        >>> rlt = paddle.static.data("fake_data", shape=[-1,1,1], dtype='float32')
        >>> debug_str = prog.to_string(throw_on_error=True, with_details=False)
        >>> print(debug_str)
T)r  r)  r*  r  r  r  r   F)rT   r  rN  r  r  )r   r$  r  r  r  rU  s         rO   r  Parameter.to_string  s    , .$//J$5
 5
 	
 
 ((tDGO -	[74+C*DBGG -  ((uEGrN   )r  r  r  r  r)  r*  r  r  Nr  )r   r   r   r   r  r   r  r  r+  r   r   r  r  r   rM   rN   rO   ri  ri    s4    8 \\!!..*!X(&P HrN   ri  c                     ^  \ rS rSrSr\S 5       rU 4S jr  S   SU 4S jjjr\	S 5       r
S r\S 5       r\S	 5       r\R                  S
 5       rS rU 4S jrS rS rU 4S jr\rSrU =r$ )rh  iB  a  
EagerParamBase is derived from Tensor( Which is the concept in Eager-Dygraph Mode).
A EagerParamBase is a persistable Tensor, and will be updated by optimizers
after each iteration.
The training of a neural network is essentially the updating of
its EagerParamBase.

Relative to a general Tensor, a EagerParamBase has several its own
member variables:

Args:
    trainable(bool): True if the EagerParamBase need to be updated after
        iterations.
    optimize_attr(map): EagerParamBase attributes related with optimizing.
        Currently, it only contains 'learning_rate'.
        Default: {'learning_rate': 1.0}
    regularizer(WeightDecayRegularizer): The Regularizer which will
        be applied on the EagerParamBase. Default: None
    do_model_average(bool): True if the model average strategy will
        be applied on this EagerParamBase.
    need_clip (bool): Whether the parameter gradient need to be clipped
        in optimizer. Default is True.
c                    [        U5      S:  a  [        US   [        5      (       d  SU;   a  U R                  " U0 UD6  g U R                  " U0 UD6  g )Nr   r-  )r[   rT   rd   __init_by_shape____init_by_tensor__)r   r   r   s      rO   r   EagerParamBase.__init__[  sJ    IMja$77Gv<M""D3F3##T4V4rN   c                  > Uc  [        S5      eUc  [        S5      eU H   nUS:  d  M  [        S[        U5       35      e   Ub  [        U5      nO$[        R                  R
                  R                  nUR                  S[        R                  " S5      5      n[        U[        R                  R                  5      (       a  UR                  5       n[        TU ]=  UU(       a  [        U5      O/ U[        R                  R
                  R                   S5        U R#                  5         UR                  SS5      nU(       + U l        UR                  S	S
S05      U l        UR                  SS 5      U l        UR                  SS 5      U l        UR                  SS5      U l        UR                  SS5      U l        S U l        S U l        g )Nr  r  r   r  r   _eager_param_baseTr  r)  r  r  r*  r  r  r  F)r]   rd   r  r   r  r  r  r   r   generaterT   r)  r*  r  r   r   r+  r,  r  r)  r*  r  r  r  
_init_func_init_op_creator)r   r-  r  r   r  r   r  r   s          rO   r   EagerParamBase.__init_by_shape__b  s   =HII=HIIDax abfglbmano   )%0ELL((--Ezz&+"6"67J"KLeTZZ..//KKME DKbLL  --	
 	JJ{D1	!*]#ZZ/39OP!::mT: &

+=t DK6$jj)95A $rN   c                  > Uc  [         R                  " / 5      nUR                  nUR                  nU H   nUS:  d  M  [	        S[        U5       35      e   [        U5      nUR                  S[        R                  " S5      5      n[        TU ]-  UU(       a  [        U5      O/ U[        R                  R                  R                  S5        U R!                  5         SU l        U(       + U l        UR                  SSS05      U l        UR                  S	S 5      U l        UR                  S
S 5      U l        UR                  SS5      U l        UR                  SS5      U l        S U l        S U l        U R5                  U5        g )Nr   r  r   r  Tr)  r  r  r*  r  r  r  F)rk   	to_tensorr-  r  r]   rd   r  r   r   r  r   r   r   r  r  r+  r,  	_is_paramr  r)  r*  r  r  r  r  r  	_set_impl)	r   datarequires_gradr   r-  r  r  r   r   s	           rO   r  !EagerParamBase.__init_by_tensor__  sX    <##B'D



Dax abfglbmano   &e,zz&+"6"67J"KL DKbLL  --	
 	!..#ZZ/39OP!::mT: &

+=t DK6$jj)95A $trN   c                    U " UR                   UR                  40 UD6nUR                  SS 5      nUR                  SS 5      nUnUb5  Ub2  [        R                  R                  XUS9nUR                  S-   Ul        UR                  U5        U$ )Nprocess_mesh
placements)r  r  z.dist)r-  r  r   r   r)  r*  r   r  )r^  tensorr   r  meshr  
src_tensors          rO   from_tensorEagerParamBase.from_tensor  s     FLL&,,9&9 zz.$/ZZd3


 6**j + J  w.EJ 	
#rN   c                    Xl         g rK   r  )r   objs     rO   set_init_funcEagerParamBase.set_init_func  s    rN   c                ^    U R                   c   S5       eU R                  U S 5        S U l         g )Nz8Required self._init_func is not None, but received None.r  r  s    rO   
initializeEagerParamBase.initialize  s3    * 	
F	
* 	d#rN   c                $    U R                   (       + $ rK   )r  r  s    rO   r  EagerParamBase.trainable  s    %%%%rN   c                t    [        U[        5      (       a  U(       + U l        g [        S[	        U5       35      e)Nz4The type of trainable MUST be bool, but the type is )rT   r  r  r]   r   )r   r  s     rO   r  r    s5    i&&%.DFtIFWX rN   c                N    U R                   c   S5       eU R                  X5        g)zI
Call init_op_creator function to create initializer operation in block.
Nz>Required self._init_op_creator is not None, but received None.)r  )r   rn  s     rO   _create_init_opEagerParamBase._create_init_op  s0     $$0 	
L	
0 	d*rN   c                &   > S[         TU ]  5        3$ )a$  
Convert a EagerParamBase object to a readable string.

Returns(str): A readable string.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> linear = paddle.nn.Linear(3, 3)
        >>> print(linear.weight)
        >>> # doctest: +SKIP('it will be different')
        Parameter containing:
        Tensor(shape=[3, 3], dtype=float32, place=Place(cpu), stop_gradient=False,
        [[ 0.48948765,  0.05829060, -0.25524026],
         [-0.70368278,  0.52986908, -0.68742192],
         [-0.54217887,  0.48439729,  0.34082305]])
zParameter containing:
)r   r   )r   r   s    rO   r   EagerParamBase.__str__  s    & )):(;<<rN   c                X   [         R                  " U R                  U5      nU R                  [        R
                  " S5      -   US'   [        U R                  U R                  40 UD6nX1[        U 5      '   UR                  U S5        U R                  Ul        U R                  Ul        U$ )a  
Deep copy parameter, it will always performs Tensor copy.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import copy
        >>> linear = paddle.nn.Linear(1, 3)
        >>> linear_copy = copy.deepcopy(linear)

        >>> print(linear.weight)
        >>> # doctest: +SKIP('it will be different')
        Parameter containing:
        Tensor(shape=[1, 3], dtype=float32, place=Place(cpu), stop_gradient=False,
            [[-0.30929261, -0.90929240, -1.07851017]])

        >>> # doctest: -SKIP
        >>> print(linear_copy.weight)
        >>> # doctest: +SKIP('it will be different')
        Parameter containing:
        Tensor(shape=[1, 3], dtype=float32, place=Place(cpu), stop_gradient=False,
            [[-0.30929261, -0.90929240, -1.07851017]])

	_deepcopyr   T)rL  r  r   r   r   r  rh  r-  r  r  copy_r  r  )r   memostate	new_params       rO   __deepcopy__EagerParamBase.__deepcopy__  s    4 dmmT2		K$8$8$EEf"4::tzzCUC	"RXd##	%)%:%:	"rN   c                    [         R                  " U R                  5      n[        U R                  U R
                  40 UD6n[        R                  R                  XX5        U$ rK   )	rL  r  r   rh  r-  r  r   r)  tensor_copy)r   deviceblockingr  r  s        rO   _copy_toEagerParamBase._copy_to(  sG    dmm,"4::tzzCUC	

tArN   c                   > US:X  a7  [        U S5      (       a&  U R                  b  [        SU R                   S35      e[        TU ]  X5        g )NcolorzParameter 'zm' already has a 'color' attribute (used for distributed sharding parallel grouping) and cannot be reassigned.)r  r  AttributeErrorr   r   r   )r   r   r`   r   s      rO   r   EagerParamBase.__setattr__.  sR    GOg&&

& dii[ ), -  	D(rN   )	r  r  r  r  r  r  r)  r*  r  r  )r  zpaddle.Tensor | Noner  r  )r   r   r   r   r  dygraph_onlyr   r  r  rd  r  r  r  r  r  r  r  r   r  r  r   r  r   r   r  s   @rO   rh  rh  B  s    0 5 5-%b &*"&"& & &P  (   & &  +=*!F
) HrN   rh  c                     [         $ )a  
Get default/global startup program.

The :code:`paddle.nn` function will append the initialization operators into startup program.
The :code:`startup_program` will initialize the parameters by the OPs.

This method will return the default or the current startup program. Users can use
:ref:`api_paddle_base_framework_program_guard`  to switch :ref:`api_paddle_base_framework_Program` .

Returns:
    Program: current default startup program.

Returns type:

Examples:
    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()
        >>> x = paddle.static.data(name="x", shape=[-1, 784], dtype='float32')
        >>> out = paddle.static.nn.fc(name="fc", x=x, size=10, activation="relu")
        >>> print("main program is: {}".format(paddle.static.default_main_program()))
        >>> print("start up program is: {}".format(paddle.static.default_startup_program()))
_startup_program_rM   rN   rO   default_startup_programr  C  s
    4 rN   c                     [         $ )a  
This API can be used to get ``default main program`` which store the
descriptions of Ops and tensors.

For example ``z = paddle.add(x, y)`` will create a new ``add``
Op and a new ``z`` tensor, and they will be recorded in ``default main program`` .

The ``default main program`` is the default value for ``Program`` parameter in
a lot of APIs. For example, the :code:`Executor.run()` will execute the
:code:`default_main_program` when the program is not specified.

If you want to switch the ``default main program``, you can use :ref:`api_paddle_base_framework_program_guard` .

Returns:
    Program: A ``Program`` which holding the descriptions of OPs and tensors in the network.

Examples:
    ..  code-block:: python

        >>> import paddle

        >>> paddle.enable_static()
        >>> # Sample Network:
        >>> x = paddle.static.data(name='x', shape=[100, 100], dtype='float32')
        >>> y = paddle.static.data(name='y', shape=[100, 100], dtype='float32')
        >>> out = paddle.add(x, y)

        >>> # print the number of blocks in the program, 1 in this case
        >>> print(paddle.static.default_main_program().num_blocks)
        1
        >>> # print the default_main_program
        >>> print(paddle.static.default_main_program())
_main_program_rM   rN   rO   r  r  `  s    D rN   c                    [         nU q U$ )z
Switch the main program to a new program.

Args:
    program(Program): The new main program

Returns:
    Program: The previous main program
r  ro  prev_programs     rO   switch_main_programr    s     "LNrN   c                    [         nU q U$ )z
Switch the startup program to a new program
Args:
    program(Program): The new startup program

Returns:
    Program: The previous startup program
r  r  s     rO   switch_startup_programr    s     %LrN   c              #    #    SSK Jn  U" U S[        S5        [        U 5      n Ub!  U" US[        S5        SUl        [        U5      n Sv   [        U 5        Ub  [        U5        gg! [        U 5        Ub  [        U5        f f = f7f)a  
:api_attr: Static Graph

Change the global main program and startup program with ``with`` statement.
Layer functions in the Python ``with`` block will append operators and
Tensors to the new main programs.

Args:
    main_program(Program): New main program inside ``with`` statement.
    startup_program(Program, optional): New startup program inside ``with``
        statement. :code:`None` means not changing startup program,
        default_startup_program is still used.
        Default: None.

Examples:
    .. code-block:: python
        :name: code-example-1

        >>> import paddle

        >>> paddle.enable_static()
        >>> main_program = paddle.static.Program()
        >>> startup_program = paddle.static.Program()
        >>> with paddle.static.program_guard(main_program, startup_program):
        ...     data = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32')
        ...     hidden = paddle.static.nn.fc(x=data, size=10, activation='relu')

Notes: The temporary :code:`Program` can be used if the user does not need
to construct either of startup program or main program.

Examples:
    .. code-block:: python
        :name: code-example-2

        >>> import paddle

        >>> paddle.enable_static()
        >>> main_program = paddle.static.Program()
        >>> # does not care about startup program. Just pass a temporary value.
        >>> with paddle.static.program_guard(main_program, paddle.static.Program()):
        ...     data = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32')

r   )
check_typer~  zpaddle.static.program_guardNr  T)data_feederr  rE  r  r  r  )r~  r  r  s      rO   program_guardr    s     ^ (ng/L '|4L")		
 15-0A4L)&"?3 ' 	L)&"?3 's   ABA' B'BBc                    Uc
  [        5       n[        U [        5      (       d   e[        U[        5      (       d   eUR	                  5       R                  U 5      $ )z
Get a variable by name from the global block of a program.

Args:
    name(str): name of the variable
    program(Program|None): program object.
    If None, default_global_program() will be used.

Returns:
    Variable
)r  rT   r\   rE  r  ry  )r   ro  s     rO   _get_varr    sQ     &(dC    gw''''!%%d++rN   c               #     #    SSK Jn   SSKJn  U" 5       (       a  [	        U " 5       S9   S v   S S S 5        g S v   g ! , (       d  f       g = f7f)Nr   )Tracerr4  )tracer)dygraphr  r6  r5  _dygraph_guard)r  r5  s     rO   dygraph_guard_if_declarativer    s6     /68, -, 	 -,s   'A<A
A
Ac              #     #    [         R                  nU [         l         S v   U[         l        g ! U[         l        f = f7frK   r   )r  
tmp_tracers     rO   r  r     s0     ,,J"(J1&0
#j
#s   ?/ ?<?c              #     #    [         nU q [        U 5         S v   Uq [        [         5        g ! Uq [        [         5        f = f7frK   rn  )rk  	tmp_places     rO   _dygraph_place_guardr     sD      (I#&u-D"+*+BC #,*+BCs   A- AA  Ac                    [         nU q U$ rK   )r  )r  
pre_devices     rO   switch_devicer  %   s     JOrN   c              #  T  #    SnU (       a*  SU ;   a$  U R                  S5      u  pU S:X  a  [        S5      eU S;  a'  U [        R                  " 5       ;  a  [        SU  35      eU(       a  SR	                  X/5      n [        U 5      n Sv   [        U5        g! [        U5        f = f7f)ab  

Note:
    The API only supports static graph mode.

A context manager that specifies the device on which the OP will be placed.

Args:
    device(str|None): Specify the device to use in the context. It should be ``cpu``,
        ``gpu`` or ``gpu:x``, where ``x`` is the index of the GPUs.
        When it is set to 'cpu' or 'gpu', all OPs created in the context will be
        placed on CPUPlace or CUDAPlace. When 'gpu' is set and the program runs on
        single-card, the device index will be the same as the device on which the
        executor runs. Default: None, OPs in this context will be automatically
        assigned devices.

Examples:

    .. code-block:: python

        >>> # doctest: +REQUIRES(env:GPU)
        >>> import paddle
        >>> paddle.device.set_device('gpu')
        >>> paddle.enable_static()
        >>> support_gpu = paddle.is_compiled_with_cuda()
        >>> place = paddle.CPUPlace()
        >>> if support_gpu:
        ...     place = paddle.CUDAPlace(0) # type: ignore

        >>> # if GPU is supported, the three OPs below will be automatically assigned to CUDAPlace(0)
        >>> data1 = paddle.full(shape=[1, 3, 8, 8], fill_value=0.5, dtype='float32')
        >>> data2 = paddle.full(shape=[1, 3, 64], fill_value=0.5, dtype='float32')
        >>> shape = paddle.shape(data2)

        >>> with paddle.static.device_guard("cpu"):
        ...     # Ops created here will be placed on CPUPlace
        ...     shape = paddle.slice(shape, axes=[0], starts=[0], ends=[4])
        >>> with paddle.static.device_guard('gpu'):
        ...     # if GPU is supported, OPs created here will be placed on CUDAPlace(0), otherwise on CPUPlace
        ...     out = paddle.reshape(data1, shape=shape)

        >>> exe = paddle.static.Executor(place)
        >>> exe.run(paddle.static.default_startup_program())
        >>> result = exe.run(fetch_list=[out])
N:cpuz!Should not set device id for cpu.)r  gpudcuxpur  NzThe Attr(device) should be 'cpu', 'xpu', 'dcu', 'gpu' or custom device, and it can also be empty string or None when there is no need to specify device. But received )r  r]   r   r^  r   r  )r  r   r  s      rO   device_guardr  ,   s     ` E#-S)U?@AA<<$99;;EEKHN
 	
 6/*v&J"j!j!s   BB(B B(B%%B(c                   U c  U $ [        U [        R                  5      (       a  U $ [        U [        5      (       d  [	        SU  35      eU R                  5       n U R                  S5      (       a  U R                  SS5      n U S:X  a  [        R                  " 5       $ U S:X  a  [        R                  " 5       $ [        R                  " SU 5      nU S:X  d  U S:X  d  U S:X  d  U(       a  [        R                  " 5       (       d  [	        S	UR                  5        S
35      eU S:X  a  [        R                  " 5       $ U S:X  d  U S:X  a  [        R                  " S5      $ U R                  SS5      nUS   n[!        U5      n[        R                  " U5      $ [        R                  " SU 5      nU(       d  U S:X  d  U S:X  a  [        R"                  " 5       (       d  [	        S	UR                  5        S35      eU S:X  a  [        R$                  " S5      $ U S:X  a  [        R&                  " 5       $ U R                  SS5      nUS   n[!        U5      n[        R$                  " U5      $ [        R                  " SU 5      nU(       ao  [        R(                  " 5       (       d  [	        S	UR                  5        S35      eU R                  SS5      nUS   n[!        U5      n[        R*                  " U5      $ U R                  SS5      nUS   nU[        R,                  " 5       ;   aL  [/        U5      S:X  a  [        R0                  " US5      $ US   n[!        U5      n[        R0                  " Xc5      $ [	        SU  S35      e)z5
Convert given place to standard paddle Place object
z>place only support string which is 'Place' and so on, but got cudar  r  r  zgpu:\d+
gpu_pinnedr  zThe device should not be z., since PaddlePaddle is not compiled with CUDAr   r  r   zxpu:\d+r  
xpu_pinnedz-, since PaddlePaddle is not compiled with XPUzipu:\d+z-, since PaddlePaddle is not compiled with IPUzwPaddle supports CPUPlace, CUDAPlace, CUDAPinnedPlace, XPUPlace, XPUPinnedPlace, IPUPlace and CustomPlace, but received r  )rT   r   rT  r\   r]   r   rY   replacerY  r  r  rU  r  r  rW  r  r  rZ  r\  r  r   IPUPlacer^  r[   r`  )rk  available_gpu_placeplace_info_list	device_idavailable_xpu_placeavailable_ipu_placer  s          rO   _get_paddle_placer  r   sF    }%$$eS!!LUGT
 	
 KKMEfe,~}}zz| ((:u5E>E>))+++,?,E,E,G+H I) )  L ''))e^u~>>!$$#kk#q1O'*III>>),, ((:u5eun0E((**+,?,E,E,G+H I( (  E>==##l"&&((#kk#q1O'*III==++ ((:u5((**+,?,E,E,G+H I( (   ++c1-#A&		N	}}Y''kk#q)O!!$Kd55771$##K33'*III##K;;
 B  CH  BI  IJ  	K rN   c                    [        U [        [        45      (       d  [        S5      e/ nU  H  n[	        U5      nUR                  U5        M!     U$ )Nzplaces must to be List or Tuple)rT   rd   re   rV   r  r   )placesretr  s      rO   _get_paddle_place_listr     sJ    ftUm,,9::
Ca 

1  JrN   c                l   U [         R                  :X  a  gU [         R                  :X  a  gU [         R                  :X  a  gU [         R                  :X  a  gU [
        R                  R                  R                  :X  a  gU [
        R                  R                  R                  :X  a  g[        SU  S35      e)	Nfp16bf16fp32fp64r  r  z)got unsupported data type for promotion: r  )rk   r  r  r  r  r   r  r  r  r  rV   )in_dtypes    rO   dtype_to_strr     s    6>>!	V__	$	V^^	#	V^^	#	T\\))33	3	T\\))44	4CH:QOPPrN   c                   U R                  S5      nUR                  S-   [        U5      -   nUR                  UUSUR                  S9nU R                  S5      (       d-  [        [        R                  R                  R                  5      OU R                  S5      nUR                  USSU0SU0UR                  UR                  UUS	.S
9  U R                  R                  UR                  UR                  5        g )Nr  z.cast_F)r   r  r.  r  r  castr   r  )r  	out_dtyper  r  r  )rT  r   r  r  r  r  r  r   r  r  r  rQ  r  rv  r\  )	r  rn  r  r  r   r  	cast_nameout_varr  s	            rO   add_cast_for_type_promotionr#     s    $I(<	+BBI,,	  G {{9%% 	D++22::;WWY 
 
!!X   "	
 "  GG(--6rN   c                   US;  a  gU R                   S:w  a  gU R                  R                  U R                  S5      S   5      R                  nU R                  R                  U R                  S5      S   5      R                  nU[
        R                  :X  a%  U[
        R                  [
        R                  4;   a  gg)N)GPUXPUFr   r   r   r    T)	r   rn  rq  r;  r  rk   r  r  r  )r  r  input_x_dtypeinput_y_dtypes       rO   can_skip_promoter)  	!  s    ^#	ww##HH00#q1ABHHMHH00#q1ABHHM&&..&//::rN   c           	        S n[         R                  " 5       (       a*  [        [        5       [         R                  5      (       a  SnOC[         R
                  " 5       (       a)  [        [        5       [         R                  5      (       a  SnU nU c
  [        5       n [        U [        5      (       d  U$ U R                  5       nUR                  5       nU R                   GH  nUR                  nSnU[        U5      :  d  M#  Xg   nS n	/ n
/ n[        R                  UR                   S 5      nUb  [#        X5      (       a  US-  nMU  [%        [        UR&                  5      5       Hl  nUR(                  U   U;   d  M  UR&                  U   nU
R+                  UR,                  R/                  U5      R0                  5        UR+                  U5        Mn     [        U
5      S:X  a  [         R2                  " UR                   /U
Q76 (       ak  [         R4                  " UR                   /U
Q76 nU HD  nUR,                  R/                  U5      n	U	R0                  U:w  d  M0  [7        UUUU	U5        US-  nMF     US-  nU[        U5      :  a  GM  GM     U $ )Nr%  r&  r   r   r   )r   rU  rT   rg  rW  rZ  r\  r  rE  r  r  r  r  r[   #SUPPORT_PROMOTION_OPS_AND_INPUTNAMEr   r   r)  r  rf  r:  r   rn  r  r  need_type_promotion_old_irget_promote_dtype_old_irr#  )ro  r  org_programr  
all_paramsrn  r  r  r  r  
all_dtypesall_input_name_need_castneed_transed_var_names	input_idxinput_arg_namecommon_dtypeinput_name_need_casts                    rO   process_type_promotionr7  !  sT   F!!##
!4>>) ) 		"	"	$	$!4==* * K&(gw'''')L,,.JiiCHnBHJ')$%H%L%L&" &-1A"1M1Mq #3r'9'9#:;	>>),0FF%'%7%7	%BN%%//?EE -33NC < :!#(G(G)$) )  $<<GG (  -E(!xx667KLH~~53!$( q -E 1HCU CHnn  \ NrN   c              #    ^#    S nS nU4S jmU R                  5       n[        R                  R                  5       (       a"  U" U5      (       a  US:w  d   S5       eU" U5         S v   [        R                  R                  5       (       a  U" U5      (       a  / SQnT" XAU5        g g g ! [        R                  R                  5       (       a  U" U5      (       a  / SQnT" XAU5        f f f = f7f)Nc                :    [        S U R                   5       5      $ )Nc              3  <   #    U  H  oR                   S Lv   M     g 7frK   )r  )r3  r  s     rO   r6  ?auto_complete_op_role.<locals>.is_dist_block.<locals>.<genexpr>a!  s     @i<<t+is   )r   r  )rn  s    rO   is_dist_block,auto_complete_op_role.<locals>.is_dist_block`!  s    @eii@@@rN   c                    U R                    H0  nUR                  S:X  d  M  [        SUR                  5        S35      e   g )Nr   z?All ops' op_role should be set before the completion. However, z's op_role is -1)r  r  r]   r   )rn  r  s     rO   validate_op_roles0auto_complete_op_role.<locals>.validate_op_rolesc!  sA    ))BzzR UVXV]V]V_U``pq  rN   c                  > U R                    H|  nUR                  5       U;  a  UO,[        [        R                  R
                  R                  5      nUR                  S:X  a  XCl        UR                  5        H  nT" XQU5        M     M~     g r  )	r  r   r  r   r  r  r  r  r  )rn  r  always_forward_opsr  set_op_role	sub_blockset_op_roless         rO   rE  +auto_complete_op_role.<locals>.set_op_rolesj!  st    ))B 779$66 88??GGH 
 zzR(
YY[	Y1CD ) rN   r   z)Can't set op_role to -1 for new added ops)z
pd_op.datazbuiltin.parameterzcf.stack_createzcf.tuple_push)r  rk   	frameworkr   )ro  r  r<  r?  rn  rB  rE  s         @rO   auto_complete_op_rolerH  ^!  s     AE"   "E##%%-*>*>"}III}% 
=''))mE.B.B" );< /C)6''))mE.B.B" );< /C)s    A"C.&B* *A C.*AC++C.c              #    #    [         R                  R                  5       (       a+  [        R                  " 5       n[        R
                  " U 5         S v   [         R                  R                  5       (       a  [        R
                  " W5        g g ! [         R                  R                  5       (       a  [        R
                  " W5        f f = f7frK   )rk   rG  r   r   get_op_rolerC  )r  original_op_ropes     rO   pir_op_role_guardrL  !  s     ##%%??, .''))OO,- *6''))OO,- *   ACB ;C<CCc              #    #    [         R                  R                  5       (       a+  [        R                  " 5       n[        R
                  " U 5         S v   [         R                  R                  5       (       a  [        R
                  " W5        g g ! [         R                  R                  5       (       a  [        R
                  " W5        f f = f7frK   )rk   rG  r   r   get_chunk_idset_chunk_id)chunk_idoriginal_chunk_ids     rO   pir_chunk_id_guardrS  !  s     ##%%,,."0''))./ *6''))./ *rM  c              #  D  #    [         R                  R                  5       (       aE  [        R                  " 5       (       a+  [
        R                  " 5       n[
        R                  " U 5         S v   [         R                  R                  5       (       a2  [        R                  " 5       (       a  [
        R                  " W5        g g g ! [         R                  R                  5       (       a2  [        R                  " 5       (       a  [
        R                  " W5        f f f = f7frK   )rk   rG  r   r   r  r   get_comp_op_nameset_comp_op_name)op_nameoriginal_comp_op_names     rO   pir_op_name_guardrY  !  s     ##%%$*C*C*E*E # 4 4 6W%8''))d.G.G.I.I  !67 /J)6''))d.G.G.I.I  !67 /J)s    A)D ,C 0AD ADD c              #    #    [        U [        5      (       d   S5       e[        R                  R                  R
                  R                  U 5         S v   [        R                  R                  R
                  R                  5         g ! [        R                  R                  R
                  R                  5         f = f7f)Nzvlog level is not an int)rT   r  rk   baser   r)  %_start_capture_backward_vlog_subgraph$_stop_capture_backward_vlog_subgraph)levels    rO   backward_vlog_guardr_  !  s}     eS!!=#==!
KK@@GFCCECCEs   ACB
 3C
4B>>Cc              #  2  #    [        U [        [        45      (       d!  [        S[	        U 5      R
                   35      e[        R                  R                  R                  U 5         S v   [        U [        5      (       a*  [        R                  R                  R                  S5        g [        U [        5      (       a>  [        R                  R                  R                  [        R                  U S5      5        g g ! [        U [        5      (       a*  [        R                  R                  R                  S5        f [        U [        5      (       a>  [        R                  R                  R                  [        R                  U S5      5        f f = f7f)Nz4The input of vlog_guard must be int or dict but got r   )rT   r  rU   rV   r   r   rk   r[  r   set_vlog_levelfromkeys)module_levelss    rO   
vlog_guardrd  !  s    mc4[11B4CVC_C_B`a
 	
 KK##M2M mS))KK++A.t,,KK++DMM-,KL - mS))KK++A.t,,KK++DMM-,KL -s    A&F)D  -BF BFF)r^   dict[str, bool | str | float]r   None)r^   zstr | Sequence[str]r   re  )r   r  )r   r   )r   r  r   r  r   Generator[None, None, None])..)r   r   r   r  r   r  r   r   )r   paddle.nn.Layerr   r  r   r  r   rh  rK   )r  r\   r  
str | Noner   rf  r   )r   rf  )r  Sequence[int] | Noner   zlist[core.CUDAPlace])r  rj  r   zlist[core.XPUPlace])rb  
int | Noner   zlist[core.CPUPlace])rb  rk  r   zlist[core.CUDAPinnedPlace])rb  rk  r   zlist[core.XPUPinnedPlace])ra   ri  r   rg  )r  znp.dtype | strr   zcore.VarDesc.VarType)r  z5np.dtype | str | core.VarDesc.VarType | core.DataTyper   z$core.VarDesc.VarType | core.DataTyper  )r   rE  )ro  rE  r   rE  )r~  rE  r  zProgram | Noner   rg  )r  ri  r   rg  )r  int - 1r   rg  )rQ  rl  r   rg  )rW  r\   r   rg  )r^  r  r   rg  )rc  z
int | dictr   rg  )
__future__r   r  rL  rM  rs  r~   r  rm  ru  r  	threadingr  r  collections.abcr   
contextlibr   typesr   r   typingr   r	   r
   r   r  r  typing_extensionsr   rk   r  r   r   r   	libpaddler   r#  r   r   variable_indexr   r   wrapped_decoratorr   r   r   r   r   r   r  r   __all__kEmptyVarNameEMPTY_VAR_NAMEkTempVarNameTEMP_VAR_NAMEkGradVarSuffixr  kZeroVarSuffixZERO_VAR_SUFFIXkControlDepVarNamer  globalsrL   r+  
stride_opsrP   rb   ri   ro   localrq   r}   r   rS  r  r  r>  r  r  r  r
  r  r  r  FLOAT16r  UINT16r  BFLOAT16FLOAT32r  r  r  r  r	  r  r
  r  r  r  FLOAT8_E4M3FNr  FLOAT8_E5M2r  r  r   r   r   r   r   r   r   r   r   r  r  r   r   r"  r*  r0  r8  r<  r?  rE  rO  dygraph_not_supportr  static_onlyr  r  rQ  re  rg  rl  ro  ry  rX  r]  ra  rZ  r  r   rU  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r&  r+  r0  r:  rA  rH  rJ  rX  r   rZ  rf  rN  r  r  r  r  r  r  r{  r  r  r  r  r  rE  ri  r)  r*  rh  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r#  r)  r7  rH  rL  rS  rY  r_  rd  rM   rN   rO   <module>r     sW   #     	 	  
     $ % * = =  '     = L
I
37
##%!!#%%'%%'002 ''Sz''S#J'' Sz'' S#J	''
 Sz'' S#J'' Sz'' S#J'' S#J''  #s'' Sz'' S#J'' c3Z'' 3*'' c3Z''  #s!''" #s#''$ 3*%''& S#J'''( c3Z)''* C:+'', 3*-''. C:/''0 c
1''2 c3Z3''4 c
5''6 c3Z7''8 Sz9'': S#J;''< Sz=''> S#J?''@ SzA''B S#JC''D 3*E''F SzsD\,M'' #R
,<+\ 1 1)"	 )"X   
    &+ #~~ ~ ~	
 ~ ~ ~ ~ fb\N 62, FB<. fb\N vrl^ vrl^ 62,  lE"#!" lE"##$ 5!"$e,-'( %() %()!5)*!5)* %()3 : m-.12]X'(./|m
 MM4<<'',,dll**//OOT\\))..t||++00dll**//dll**//MM4<<'',,NNDLL((..NNDLL((..NNDLL((..NNDLL((..,,66--88DLL00;;$,,..77 &3B>2$O8
!< H   ! !  "$3*3*3* 3* 3*l 
HK#'#03#BE## 
#
 
?B'*9< 

:zod	
"		
"$
"&
"" %%:; n-]+$%:;  !23'0#f&<
.'"4( ( . (" (,/=$/=/=d$<N,F  $ 3 3 3H  $ 2 2 2F 0 k </ </~ 0 | #1 #1L?&E?E?E?P4C4)405((* 
			*	*	

0	;@,4"	,)X+ +,* ,t(* t(n+6
 6
ry( y(x 4 46t2nA AV :<R&o6 o6d`8 `8F_9v _9Do& o&dw wt3o$6 odxTZZ&& xx I *.  ':"J  =AC4C4,:C4 C4 C4L,( 	 	 1 1 
D 
D B" B"JZz	Q"7: AJ ,= ,=d . . 0 0 8 8 F F M MrN   