
    x-j9V                    V   d dl mZ d dlZd dlmZ d dlZd dlad dlmZ d dl	m
Z
 ddlmZ ddlmZ erd d	lmZ d d
lmZ d dlmZ d dlmZmZ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 ej        j        j!        ej        j        j"        gZ#da$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%d.d*Z& G d+ d,e'          Z(d- Z)dS )/    )annotationsN)TYPE_CHECKING)_C_ops)size_args_decorator_patch   )core)convert_np_dtype_to_dtype_)Any)NDArray)Tensor)	DTypeLike	PlaceLike	ShapeLike)__add____radd____sub____rsub____mul____rmul____div____truediv____rdiv____rtruediv__
__matmul__Ffloat16halfbfloat16float32floatfloat64doubleint8charint16shortint32intint64longbool	complex64
complex128)r,   cfloatcdoubledataNDArray[Any]dtyper   devicer   returnr   c                0    t          j        | |||          S N)paddletensor)r/   r1   r2   requires_grads       a/var/www/html/banglarbhumi/venv/lib/python3.11/site-packages/paddle/base/dygraph/math_op_patch.py_rebuild_tensorr:   k   s$     =	      c                  2     e Zd ZU ded<    fdZddZ xZS )
TensorSizez	list[int]as_shapec                    t                                          | t          t          j        |                              }||_        |S r5   )super__new__r'   npprodr>   )clsshapeinstance	__class__s      r9   rA   zTensorSize.__new__|   s7    77??3BGENN(;(;<<!r;   Nc                L    t          j        | j                  }||S ||         S r5   )r6   Sizer>   )selfdimrE   s      r9   __call__zTensorSize.__call__   s'    DM**;LSzr;   r5   )__name__
__module____qualname____annotations__rA   rL   __classcell__)rG   s   @r9   r=   r=   y   sZ             
       r;   r=   c                 $  $% dUd%dV%fd} %fd}dWd
}dXd$dY$fd}dYd}dZd}d[d}d\d}d\d}d\d}	d\d}
t           d\d            }d\d}d\d}t           d\d            }t           dYd            }t           dYd            }d d d!d!d"d]d-}t          d d d!d!d"d^d.            }t          d d d!d!d"d^d/            }t          d d d!d!d"d^d0            }t           d_d1            }|j        d`d4            }dadbd6}t           dcd7            }ddd8}d9|fd:|fd;|fd<|fd=|fd>|fd?|	fd@|
fdA%fdB| fdC| fdD|fdE|fdF|fdG|fd#|fdH|fdI|fdJ|fdK|fdL|fdM|fd*|fdN|fdOdP|fdQ|fg} |            }|                    |           g dR}t          }d5at
          j        j        }|sQ|D ]&}t          ||d           }|rt          |||           '|D ]#} | dS         }| dT         }t          |||           $d S dSd l
at          j        j        D ]A}t          ||          rt          t          j        |d           }|rt          |||           Bt          j        j        D ]3\  }!}"t          t          j        |"d           }#|#rt          ||!|#           4d S )ez
    Similar to monkey_patch_variable.
    The difference is, in dygraph mode, use auto-generated op functions for better performance.
    rJ   r   r1   r   r3   c                    t          |t          j        j        t          j        f          st          |          }| j        |k    r| S t          j        | |          S )a$  

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

        Args:
            dtype: The target data type.

        Returns:
            Tensor: a new Tensor with target dtype

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> import numpy as np

                >>> original_tensor = paddle.ones([2, 2])
                >>> print("original tensor's dtype is: {}".format(original_tensor.dtype))
                original tensor's dtype is: paddle.float32
                >>> new_tensor = original_tensor.astype('float32')
                >>> print("new tensor's dtype is: {}".format(new_tensor.dtype))
                new tensor's dtype is: paddle.float32
        )	
isinstancer   VarDescVarTypeDataTyper	   r1   r   cast)rJ   r1   s     r9   astypez(monkey_patch_math_tensor.<locals>.astype   sS    2 %$,"6!FGG 	6.u55E:K{4'''r;   c                   |                                  r | d          } |d          S |                                 r> |                                 d          }t          j        d            |d          S  | d          S )Nr"   uint8z:Casting complex values to real discards the imaginary part)is_floating_point
is_complexrealloggingwarning)rJ   r7   r^   rY   s      r9   bytez&monkey_patch_math_tensor.<locals>.byte   s    !!## 
	)VD&))F6&'***__ 	)6$))++v..DOL   6$(((6$(((r;   c                     g } t                                           D ]A\  }}fd} ||          }||_        d| d| d|_        |                     ||f           B| S )z?
        Batch create all data type conversion methods
        c                     d fd}|S )NrJ   r   r3   c                     |           S r5    )rJ   rY   r1   s    r9   conversion_methodz}monkey_patch_math_tensor.<locals>._create_dtype_conversion_methods.<locals>.make_conversion_method.<locals>.conversion_method   s    !6$...r;   rJ   r   r3   r   re   )r1   rf   rY   s   ` r9   make_conversion_methodzbmonkey_patch_math_tensor.<locals>._create_dtype_conversion_methods.<locals>.make_conversion_method   s/    / / / / / / / )(r;   z
            Cast a Tensor to z data type if it differs from the current dtype;
            otherwise, return the original Tensor.
            Returns:
                Tensor: a new Tensor with z dtype
            )_supported_dtype_conversionsitemsrM   __doc__append)methodsmethod_nametarget_dtyperh   method_implrY   s        r9    _create_dtype_conversion_methodszBmonkey_patch_math_tensor.<locals>._create_dtype_conversion_methods   s     )E)K)K)M)M 	7 	7%K) ) ) ) ) 10>>K#.K #*# # ,8	# # #K NNK56666r;   otherc                6    |                      |j                  S r5   )rY   r1   )rJ   rr   s     r9   type_asz)monkey_patch_math_tensor.<locals>.type_as   s    {{5;'''r;   varscaler   biasc                J    t          j        | t          |          |d          S )NT)r   rv   r   )ru   rv   rw   s      r9   _scalar_elementwise_op_z9monkey_patch_math_tensor.<locals>._scalar_elementwise_op_   s      |CutT:::r;   c                     | dd          S )Ng      g        re   )ru   ry   s    r9   _neg_z'monkey_patch_math_tensor.<locals>._neg_   s    &&sD#666r;   c                *    |                                  S r5   )absru   s    r9   _abs_z'monkey_patch_math_tensor.<locals>._abs_   s    wwyyr;   complexc                $   t          j        | j                  }|dk    s
