B
     \.                 @   s  d Z ddlmZmZ ddlZddlZddlmZm	Z	m
Z
 ddlmZmZmZ ye W n ek
rl   eZY nX e	jZe	jZe	jZed8ddZd	d
 Zdd Zed9ddZeejdddfddZeejddfddZeejdddddfddZejed:ddZdd Z dd Z!dd Z"d;d d!Z#ed"d# Z$eejd$d% Z%eejd&d' Z&d<d(d)Z'e
j(Z(d*d+ Z)d,d- Z*d.d/ Z+d0d1 Z,d=d2d3Z-d4d5 Z.ejd6d7 Z/ee
j0Z0ee
j1Z1ee
j2Z2dS )>z%
API that are reported to numba.cuda
    )print_functionabsolute_importN   )devicearraydevicesdriver)InOutInOutc       	      C   s   | d }|  d}t| d }t|||dd\}}}t|||j}t| d d }tjt	 |||d}t
j||||d	}|S )
zCreate a DeviceNDArray from a cuda-array-interface description.
    The *owner* is the owner of the underlying memory.
    The resulting DeviceNDArray will acquire a reference from it.
    shapestridesZtypestrC)orderdatar   )sizeowner)r   r   dtypegpu_data)getnpr   _prepare_shape_strides_dtyper   memory_size_from_infoitemsizeZget_devptr_for_active_ctxZMemoryPointercurrent_contextr   DeviceNDArray)	Zdescr   r   r   r   r   Zdevptrr   Zda r   -lib/python3.7/site-packages/numba/cuda/api.pyfrom_cuda_array_interface   s    

r   c             C   s$   t | stdnt| j| dS dS )zCreate a DeviceNDArray from any object that implements
    the cuda-array-interface.

    A view of the underlying GPU buffer is created.  No copying of the data
    is done.  The resulting DeviceNDArray will acquire a reference from `obj`.
    z1*obj* doesn't implement the cuda array interface.)r   N)is_cuda_array	TypeErrorr   __cuda_array_interface__)objr   r   r   as_cuda_array1   s    
r"   c             C   s
   t | dS )zwTest if the object has defined the `__cuda_array_interface__`.

    Does not verify the validity of the interface.
    r    )hasattr)r!   r   r   r   r   ?   s    r   Tc             C   s6   |dkr t j| ||d\}}|S |r2|j| |d |S )a  to_device(obj, stream=0, copy=True, to=None)

    Allocate and transfer a numpy ndarray or structured scalar to the device.

    To copy host->device a numpy array::

        ary = np.arange(10)
        d_ary = cuda.to_device(ary)

    To enqueue the transfer to a stream::

        stream = cuda.stream()
        d_ary = cuda.to_device(ary, stream=stream)

    The resulting ``d_ary`` is a ``DeviceNDArray``.

    To copy device->host::

        hary = d_ary.copy_to_host()

    To copy device->host to an existing array::

        ary = np.empty(shape=d_ary.shape, dtype=d_ary.dtype)
        d_ary.copy_to_host(ary)

    To enqueue the transfer to a stream::

        hary = d_ary.copy_to_host(stream=stream)
    N)streamcopy)r$   )r   auto_deviceZcopy_to_device)r!   r$   r%   tonewr   r   r   	to_deviceG   s    r)   r   c             C   s&   t | |||\} }}tj| |||dS )zdevice_array(shape, dtype=np.float, strides=None, order='C', stream=0)

    Allocate an empty device ndarray. Similar to :meth:`numpy.empty`.
    )r   r   r   r$   )r   r   r   )r   r   r   r   r$   r   r   r   device_arrayn   s    
r*   c             C   sD   t | |||\} }}t| ||j}t |}tj| ||||dS )zpinned_array(shape, dtype=np.float, strides=None, order='C')

    Allocate a np.ndarray with a buffer that is pinned (pagelocked).
    Similar to np.empty().
    )r   r   r   r   buffer)r   r   r   r   r   memhostallocr   ndarray)r   r   r   r   bytesizer+   r   r   r   pinned_arrayz   s    r/   Fc             C   sl   t | |||\} }}t| ||j}t j|dd}tj| ||||d}	tjj|	t	j
d}
|
j||d |
S )a&  mapped_array(shape, dtype=np.float, strides=None, order='C', stream=0, portable=False, wc=False)

    Allocate a mapped ndarray with a buffer that is pinned and mapped on
    to the device. Similar to np.empty()

    :param portable: a boolean flag to allow the allocated device memory to be
              usable in multiple devices.
    :param wc: a boolean flag to enable writecombined allocation which is faster
        to write by the host and to read by the device, but slower to
        write by the host and slower to write by the device.
    T)mapped)r   r   r   r   r+   )type)r$   )r   r   r   r   r   r,   r   r-   Zviewr   ZMappedNDArrayZdevice_setup)r   r   r   r   r$   ZportableZwcr.   r+   ZnparyZ
mappedviewr   r   r   mapped_array   s    r2   c             c   sZ   t |}t ||j }tjj|  } tjd| ||d}|jt	 |||dV  |
  dS )a  
    A context manager that opens a IPC *handle* (*CUipcMemHandle*) that is
    represented as a sequence of bytes (e.g. *bytes*, tuple of int)
    and represent it as an array of the given *shape*, *strides* and *dtype*.
    The *strides* can be omitted.  In that case, it is assumed to be a 1D
    C contiguous array.

    Yields a device array.

    The IPC handle is closed automatically when context manager exits.
    N)offset)r   r   r   )r   r   Zprodr   r   ZdrvapiZcu_ipc_mem_handleZ	IpcHandleZ
