o
    + i                     @  sZ  d dl mZ d dlZd dlZd dlZd dlmZ d dlmZ d dl	Z
d dlmZ d dlmZ d dlmZ d dlmZ d	d
lmZ erLd dlmZmZmZ daejejejejejejgZ i ddddddddddddddddddddddddddddddddddddddZ!g d Z"d!d" Z#ee#Z$d#d$ Z%d%d& Z&dS )'    )annotationsN)reduce)TYPE_CHECKING)_C_ops)DataType)wrap_decorator)size_args_decorator_patch   )Value)	DTypeLike	PlaceLike	ShapeLikeFfloat16Zhalfbfloat16float32floatfloat64doubleint8charint16Zshortint32intint64longbool	complex64
complex128)r   ZcfloatZcdouble)__add____radd____sub____rsub____mul____rmul____mod____rmod____div____rdiv____truediv____rtruediv____floordiv____rfloordiv____pow____rpow____eq____ne____lt____le____gt____ge__c                   s    fdd}|S )Nc                    s   t d j d j d)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'.)AssertionError__name__argskwargsfunc d/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/paddle/pir/math_op_patch.py__impl__i   s
   
z'_fake_interface_only_.<locals>.__impl__r<   )r;   r>   r<   r:   r=   _fake_interface_only_h   s   r?   c           	   
   C  s   t | tsJ t|}d}g }t| jD ]\}}|dk r.|dk r(|}|| q|d q|| q|dks:J ddlm} t	| ||||||
 }d|_|S )Nr   r	   )coreT)
isinstancer
   r   	enumerateshapeappendZpaddle.frameworkrA   r   Zfull_batch_size_likePlacestop_gradient)	Zref_varvaluedtypeZ	batch_dimZ	out_shapeidrA   outr<   r<   r=   create_tensor_with_batchsizew   s$   rM   c            8        s  dd dd } ddd}t dd	 }d
d }dd }t dd }dd }dd }dfdd}fdd  fdd}	 fdd}
dd }fd d!}fd"d#}fd$d%}fd&d'}fd(d)}fd*d+}fd,d-}	.	 d fd/d0	}t fd1d2}t d3d4 }t d5d6 }d d d.d.d7dfdCdD}td d d.d.d7dfdEdF}td d d.d.d7dfdGdH}td d d.d.d7dfdIdJ}dKdL }dMdN }dOdP }dQdR }fdSdT}tdUdV } dWdX }!fdYdZ}"d[d\ }#d]d^ }$d_d` }%fdadb}&dcdd }'	 	 	 dfdedf	}(fdgdh})tdidj }*tdkdl }+tdmdn },t ddpdq}-|-jddtdq}-dud lg dv| fdw|fdx|fdy|fdz|fd{|fd||fd}|fd~|fd fd|	fd|	fd|fd8|fd|fd|fd|fd|fd|fd|fd@|-fd|fd| fd|!fd|"fd|&fd|'fd|#fd|%fd|$fd|(fd|)fd|+fd|*fd|,fd|djjd.|fd|djjd.|fd|djjd.|fd|djjd|fd|djjd.|fd|djjd.|fd|djj	d.|fd|djj	d.|fd|djj	dd fd|djj	dd fd|djj
d.d fd|djj
dd fd|djjd.d fd|djjdd fd|djjd.d fd|djjdd fd|djjd.d fd|djjdd fd|fd|fd|djjd.d fd|djjd.d fd|djjd.d fd|djjd.d fd|djjd.d fd|djjd.d fd|fd|fd|fd|f}.|
 }/|.|/ tsW|.D ]}0|0du }1|0d }2tt|1|2 qdud ljjD ]}1tt|1rqtj|1d }2|2r)tt|1|2 qjjD ]\}3}4tj|4d }5|5rCtt|3|5 q/ddlm}6m}7 |6t_ |7t_!dad S d S )Nc                 S  s   z| j }W |S    td)NzCannot get data type from var)rI   
