
    |j]>                    .   d dl mZ d dlZd dlmZmZ d dlZd dlmZ	 d dl
mZ d dlZd dlmZmZ d dlmZ d dlmZmZmZ d dlmZ d d	lmZ d d
lmZmZ ddlmZ erd dlmZ d dl m!Z!m"Z"m#Z#m$Z$m%Z% g Z&d%dZ'e	 	 d&d'd            Z( G d d          Z)d(d$Z*dS ))    )annotationsN)TYPE_CHECKINGAny)Self)Variablecore)
check_type)convert_np_dtype_to_dtype_in_pir_modestatic_only)LayerHelper)DataType)get_current_insertion_pointset_insertion_point   _setitem_static)Tensor)	DTypeLike	ShapeLikeSize1TensorIndex
TensorLikereturnboolc                H    t          |                                           dvS )N)falseoff0none)strlower)vals    c/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/paddle/static/input.pyevaluate_flagr%   6   s    s88>>#@@@    namer!   shaper   dtypeDTypeLike | None	lod_levelintpaddle.Tensorc           
        d }t          di t                      }t          | dt          t          fd           t          |dt
          t          fd           t          |          }t          t          |                    D ]Z}||         d||<   t          ||         t                    r0||         dk     r$||         dk    rt          d||                    [|t          j                    }t                      r|}t          |t                    s$t          j        j                            |          }t'                      } |             t          j                            | ||t#          j                              }	t/          |           |	S |                    | ||t"          j        j        j        d	|d	d	
          }	t8          j                            dd          }
t?          |
          rft          di t                      }t          |t"          j        j                  st%          |          }|                     di d|	i||d| d           |	S )a  

    This function creates a variable on the global block. The global variable
    can be accessed by all the following operators in the graph. The variable
    is a placeholder that could be fed with input, such as Executor can feed
    input into the variable. When `dtype` is None, the dtype
    will get from the global dtype by `paddle.get_default_dtype()`.

    Args:
        name (str): The name/alias of the variable, see :ref:`api_guide_Name`
            for more details.
        shape (list|tuple): List|Tuple of integers declaring the shape. You can
            set None or -1 at a dimension to indicate the dimension can be of any
            size. For example, it is useful to set changeable batch size as None or -1.
        dtype (np.dtype|str, optional): The type of the data. Supported
            dtype: bool, float16, float32, float64, int8, int16, int32, int64,
            uint8. Default: None. When `dtype` is not set, the dtype will get
            from the global dtype by `paddle.get_default_dtype()`.
        lod_level (int, optional): The LoD level of the DenseTensor. Usually users
            don't have to set this value. Default: 0.

    Returns:
        Variable: The global variable that gives access to the data.

    Examples:
        .. code-block:: python

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

            # Creates a variable with fixed size [3, 2, 1]
            # User can only feed data of the same shape to x
            # the dtype is not set, so it will set "float32" by
            # paddle.get_default_dtype(). You can use paddle.get_default_dtype() to
            # change the global dtype
            >>> x = paddle.static.data(name='x', shape=[3, 2, 1])

            # Creates a variable with changeable batch size -1.
            # Users can feed data of any batch size into y,
            # but size of each data sample has to be [2, 1]
            >>> y = paddle.static.data(name='y', shape=[-1, 2, 1], dtype='float32')

            >>> z = x + y

            # In this example, we will feed x and y with np-ndarray "1"
            # and fetch z, like implementing "1 + 1 = 2" in PaddlePaddle
            >>> feed_data = np.ones(shape=[3, 2, 1], dtype=np.float32)

            >>> exe = paddle.static.Executor(paddle.framework.CPUPlace())
            >>> out = exe.run(paddle.static.default_main_program(),
            ...             feed={
            ...                 'x': feed_data,
            ...                 'y': feed_data
            ...             },
            ...             fetch_list=[z.name])

            # np-ndarray of shape=[3, 2, 1], dtype=float32, whose elements are 2
            >>> print(out)
            [array([[[2.],
                    [2.]],
                   [[2.],
                    [2.]],
                   [[2.],
                    [2.]]], dtype=float32)]

    c                 &   t           j        j                                        } |                                 j        }t          |          dk    rd S |D ]<}|                                dk    r"t           j                            |            d S =d S )Nr   z
