
    |jS2                       d dl mZ d dlmZmZ d dlZd dlZd dlmZm	Z	 d dl
mZ d dlmZmZmZmZmZ d dlmZ d dlmZmZ erd dlmZ d d	lmZmZmZmZ d d
lmZmZm Z  ddgZ!d Z"d Z#d Z$d Z%	 	 	 	 d&d'd Z&d! Z'e	 	 	 	 d&d(d%            Z(dS ))    )annotations)TYPE_CHECKINGAnyN)_C_opsin_dynamic_mode)convert_dtype)_current_expected_place_get_paddle_placecoredygraph_onlyin_pir_mode)LayerHelper)max	to_tensor)CPUPlaceCUDAPinnedPlace	CUDAPlaceTensor)	DTypeLikeNumericSequence	ShapeLikesparse_coo_tensorsparse_csr_tensorc                    |rGt          |          t          | j                  k    r"|                     t          |                    S | S )N)r   dtypeastype)datar   s     f/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/paddle/sparse/creation.py_handle_dtyper   .   sF     5=#<#<<<;;}U33444K    c                   t          | j                  dk    sJ t          | d          }|dz   }|                                }t          |j                  dk    r"t	          j        ||j        dd                    }t          |          S )N      )axis)lenshaper   numpynpappendlist)indicesvalueslenss      r   _infer_dense_shaper.   5   s    w}""""wQD!8D::<<D
6<1yv|ABB/00::r    c                    t          |           } | t                      } nKt          | t          j        t          j        t          j        t          j        f          st          d          | S )Nz^'place' must be any of paddle.Place, paddle.CPUPlace, paddle.CUDAPinnedPlace, paddle.CUDAPlace)	r
   r	   
isinstancer   Placer   r   r   
ValueError)places    r   
_get_placer4   ?   sh    e$$E}'))
DM4+?P  
 l
 
 	
 Lr    c                    | t           j        t           j        t           j        t           j        fvrt          d          d S )NzDthe dtype of indices must be 'int8' or 'int16' or 'int32' or 'int64')paddleint8int16int32int64	TypeError)r   s    r   _check_indices_dtyper<   L   s<    V[&,flKKKR
 
 	
 LKr    Tr+   Mlist[list[int]] | tuple[tuple[int, ...], ...] | npt.NDArray[np.int_] | Tensorr,   +NumericSequence | npt.NDArray[Any] | Tensorr&   ShapeLike | Noner   DTypeLike | Noner3   3CPUPlace | CUDAPinnedPlace | CUDAPlace | str | Nonestop_gradientboolreturnr   c           
     F   t                      rt          |          }t          | t          j        j                  st          | d|d          } t          |t          j        j                  st          ||||          }t          | j                  dk    rt          d          | j        d         }| j        d         }t          | j                   ||j        d         k    r t          d| d	|j        d                    t          |j                  dz
  }| j                            |          s|                     |d
          } |j                            |          s|                    |d
          }t          ||          }||_        t#          | |          }	||	}net%          |          }||	k     rt          d|	 d|           t          |          ||z   k    r%t          d| d| dt          |                     t'          j        || |          S t+                      rt'          j        || |          S d}
|| d}|d         d|d<   d|i}t-          |
          }|                    |          }|                    |
