o
    "je                     @   s  d dl Z d dlZd dlmZ ddlmZ ddlmZmZm	Z	 ddl
mZ ejjjejjjejjjejjjejjjejjjgZg dZg d	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-d.Zd/ad0d1 ZdS )2    N)in_to_static_mode   )core)Variablestatic_onlyunique_name   )OpProtoHolder)__eq____ne____lt____le____gt____ge__)__add____radd____sub____rsub____mul____rmul__r   zA + Br   zA += Br   zA - Br   zA -= Br   zA * Br   zA *= B__div__zA / B__truediv____rdiv__zA /= B__rtruediv____pow__zA ** B__rpow__zA **= B__floordiv__zA //B__mod__zA % B
__matmul__zA @ Br
   zA == Br   zA != BzA < BzA <= BzA > BzA >= B)r   r   r   r   Fc                     s  dd dd dd fddfd	d
} fddfddfddt fdd}t dpfdd	}t dd }fddt dd }t dd }t dd }fd d!  fd"d#}td$d% }d&d' }	d(d) }
 fd*d+} fd,d-} fd.d/} fd0d1} fd2d3}	 dqfd5d6	}fd7d8}fd9d:}fd;d<}g d=|fd>fd?|fd@|fdA|fdB|fdC|fdD|fdE|