ValueError)varrI   r<   r<   r=   safe_get_dtype   s
   z*monkey_patch_value.<locals>.safe_get_dtypec                 S  s   t | dS )a  
        In dy2static, Value also needs cpu() and cuda() interface.
        But, the underneath operator has only forward op but not backward one.

        Returns:
            The tensor which has copied to cpu place.

        Examples:
            In Static Graph Mode:

            .. code-block:: python

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

                >>> x = paddle.static.data(name="x", shape=[2,2], dtype='float32')
                >>> y = x.cpu()
        r   )r   memcpyselfr<   r<   r=   cpu   s   zmonkey_patch_value.<locals>.cpuTc                 S  s0   |dur	t d |durt d t| dS )a  
        In dy2static, Value also needs cpu() and cuda() interface.
        But, the underneath operator has only forward op but not backward one.

        Args:
            self(Value): The variable itself.
            device_id(int, optional): The destination GPU device id. Default: None, means current device.
                We add this argument for dy2static translation, please do not use it.
            blocking(bool, optional): Whether blocking or not, Default: True.
                We add this argument for dy2static translation, please do not use it.

        Returns:
            The tensor which has copied to cuda place.

        Examples:
            In Static Graph Mode:

            .. code-block:: python

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

                >>> x = paddle.static.data(name="x", shape=[2,2], dtype='float32')
                >>> y = x.cpu()
                >>> z = y.cuda()
        Nz3device_id is not supported, and it will be ignored.T2blocking is not supported, and it will be ignored.r	   )warningswarnr   rQ   )rS   Z	device_idblockingr<   r<   r=   cuda   s
   

z monkey_patch_value.<locals>.cudac                 S     t d dS )z
        Value don't have 'place' interface in static graph mode
        But this interface can greatly facilitate dy2static.
        So we give a warning here and return None.
        zaValue do not have 'place' interface for pir graph mode, try not to use it. None will be returned.NrV   rW   rR   r<   r<   r=   place   s   z!monkey_patch_value.<locals>.placec                 S  s   t d | S )z
        Value don't have 'contiguous' interface in static graph mode
        But this interface can greatly facilitate dy2static.
        So we give a warning here and return None.
        ziValue do not have 'contiguous' interface for static graph mode, try not to use it. self will be returned.r[   rR   r<   r<   r=   
contiguous      z&monkey_patch_value.<locals>.contiguousc                 S  rZ   )z
        Value don't have 'is_contiguous' interface in static graph mode
        But this interface can greatly facilitate dy2static.
        So we give a warning here and return None.
        zlValue do not have 'is_contiguous' interface for static graph mode, try not to use it. True will be returned.Tr[   rR   r<   r<   r=   is_contiguous   r^   z)monkey_patch_value.<locals>.is_contiguousc                 S  
   t | jS )a  
        Returns the dimension of current Value

        Returns:
            the dimension

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> paddle.enable_static()

                >>> # create a static Value
                >>> x = paddle.static.data(name='x', shape=[3, 2, 1])
                >>> # print the dimension of the Value
                >>> print(x.ndim)
                3
        lenrD   rR   r<   r<   r=   _ndim   s   
z!monkey_patch_value.<locals>._ndimc                 S  r`   )a  
        Returns the dimension of current Value

        Returns:
            the dimension

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> paddle.enable_static()

                >>> # create a static Value
                >>> x = paddle.static.data(name='x', shape=[3, 2, 1])
                >>> # print the dimension of the Value
                >>> print(x.ndimension())
                3
        ra   rR   r<   r<   r=   
ndimension     
z&monkey_patch_value.<locals>.ndimensionc                 S  r`   )a  
        Returns the dimension of current Value

        Returns:
            the dimension

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> paddle.enable_static()

                >>> # create a static Value
                >>> x = paddle.static.data(name='x', shape=[3, 2, 1])
                >>> # print the dimension of the Value
                >>> print(x.dim())
                3
        ra   rR   r<   r<   r=   dim"  re   zmonkey_patch_value.<locals>.dimr8   r   c           	   	     s  |   r
|  s
dS ddlm} || }t|dkr!tdd |nd}d}t|dkr<t| jjs:|dkr:t	d| S t|dkr[|\}t| jjsZ||krZt	d| d	| npt|t|krgt	d
dgt| }t
dt|D ]}||  ||   || d < qut
t|D ]=}|| }t|tstd| dt| t||  jjs||| krt	d| d| d||  ||||  7 }q|  | S )z
        In order to be compatible with the item interface introduced by the dynamic graph, it does nothing but returns self.
        It will check that the shape must be a 1-D tensor
        Nr   )Shapec                 S  s   t | | S N)r   )xyr<   r<   r=   <lambda>E      z3monkey_patch_value.<locals>._item.<locals>.<lambda>r	   zUonly one element tensors can be converted to Python scalars when no input coordinateszindex z is out of bounds for size z&incorrect number of indices for Tensorzargument (position z) must be long, but got z is out of bounds for axis z with size )Zis_distZ_is_initializedZpaddle.jit.dy2staticrg   rb   r   rB   pirr
   rN   ranger   	TypeErrortypeflatten)	rS   r8   rg   dimsnumeloffsetstridesrJ   indexpaddler<   r=   _item8  sL    