pd_op.data)	paddlepirr   default_main_programglobal_blockopslenr'   r   )r2   r4   ops      r$   _reset_data_op_insertion_pointz,data.<locals>._reset_data_op_insertion_point   s    %zCCEE"//115s88q==F 	 	BwwyyL((
..r222 )	 	r&   datar'   r(   Nr   zIOnly -1 can be used in shape to indicate unknown dimension, but received T)r'   r(   r)   typestop_gradientr+   is_dataneed_check_feedFLAGS_enable_pir_in_executorout)r(   r)   placer'   )r:   inputsoutputsattrs)r8   )!r   localsr	   bytesr!   listtupleranger5   
isinstancer,   
ValueErrorr0   get_default_dtyper   r   r1   r   r
   r   _pir_opsr8   Placer   create_global_variableVarDescVarTypeDENSE_TENSORosenvirongetr%   	append_op)r'   r(   r)   r+   r7   helperiir_dtypeprev_insertion_pointr?   is_pir_modes              r$   r8   r8   :   sm   X   ,,688,,FtVeS\6222uge}f555KKE3u::  8E!HeAh$$ 	qA%(b..f\abc\dff   }(**}} (H-- 	IzAA%HHH:<<&&(((o""4$*,,GG0111


'
'\!. ( 	 	C *..!?FFK[!! 
00vxx00%!566 	6.u55ECL	 	 	 
	
 
	
 
	
 Jr&   c                      e Zd ZdZ	 	 	 d$d%dZd Zd&dZed'd(d            Ze	 d'd)d            Z	d*dZ
d+dZd Zd,d Zd-d"Zd.d#ZdS )/	InputSpeca@  
    InputSpec describes the signature information of the model input, such as ``shape`` , ``dtype`` , ``name`` .

    This interface is often used to specify input tensor information of models in high-level API.
    It's also used to specify the tensor information for each input parameter of the forward function
    decorated by `@paddle.jit.to_static`.

    Args:
        shape (tuple(integers)|list[integers]): List|Tuple of integers
            declaring the shape. You can set "None" or -1 at a dimension
            to indicate the dimension can be of any size. For example,
            it is useful to set changeable batch size as "None" or -1.
        dtype (np.dtype|str, optional): The type of the data. Supported
            dtype: bool, float16, float32, float64, int8, int16, int32, int64,
            uint8. Default: float32.
        name (str): The name/alias of the variable, see :ref:`api_guide_Name`
            for more details.
        stop_gradient (bool, optional): A boolean that mentions whether gradient should flow. Default is False, means don't stop calculate gradients.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> from paddle.static import InputSpec

            >>> input = InputSpec([None, 784], 'float32', 'x')
            >>> label = InputSpec([None, 1], 'int64', 'label')

            >>> print(input)
            InputSpec(shape=(-1, 784), dtype=paddle.float32, name=x, stop_gradient=False)

            >>> print(label)
            InputSpec(shape=(-1, 1), dtype=paddle.int64, name=label, stop_gradient=False)
    float32NFr(   r   r)   r   r'   
str | Noner;   r   r   Nonec                    |                      |          | _        |0t          |t          j        t
          f          rt          |          }|| _        || _        || _        d S N)	_verifyr(   rI   npr)   r!   r
   r'   r;   )selfr(   r)   r'   r;   s        r$   __init__zInputSpec.__init__   s^     \\%((
%"(C11 :2599
	*r&   c                D    t          | j        | j        | j                  S )Nr(   r)   )r8   r'   r(   r)   rd   s    r$   _create_feed_layerzInputSpec._create_feed_layer   s    DITZtzBBBBr&   r!   c           
     p    t          |           j         d| j         d| j         d| j         d| j         d
