Ë
    –\;jº<  ã                   ó¬   — d dl Z d dl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 g Zd	efd
„Zedd„«       Z G d„ d«      Zd„ Zy)é    N)ÚVariableÚcore)Ú
check_type)Úconvert_np_dtype_to_dtype_Úin_pir_modeÚstatic_only)ÚLayerHelper)ÚDataTypeé   ©Ú_setitem_staticÚreturnc                 ó8   — t        | «      j                  «       dvS )N)ÚfalseÚoffÚ0Únone)ÚstrÚlower)Úvals    ú\G:\00. PROJECTS\API\Inventory\templateJSON\kerjaOCR\Lib\site-packages\paddle/static/input.pyÚevaluate_flagr   #   s   € Üˆs‹8�>‰>ÓÐ#@Ð@Ð@ó    c           
      óä  — d„ }t        di t        «       ¤Ž}t        | dt        t        fd«       t        |dt
        t        fd«       t        |«      }t        t        |«      «      D ]  }||   �Œ	d||<   Œ |€t        j                  «       }t        «       r–|}t        |t        «      s)t        j                  j                  j!                  |«      } |«        t        j"                  j%                  | ||t        j&                  «       «      }t        j                  j)                  «        |S |j+                  | ||t        j,                  j.                  j0                  d|dd¬«      }t2        j4                  j7                  d	d«      }	t9        |	«      r^t        di t        «       ¤Ž}t        |t        j,                  j.                  «      st!        |«      }|j;                  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 LoDTensor. 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

            >>> 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                  «       } | j	                  «       j
                  }t        |«      dk(  ry |D ]6  }|j                  «       dk7  sŒt         j                  j                  |«        y  y )Nr   z
pd_op.data)	ÚpaddleÚpirr   Údefault_main_programÚglobal_blockÚopsÚlenÚnameÚset_insertion_point)r   r    Úops      r   Ú_reset_data_op_insertion_pointz,data.<locals>._reset_data_op_insertion_pointm   sh   € Ü%Ÿz™zŸ™×CÑCÓEÐØ"×/Ñ/Ó1×5Ñ5ˆÜˆs‹8�qŠ=ØÛˆBØ�w‰w‹y˜LÓ(Ü—
‘
×.Ñ.¨rÔ2Ùñ r   Údatar"   ÚshapeNéÿÿÿÿT)r"   r'   ÚdtypeÚtypeÚstop_gradientÚ	lod_levelÚis_dataÚneed_check_feedÚFLAGS_enable_pir_in_executorÚoutr   )r'   r)   Úplacer"   )r*   ÚinputsÚoutputsÚattrs)r&   )r	   Úlocalsr   Úbytesr   ÚlistÚtupleÚranger!   r   Úget_default_dtyper   Ú
isinstancer
   r   r   r   Ú_pir_opsr&   ÚPlaceÚreset_insertion_point_to_endÚcreate_global_variableÚVarDescÚVarTypeÚ
LOD_TENSORÚosÚenvironÚgetr   Ú	append_op)
r"   r'   r)   r,   r%   ÚhelperÚiÚir_dtyper0   Úis_pir_modes
             r   r&   r&   '   s©  € òLô Ñ,¤6£8Ñ,€FÜˆt�Vœe¤S˜\¨6Ô2Üˆu�g¤¤e˜}¨fÔ5ä�‹K€EÜ”3�u“:ÖˆØ�‰8ÑØˆE�!ŠHð ð €}Ü×(Ñ(Ó*ˆä„}ØˆÜ˜(¤HÔ-Ü—z‘z—‘×AÑAÀ%ÓHˆHÙ&Ô(Ü�o‰o×"Ñ" 4¨°¼$¿*¹*»,ÓGˆÜ�
‰
×/Ñ/Ô1Øˆ
à
×
'Ñ
'ØØØÜ�\‰\×!Ñ!×,Ñ,ØØØØð (ó 	€Cô —*‘*—.‘.Ð!?ÀÓF€KÜ�[Ô!ÜÑ0¤v£xÑ0ˆÜ˜%¤§¡×!5Ñ!5Ô6Ü.¨uÓ5ˆEØ×ÑØØØ˜C�LàØØØñ	ð	 	ô 
	
ð €Jr   c                   ól   — e Zd ZdZdd„Zd„ Zd„ Zedd„«       Zedd„«       Z	d„ Z
d	„ Zd
„ Zd„ Zd„ Zd„ Zy)Ú	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)
    Nc                 ó´   — | j                  |«      | _        |�+t        |t        j                  t
        f«      rt        |«      }|| _        || _        || _        y ©N)	Ú_verifyr'   r;   Únpr)   r   r   r"   r+   )Úselfr'   r)   r"   r+   s        r   Ú__init__zInputSpec.__init__Î   sJ   € à—\‘\ %Ó(ˆŒ
àÐÜ˜%¤"§(¡(¬C Ô1Ü2°5Ó9�àˆŒ
ØˆŒ	Ø*ˆÕr   c                 óZ   — t        | j                  | j                  | j                  ¬«      S )N©r'   r)   )r&   r"   r'   r)   ©rQ   s    r   Ú_create_feed_layerzInputSpec._create_feed_layerÚ   s   € Ü�D—I‘I T§Z¡Z°t·z±zÔBÐBr   c                 ó¢   — dj                  t        | «      j                  | j                  | j                  | j
                  | j                  «      S )Nz1{}(shape={}, dtype={}, name={}, stop_gradient={}))Úformatr*   Ú__name__r'   r)   r"   r+   rU   s    r   Ú__repr__zInputSpec.__repr__Ý   s@   € ØB×IÑIÜ�‹J×ÑØ�J‰JØ�J‰JØ�I‰IØ×Ñó
ð 	
r   c                 ó  — t        |t        t        j                  j                  f«      r, | |j
                  |j                  |xs |j                  «      S t        dj                  t        |«      j                  «      «      ‚)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)

        z3Input `tensor` should be a Tensor, but received {}.)r;   r   r   ÚeagerÚTensorr'   r)   r"   Ú
ValueErrorrX   r*   rY   )ÚclsÚtensorr"   s      r   Úfrom_tensorzInputSpec.from_tensoræ   se   € ô2 �fœx¬¯©×):Ñ):Ð;Ô<Ù�v—|‘| V§\¡\°4Ò3F¸6¿;¹;ÓGÐGäØE×LÑLÜ˜“L×)Ñ)óóð r   c                 ó>   —  | |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)

        rT   )r_   Úndarrayr"   s      r   Ú
from_numpyzInputSpec.from_numpy  s   € ñ. �7—=‘= '§-¡-°Ó6Ð6r   c                 ón  — t        |t        t        f«      r8t        |«      dk7  r$t	        dj                  |t        |«      «      «      ‚|d   }n=t        |t        «      s-t        dj                  t        |«      j                  «      «      ‚|gt        | j                  «      z   }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)

        é   z5Length of batch_size: {} shall be 1, but received {}.z1type(batch_size) shall be `int`, but received {}.)r;   r7   r8   r!   r^   rX   ÚintÚ	TypeErrorr*   rY   r'   )rQ   Ú
batch_sizeÚ	new_shapes      r   ÚbatchzInputSpec.batch!  s¨   € ô* �j¤4¬ -Ô0Ü�:‹ !Ò#Ü ØK×RÑRØ"¤C¨
£Oóóð ð
 $ A™‰JÜ˜J¬Ô,ÜØC×JÑJÜ˜Ó$×-Ñ-óóð ð  �L¤4¨¯