z!monkey_patch_value.<locals>._itemc                   s2   t |ts jj|}| j|kr| S t| |S )a  
        **Notes**:

        Convert a value to a specified data type if it differs from the current dtype;
        otherwise, return the original value.

        Args:

            self(Value): The source Value

            dtype: The target data type

        Returns:
            Value: Value with new dtype

        Examples:
            In Static Graph Mode:

            .. code-block:: python

                >>> import paddle
                >>> paddle.enable_static()
                >>> startup_prog = paddle.static.Program()
                >>> main_prog = paddle.static.Program()
                >>> with paddle.static.program_guard(startup_prog, main_prog):
                ...     original_value = paddle.static.data(name = "new_value", shape=[2,2], dtype='float32')
                ...     new_value = original_value.astype('int64')
                ...     print(f"new value's dtype is: {new_value.dtype}")
                ...
                new Value's dtype is: paddle.int64

        )rB   r   rm   rA   Zconvert_np_dtype_to_dtype_rI   r   cast)rS   rI   rw   r<   r=   astypeq  s
   
"
z"monkey_patch_value.<locals>.astypec                   sF   |   r | d} |dS |  r |  d} |dS  | dS )Nr   uint8)Zis_floating_pointZ
is_complexreal)rS   tensorr}   r{   r<   r=   byte  s   



z monkey_patch_value.<locals>.bytec                    sV   g } t  D ]"\}} fdd}||}||_d| d| d|_| ||f q| S )z?
        Batch create all data type conversion methods
        c                       fdd}|S )Nc                   s
    | S rh   r<   rR   r{   rI   r<   r=   conversion_method     
zwmonkey_patch_value.<locals>._create_dtype_conversion_methods.<locals>.make_conversion_method.<locals>.conversion_methodr<   )rI   r   r   rI   r=   make_conversion_method  s   z\monkey_patch_value.<locals>._create_dtype_conversion_methods.<locals>.make_conversion_methodz
            Cast a Value to z data type if it differs from the current dtype;
            otherwise, return the original Value.
            Returns:
                Value: a new Value with z dtype
            )_supported_dtype_conversionsitemsr6   __doc__rE   )methodsmethod_nameZtarget_dtyper   method_implr   r<   r=    _create_dtype_conversion_methods  s   
z<monkey_patch_value.<locals>._create_dtype_conversion_methodsc                 S  s   |  |jS rh   r   )rS   otherr<   r<   r=   type_as     z#monkey_patch_value.<locals>.type_asc                        | d|S N      ?scalerO   rH   rw   r<   r=   _scalar_add_     z(monkey_patch_value.<locals>._scalar_add_c                   s     | d| S r   r   r   rw   r<   r=   _scalar_sub_  s   z(monkey_patch_value.<locals>._scalar_sub_c                   r   )N      r   r   rw   r<   r=   _scalar_rsub_  r   z)monkey_patch_value.<locals>._scalar_rsub_c                   s     | |dS )N        r   r   rw   r<   r=   _scalar_mul_  r   z(monkey_patch_value.<locals>._scalar_mul_c                   s     | d| dS )Nr   r   r   r   rw   r<   r=   _scalar_div_  s   z(monkey_patch_value.<locals>._scalar_div_c                   s     | ddS )Nr   r   r   rO   rw   r<   r=   _scalar_neg_  r   z(monkey_patch_value.<locals>._scalar_neg_c                   
     | S rh   )absr   rw   r<   r=   _scalar_abs_  r   z(monkey_patch_value.<locals>._scalar_abs_Fc                   s&    fdd}d|_ | |_|S )Nc                   s  t |tr| jtv r | tj} d ur| |S n2t |trKt|}jkr4| jtv r4| tj} | jj	krA| tj
} d urJ| |S n	 | }t |ts}rt| jD ]}|dk rht| ||} nqZjj| j||}n	jjg ||}r| }|} |}| |}|S )Nr   )rB   r   rI   _supported_int_dtype_r   ZFLOAT32r   dividerz   r   INT64r
   rD   rM   r~   ZcreationZfill_constant)rS   Z	other_varZ	lhs_dtypeelemtmprL   )r{   rx   
python_apireverserP   scalar_methodr<   r=   r>     sX   




	




z>monkey_patch_value.<locals>._binary_creator_.<locals>.__impl__z
            Args:
                self(Value): left hand Value
                other_var(Value|float|int): right hand Value

            Returns:
                Value
            )r   r6   )r   r   r   r   r>   r{   rx   rP   )r   r   r   r=   _binary_creator_  s   Hz,monkey_patch_value.<locals>._binary_creator_c                   r   )a  
        Returns the number of elements for current Value, which is a int64 Value with shape [] .

        Returns:
            Value, the number of elements for current Value

        Examples:
            .. code-block:: python

            >>> import paddle
            >>> paddle.enable_static()
            >>> startup_prog = paddle.static.Program()
            >>> main_prog = paddle.static.Program()
            >>> with paddle.static.program_guard(startup_prog, main_prog):
            ...     x = paddle.assign(np.random.rand(2, 3, 4).astype("float32"))
            ...     (output_x,) = exe.run(main_program, fetch_list=[x.size])
            ...     print(f"value's size is: {output_x}")
            ...
            value's size is: 24
        )rs   rR   rw   r<   r=   _size_/  s   