J d            |                                 s
J d            |                                 s|                     d          } t          t          j        |                     S )N   z6only one element variable can be converted to complex.$variable's tensor is not initializedr+   )rB   rC   rE   _is_initializedr]   rY   r   arrayru   numels     r9   	_complex_z+monkey_patch_math_tensor.<locals>._complex_   s    	""zzzD zz ""$$LL&LLL$~~ 	***[))Crx}}%%%r;   c                n   t          j        | j                  }|dk    s
J d            |                                 s
J d            | j        t
          j        j        j        k    s| j        t
          j	        j
        k    r|                     d          } t          t          j        |                     S )Nr   z4only one element variable can be converted to float.r   r   )rB   rC   rE   r   r1   r   rU   rV   BF16rW   BFLOAT16rY   r   r   r   s     r9   _float_z)monkey_patch_math_tensor.<locals>._float_   s    	""zzzB zz ""$$LL&LLL$I-222yDM222**Y''CRXc]]###r;   r'   c                n   t          j        | j                  }|dk    s
J d            |                                 s
J d            | j        t
          j        j        j        k    s| j        t
          j	        j
        k    r|                     d          } t          t          j        |                     S )Nr   z3only one element variable can be converted to long.r   r   rB   rC   rE   r   r1   r   rU   rV   r   rW   r   rY   r'   r   r   s     r9   _long_z(monkey_patch_math_tensor.<locals>._long_   s    	""zzzPzzz""$$LL&LLL$I-222yDM222**Y''C28C==!!!r;   c                n   t          j        | j                  }|dk    s
J d            |                                 s
J d            | j        t
          j        j        j        k    s| j        t
          j	        j
        k    r|                     d          } t          t          j        |                     S )Nr   z2only one element variable can be converted to int.r   r   r   r   s     r9   _int_z'monkey_patch_math_tensor.<locals>._int_	  s    	""zzzOzzz""$$LL&LLL$I-222yDM222**Y''C28C==!!!r;   c                   | j         dk    s