©
Ó#3Ñ3ˆ	Ü˜9Ó%ˆŒ
àˆr   c                 ó’   — t        | j                  «      dk(  rt        d«      ‚| j                  | 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.rf   N)r!   r'   r^   rO   rU   s    r   ÚunbatchzInputSpec.unbatchJ  sE   € ô$ ˆt�z‰z‹?˜aÒÜØJóð ð —\‘\ $§*¡*¨Q¨R .Ó1ˆŒ
Øˆr   c           	      ó`  — t        |t        t        f«      s-t        dj	                  t        |«      j                  «      «      ‚t        |«      D ]S  \  }}|�?t        |t        «      s/t        dj	                  |t        |«      j                  |«      «      ‚|�|dk  sŒOd||<   ŒU t        |«      S )zI
        Verifies the input shape and modifies `None` into `-1`.
        zMType of `shape` in InputSpec should be one of (tuple, list), but received {}.z3shape[{}] should be an `int`, but received `{}`:{}.r(   )
r;   r7   r8   rh   rX   r*   rY   Ú	enumeraterg   r^   )rQ   r'   rH   Úeles       r   rO   zInputSpec._verifyd  s¬   € ô ˜%¤$¬ Ô/ÜØ_×fÑfÜ˜“K×(Ñ(óóð ô   Ö&‰FˆAˆsØˆÜ! #¤sÔ+Ü$ØM×TÑTØœt C›y×1Ñ1°3óóð ð
 ˆ{˜c B›hØ��a’ð 'ô �U‹|Ðr   c                 ól   — t        t        | j                  «      | j                  | j                  f«      S rN   )Úhashr8   r'   r)   r+   rU   s    r   Ú__hash__zInputSpec.__hash__|  s)   € ô ”U˜4Ÿ:™:Ó&¨¯
©
°D×4FÑ4FÐGÓHÐHr   c                 óh   ‡ ‡— g d¢}t        ‰ «      t        ‰«      u xr t        ˆˆ fd„|D «       «      S )N)r'   r)   r"   r+   c              3   óP   •K  — | ]  }t        ‰|«      t        ‰|«      k(  –— Œ y ­wrN   )Úgetattr)Ú.0ÚattrÚotherrQ   s     €€r   Ú	<genexpr>z#InputSpec.__eq__.<locals>.<genexpr>�  s(   øè ø€ ð 1
ÙDI¸DŒG�D˜$Ó¤7¨5°$Ó#7Õ7ÁEùs   ƒ#&)r*   Úall)rQ   ry   Úslotss   `` r   Ú__eq__zInputSpec.__eq__�  s6   ù€ Ú;ˆÜ�D‹zœT %›[Ð(ò 
¬Sô 1
ÙDIó1
ó .
ð 	
r   c                 ó   — | |k(   S rN   © )rQ   ry   s     r   Ú__ne__zInputSpec.__ne__“  s   € Ø˜5‘=Ð Ð r   )Úfloat32NFrN   )rY   Ú
__module__Ú__qualname__Ú__doc__rR   rV   rZ   Úclassmethodra   rd   rk   rm   rO   rs   r}   r€   r   r   r   rL   rL   ª   sa   „ ñ!óF
+òCò
ð òó ððB ò7ó ð7ò0'òRò4ò0Iò"
ó!r   rL   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   )ÚxÚindexÚvalues      r   ÚsetitemrŠ   —  s   € ô* ˜1˜e UÓ+Ð+r   )Nr   )rC   ÚnumpyrP   r   Úpaddle.baser   r   Úpaddle.base.data_feederr   Úpaddle.base.frameworkr   r   r   Úpaddle.base.layer_helperr	   Úpaddle.base.libpaddler
   Úbase.variable_indexr   Ú__all__Úboolr   r&   rL   rŠ   r   r   r   Ú<module>r”      sg   ðó 
ã ã ß &Ý .÷ñ õ
 1Ý *å 1à
€ðA˜$ó Að òó ð÷Dj!ñ j!óZ,r   