|d|i|           |S )a=  
    Constructs a sparse ``paddle.Tensor`` in coordinate format according to the indices
    and values of the specified non-zero elements.

    Args:
        indices(list|tuple|ndarray|Tensor): the indices of non-zero elements.
            Can be a list, tuple, numpy\.ndarray, paddle\.Tensor. The indices must be 2-D.
        values(list|tuple|ndarray|Tensor): Initial values for the tensor.
            Can be a scalar, list, tuple, numpy\.ndarray, paddle\.Tensor.
        shape(list|tuple|None, optional): The shape of the sparse tensor also represents the shape of
            original dense tensor. If not provided the smallest shape will be inferred to
            hold all elements.
        dtype(str|paddle.dtype|np.dtype, optional): The desired data type of returned tensor. Can be 'bool' , 'float16' ,
            'float32' , 'float64' , 'int8' , 'int16' , 'int32' , 'int64' , 'uint8',
            'complex64' , 'complex128'. Default: None, infers dtype from ``data``
            except for python float number which gets dtype from ``get_default_type`` .
        place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str|None, optional): The place to allocate Tensor. Can be
            CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is
            string, It can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where ``x`` is the index of the GPUs.
        stop_gradient(bool, optional): Whether to block the gradient propagation of Autograd. Default: True.

    Returns:
        Tensor: A Tensor constructed from ``indices`` and ``values`` .

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> indices = [[0, 1, 2], [1, 2, 0]]
            >>> values = [1.0, 2.0, 3.0]
            >>> dense_shape = [3, 3]
            >>> coo = paddle.sparse.sparse_coo_tensor(indices, values, dense_shape)
            >>> print(coo)
            Tensor(shape=[3, 3], dtype=paddle.float32, place=Place(cpu), stop_gradient=True,
                   indices=[[0, 1, 2],
                            [1, 2, 0]],
                   values=[1., 2., 3.])
    NTr   r3   rB   r"   z'indices' must be 2-D.r#   r   zBthe indices and values must have same number of non-zero, but get z and Fzthe minimum shape required is z
, but get z7the number of dimensions(len(shape) must be sparse_dim(z) + dense_dim(z), but get sparse_sparse_coo_tensor)r,   r+   r&   out)typeinputsoutputsattrs)r   r4   r0   r   eagerr   r   r%   r&   r2   r<   r   r3   _equals_copy_tor   rB   r.   r*   r   rH   r   r   )create_sparse_variable_for_type_inference	append_op)r+   r,   r&   r   r3   rB   nnz
sparse_dim	dense_dim	min_shapeop_typerK   rM   helperrI   s                  r   r   r   S   s   l  >5!!'4:#455 	t5  G &$*"344 	Dvue]CCFw}""5666mA]1%
W]+++&,q/!!pUXpp_e_klm_npp   %%)	}$$U++ 	5&&ue44G|##E** 	3__UE22Fvu--,&w77	=EEKKEy   QYQQ%QQ   5zzZ)333  Kj  K  Khq  K  K  B  CH  I  I  K  K   .vwFFF	 .vwFFF -"w778E!H% W%%>>uEE%U 	 	
 	
 	
 
r    c                   |                                  }|                                 }t          j        |d d         |dd          k              dz   }t          t	          |          |z            |z  t	          |          k    rt          d| d          |                                dz   }t          t	          |          |z            dz
  }|dk    r||gS |||gS )NrG   r#   z-The calculated original matrix batch size is za, but it cannot correctly split the row data. Please carefully check the data or the input shape.)r'   r(   sumintr%   r2   r   )crowscolscrows_numpy