S )Nz(shape=z, dtype=z, name=z, stop_gradient=))r:   __name__r(   r)   r'   r;   rh   s    r$   __repr__zInputSpec.__repr__  sn    t**%  F  Fdj  F  F$*  F  FUYU^  F  Fpt  qC  F  F  F  	Fr&   tensorr   r   c                    t          |t          t          j        j        t
          j        j        f          r | |j        |j	        |p|j
                  S t          dt          |          j         d          )a  
        Generates a InputSpec based on the description of input tensor.

        Args:
            tensor(Tensor): the source tensor to generate a InputSpec instance

        Returns:
            A InputSpec instance generated from Tensor.

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> from paddle.static import InputSpec

                >>> paddle.disable_static()

                >>> x = paddle.ones([2, 2], dtype="float32")
                >>> x_spec = InputSpec.from_tensor(x, name='x')
                >>> print(x_spec)
                InputSpec(shape=(2, 2), dtype=paddle.float32, name=x, stop_gradient=False)

        z0Input `tensor` should be a Tensor, but received .)rI   r   r   eagerr   r0   r1   Valuer(   r)   r'   rJ   r:   rl   )clsrn   r'   s      r$   from_tensorzInputSpec.from_tensor  so    2 fx):FJ<LMNN 	3v|V\43F6;GGG[4<<CX[[[  r&   ndarraynpt.NDArray[Any]c                0     | |j         |j        |          S )a  
        Generates a InputSpec based on the description of input np.ndarray.

        Args:
            tensor(Tensor): the source numpy ndarray to generate a InputSpec instance

        Returns:
            A InputSpec instance generated from Tensor.

        Examples:
            .. code-block:: python

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

                >>> x = np.ones([2, 2], np.float32)
                >>> x_spec = InputSpec.from_numpy(x, name='x')
                >>> print(x_spec)
                InputSpec(shape=(2, 2), dtype=paddle.float32, name=x, stop_gradient=False)

        rg   )rs   ru   r'   s      r$   
from_numpyzInputSpec.from_numpy$  s    2 s7='-666r&   
batch_sizeint | Size1c                   t          |t          t          f          r?t          |          dk    r#t	          d| dt          |           d          |d         }n:t          |t
                    s%t          dt          |          j         d          |gt          | j	                  }t          |          | _	        | S )ac  
        Inserts `batch_size` in front of the `shape`.

        Args:
            batch_size(int): the inserted integer value of batch size.

        Returns:
            The original InputSpec instance by inserting `batch_size` in front of `shape`.

        Examples:
            .. code-block:: python

                >>> from paddle.static import InputSpec

                >>> x_spec = InputSpec(shape=[64], dtype='float32', name='x')
                >>> x_spec.batch(4)
                >>> print(x_spec)
                InputSpec(shape=(4, 64), dtype=paddle.float32, name=x, stop_gradient=False)

           zLength of batch_size: z shall be 1, but received rp   r   z.type(batch_size) shall be `int`, but received )
rI   rF   rG   r5   rJ   r,   	TypeErrorr:   rl   r(   )rd   ry   	new_shapes      r$   batchzInputSpec.batch?  s    * j4-00 		:!## eZeeSVWaSbSbeee   $AJJJ,, 	]jAQAQAZ]]]    3$tz"2"23	9%%
r&   c                    t          | j                  dk    rt          d          |                     | j        dd                   | _        | S )a:  
        Removes the first element of `shape`.

        Returns:
            The original InputSpec instance by removing the first element of `shape` .

        Examples:
            .. code-block:: python

                >>> from paddle.static import InputSpec

                >>> x_spec = InputSpec(shape=[4, 64], dtype='float32', name='x')
                >>> x_spec.unbatch()
                >>> print(x_spec) # InputSpec(shape=(64,), dtype=paddle.float32, name=x)
                InputSpec(shape=(64,), dtype=paddle.float32, name=x, stop_gradient=False)

        r   z8Not support to unbatch a InputSpec when len(shape) == 0.r|   N)r5   r(   rJ   rb   rh   s    r$   unbatchzInputSpec.unbatchd  sP    $ tz??aJ   \\$*QRR.11
r&   c           
     j   t          |t          t          f          s%t          dt	          |          j         d          t          |          D ]T\  }}|@t          |t                    s+t          d| dt	          |          j         d| d          ||dk     rd||<   Ut          |          S )zI
        Verifies the input shape and modifies `None` into `-1`.
        zJType of `shape` in InputSpec should be one of (tuple, list), but received rp   Nzshape[z$] should be an `int`, but received `z`:r9   )	rI   rF   rG   r}   r:   rl   	enumerater,   rJ   )rd   r(   rW   eles       r$   rb   zInputSpec._verify~  s     %$// 	t]abg]h]h]qttt    && 	 	FAs!#s++ $dddS		HZdd^addd   {cBhhaU||r&   r,   c                ^    t          t          | j                  | j        | j        f          S ra   )hashrG   r(   r)   r;   rh   s    r$   __hash__zInputSpec.__hash__  s(     U4:&&
D4FGHHHr&   otherc                     g d}t                     t                    u ot           fd|D                       S )N)r(   r)   r'   r;   c              3  \   K   | ]&}t          |          t          |          k    V  'd S ra   )getattr).0attrr   rd   s     r$   	<genexpr>z#InputSpec.__eq__.<locals>.<genexpr>  sM       1
 1
