
    |jM%                    "   d dl mZ d dlZd dlZd dlmZ d dlmZmZmZm	Z	 d dl
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gZ e	dd          Z G d dee                   Z G d dej                  Zd"dZdddd#d!ZdS )$    )annotationsN)IntEnum)TYPE_CHECKINGLiteralProtocolTypeVar   )DenseTensor)
check_type)in_dygraph_mode)CapsuleType)Tensor)	PlaceLike	to_dlpackfrom_dlpack	_T_contraT)contravariantc                  .    e Zd ZdZdddddddZddZdS )SupportDLPackz
    ref:
        https://github.com/numpy/numpy/blob/7e6e48ca7aacae9994d18a3dadbabd2b91c32151/numpy/__init__.pyi#L3068-L3077
        https://github.com/numpy/numpy/blob/7e6e48ca7aacae9994d18a3dadbabd2b91c32151/numpy/__init__.pyi#L4730-L4731
    .N)streammax_version	dl_devicecopyr   None | _T_contrar   tuple[int, int] | Noner   tuple[IntEnum, int] | Noner   bool | Nonereturnr   c                   d S N )selfr   r   r   r   s        c/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/paddle/utils/dlpack.py
__dlpack__zSupportDLPack.__dlpack__2   s	     c    tuple[int, Literal[0]]c                    d S r    r!   )r"   s    r#   __dlpack_device__zSupportDLPack.__dlpack_device__;   s      r%   )
r   r   r   r   r   r   r   r   r   r   )r   r&   )__name__
__module____qualname____doc__r$   r(   r!   r%   r#   r   r   +   sT          $'.104       ?>>>>>r%   r   c                  N    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdS )DLDeviceType)   )r	   )   )   )   )   )	   )
   )   )   )   )   )   )   )   )   N)r)   r*   r+   kDLCPUkDLCUDAkDLCUDAHost	kDLOpenCL	kDLVulkankDLMetalkDLVPIkDLROCMkDLROCMHost	kDLExtDevkDLCUDAManaged	kDLOneAPI	kDLWebGPU
kDLHexagonkDLMAIAkDLTrnr!   r%   r#   r.   r.   >   s^        FGKIIHFGKINIIJGFFFr%   r.   xr   r   r   c                X   t                      rrt          | t          j                  s t	          dt          |            d          |                                                                                                 S t          | dt          d           |                                 S )an  
    Encodes a tensor to DLPack.

    Args:
        x (Tensor): The input tensor, and the data type can be ``bool``, ``float16``, ``float32``,
            ``float64``, ``int8``, ``int16``, ``int32``, ``int64``, ``uint8``, ``complex64``,
            ``complex128``.

    Returns:
        dltensor, and the data type is PyCapsule.

    Examples:
        .. code-block:: python
            :name: code-paddle-to-paddle

            >>> import paddle
            >>> # x is a tensor with shape [2, 4]
            >>> x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9],
            ...                       [0.1, 0.2, 0.6, 0.7]])
            >>> dlpack = paddle.to_dlpack(x)
            >>> print(dlpack)
            >>> # doctest: +SKIP('the address will change in every run')
            <capsule object "dltensor" at 0x7f6103c681b0>
            >>> #doctest: -SKIP

            >>> # dlpack capsule will be renamed to 'used_dltensor' after decoded
            >>> y = paddle.from_dlpack(dlpack)
            >>> print(dlpack)
            >>> # doctest: +SKIP('the address will change in every run')
            <capsule object "used_dltensor" at 0x7f6103c681b0>

        .. code-block:: python
            :name: code-paddle-to-torch

            >>> # doctest: +SKIP('torch will not be installed')
            >>> # type: ignore
            >>> # convert tensor from paddle to other framework using to_dlpack
            >>> import torch

            >>> x = paddle.randn([2, 4]).to(device="cpu")
            >>> y = torch.from_dlpack(paddle.to_dlpack(x))
            >>> print(y.shape)
            torch.Size([2, 4])
            >>> # doctest: -SKIP
    zAThe type of 'x' in to_dlpack must be paddle.Tensor, but received .rN   r   )r   
isinstancepaddler   	TypeErrortypevalue
get_tensor
_to_dlpackr   r
   )rN   s    r#   r   r   Q   s    \  3!V]++ 	,!%a, , ,  
 wwyy##%%00222q#k222<<>>r%   )devicer   dlpackSupportDLPack | CapsuleTyperX   PlaceLike | Noner   r   c                  t          | d          rfi }d|d<   |||d<   |Kt          j        j                            |          }t          j        j                            |          |d<   |                                 }|d         t          j	        fv rt          j                    5  t          j        dt          	           t          j        j                            |d
                   }ddd           n# 1 swxY w Y   |d         t          j	        k    }|r|j        dk    rd