J d            | j        t          j        j        j        k    r3t          |                                                                           S | j        t          j        j        j	        k    r3t          |                                 
                                          S | j        d         S )Nr   zlen() of a 0-D tensor is wrong)ndimtyper   rU   rV   VOCABlenvalueget_map_tensorSTRINGSget_string_tensorrE   r~   s    r9   _len_z'monkey_patch_math_tensor.<locals>._len_  s    x!|||=|||8t|+111syy{{1133444X-555syy{{44667779Q<r;   c                n   t          j        | j                  }|dk    s
J d            |                                 s
J d            | j        t
          j        j        j        k    s| j        t
          j	        j
        k    r|                     d          } t          t          j        |                     S )Nr   z;only one element variable can be converted to python index.r   r   r   r   s     r9   _index_z)monkey_patch_math_tensor.<locals>._index_  s    	""zzzI zz ""$$LL&LLL$I-222yDM222**Y''C28C==!!!r;   c                *    t          | j                  S r5   r   rE   r~   s    r9   _ndimz'monkey_patch_math_tensor.<locals>._ndim*  s    39~~r;   c                *    t          | j                  S r5   r   r~   s    r9   
ndimensionz,monkey_patch_math_tensor.<locals>.ndimension.      39~~r;   c                *    t          | j                  S r5   r   r~   s    r9   rK   z%monkey_patch_math_tensor.<locals>.dim1  r   r;   c                *    t          | j                  S r5   )r=   rE   r~   s    r9   _size_z(monkey_patch_math_tensor.<locals>._size_4  s    #)$$$r;   c           	         t          | j                  dk    r| S t          t          t	          t          | j                                                }t          j        | |          }|S )Nr   )r   rE   listreversedranger   	transposeru   permouts      r9   _T_z%monkey_patch_math_tensor.<locals>._T_8  sV    sy>>QJHU3sy>>223344sD))
r;   c                   t          | j                  dk     rt          d| j         d          t	          t          t          | j                                      }|d         |d         c|d<   |d<   t          j        | |          }|S )a  
        Return the last two dimensions of a Tensor transposed.

        Args:
            var (Tensor): The input Tensor, which must have at least 2 dimensions.

        Returns:
            Tensor: A new Tensor with its last two dimensions swapped.

        Examples:
            .. code-block:: pycon

                >>> import paddle
                >>> x = paddle.randn([2, 3, 4])
                >>> x_transposed = x.mT
                >>> x_transposed.shape
                paddle.Size([2, 4, 3])
        r   zTensor.ndim(z/) is required to be greater than or equal to 2.)r   rE   
ValueErrorr   r   r   r   r   r   s      r9   _mT_z&monkey_patch_math_tensor.<locals>._mT_@  s    ( sy>>AXsxXXX   E#ci..))**!"XtBxR$r(sD))
r;   NFr1   r2   r8   
pin_memorysizer   
fill_valuebool | float | paddle.TensorDTypeLike | Noner2   PlaceLike | Noner8   r*   r   c               Z    || j         }|| j        }t          j        ||||||          S )aR  
        Create a new Tensor of specified shape and fill it with a given value.

        Args:
            var (Tensor): A reference Tensor for default dtype and device.
            size (ShapeLike): Shape of the new Tensor.
            fill_value (bool | float | Tensor): Value to fill the Tensor with.
            dtype (DTypeLike, optional): Desired data type of the new Tensor. Defaults to `var.dtype`.
            device (PlaceLike, optional): Device on which to place the new Tensor. Defaults to `var.place`.
            requires_grad (bool, optional): Whether to track gradients. Default: False.
            pin_memory (bool, optional): Whether to pin memory. Default: False.

        Returns:
            Tensor: A new Tensor filled with `fill_value`.

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> x = paddle.ones([2, 2])
                >>> y = x.new_full([3, 3], 5.0)
                >>> y.numpy()
                array([[5., 5., 5.],
                       [5., 5., 5.],
                       [5., 5., 5.]], dtype=float32)
        Nr   r1   placer6   full)ru   r   r   r1   r2   r8   r   s          r9   