fdF|	fdG|fdH|dHdId4|fdJ|dJdId4|fdK|dKdLd4|fdM|dMdLd|fdN|dNdOd4|fdP|dPdOd4|fdQ|dQdRd4|fdS|dSdRd4|fdT|dTdRdd fdU|dUdRdd fdV|dVdWd4d fdX|dXdWdd fdY|dYdZd4d fd[|d[d\d4d fd]|d]d^d4d fd_|d_d`d4d fda|dadbd4d fdc|dcddd4d fde|dedfd4d fdg|dgdhd4d fdi|didjd4d fdk|fdl|fdm|f}ts|D ]}|dn }|do }tt|| qdad S dnd l}|jjD ]}tt|rݐqt	|j|d }|rtt|| q|jj
D ]\}}t	|j|d }|rtt|| qdad S )rNc                   S   s
   t dS )Ntmp)r   generate r!   r!   a/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddle/base/layers/math_op_patch.pyunique_tmp_nameH   s   
z.monkey_patch_variable.<locals>.unique_tmp_namec                 S   s    z| j }W |S    td| j)NzCannot get data type from %s)dtype
ValueErrorname)varr$   r!   r!   r"   safe_get_dtypeK   s
   z-monkey_patch_variable.<locals>.safe_get_dtypec                 S   s   | j j S )N)blockprogramcurrent_blockr'   r!   r!   r"   r+   R      z,monkey_patch_variable.<locals>.current_blockc                    s     }| j ||dS )N)r&   r$   
create_var)r)   r$   tmp_namer#   r!   r"   create_new_tmp_varU   s   z1monkey_patch_variable.<locals>.create_new_tmp_varc                    s     }| j |||dS )N)r&   r$   typer.   )r)   r$   r3   r0   r1   r!   r"   create_new_tmp_sparse_varY   s   z8monkey_patch_variable.<locals>.create_new_tmp_sparse_varc                    s@   t |} | |}| jdd|gi|j||dddd d|_|S )NZfill_constantOutF)r$   shapevalueZ	force_cpuT)r3   outputsattrsstop_gradient)float	append_opr$   r:   )r)   r7   r$   r6   r'   )r2   r!   r"   create_tensor]   s   
z,monkey_patch_variable.<locals>.create_tensorc                    s    | ||g dS )N)r6   r!   )r)   r7   r$   )r=   r!   r"   create_scalarn      z,monkey_patch_variable.<locals>.create_scalarc           	   	      s   t | tsJ t|}| } ||}d}g }t| jD ]\}}|dk r7|dk r1|}|| q|d q|| q|dksCJ |jdd|gid| gi||||ddd	 d|_|S )
Nr   r   Zfill_constant_batch_size_liker5   ZInput)r6   r7   Zinput_dim_idxZoutput_dim_idxT)r3   r8   inputsr9   r:   )
isinstancer   r;   	enumerater6   appendr<   r:   )	Zref_varr7   r$   r)   r'   Z	batch_dimZ	out_shapeidr2   r+   r!   r"   create_tensor_with_batchsizeq   s6   
z;monkey_patch_variable.<locals>.create_tensor_with_batchsizec                    sT    | } }|j || j| j| jddd}ddi}|jdd| gid|gi|d	 |S )
a  
        In dy2static, Variable 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()
        FTr&   r$   r6   r3   Zpersistabler:   dst_place_typer   memcpyXr5   r3   rA   r8   r9   )r/   r$   r6   r3   r<   )selfr)   r0   outputr9   r+   r#   r!   r"   cpu   s$   	z"monkey_patch_variable.<locals>.cpuTc                    sx   |dur	t d |durt d  | } }|j|| j| j| jddd}ddi}|jd	d
| gid|gi|d |S )a  
        In dy2static, Variable also needs cpu() and cuda() interface.
        But, the underneath operator has only forward op but not backward one.

        Args:
            self(Variable): 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.FrI   rJ   r   rK   rL   r5   rM   )warningswarnr/   r$   r6   r3   r<   )rN   Z	device_idblockingr)   r0   rO   r9   rP   r!   r"   cuda   s,   

	z#monkey_patch_variable.<locals>.cudac                 S   s   t d dS )z
        Variable 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.
        zgVariable do not have 'place' interface for static graph mode, try not to use it. None will be returned.N)rR   rS   rN   r!   r!   r"   place   s   z$monkey_patch_variable.<locals>.placec                    sF   | } ||}|j dd| gid|gi| j|jdd | j|_|S )ah  
        **Notes**:
            **The variable must be a** :ref:`api_paddle_Tensor`

        Cast a variable to a specified data type.

        Args:

            self(Variable): The source variable

            dtype: The target data type

        Returns:
            Variable: Variable with new dtype

        Examples:
            In Static Graph Mode:

            .. code-block:: python

                >>> import paddle
                >>> import paddle.base as base
                >>> paddle.enable_static()
                >>> startup_prog = paddle.static.Program()
                >>> main_prog = paddle.static.Program()
                >>> with base.program_guard(startup_prog, main_prog):
                ...     original_variable = paddle.static.data(name = "new_variable", shape=[2,2], dtype='float32')
                ...     new_variable = original_variable.astype('int64')
                ...     print("new var's dtype is: {}".format(new_variable.dtype))
                ...
                new var's dtype is: paddle.int64

            In Dygraph Mode:

            .. code-block:: python

                >>> import paddle.base as base
                >>> import numpy as np

                >>> x = np.ones([2, 2], np.float32)
                >>> with base.dygraph.guard():
                ...     original_variable = base.dygraph.to_variable(x)
                ...     print("original var's dtype is: {}, numpy dtype is {}".format(original_variable.dtype, original_variable.numpy().dtype))
                ...     new_variable = original_variable.astype('int64')
                ...     print("new var's dtype is: {}, numpy dtype is {}".format(new_variable.dtype, new_variable.numpy().dtype))
                ...
                original var's dtype is: paddle.float32, numpy dtype is float32
                new var's dtype is: paddle.int64, numpy dtype is int64
        castrL   r5   )Zin_dtypeZ	out_dtyperM   )r<   r$   r:   )rN   r$   r)   outrG   r!   r"   astype   s   2
z%monkey_patch_variable.<locals>.astypec                 S   s   t |tst r	 ddlm} ||}n	tdt| | jtjj	j
kr-td| jddlm}m} |||| | d dS )zV
        **Notes**:
           **The type variable must be LoD Tensor Array.

        r   )	to_tensorz4Required input var should be Variable, but received zZOnly Variable with VarType.LOD_TENSOR_ARRAY support `append` method, but received type: {})array_lengtharray_write)xrE   arrayN)rB   r   r   Zpaddle.tensor.creationr[   	TypeErrorr3   r   VarDescVarTypeLOD_TENSOR_ARRAYformatZpaddle.tensor.arrayr\   r]   )rN   r'   r[   r\   r]   r!   r!   r"   rD   7  s    

z%monkey_patch_variable.<locals>.appendc                 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   z8Required input var should be 1-D Variable, but received )lenr6   r`   rV   r!   r!   r"   _itemR  s
   