<@GD$75$#7#771
 1
 1
 1
 1
 1
r&   )r:   all)rd   r   slotss   `` r$   __eq__zInputSpec.__eq__  sd    ;;;DzzT%[[( 
S 1
 1
 1
 1
 1
DI1
 1
 1
 .
 .
 	
r&   c                    | |k     S ra    )rd   r   s     r$   __ne__zInputSpec.__ne__  s    5=  r&   )r]   NF)
r(   r   r)   r   r'   r^   r;   r   r   r_   )r   r!   ra   )rn   r   r'   r^   r   r   )ru   rv   r'   r^   r   r   )ry   rz   r   r   )r   r   )r   r,   )r   r   r   r   r   r   )rl   
__module____qualname____doc__re   ri   rm   classmethodrt   rx   r   r   rb   r   r   r   r   r&   r$   r\   r\      s2       ! !L %#+ + + + +$C C CF F F F     [> ;?7 7 7 7 [74# # # #J   4  (I I I I"
 
 
 
! ! ! ! ! !r&   r\   xr   indexr   valuer   c                $    t          | ||          S )a=  
    x(Tensor): input Tensor.
    index(Scalar|Tuple|List|Tensor): Where should be set value.
    value(Scalar|Tensor): The value which is going to be set.

    [How to write index?]
    1. ':' -> slice(),
       (1) a[:]=v -> setitem(a, slice(None,None,None), v)
       (2) a[1::2] -> setitem(a, slice(1,None,2), v)

    2. if there are multiple indexes for axes, use TUPLE (Not LIST) to pack them.
       (1) a[1, 2]=v -> setitem(a, (1, 2), v)
       (2) a[[1,2],[2,3]]=v -> setitem(a, ([1,2],[2,3]), v)
       (3) a[1,:, 3] = v -> setitem(a, (1, slice(None,None,None),3), v)
       (4) a[1, ..., 2]=v -> setitem(a, (1, ..., 2), v)

    3. You can always use TUPLE as index input, even there is only one index.
       (1) a[Tensor([10,10])]=v -> setitem(a, (Tensor([10,10]),), v)
       (2) a[1] = v -> setitem(a, (1,), v)
    r   )r   r   r   s      r$   setitemr     s    2 1eU+++r&   r   )Nr   )
r'   r!   r(   r   r)   r*   r+   r,   r   r-   )r   r   r   r   r   r   r   r   )+
__future__r   rR   typingr   r   numpyrc   numpy.typingnpttyping_extensionsr   r0   paddle.baser   r   paddle.base.data_feederr	   paddle.base.frameworkr
   r   r   paddle.base.layer_helperr   paddle.base.libpaddler   paddle.base.libpaddle.pirr   r   base.variable_indexr   r   paddle._typingr   r   r   r   r   __all__r%   r8   r\   r   r   r&   r$   <module>r      s2   # " " " " " 				 % % % % % % % %           " " " " " "  & & & & & & & & . . . . . .         
 1 0 0 0 0 0 * * * * * *       
 2 1 1 1 1 1               A A A A  #	J J J J JZb! b! b! b! b! b! b! b!J, , , , , ,r&   