_new_full_z,monkey_patch_math_tensor.<locals>._new_full_]  sH    J =IE>YF{'!
 
 
 	
r;   c               X    || j         }|| j        }t          j        |||||          S )a  
        Create a new uninitialized Tensor of the specified shape.

        Args:
            var (Tensor): A reference Tensor for default dtype and device.
            size (ShapeLike): Shape of the new Tensor.
            dtype (DTypeLike, optional): Desired data type of the new Tensor. Defaults to `var.dtype`.
            device (PlaceLike, optional): Device on which to place the new Tensor. Defaults to `var.place`.
            requires_grad (bool, optional): Whether to track gradients. Default: False.
            pin_memory (bool, optional): Whether to pin memory. Default: False.

        Returns:
            Tensor: A new uninitialized Tensor with the specified shape.

        Examples:
            .. code-block:: pycon

                >>> import paddle
                >>> x = paddle.ones([2, 2])
                >>> y = x.new_empty(3, 3)  # type: ignore
                >>> y.shape
                paddle.Size([3, 3])
        Nr2   r8   r   )r1   r   r6   emptyru   r   r1   r2   r8   r   s         r9   _new_empty_z-monkey_patch_math_tensor.<locals>._new_empty_  sE    D =IE>YF|'!
 
 
 	
r;   c               Z    || j         }|| j        }t          j        |d||||          S )a  
        Create a new Tensor of the specified shape filled with ones.

        Args:
            var (Tensor): A reference Tensor for default dtype and device.
            size (ShapeLike): Shape of the new Tensor.
            dtype (DTypeLike, optional): Desired data type of the new Tensor. Defaults to `var.dtype`.
            device (PlaceLike, optional): Device on which to place the new Tensor. Defaults to `var.place`.
            requires_grad (bool, optional): Whether to track gradients. Default: False.
            pin_memory (bool, optional): Whether to pin memory. Default: False.

        Returns:
            Tensor: A new Tensor filled with ones.

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> x = paddle.zeros([2, 2])
                >>> y = x.new_ones(3, 3)  # type: ignore
                >>> y.numpy()
                array([[1., 1., 1.],
                       [1., 1., 1.],
                       [1., 1., 1.]], dtype=float32)
        Nr   r   r   r   s         r9   