n|j        }||d<   	  | j        di |}	n4# t&          $ r% |                    d            | j        di |}	Y nw xY w| }	t          j        j                            |	          }
t-                      r(t          j        |
|
                                          }
|
S )a  
    Decodes a DLPack to a tensor. The returned Paddle tensor will share the memory with
    the tensor from given dlpack.

    Args:
        dlpack (SupportDLPack | CapsuleType): A PyCapsule object with the dltensor,
            or that implements '__dlpack__' and '__dlpack_device__' methods.

            If `dlpack` is a tensor (or ndarray) object, it must support
            the `__dlpack__` protocol (i.e., have a `dlpack.__dlpack__`
            method). Otherwise `dlpack` may be a DLPack capsule, which is
            an opaque `PyCapsule` instance, typically produced by a
            `to_dlpack` function or method.

        device (PlaceLike, optional): The device of the returned tensor. If not
            specified, the device will be the same as that of the input `dlpack`.
        copy (bool, optional): Whether or not to copy the input.
            If True, the output tensor always copied. If False, the output tensor must never
            copied, and raise a BufferError in case a copy is deemed necessary. If None, the
            output tensor must reuse the existing memory buffer if possible and copy otherwise.
            Default: None.

    Returns:
        out (Tensor): A tensor decoded from DLPack. The data type of returned tensor
            can be one of: ``int32``, ``int64``, ``float16``, ``float32`` and ``float64``.
            The device of returned tensor can be one of: ``CPU``, ``CUDAPlace``, ``CUDAPinnedPlace``.

    Examples:
        .. code-block:: python
            :name: code-paddle-from-paddle

            >>> import paddle
            >>> # From DLPack capsule
            >>> x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9],
            ...                       [0.1, 0.2, 0.6, 0.7]], place="cpu")
            >>> dlpack = paddle.to_dlpack(x)

            >>> y = paddle.from_dlpack(dlpack)
            >>> # dlpack capsule will be renamed to 'used_dltensor' after decoded
            >>> print(dlpack)
            >>> # doctest: +SKIP('the address will change in every run')
            <capsule object "used_dltensor" at 0x7f6103c681b0>
            >>> # doctest: -SKIP

            >>> print(y)
            Tensor(shape=[2, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
                   [[0.20000000, 0.30000001, 0.50000000, 0.89999998],
                    [0.10000000, 0.20000000, 0.60000002, 0.69999999]])
            >>> # data of tensor x is shared with tensor y
            >>> y[0, 0] = 10.0
            >>> print(x)
            Tensor(shape=[2, 4], dtype=float32, place=Place(gpu:0), stop_gradient=True,
                   [[10.       , 0.30000001, 0.50000000, 0.89999998],
                    [0.10000000, 0.20000000, 0.60000002, 0.69999999]])

        .. code-block:: python
            :name: code-paddle-from-numpy

            >>> # Directly from external tensor that implements '__dlpack__' and '__dlpack_device__' methods
            >>> import paddle
            >>> import numpy as np
            >>> x = np.array([[0.2, 0.3, 0.5, 0.9],
            ...              [0.1, 0.2, 0.6, 0.7]])
            >>> y = paddle.from_dlpack(x)
            >>> y[0, 0] = 10.0
            >>> # data of tensor x is shared with tensor y
            >>> print(x)
            [[10.   0.3  0.5  0.9]
            [ 0.1  0.2  0.6  0.7]]
    r$   )r/   r	   r   Nr   r   r   ignore)categoryr/   r   )placer!   )hasattrrR   base	framework_get_paddle_placecoreplace_to_dl_devicer(   r.   r?   warningscatch_warningsfilterwarningsUserWarningrX   cudacurrent_streamcuda_streamr$   rS   popr   r   r   _place)rY   rX   r   kwargsr_   dlpack_devicer   is_gpu
stream_ptrdlpack_outs              r#   r   r      s?   Z v|$$ $ &}!F6NK);;FCCE"(+"2"E"Ee"L"LF;0022  4666(** M M';GGGG+::=;KLLM M M M M M M M M M M M M M M #1%)==FO 2a 7 7V=O   *F8	2'f'11&11GG 	2 	2 	2JJ}%%%'f'11&11GGG	2 -3[-=-I-I. .C  =mCszz||<<<Js%   )AC;;C?C?8E ,E54E5)rN   r   r   r   )rY   rZ   rX   r[   r   r   r   r   )
__future__r   enumrf   r   typingr   r   r   r   rR   	base.corer
   base.data_feederr   base.frameworkr   typing_extensionsr   r   paddle._typingr   __all__r   r   r.   r   r   r!   r%   r#   <module>r~      s   # " " " " "         < < < < < < < < < < < <  # # # # # # ) ) ) ) ) ) , , , , , , )------(((((( 
 GKt444	? ? ? ? ?HY' ? ? ?&    4<   &8 8 8 8|  $	z z z z z z z zr%   