z"monkey_patch_value.<locals>._size_c                 S  s4   t | jdkr	| S tttt | j}t| |S )aZ  

        Permute current Value 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	   )rb   rD   listreversedrn   r   	transposerS   permr<   r<   r=   _T_G  s   zmonkey_patch_value.<locals>._T_c                 S  s\   t | jdk rtdt | j dttt | j}|d |d |d< |d< t| |S )al  

        Permute current Value with its last two dimensions reversed.

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

        Examples:
            .. code-block:: python

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

                >>> x = paddle.ones(shape=[2, 3, 5])
                >>> x_mT = x.mT

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

           zTensor.ndim(z/) is required to be greater than or equal to 2.r@   )rb   rD   rN   r   rn   r   r   r   r<   r<   r=   _mT_d  s   z monkey_patch_value.<locals>._mT_rI   devicerequires_grad
pin_memorysizer   
fill_valuebool | float | paddle.TensorrI   DTypeLike | Noner   PlaceLike | Noner   r   r   c                  s2   |du r| j }|du r| j} j||||||dS )a$  

        Returns a Tensor of size ``size`` filled with ``fill_value``.
        By default, the returned Tensor has the same dtype and place as this tensor.

        Examples:
            .. code-block:: python

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

                >>> x = paddle.ones(shape=[2, 3, 5])
                >>> x_new = x.new_full([2, 3], 3.14, dtype="float64", device="cpu")

                >>> exe = paddle.static.Executor()
                >>> x_new_np = exe.run(paddle.static.default_main_program(), fetch_list=[x_new])[0]
                >>> print(x_new_np.shape)
                (2, 5, 3)
                >>> print(str(x_new_np.dtype))
                'paddle.float64'
                >>> print(x_new_np.place)
                Place(cpu)
        Nr   rI   r\   full)rS   r   r   rI   r   r   r   rw   r<   r=   
_new_full_     !z&monkey_patch_value.<locals>._new_full_c                  s0   |du r| j }|du r| j} j|||||dS )a   

        Returns a Tensor of size ``size`` filled with uninitialized data.
        By default, the returned Tensor has the same dtype and place as this tensor.

        Examples:
            .. code-block:: python

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

                >>> x = paddle.ones(shape=[2, 3, 5])
                >>> x_new = x.new_empty([2, 3], dtype="float64", device="cpu")

                >>> exe = paddle.static.Executor()
                >>> x_new_np = exe.run(paddle.static.default_main_program(), fetch_list=[x_new])[0]
                >>> print(x_new_np.shape)
                (2, 3)
                >>> print(str(x_new_np.dtype))
                'paddle.float64'
                >>> print(x_new_np.place)
                Place(cpu)
        Nr   )rI   r\   emptyrS   r   rI   r   r   r   rw   r<   r=   _new_empty_  s   !z'monkey_patch_value.<locals>._new_empty_c                  2   |du r| j }|du r| j} j|d||||dS )a  

        Returns a Tensor of size ``size`` filled with ``1``.
        By default, the returned Tensor has the same dtype and place as this tensor.

        Examples:
            .. code-block:: python

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

                >>> x = paddle.ones(shape=[2, 3, 5])
                >>> x_new = x.new_ones([2, 3], dtype="float64", device="cpu")

                >>> exe = paddle.static.Executor()
                >>> x_new_np = exe.run(paddle.static.default_main_program(), fetch_list=[x_new])[0]
                >>> print(x_new_np.shape)
                (2, 3)
                >>> print(str(x_new_np.dtype))
                'paddle.float64'
                >>> print(x_new_np.place)
                Place(cpu)
        Nr	   r   r   r   rw   r<   r=   