cols_numpybatchscolrows          r   _infer_dense_csr_shaperc      s    ++--KJVK${122677!;FCv%&&/C4D4DDD fF  f  f  f
 
 	
 ..

Q
C
c+'
(
(1
,C{{SzS!!r    r\   ;list[int] | tuple[int, ...] | npt.NDArray[np.int_] | Tensorr]   c                   t          |          }t          | t          j        j                  st          | d|d          } t          |t          j        j                  st          |d|d          }t          |t          j        j                  st          ||||          }t          | j                   t          |j                   |9t          |          dk    r%t          |          dk    rt          d|           nt          | |          }|t          |          dz
           }| j                            |          s|                     |d          } |j                            |          s|                    |d          }|j                            |          s|                    |d          }t          ||          }||_        t          | j                  dk    s0t          |j                  dk    st          |j                  dk    rt          d	          t          |          t          |          k    rt          d
          t          |          dk    rw| j        d         |dz   k    r!t          d| j        d          d| d          | d         dk    rt          d          | d         |j        d         k    rt          d          n8| j        d         |dz   z  dk    r!t          d| j        d          d| d          t          j                            | ||||          S )aO	  
    Constructs a sparse ``paddle.Tensor`` in CSR(Compressed Sparse Row) format according to the
    ``crows``, ``cols`` and ``values``.
    Currently, the crows and cols of each batch must be incremented.

    Args:
        crows(list|tuple|ndarray|Tensor): 1-D array, each element in the rows represents the
            starting position of the first non-zero element of each row in values.
            Can be a list, tuple, numpy\.ndarray, paddle\.Tensor.
        cols(list|tuple|ndarray|Tensor): 1-D array, the column of non-zero elements.
            Can be a list, tuple, numpy\.ndarray, paddle\.Tensor.
        values(list|tuple|ndarray|Tensor): 1-D array, the non-zero elements.
            Can be a scalar, list, tuple, numpy\.ndarray, paddle\.Tensor.
        shape(list|tuple, optional): The shape of the sparse tensor also represents the shape of
            original dense tensor.
            hold all elements.
        dtype(str|paddle.dtype|np.dtype, optional): The desired data type of returned tensor. Can be 'bool' , 'float16' ,
            'float32' , 'float64' , 'int8' , 'int16' , 'int32' , 'int64' , 'uint8',
            'complex64' , 'complex128'. Default: None, infers dtype from ``data``
            except for python float number which gets dtype from ``get_default_type`` .
        place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str|None, optional): The place to allocate Tensor. Can be
            CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is
            string, It can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where ``x`` is the index of the GPUs.
        stop_gradient(bool, optional): Whether to block the gradient propagation of Autograd. Default: True.

    Returns:
        Tensor: A Tensor constructed from ``crows``, ``cols`` and ``values`` .

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> crows = [0, 2, 3, 5]
            >>> cols = [1, 3, 2, 0, 1]
            >>> values = [1, 2, 3, 4, 5]
            >>> dense_shape = [3, 4]
            >>> csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape)
            >>> print(csr)
            Tensor(shape=[3, 4], dtype=paddle.int64, place=Place(cpu), stop_gradient=True,
                   crows=[0, 2, 3, 5],
                   cols=[1, 3, 2, 0, 1],
                   values=[1, 2, 3, 4, 5])
    NTrF   r"      z>SparseCsrTensor only support 2-D or 3-D matrix. but get shape Fr#   z-The 'crows', 'cols' and 'values' must be 1-D.z3the length of cols must be same as length of valuesr   zThe length(z%) of crows must be equal to the rows(z)+1 of matrix.z the 0th value of crows must be 0rG   z<the last value of crows must be equal the number of non-zeroz&) of crows must be divisible the rows()r4   r0   r   rN   r   r   r<   r   r%   r2   rc   r3   rO   rP   r   rB   r&   r   )r\   r]   r,   r&   r   r3   rB   rowss           r   r   r      s:   p uEeTZ.// N%t5MMMdDJ-.. LTdKKKfdj/00 @65%??%%%$$$u::??s5zzQXQVXX   'ud33Ua D;u%% -ue,,:e$$ +}}UE**<&& /..65))F(F
5;1DJ1 4 4FL8I8IQ8N8NHIII
4yyCKKNOOO
5zzQ;q>TAX%%gek!nggSWggg   8q==?@@@9Q''N   (
 ;q>TAX&!++hek!nhhTXhhh  
 :''tVUM  r    )NNNT)r+   r=   r,   r>   r&   r?   r   r@   r3   rA   rB   rC   rD   r   )r\   rd   r]   rd   r,   r>   r&   r?   r   r@   r3   rA   rB   rC   rD   r   ))
__future__r   typingr   r   r'   r(   r6   r   r   paddle.base.data_feederr   paddle.base.frameworkr	   r
   r   r   r   paddle.base.layer_helperr   paddle.tensorr   r   numpy.typingnptr   r   r   r   paddle._typingr   r   r   __all__r   r.   r4   r<   r   rc   r    r    r   <module>rs      s
   # " " " " " % % % % % % % %      * * * * * * * * 1 1 1 1 1 1              1 0 0 0 0 0 ( ( ( ( ( ( ( ( ECCCCCCCCCCCCDDDDDDDDDD     
 
 

 
 
 #"AEt t t t tn" " "" 
 #"AEs s s s s s sr    