o
    + iC2                     @  s  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d Z"dd Z#dd Z$dd Z%				d+d,d$dZ&d%d& Z'e				d+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                 C  s(   |rt |t | jkr| t |S | S )N)r   dtypeZastype)datar    r   b/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/paddle/sparse/creation.py_handle_dtype.   s   r   c                 C  sZ   t | jdks	J t| dd}|d }| }t |jdkr)t||jdd  }t|S )N      )Zaxis)lenshaper   numpynpappendlist)indicesvaluesZlensr   r   r   _infer_dense_shape5   s   r(   c                 C  s@   t | } | d u rt } | S t| 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
   ZPlacer   r   r   
ValueError)placer   r   r   
_get_place?   s   r,   c                 C  s$   | 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')paddleZint8Zint16Zint32Zint64	TypeError)r   r   r   r   _check_indices_dtypeL   s
   r/   Tr&   Mlist[list[int]] | tuple[tuple[int, ...], ...] | npt.NDArray[np.int_] | Tensorr'   +NumericSequence | npt.NDArray[Any] | Tensorr!   ShapeLike | Noner   DTypeLike | Noner+   3CPUPlace | CUDAPinnedPlace | CUDAPlace | str | Nonestop_gradientboolreturnr   c                 C  s  t  rt|}t| tjjst| d|dd} t|tjjs$t||||}t| jdkr/t	d| jd }| jd }t
| j ||jd krRt	d| d	|jd  t|jd }| j|se| |d
} |j|sq||d
}t||}||_t| |}	|du r|	}n)t|}||	k rt	d|	 d| t||| krt	d| d| dt| t|| |S t rt|| |S d}
|| d}|d du rd|d< d|i}t|
}||}|j|
|d|i|d |S )a5  
    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|np.dtype|None, 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   r+   r5   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inputsZoutputsattrs)r   r,   r)   r
   eagerr   r   r    r!   r*   r/   r   r+   _equals_copy_tor   r5   r(   r%   r   r:   r   r   Z)create_sparse_variable_for_type_inferenceZ	append_op)r&   r'   r!   r   r+   r5   ZnnzZ
sparse_dimZ	dense_dimZ	min_shapeZop_typer=   r>   helperr;   r   r   r   r   S   sd   6






c                 C  s   |   }|  }t|d d |dd  kd }tt|| | t|kr/td| d| d }tt|| d }|dkrG||gS |||gS )Nr9   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    r*   r   )crowscolsZcrows_numpyZ
cols_numpyZbatchscolrowr   r   r   _infer_dense_csr_shape   s   "

rI   rE   ;list[int] | tuple[int, ...] | npt.NDArray[np.int_] | TensorrF   c                 C  s  t |}t| tjjst| d|dd} t|tjjs"t|d|dd}t|tjjs0t||||}t| j t|j |durRt|dkrQt|dkrQt	d| nt
| |}|t|d  }| j|sk| |d} |j|sw||d}|j|s||d}t||}||_t| jdkst|jdkst|jdkrt	d	t|t|krt	d
t|dkr| jd |d krt	d| jd  d| d| d dkrt	d| d |jd krt	dn| jd |d  dkrt	d| jd  d| dtj| ||||S )aG	  
    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|np.dtype|None, 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])
    NTr8   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 0r9   z<the last value of crows must be equal the number of non-zeroz&) of crows must be divisible the rows()r,   r)   r
   r?   r   r   r/   r   r    r*   rI   r+   r@   rA   r   r5   r!   r   )rE   rF   r'   r!   r   r+   r5   rowsr   r   r   r      s`   8



*
)NNNT)r&   r0   r'   r1   r!   r2   r   r3   r+   r4   r5   r6   r7   r   )rE   rJ   rF   rJ   r'   r1   r!   r2   r   r3   r+   r4   r5   r6   r7   r   ))
__future__r   typingr   r   r"   r#   r-   r   r   Zpaddle.base.data_feederr   Zpaddle.base.frameworkr   r	   r
   r   r   Zpaddle.base.layer_helperr   Zpaddle.tensorr   r   Znumpy.typingZnptr   r   r   r   Zpaddle._typingr   r   r   __all__r   r(   r,   r/   r   rI   r   r   r   r   r   <module>   s@   
w