_new_ones_  r   z&monkey_patch_value.<locals>._new_ones_c                  r   )a  

        Returns a Tensor of size ``size`` filled with ``0``.
        By default, the returned Tensor has the same dtype and place as this tensor.

        Examples:
            .. code-block:: python

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

                >>> x = paddle.ones(shape=[2, 3, 5])
                >>> x_new = x.new_zeros([2, 3], dtype="float64", device="cpu")

                >>> exe = paddle.static.Executor()
                >>> x_new_np = exe.run(paddle.static.default_main_program(), fetch_list=[x_new])[0]
                >>> print(x_new_np.shape)
                (2, 3)
                >>> print(str(x_new_np.dtype))
                'paddle.float64'
                >>> print(x_new_np.place)
                Place(cpu)
        Nr   r   r   r   rw   r<   r=   _new_zeros_  r   z'monkey_patch_value.<locals>._new_zeros_c                 S     d}t t|)Na              int(Tensor) is not supported in static graph mode. Because it's value is not available during the static mode.
            It's usually triggered by the logging implicitly, for example:
                >>> logging.info("The value of x is: {int(x)}")
                                                          ^ `x` is Tensor, `int(x)` triggers int(Tensor)

                There are two common workarounds available:
                If you are logging Tensor values, then consider logging only at dynamic graphs, for example:

                    Modify the following code
                    >>> logging.info("The value of x is: {int(x)}")
                    to
                    >>> if paddle.in_dynamic_mode():
                    ...     logging.info("The value of x is: {int(x)}")

                If you need to convert the Tensor type, for example:
                    Modify the following code
                    >>> x = int(x)
                    to
                    >>> x = x.astype("int64")
        ro   textwrapdedentrS   	error_msgr<   r<   r=   _int_@  s   z!monkey_patch_value.<locals>._int_c                 S  r   )Na              float(Tensor) is not supported in static graph mode. Because it's value is not available during the static mode.
            It's usually triggered by the logging implicitly, for example:
                >>> logging.info("The value of x is: {float(x)}")
                                                            ^ `x` is Tensor, `float(x)` triggers float(Tensor)

                There are two common workarounds available:
                If you are logging Tensor values, then consider logging only at dynamic graphs, for example:

                    Modify the following code
                    >>> logging.info("The value of x is: {float(x)}")
                    to
                    >>> if paddle.in_dynamic_mode():
                    ...     logging.info("The value of x is: {float(x)}")

                If you need to convert the Tensor type, for example:
                    Modify the following code
                    >>> x = float(x)
                    to
                    >>> x = x.astype("float64")
        r   r   r<   r<   r=   _float_Y     z#monkey_patch_value.<locals>._float_c                 S  r   )Na              bool(Tensor) is not supported in static graph mode. Because it's value is not available during the static mode.
            If you haven't call bool(Tensor) explicitly, it's usually triggered by the control flow implicitly, for example:
                >>> if x > 0:
                       ^ `x` is Tensor, `x` > 0 is also a Tensor, `if x > 0` triggers bool(Tensor)
                ...     y = y + 1

            There are two common workarounds available:
            If you are checking for Tensor values, then consider checking only at dynamic graphs, for example:

                Modify the following code
                >>> if x > 0:
                ...     raise ValueError("x should be positive")
                to
                >>> if paddle.in_dynamic_mode() and x < 0:
                >>>     raise ValueError("x should be positive")

            If you need to control the flow of execution based on the value of the Tensor, then you need to rewrite the code as a control flow, for example:

                Modify the following code
                >>> if x < y:
                ...     y = y + 1
                ... else:
                ...     y = y - 1
                to
                >>> pred = paddle.less_than(x=x, y=y, name=None)
                >>> y = paddle.static.nn.cond(pred, lambda: y + 1, lambda: y - 1)
                For more info, please refer to https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/static/nn/cond_cn.html
            r   r   r<   r<   r=   _bool_q  s   z"monkey_patch_value.<locals>._bool_c                 S  r   )Na(              complex(Tensor) is not supported in static graph mode. Because it's value is not available during the static mode.
            It's usually triggered by the logging implicitly, for example:
                >>> logging.info("The value of x is: {complex(x)}")
                                                              ^ `x` is Tensor, `complex(x)` triggers complex(Tensor)

                There are two common workarounds available:
                If you are logging Tensor values, then consider logging only at dynamic graphs, for example:

                    Modify the following code
                    >>> logging.info("The value of x is: {complex(x)}")
                    to
                    >>> if paddle.in_dynamic_mode():
                    ...     logging.info("The value of x is: {complex(x)}")

                If you need to convert the Tensor type, for example:
                    Modify the following code
                    >>> x = complex(x)
                    to
                    >>> x = x.astype("complex64")
        r   r   r<   r<   r=   	_complex_  r   z%monkey_patch_value.<locals>._complex_c                   r   )a  
        Returns a new static Value, which is the clone of the original static
        Value. It remains in the current graph, that is, the cloned Value
        provides gradient propagation. Calling ``out = tensor.clone()`` is same
        as ``out = assign(tensor)`` .

        Returns:
            Value, The cloned Value.

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> paddle.enable_static()

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

        )ZassignrR   rw   r<   r=   clone  s   