z$monkey_patch_variable.<locals>._itemc                 W   s<   ddl m} | jtjjjkrtd| j|| g|R  S )a  
        The type variable must be LoD Tensor Array.
        When self is LoDTensorArray, calling pop is similar to Python's pop on list.
        This interface is used to simplify dygraph to static graph operations.

        Args:
            self(Variable): The source variable, which must be LOD_TENSOR_ARRAY
            *args: optional, a int means index.
        Returns:
            Variable: self[index]
        r   )_run_paddle_popzWOnly Variable with VarType.LOD_TENSOR_ARRAY support `pop` method, but received type: {})	Z&paddle.jit.dy2static.convert_operatorsrg   r3   r   ra   rb   rc   r`   rd   )rN   argsrg   r!   r!   r"   pop^  s   z"monkey_patch_variable.<locals>.popc                    s<   | } || j }|jdd| gid|gi||dd |S )NscalerL   r5   )rj   biasrM   r$   r<   )r'   rj   rk   r)   rY   rG   r!   r"   _scalar_op_u  s   z*monkey_patch_variable.<locals>._scalar_op_c                    s    | ddS )N              r!   r,   rm   r!   r"   _neg_  r-   z$monkey_patch_variable.<locals>._neg_c                 S   
   t | jS )a  
        Returns the dimension of current Variable

        Returns:
            the dimension

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> paddle.enable_static()

                >>> # create a static Variable
                >>> x = paddle.static.data(name='x', shape=[3, 2, 1])
                >>> # print the dimension of the Variable
                >>> print(x.ndim)
                3
        re   r6   rV   r!   r!   r"   _ndim  s   
z$monkey_patch_variable.<locals>._ndimc                 S   rr   )a  
        Returns the dimension of current Variable

        Returns:
            the dimension

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> paddle.enable_static()

                >>> # create a static Variable
                >>> x = paddle.static.data(name='x', shape=[3, 2, 1])
                >>> # print the dimension of the Variable
                >>> print(x.ndimension())
                3
        rs   rV   r!   r!   r"   
ndimension     
z)monkey_patch_variable.<locals>.ndimensionc                 S   rr   )a  
        Returns the dimension of current Variable

        Returns:
            the dimension

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> paddle.enable_static()

                >>> # create a static Variable
                >>> x = paddle.static.data(name='x', shape=[3, 2, 1])
                >>> # print the dimension of the Variable
                >>> print(x.dim())
                3
        rs   rV   r!   r!   r"   dim  rv   z"monkey_patch_variable.<locals>.dimc                        | d|S N      ?r!   r'   r7   rp   r!   r"   _scalar_add_  r-   z+monkey_patch_variable.<locals>._scalar_add_c                    s    | d| S ry   r!   r{   rp   r!   r"   _scalar_sub_  s   z+monkey_patch_variable.<locals>._scalar_sub_c                    rx   )Nrn   r!   r{   rp   r!   r"   _scalar_rsub_  r-   z,monkey_patch_variable.<locals>._scalar_rsub_c                    s    | |dS )Nro   r!   r{   rp   r!   r"   _scalar_mul_  r-   z+monkey_patch_variable.<locals>._scalar_mul_c                    s    | d| dS )Nrz   ro   r!   r{   rp   r!   r"   _scalar_div_  r?   z+monkey_patch_variable.<locals>._scalar_div_Fc                    sH   	 
fdd}t  j}d| d|_ |_|S )Nc              
      sr  t |tr| jtv r | d} 
d ur
| |S n"t |tr:t|}dkr0| jtv r0 | d} 
d ur9
| |S n	 	| }t |tsmrd| jD ]}|dk rW| ||} nqI| ||| jd}n	| ||d}	|}||krtv rt	||rt
||}td d| d| d	|  tjd
dd ||kr ||}||kr | |} n ||}n ||}r| }|} |}dks̈dkr| jtv rۈ | d}  |d}tv r| dd}n
| 	| d}d}|jdkr#|jd dkr#t d }	|	d }
|	d }tjd|
|t t td | j| g|gdd|id|id |S )NZfloat32elementwise_divr   )r$   r6   )r7   r$   zThe input dtypes of OP z are z and z&, the output will be auto-promoted to ignorezThe input dtypes of OP)messagedividebool)r$   r@   r   r   a  {}:{}
The behavior of expression {} has been unified with {}(X, Y, axis=-1) from Paddle 2.0. If your code works well in the older versions but crashes in this version, try to use {}(X, Y, axis=0) instead of {}. This transitional warning will be dropped in the future.)category)rL   Yr5   axisrM   )rB   r;   r$   _supported_int_dtype_intr   r6   SUPPORT_PROMOTION_OPSr   Zneed_type_promotionZget_promote_dtyperR   rS   filterwarningscompare_opsndiminspectstackrd   EXPRESSION_MAPDeprecationWarningr<   )rN   Z	other_varZ	lhs_dtypeelemZ	rhs_dtypeZcommon_dtyper   rY   r   r   	file_nameline_num)rZ   r2   r>   r=   rH   r+   method_nameop_typereverser(   scalar_methodr!   r"   __impl__  s   




	











zAmonkey_patch_variable.<locals>._binary_creator_.<locals>.__impl__z	
        z
        Args:
            self(Variable): left hand variable
            other_var(Variable|float|int): right hand variable

        Returns:
            Variable
        )r	   instanceZget_op_protocomment__doc____name__)r   r   r   r   r   r   )rZ   r2   r>   r=   rH   r+   r(   )r   r   r   r   r"   _binary_creator_  s     
	z/monkey_patch_variable.<locals>._binary_creator_c                    6   | } || j }|jdd| gid|gii d |S )NZsparse_valuesr^   rY   rM   rl   r'   r)   rY   rG   r!   r"   valuesi     z%monkey_patch_variable.<locals>.valuesc                    r   )NZsparse_indicesr^   rY   rM   rl   r   rG   r!   r"   indicest  r   z&monkey_patch_variable.<locals>.indicesc                    r   )NZsparse_to_denser^   rY   rM   rl   r   rG   r!   r"   to_dense  r   z'monkey_patch_variable.<locals>.to_dense__neg__rZ   rQ   rU   rW   rD   itemri   rw   ru   r   r   Zelementwise_addr   r   Zelementwise_subr   r   Zelementwise_mulr   r   r   r   r   r   r   Zelementwise_powr   r   Zelementwise_floordivr   Zelementwise_modr   Z	matmul_v2r
   equalr   	not_equalr   	less_thanr   Z
less_equalr   greater_thanr   Zgreater_equalr   r   r   r   r   )NT)FN)r   property_already_patch_variablesetattrr   Zpaddle.tensorZtensorZtensor_method_funchasattrgetattrZmagic_method_func)r4   rQ   rU   rW   rD   rf   ri   rq   rt   ru   rw   r|   r}   r~   r   r   r   r   r   r   Zvariable_methodsmethodr   Zmethod_implZpaddleZmagic_methodZorigin_methodimplr!   )	rm   rZ   r2   r>   r=   rH   r+   r(   r#   r"   monkey_patch_variableG   sR  !'4

=



 	
#(.28<@DHNRVWXYZ[\]^br   )r   rR   Zpaddle.base.dygraph.baser    r   Z	frameworkr   r   r   Zlayer_function_generatorr	   ra   rb   ZBOOLZUINT8ZINT8ZINT16ZINT32ZINT64r   r   r   r   r   r   r!   r!   r!   r"   <module>   sr   			