_new_ones_z,monkey_patch_math_tensor.<locals>._new_ones_  H    H =IE>YF{'!
 
 
 	
r;   c               Z    || j         }|| j        }t          j        |d||||          S )a  
        Create a new Tensor of the specified shape filled with zeros.

        Args:
            var (Tensor): A reference Tensor for default dtype and device.
            size (ShapeLike): Shape of the new Tensor.
            dtype (DTypeLike, optional): Desired data type of the new Tensor. Defaults to `var.dtype`.
            device (PlaceLike, optional): Device on which to place the new Tensor. Defaults to `var.place`.
            requires_grad (bool, optional): Whether to track gradients. Default: False.
            pin_memory (bool, optional): Whether to pin memory. Default: False.

        Returns:
            Tensor: A new Tensor filled with zeros.

        Examples:
            .. code-block:: python

            >>> import paddle
            >>> x = paddle.ones([2, 2])
            >>> y = x.new_zeros(3, 3)  # type: ignore
            >>> y.numpy()
            array([[0., 0., 0.],
                   [0., 0., 0.],
                   [0., 0., 0.]], dtype=float32)
        Nr   r   r   r   s         r9   _new_zeros_z-monkey_patch_math_tensor.<locals>._new_zeros_  r   r;   c                    | 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
        )stop_gradientrJ   s    r9   r8   z/monkey_patch_math_tensor.<locals>.requires_grad#  s    $ %%%r;   r   Nonec                ~    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.
        $requires_grad must be bool, but got NrT   r*   	TypeErrorr   r   )rJ   r   s     r9   r8   z/monkey_patch_math_tensor.<locals>.requires_grad7  sK     %&& 	DtE{{DD   "'Yr;   Tc                ~    t          |t                    st          dt          |                     | | _        | S )z
        Set whether this Tensor requires gradient computation.

        Args:
            requires_grad (bool): True to enable gradient computation, False to disable.
        r   r   )rJ   r8   s     r9   requires_grad_z0monkey_patch_math_tensor.<locals>.requires_grad_E  sM     -.. 	LtM7J7JLL   "/.r;   c                *    |                                  S )a5  
        Returns the number of bytes allocated on the machine for a single element of the Tensor.

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> x = paddle.randn((2,3),dtype=paddle.float64)
                >>> x.itemsize
                8
        )element_sizer   s    r9   itemsizez*monkey_patch_math_tensor.<locals>.itemsizeS  s       """r;   c                    |                                  }t          | j                  dd         }t          | j                  dd          }| j        }t
          ||||ffS )N   r      )numpystrr   r1   r8   r:   )rJ   proto
data_numpyr   r1   r8   s         r9   _reduce_ex_z-monkey_patch_math_tensor.<locals>._reduce_ex_b  sa    ZZ\\
DJ"%DJ#*	!
 
 	
r;   __neg____abs____complex__	__float____long____int____len__	__index__rY   ra   r[   rt   rK   r   r   TmTnew_full	new_emptynew_ones	new_zerosr   )__array_ufunc__Nr   __reduce_ex__)r   r   r   r   r   r   r   r   r   r   __mod____rmod__r   __rmatmul____gt____ge____lt____le____floordiv____rfloordiv____pow____rpow____eq____ne__r   r   )rJ   r   r1   r   r3   r   rg   )rJ   r   rr   r   r3   r   )ru   r   rv   r   rw   r   r3   r   )ru   r   r3   r   )ru   r   r3   r   )ru   r   r3   r   )ru   r   r3   r'   )ru   r   r   r   r   r   r1   r   r2   r   r8   r*   r   r*   r3   r   )ru   r   r   r   r1   r   r2   r   r8   r*   r   r*   r3   r   )rJ   r   r3   r*   )rJ   r   r   r*   r3   r   )T)r8   r*   r3   r   )rJ   r   r3   r'   )rJ   r   )propertyr   setterextend_already_patch_eager_tensorr   eagerr   getattrsetattrpaddle.tensorr6   r7   tensor_method_funchasattrmagic_method_func)&ra   rq   rt   r{   r   r   r   r   r   r   r   r   r   rK   r   r   r   r   r   r   r   r8   r   r   r   eager_methodsdtype_conversion_methodseager_cpp_level_patchlocal_already_patchlocal_tensorrn   rp   methodmagic_methodorigin_methodimplry   rY   s&                                       @@r9   monkey_patch_math_tensorr     s   ( ( ( (B) ) ) ) ) )    6( ( ( (; ; ; ;
7 7 7 7 7 7   & & & &$ $ $ $	" 	" 	" 	"	" 	" 	" 	"       " " " "    X       % % % X%    X    XB #'#'# 1
 1
 1
 1
 1
 1
f 
 #'#'# ,
 ,
 ,
 ,
 ,
 ,
\ 
 #'#'# /
 /
 /
 /
 /
 /
b 
 #'#'# /
 /
 /
 /
 /
 /
b & & & X&& ' ' ' '     # # # X#

 

 

 

 
E	E		"	g	V	E	E	g	6		$	G		z"			c
	t	Z 	k"	Z 	k"	-(	>*!	X	+&9M>  @?AA1222  : 6"&:$L :0 	@ 	@K!,TBBK @k;???# 	< 	<F )K )KL+{;;;;	< 	<
 	 "=; 	@ 	@K|[11 !&-dCCK @k;???+1=+J 	: 	:'L-6=->>D :lD999	: 	:r;   )r/   r0   r1   r   r2   r   r3   r   )*
__future__r   r_   typingr   r   rB   r6   r   paddle.utils.decorator_utilsr    r   	frameworkr	   r
   numpy.typingr   r   paddle._typingr   r   r   rU   rV   UINT8INT8INT16INT32INT64BOOL_supported_int_dtype_!_supported_promote_complex_types_	COMPLEX64
COMPLEX128_complex_dtypesr   ri   r:   r'   r=   r  re   r;   r9   <module>r$     s   # " " " " "                                    2 2 2 2 2 2 ?$$$$$$>>>>>>>>>> 	LLLLLL  % % % ! 	L"L#
 $  y  I  
	 
 y  Y  y  i  F  F  W   W! " W# $ 
7% & W' ( G) , F- . / 0 5      <          A	: A	: A	: A	: A	:r;   