z!monkey_patch_value.<locals>.clonec                 S     dS )aJ  
        **Notes**:
            **1. This API is ONLY available in Dygraph mode**

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

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

        Returns:  None

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> 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
        Nr<   rR   r<   r<   r=   clear_gradient  s   "z*monkey_patch_value.<locals>.clear_gradientc                 S  s<   |   std|  ddlm}m} |||| | d dS )zL
        Notes:
           The type of Value must be Tensor Array.

        zGOnly Value with DenseTensorArray support `append` method, but received r   )array_lengtharray_write)ri   rJ   arrayN)is_dense_tensor_array_typero   Zpaddle.tensor.arrayr   r   )rS   rO   r   r   r<   r<   r=   rE     s   z"monkey_patch_value.<locals>.appendc                   s>   |   std|  t|dkrd}n|d } j| |S )a  
        The type of Value must be Tensor Array.
        When self is TensorArray, calling pop is similar to Python's pop on list.
        This interface is used to simplify dygraph to static graph operations.

        Args:
            self(Value): The source variable, which must be DenseTensorArray
            *args: optional, a int means index.
        Returns:
            Value: self[index]
        zDOnly Value with DenseTensorArray support `pop` method, but received r   r@   )r   ro   rb   Z_pir_opsZ	array_pop)rS   r8   idxrw   r<   r=   pop  s   zmonkey_patch_value.<locals>.popc                 S  
   t | S rh   )r   Zsparse_to_denserR   r<   r<   r=   to_dense  r   z$monkey_patch_value.<locals>.to_densec                 S  r   rh   )r   Zsparse_valuesrR   r<   r<   r=   values  r   z"monkey_patch_value.<locals>.valuesc                 S  r   rh   )r   Zsparse_indicesrR   r<   r<   r=   indices  r   z#monkey_patch_value.<locals>.indicesc                   sN    j jj  sJ d|  s|  r# j|  |}| | d S t	d)Nz3We only support call 'set_shape' in to_static mode.zBCurrently, we can only set shape for dense and selected_row tensor)
baseZdygraphZin_to_static_modeZis_dense_tensor_typeZis_selected_row_typerm   Zcreate_shaped_typerp   set_typerN   )rS   rD   rp   rw   r<   r=   	set_shape  s   z%monkey_patch_value.<locals>.set_shapec                 S  s   t t| S rh   )hashidrR   r<   r<   r=   
value_hash"  r   z&monkey_patch_value.<locals>.value_hashc                   s   |d u r|d u r|d u r S |d ur6t |trj|}nt |jjjjjfr-n	t	dt
|j |d u r=d}n	t |tsFJ d fdd}| |||S )Nzdevice value error, must be str, paddle.CPUPlace(), paddle.CUDAPlace(), paddle.CUDAPinnedPlace(), paddle.XPUPlace() or paddle.CustomPlace(), but the type of device is Tz5blocking value error, must be the True, False or Nonec                   s   |d u r| j }| }||j kr. jjj|jd |j|d}W d    n1 s(w   Y  n|}t| jr>|j|d}|S t| j	rU|durMt
d td}|S t| jra| }|S |}|S )N)r\   r   )rX   TrU   r   )rI   r   Z	frameworkZ_dygraph_place_guardr\   rz   rB   	CUDAPlacerY   CUDAPinnedPlacerV   rW   r   rQ   CPUPlacerT   )tr   rI   rX   Zt_usedZt_castedZnew_t)rx   rS   r<   r=   	transformJ  s4   
z2monkey_patch_value.<locals>._to.<locals>.transform)rB   strr   Z_convert_to_placerA   rF   r   r   r   rN   rp   r6   r   )rS   r   rI   rX   r   rw   rR   r=   _to%  s4   
zmonkey_patch_value.<locals>._toc           	   
     sJ  t |}t |}|| dks|| dkrtdh d}t| | }t |dkr4tdtt| d#ddd$d	d