open_arrayr   close)Zhandler   r   r   r3   r   Z	ipchandler   r   r   open_ipc_array   s    

r5   c               C   s
   t   S )z Synchronize the current context.)r   synchronizer   r   r   r   r6      s    r6   c             C   sZ   t |}t| ttfr| f} t|ttfr4|f}n| dkr@d} |pNt| ||}| ||fS )Nr   )r   )r   r   
isinstanceintlong_fill_stride_by_order)r   r   r   r   r   r   r   r      s    
r   c             C   s   t | }dg| }|dkr\|j|d< xtt|d D ] }||d  | |d   ||< q6W nL|dkr|j|d< x8td|D ] }||d  | |d   ||< qzW ntdt|S )Nr   r   r   Fzmust be either C/F order)lenr   reversedrange
ValueErrortuple)r   r   r   Zndr   dr   r   r   r:      s    

"
"r:   c             C   s   t | j| j| j|dS )z=Call cuda.devicearray() with information from the array.
    )r   r   r   r$   )r*   r   r   r   )aryr$   r   r   r   device_array_like   s    
rD   c               C   s
   t   S )zWstream()

    Create a CUDA stream that represents a command queue for the device.
    )r   Zcreate_streamr   r   r   r   r$      s    r$   c              g   sF   g }x6| D ].}t  j|t|t|dd}|| q
W dV  dS )zIA context manager for temporary pinning a sequence of host ndarrays.
    F)r0   N)r   mempinr   host_pointerhost_memory_sizeappend)arylistpmlistrC   pmr   r   r   pinned   s    
rL   c           	   o   s   |rd|kst d|dd}g }g }xP| D ]H}t j|t|t|dd}|| tj	|||d}|| q.W z"t
|dkr|d V  n|V  W dx|D ]}|  qW X dS )	zKA context manager for temporarily mapping a sequence of host ndarrays.
    r$   z Only accept 'stream' as keyword.r   T)r0   )r   r$   r   N)AssertionErrorr   r   rE   r   rF   rG   rH   r   Zfrom_array_liker=   Zfree)rI   Zkwsr$   rJ   Z
devarylistrC   rK   Zdevaryr   r   r   r0      s"    



r0   c             C   s   t  j| d}|S )zs
    Create a CUDA event. Timing data is only recorded by the event if it is
    created with ``timing=True``.
    )timing)r   Zcreate_event)rN   Zevtr   r   r   event  s    rO   c             C   s   t | }|jS )z
    Make the context associated with device *device_id* the current context.

    Returns a Device instance.

    Raises exception on error.
    )r   get_contextdevice)Z	device_idcontextr   r   r   select_device&  s    
rS   c               C   s   t  jS )z5Get current device associated with the current thread)r   rQ   r   r   r   r   get_current_device2  s    rT   c               C   s   t jS )z%Return a list of all detected devices)r   gpusr   r   r   r   list_devices7  s    rV   c               C   s   t   dS )z
    Explicitly clears all contexts in the current thread, and destroys all
    contexts if the current thread is the main thread.
    N)r   resetr   r   r   r   r4   <  s    r4   c             C   s   t j| ||dS )N)r$   r%   )r   r&   )rC   r$   r%   r   r   r   _auto_deviceD  s    rX   c              C   s   t  } tdt|   d}x| D ]}g }|j}|dd| fg7 }|d|jfg7 }|d|jfg7 }|dk rnd}nd	}|d
7 }td|j|j|f  x |D ]\}}td||f  qW q W td td|t| f  |dkS )z
    Detect supported CUDA hardware and print a summary of the detected hardware.

    Returns a boolean indicating whether any supported devices were detected.
    zFound %d CUDA devicesr   zcompute capabilityz%d.%dzpci device idz
pci bus id)   r   z[NOT SUPPORTED: CC < 2.0]z[SUPPORTED]r   zid %d    %20s %40sz%40s: %szSummary:z	%d/%d devices are supported)rV   printr=   Zcompute_capabilityZPCI_DEVICE_IDZ
PCI_BUS_IDidname)ZdevlistZsupported_countZdevZattrsZccZsupportkeyvalr   r   r   detectH  s&    
r_   c           	   c   s&   t  j} |   dV  W dQ R X dS )aV  
    Temporarily disable memory deallocation.
    Use this to prevent resource deallocation breaking asynchronous execution.

    For example::

        with defer_cleanup():
            # all cleanup is deferred in here
            do_speed_critical_code()
        # cleanup can occur here

    Note: this context manager can be nested.
    N)r   Zdeallocationsdisable)Zdeallocsr   r   r   defer_cleanupf  s    
ra   )N)r   TN)Nr   )r   )T)r   T)3__doc__Z
__future__r   r   
contextlibZnumpyr   Zcudadrvr   r   r   argsr   r	   r
   r9   	NameErrorr8   Zrequire_contextrP   r   rU   r   r"   r   r)   floatr*   r/   r2   contextmanagerr5   r6   r   r:   rD   r$   rL   r0   rO   Zevent_elapsed_timerS   rT   rV   r4   rX   r_   ra   Z	profilingZprofile_startZprofile_stopr   r   r   r   <module>   sb   
&

	



