o
    #jO                     @   s|   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a	ej
ejejejejejgZdd	 ZeeZd
d Zdd ZdS )    N)_C_ops)DataType)wrap_decorator   )ValueFc                    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 Y/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddle/pir/math_op_patch.py__impl__%   s
   
z'_fake_interface_only_.<locals>.__impl__r   )r   r   r   r   r   _fake_interface_only_$   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   float	enumerateshapeappendZpaddle.frameworkr   r   Zfull_batch_size_likeZPlaceZstop_gradient)	Zref_varvaluedtypeZ	batch_dimZ	out_shapeidr   outr   r   r   create_tensor_with_batchsize3   s$   r   c                     s  dd dd } dMdd}dd	 }t d
d }dd }dd }dd }fdd fdd}fdd}fdd}	fdd}
fdd}		 dN fdd 	}t fd!d"}fd#d$}td%d& }d'd( }d)d lg d*| fd+|fd,|fd-|fd.|fd/|fd0|fd1 fd2|fd3|fd4|fd5|fd6|d6jjd|fd7|d7jjd|fd8|d8jjd|fd9|d9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dA|dAjjdd fdB|dBjj	dd fdC|dCjj
dd fdD|dDjjdd fdE|dEjjdd fdF|dFjjdd fdG|dGjjdd fdH|dHjjdd fdI|dIjjdd f}ts|D ]}|d) }|dJ }tt|| qd)d ljjD ]}tt|rqtj|d }|rtt|| qjjD ]\}}tj|d }|rtt|| qdKdLlm} |t_dad S d S )ONc                 S   s   z| j }W |S    td)NzCannot get data type from var)r   
ValueError)varr   r   r   r   safe_get_dtypeN   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   cpuU   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.Tz2blocking is not supported, and it will be ignored.r   )warningswarnr   r"   )r$   Z	device_idblockingr   r   r   cudal   s
   

z monkey_patch_value.<locals>.cudac                 S   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 warnning here and return None.
        zaValue do not have 'place' interface for pir graph mode, try not to use it. None will be returned.N)r&   r'   r#   r   r   r   place   s   z!monkey_patch_value.<locals>.placec                 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
        lenr   r#   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
        r,   r#   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
        r,   r#   r   r   r   dim   r0   zmonkey_patch_value.<locals>.dimc                 S   s"   t | jdkrtd| j | 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
        r   z5Required input var should be 1-D Value, but received )r-   r   	TypeErrorr#   r   r   r   _item   s
   
z!monkey_patch_value.<locals>._itemc                    s$   t |ts jj|}t| |S )a  
        **Notes**:

        Cast a Value to a specified data type.

        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

        )r   r   Zpirr   Zconvert_np_dtype_to_dtype_r   cast)r$   r   paddler   r   astype   s   
!z"monkey_patch_value.<locals>.astypec                         | d|S N      ?scaler    r   r5   r   r   _scalar_add_     z(monkey_patch_value.<locals>._scalar_add_c                    s     | d| S r9   r;   r=   r5   r   r   _scalar_sub_  s   z(monkey_patch_value.<locals>._scalar_sub_c                    r8   )Ng      r;   r=   r5   r   r   _scalar_rsub_  r?   z)monkey_patch_value.<locals>._scalar_rsub_c                    s     | |dS )N        r;   r=   r5   r   r   _scalar_mul_  r?   z(monkey_patch_value.<locals>._scalar_mul_c                    s     | d| dS )Nr:   rB   r;   r=   r5   r   r   _scalar_div_  s   z(monkey_patch_value.<locals>._scalar_div_Fc                    s&    fdd}d|_ | |_|S )Nc                    sN  t |tr| jtv r | tj} d ur| |S n%t |tr>t|}jkr4| jtv r4| tj d ur=| |S n	 | }|}t |t	srri| j
D ]}|dk r]t| ||} nqOjj| j
||}n	jjg ||}|}||kr||}r| }|} |}jkr| jtv r| tj} |tj}| |}|S )Nr   )r   r   r   _supported_int_dtype_r   ZFLOAT32intdivider4   r   r   r   tensorZcreationZfill_constant)r$   Z	other_varZ	lhs_dtypeZother_var_valueelemZ	rhs_dtypetmpr   )r7   r6   
python_apireverser!   scalar_methodr   r   r   "  sd   




	






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
            )__doc__r	   )method_namerK   rL   rM   r   r7   r6   r!   )rK   rL   rM   r   _binary_creator_  s   Pz,monkey_patch_value.<locals>._binary_creator_c                    
     | S )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
        )Znumelr#   r5   r   r   _size_}  s   
z"monkey_patch_value.<locals>._size_c                    rR   )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assignr#   r5   r   r   clone  s   
z!monkey_patch_value.<locals>.clonec                 S   s   dS )a  
        **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 paddle.base as base
                >>> import numpy as np

                >>> x = np.ones([2, 2], np.float32)
                >>> inputs2 = []
                >>> for _ in range(10):
                >>>     tmp = base.dygraph.base.to_variable(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   r#   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 )zS
        **Notes**:
           **The type Value must be LoD Tensor Array.

        zQOnly Value with pd_op.tensor_array support `append` method, but received type: {}r   )array_lengtharray_write)xr   arrayN)Zis_dense_tensor_array_typer2   formattypeZpaddle.tensor.arrayrV   rW   )r$   r    rV   rW   r   r   r   r     s   z"monkey_patch_value.<locals>.appendr   r%   r)   r*   itemr1   r/   ndimr7   sizerT   rU   r   __add____radd____sub____rsub____mul____rmul____div____truediv__Z__rdiv____rtruediv____pow____rpow____floordiv____mod__
__matmul____ne____lt____le____gt____ge__r      )_getitem_static)NT)FN)propertyfake_interface_onlyr6   rH   addsubtractmultiplyrG   powZfloor_divide	remaindermatmul	not_equal	less_thanZ
less_equalgreater_thanZgreater_equal_already_patch_valuesetattrr   Zpaddle.tensorZtensor_method_funchasattrgetattrZmagic_method_funcZbase.variable_indexrs   __getitem__)r%   r)   r*   r.   r/   r1   r3   r>   r@   rA   rC   rD   rQ   rS   rT   rU   r   Zvalue_methodsmethodrO   Zmethod_implZmagic_methodZorigin_methodimplrs   r   rP   r   monkey_patch_valueM   sT  
$

%a
$	
%,28>BFJNTXbfjnrzr   )r&   r6   r   Zpaddle.base.libpaddler   Zpaddle.base.wrapped_decoratorr    r   r   ZBOOLZUINT8ZINT8ZINT16ZINT32ZINT64rE   r   ru   r   r   r   r   r   r   <module>   s"   
