o
    Qe12  ã                   @   sv   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 d dl	m
Z
 d dl	mZ g Zeddd„ƒZG d	d
„ d
eƒZdS )é    N)ÚcoreÚVariable)ÚLayerHelper)Ú
check_type)Úconvert_np_dtype_to_dtype_)Ústatic_onlyc              
   C   s²   t di tƒ ¤Ž}t| dtjtjfdƒ t|dttfdƒ t|ƒ}tj 	t
|ƒ¡D ]}|| du r4d||< q(|rG|j| ||tjjjd|dddS |j| |t ¡ tjjjd|dddS )	aÉ
  
    **Data Layer**

    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. For more details about when and how to
           use LoD level, see :ref:`user_guide_lod_tensor` . 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)

    ÚdataÚnameÚshapeNéÿÿÿÿT)r	   r
   ÚdtypeÚtypeZstop_gradientÚ	lod_levelZis_dataZneed_check_feed)r   )r   Úlocalsr   ÚsixÚbinary_typeÚ	text_typeÚlistÚtupleÚmovesÚrangeÚlenZcreate_global_variabler   ÚVarDescÚVarTypeZ
LOD_TENSORÚpaddleZget_default_dtype)r	   r
   r   r   ÚhelperÚi© r   úCD:\Projects\ConvertPro\env\Lib\site-packages\paddle/static/input.pyr      s:   A€øør   c                   @   sv   e Zd ZdZddd„Zdd„ Zdd	„ Zedd
d„ƒZeddd„ƒZ	dd„ Z
dd„ Zd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.

    Examples:
        .. code-block:: python

            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)
            print(label)  # InputSpec(shape=(-1, 1), dtype=paddle.int64, name=label)
    Úfloat32Nc                 C   s:   |   |¡| _|d urt|tjjƒst|ƒ}|| _|| _d S ©N)	Ú_verifyr
   Ú
isinstancer   r   r   r   r   r	   )Úselfr
   r   r	   r   r   r   Ú__init__œ   s   
zInputSpec.__init__c                 C   s   t | j| j| jdS )N©r
   r   )r   r	   r
   r   ©r$   r   r   r   Ú_create_feed_layer¦   s   zInputSpec._create_feed_layerc                 C   s   d  t| ƒj| j| j| j¡S )Nz{}(shape={}, dtype={}, name={}))Úformatr   Ú__name__r
   r   r	   r'   r   r   r   Ú__repr__©   s   ÿzInputSpec.__repr__c                 C   s@   t |ttjtjjfƒr| |j|j|p|jƒS t	d 
t|ƒj¡ƒ‚)ay  
        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)

        z3Input `tensor` should be a Tensor, but received {}.)r#   r   r   ZVarBaseÚeagerZTensorr
   r   r	   Ú
ValueErrorr)   r   r*   )ÚclsZtensorr	   r   r   r   Úfrom_tensor®   s   ÿÿzInputSpec.from_tensorc                 C   s   | |j |j|ƒS )aV  
        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)

        r&   )r.   Zndarrayr	   r   r   r   Ú
from_numpyÏ   s   zInputSpec.from_numpyc                 C   sv   t |ttfƒrt|ƒdkrtd |t|ƒ¡ƒ‚|d }nt |tjƒs,td t	|ƒj
¡ƒ‚|gt| jƒ }t|ƒ| _| S )a0  
        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)

        é   z5Length of batch_size: {} shall be 1, but received {}.z1type(batch_size) shall be `int`, but received {}.)r#   r   r   r   r-   r)   r   Úinteger_typesÚ	TypeErrorr   r*   r
   )r$   Z
batch_sizeZ	new_shaper   r   r   Úbatchç   s"   ÿÿ
ÿÿ
zInputSpec.batchc                 C   s0   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)

        r   z8Not support to unbatch a InputSpec when len(shape) == 0.r1   N)r   r
   r-   r"   r'   r   r   r   Úunbatch  s   ÿzInputSpec.unbatchc                 C   sš   t |ttfƒstd t|ƒj¡ƒ‚t|ƒdkrtd |¡ƒ‚t	|ƒD ]&\}}|dur<t |t
jƒs<td |t|ƒj|¡ƒ‚|du sD|dk rHd||< q"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 {}.r   zH`shape` in InputSpec should contain at least 1 element, but received {}.Nz3shape[{}] should be an `int`, but received `{}`:{}.r   )r#   r   r   r3   r)   r   r*   r   r-   Ú	enumerater   r2   )r$   r
   r   Zeler   r   r   r"   (  s0   ÿÿÿÿÿÿ€zInputSpec._verifyc                 C   s   t t| jƒ| jfƒS r!   )Úhashr   r
   r   r'   r   r   r   Ú__hash__F  s   zInputSpec.__hash__c                    s0   g d¢}t ˆƒt ˆ ƒu ot‡ ‡fdd„|D ƒƒS )N)r
   r   r	   c                 3   s$    | ]}t ˆ|ƒt ˆ |ƒkV  qd S r!   )Úgetattr)Ú.0Úattr©Úotherr$   r   r   Ú	<genexpr>Y  s   € 
ÿz#InputSpec.__eq__.<locals>.<genexpr>)r   Úall)r$   r=   Úslotsr   r<   r   Ú__eq__W  s   ÿzInputSpec.__eq__c                 C   s
   | |k S r!   r   )r$   r=   r   r   r   Ú__ne__]  s   
zInputSpec.__ne__)r    Nr!   )r*   Ú
__module__Ú__qualname__Ú__doc__r%   r(   r+   Úclassmethodr/   r0   r4   r5   r"   r8   rA   rB   r   r   r   r   r   }   s    

 (r   )Nr   )r   r   Zpaddle.fluidr   r   Zpaddle.fluid.layer_helperr   Zpaddle.fluid.data_feederr   Zpaddle.fluid.frameworkr   r   Ú__all__r   Úobjectr   r   r   r   r   Ú<module>   s   a