d#dd	G dd d 
fdd
fdd
fddd% fddd& fdd fdd 	f
dd }||i |}|d!d}|dur|d! |j|d"< |j	 | j
d'i |S )(a  
        Performs Tensor dtype and/or device conversion. A paddle.dtype and place
        are inferred from the arguments of ``self.to(*args, **kwargs)``.There are
        three ways to call `to`:

            1. to(dtype, blocking=True)
            2. to(device, dtype=None, blocking=True)
            3. to(other, blocking=True)

        Returns:
            Tensor: self

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> x = paddle.to_tensor([1,2,3])
                >>> print(x)
                Tensor(shape=[3], dtype=int64, place=Place(gpu:0), stop_gradient=True,
                    [1, 2, 3])

                >>> x = x.to("cpu")
                >>> print(x.place)
                Place(cpu)

                >>> x = x.to("float32")
                >>> print(x.dtype)
                paddle.float32

                >>> x = x.to("gpu", "int16")
                >>> print(x)
                Tensor(shape=[3], dtype=int16, place=Place(gpu:0), stop_gradient=True,
                    [1, 2, 3])
                >>> y = paddle.to_tensor([4,5,6])
                >>> y
                Tensor(shape=[3], dtype=int64, place=Place(gpu:0), stop_gradient=True,
                    [4, 5, 6])
                >>> y = y.to(x)
                >>> print(y)
                Tensor(shape=[3], dtype=int16, place=Place(gpu:0), stop_gradient=True,
                    [4, 5, 6])
           r   a  to() received too many arguments - expected one of:
                  * (Union[str, paddle.CPUPlace(), paddle.CUDAPlace(), paddle.CUDAPinnedPlace(), paddle.XPUPlace(), paddle.CustomPlace()]                 device, Union[str, paddle.dtype, numpy.dtype] dtype, bool blocking)
                 * (Union[str, paddle.dtype, numpy.dtype] dtype, bool blocking)
                 * (paddle.Tensor other, bool blocking) >   r   r   rI   rX   z(to() got an unexpected keyword argument Nc                 S     d S rh   r<   )rI   rX   r<   r<   r=   dtype_first_sig      z7monkey_patch_value.<locals>.to.<locals>.dtype_first_sigc                 S  r   rh   r<   )r   rI   rX   r<   r<   r=   device_first_sig  r   z8monkey_patch_value.<locals>.to.<locals>.device_first_sigc                 S  r   rh   r<   )r   rX   r<   r<   r=   tensor_like_first_sig  r   z=monkey_patch_value.<locals>.to.<locals>.tensor_like_first_sigc                   @  s   e Zd ZdS )z.monkey_patch_value.<locals>.to.<locals>._NoArgN)r6   
__module____qualname__r<   r<   r<   r=   _NoArg  rl   r   c                   s0   g d}t |  jtjfpt | to|  |v S )N)r   r   r   r   r   r   r   r   r|   r   r   r   )rB   rI   npr   lower)argZvalid_dtypesrw   r<   r=   is_dtype  s   z0monkey_patch_value.<locals>.to.<locals>.is_dtypec                   s   | d u pt |  jjtfS rh   )rB   rA   rF   r   r   rw   r<   r=   	is_device  s   z1monkey_patch_value.<locals>.to.<locals>.is_devicec                   s   t |  jjS rh   )rB   rm   r
   r   rw   r<   r=   	is_tensor  r   z1monkey_patch_value.<locals>.to.<locals>.is_tensorpositionr   c                   r   )Nc                   s   t | kr
|  S   S rh   )rb   r7   )r   r   r<   r=   extract_positional_arg  s   zgmonkey_patch_value.<locals>.to.<locals>.create_positional_arg_extractor.<locals>.extract_positional_argr<   )r   r  r   r   r=   create_positional_arg_extractor  s   zGmonkey_patch_value.<locals>.to.<locals>.create_positional_arg_extractorkeyr   c                   s    fdd}|S )Nc                   s6   |v rt |krt|  kr| S   S rh   )rb   r   keysr7   )r   r  r   r<   r=   extract_keyword_arg  s
   zamonkey_patch_value.<locals>.to.<locals>.create_keyword_arg_extractor.<locals>.extract_keyword_argr<   )r  r   r  r  r  r   r=   create_keyword_arg_extractor  s   	zDmonkey_patch_value.<locals>.to.<locals>.create_keyword_arg_extractorc                    r   )Nc                   s,   D ]}t || | } s|  S q  S rh   )rB   )r8   r9   	extractorr   )r   
extractorsr<   r=   chain  s
   zGmonkey_patch_value.<locals>.to.<locals>.chain_extractors.<locals>.chainr<   )r  r  r  )r  r=   chain_extractors  s   z8monkey_patch_value.<locals>.to.<locals>.chain_extractorsc                    s   dddddfdddddf	dddddfi}|  D ](\}\}}t|| | } sX||rXt|j| i |}|  |j  S q0td)Nr   r  rI   r  r   r   zNo matching signature found.)r   rB   inspect	signaturebindapply_defaults	argumentsrN   )r8   r9   Zsignature_mapsigr
  	conditionr   Z
bound_args
r   r  r	  r  r   r   r   r   r   r   r<   r=   dispatch_to_signature  sB   



z=monkey_patch_value.<locals>.to.<locals>.dispatch_to_signaturer   rI   rh   )NN)r   r   )r  r   r   r   r<   )rb   ro   setr  nextitergetr   rI   r\   r   )	rS   r8   r9   Z	size_argsZsize_kwargsZ
valid_keysZinvalid_keysr  r   rw   r  r=   toj  s@   ,



	#

zmonkey_patch_value.<locals>.toc                 S  r   )am  
        **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())
        Nr<   rR   r<   r<   r=   numpy     z!monkey_patch_value.<locals>.numpyc                 S  r   )a  
        **Notes**:
            **This API is ONLY available in Dygraph mode**
        Returns a Python list that contains the elements of current :ref:`api_guide_Variable_en`

        Returns:
            list: The Python list containing the elements of current Variable.

        Returns type:
            list: Elements have the same dtype as current Variable

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> import paddle.base as base
                >>> import numpy as np
                >>> data = np.random.uniform(-1, 1, [2, 3]).astype('float32')
                >>> with base.dygraph.guard():
                ...     x = paddle.to_tensor(data)
                ...     print(x.tolist())  # Convert tensor to Python list
        Nr<   rR   r<   r<   r=   tolist/  r  z"monkey_patch_value.<locals>.tolistc                 S  r   )z
        Value don't have 'register_hook' interface in static graph mode
        But this interface can greatly facilitate dy2static.
        So we give a error here.
        Nr<   )rS   hookr<   r<   r=   register_hookI  s   z)monkey_patch_value.<locals>.register_hookreturnc                 S  s   | j  S )a!  
        Whether this Tensor requires gradient computation.

        This is a convenience property that returns the opposite of stop_gradient.
        Setting requires_grad=True is equivalent to setting stop_gradient=False.

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> x = paddle.randn([2, 3])
                >>> print(x.requires_grad)  # False by default
                >>>
                >>> x.requires_grad = False
                >>> print(x.stop_gradient)  # True
        )rG   rR   r<   r<   r=   r   R  s   z)monkey_patch_value.<locals>.requires_gradrH   Nonec                 S  s(   t |tstdt| | | _dS )z
        Set whether this Tensor requires gradient computation.

        Args:
            value (bool): True to enable gradient computation, False to disable.
        z$requires_grad must be bool, but got N)rB   r   ro   rp   rG   )rS   rH   r<   r<   r=   r   f  s
   
r   rT   rY   r\   r]   r_   itemrf   rd   ndimr{   r   r|   r   TZmTZnew_fullZ	new_emptyZnew_onesZ	new_zerosr   r   rE   r   r   __hash__r   r   r   r   r  r  r  r   r   r   r    r!   r"   r#   r&   r(   r'   r)   r,   r-   r*   r+   r$   r%   
__matmul____rmatmul____neg____abs__r.   r/   r0   r1   r2   r3   	__float____int____bool____complex__r	   r   )_getitem_static_setitem_static)NT)r8   r   )FN)r   r   r   r   rI   r   r   r   r   r   r   r   )
r   r   rI   r   r   r   r   r   r   r   )NNN)r!  r   )rH   r   r!  r"  )"propertyr   fake_interface_onlysetterrx   r~   addsubtractmultiplyr   powZfloor_divide	remaindermatmulequal	not_equal	less_thanZ
less_equalgreater_thanZgreater_equalextend_already_patch_valuesetattrr
   Zpaddle.tensorZtensor_method_funchasattrgetattrZmagic_method_funcZbase.variable_indexr/  r0  __getitem____setitem__)8rT   rY   r\   r]   r_   rc   rd   rf   ry   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rE   r   r   r   r   r   r   r   r  r  r  r   r   Zvalue_methodsZdtype_conversion_methodsmethodr   r   Zmagic_methodZorigin_methodimplr/  r0  r<   r   r=   monkey_patch_value   s  
$


9*Y

%/-.. 
#E ,


	
 !"#&+17=DJPVZ^bflrvz~       
               !  "  $
rG  )'
__future__r   r  r   rV   	functoolsr   typingr   r  r   rx   r   Zpaddle.base.libpaddler   Zpaddle.base.wrapped_decoratorr   Zpaddle.utils.decorator_utilsr    r
   Zpaddle._typingr   r   r   r?  ZBOOLZUINT8ZINT8ZINT16ZINT32r   r   r   ZSUPPORT_PROMOTION_OPSr?   r2  rM   rG  r<   r<   r<   r=   <module>   s   	
