repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/ucx-py/ucp
rapidsai_public_repos/ucx-py/ucp/_libs/__init__.py
# Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. # See file LICENSE for terms. from .utils import nvtx_annotate # noqa
0
rapidsai_public_repos/ucx-py/ucp
rapidsai_public_repos/ucx-py/ucp/_libs/ucx_request.pyx
# Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. # See file LICENSE for terms. # cython: language_level=3 from cpython.ref cimport Py_DECREF, Py_INCREF, PyObject from libc.stdint cimport uintptr_t from .exceptions import UCXError, UCXMsgTruncated from .ucx_api_dep cimport * # Counter used as UCXRequest UIDs cdef unsigned int _ucx_py_request_counter = 0 cdef class UCXRequest: """Python wrapper of UCX request handle. Don't create this class directly, the send/recv functions and their callback functions will return UCXRequest objects. Notice, this class doesn't own the handle and multiple instances of UCXRequest can point to the same underlying UCX handle. Furthermore, UCX can modify/free the UCX handle without notice thus we use `_uid` to make sure the handle hasn't been modified. """ cdef: ucx_py_request *_handle unsigned int _uid def __init__(self, uintptr_t req_as_int): global _ucx_py_request_counter cdef ucx_py_request *req = <ucx_py_request*>req_as_int assert req != NULL self._handle = req cdef dict info = {"status": "pending"} if self._handle.info == NULL: # First time we are wrapping this UCX request Py_INCREF(info) self._handle.info = <PyObject*> info _ucx_py_request_counter += 1 self._uid = _ucx_py_request_counter assert self._handle.uid == 0 self._handle.uid = _ucx_py_request_counter else: self._uid = self._handle.uid cpdef bint closed(self): return self._handle == NULL or self._uid != self._handle.uid cpdef void close(self) except *: """This routine releases the non-blocking request back to UCX, regardless of its current state. Communications operations associated with this request will make progress internally, however no further notifications or callbacks will be invoked for this request. """ if not self.closed(): Py_DECREF(<object>self._handle.info) self._handle.info = NULL self._handle.uid = 0 ucp_request_free(self._handle) self._handle = NULL @property def info(self): assert not self.closed() return <dict> self._handle.info @property def handle(self): assert not self.closed() return int(<uintptr_t>self._handle) def __hash__(self): if self.closed(): return id(self) else: return self._uid def __eq__(self, other): return hash(self) == hash(other) def __repr__(self): if self.closed(): return "<UCXRequest closed>" else: return ( f"<UCXRequest handle={hex(self.handle)} " f"uid={self._uid} info={self.info}>" ) cdef UCXRequest _handle_status( ucs_status_ptr_t status, int64_t expected_receive, cb_func, cb_args, cb_kwargs, unicode name, set inflight_msgs ): if UCS_PTR_STATUS(status) == UCS_OK: return cdef str ucx_status_msg, msg if UCS_PTR_IS_ERR(status): ucx_status_msg = ( ucs_status_string(UCS_PTR_STATUS(status)).decode("utf-8") ) msg = "<%s>: %s" % (name, ucx_status_msg) raise UCXError(msg) cdef UCXRequest req = UCXRequest(<uintptr_t><void*> status) assert not req.closed() cdef dict req_info = <dict>req._handle.info if req_info["status"] == "finished": try: # The callback function has already handled the request received = req_info.get("received", None) if received is not None and received != expected_receive: msg = "<%s>: length mismatch: %d (got) != %d (expected)" % ( name, received, expected_receive ) raise UCXMsgTruncated(msg) else: cb_func(req, None, *cb_args, **cb_kwargs) return finally: req.close() else: req_info["cb_func"] = cb_func req_info["cb_args"] = cb_args req_info["cb_kwargs"] = cb_kwargs req_info["expected_receive"] = expected_receive req_info["name"] = name inflight_msgs.add(req) req_info["inflight_msgs"] = inflight_msgs return req
0
rapidsai_public_repos/ucx-py/ucp
rapidsai_public_repos/ucx-py/ucp/_libs/ucx_address.pyx
# Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2020-2021, UT-Battelle, LLC. All rights reserved. # See file LICENSE for terms. # cython: language_level=3 from libc.stdint cimport uintptr_t from libc.stdlib cimport free from libc.string cimport memcpy from .arr cimport Array from .ucx_api_dep cimport * def _ucx_address_finalizer( uintptr_t handle_as_int, uintptr_t worker_handle_as_int, ): cdef ucp_address_t *address = <ucp_address_t *>handle_as_int cdef ucp_worker_h worker = <ucp_worker_h>worker_handle_as_int if worker_handle_as_int != 0: ucp_worker_release_address(worker, address) else: free(address) cdef class UCXAddress(UCXObject): """Python representation of ucp_address_t""" cdef ucp_address_t *_address cdef size_t _length def __cinit__( self, uintptr_t address_as_int, size_t length, UCXWorker worker=None, ): address = <ucp_address_t *> address_as_int # Copy address to `self._address` self._address = <ucp_address_t *> malloc(length) self._length = length memcpy(self._address, address, length) self.add_handle_finalizer( _ucx_address_finalizer, int(<uintptr_t>self._address), 0 if worker is None else worker.handle, ) if worker is not None: worker.add_child(self) @classmethod def from_buffer(cls, buffer): buf = Array(buffer) assert buf.c_contiguous return UCXAddress(buf.ptr, buf.nbytes) @classmethod def from_worker(cls, UCXWorker worker): cdef ucs_status_t status cdef ucp_worker_h ucp_worker = worker._handle cdef ucp_address_t *address cdef size_t length status = ucp_worker_get_address(ucp_worker, &address, &length) assert_ucs_status(status) return UCXAddress(<uintptr_t>address, length, worker=worker) @property def address(self): return <uintptr_t>self._address @property def length(self): return int(self._length) def __getbuffer__(self, Py_buffer *buffer, int flags): get_ucx_object(buffer, flags, <void*>self._address, self._length, self) def __releasebuffer__(self, Py_buffer *buffer): pass def __reduce__(self): return (UCXAddress.from_buffer, (bytes(self),)) def __hash__(self): return hash(bytes(self))
0
rapidsai_public_repos/ucx-py/ucp
rapidsai_public_repos/ucx-py/ucp/_libs/transfer_stream.pyx
# Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2020 UT-Battelle, LLC. All rights reserved. # See file LICENSE for terms. # cython: language_level=3 from libc.stdint cimport uintptr_t from .arr cimport Array from .exceptions import ( UCXCanceled, UCXError, UCXMsgTruncated, UCXNotConnected, UCXUnreachable, log_errors, ) from .ucx_api_dep cimport * def stream_send_nb( UCXEndpoint ep, Array buffer, size_t nbytes, cb_func, tuple cb_args=None, dict cb_kwargs=None, str name=None ): """ This routine sends data to a destination endpoint The routine is non-blocking and therefore returns immediately, however the actual send operation may be delayed. The send operation is considered completed when it is safe to reuse the source buffer. If the send operation is completed immediately the routine returns None and the call-back function is not invoked. If the operation is not completed immediately and no exception is raised, then the UCP library will schedule invocation of the call-back upon completion of the send operation. In other words, the completion of the operation will be signaled either by the return code or by the call-back. Note ---- The user should not modify any part of the buffer after this operation is called, until the operation completes. Parameters ---------- ep: UCXEndpoint The destination endpoint buffer: Array An ``Array`` wrapping a user-provided array-like object nbytes: int Size of the buffer to use. Must be equal or less than the size of buffer cb_func: callable The call-back function, which must accept `request` and `exception` as the first two arguments. cb_args: tuple, optional Extra arguments to the call-back function cb_kwargs: dict, optional Extra keyword arguments to the call-back function name: str, optional Descriptive name of the operation """ ep.raise_on_error() if cb_args is None: cb_args = () if cb_kwargs is None: cb_kwargs = {} if name is None: name = u"stream_send_nb" if Feature.STREAM not in ep.worker._context._feature_flags: raise ValueError("UCXContext must be created with `Feature.STREAM`") if buffer.cuda and not ep.worker._context.cuda_support: raise ValueError( "UCX is not configured with CUDA support, please add " "`cuda_copy` and/or `cuda_ipc` to the `UCX_TLS` environment" "variable if you're manually setting a different value. If you" "are building UCX from source, please see " "https://ucx-py.readthedocs.io/en/latest/install.html for " "more information." ) if not buffer._contiguous(): raise ValueError("Array must be C or F contiguous") cdef ucp_send_callback_t _send_cb = <ucp_send_callback_t>_send_callback cdef ucs_status_ptr_t status = ucp_stream_send_nb( ep._handle, <void*>buffer.ptr, nbytes, ucp_dt_make_contig(1), _send_cb, 0 ) return _handle_status( status, nbytes, cb_func, cb_args, cb_kwargs, name, ep._inflight_msgs ) cdef void _stream_recv_callback( void *request, ucs_status_t status, size_t length ) with gil: cdef UCXRequest req cdef dict req_info cdef str name, ucx_status_msg, msg cdef set inflight_msgs cdef tuple cb_args cdef dict cb_kwargs with log_errors(): req = UCXRequest(<uintptr_t><void*> request) assert not req.closed() req_info = <dict>req._handle.info req_info["status"] = "finished" if "cb_func" not in req_info: # This callback function was called before ucp_tag_recv_nb() returned return exception = None if status == UCS_ERR_CANCELED: name = req_info["name"] msg = "<%s>: " % name exception = UCXCanceled(msg) elif status == UCS_ERR_NOT_CONNECTED: name = req_info["name"] msg = "<%s>: " % name exception = UCXNotConnected(msg) elif status == UCS_ERR_UNREACHABLE: name = req_info["name"] msg = "<%s>: " % name exception = UCXUnreachable(msg) elif status != UCS_OK: name = req_info["name"] ucx_status_msg = ucs_status_string(status).decode("utf-8") msg = "<%s>: %s" % (name, ucx_status_msg) exception = UCXError(msg) elif length != req_info["expected_receive"]: name = req_info["name"] msg = "<%s>: length mismatch: %d (got) != %d (expected)" % ( name, length, req_info["expected_receive"] ) exception = UCXMsgTruncated(msg) try: inflight_msgs = req_info["inflight_msgs"] inflight_msgs.discard(req) cb_func = req_info["cb_func"] if cb_func is not None: cb_args = req_info["cb_args"] if cb_args is None: cb_args = () cb_kwargs = req_info["cb_kwargs"] if cb_kwargs is None: cb_kwargs = {} cb_func(req, exception, *cb_args, **cb_kwargs) finally: req.close() def stream_recv_nb( UCXEndpoint ep, Array buffer, size_t nbytes, cb_func, tuple cb_args=None, dict cb_kwargs=None, str name=None ): """ This routine receives data on the endpoint. The routine is non-blocking and therefore returns immediately. The receive operation is considered complete when the message is delivered to the buffer. If data is not immediately available, the operation will be scheduled for receive and a request handle will be returned. In order to notify the application about completion of a scheduled receive operation, the UCP library will invoke the call-back when data is in the receive buffer and ready for application access. If the receive operation cannot be started, the routine raise an exception. Parameters ---------- ep: UCXEndpoint The destination endpoint buffer: Array An ``Array`` wrapping a user-provided array-like object nbytes: int Size of the buffer to use. Must be equal or less than the size of buffer cb_func: callable The call-back function, which must accept `request` and `exception` as the first two arguments. cb_args: tuple, optional Extra arguments to the call-back function cb_kwargs: dict, optional Extra keyword arguments to the call-back function name: str, optional Descriptive name of the operation """ if cb_args is None: cb_args = () if cb_kwargs is None: cb_kwargs = {} if name is None: name = u"stream_recv_nb" if buffer.readonly: raise ValueError("writing to readonly buffer!") if Feature.STREAM not in ep.worker._context._feature_flags: raise ValueError("UCXContext must be created with `Feature.STREAM`") if buffer.cuda and not ep.worker._context.cuda_support: raise ValueError( "UCX is not configured with CUDA support, please add " "`cuda_copy` and/or `cuda_ipc` to the `UCX_TLS` environment" "variable if you're manually setting a different value. If you" "are building UCX from source, please see " "https://ucx-py.readthedocs.io/en/latest/install.html for " "more information." ) if not buffer._contiguous(): raise ValueError("Array must be C or F contiguous") cdef size_t length cdef ucp_stream_recv_callback_t _stream_recv_cb = ( <ucp_stream_recv_callback_t>_stream_recv_callback ) cdef ucs_status_ptr_t status = ucp_stream_recv_nb( ep._handle, <void*>buffer.ptr, nbytes, ucp_dt_make_contig(1), _stream_recv_cb, &length, UCP_STREAM_RECV_FLAG_WAITALL, ) return _handle_status( status, nbytes, cb_func, cb_args, cb_kwargs, name, ep._inflight_msgs )
0
rapidsai_public_repos/ucx-py/ucp
rapidsai_public_repos/ucx-py/ucp/_libs/utils.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # See file LICENSE for terms. import fcntl import glob import os import socket import struct try: from nvtx import annotate as nvtx_annotate except ImportError: # If nvtx module is not installed, `annotate` yields only. from contextlib import contextmanager @contextmanager def nvtx_annotate(message=None, color=None, domain=None): yield try: from dask.utils import format_bytes, format_time, parse_bytes except ImportError: def format_time(x): if x < 1e-6: return f"{x * 1e9:.3f} ns" if x < 1e-3: return f"{x * 1e6:.3f} us" if x < 1: return f"{x * 1e3:.3f} ms" else: return f"{x:.3f} s" def format_bytes(x): """Return formatted string in B, KiB, MiB, GiB or TiB""" if x < 1024: return f"{x} B" elif x < 1024**2: return f"{x / 1024:.2f} KiB" elif x < 1024**3: return f"{x / 1024**2:.2f} MiB" elif x < 1024**4: return f"{x / 1024**3:.2f} GiB" else: return f"{x / 1024**4:.2f} TiB" parse_bytes = None def print_separator(separator="-", length=80): """Print a single separator character multiple times""" print(separator * length) def print_key_value(key, value, key_length=25): """Print a key and value with fixed key-field length""" print(f"{key: <{key_length}} | {value}") def print_multi(values, key_length=25): """Print a key and value with fixed key-field length""" assert isinstance(values, tuple) or isinstance(values, list) assert len(values) > 1 print_str = "".join(f"{s: <{key_length}} | " for s in values[:-1]) print_str += values[-1] print(print_str) def get_address(ifname=None): """ Get the address associated with a network interface. Parameters ---------- ifname : str The network interface name to find the address for. If None, it uses the value of environment variable `UCXPY_IFNAME` and if `UCXPY_IFNAME` is not set it defaults to "ib0" An OSError is raised for invalid interfaces. Returns ------- address : str The inet addr associated with an interface. Raises ------ RuntimeError If a network address could not be determined. Examples -------- >>> get_address() '10.33.225.160' >>> get_address(ifname='lo') '127.0.0.1' """ def _get_address(ifname): ifname = ifname.encode() with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: return socket.inet_ntoa( fcntl.ioctl( s.fileno(), 0x8915, struct.pack("256s", ifname[:15]) # SIOCGIFADDR )[20:24] ) def _try_interfaces(): prefix_priority = ["ib", "eth", "en", "docker"] iftypes = {p: [] for p in prefix_priority} for i in glob.glob("/sys/class/net/*"): name = i.split("/")[-1] for p in prefix_priority: if name.startswith(p): iftypes[p].append(name) for p in prefix_priority: iftype = iftypes[p] iftype.sort() for i in iftype: try: return _get_address(i) except OSError: pass raise RuntimeError( "A network address could not be determined, an interface that has a valid " "IP address with the environment variable `UCXPY_IFNAME`." ) if ifname is None: ifname = os.environ.get("UCXPY_IFNAME") if ifname is not None: return _get_address(ifname) else: return _try_interfaces()
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_peer_send_recv.py
import multiprocessing as mp import os from itertools import repeat import pytest from ucp._libs import ucx_api from ucp._libs.utils_test import blocking_flush, blocking_recv, blocking_send mp = mp.get_context("spawn") def _rma_setup(worker, address, prkey, base, msg_size): ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, address, endpoint_error_handling=True ) rkey = ep.unpack_rkey(prkey) mem = ucx_api.RemoteMemory(rkey, base, msg_size) return ep, mem def _test_peer_communication_rma(queue, rank, msg_size): ctx = ucx_api.UCXContext(feature_flags=(ucx_api.Feature.RMA, ucx_api.Feature.TAG)) worker = ucx_api.UCXWorker(ctx) self_address = worker.get_address() mem_handle = ctx.alloc(msg_size) self_base = mem_handle.address self_prkey = mem_handle.pack_rkey() self_ep, self_mem = _rma_setup( worker, self_address, self_prkey, self_base, msg_size ) send_msg = bytes(repeat(rank, msg_size)) if not self_mem.put_nbi(send_msg): blocking_flush(self_ep) queue.put((rank, self_address, self_prkey, self_base)) right_rank, right_address, right_prkey, right_base = queue.get() left_rank, left_address, left_prkey, left_base = queue.get() right_ep, right_mem = _rma_setup( worker, right_address, right_prkey, right_base, msg_size ) right_msg = bytearray(msg_size) right_mem.get_nbi(right_msg) left_ep, left_mem = _rma_setup( worker, left_address, left_prkey, left_base, msg_size ) left_msg = bytearray(msg_size) left_mem.get_nbi(left_msg) blocking_flush(worker) assert left_msg == bytes(repeat(left_rank, msg_size)) assert right_msg == bytes(repeat(right_rank, msg_size)) # We use the blocking tag send/recv as a barrier implementation recv_msg = bytearray(8) if rank == 0: send_msg = bytes(os.urandom(8)) blocking_send(worker, right_ep, send_msg, right_rank) blocking_recv(worker, left_ep, recv_msg, rank) else: blocking_recv(worker, left_ep, recv_msg, rank) blocking_send(worker, right_ep, recv_msg, right_rank) def _test_peer_communication_tag(queue, rank, msg_size): ctx = ucx_api.UCXContext(feature_flags=(ucx_api.Feature.TAG,)) worker = ucx_api.UCXWorker(ctx) queue.put((rank, worker.get_address())) right_rank, right_address = queue.get() left_rank, left_address = queue.get() right_ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, right_address, endpoint_error_handling=True, ) left_ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, left_address, endpoint_error_handling=True, ) recv_msg = bytearray(msg_size) if rank == 0: send_msg = bytes(os.urandom(msg_size)) blocking_send(worker, right_ep, send_msg, right_rank) blocking_recv(worker, left_ep, recv_msg, rank) assert send_msg == recv_msg else: blocking_recv(worker, left_ep, recv_msg, rank) blocking_send(worker, right_ep, recv_msg, right_rank) @pytest.mark.parametrize( "test_name", [_test_peer_communication_tag, _test_peer_communication_rma] ) @pytest.mark.parametrize("msg_size", [10, 2**24]) def test_peer_communication(test_name, msg_size, num_nodes=2): """Test peer communication by sending a message between each worker""" queues = [mp.Queue() for _ in range(num_nodes)] ps = [] addresses = [] for rank, queue in enumerate(queues): p = mp.Process(target=test_name, args=(queue, rank, msg_size)) p.start() ps.append(p) addresses.append(queue.get()) for i in range(num_nodes): queues[i].put(addresses[(i + 1) % num_nodes]) # Right peer queues[i].put(addresses[(i - 1) % num_nodes]) # Left peer for p in ps: p.join() assert not p.exitcode
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_cancel.py
import multiprocessing as mp import re import pytest from ucp._libs import ucx_api from ucp._libs.arr import Array from ucp._libs.utils import get_address from ucp.exceptions import UCXCanceled mp = mp.get_context("spawn") WireupMessage = bytearray(b"wireup") DataMessage = bytearray(b"0" * 10) def _handler(request, exception, ret): if exception is not None: ret[0] = exception else: ret[0] = request def _server_cancel(queue, transfer_api): """Server that establishes an endpoint to client and immediately closes it, triggering received messages to be canceled on the client. """ feature_flags = ( ucx_api.Feature.AM if transfer_api == "am" else ucx_api.Feature.TAG, ) ctx = ucx_api.UCXContext(feature_flags=feature_flags) worker = ucx_api.UCXWorker(ctx) # Keep endpoint to be used from outside the listener callback ep = [None] def _listener_handler(conn_request): ep[0] = ucx_api.UCXEndpoint.create_from_conn_request( worker, conn_request, endpoint_error_handling=True, ) listener = ucx_api.UCXListener(worker=worker, port=0, cb_func=_listener_handler) queue.put(listener.port) while ep[0] is None: worker.progress() ep[0].close() worker.progress() def _client_cancel(queue, transfer_api): """Client that connects to server and waits for messages to be received, because the server closes without sending anything, the messages will trigger cancelation. """ feature_flags = ( ucx_api.Feature.AM if transfer_api == "am" else ucx_api.Feature.TAG, ) ctx = ucx_api.UCXContext(feature_flags=feature_flags) worker = ucx_api.UCXWorker(ctx) port = queue.get() ep = ucx_api.UCXEndpoint.create( worker, get_address(), port, endpoint_error_handling=True, ) ret = [None] if transfer_api == "am": ucx_api.am_recv_nb(ep, cb_func=_handler, cb_args=(ret,)) match_msg = ".*am_recv.*" else: msg = Array(bytearray(1)) ucx_api.tag_recv_nb( worker, msg, msg.nbytes, tag=0, cb_func=_handler, cb_args=(ret,), ep=ep ) match_msg = ".*tag_recv_nb.*" while ep.is_alive(): worker.progress() canceled = worker.cancel_inflight_messages() while ret[0] is None: worker.progress() assert canceled == 1 assert isinstance(ret[0], UCXCanceled) assert re.match(match_msg, ret[0].args[0]) @pytest.mark.parametrize("transfer_api", ["am", "tag"]) def test_message_probe(transfer_api): queue = mp.Queue() server = mp.Process( target=_server_cancel, args=(queue, transfer_api), ) server.start() client = mp.Process( target=_client_cancel, args=(queue, transfer_api), ) client.start() client.join(timeout=10) server.join(timeout=10) assert client.exitcode == 0 assert server.exitcode == 0
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_arr.py
import array import functools import io import mmap import operator import pytest from ucp._libs.arr import Array builtin_buffers = [ b"", b"abcd", array.array("i", []), array.array("i", [0, 1, 2, 3]), array.array("I", [0, 1, 2, 3]), array.array("f", []), array.array("f", [0, 1, 2, 3]), array.array("d", [0, 1, 2, 3]), memoryview(array.array("B", [0, 1, 2, 3, 4, 5])).cast("B", (3, 2)), memoryview(b"abcd"), memoryview(bytearray(b"abcd")), io.BytesIO(b"abcd").getbuffer(), mmap.mmap(-1, 5), ] @pytest.mark.parametrize("buffer", builtin_buffers) def test_Array_ptr_builtins(buffer): arr = Array(buffer) assert arr.ptr != 0 @pytest.mark.parametrize("buffer", builtin_buffers) def test_Array_readonly_builtins(buffer): arr = Array(buffer) mv = memoryview(buffer) assert arr.readonly == mv.readonly @pytest.mark.parametrize("buffer", builtin_buffers) def test_Array_obj_builtins(buffer): arr = Array(buffer) mv = memoryview(buffer) assert arr.obj is mv.obj @pytest.mark.parametrize("buffer", builtin_buffers) def test_Array_itemsize_builtins(buffer): arr = Array(buffer) mv = memoryview(buffer) assert arr.itemsize == mv.itemsize @pytest.mark.parametrize("buffer", builtin_buffers) def test_Array_ndim_builtins(buffer): arr = Array(buffer) mv = memoryview(buffer) assert arr.ndim == mv.ndim @pytest.mark.parametrize("buffer", builtin_buffers) def test_Array_shape_builtins(buffer): arr = Array(buffer) mv = memoryview(buffer) assert arr.shape == mv.shape @pytest.mark.parametrize("buffer", builtin_buffers) def test_Array_strides_builtins(buffer): arr = Array(buffer) mv = memoryview(buffer) assert arr.strides == mv.strides @pytest.mark.parametrize("buffer", builtin_buffers) def test_Array_nbytes_builtins(buffer): arr = Array(buffer) mv = memoryview(buffer) assert arr.nbytes == mv.nbytes @pytest.mark.parametrize("buffer", builtin_buffers) def test_Array_contiguous_builtins(buffer): mv = memoryview(buffer) arr = Array(buffer) assert arr.c_contiguous == mv.c_contiguous assert arr.f_contiguous == mv.f_contiguous assert arr.contiguous == mv.contiguous mv2 = memoryview(buffer)[::2] if mv2: arr2 = Array(mv2) assert arr2.c_contiguous == mv2.c_contiguous assert arr2.f_contiguous == mv2.f_contiguous assert arr2.contiguous == mv2.contiguous array_params = [ ((2, 3), "i4", (12, 4)), ((2, 3), "u4", (12, 4)), ((2, 3), "f4", (12, 4)), ((2, 3), "f8", (24, 8)), ((2, 3), "f8", (8, 16)), ] def create_array(xp, shape, dtype, strides): if xp == "cupy": iface_prop = "__cuda_array_interface__" elif xp == "numpy": iface_prop = "__array_interface__" xp = pytest.importorskip(xp) nelem = functools.reduce(operator.mul, shape, 1) data = xp.arange(nelem, dtype=dtype) arr = xp.ndarray(shape, dtype, data.data, strides=strides) iface = getattr(arr, iface_prop) return xp, arr, iface @pytest.mark.parametrize("xp", ["cupy", "numpy"]) @pytest.mark.parametrize("shape, dtype, strides", array_params) def test_Array_ndarray_ptr(xp, shape, dtype, strides): xp, arr, iface = create_array(xp, shape, dtype, strides) arr2 = Array(arr) assert arr2.ptr == iface["data"][0] @pytest.mark.parametrize("xp", ["cupy", "numpy"]) @pytest.mark.parametrize("shape, dtype, strides", array_params) def test_Array_ndarray_is_cuda(xp, shape, dtype, strides): xp, arr, iface = create_array(xp, shape, dtype, strides) arr2 = Array(arr) is_cuda = xp.__name__ == "cupy" assert arr2.cuda == is_cuda @pytest.mark.parametrize("xp", ["cupy", "numpy"]) @pytest.mark.parametrize("shape, dtype, strides", array_params) def test_Array_ndarray_nbytes(xp, shape, dtype, strides): xp, arr, iface = create_array(xp, shape, dtype, strides) arr2 = Array(arr) assert arr2.nbytes == arr.nbytes @pytest.mark.parametrize("xp", ["cupy", "numpy"]) @pytest.mark.parametrize("shape, dtype, strides", array_params) def test_Array_ndarray_shape(xp, shape, dtype, strides): xp, arr, iface = create_array(xp, shape, dtype, strides) arr2 = Array(arr) assert arr2.shape == arr.shape @pytest.mark.parametrize("xp", ["cupy", "numpy"]) @pytest.mark.parametrize("shape, dtype, strides", array_params) def test_Array_ndarray_strides(xp, shape, dtype, strides): xp, arr, iface = create_array(xp, shape, dtype, strides) arr2 = Array(arr) assert arr2.strides == arr.strides @pytest.mark.parametrize("xp", ["cupy", "numpy"]) @pytest.mark.parametrize("shape, dtype, strides", array_params) def test_Array_ndarray_contiguous(xp, shape, dtype, strides): xp, arr, iface = create_array(xp, shape, dtype, strides) arr2 = Array(arr) assert arr2.c_contiguous == arr.flags.c_contiguous assert arr2.f_contiguous == arr.flags.f_contiguous assert arr2.contiguous == (arr.flags.c_contiguous or arr.flags.f_contiguous)
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_probe.py
import multiprocessing as mp import pytest from ucp._libs import ucx_api from ucp._libs.utils import get_address from ucp._libs.utils_test import ( blocking_am_recv, blocking_am_send, blocking_recv, blocking_send, ) mp = mp.get_context("spawn") WireupMessage = bytearray(b"wireup") DataMessage = bytearray(b"0" * 10) def _server_probe(queue, transfer_api): """Server that probes and receives message after client disconnected. Note that since it is illegal to call progress() in callback functions, we keep a reference to the endpoint after the listener callback has terminated, this way we can progress even after Python blocking calls. """ feature_flags = ( ucx_api.Feature.AM if transfer_api == "am" else ucx_api.Feature.TAG, ) ctx = ucx_api.UCXContext(feature_flags=feature_flags) worker = ucx_api.UCXWorker(ctx) # Keep endpoint to be used from outside the listener callback ep = [None] def _listener_handler(conn_request): ep[0] = ucx_api.UCXEndpoint.create_from_conn_request( worker, conn_request, endpoint_error_handling=True, ) listener = ucx_api.UCXListener(worker=worker, port=0, cb_func=_listener_handler) queue.put(listener.port), while ep[0] is None: worker.progress() ep = ep[0] # Ensure wireup and inform client before it can disconnect if transfer_api == "am": wireup = blocking_am_recv(worker, ep) else: wireup = bytearray(len(WireupMessage)) blocking_recv(worker, ep, wireup) queue.put("wireup completed") # Ensure client has disconnected -- endpoint is not alive anymore while ep.is_alive() is True: worker.progress() # Probe/receive message even after the remote endpoint has disconnected if transfer_api == "am": while ep.am_probe() is False: worker.progress() received = blocking_am_recv(worker, ep) else: while worker.tag_probe(0) is False: worker.progress() received = bytearray(len(DataMessage)) blocking_recv(worker, ep, received) assert wireup == WireupMessage assert received == DataMessage def _client_probe(queue, transfer_api): feature_flags = ( ucx_api.Feature.AM if transfer_api == "am" else ucx_api.Feature.TAG, ) ctx = ucx_api.UCXContext(feature_flags=feature_flags) worker = ucx_api.UCXWorker(ctx) port = queue.get() ep = ucx_api.UCXEndpoint.create( worker, get_address(), port, endpoint_error_handling=True, ) _send = blocking_am_send if transfer_api == "am" else blocking_send _send(worker, ep, WireupMessage) _send(worker, ep, DataMessage) # Wait for wireup before disconnecting assert queue.get() == "wireup completed" @pytest.mark.parametrize("transfer_api", ["am", "tag"]) def test_message_probe(transfer_api): queue = mp.Queue() server = mp.Process( target=_server_probe, args=(queue, transfer_api), ) server.start() client = mp.Process( target=_client_probe, args=(queue, transfer_api), ) client.start() client.join(timeout=10) server.join(timeout=10) assert client.exitcode == 0 assert server.exitcode == 0
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_rma.py
import array import io import mmap import os import pytest from ucp._libs import ucx_api from ucp._libs.utils_test import blocking_flush builtin_buffers = [ b"", b"abcd", array.array("i", []), array.array("i", [0, 1, 2, 3]), array.array("I", [0, 1, 2, 3]), array.array("f", []), array.array("f", [0, 1, 2, 3]), array.array("d", [0, 1, 2, 3]), memoryview(array.array("B", [0, 1, 2, 3, 4, 5])).cast("B", (3, 2)), memoryview(b"abcd"), memoryview(bytearray(b"abcd")), io.BytesIO(b"abcd").getbuffer(), mmap.mmap(-1, 5), ] def _(*args, **kwargs): pass def test_flush(): ctx = ucx_api.UCXContext({}) worker = ucx_api.UCXWorker(ctx) ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, worker.get_address(), endpoint_error_handling=True, ) req = ep.flush(_) if req is None: info = req.info while info["status"] == "pending": worker.progress() assert info["status"] == "finished" @pytest.mark.parametrize("msg_size", [10, 2**24]) def test_implicit(msg_size): ctx = ucx_api.UCXContext({}) mem = ucx_api.UCXMemoryHandle.alloc(ctx, msg_size) packed_rkey = mem.pack_rkey() worker = ucx_api.UCXWorker(ctx) ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, worker.get_address(), endpoint_error_handling=True, ) rkey = ep.unpack_rkey(packed_rkey) self_mem = ucx_api.RemoteMemory(rkey, mem.address, msg_size) send_msg = bytes(os.urandom(msg_size)) if not self_mem.put_nbi(send_msg): blocking_flush(ep) recv_msg = bytearray(len(send_msg)) if not self_mem.get_nbi(recv_msg): blocking_flush(ep) assert send_msg == recv_msg @pytest.mark.parametrize("msg_size", [10, 2**24]) def test_explicit(msg_size): ctx = ucx_api.UCXContext({}) mem = ucx_api.UCXMemoryHandle.alloc(ctx, msg_size) packed_rkey = mem.pack_rkey() worker = ucx_api.UCXWorker(ctx) ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, worker.get_address(), endpoint_error_handling=True, ) rkey = ep.unpack_rkey(packed_rkey) self_mem = ucx_api.RemoteMemory(rkey, mem.address, msg_size) send_msg = bytes(os.urandom(msg_size)) put_req = self_mem.put_nb(send_msg, _) if put_req is not None: blocking_flush(ep) recv_msg = bytearray(len(send_msg)) recv_req = self_mem.get_nb(recv_msg, _) if recv_req is not None: blocking_flush(ep) assert send_msg == recv_msg @pytest.mark.parametrize("msg_size", [10, 2**24]) def test_ucxio(msg_size): ctx = ucx_api.UCXContext({}) mem = ucx_api.UCXMemoryHandle.alloc(ctx, msg_size) packed_rkey = mem.pack_rkey() worker = ucx_api.UCXWorker(ctx) ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, worker.get_address(), endpoint_error_handling=True, ) rkey = ep.unpack_rkey(packed_rkey) uio = ucx_api.UCXIO(mem.address, msg_size, rkey) send_msg = bytes(os.urandom(msg_size)) uio.write(send_msg) uio.seek(0) recv_msg = uio.read(msg_size) assert send_msg == recv_msg # The alloc function may return more memory than requested based on OS page # size. So this test for insane seek values uses 2GB seeks to make sure we # always run into trouble max_possible = 2 * 1024 * 1024 * 1024 @pytest.mark.parametrize("seek_loc", [-max_possible, max_possible]) @pytest.mark.parametrize("seek_flag", [io.SEEK_CUR, io.SEEK_SET, io.SEEK_END]) def test_ucxio_seek_bad(seek_loc, seek_flag): msg_size = 1024 ctx = ucx_api.UCXContext({}) mem = ucx_api.UCXMemoryHandle.alloc(ctx, msg_size) packed_rkey = mem.pack_rkey() worker = ucx_api.UCXWorker(ctx) ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, worker.get_address(), endpoint_error_handling=True, ) rkey = ep.unpack_rkey(packed_rkey) uio = ucx_api.UCXIO(mem.address, msg_size, rkey) send_msg = bytes(os.urandom(msg_size)) uio.write(send_msg) uio.seek(seek_loc, seek_flag) recv_msg = uio.read(len(send_msg)) if seek_loc > 0: expected = b"" else: expected = send_msg assert recv_msg == expected @pytest.mark.parametrize( "seek_data", [(io.SEEK_CUR, -25), (io.SEEK_SET, 4), (io.SEEK_END, -8)] ) def test_ucxio_seek_good(seek_data): seek_flag, seek_dest = seek_data ctx = ucx_api.UCXContext({}) mem = ucx_api.UCXMemoryHandle.alloc(ctx, 1024) msg_size = mem.length packed_rkey = mem.pack_rkey() worker = ucx_api.UCXWorker(ctx) ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, worker.get_address(), endpoint_error_handling=True, ) rkey = ep.unpack_rkey(packed_rkey) uio = ucx_api.UCXIO(mem.address, msg_size, rkey) send_msg = bytes(os.urandom(msg_size)) uio.write(send_msg) uio.seek(seek_dest, seek_flag) recv_msg = uio.read(4) assert recv_msg == send_msg[seek_dest : seek_dest + 4] def test_force_requests(): msg_size = 1024 ctx = ucx_api.UCXContext({}) mem = ucx_api.UCXMemoryHandle.alloc(ctx, msg_size) packed_rkey = mem.pack_rkey() worker = ucx_api.UCXWorker(ctx) ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, worker.get_address(), endpoint_error_handling=True, ) rkey = ep.unpack_rkey(packed_rkey) self_mem = ucx_api.RemoteMemory(rkey, mem.address, msg_size) counter = 0 send_msg = bytes(os.urandom(msg_size)) req = self_mem.put_nb(send_msg, _) while req is None: counter = counter + 1 req = self_mem.put_nb(send_msg, _) # This `if` is here because some combinations of transports, such as # normal desktop PCs, will never have their transports exhausted. So # we have a break to make sure this test still completes if counter > 10000: pytest.xfail("Could not generate a request") blocking_flush(worker) while worker.progress(): pass while self_mem.put_nb(send_msg, _): pass blocking_flush(worker)
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_address_object.py
import multiprocessing as mp import pickle from ucp._libs import ucx_api mp = mp.get_context("spawn") def test_pickle_ucx_address(): ctx = ucx_api.UCXContext() worker = ucx_api.UCXWorker(ctx) org_address = worker.get_address() dumped_address = pickle.dumps(org_address) org_address_hash = hash(org_address) org_address = bytes(org_address) new_address = pickle.loads(dumped_address) assert org_address_hash == hash(new_address) assert bytes(org_address) == bytes(new_address)
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_config.py
import os import pytest from ucp._libs import ucx_api from ucp._libs.arr import Array from ucp._libs.exceptions import UCXConfigError def test_get_config(): # Cache user-defined UCX_TLS and unset it to test default value tls = os.environ.get("UCX_TLS", None) if tls is not None: del os.environ["UCX_TLS"] ctx = ucx_api.UCXContext() config = ctx.get_config() assert isinstance(config, dict) assert config["TLS"] == "all" # Restore user-defined UCX_TLS if tls is not None: os.environ["UCX_TLS"] = tls def test_set_env(): os.environ["UCX_SEG_SIZE"] = "2M" ctx = ucx_api.UCXContext() config = ctx.get_config() assert config["SEG_SIZE"] == os.environ["UCX_SEG_SIZE"] def test_init_options(): os.environ["UCX_SEG_SIZE"] = "2M" # Should be ignored options = {"SEG_SIZE": "3M"} ctx = ucx_api.UCXContext(options) config = ctx.get_config() assert config["SEG_SIZE"] == options["SEG_SIZE"] @pytest.mark.skipif( ucx_api.get_ucx_version() >= (1, 12, 0), reason="Beginning with UCX >= 1.12, it's only possible to validate " "UCP options but not options from other modules such as UCT. " "See https://github.com/openucx/ucx/issues/7519.", ) def test_init_unknown_option(): options = {"UNKNOWN_OPTION": "3M"} with pytest.raises(UCXConfigError): ucx_api.UCXContext(options) def test_init_invalid_option(): options = {"SEG_SIZE": "invalid-size"} with pytest.raises(UCXConfigError): ucx_api.UCXContext(options) @pytest.mark.parametrize( "feature_flag", [ucx_api.Feature.TAG, ucx_api.Feature.STREAM, ucx_api.Feature.AM] ) def test_feature_flags_mismatch(feature_flag): ctx = ucx_api.UCXContext(feature_flags=(feature_flag,)) worker = ucx_api.UCXWorker(ctx) addr = worker.get_address() ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, addr, endpoint_error_handling=False ) msg = Array(bytearray(10)) if feature_flag != ucx_api.Feature.TAG: with pytest.raises( ValueError, match="UCXContext must be created with `Feature.TAG`" ): ucx_api.tag_send_nb(ep, msg, msg.nbytes, 0, None) with pytest.raises( ValueError, match="UCXContext must be created with `Feature.TAG`" ): ucx_api.tag_recv_nb(worker, msg, msg.nbytes, 0, None) if feature_flag != ucx_api.Feature.STREAM: with pytest.raises( ValueError, match="UCXContext must be created with `Feature.STREAM`" ): ucx_api.stream_send_nb(ep, msg, msg.nbytes, None) with pytest.raises( ValueError, match="UCXContext must be created with `Feature.STREAM`" ): ucx_api.stream_recv_nb(ep, msg, msg.nbytes, None) if feature_flag != ucx_api.Feature.AM: with pytest.raises( ValueError, match="UCXContext must be created with `Feature.AM`" ): ucx_api.am_send_nbx(ep, msg, msg.nbytes, None) with pytest.raises( ValueError, match="UCXContext must be created with `Feature.AM`" ): ucx_api.am_recv_nb(ep, None)
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_mem.py
import array import io import mmap import pytest from ucp._libs import ucx_api builtin_buffers = [ b"", b"abcd", array.array("i", []), array.array("i", [0, 1, 2, 3]), array.array("I", [0, 1, 2, 3]), array.array("f", []), array.array("f", [0, 1, 2, 3]), array.array("d", [0, 1, 2, 3]), memoryview(array.array("B", [0, 1, 2, 3, 4, 5])).cast("B", (3, 2)), memoryview(b"abcd"), memoryview(bytearray(b"abcd")), io.BytesIO(b"abcd").getbuffer(), mmap.mmap(-1, 5), ] def test_alloc(): ctx = ucx_api.UCXContext({}) mem = ucx_api.UCXMemoryHandle.alloc(ctx, 1024) rkey = mem.pack_rkey() assert rkey is not None @pytest.mark.parametrize("buffer", builtin_buffers) def test_map(buffer): ctx = ucx_api.UCXContext({}) mem = ucx_api.UCXMemoryHandle.map(ctx, buffer) rkey = mem.pack_rkey() assert rkey is not None def test_ctx_alloc(): ctx = ucx_api.UCXContext({}) mem = ctx.alloc(1024) rkey = mem.pack_rkey() assert rkey is not None @pytest.mark.parametrize("buffer", builtin_buffers) def test_ctx_map(buffer): ctx = ucx_api.UCXContext({}) mem = ctx.map(buffer) rkey = mem.pack_rkey() assert rkey is not None def test_rkey_unpack(): ctx = ucx_api.UCXContext({}) mem = ucx_api.UCXMemoryHandle.alloc(ctx, 1024) packed_rkey = mem.pack_rkey() worker = ucx_api.UCXWorker(ctx) ep = ucx_api.UCXEndpoint.create_from_worker_address( worker, worker.get_address(), endpoint_error_handling=True, ) rkey = ep.unpack_rkey(packed_rkey) assert rkey is not None
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_endpoint.py
import functools import multiprocessing as mp import pytest from ucp._libs import ucx_api from ucp._libs.utils import get_address mp = mp.get_context("spawn") def _close_callback(closed): closed[0] = True def _server(queue, server_close_callback): """Server that send received message back to the client Notice, since it is illegal to call progress() in call-back functions, we use a "chain" of call-back functions. """ ctx = ucx_api.UCXContext(feature_flags=(ucx_api.Feature.TAG,)) worker = ucx_api.UCXWorker(ctx) listener_finished = [False] closed = [False] # A reference to listener's endpoint is stored to prevent it from going # out of scope too early. # ep = None def _listener_handler(conn_request): global ep ep = ucx_api.UCXEndpoint.create_from_conn_request( worker, conn_request, endpoint_error_handling=True, ) if server_close_callback is True: ep.set_close_callback(functools.partial(_close_callback, closed)) listener_finished[0] = True listener = ucx_api.UCXListener(worker=worker, port=0, cb_func=_listener_handler) queue.put(listener.port) if server_close_callback is True: while closed[0] is False: worker.progress() assert closed[0] is True else: while listener_finished[0] is False: worker.progress() def _client(port, server_close_callback): ctx = ucx_api.UCXContext(feature_flags=(ucx_api.Feature.TAG,)) worker = ucx_api.UCXWorker(ctx) ep = ucx_api.UCXEndpoint.create( worker, get_address(), port, endpoint_error_handling=True, ) if server_close_callback is True: ep.close() worker.progress() else: closed = [False] ep.set_close_callback(functools.partial(_close_callback, closed)) while closed[0] is False: worker.progress() @pytest.mark.parametrize("server_close_callback", [True, False]) def test_close_callback(server_close_callback): queue = mp.Queue() server = mp.Process( target=_server, args=(queue, server_close_callback), ) server.start() port = queue.get() client = mp.Process( target=_client, args=(port, server_close_callback), ) client.start() client.join(timeout=10) server.join(timeout=10) assert client.exitcode == 0 assert server.exitcode == 0
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_listener.py
from ucp._libs import ucx_api def test_listener_ip_port(): ctx = ucx_api.UCXContext() worker = ucx_api.UCXWorker(ctx) def _listener_handler(conn_request): pass listener = ucx_api.UCXListener(worker=worker, port=0, cb_func=_listener_handler) assert isinstance(listener.ip, str) and listener.ip assert ( isinstance(listener.port, int) and listener.port >= 0 and listener.port <= 65535 )
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_server_client.py
import multiprocessing as mp import os from queue import Empty as QueueIsEmpty import pytest from ucp._libs import ucx_api from ucp._libs.arr import Array from ucp._libs.utils import get_address from ucp._libs.utils_test import blocking_recv, blocking_send mp = mp.get_context("spawn") def _echo_server(get_queue, put_queue, msg_size): """Server that send received message back to the client Notice, since it is illegal to call progress() in call-back functions, we use a "chain" of call-back functions. """ ctx = ucx_api.UCXContext(feature_flags=(ucx_api.Feature.TAG,)) worker = ucx_api.UCXWorker(ctx) # A reference to listener's endpoint is stored to prevent it from going # out of scope too early. ep = None def _send_handle(request, exception, msg): # Notice, we pass `msg` to the handler in order to make sure # it doesn't go out of scope prematurely. assert exception is None def _recv_handle(request, exception, ep, msg): assert exception is None ucx_api.tag_send_nb( ep, msg, msg.nbytes, tag=0, cb_func=_send_handle, cb_args=(msg,) ) def _listener_handler(conn_request): global ep ep = ucx_api.UCXEndpoint.create_from_conn_request( worker, conn_request, endpoint_error_handling=True, ) msg = Array(bytearray(msg_size)) ucx_api.tag_recv_nb( worker, msg, msg.nbytes, tag=0, cb_func=_recv_handle, cb_args=(ep, msg) ) listener = ucx_api.UCXListener(worker=worker, port=0, cb_func=_listener_handler) put_queue.put(listener.port) while True: worker.progress() try: get_queue.get(block=False, timeout=0.1) except QueueIsEmpty: continue else: break def _echo_client(msg_size, port): ctx = ucx_api.UCXContext(feature_flags=(ucx_api.Feature.TAG,)) worker = ucx_api.UCXWorker(ctx) ep = ucx_api.UCXEndpoint.create( worker, get_address(), port, endpoint_error_handling=True, ) send_msg = bytes(os.urandom(msg_size)) recv_msg = bytearray(msg_size) blocking_send(worker, ep, send_msg) blocking_recv(worker, ep, recv_msg) assert send_msg == recv_msg @pytest.mark.parametrize("msg_size", [10, 2**24]) def test_server_client(msg_size): put_queue, get_queue = mp.Queue(), mp.Queue() server = mp.Process( target=_echo_server, args=(put_queue, get_queue, msg_size), ) server.start() port = get_queue.get() client = mp.Process(target=_echo_client, args=(msg_size, port)) client.start() client.join(timeout=10) assert not client.exitcode put_queue.put("Finished") server.join(timeout=10) assert not server.exitcode
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/tests/test_server_client_am.py
import multiprocessing as mp import os from functools import partial from queue import Empty as QueueIsEmpty import numpy as np import pytest from ucp._libs import ucx_api from ucp._libs.arr import Array from ucp._libs.utils import get_address from ucp._libs.utils_test import blocking_am_recv, blocking_am_send mp = mp.get_context("spawn") RNDV_THRESH = 8192 def get_data(): ret = {} ret["bytearray"] = { "allocator": bytearray, "generator": lambda n: bytearray(os.urandom(n)), "validator": lambda recv, exp: np.testing.assert_equal(recv, exp), "memory_type": ucx_api.AllocatorType.HOST, } ret["numpy"] = { "allocator": partial(np.ones, dtype=np.uint8), "generator": partial(np.arange, dtype=np.int64), "validator": lambda recv, exp: np.testing.assert_equal( recv.view(np.int64), exp ), "memory_type": ucx_api.AllocatorType.HOST, } try: import cupy as cp ret["cupy"] = { "allocator": partial(cp.ones, dtype=np.uint8), "generator": partial(cp.arange, dtype=np.int64), "validator": lambda recv, exp: cp.testing.assert_array_equal( recv.view(np.int64), exp ), "memory_type": ucx_api.AllocatorType.CUDA, } except ImportError: pass return ret def _echo_server(get_queue, put_queue, msg_size, datatype): """Server that send received message back to the client Notice, since it is illegal to call progress() in call-back functions, we use a "chain" of call-back functions. """ data = get_data()[datatype] ctx = ucx_api.UCXContext( config_dict={"RNDV_THRESH": str(RNDV_THRESH)}, feature_flags=(ucx_api.Feature.AM,), ) worker = ucx_api.UCXWorker(ctx) worker.register_am_allocator(data["allocator"], data["memory_type"]) # A reference to listener's endpoint is stored to prevent it from going # out of scope too early. ep = None def _send_handle(request, exception, msg): # Notice, we pass `msg` to the handler in order to make sure # it doesn't go out of scope prematurely. assert exception is None def _recv_handle(recv_obj, exception, ep): assert exception is None msg = Array(recv_obj) ucx_api.am_send_nbx(ep, msg, msg.nbytes, cb_func=_send_handle, cb_args=(msg,)) def _listener_handler(conn_request): global ep ep = ucx_api.UCXEndpoint.create_from_conn_request( worker, conn_request, endpoint_error_handling=True, ) # Wireup ucx_api.am_recv_nb(ep, cb_func=_recv_handle, cb_args=(ep,)) # Data ucx_api.am_recv_nb(ep, cb_func=_recv_handle, cb_args=(ep,)) listener = ucx_api.UCXListener(worker=worker, port=0, cb_func=_listener_handler) put_queue.put(listener.port) while True: worker.progress() try: get_queue.get(block=False, timeout=0.1) except QueueIsEmpty: continue else: break def _echo_client(msg_size, datatype, port): data = get_data()[datatype] ctx = ucx_api.UCXContext( config_dict={"RNDV_THRESH": str(RNDV_THRESH)}, feature_flags=(ucx_api.Feature.AM,), ) worker = ucx_api.UCXWorker(ctx) worker.register_am_allocator(data["allocator"], data["memory_type"]) ep = ucx_api.UCXEndpoint.create( worker, get_address(), port, endpoint_error_handling=True, ) # The wireup message is sent to ensure endpoints are connected, otherwise # UCX may not perform any rendezvous transfers. send_wireup = bytearray(b"wireup") send_data = data["generator"](msg_size) blocking_am_send(worker, ep, send_wireup) blocking_am_send(worker, ep, send_data) recv_wireup = blocking_am_recv(worker, ep) recv_data = blocking_am_recv(worker, ep) # Cast recv_wireup to bytearray when using NumPy as a host allocator, # this ensures the assertion below is correct if datatype == "numpy": recv_wireup = bytearray(recv_wireup) assert bytearray(recv_wireup) == send_wireup if data["memory_type"] == "cuda" and send_data.nbytes < RNDV_THRESH: # Eager messages are always received on the host, if no host # allocator is registered UCX-Py defaults to `bytearray`. assert recv_data == bytearray(send_data.get()) data["validator"](recv_data, send_data) @pytest.mark.parametrize("msg_size", [10, 2**24]) @pytest.mark.parametrize("datatype", get_data().keys()) def test_server_client(msg_size, datatype): put_queue, get_queue = mp.Queue(), mp.Queue() server = mp.Process( target=_echo_server, args=(put_queue, get_queue, msg_size, datatype), ) server.start() port = get_queue.get() client = mp.Process(target=_echo_client, args=(msg_size, datatype, port)) client.start() client.join(timeout=10) assert not client.exitcode put_queue.put("Finished") server.join(timeout=10) assert not server.exitcode
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/src/c_util.c
/** * Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. * See file LICENSE for terms. */ #include "c_util.h" #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int c_util_set_sockaddr(ucs_sock_addr_t *sockaddr, const char *ip_address, uint16_t port) { struct sockaddr_in *addr = malloc(sizeof(struct sockaddr_in)); if(addr == NULL) { return 1; } memset(addr, 0, sizeof(struct sockaddr_in)); addr->sin_family = AF_INET; addr->sin_addr.s_addr = ip_address==NULL ? INADDR_ANY : inet_addr(ip_address); addr->sin_port = htons(port); sockaddr->addr = (const struct sockaddr *) addr; sockaddr->addrlen = sizeof(struct sockaddr_in); return 0; } void c_util_sockaddr_free(ucs_sock_addr_t *sockaddr) { free((void*) sockaddr->addr); } void c_util_sockaddr_get_ip_port_str(const struct sockaddr_storage *sock_addr, char *ip_str, char *port_str, size_t max_str_size) { struct sockaddr_in addr_in; struct sockaddr_in6 addr_in6; switch (sock_addr->ss_family) { case AF_INET: memcpy(&addr_in, sock_addr, sizeof(struct sockaddr_in)); inet_ntop(AF_INET, &addr_in.sin_addr, ip_str, max_str_size); snprintf(port_str, max_str_size, "%d", ntohs(addr_in.sin_port)); case AF_INET6: memcpy(&addr_in6, sock_addr, sizeof(struct sockaddr_in6)); inet_ntop(AF_INET6, &addr_in6.sin6_addr, ip_str, max_str_size); snprintf(port_str, max_str_size, "%d", ntohs(addr_in6.sin6_port)); default: ip_str = "Invalid address family"; port_str = "Invalid address family"; } }
0
rapidsai_public_repos/ucx-py/ucp/_libs
rapidsai_public_repos/ucx-py/ucp/_libs/src/c_util.h
/** * Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. * See file LICENSE for terms. */ #include <stdint.h> #include <sys/socket.h> #include <ucp/api/ucp.h> int c_util_set_sockaddr(ucs_sock_addr_t *sockaddr, const char *ip_address, uint16_t port); void c_util_sockaddr_free(ucs_sock_addr_t *sockaddr); void c_util_sockaddr_get_ip_port_str( const struct sockaddr_storage *sock_addr, char *ip_str, char *port_str, size_t max_str_size );
0
rapidsai_public_repos/ucx-py/conda
rapidsai_public_repos/ucx-py/conda/environments/builddocs.yml
name: ucx_dev channels: - rapidsai - nvidia - conda-forge dependencies: # required for building docs - sphinx - sphinx-markdown-tables - sphinx_rtd_theme - sphinxcontrib-websupport - nbsphinx - numpydoc - recommonmark - pandoc=<2.0.0 - pip - ucx - cython - tomli
0
rapidsai_public_repos/ucx-py/conda/recipes
rapidsai_public_repos/ucx-py/conda/recipes/ucx-py/conda_build_config.yaml
c_compiler_version: - 11 cxx_compiler_version: - 11 ucx: - "==1.14.*"
0
rapidsai_public_repos/ucx-py/conda/recipes
rapidsai_public_repos/ucx-py/conda/recipes/ucx-py/meta.yaml
# Copyright (c) 2019-2023, NVIDIA CORPORATION. {% set data = load_file_data("pyproject.toml") %} {% set version = environ['RAPIDS_PACKAGE_VERSION'].lstrip('v') %} {% set py_version = environ['CONDA_PY'] %} {% set cuda_version = '.'.join(environ['RAPIDS_CUDA_VERSION'].split('.')[:2]) %} {% set date_string = environ['RAPIDS_DATE_STRING'] %} package: name: ucx-py version: {{ version }} source: path: ../../.. build: number: {{ GIT_DESCRIBE_NUMBER }} string: py{{ py_version }}_{{ date_string }}_{{ GIT_DESCRIBE_HASH }}_{{ GIT_DESCRIBE_NUMBER }} script: - {{ PYTHON }} -m pip install . -vv ignore_run_exports_from: - ucx requirements: build: - {{ compiler('c') }} - {{ compiler('cxx') }} host: - python - pip - ucx {% for r in data.get("build-system", {}).get("requires", []) %} - {{ r }} {% endfor %} run: - python - ucx >=1.14.1,<1.16.0 {% for r in data.get("project", {}).get("dependencies", []) %} - {{ r }} {% endfor %} test: imports: - ucp about: home: {{ data.get("project", {}).get("urls", {}).get("Homepage", "") }} license: {{ data.get("project", {}).get("license", {}).get("text", "") }} license_file: {% for e in data.get("tool", {}).get("setuptools", {}).get("license-files", []) %} - ../../../{{ e }} {% endfor %} summary: {{ data.get("project", {}).get("description", "") }} dev_url: {{ data.get("project", {}).get("urls", {}).get("Source", "") }} doc_url: {{ data.get("project", {}).get("urls", {}).get("Documentation", "") }}
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/docker/bench-all.sh
#!/bin/bash # Copyright (c) 2022, NVIDIA CORPORATION. set -e function logger { echo -e "\n$@\n" } # Requires conda installed at /opt/conda and the ucx environment setup # See UCXPy-CUDA.dockerfile source /opt/conda/etc/profile.d/conda.sh conda activate ucx cd ucx-py/ # Benchmark using command-line provided transports or else default for tls in ${@:-"tcp" "all"}; do export UCX_TLS=${tls} logger "Python pytest for ucx-py" logger "Tests (UCX_TLS=${UCX_TLS})" pytest --cache-clear -vs ucp/_libs/tests pytest --cache-clear -vs tests/ for array_type in "numpy" "cupy" "rmm"; do logger "Benchmarks (UCX_TLS=${UCX_TLS}, array_type=${array_type})" python ucp.benchmarks.send_recv -l ucp-async -o ${array_type} \ --server-dev 0 --client-dev 0 --reuse-alloc python ucp.benchmarks.send_recv -l ucp-core -o ${array_type} \ --server-dev 0 --client-dev 0 --reuse-alloc done done
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/docker/README.md
# Docker container ## Summary Contains reference dockerfile and build script to run UCX-Py tests and benchmarks. This is a minimal setup, without support for CUDA, MOFED, or rdma-core. ## Building Docker image To begin, it's necessary to build the image, this is done as follows: ```bash cd docker docker build -t ucx-py -f Dockerfile . ``` ## Running Once building the Docker image is complete, the container can be started with the following command: ```bash docker run ucx-py ``` The container above will run UCX-Py tests and benchmarks. ## Infiniband/NVLink-enabled docker file In addition to the reference Docker image, there are two further docker files which have support for CUDA devices and InfiniBand/NVLink-enabled communications using either [rdma-core](https://github.com/linux-rdma/rdma-core) or [MOFED](https://network.nvidia.com/products/infiniband-drivers/linux/mlnx_ofed/). In both cases, the default base image is [nvidia/cuda:11.5.2-devel-ubuntu20.04](https://hub.docker.com/r/nvidia/cuda/tags?page=1&name=11.5.2-devel-ubuntu20.04). The rdma-core image should work as long as the host system has MOFED >= 5.0. If you use the MOFED image, then the host version (reported by `ofed_info -s`) should match that used when building the container. To use one of these images, first build it ```bash docker build -t ucx-py-mofed -f UCXPy-MOFED.dockerfile . # or docker build -t ucx-py-rdma -f UCXPy-rdma-core.dockerfile . ``` ### Controlling build-args You can control some of the behaviour of the docker file with docker `--build-arg` flags: - `UCX_VERSION_TAG`: git committish for the version of UCX to build (default `v1.13.0`); - `CONDA_HOME`: Where to install conda in the image (default `/opt/conda`); - `CONDA_ENV`: What to name the conda environment (default `ucx`); - `CONDA_ENV_SPEC`: yaml file used when initially creating the conda environment (default `ucx-py-cuda11.5.yml`); - `CUDA_VERSION`: version of cuda toolkit in the base image (default `11.5.2`), must exist in the [nvidia/cuda](https://hub.docker.com/layers/cuda/nvidia/cuda) docker hub image list; - `DISTRIBUTION_VERSION`: version of distribution in the base image (default `ubuntu20.04`), must exist in the [nvidia/cuda](https://hub.docker.com/layers/cuda/nvidia/cuda) docker hub image list. Note that rdma-core provides forward-compatibility with version 28.0 (shipped with ubuntu20.04) supporting MOFED 5.0 and later. Other distributions may provide a different version of rdma-core for which MOFED compatibility may vary; - `MOFED_VERSION`: (MOFED image only) version of MOFED to download (default `5.3-1.0.5.0`), must match version on host system ### Running Running the container requires a number of additional flags to expose high-performance transports from the host. `docker run --privileged` is a catch-all that will definitely provide enough permissions (`ulimit -l unlimited` is then needed in the container). Alternately, provide `--ulimit memlock=-1` and expose devices with `--device /dev/infiniband`, see [the UCX documentation](https://openucx.readthedocs.io/en/master/running.html#running-in-docker-containers) for more details. To expose the infiniband devices using IPoIB, we need to in addition map the relevant host network interfaces, a catchall is just to use `--network host`. For example, a run command that exposes all devices available in `/dev/infiniband` along with the network interfaces on the host is (assuming that the `ucx-py-rdma` image tag has been built as above): ```bash docker run --ulimit memlock=-1 --device /dev/infiniband --network host -ti ucx-py-rdma /bin/bash ``` UCX-Py is installed via [mamba](https://mamba.readthedocs.io/en/latest/index.html) in the `ucx` environment; so ```bash source /opt/conda/etc/profile.d/conda.sh source /opt/conda/etc/profile.d/mamba.sh mamba activate ucx ``` in the container will provide a Python with UCX-Py available.
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/docker/ucx-py-cuda11.5.yml
channels: - rapidsai - nvidia - conda-forge dependencies: - python=3.9 - cudatoolkit=11.5 - setuptools - cython>=0.29.14,<3.0.0a0 - pytest - pytest-asyncio - dask - distributed - cupy - numba>=0.57 - rmm
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/docker/build-ucx.sh
#!/bin/bash set -ex UCX_VERSION_TAG=${1:-"v1.13.0"} CONDA_HOME=${2:-"/opt/conda"} CONDA_ENV=${3:-"ucx"} CUDA_HOME=${4:-"/usr/local/cuda"} # Send any remaining arguments to configure CONFIGURE_ARGS=${@:5} source ${CONDA_HOME}/etc/profile.d/conda.sh source ${CONDA_HOME}/etc/profile.d/mamba.sh mamba activate ${CONDA_ENV} git clone https://github.com/openucx/ucx.git cd ucx git checkout ${UCX_VERSION_TAG} ./autogen.sh mkdir build-linux && cd build-linux ../contrib/configure-release --prefix=${CONDA_PREFIX} --with-sysroot --enable-cma \ --enable-mt --enable-numa --with-gnu-ld --with-rdmacm --with-verbs \ --with-cuda=${CUDA_HOME} \ ${CONFIGURE_ARGS} make -j install
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/docker/run.sh
#!/bin/bash # Copyright (c) 2021, NVIDIA CORPORATION. set -e function logger { echo -e "\n$@\n" } PYTHON_PREFIX=$(python -c "import distutils.sysconfig; print(distutils.sysconfig.PREFIX)") ################################################################################ # SETUP - Install python packages and check environment ################################################################################ pip install \ "pytest" "pytest-asyncio" \ "dask" "distributed" \ "cython" logger "Check versions" python --version pip list ################################################################################ # BUILD - Build UCX master, UCX-Py and run tests ################################################################################ logger "Build UCX master" cd $HOME git clone https://github.com/openucx/ucx cd ucx ./autogen.sh ./contrib/configure-devel \ --prefix=$PYTHON_PREFIX \ --enable-gtest=no \ --with-valgrind=no make -j install echo $PYTHON_PREFIX >> /etc/ld.so.conf.d/python.conf ldconfig logger "UCX Version and Build Information" ucx_info -v ################################################################################ # TEST - Run pytests for ucx-py ################################################################################ logger "Clone and Build UCX-Py" cd $HOME git clone https://github.com/rapidsai/ucx-py cd ucx-py python setup.py build_ext --inplace python -m pip install -e . for tls in "tcp" "all"; do export UCX_TLS=$tls logger "Python pytest for ucx-py" # Test with TCP/Sockets logger "Tests (UCX_TLS=$UCX_TLS)" pytest --cache-clear -vs ucp/_libs/tests pytest --cache-clear -vs tests/ logger "Benchmarks (UCX_TLS=$UCX_TLS)" python -m ucp.benchmarks.send_recv -l ucp-async -o numpy \ --server-dev 0 --client-dev 0 --reuse-alloc python -m ucp.benchmarks.send_recv -l ucp-core -o numpy \ --server-dev 0 --client-dev 0 --reuse-alloc done
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/docker/UCXPy-rdma-core.dockerfile
ARG CUDA_VERSION=11.5.2 ARG DISTRIBUTION_VERSION=ubuntu20.04 FROM nvidia/cuda:${CUDA_VERSION}-devel-${DISTRIBUTION_VERSION} # Tag to checkout from UCX repository ARG UCX_VERSION_TAG=v1.13.0 # Where to install conda, and what to name the created environment ARG CONDA_HOME=/opt/conda ARG CONDA_ENV=ucx # Name of conda spec file in the current working directory that # will be used to build the conda environment. ARG CONDA_ENV_SPEC=ucx-py-cuda11.5.yml ENV CONDA_ENV="${CONDA_ENV}" ENV CONDA_HOME="${CONDA_HOME}" # Where cuda is installed ENV CUDA_HOME="/usr/local/cuda" SHELL ["/bin/bash", "-c"] RUN apt-get update -y \ && apt-get --fix-missing upgrade -y \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends tzdata \ && apt-get install -y \ automake \ dh-make \ git \ libcap2 \ libnuma-dev \ libtool \ make \ pkg-config \ udev \ curl \ librdmacm-dev \ rdma-core \ && apt-get autoremove -y \ && apt-get clean RUN curl -fsSL https://github.com/conda-forge/miniforge/releases/latest/download/Mambaforge-Linux-x86_64.sh \ -o /minimamba.sh \ && bash /minimamba.sh -b -p ${CONDA_HOME} \ && rm /minimamba.sh ENV PATH="${CONDA_HOME}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${CUDA_HOME}/bin" WORKDIR /root COPY ${CONDA_ENV_SPEC} /root/conda-env.yml COPY build-ucx.sh /root/build-ucx.sh COPY build-ucx-py.sh /root/build-ucx-py.sh RUN mamba env create -n ${CONDA_ENV} --file /root/conda-env.yml RUN bash ./build-ucx.sh ${UCX_VERSION_TAG} ${CONDA_HOME} ${CONDA_ENV} ${CUDA_HOME} RUN bash ./build-ucx-py.sh ${CONDA_HOME} ${CONDA_ENV}
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/docker/Dockerfile
FROM python:3 RUN apt-get update && \ DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends tzdata && \ apt-get install -y \ automake \ dh-make \ g++ \ git \ libcap2 \ libnuma-dev \ libtool \ make \ udev \ wget \ && apt-get remove -y openjdk-11-* || apt-get autoremove -y \ && apt-get clean && rm -rf /var/lib/apt/lists/* COPY run.sh /root WORKDIR /root CMD [ "/root/run.sh" ]
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/docker/build-ucx-py.sh
#!/bin/bash set -ex CONDA_HOME=${1:-"/opt/conda"} CONDA_ENV=${2:-"ucx"} source ${CONDA_HOME}/etc/profile.d/conda.sh source ${CONDA_HOME}/etc/profile.d/mamba.sh mamba activate ${CONDA_ENV} git clone https://github.com/rapidsai/ucx-py.git pip install -v ucx-py/
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/docker/UCXPy-MOFED.dockerfile
ARG CUDA_VERSION=11.5.2 ARG DISTRIBUTION_VERSION=ubuntu20.04 FROM nvidia/cuda:${CUDA_VERSION}-devel-${DISTRIBUTION_VERSION} # Make available to later build stages ARG DISTRIBUTION_VERSION # Should match host OS OFED version (as reported by ofed_info -s) ARG MOFED_VERSION=5.3-1.0.5.0 # Tag to checkout from UCX repository ARG UCX_VERSION_TAG=v1.13.0 # Where to install conda, and what to name the created environment ARG CONDA_HOME=/opt/conda ARG CONDA_ENV=ucx # Name of conda spec file in the current working directory that # will be used to build the conda environment. ARG CONDA_ENV_SPEC=ucx-py-cuda11.5.yml ENV CONDA_ENV="${CONDA_ENV}" ENV CONDA_HOME="${CONDA_HOME}" # Where cuda is installed ENV CUDA_HOME="/usr/local/cuda" SHELL ["/bin/bash", "-c"] RUN apt-get update -y \ && apt-get --fix-missing upgrade -y \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends tzdata \ && apt-get install -y \ automake \ dh-make \ git \ libcap2 \ libnuma-dev \ libtool \ make \ pkg-config \ udev \ curl \ && apt-get autoremove -y \ && apt-get clean RUN curl -fsSL https://github.com/conda-forge/miniforge/releases/latest/download/Mambaforge-Linux-x86_64.sh \ -o /minimamba.sh \ && bash /minimamba.sh -b -p ${CONDA_HOME} \ && rm /minimamba.sh ENV PATH="${CONDA_HOME}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${CUDA_HOME}/bin" RUN curl -fsSL https://content.mellanox.com/ofed/MLNX_OFED-${MOFED_VERSION}/MLNX_OFED_LINUX-${MOFED_VERSION}-${DISTRIBUTION_VERSION}-x86_64.tgz | tar xz \ && (cd MLNX_OFED_LINUX-${MOFED_VERSION}-${DISTRIBUTION_VERSION}-x86_64 \ && yes | ./mlnxofedinstall --user-space-only --without-fw-update \ --without-neohost-backend) \ && rm -rf /var/lib/apt/lists/* \ && rm -rf /MLNX_OFED_LINUX-${MOFED_VERSION}-${DISTRIBUTION_VERSION}-x86_64 WORKDIR /root COPY ${CONDA_ENV_SPEC} /root/conda-env.yml COPY build-ucx.sh /root/build-ucx.sh COPY build-ucx-py.sh /root/build-ucx-py.sh COPY bench-all.sh /root/bench-all.sh RUN mamba env create -n ${CONDA_ENV} --file /root/conda-env.yml RUN bash ./build-ucx.sh ${UCX_VERSION_TAG} ${CONDA_HOME} ${CONDA_ENV} ${CUDA_HOME} RUN bash ./build-ucx-py.sh ${CONDA_HOME} ${CONDA_ENV} CMD ["/root/bench-all.sh", "tcp,cuda_copy,cuda_ipc", "rc,cuda_copy", "all"]
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/docs/Makefile
# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/quickstart.rst
Quickstart ========== Setup ----- Create a new conda environment with UCX-Py: :: conda create -n ucx -c conda-forge -c rapidsai \ cudatoolkit=<CUDA version> ucx-py For a more detailed guide on installation options please refer to the :doc:`install` page. Send/Recv NumPy Arrays ---------------------- Process 1 - Server ~~~~~~~~~~~~~~~~~~ .. code-block:: python import asyncio import time import ucp import numpy as np n_bytes = 2**30 host = ucp.get_address(ifname='eth0') # ethernet device name port = 13337 async def send(ep): # recv buffer arr = np.empty(n_bytes, dtype='u1') await ep.recv(arr) assert np.count_nonzero(arr) == np.array(0, dtype=np.int64) print("Received NumPy array") # increment array and send back arr += 1 print("Sending incremented NumPy array") await ep.send(arr) await ep.close() lf.close() async def main(): global lf lf = ucp.create_listener(send, port) while not lf.closed(): await asyncio.sleep(0.1) if __name__ == '__main__': asyncio.run(main()) Process 2 - Client ~~~~~~~~~~~~~~~~~~ .. code-block:: python import asyncio import ucp import numpy as np port = 13337 n_bytes = 2**30 async def main(): host = ucp.get_address(ifname='eth0') # ethernet device name ep = await ucp.create_endpoint(host, port) msg = np.zeros(n_bytes, dtype='u1') # create some data to send # send message print("Send Original NumPy array") await ep.send(msg) # send the real message # recv response print("Receive Incremented NumPy arrays") resp = np.empty_like(msg) await ep.recv(resp) # receive the echo await ep.close() np.testing.assert_array_equal(msg + 1, resp) if __name__ == '__main__': asyncio.run(main()) Send/Recv CuPy Arrays --------------------- .. note:: If you are passing CuPy arrays between GPUs and want to use `NVLINK <https://www.nvidia.com/en-us/data-center/nvlink/>`_ ensure you have correctly set ``UCX_TLS`` with ``cuda_ipc``. See the :doc:`configuration` for more details Process 1 - Server ~~~~~~~~~~~~~~~~~~ .. code-block:: python import asyncio import time import ucp import cupy as cp n_bytes = 2**30 host = ucp.get_address(ifname='eth0') # ethernet device name port = 13337 async def send(ep): # recv buffer arr = cp.empty(n_bytes, dtype='u1') await ep.recv(arr) assert cp.count_nonzero(arr) == cp.array(0, dtype=cp.int64) print("Received CuPy array") # increment array and send back arr += 1 print("Sending incremented CuPy array") await ep.send(arr) await ep.close() lf.close() async def main(): global lf lf = ucp.create_listener(send, port) while not lf.closed(): await asyncio.sleep(0.1) if __name__ == '__main__': asyncio.run(main()) Process 2 - Client ~~~~~~~~~~~~~~~~~~ .. code-block:: python import asyncio import ucp import cupy as cp import numpy as np port = 13337 n_bytes = 2**30 async def main(): host = ucp.get_address(ifname='eth0') # ethernet device name ep = await ucp.create_endpoint(host, port) msg = cp.zeros(n_bytes, dtype='u1') # create some data to send # send message print("Send Original CuPy array") await ep.send(msg) # send the real message # recv response print("Receive Incremented CuPy arrays") resp = cp.empty_like(msg) await ep.recv(resp) # receive the echo await ep.close() cp.testing.assert_array_equal(msg + 1, resp) if __name__ == '__main__': asyncio.run(main())
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/os-limits.rst
Operating System Limits ======================= UCX can be affected by a variety of limits, not just defined by UCX itself but also by the operating system. In this section we describe some of the limits that may be encountered by the user when running UCX-Py or just UCX alone. File Descriptors ---------------- In sockets-based connections, multiple file descriptors may be open to establish connections between endpoints. When UCX is establishing connection between endpoints via protocols such as TCP, an error such as below may occur: :: ucp.exceptions.UCXError: User-defined limit was reached One possible cause for this is that the limit established by the OS or system administrators has been reached by the user. This limit can be checked with: :: $ ulimit -n If the user has permission to do so, the file descriptor limit can be increased by typing the new limit after the command above. For example, to set a new limit of 1 million, the following should be executed: :: $ ulimit -n 1000000 Another way the number of open files limit can be increased is by editing the limits.conf file in the operating system. Please consult your system administration for details. Please note that the number of open files required may different according to the application, further investigation may be required to find optimal values. For systems with specialized hardware such as InfiniBand, using RDMACM may also help circumventing that issue, as it doesn't rely heavily on file descriptors. Maximum Connections ------------------- UCX respects the operating system's limit of socket listen() backlog, known in userspace as SOMAXCONN. This limit may cause creating may cause new endpoints from connecting to a listener to hang if too many connections happen to be initiated too quickly. To check for the current limit, the user can execute the following command: :: $ sysctl net.core.somaxconn For most Linux distros, the default limit is 128. To increase that limit to 65535 for example, the user may run the following (require root or sudo permissions): :: $ sudo sysctl -w net.core.somaxconn=128
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/install.rst
Install ======= Prerequisites ------------- UCX depends on the following system libraries being present: * For system topology identification: ``libnuma`` (``numactl`` on Enterprise Linux) * For MOFED 4.x support: ``libibcm``, ``libibverbs`` and ``librdmacm``. Ideally installed from `Mellanox OFED Drivers <https://www.mellanox.com/products/infiniband-drivers/linux/mlnx_ofed>`_ * For MOFED 5.0 or higher: `Mellanox OFED Drivers <https://www.mellanox.com/products/infiniband-drivers/linux/mlnx_ofed>`_ Please install the packages above with your Linux system's package manager. When building from source you will also need the ``*-dev`` (``*-devel`` on Enterprise Linux) packages as well. Optional Packages ~~~~~~~~~~~~~~~~~ Enabling InfiniBand requires that host is running a build of Linux kernel 5.6 or higher with InfiniBand active or `NVIDIA MLNX_OFED Drivers 5.0 or higher <https://network.nvidia.com/products/infiniband-drivers/linux/mlnx_ofed/>`_. Once the existence of either Linux kernel 5.6 or higher or MOFED 5.0 or higher is confirmed, verify that InfiniBand support is active by checking for the presence of ``/dev/infiniband/rdma_cm`` and ``/dev/infiniband/uverbs*``: :: $ ls -l /dev/infiniband/{rdma_cm,uverbs*} crw-rw-rw- 1 root root 10, 58 May 18 20:43 /dev/infiniband/rdma_cm crw-rw-rw- 1 root root 231, 192 May 18 20:43 /dev/infiniband/uverbs0 crw-rw-rw- 1 root root 231, 193 May 18 20:43 /dev/infiniband/uverbs1 crw-rw-rw- 1 root root 231, 194 May 18 20:43 /dev/infiniband/uverbs2 crw-rw-rw- 1 root root 231, 195 May 18 20:43 /dev/infiniband/uverbs3 Conda ----- Conda packages can be installed as so. Replace ``<CUDA version>`` with the desired version (minimum ``11.2``). These are available both on ``rapidsai`` and ``rapidsai-nightly``. Starting with the UCX 1.14.1 conda-forge package, InfiniBand support is available again via rdma-core, thus building UCX from source is not required solely for that purpose anymore but may still be done if desired (e.g., to test for new capabilities or bug fixes). :: conda create -n ucx -c conda-forge -c rapidsai \ cudatoolkit=<CUDA version> ucx-py Source ------ The following instructions assume you'll be using UCX-Py on a CUDA enabled system and is in a `Conda environment <https://docs.conda.io/projects/conda/en/latest/>`_. Build Dependencies ~~~~~~~~~~~~~~~~~~ :: conda create -n ucx -c conda-forge \ automake make libtool pkg-config \ "python=3.9" setuptools "cython>=3.0.0" .. note:: The Python version must be explicitly specified here, UCX-Py currently supports only Python 3.9 and 3.10. Test Dependencies ~~~~~~~~~~~~~~~~~ :: conda install -n ucx -c rapidsai -c nvidia -c conda-forge \ pytest pytest-asyncio \ cupy "numba>=0.57" cudf \ dask distributed cloudpickle UCX >= 1.11.1 ~~~~~~~~~~~~~ Instructions for building UCX >= 1.11.1 (minimum version supported by UCX-Py), make sure to change ``git checkout v1.11.1`` to a newer version if desired: :: conda activate ucx git clone https://github.com/openucx/ucx cd ucx git checkout v1.11.1 ./autogen.sh mkdir build cd build # Performance build ../contrib/configure-release --prefix=$CONDA_PREFIX --with-cuda=$CUDA_HOME --enable-mt # Debug build ../contrib/configure-devel --prefix=$CONDA_PREFIX --with-cuda=$CUDA_HOME --enable-mt make -j install UCX + rdma-core ~~~~~~~~~~~~~~~ It is possible to enable InfiniBand support via the conda-forge rdma-core package. To do so, first activate the environment created previously and install conda-forge compilers and rdma-core: :: conda activate ucx conda install -c conda-forge c-compiler cxx-compiler gcc_linux-64=11.* rdma-core=28.* After installing the necessary dependencies, it's now time to build UCX from source, make sure to change ``git checkout v1.11.1`` to a newer version if desired: :: git clone https://github.com/openucx/ucx cd ucx git checkout v1.11.1 ./autogen.sh mkdir build cd build # Performance build ../contrib/configure-release --prefix=$CONDA_PREFIX --with-cuda=$CUDA_HOME --enable-mt --with-verbs --with-rdmacm # Debug build ../contrib/configure-devel --prefix=$CONDA_PREFIX --with-cuda=$CUDA_HOME --enable-mt --with-verbs --with-rdmacm make -j install UCX + MOFED ~~~~~~~~~~~ It is still possible to build UCX and use the MOFED system install. Unlike the case above, we must not install conda-forge compilers, this is because conda-forge compilers can't look for libraries in the system directories (e.g., ``/usr``). Additionally, the rdma-core conda-forge package should not be installed either, because compiling with a newer MOFED version will cause ABI incompatibilities. Before continuing, first ensure MOFED 5.0 or higher is installed, for example in the example below we have MOFED ``5.4-3.5.8.0``: :: (ucx) user@dgx:~$ ofed_info -s MLNX_OFED_LINUX-5.4-3.5.8.0: If MOFED drivers are not installed on the machine, you can download drivers directly from `NVIDIA <https://network.nvidia.com/products/infiniband-drivers/linux/mlnx_ofed/>`_. Building UCX >= 1.11.1 as shown previously should automatically include InfiniBand support if available in the system. It is possible to explicitly activate those, ensuring the system satisfies all dependencies or fail otherwise, by including the ``--with-rdmacm`` and ``--with-verbs`` build flags. Additionally, we want to make sure UCX uses compilers from the system, we do so by specifying ``CC=/usr/bin/gcc`` and ``CXX=/usr/bin/g++``, be sure to adjust that for the path to your system compilers. For example: :: CC=/usr/bin/gcc CXX=/usr/bin/g++ \ ../contrib/configure-release \ --enable-mt \ --prefix="$CONDA_PREFIX" \ --with-cuda="$CUDA_HOME" \ --enable-mt \ --with-rdmacm \ --with-verbs UCX-Py ~~~~~~ Building and installing UCX-Py can be done via `pip install`. For example: :: conda activate ucx git clone https://github.com/rapidsai/ucx-py.git cd ucx-py pip install -v . # or for develop build pip install -v -e .
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/deployment.rst
NVLink and Docker/Kubernetes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In order to use NVLink when running in containers using Docker and/or Kubernetes the processes must share an IPC namespace for NVLink to work correctly. Many GPUs in one container ^^^^^^^^^^^^^^^^^^^^^^^^^^ The simplest way to ensure that processing accessing GPUs share an IPC namespace is to run the processes within the same container. This means exposing multiple GPUs to a single container. Many containers with a shared IPC namespace ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you wish to isolate your processes into multiple containers and expose one or more GPUs to each container you need to ensure they are using a shared IPC namespace. In a Docker configuration you can mark one container as having a shareable IPC namespace with the flag ``--ipc="shareable"``. Other containers can then share that namespace with the flag ``--ipc="container: <_name-or-ID_>"`` and passing the name or ID of the container that is sharing it’s namespace. You can also share the host IPC namespace with your container with the flag ``--ipc="host"``, however this is not recommended on multi-tenant hosts. Privileged pods in a Kubernetes cluster `can also be configured to share the host IPC`_. For more information see the `Docker documentation`_. .. _can also be configured to share the host IPC: https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces .. _Docker documentation: https://docs.docker.com/engine/reference/run/#ipc-settings---ipc
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/glossary.rst
Glossary -------- - ACK Acknowledge - am Active Message - AMO Atomic Memory Operation - ANL Argonne National Laboratory - AZP AZure Pipeline - bcopy Byte copy - Bistro Binary Instrumentation - BTL Byte Transfer Layer - cm Connection Manager - CMA Cross Memory Attach - CQ Completion Queue(Infiniband) - CQE Completion Queue Entry(Infiniband) - csmock static analysis tools - CUDA Compute Unified Device Architecture(NVIDIA) - DC Dynamically Connected transport(Infiniband) - ep EndPoint - FC Flow Control - fd File Descriptor - GDR GPUDirect RDMA - gtest Google Test - HPC High Performance Computing - HWTM HardWare Tag Matching - IB Infiniband - iface Interaface - IPC Inter Process Communication - JUCX Java API over UCP - KLM A new sophisticated way of creating memory regions.- (Mellanox specific) - KNEM Kernel Nemesis - LLNL Lawrence Livermore National Laboratory - madvise give advice about use of memory. See manual - madvise(2) - md Memory Domain - MEMH Memory Handle - MLX Mellanox Technologies - mlx5 Connect-X5 VPI - mm Memory Mapper - MPI Message Passing INterface - MPICH A MPI Implementation - MTT The MPI Testing Tool - NAK Negative Acknowledge - ODP OnDemand Paging - OFA OpenFabrics Alliance - OMPI OpenMPI - OOB Out of band - OOO Out of Order - OPA Omni-Path Architecture - Open MPI A MPI Implementation - ORNL Oak Ridge National Laboratory - PCIe PCI Express - PGAS Partitioned Global Address Space - POSIX Portable operating system interface - ppn processes per node - PR Pull Request - PROGRESS64 A C library of scalable functions for - concurrent programs, primarily focused on networking - applications.(https://github.com/ARM-software/- progress64) - QP Queue Pair(Infiniband) - RC Reliable Connection (Infiniband) - rcache Registration Cache - RDMA Remote Direct Memory Access - REQ Request - rkey Remote KEY - RMA Remote Memory Access - RNR Receiver Not Ready - RoCE RDMA over Converged Ethernet - ROCm Radeon Open Compute platform(AMD) - RTE Run Time Environment - RX Receive - Skb Socket Buffer - sm Shared Memory - SM Subnet Manager(Infiniband) - SockCM Socket Connection Manager - SRQ Shared Receive Queue - SYSV UNIX System V - tl Transport Layer - TLS Transpot LayerS - TM Tag Matching - TX Transmit - UC Unreliable Connection (Infiniband) - UCF Unified Communication Framework - UCM Unified Communication Memory - UCP Unified Communication Protocols Higher level API - UCS Unified Communication Service Common utilities. - UCT Unified Communication Transport Lower level API - UCX Unified Communication X - UD Unreliable Datagram (Infiniband) - uGNI user level generic network interface(Cray) - UMR User mode memory registration - VPI Virtual Protocol Interconnect - WQ Work Queue(Infiniband) - WQE Work Queue Elements (pronounce WOOKIE) - WR Work Request - XPMEM cross partition memory - XRC eXtended Reliable Connection(Infiniband) - Zcopy Zero Copy
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/send-recv.rst
Send/Recv Internals =================== Generally UCX creates connections between endpoints with the following steps: 1. Create a ``Listener`` with defined IP address and port a. ``Listener`` defines a callback function to process communications from endpoints 2. Connect an ``Endpoint`` to the ``Listener`` 3. ``Endpoint`` communicates with the ``Listener`` 4. When finished, close ``Endpoint`` and ``Listener`` Below we go into more detail as we create an echo server in UCX and compare with `Python Sockets <https://docs.python.org/3/library/socket.html#example>`_ Server ------ First, we create the server -- in UCX-Py, we create a server with ``create_listener`` and build a blocking call to keep the listener alive. The listener invokes a callback function when an incoming connection is accepted. This callback should take in an ``Endpoint`` as an argument for ``send``/``recv``. For Python sockets, the server is similarly constructed. ``bind`` opens a connection on a given port and ``accept`` is Python Sockets' blocking call for incoming connections. In both UCX-Py and Sockets, once a connection has been made, both receive data and echo the same data back to the client +------------------------------------------------------+----------------------------------------------------------+ | UCX | Python Sockets | +------------------------------------------------------+----------------------------------------------------------+ | .. code-block:: python | .. code-block:: python | | | | | async def echo_server(ep): | s = socket.socket(...) | | obj = await ep.recv_obj() | s.bind((HOST, PORT)) | | await ep.send_obj(obj) | s.listen(1) | | | | | lf = ucp.create_listener(echo_server, port) | while True: | | | conn, addr = s.accept() | | while not lf.closed(): | data = conn.recv(1024) | | await asyncio.sleep(0.1) | if not data: break | | | conn.sendall(data) | | | conn.close() | +------------------------------------------------------+----------------------------------------------------------+ .. note:: In this example we create servers which listen forever. In production applications developers should also call appropriate closing functions Client ------ For Sockets, on the client-side we connect to the established host/port combination and send data to the socket. The client-side is a bit more interesting in UCX-Py: ``create_endpoint``, also uses a host/port combination to establish a connection, and after an ``Endpoint`` is created, ``hello, world`` is passed back and forth between the client an server. +------------------------------------------------------+----------------------------------------------------------+ | UCX | Python Sockets | +------------------------------------------------------+----------------------------------------------------------+ | .. code-block:: python | .. code-block:: python | | | | | client = await ucp.create_endpoint(addr, port) | s = socket.socket(...) | | | s.connect((HOST, PORT)) | | msg = bytearray(b"hello, world") | s.sendall(b'hello, world') | | await client.send_obj(msg) | echo_msg = s.recv(1024) | | echo_msg = await client.recv_obj() | | | await client.close() | s.close() | | | | +------------------------------------------------------+----------------------------------------------------------+ So what happens with ``create_endpoint`` ? Unlike Sockets, UCX employs a tag-matching strategy where endpoints are created with a unique id and send/receive operations also use unique ids (these are called ``tags``). With standard TCP connections, when a incoming requests is made, a socket is created with a unique 4-tuple: client address, client port, server address, and server port. With this uniqueness, threads and processes alike are now free to communicate with one another. Again, UCX, uses tags for uniqueness so when an incoming request is made, the receiver matches the ``Endpoint`` ID and a unique tag -- for more details on tag-matching please see the `this page <https://www.kernel.org/doc/html/latest/infiniband/tag_matching.html>`_. ``create_endpoint``, will create an ``Endpoint`` with three steps: #. Generate unique IDs to use as tags #. Exchange endpoint info such as tags #. Use the info to create an endpoint Again, an ``Endpoint`` sends and receives with `unique tags <http://openucx.github.io/ucx/api/v1.8/html/group___u_c_t___t_a_g.html>`_. .. code-block:: python ep = Endpoint( endpoint=ucx_ep, ctx=self, msg_tag_send=peer_info["msg_tag"], msg_tag_recv=msg_tag, ctrl_tag_send=peer_info["ctrl_tag"], ctrl_tag_recv=ctrl_tag, guarantee_msg_order=guarantee_msg_order, ) Most users will not care about these details but developers and interested network enthusiasts may. Looking at the DEBUG (``UCXPY_LOG_LEVEL=DEBUG``) output of the client can help clarify what UCX-Py/UCX is doing under the hood:: # client = await ucp.create_endpoint(addr, port) [1594319245.032609] [dgx12:5904] UCXPY DEBUG create_endpoint() client: 0x7f5e6e7bd0d8, msg-tag-send: 0x88e288ec81799a75, msg-tag-recv: 0xf29f8e9b7ce33f66, ctrl-tag-send: 0xb1cd5cb9b1120434, ctrl-tag-recv: 0xe79506f1d24b4997 # await client.send_obj(msg) [1594319251.364999] [dgx12:5904] UCXPY DEBUG [Send #000] ep: 0x7f5e6e7bd0d8, tag: 0x88e288ec81799a75, nbytes: 8, type: <class 'bytes'> [1594319251.365213] [dgx12:5904] UCXPY DEBUG [Send #001] ep: 0x7f5e6e7bd0d8, tag: 0x88e288ec81799a75, nbytes: 12, type: <class 'bytearray'> # echo_msg = await client.recv_obj() [1594319260.452441] [dgx12:5904] UCXPY DEBUG [Recv #000] ep: 0x7f5e6e7bd0d8, tag: 0xf29f8e9b7ce33f66, nbytes: 8, type: <class 'bytearray'> [1594319260.452677] [dgx12:5904] UCXPY DEBUG [Recv #001] ep: 0x7f5e6e7bd0d8, tag: 0xf29f8e9b7ce33f66, nbytes: 12, type: <class 'bytearray'> # await client.close() [1594319287.522824] [dgx12:5904] UCXPY DEBUG [Send shutdown] ep: 0x7f5e6e7bd0d8, tag: 0xb1cd5cb9b1120434, close_after_n_recv: 2 [1594319287.523172] [dgx12:5904] UCXPY DEBUG Endpoint.abort(): 0x7f5e6e7bd0d8 [1594319287.523331] [dgx12:5904] UCXPY DEBUG Future cancelling: [Recv shutdown] ep: 0x7f5e6e7bd0d8, tag: 0xe79506f1d24b4997 We can see from the above that when the ``Endpoint`` is created, 4 tags are generated: ``msg-tag-send``, ``msg-tag-recv``, ``ctrl-tag-send``, and ``ctrl-tag-recv``. This data is transmitted to the server via a `stream <http://openucx.github.io/ucx/api/v1.8/html/group___u_c_p___c_o_m_m.html#ga9022ff0ebb56cac81f6ba81bb28f71b3>`_ communication in an `exchange peer info <https://github.com/rapidsai/ucx-py/blob/6e1c1d201a382c689ca098c848cbfdc8237e1eba/ucp/core.py#L38-L89>`_ convenience function. Next, the client sends data on the ``msg-tag-send`` tag. Two messages are sent, the size of the data ``8 bytes`` and data itself. The server receives the data and immediately echos the data back. The client then receives two messages the size of the data and the data itself. Lastly, the client closes down. When the client closes, it sends a `control message <https://github.com/rapidsai/ucx-py/blob/6e1c1d201a382c689ca098c848cbfdc8237e1eba/ucp/core.py#L524-L534>`_ to the server's ``Endpoint`` instructing it to `also close <https://github.com/rapidsai/ucx-py/blob/6e1c1d201a382c689ca098c848cbfdc8237e1eba/ucp/core.py#L112-L140>`_
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/configuration.rst
Configuration ============= UCX/UCX-Py can be configured with a wide variety of options and optimizations including: transport, caching, etc. Users can configure UCX/UCX-Py either with environment variables or programmatically during initialization. Below we demonstrate setting ``UCX_MEMTYPE_CACHE`` to ``n`` and checking the configuration: .. code-block:: python import ucp options = {"MEMTYPE_CACHE": "n"} ucp.init(options) assert ucp.get_config()['MEMTYPE_CACHE'] is 'n' .. note:: When programmatically configuring UCX-Py, the ``UCX`` prefix is not used. For novice users we recommend using UCX-Py defaults, see the next section for details. UCX-Py vs UCX Defaults ---------------------- UCX-Py redefines some of the UCX defaults for a variety of reasons, including better performance for the more common Python use cases, or to work around known limitations or bugs of UCX. To verify UCX default configurations, for the currently installed UCX version please run the command-line tool ``ucx_info -f``. Below is a list of the UCX-Py redefined default values, and what conditions are required for them to apply. Apply to all UCX versions: :: UCX_RNDV_THRESH=8192 UCX_RNDV_SCHEME=get_zcopy Apply to UCX >= 1.12.0, older UCX versions rely on UCX defaults: :: UCX_CUDA_COPY_MAX_REG_RATIO=1.0 UCX_MAX_RNDV_RAILS=1 Please note that ``UCX_CUDA_COPY_MAX_REG_RATIO=1.0`` is only set provided at least one GPU is present with a BAR1 size smaller than its total memory (e.g., NVIDIA T4). UCX Environment Variables in UCX-Py ----------------------------------- In this section we go over a brief overview of some of the more relevant variables for current UCX-Py usage, along with some comments on their uses and limitations. To see a complete list of UCX environment variables, their descriptions and default values, please run the command-line tool ``ucx_info -f``. DEBUG ~~~~~ Debug variables for both UCX and UCX-Py can be set UCXPY_LOG_LEVEL/UCX_LOG_LEVEL ````````````````````````````` Values: DEBUG, TRACE If UCX has been built with debug mode enabled MEMORY ~~~~~~ UCX_MEMTYPE_CACHE ````````````````` This is a UCX Memory optimization which toggles whether UCX library intercepts cu*alloc* calls. UCX-Py defaults this value to ``n``. There `known issues <https://github.com/openucx/ucx/wiki/NVIDIA-GPU-Support#known-issues>`_ when using this feature. Values: ``n``/``y`` UCX_CUDA_IPC_CACHE `````````````````` This is a UCX CUDA Memory optimization which enables/disables a remote endpoint IPC memhandle mapping cache. UCX/UCX-Py defaults this value to ``y`` Values: ``n``/``y`` UCX_MEMTYPE_REG_WHOLE_ALLOC_TYPES ````````````````````````````````` By defining ``UCX_MEMTYPE_REG_WHOLE_ALLOC_TYPES=cuda`` (default in UCX >= 1.12.0), UCX enables registration cache based on a buffer's base address, thus preventing multiple time-consuming registrations for the same buffer. This is particularly useful when using a CUDA memory pool, thus requiring a single registration between two ends for the entire pool, providing considerable performance gains, especially when using InfiniBand. TRANSPORTS ~~~~~~~~~~ UCX_MAX_RNDV_RAILS `````````````````` Limiting the number of rails (network devices) to ``1`` allows UCX to use only the closest device according to NUMA locality and system topology. Particularly useful with InfiniBand and CUDA GPUs, ensuring all transfers from/to the GPU will use the closest InfiniBand device and thus implicitly enable GPUDirectRDMA. .. note:: On CPU-only systems, better network bandwidth performance with infiniband transports may be achieved by letting UCX use more than a single network device. This can be achieved by explicitly setting ``UCX_MAX_RNDV_RAILS`` to ``2`` or higher. Values: Int (UCX-Py default: ``1``) UCX_RNDV_THRESH ``````````````` This is a configurable parameter used by UCX to help determine which transport method should be used. For example, on machines with multiple GPUs, and with NVLink enabled, UCX can deliver messages either through TCP or NVLink. Sending GPU buffers over TCP is costly as it triggers a device-to-host on the sender side, and then host-to-device transfer on the receiver side -- we want to avoid these kinds of transfers when NVLink is available. If a buffer is below the threshold, `Rendezvous-Protocol <https://github.com/openucx/ucx/wiki/Rendezvous-Protocol>`_ is triggered and for UCX-Py users, this will typically mean messages will be delivered through TCP. Depending on the application, messages can be quite small, therefore, we recommend setting a small value if the application uses NVLink or InfiniBand: ``UCX_RNDV_THRESH=8192`` Values: Int (UCX-Py default: ``8192``) UCX_RNDV_SCHEME ``````````````` Communication scheme in RNDV protocol Values: - ``put_zcopy`` - ``get_zcopy`` - ``auto`` (default) UCX_TCP_RX_SEG_SIZE ``````````````````` Size of send copy-out buffer when receiving. This environment variable controls the size of the buffer on the host when receiving data over TCP. UCX_TCP_TX_SEG_SIZE ``````````````````` Size of send copy-out buffer when transmitting. This environment variable controls the size of the buffer on the host when sending data over TCP. .. note:: Users should take care to properly tune ``UCX_TCP_{RX/TX}_SEG_SIZE`` parameters when mixing TCP with other transports methods as well as when using TCP over UCX in isolation. These variables will impact CUDA transfers when no NVLink or InfiniBand is available between UCX-Py processes. These parameters will cause the HostToDevice and DeviceToHost copies of buffers to be broken down in several chunks when the size of a buffer exceeds the size defined by these two variables. If an application is expected to transfer very large buffers, increasing such values may improve overall performance. UCX_TLS ``````` Transport Methods (Simplified): - ``all`` -> use all the available transports - ``rc`` -> InfiniBand (ibv_post_send, ibv_post_recv, ibv_poll_cq) uses rc_v and rc_x (preferably if available) - ``cuda_copy`` -> cuMemHostRegister, cuMemcpyAsync - ``cuda_ipc`` -> CUDA Interprocess Communication (cuIpcCloseMemHandle, cuIpcOpenMemHandle, cuMemcpyAsync) - ``sm/shm`` -> all shared memory transports (mm, cma, knem) - ``mm`` -> shared memory transports - only memory mappers - ``ugni`` -> ugni_smsg and ugni_rdma (uses ugni_udt for bootstrap) - ``ib`` -> all infiniband transports (rc/rc_mlx5, ud/ud_mlx5, dc_mlx5) - ``rc_v`` -> rc verbs (uses ud for bootstrap) - ``rc_x`` -> rc with accelerated verbs (uses ud_mlx5 for bootstrap) - ``ud_v`` -> ud verbs - ``ud_x`` -> ud with accelerated verbs - ``ud`` -> ud_v and ud_x (preferably if available) - ``dc/dc_x`` -> dc with accelerated verbs - ``tcp`` -> sockets over TCP/IP - ``cuda`` -> CUDA (NVIDIA GPU) memory support - ``rocm`` -> ROCm (AMD GPU) memory support SOCKADDR_TLS_PRIORITY ````````````````````` Priority of sockaddr transports InfiniBand Device ~~~~~~~~~~~~~~~~~~ Select InfiniBand Device UCX_NET_DEVICES ``````````````` Typically these will be the InfiniBand device corresponding to a particular set of GPUs. Values: - ``mlx5_0:1`` To find more information on the topology of InfiniBand-GPU pairing run the following:: nvidia-smi topo -m Example Configs --------------- InfiniBand -- No NVLink ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: UCX_RNDV_SCHEME=get_zcopy UCX_MEMTYPE_CACHE=n UCX_TLS=rc,tcp,cuda_copy <SCRIPT> InfiniBand -- With NVLink ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: UCX_RNDV_SCHEME=get_zcopy UCX_MEMTYPE_CACHE=n UCX_TLS=rc,tcp,cuda_copy,cuda_ipc <SCRIPT> TLS/Socket -- No NVLink ~~~~~~~~~~~~~~~~~~~~~~~ :: UCX_RNDV_SCHEME=get_zcopy UCX_MEMTYPE_CACHE=n UCX_TLS=tcp,cuda_copy <SCRIPT> TLS/Socket -- With NVLink ~~~~~~~~~~~~~~~~~~~~~~~~~ :: UCX_RNDV_SCHEME=get_zcopy UCX_MEMTYPE_CACHE=n UCX_TLS=tcp,cuda_copy,cuda_ipc <SCRIPT>
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/ucx-debug.rst
UCX Debugging ============= InfiniBand ---------- System Configuration ~~~~~~~~~~~~~~~~~~~~ ``ibdev2netdev`` -- check to ensure at least one IB controller is configured for IPoIB :: user@mlnx:~$ ibdev2netdev mlx5_0 port 1 ==> ib0 (Up) mlx5_1 port 1 ==> ib1 (Up) mlx5_2 port 1 ==> ib2 (Up) mlx5_3 port 1 ==> ib3 (Up) ``ucx_info -d`` and ``ucx_info -p -u t`` are helpful commands to display what UCX understands about the underlying hardware. For example, we can check if UCX has been built correctly with ``RDMA`` and if it is available. :: user@pdgx:~$ ucx_info -d | grep -i rdma # Memory domain: rdmacm # Component: rdmacm # Connection manager: rdmacm user@dgx:~$ ucx_info -b | grep -i rdma #define HAVE_DECL_RDMA_ESTABLISH 1 #define HAVE_DECL_RDMA_INIT_QP_ATTR 1 #define HAVE_RDMACM_QP_LESS 1 #define UCX_CONFIGURE_FLAGS "--disable-logging --disable-debug --disable-assertions --disable-params-check --prefix=/gpfs/fs1/user/miniconda3/envs/ucx-dev --with-sysroot --enable-cma --enable-mt --enable-numa --with-gnu-ld --with-rdmacm --with-verbs --with-cuda=/gpfs/fs1/SHARE/Utils/CUDA/10.2.89.0_440.33.01" #define uct_MODULES ":cuda:ib:rdmacm:cma" InfiniBand Performance ~~~~~~~~~~~~~~~~~~~~~~ ``ucx_perftest`` should confirm InfiniBand bandwidth to be in the 10+ GB/s range :: CUDA_VISIBLE_DEVICES=0 UCX_NET_DEVICES=mlx5_0:1 UCX_TLS=rc,cuda_copy ucx_perftest -t tag_bw -m cuda -s 10000000 -n 10 -p 9999 & \ CUDA_VISIBLE_DEVICES=1 UCX_NET_DEVICES=mlx5_1:1 UCX_TLS=rc,cuda_copy ucx_perftest `hostname` -t tag_bw -m cuda -s 100000000 -n 10 -p 9999 +--------------+-----------------------------+---------------------+-----------------------+ | | latency (usec) | bandwidth (MB/s) | message rate (msg/s) | +--------------+---------+---------+---------+----------+----------+-----------+-----------+ | # iterations | typical | average | overall | average | overall | average | overall | +--------------+---------+---------+---------+----------+----------+-----------+-----------+ +------------------------------------------------------------------------------------------+ | API: protocol layer | | Test: tag match bandwidth | | Data layout: (automatic) | | Send memory: cuda | | Recv memory: cuda | | Message size: 100000000 | +------------------------------------------------------------------------------------------+ 10 0.000 9104.800 9104.800 10474.41 10474.41 110 110 ``-c`` option is NUMA dependent and sets the CPU Affinity of process for a particular GPU. CPU Affinity information can be found in ``nvidia-smi topo -m`` :: user@mlnx:~$ nvidia-smi topo -m GPU0 GPU1 GPU2 GPU3 GPU4 GPU5 GPU6 GPU7 mlx5_0 mlx5_1 mlx5_2 mlx5_3 CPU Affinity GPU0 X NV1 NV1 NV2 NV2 SYS SYS SYS PIX PHB SYS SYS 0-19,40-59 GPU1 NV1 X NV2 NV1 SYS NV2 SYS SYS PIX PHB SYS SYS 0-19,40-59 GPU2 NV1 NV2 X NV2 SYS SYS NV1 SYS PHB PIX SYS SYS 0-19,40-59 GPU3 NV2 NV1 NV2 X SYS SYS SYS NV1 PHB PIX SYS SYS 0-19,40-59 GPU4 NV2 SYS SYS SYS X NV1 NV1 NV2 SYS SYS PIX PHB 20-39,60-79 GPU5 SYS NV2 SYS SYS NV1 X NV2 NV1 SYS SYS PIX PHB 20-39,60-79 GPU6 SYS SYS NV1 SYS NV1 NV2 X NV2 SYS SYS PHB PIX 20-39,60-79 GPU7 SYS SYS SYS NV1 NV2 NV1 NV2 X SYS SYS PHB PIX 20-39,60-79 mlx5_0 PIX PIX PHB PHB SYS SYS SYS SYS X PHB SYS SYS mlx5_1 PHB PHB PIX PIX SYS SYS SYS SYS PHB X SYS SYS mlx5_2 SYS SYS SYS SYS PIX PIX PHB PHB SYS SYS X PHB mlx5_3 SYS SYS SYS SYS PHB PHB PIX PIX SYS SYS PHB X Legend: X = Self SYS = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI) NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node PHB = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU) PXB = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge) PIX = Connection traversing at most a single PCIe bridge NV# = Connection traversing a bonded set of # NVLinks NVLink ------ System Configuration ~~~~~~~~~~~~~~~~~~~~ The NVLink connectivity on the system above (DGX-1) is not homogenous, some GPUs are connected by a single NVLink connection (NV1, e.g., GPUs 0 and 1), others with two NVLink connections (NV2, e.g., GPUs 1 and 2), and some not connected at all via NVLink (SYS, e.g., GPUs 3 and 4)." NVLink Performance ~~~~~~~~~~~~~~~~~~ ``ucx_perftest`` should confirm NVLink bandwidth to be in the 20+ GB/s range :: CUDA_VISIBLE_DEVICES=0 UCX_TLS=cuda_ipc,cuda_copy,tcp ucx_perftest -t tag_bw -m cuda -s 10000000 -n 10 -p 9999 -c 0 & \ CUDA_VISIBLE_DEVICES=1 UCX_TLS=cuda_ipc,cuda_copy,tcp ucx_perftest `hostname` -t tag_bw -m cuda -s 100000000 -n 10 -p 9999 -c 1 +--------------+-----------------------------+---------------------+-----------------------+ | | latency (usec) | bandwidth (MB/s) | message rate (msg/s) | +--------------+---------+---------+---------+----------+----------+-----------+-----------+ | # iterations | typical | average | overall | average | overall | average | overall | +--------------+---------+---------+---------+----------+----------+-----------+-----------+ +------------------------------------------------------------------------------------------+ | API: protocol layer | | Test: tag match bandwidth | | Data layout: (automatic) | | Send memory: cuda | | Recv memory: cuda | | Message size: 100000000 | +------------------------------------------------------------------------------------------+ 10 0.000 4163.694 4163.694 22904.52 22904.52 240 240 Experimental Debugging ---------------------- A list of problems we have run into along the way while trying to understand performance issues with UCX/UCX-Py: - System-wide settings environment variables. For example, we saw a system with ``UCX_MEM_MMAP_HOOK_MODE`` set to ``none``. Unsetting this env var resolved problems: https://github.com/rapidsai/ucx-py/issues/616 . One can quickly check system wide variables with ``env|grep ^UCX_``. - ``sockcm_iface.c:257 Fatal: sockcm_listener: unable to create handler for new connection``. This is an error we've seen when limits are place on the number of file descriptors and occurs when ``SOCKCM`` is used for establishing connections. User have two choices for resolving this issue: increase the ``open files`` limit (check ulimit configuration) or use ``RDMACM`` when establishing a connection ``UCX_SOCKADDR_TLS_PRIORITY=rdmacm``. ``RDMACM`` is only available using InfiniBand devices.
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- # The full version, including alpha/beta/rc tags. from ucp import __version__ as release # The short X.Y version. version = ".".join(release.split(".")[:2]) project = "ucx-py" copyright = "2019-2021, NVIDIA" author = "NVIDIA" # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.mathjax", "sphinx.ext.viewcode", "sphinx.ext.githubpages", "sphinx.ext.autosummary", "sphinx.ext.intersphinx", "sphinx.ext.extlinks", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = ".rst" # The master toctree document. master_doc = "index" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = "ucx-pydoc" # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, "ucx-py.tex", "ucx-py Documentation", "NVIDIA", "manual") ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, "ucx-py", "ucx-py Documentation", [author], 1)] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "ucx-py", "ucx-py Documentation", author, "ucx-py", "One line description of project.", "Miscellaneous", ) ] # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ["search.html"] # -- Extension configuration -------------------------------------------------
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/transport-monitoring.rst
Monitoring Transports ===================== Below is a list of commonly used tools and commands to monitor InfiniBand and CUDA IPC messages: Infiniband ---------- Monitor InfiniBand packet counters -- this number should dramatically increase when there's InfiniBand traffic: :: watch -n 0.1 'cat /sys/class/infiniband/mlx5_*/ports/1/counters/port_xmit_data' CUDA IPC/NVLink --------------- Monitor traffic over all GPUs :: nvidia-smi nvlink -gt d Monitor traffic over all GPUs on counter 0 .. note:: nvidia-smi nvlink -g is now deprecated :: # set counters nvidia-smi nvlink -sc 0bz watch -d 'nvidia-smi nvlink -g 0' Stats Monitoring of GPUs :: dcgmi dmon -e 449 `nvdashboard <https://github.com/rapidsai/jupyterlab-nvdashboard>`_
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/api.rst
API === .. currentmodule:: ucp **ucp** .. autosummary:: ucp ucp.create_listener ucp.create_endpoint ucp.get_address ucp.get_config ucp.get_ucp_worker ucp.get_ucx_version ucp.init ucp.progress ucp.reset **Endpoint** .. autosummary:: Endpoint Endpoint.abort Endpoint.close Endpoint.closed Endpoint.close_after_n_recv Endpoint.cuda_support Endpoint.get_ucp_endpoint Endpoint.get_ucp_worker Endpoint.recv Endpoint.send Endpoint.ucx_info Endpoint.uid **Listener** .. autosummary:: Listener Listener.close Listener.closed Listener.port .. currentmodule:: ucp .. autofunction:: create_listener .. autofunction:: create_endpoint .. autofunction:: get_address .. autofunction:: get_config .. autofunction:: get_ucp_worker .. autofunction:: get_ucx_version .. autofunction:: init .. autofunction:: progress .. autofunction:: reset Endpoint -------- .. currentmodule:: ucp .. autoclass:: Endpoint :members: Listener -------- .. currentmodule:: ucp .. autoclass:: Listener :members:
0
rapidsai_public_repos/ucx-py/docs
rapidsai_public_repos/ucx-py/docs/source/index.rst
UCX-Py ====== UCX-Py is the Python interface for `UCX <https://github.com/openucx/ucx>`_, a low-level high-performance networking library. UCX and UCX-Py supports several transport methods including InfiniBand and NVLink while still using traditional networking protocols like TCP. .. image:: _static/Architecture.png :alt: A simple dask dictionary :align: center .. toctree:: :maxdepth: 1 :hidden: quickstart install configuration deployment ucx-debug .. toctree:: :maxdepth: 1 :hidden: :caption: Help & reference os-limits transport-monitoring send-recv api glossary
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/ci/test_python.sh
#!/bin/bash set -euo pipefail rapids-logger "Create test conda environment" . /opt/conda/etc/profile.d/conda.sh rapids-dependency-file-generator \ --output conda \ --file_key test_python \ --matrix "cuda=${RAPIDS_CUDA_VERSION%.*};arch=$(arch);py=${RAPIDS_PY_VERSION}" | tee env.yaml rapids-mamba-retry env create --force -f env.yaml -n test conda activate test rapids-print-env rapids-logger "Check GPU usage" nvidia-smi rapids-logger "Check NICs" awk 'END{print $1}' /etc/hosts cat /etc/hosts run_tests() { rapids-logger "UCX Version and Build Configuration" ucx_info -v rapids-logger "Python pytest for ucx-py" # list test directory ls tests/ # Setting UCX options export UCX_TLS=tcp,cuda_copy # Test with TCP/Sockets rapids-logger "TEST WITH TCP ONLY" timeout 10m pytest --cache-clear -vs tests/ timeout 2m pytest --cache-clear -vs ucp/_libs/tests rapids-logger "Run local benchmark" # cd to root directory to prevent repo's `ucp` directory from being used # in subsequent commands pushd / timeout 1m python -m ucp.benchmarks.send_recv -o cupy --server-dev 0 --client-dev 0 --reuse-alloc --backend ucp-async timeout 1m python -m ucp.benchmarks.send_recv -o cupy --server-dev 0 --client-dev 0 --reuse-alloc --backend ucp-core timeout 1m python -m ucp.benchmarks.cudf_merge --chunks-per-dev 4 --chunk-size 10000 --rmm-init-pool-size 2097152 popd } rapids-logger "Downloading artifacts from previous jobs" PYTHON_CHANNEL=$(rapids-download-conda-from-s3 python) rapids-mamba-retry install \ --channel "${PYTHON_CHANNEL}" \ ucx-py rapids-logger "Run tests with conda package" run_tests # The following block is untested in GH Actions TEST_UCX_MASTER=0 if [[ "${TEST_UCX_MASTER}" == 1 ]]; then rapids-logger "Build UCX master" git clone https://github.com/openucx/ucx ucx-master pushd ucx-master ./autogen.sh mkdir build pushd build ../contrib/configure-release --prefix="${CONDA_PREFIX}" --with-cuda="${CUDA_HOME}" --enable-mt make -j install rapids-logger "Build UCX-Py" popd; popd git clean -ffdx python setup.py build_ext --inplace python -m pip install -e . rapids-logger "Run tests with pip package against ucx master" run_tests fi
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/ci/build_python.sh
#!/bin/bash # Copyright (c) 2023, NVIDIA CORPORATION. set -euo pipefail source rapids-env-update rapids-print-env version=$(rapids-generate-version) commit=$(git rev-parse HEAD) echo "${version}" > VERSION sed -i "/^__git_commit__/ s/= .*/= \"${commit}\"/g" ucp/_version.py rapids-logger "Begin py build" RAPIDS_PACKAGE_VERSION=${version} rapids-conda-retry mambabuild \ conda/recipes/ucx-py rapids-upload-conda-to-s3 python
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/ci/build_wheel.sh
#!/bin/bash # Copyright (c) 2023, NVIDIA CORPORATION. set -euo pipefail package_name="ucx-py" underscore_package_name=$(echo "${package_name}" | tr "-" "_") source rapids-configure-sccache source rapids-date-string version=$(rapids-generate-version) commit=$(git rev-parse HEAD) RAPIDS_PY_CUDA_SUFFIX="$(rapids-wheel-ctk-name-gen ${RAPIDS_CUDA_VERSION})" # This is the version of the suffix with a preceding hyphen. It's used # everywhere except in the final wheel name. PACKAGE_CUDA_SUFFIX="-${RAPIDS_PY_CUDA_SUFFIX}" # Patch project metadata files to include the CUDA version suffix and version override. pyproject_file="pyproject.toml" sed -i "s/name = \"${package_name}\"/name = \"${package_name}${PACKAGE_CUDA_SUFFIX}\"/g" ${pyproject_file} echo "${version}" > VERSION sed -i "/^__git_commit__/ s/= .*/= \"${commit}\"/g" ucp/_version.py # For nightlies we want to ensure that we're pulling in alphas as well. The # easiest way to do so is to augment the spec with a constraint containing a # min alpha version that doesn't affect the version bounds but does allow usage # of alpha versions for that dependency without --pre alpha_spec='' if ! rapids-is-release-build; then alpha_spec=',>=0.0.0a0' fi sed -r -i "s/cudf==(.*)\"/cudf${PACKAGE_CUDA_SUFFIX}==\1${alpha_spec}\"/g" ${pyproject_file} if [[ $PACKAGE_CUDA_SUFFIX == "-cu12" ]]; then sed -i "s/cupy-cuda11x/cupy-cuda12x/g" ${pyproject_file} fi python -m pip wheel . -w dist -vvv --no-deps --disable-pip-version-check mkdir -p final_dist python -m auditwheel repair -w final_dist dist/* # Auditwheel rewrites dynamic libraries that are referenced at link time in the # package. However, UCX loads a number of sub-libraries at runtime via dlopen; # these are not picked up by auditwheel. Since we have a priori knowledge of # what these libraries are, we mimic the behaviour of auditwheel by using the # same hash-based uniqueness scheme and rewriting the link paths. WHL=$(realpath final_dist/${underscore_package_name}*manylinux*.whl) # first grab the auditwheel hashes for libuc{tms} LIBUCM=$(unzip -l $WHL | awk 'match($4, /libucm-[^\.]+\./) { print substr($4, RSTART) }') LIBUCT=$(unzip -l $WHL | awk 'match($4, /libuct-[^\.]+\./) { print substr($4, RSTART) }') LIBUCS=$(unzip -l $WHL | awk 'match($4, /libucs-[^\.]+\./) { print substr($4, RSTART) }') LIBNUMA=$(unzip -l $WHL | awk 'match($4, /libnuma-[^\.]+\./) { print substr($4, RSTART) }') # Extract the libraries that have already been patched in by auditwheel mkdir -p repair_dist/${underscore_package_name}_${RAPIDS_PY_CUDA_SUFFIX}.libs/ucx unzip $WHL "${underscore_package_name}_${RAPIDS_PY_CUDA_SUFFIX}.libs/*.so*" -d repair_dist/ # Patch the RPATH to include ORIGIN for each library pushd repair_dist/${underscore_package_name}_${RAPIDS_PY_CUDA_SUFFIX}.libs for f in libu*.so* do if [[ -f $f ]]; then patchelf --add-rpath '$ORIGIN' $f fi done popd # Now copy in all the extra libraries that are only ever loaded at runtime pushd repair_dist/${underscore_package_name}_${RAPIDS_PY_CUDA_SUFFIX}.libs/ucx if [[ -d /usr/lib64/ucx ]]; then cp -P /usr/lib64/ucx/* . elif [[ -d /usr/lib/ucx ]]; then cp -P /usr/lib/ucx/* . else echo "Could not find ucx libraries" exit 1 fi # we link against <python>/lib/site-packages/${underscore_package_name}_${RAPIDS_PY_CUDA_SUFFIX}.lib/libuc{ptsm} # we also amend the rpath to search one directory above to *find* libuc{tsm} for f in libu*.so* do # Avoid patching symlinks, which is redundant if [[ ! -L $f ]]; then patchelf --replace-needed libuct.so.0 $LIBUCT $f patchelf --replace-needed libucs.so.0 $LIBUCS $f patchelf --replace-needed libucm.so.0 $LIBUCM $f patchelf --replace-needed libnuma.so.1 $LIBNUMA $f patchelf --add-rpath '$ORIGIN/..' $f fi done # Bring in cudart as well. To avoid symbol collision with other libraries e.g. # cupy we mimic auditwheel by renaming the libraries to include the hashes of # their names. Since there will typically be a chain of symlinks # libcudart.so->libcudart.so.X->libcudart.so.X.Y.Z we need to follow the chain # and rename all of them. find /usr/local/cuda/ -name "libcudart*.so*" | xargs cp -P -t . src=libcudart.so hash=$(sha256sum ${src} | awk '{print substr($1, 0, 8)}') target=$(basename $(readlink -f ${src})) mv ${target} ${target/libcudart/libcudart-${hash}} while readlink ${src} > /dev/null; do target=$(readlink ${src}) ln -s ${target/libcudart/libcudart-${hash}} ${src/libcudart/libcudart-${hash}} rm -f ${src} src=${target} done to_rewrite=$(ldd libuct_cuda.so | awk '/libcudart/ { print $1 }') patchelf --replace-needed ${to_rewrite} libcudart-${hash}.so libuct_cuda.so patchelf --add-rpath '$ORIGIN' libuct_cuda.so popd pushd repair_dist zip -r $WHL ${underscore_package_name}_${RAPIDS_PY_CUDA_SUFFIX}.libs/ popd RAPIDS_PY_WHEEL_NAME="${underscore_package_name}_${RAPIDS_PY_CUDA_SUFFIX}" rapids-upload-wheels-to-s3 final_dist
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/ci/check_style.sh
#!/bin/bash # Copyright (c) 2023, NVIDIA CORPORATION. set -euo pipefail rapids-logger "Create checks conda environment" . /opt/conda/etc/profile.d/conda.sh rapids-dependency-file-generator \ --output conda \ --file_key checks \ --matrix "cuda=${RAPIDS_CUDA_VERSION%.*};arch=$(arch);py=${RAPIDS_PY_VERSION}" | tee env.yaml rapids-mamba-retry env create --force -f env.yaml -n checks conda activate checks # Run pre-commit checks pre-commit run --hook-stage manual --all-files --show-diff-on-failure
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/ci/test_wheel.sh
#!/bin/bash # Copyright (c) 2023, NVIDIA CORPORATION. set -eoxu pipefail mkdir -p ./dist RAPIDS_PY_CUDA_SUFFIX="$(rapids-wheel-ctk-name-gen ${RAPIDS_CUDA_VERSION})" RAPIDS_PY_WHEEL_NAME="ucx_py_${RAPIDS_PY_CUDA_SUFFIX}" rapids-download-wheels-from-s3 ./dist # echo to expand wildcard before adding `[extra]` requires for pip python -m pip install $(echo ./dist/ucx_py*.whl)[test] cd tests python -m pytest --cache-clear -vs . cd ../ucp python -m pytest --cache-clear -vs ./_libs/tests/
0
rapidsai_public_repos/ucx-py/ci
rapidsai_public_repos/ucx-py/ci/release/update-version.sh
#!/bin/bash ######################## # ucx-py Version Updater # ######################## ## Usage # bash update-version.sh <new_version> # Format is Major.Minor.Patch - no leading 'v' or trailing 'a' # Example: 0.30.00 NEXT_FULL_TAG=$1 # Get current version CURRENT_TAG=$(git tag | grep -xE 'v[0-9\.]+' | sort --version-sort | tail -n 1 | tr -d 'v') CURRENT_MAJOR=$(echo $CURRENT_TAG | awk '{split($0, a, "."); print a[1]}') CURRENT_MINOR=$(echo $CURRENT_TAG | awk '{split($0, a, "."); print a[2]}') CURRENT_PATCH=$(echo $CURRENT_TAG | awk '{split($0, a, "."); print a[3]}') CURRENT_SHORT_TAG=${CURRENT_MAJOR}.${CURRENT_MINOR} #Get <major>.<minor> for next version NEXT_MAJOR=$(echo $NEXT_FULL_TAG | awk '{split($0, a, "."); print a[1]}') NEXT_MINOR=$(echo $NEXT_FULL_TAG | awk '{split($0, a, "."); print a[2]}') NEXT_SHORT_TAG=${NEXT_MAJOR}.${NEXT_MINOR} # Get RAPIDS version associated w/ ucx-py version NEXT_RAPIDS_SHORT_TAG="$(curl -sL https://version.gpuci.io/ucx-py/${NEXT_SHORT_TAG})" # Need to distutils-normalize the versions for some use cases NEXT_RAPIDS_SHORT_TAG_PEP440=$(python -c "from setuptools.extern import packaging; print(packaging.version.Version('${NEXT_RAPIDS_SHORT_TAG}'))") NEXT_RAPIDS_FULL_TAG_PEP440=$(python -c "from setuptools.extern import packaging; print(packaging.version.Version('${NEXT_FULL_TAG}'))") echo "Preparing release $CURRENT_TAG => $NEXT_FULL_TAG" # Inplace sed replace; workaround for Linux and Mac function sed_runner() { sed -i.bak ''"$1"'' $2 && rm -f ${2}.bak } DEPENDENCIES=( cudf ) for FILE in dependencies.yaml; do for DEP in "${DEPENDENCIES[@]}"; do sed_runner "/-.* ${DEP}==/ s/==.*/==${NEXT_RAPIDS_SHORT_TAG_PEP440}\.*/g" ${FILE}; done done for FILE in .github/workflows/*.yaml; do sed_runner "/shared-workflows/ s/@.*/@branch-${NEXT_RAPIDS_SHORT_TAG}/g" "${FILE}" done echo "${NEXT_RAPIDS_FULL_TAG_PEP440}" > VERSION
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/debug-tests/test_send_recv_many_workers.py
import asyncio import multiprocessing import os import random import threading import cloudpickle import numpy as np import pytest from debug_utils import get_cuda_devices, set_rmm from utils import recv, send from distributed.comm.utils import to_frames from distributed.protocol import to_serialize import ucp from ucp.utils import get_event_loop cupy = pytest.importorskip("cupy") rmm = pytest.importorskip("rmm") TRANSFER_ITERATIONS = 5 EP_ITERATIONS = 3 def get_environment_variables(cuda_device_index): env = os.environ.copy() env["CUDA_VISIBLE_DEVICES"] = str(cuda_device_index) return env def restore_environment_variables(cuda_visible_devices, ucx_net_devices): if cuda_visible_devices is None: os.environ.pop("CUDA_VISIBLE_DEVICES") else: os.environ["CUDA_VISIBLE_DEVICES"] = cuda_visible_devices async def get_ep(name, port): addr = ucp.get_address() ep = await ucp.create_endpoint(addr, port) return ep def client(env, port, func, enable_rmm): # connect to server's listener # receive object for TRANSFER_ITERATIONS # repeat for EP_ITERATIONS import numba.cuda numba.cuda.current_context() async def read(): await asyncio.sleep(1) ep = await get_ep("client", port) for i in range(TRANSFER_ITERATIONS): frames, msg = await recv(ep) print("size of the message: ", len(msg["data"])) print("Shutting Down Client...") await ep.close() if enable_rmm: set_rmm() for i in range(EP_ITERATIONS): print("ITER: ", i) get_event_loop().run_until_complete(read()) print("FINISHED") def server(env, port, func, enable_rmm, num_workers, proc_conn): # create frames to send # create listener # notify parent process of listener status # write object to each new connection for TRANSFER_ITERATIONS # close listener after num_workers*EP_ITERATIONS have disconnected os.environ.update(env) import numba.cuda numba.cuda.current_context() loop = get_event_loop() # Creates frames only once to prevent filling the entire GPU print("CREATING CUDA OBJECT IN SERVER...") cuda_obj_generator = cloudpickle.loads(func) cuda_obj = cuda_obj_generator() msg = {"data": to_serialize(cuda_obj)} frames = loop.run_until_complete( to_frames(msg, serializers=("cuda", "dask", "pickle")) ) async def f(listener_port, frames): # coroutine shows up when the client asks # to connect if enable_rmm: set_rmm() # Use a global so the `write` callback function can read frames global _frames global _connected global _disconnected global _lock _connected = 0 _disconnected = 0 _lock = threading.Lock() _frames = frames async def write(ep): global _connected global _disconnected _lock.acquire() _connected += 1 _lock.release() for i in range(TRANSFER_ITERATIONS): print("ITER: ", i) # Send meta data await send(ep, _frames) print("CONFIRM RECEIPT") await ep.close() _lock.acquire() _disconnected += 1 _lock.release() # break lf = ucp.create_listener(write, port=listener_port) proc_conn.send("initialized") proc_conn.close() try: while _disconnected < num_workers * EP_ITERATIONS: await asyncio.sleep(0.1) print("Closing listener") lf.close() except ucp.UCXCloseError: pass loop.run_until_complete(f(port, frames)) def dataframe(): import numpy as np import cudf # always generate the same random numbers np.random.seed(0) size = 2**26 return cudf.DataFrame( {"a": np.random.random(size), "b": np.random.random(size)}, index=np.random.randint(size, size=size), ) def series(): import cudf return cudf.Series(np.arange(90000)) def empty_dataframe(): import cudf return cudf.DataFrame({"a": [1.0], "b": [1.0]}).head(0) def cupy_obj(): import cupy size = 10**8 return cupy.arange(size) @pytest.mark.skipif( len(get_cuda_devices()) < 2, reason="A minimum of two GPUs is required" ) @pytest.mark.parametrize( "cuda_obj_generator", [dataframe, empty_dataframe, series, cupy_obj] ) @pytest.mark.parametrize("enable_rmm", [True, False]) def test_send_recv_cu(cuda_obj_generator, enable_rmm): cuda_visible_devices_base = os.environ.get("CUDA_VISIBLE_DEVICES") ucx_net_devices_base = os.environ.get("UCX_NET_DEVICES") # grab first two devices cuda_visible_devices = get_cuda_devices() num_workers = len(cuda_visible_devices) port = random.randint(13000, 15500) # serialize function and send to the client and server # server will use the return value of the contents, # serialize the values, then send serialized values to client. # client will compare return values of the deserialized # data sent from the server server_env = get_environment_variables(cuda_visible_devices[0]) func = cloudpickle.dumps(cuda_obj_generator) ctx = multiprocessing.get_context("spawn") os.environ.update(server_env) parent_conn, child_conn = multiprocessing.Pipe() server_process = ctx.Process( name="server", target=server, args=[server_env, port, func, enable_rmm, num_workers, child_conn], ) server_process.start() server_msg = parent_conn.recv() assert server_msg == "initialized" client_processes = [] print(cuda_visible_devices) for i in range(num_workers): # cudf will ping the driver for validity of device # this will influence device on which a cuda context is created. # work around is to update env with new CVD before spawning client_env = get_environment_variables(cuda_visible_devices[i]) os.environ.update(client_env) proc = ctx.Process( name="client_" + str(i), target=client, args=[client_env, port, func, enable_rmm], ) proc.start() client_processes.append(proc) # Ensure restoration of environment variables immediately after starting # processes, to avoid never restoring them in case of assertion failures below restore_environment_variables(cuda_visible_devices_base, ucx_net_devices_base) server_process.join() for i in range(len(client_processes)): client_processes[i].join() assert client_processes[i].exitcode == 0 assert server_process.exitcode == 0
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/debug-tests/README.md
## Debug Tests Files in this directory are useful for debugging purposes and often require being executed in two separate sessions (tmux/ssh/etc). NOTE: This was moved outside of the tests directory to prevent users running potentially unstable tests by accident. ## Send/Recv `send.py` and `recv.py` are used to debug/confirm nvlink message passing over 1000 iterations of either CuPy or cudf objects: ### Process 1 > UCXPY_IFNAME=enp1s0f0 CUDA_VISIBLE_DEVICES=0,1 UCX_MEMTYPE_CACHE=n UCX_TLS=tcp,cuda_copy,cuda_ipc /usr/local/cuda/bin/nvprof python tests/debug-testssend.py ### Process 2 > UCXPY_LOG_LEVEL=DEBUG UCX_LOG_LEVEL=DEBUG UCXPY_IFNAME=enp1s0f0 CUDA_VISIBLE_DEVICES=0,1 UCX_MEMTYPE_CACHE=n UCX_TLS=tcp,cuda_copy,cuda_ipc /usr/local/cuda/bin/nvprof python tests/recv.py `nvprof` is used to verify NVLINK usage and we are looking at two things primarily: - existence of [CUDA memcpy PtoP] - balanced cudaMalloc/cudaFree ### Multi-worker Setup This setup is particularly useful for IB testing when `multi-node-workers.sh` is placed in a NFS mount and can be executed independently on each machine - bash scheduler.sh - bash multi-node-workers.sh
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/debug-tests/server.py
import asyncio import os import cloudpickle import pytest from debug_utils import ITERATIONS, parse_args, set_rmm, start_process from utils import recv, send from distributed.comm.utils import to_frames from distributed.protocol import to_serialize import ucp from ucp.utils import get_event_loop cmd = "nvidia-smi nvlink --setcontrol 0bz" # Get output in bytes # subprocess.check_call(cmd, shell=True) pynvml = pytest.importorskip("pynvml", reason="PYNVML not installed") async def get_ep(name, port): addr = ucp.get_address() ep = await ucp.create_endpoint(addr, port) return ep def server(env, port, func, verbose): # create listener receiver # write cudf object # confirm message is sent correctly os.environ.update(env) async def f(listener_port): # coroutine shows up when the client asks # to connect set_rmm() async def write(ep): print("CREATING CUDA OBJECT IN SERVER...") cuda_obj_generator = cloudpickle.loads(func) cuda_obj = cuda_obj_generator() msg = {"data": to_serialize(cuda_obj)} frames = await to_frames(msg, serializers=("cuda", "dask", "pickle")) while True: for i in range(ITERATIONS): print("ITER: ", i) # Send meta data await send(ep, frames) frames, msg = await recv(ep) print("CONFIRM RECEIPT") await ep.close() break # lf.close() del msg del frames lf = ucp.create_listener(write, port=listener_port) try: while not lf.closed(): await asyncio.sleep(0.1) except ucp.UCXCloseError: pass loop = get_event_loop() while True: loop.run_until_complete(f(port)) def main(): args = parse_args(server_address=False) start_process(args, server) if __name__ == "__main__": main()
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/debug-tests/debug_utils.py
import argparse import os import cloudpickle import cupy from utils import get_num_gpus from dask.utils import parse_bytes import rmm from rmm.allocators.cupy import rmm_cupy_allocator ITERATIONS = 100 def set_rmm(): rmm.reinitialize( pool_allocator=True, managed_memory=False, initial_pool_size=parse_bytes("6GB") ) cupy.cuda.set_allocator(rmm_cupy_allocator) def parse_args(server_address=False): parser = argparse.ArgumentParser(description="Tester client process") if server_address is True: parser.add_argument( "-s", "--server", default=None, help="Server address, ucp.get_address() if not specified", ) parser.add_argument("-p", "--port", default=13337, help="Server port", type=int) parser.add_argument( "-o", "--object_type", default="numpy", choices=["numpy", "cupy", "cudf"], help="In-memory array type.", ) parser.add_argument( "-c", "--cpu-affinity", metavar="N", default=-1, type=int, help="CPU affinity (default -1: unset).", ) parser.add_argument( "-v", "--verbose", default=False, action="store_true", help="Print timings per iteration.", ) return parser.parse_args() def get_cuda_devices(): if "CUDA_VISIBLE_DEVICES" in os.environ: return os.environ["CUDA_VISIBLE_DEVICES"].split(",") else: ngpus = get_num_gpus() return list(range(ngpus)) def total_nvlink_transfer(): import pynvml pynvml.nvmlShutdown() pynvml.nvmlInit() try: cuda_dev_id = int(os.environ["CUDA_VISIBLE_DEVICES"].split(",")[0]) except Exception as e: print(e) cuda_dev_id = 0 nlinks = pynvml.NVML_NVLINK_MAX_LINKS handle = pynvml.nvmlDeviceGetHandleByIndex(cuda_dev_id) rx = 0 tx = 0 for i in range(nlinks): transfer = pynvml.nvmlDeviceGetNvLinkUtilizationCounter(handle, i, 0) rx += transfer["rx"] tx += transfer["tx"] return rx, tx def start_process(args, process_function): if args.cpu_affinity >= 0: os.sched_setaffinity(0, [args.cpu_affinity]) base_env = os.environ env = base_env.copy() port = 15339 # serialize function and send to the client and server # server will use the return value of the contents, # serialize the values, then send serialized values to client. # client will compare return values of the deserialized # data sent from the server obj = get_object(args.object_type) obj_func = cloudpickle.dumps(obj) process_function(env, port, obj_func, args.verbose) def cudf_obj(): import numpy as np import cudf size = 2**26 return cudf.DataFrame( {"a": np.random.random(size), "b": np.random.random(size), "c": ["a"] * size} ) def cudf_from_cupy_obj(): import cupy import numpy as np import cudf size = 9**5 obj = cupy.arange(size) data = [obj for i in range(10)] data.extend([np.arange(10) for i in range(10)]) data.append(cudf.Series([1, 2, 3, 4])) data.append({"key": "value"}) data.append({"key": cudf.Series([0.45, 0.134])}) return data def cupy_obj(): import cupy as cp size = 10**9 return cp.arange(size) def numpy_obj(): import numpy as np size = 2**20 obj = np.arange(size) return obj def get_object(object_type): if object_type == "numpy": return numpy_obj elif object_type == "cupy": return cupy_obj elif object_type == "cudf": return cudf_obj else: raise TypeError("Object type %s unknown" % (object_type))
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/debug-tests/scheduler.sh
#!/bin/bash set -e #export UCX_LOG_LEVEL=TRACE # export UCXPY_LOG_LEVEL=DEBUG export UCX_MEMTYPE_CACHE=n export UCX_TLS=tcp,cuda_copy,rc,cuda_ipc UCX_NET_DEVICES=mlx5_0:1 CUDA_VISIBLE_DEVICES=0 python send.py 2>&1 | tee /tmp/send-log.txt &
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/debug-tests/utils.py
import io import logging import os from contextlib import contextmanager import numpy as np import pytest import ucp normal_env = { "UCX_RNDV_SCHEME": "put_zcopy", "UCX_MEMTYPE_CACHE": "n", "UCX_TLS": "rc,cuda_copy,cuda_ipc", "CUDA_VISIBLE_DEVICES": "0", } def set_env(): os.environ.update(normal_env) def get_num_gpus(): import pynvml pynvml.nvmlInit() ngpus = pynvml.nvmlDeviceGetCount() pynvml.nvmlShutdown() return ngpus def get_cuda_devices(): if "CUDA_VISIBLE_DEVICES" in os.environ: return os.environ["CUDA_VISIBLE_DEVICES"].split(",") else: ngpus = get_num_gpus() return list(range(ngpus)) @contextmanager def captured_logger(logger, level=logging.INFO, propagate=None): """Capture output from the given Logger.""" if isinstance(logger, str): logger = logging.getLogger(logger) orig_level = logger.level orig_handlers = logger.handlers[:] if propagate is not None: orig_propagate = logger.propagate logger.propagate = propagate sio = io.StringIO() logger.handlers[:] = [logging.StreamHandler(sio)] logger.setLevel(level) try: yield sio finally: logger.handlers[:] = orig_handlers logger.setLevel(orig_level) if propagate is not None: logger.propagate = orig_propagate def cuda_array(size): try: import rmm return rmm.DeviceBuffer(size=size) except ImportError: import numba.cuda return numba.cuda.device_array((size,), dtype="u1") async def send(ep, frames): pytest.importorskip("distributed") from distributed.utils import nbytes await ep.send(np.array([len(frames)], dtype=np.uint64)) await ep.send( np.array([hasattr(f, "__cuda_array_interface__") for f in frames], dtype=bool) ) await ep.send(np.array([nbytes(f) for f in frames], dtype=np.uint64)) # Send frames for frame in frames: if nbytes(frame) > 0: await ep.send(frame) async def recv(ep): pytest.importorskip("distributed") from distributed.comm.utils import from_frames try: # Recv meta data nframes = np.empty(1, dtype=np.uint64) await ep.recv(nframes) is_cudas = np.empty(nframes[0], dtype=bool) await ep.recv(is_cudas) sizes = np.empty(nframes[0], dtype=np.uint64) await ep.recv(sizes) except (ucp.exceptions.UCXCanceled, ucp.exceptions.UCXCloseError) as e: msg = "SOMETHING TERRIBLE HAS HAPPENED IN THE TEST" raise e(msg) # Recv frames frames = [] for is_cuda, size in zip(is_cudas.tolist(), sizes.tolist()): if size > 0: if is_cuda: frame = cuda_array(size) else: frame = np.empty(size, dtype=np.uint8) await ep.recv(frame) frames.append(frame) else: if is_cuda: frames.append(cuda_array(size)) else: frames.append(b"") msg = await from_frames(frames) return frames, msg async def am_send(ep, frames): await ep.am_send(np.array([len(frames)], dtype=np.uint64)) # Send frames for frame in frames: await ep.am_send(frame) async def am_recv(ep): pytest.importorskip("distributed") from distributed.comm.utils import from_frames try: # Recv meta data nframes = (await ep.am_recv()).view(np.uint64) except (ucp.exceptions.UCXCanceled, ucp.exceptions.UCXCloseError) as e: msg = "SOMETHING TERRIBLE HAS HAPPENED IN THE TEST" raise e(msg) # Recv frames frames = [] for _ in range(nframes[0]): frame = await ep.am_recv() frames.append(frame) msg = await from_frames(frames) return frames, msg
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/debug-tests/test_endpoint_error_callback.py
# This test requires InfiniBand, to run: # UCXPY_IFNAME=ib0 UCX_NET_DEVICES=mlx5_0:1 \ # UCX_TLS=rc,tcp,cuda_copy \ # py.test --cache-clear tests/debug-tests/test_endpoint_error_callback.py import asyncio import multiprocessing import os import random import signal import sys import cloudpickle import pytest from utils import get_cuda_devices, get_num_gpus, recv, send from distributed.comm.utils import to_frames from distributed.protocol import to_serialize import ucp from ucp.utils import get_event_loop cupy = pytest.importorskip("cupy") async def get_ep(name, port, endpoint_error_handling): addr = ucp.get_address() ep = await ucp.create_endpoint( addr, port, endpoint_error_handling=endpoint_error_handling ) return ep def client(port, func, endpoint_error_handling): # wait for server to come up # receive cupy object # process suicides ucp.init() # must create context before importing # cudf/cupy/etc async def read(): await asyncio.sleep(1) ep = await get_ep("client", port, endpoint_error_handling) msg = None import cupy cupy.cuda.set_allocator(None) frames, msg = await recv(ep) # Client process suicides to force an "Endpoint timeout" # on the server os.kill(os.getpid(), signal.SIGKILL) get_event_loop().run_until_complete(read()) def server(port, func, endpoint_error_handling): # create listener receiver # send cupy object # receive cupy object and raise flag on timeout # terminates ep/listener # checks that "Endpoint timeout" was flagged and return process status accordingly ucp.init() global ep_failure_occurred ep_failure_occurred = False async def f(listener_port): # coroutine shows up when the client asks # to connect async def write(ep): global ep_failure_occurred import cupy cupy.cuda.set_allocator(None) print("CREATING CUDA OBJECT IN SERVER...") cuda_obj_generator = cloudpickle.loads(func) cuda_obj = cuda_obj_generator() msg = {"data": to_serialize(cuda_obj)} frames = await to_frames(msg, serializers=("cuda", "dask", "pickle")) # Send meta data try: await send(ep, frames) except Exception: # Avoids process hanging on "Endpoint timeout" pass if endpoint_error_handling is True: try: frames, msg = await recv(ep) except ucp.exceptions.UCXError: ep_failure_occurred = True else: try: frames, msg = await asyncio.wait_for(recv(ep), 3) except asyncio.TimeoutError: ep_failure_occurred = True print("Shutting Down Server...") await ep.close() lf.close() lf = ucp.create_listener( write, port=listener_port, endpoint_error_handling=endpoint_error_handling ) try: while not lf.closed(): await asyncio.sleep(0.1) except ucp.UCXCloseError: pass get_event_loop().run_until_complete(f(port)) if ep_failure_occurred: sys.exit(0) else: sys.exit(1) def cupy_obj(): import cupy size = 10**8 return cupy.arange(size) @pytest.mark.skipif( get_num_gpus() <= 2, reason="Machine does not have more than two GPUs" ) @pytest.mark.parametrize("endpoint_error_handling", [True, False]) def test_send_recv_cu(endpoint_error_handling): base_env = os.environ env_client = base_env.copy() # grab first two devices cvd = get_cuda_devices()[:2] cvd = ",".join(map(str, cvd)) # reverse CVD for other worker env_client["CUDA_VISIBLE_DEVICES"] = cvd[::-1] port = random.randint(13000, 15500) # serialize function and send to the client and server # server will use the return value of the contents, # serialize the values, then send serialized values to client. # client will compare return values of the deserialized # data sent from the server func = cloudpickle.dumps(cupy_obj) ctx = multiprocessing.get_context("spawn") server_process = ctx.Process( name="server", target=server, args=[port, func, endpoint_error_handling] ) client_process = ctx.Process( name="client", target=client, args=[port, func, endpoint_error_handling] ) server_process.start() # cudf will ping the driver for validity of device # this will influence device on which a cuda context is created. # work around is to update env with new CVD before spawning os.environ.update(env_client) client_process.start() server_process.join() client_process.join() print("server_process.exitcode:", server_process.exitcode) assert server_process.exitcode == 0 assert client_process.exitcode == -9
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/debug-tests/client.py
import asyncio import os import time import pynvml import pytest from debug_utils import ( ITERATIONS, parse_args, set_rmm, start_process, total_nvlink_transfer, ) from utils import recv, send import ucp from ucp.utils import get_event_loop pynvml.nvmlInit() cmd = "nvidia-smi nvlink --setcontrol 0bz" # Get output in bytes # subprocess.check_call(cmd, shell=True) pynvml = pytest.importorskip("pynvml", reason="PYNVML not installed") async def get_ep(name, port): addr = ucp.get_address() ep = await ucp.create_endpoint(addr, port) return ep def client(env, port, func, verbose): # wait for server to come up # receive cudf object # deserialize # assert deserialized msg is cdf # send receipt os.environ.update(env) before_rx, before_tx = total_nvlink_transfer() async def read(): await asyncio.sleep(1) ep = await get_ep("client", port) for i in range(ITERATIONS): bytes_used = pynvml.nvmlDeviceGetMemoryInfo( pynvml.nvmlDeviceGetHandleByIndex(0) ).used bytes_used # print("Bytes Used:", bytes_used, i) frames, msg = await recv(ep) # Send meta data await send(ep, frames) print("Shutting Down Client...") await ep.close() set_rmm() for i in range(ITERATIONS): print("ITER: ", i) t = time.time() get_event_loop().run_until_complete(read()) if verbose: print("Time take for interation %d: %ss" % (i, time.time() - t)) print("FINISHED") # num_bytes = nbytes(rx_cuda_obj) # print(f"TOTAL DATA RECEIVED: {num_bytes}") # nvlink only measures in KBs # if num_bytes > 90000: # rx, tx = total_nvlink_transfer() # msg = f"RX BEFORE SEND: {before_rx} -- RX AFTER SEND: {rx} \ # -- TOTAL DATA: {num_bytes}" # print(msg) # assert rx > before_rx # import cloudpickle # cuda_obj_generator = cloudpickle.loads(func) # pure_cuda_obj = cuda_obj_generator() # from cudf.testing._utils import assert_eq # import cupy as cp # if isinstance(rx_cuda_obj, cp.ndarray): # cp.testing.assert_allclose(rx_cuda_obj, pure_cuda_obj) # else: # assert_eq(rx_cuda_obj, pure_cuda_obj) def main(): args = parse_args(server_address=True) start_process(args, client) if __name__ == "__main__": main()
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/debug-tests/multi-node-workers.sh
#!/bin/bash set -e #export UCX_LOG_LEVEL=DEBUG #export UCXPY_LOG_LEVEL=DEBUG export UCX_MEMTYPE_CACHE=n export UCX_TLS=tcp,cuda_copy,rc UCX_NET_DEVICES=mlx5_0:1 CUDA_VISIBLE_DEVICES=0 python recv.py 2>&1 | tee /tmp/recv-log-0.txt & UCX_NET_DEVICES=mlx5_0:1 CUDA_VISIBLE_DEVICES=1 python recv.py 2>&1 | tee /tmp/recv-log-1.txt & UCX_NET_DEVICES=mlx5_1:1 CUDA_VISIBLE_DEVICES=2 python recv.py 2>&1 | tee /tmp/recv-log-2.txt & UCX_NET_DEVICES=mlx5_1:1 CUDA_VISIBLE_DEVICES=3 python recv.py 2>&1 | tee /tmp/recv-log-3.txt & UCX_NET_DEVICES=mlx5_2:1 CUDA_VISIBLE_DEVICES=4 python recv.py 2>&1 | tee /tmp/recv-log-4.txt & UCX_NET_DEVICES=mlx5_2:1 CUDA_VISIBLE_DEVICES=5 python recv.py 2>&1 | tee /tmp/recv-log-5.txt & UCX_NET_DEVICES=mlx5_3:1 CUDA_VISIBLE_DEVICES=6 python recv.py 2>&1 | tee /tmp/recv-log-6.txt & UCX_NET_DEVICES=mlx5_3:1 CUDA_VISIBLE_DEVICES=7 python recv.py 2>&1 | tee /tmp/recv-log-7.txt & sleep 3600
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/examples/cupy-example.py
import asyncio import time import cupy from dask import array as da from dask_cuda import LocalCUDACluster from dask_cuda.initialize import initialize from distributed import Client enable_tcp_over_ucx = True enable_infiniband = False enable_nvlink = False async def run(): initialize( create_cuda_context=True, enable_tcp_over_ucx=enable_tcp_over_ucx, enable_infiniband=enable_infiniband, enable_nvlink=enable_nvlink, ) async with LocalCUDACluster( interface="enp1s0f0", protocol="ucx", enable_tcp_over_ucx=enable_tcp_over_ucx, enable_infiniband=enable_infiniband, enable_nvlink=enable_nvlink, asynchronous=True, ) as cluster: async with Client(cluster, asynchronous=True) as client: rs = da.random.RandomState(RandomState=cupy.random.RandomState) a = rs.normal(10, 1, (int(4e3), int(4e3)), chunks=(int(1e3), int(1e3))) x = a + a.T for i in range(100): print("Running iteration:", i) start = time.time() await client.compute(x) print("Time for iteration", i, ":", time.time() - start) if __name__ == "__main__": asyncio.run(run())
0
rapidsai_public_repos/ucx-py
rapidsai_public_repos/ucx-py/examples/cudf-example.py
import asyncio import time from dask_cuda import LocalCUDACluster from dask_cuda.initialize import initialize from distributed import Client import cudf import dask_cudf enable_tcp_over_ucx = True enable_infiniband = False enable_nvlink = False async def run(): initialize( create_cuda_context=True, enable_tcp_over_ucx=enable_tcp_over_ucx, enable_infiniband=enable_infiniband, enable_nvlink=enable_nvlink, ) async with LocalCUDACluster( interface="enp1s0f0", protocol="ucx", enable_tcp_over_ucx=enable_tcp_over_ucx, enable_infiniband=enable_infiniband, enable_nvlink=enable_nvlink, asynchronous=True, ) as cluster: async with Client(cluster, asynchronous=True) as client: d = dask_cudf.from_cudf( cudf.DataFrame({"a": range(2**16)}), npartitions=2 ) r = d.sum() for i in range(100): print("Running iteration:", i) start = time.time() await client.compute(r) print("Time for iteration", i, ":", time.time() - start) if __name__ == "__main__": asyncio.run(run())
0
rapidsai_public_repos
rapidsai_public_repos/test-installer/README.md
This repo contains simple scripts to test the install of RAPIDS in a conda environment.
0
rapidsai_public_repos/test-installer/ci
rapidsai_public_repos/test-installer/ci/axis/axis.yml
INSTALLER: - conda - mamba RAPIDS_VER: - '22.02' - '22.04' RAPIDS_CONDA_CHANNEL: - rapidsai - rapidsai-nightly excludes: - RAPIDS_VER: '22.02' RAPIDS_CONDA_CHANNEL: rapidsai-nightly - RAPIDS_VER: '22.04' RAPIDS_CONDA_CHANNEL: rapidsai
0
rapidsai_public_repos/test-installer/ci
rapidsai_public_repos/test-installer/ci/cpu/build.sh
#!/bin/bash set -e export PATH=/opt/conda/bin:/usr/local/cuda/bin:$PATH export HOME="$WORKSPACE" . /opt/conda/etc/profile.d/conda.sh conda config --set ssl_verify False conda install -y -c gpuci gpuci-tools || conda install -y -c gpuci gpuci-tools if [[ "$INSTALLER" == "mamba" ]]; then gpuci_logger "Install mamba" gpuci_conda_retry install -y -c conda-forge mamba fi CHANNELS="-c $RAPIDS_CONDA_CHANNEL -c nvidia -c conda-forge" gpuci_logger "Install rapids" if [[ "$INSTALLER" == "conda" ]]; then gpuci_conda_retry create -n test $CHANNELS rapids=$RAPIDS_VER cudatoolkit=11.5 dask-sql elif [[ "$INSTALLER" == "mamba" ]]; then gpuci_mamba_retry create -n test $CHANNELS rapids=$RAPIDS_VER cudatoolkit=11.5 dask-sql else gpuci_logger "Unknown INSTALLER" exit 1 fi
0
rapidsai_public_repos
rapidsai_public_repos/rapids-triton-template/CMakeLists.txt
#============================================================================= # Copyright (c) 2020-2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #============================================================================= cmake_minimum_required(VERSION 3.21 FATAL_ERROR) ############################################################################## # - Target names ------------------------------------------------------------- # TODO(template): Insert the name of your backend below set(BACKEND_NAME "REPLACE_ME") set(BACKEND_TARGET "triton_${BACKEND_NAME}") ############################################################################## # - Prepare rapids-cmake ----------------------------------------------------- file(DOWNLOAD https://raw.githubusercontent.com/rapidsai/rapids-cmake/branch-21.10/RAPIDS.cmake ${CMAKE_BINARY_DIR}/RAPIDS.cmake) include(${CMAKE_BINARY_DIR}/RAPIDS.cmake) include(rapids-cmake) include(rapids-cpm) include(rapids-cuda) include(rapids-export) include(rapids-find) rapids_cuda_init_architectures(RAPIDS_TRITON_BACKEND) project(RAPIDS_TRITON_BACKEND VERSION 21.10.00 LANGUAGES CXX CUDA) ############################################################################## # - build type --------------------------------------------------------------- # Set a default build type if none was specified rapids_cmake_build_type(Release) # this is needed for clang-tidy runs set(CMAKE_EXPORT_COMPILE_COMMANDS ON) ############################################################################## # - User Options ------------------------------------------------------------ option(BUILD_BACKEND_TESTS "Build RAPIDS_TRITON_BACKEND unit-tests" ON) option(CUDA_ENABLE_KERNEL_INFO "Enable kernel resource usage info" OFF) option(CUDA_ENABLE_LINE_INFO "Enable lineinfo in nvcc" OFF) option(DETECT_CONDA_ENV "Enable detection of conda environment for dependencies" ON) option(DISABLE_DEPRECATION_WARNINGS "Disable depreaction warnings " ON) option(NVTX "Enable nvtx markers" OFF) message(VERBOSE "RAPIDS_TRITON_BACKEND: Enabling detection of conda environment for dependencies: ${DETECT_CONDA_ENV}") message(VERBOSE "RAPIDS_TRITON_BACKEND: Enabling kernelinfo in nvcc: ${CUDA_ENABLE_KERNEL_INFO}") message(VERBOSE "RAPIDS_TRITON_BACKEND: Enabling lineinfo in nvcc: ${CUDA_ENABLE_LINE_INFO}") message(VERBOSE "RAPIDS_TRITON_BACKEND: Enabling nvtx markers: ${NVTX}") message(VERBOSE "RAPIDS_TRITON_BACKEND: Build RAPIDS_TRITON_BACKEND unit-tests: ${BUILD_TESTS}") # Set RMM logging level set(RMM_LOGGING_LEVEL "INFO" CACHE STRING "Choose the logging level.") set_property(CACHE RMM_LOGGING_LEVEL PROPERTY STRINGS "TRACE" "DEBUG" "INFO" "WARN" "ERROR" "CRITICAL" "OFF") message(VERBOSE "RAPIDS_TRITON_BACKEND: RMM_LOGGING_LEVEL = '${RMM_LOGGING_LEVEL}'.") ############################################################################## # - Conda environment detection ---------------------------------------------- if(DETECT_CONDA_ENV) rapids_cmake_support_conda_env( conda_env MODIFY_PREFIX_PATH ) if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT AND DEFINED ENV{CONDA_PREFIX}) message(STATUS "RAPIDS_TRITON_BACKEND: No CMAKE_INSTALL_PREFIX argument detected, setting to: $ENV{CONDA_PREFIX}") set(CMAKE_INSTALL_PREFIX "$ENV{CONDA_PREFIX}") endif() endif() ############################################################################## # - compiler options --------------------------------------------------------- # * find CUDAToolkit package # * determine GPU architectures # * enable the CMake CUDA language # * set other CUDA compilation flags rapids_find_package(CUDAToolkit REQUIRED BUILD_EXPORT_SET ${BACKEND_TARGET}-exports INSTALL_EXPORT_SET ${BACKEND_TARGET}-exports ) include(cmake/modules/ConfigureCUDA.cmake) ############################################################################## # - Requirements ------------------------------------------------------------- # add third party dependencies using CPM rapids_cpm_init() include(cmake/thirdparty/get_rapids-triton.cmake) if(BUILD_TESTS) include(cmake/thirdparty/get_gtest.cmake) endif() ############################################################################## # - install targets----------------------------------------------------------- # TODO(template): Add any additional source files below add_library( ${BACKEND_TARGET} SHARED src/api.cc ) set_target_properties(${BACKEND_TARGET} PROPERTIES BUILD_RPATH "\$ORIGIN" # set target compile options CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON POSITION_INDEPENDENT_CODE ON INTERFACE_POSITION_INDEPENDENT_CODE ON ) target_compile_options(${BACKEND_TARGET} PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:${RAPIDS_TRITON_BACKEND_CXX_FLAGS}>" "$<$<COMPILE_LANGUAGE:CUDA>:${RAPIDS_TRITON_BACKEND_CUDA_FLAGS}>" ) target_include_directories(${BACKEND_TARGET} PRIVATE "$<BUILD_INTERFACE:${RAPIDS_TRITON_BACKEND_SOURCE_DIR}/include>" "${CMAKE_CURRENT_SOURCE_DIR}/src" ) target_link_libraries(${BACKEND_TARGET} PRIVATE rapids_triton::rapids_triton triton-core-serverstub triton-backend-utils "${TRITONSERVER_LIB}" $<TARGET_NAME_IF_EXISTS:conda_env> ) install( TARGETS ${BACKEND_TARGET} LIBRARY DESTINATION /opt/tritonserver/backends/${BACKEND_NAME} ) ############################################################################## # - build test executable ---------------------------------------------------- # TODO (wphicks) # if(BUILD_TESTS) # include(test/CMakeLists.txt) # endif()
0
rapidsai_public_repos
rapidsai_public_repos/rapids-triton-template/README.md
<!-- # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of NVIDIA CORPORATION nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <!--TODO(template): Replace this with the README for your backend --> [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) # The RAPIDS-Triton Backend Template This template repo offers a starting place for those wishing to create a Triton backend with [RAPIDS-Triton](https://github.com/rapidsai/rapids-triton). For an example of how to use this template with detailed commentary, check out the [Linear Example](https://github.com/rapidsai/rapids-triton-linear-example) repo. Throughout the repo, you will find comments labeled `TODO(template)`, indicating places where you will need to insert your own code or make changes. Working through each of these should allow you to create a working Triton backend.
0
rapidsai_public_repos
rapidsai_public_repos/rapids-triton-template/Dockerfile
########################################################################################### # Arguments for controlling build details ########################################################################################### # Version of Triton to use ARG TRITON_VERSION=21.08 # Base container image ARG BASE_IMAGE=nvcr.io/nvidia/tritonserver:${TRITON_VERSION}-py3 # Whether or not to build indicated components ARG BUILD_TESTS=OFF ARG BUILD_EXAMPLE=ON FROM ${BASE_IMAGE} as base ENV PATH="/root/miniconda3/bin:${PATH}" RUN apt-get update \ && apt-get install --no-install-recommends -y wget patchelf \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* ENV PYTHONDONTWRITEBYTECODE=true RUN wget \ https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \ && mkdir /root/.conda \ && bash Miniconda3-latest-Linux-x86_64.sh -b \ && rm -f Miniconda3-latest-Linux-x86_64.sh COPY ./conda/environments/rapids_triton_dev_cuda11.4.yml /environment.yml RUN conda env update -f /environment.yml \ && rm /environment.yml \ && conda clean -afy \ && find /root/miniconda3/ -follow -type f -name '*.pyc' -delete \ && find /root/miniconda3/ -follow -type f -name '*.js.map' -delete ENV PYTHONDONTWRITEBYTECODE=false RUN mkdir /rapids_triton COPY ./src /rapids_triton/src COPY ./CMakeLists.txt /rapids_triton COPY ./cmake /rapids_triton/cmake WORKDIR /rapids_triton SHELL ["conda", "run", "--no-capture-output", "-n", "rapids_triton_dev", "/bin/bash", "-c"] FROM base as build-stage ARG TRITON_VERSION ENV TRITON_VERSION=$TRITON_VERSION ARG BUILD_TYPE=Release ENV BUILD_TYPE=$BUILD_TYPE ARG BUILD_TESTS ENV BUILD_TESTS=$BUILD_TESTS ARG BUILD_EXAMPLE ENV BUILD_EXAMPLE=$BUILD_EXAMPLE RUN mkdir /rapids_triton/build /rapids_triton/install WORKDIR /rapids_triton/build RUN cmake \ -GNinja \ -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ -DBUILD_TESTS="${BUILD_TESTS}" \ -DCMAKE_INSTALL_PREFIX=/rapids_triton/install \ -DTRITON_COMMON_REPO_TAG="r${TRITON_VERSION}" \ -DTRITON_CORE_REPO_TAG="r${TRITON_VERSION}" \ -DTRITON_BACKEND_REPO_TAG="r${TRITON_VERSION}" \ .. RUN ninja install FROM ${BASE_IMAGE} ARG BACKEND_NAME ENV BACKEND_NAME=$BACKEND_NAME RUN mkdir /models # Remove existing backend install RUN if [ -d /opt/tritonserver/backends/${BACKEND_NAME} ]; \ then \ rm -rf /opt/tritonserver/backends/${BACKEND_NAME}/*; \ fi # TODO(template): If linking against any shared libraries, copy them over as # well COPY --from=build-stage \ /opt/tritonserver/backends/$BACKEND_NAME \ /opt/tritonserver/backends/$BACKEND_NAME ENTRYPOINT ["tritonserver", "--model-repository=/models"]
0
rapidsai_public_repos/rapids-triton-template/conda
rapidsai_public_repos/rapids-triton-template/conda/environments/rapids_triton_dev_cuda11.4.yml
--- name: rapids_triton_dev channels: - nvidia - conda-forge dependencies: - cmake>=3.21 - cudatoolkit=11.4 - ninja - rapidjson # TODO(template): Add any build dependencies for your backend
0
rapidsai_public_repos/rapids-triton-template/conda
rapidsai_public_repos/rapids-triton-template/conda/environments/rapids_triton_test.yml
--- name: rapids_triton_test channels: - conda-forge dependencies: - flake8 - pip - python - pytest - numpy - pip: - nvidia-pyindex # TODO(template): Add any test dependencies for your tests here
0
rapidsai_public_repos/rapids-triton-template/cmake
rapidsai_public_repos/rapids-triton-template/cmake/modules/ConfigureCUDA.cmake
#============================================================================= # Copyright (c) 2018-2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #============================================================================= if(DISABLE_DEPRECATION_WARNINGS) list(APPEND RAPIDS_TRITON_CXX_FLAGS -Wno-deprecated-declarations) list(APPEND RAPIDS_TRITON_CUDA_FLAGS -Xcompiler=-Wno-deprecated-declarations) endif() if(CMAKE_COMPILER_IS_GNUCXX) list(APPEND RAPIDS_TRITON_CXX_FLAGS -Wall -Werror -Wno-unknown-pragmas -Wno-error=deprecated-declarations) endif() list(APPEND RAPIDS_TRITON_CUDA_FLAGS --expt-extended-lambda --expt-relaxed-constexpr) # set warnings as errors if(CMAKE_CUDA_COMPILER_VERSION VERSION_GREATER_EQUAL 11.2.0) list(APPEND RAPIDS_TRITON_CUDA_FLAGS -Werror=all-warnings) endif() list(APPEND RAPIDS_TRITON_CUDA_FLAGS -Xcompiler=-Wall,-Werror,-Wno-error=deprecated-declarations) # Option to enable line info in CUDA device compilation to allow introspection when profiling / memchecking if(CUDA_ENABLE_LINEINFO) list(APPEND RAPIDS_TRITON_CUDA_FLAGS -lineinfo) endif() # Debug options if(CMAKE_BUILD_TYPE MATCHES Debug) message(VERBOSE "RAPIDS_TRITON: Building with debugging flags") list(APPEND RAPIDS_TRITON_CUDA_FLAGS -G -Xcompiler=-rdynamic) endif()
0
rapidsai_public_repos/rapids-triton-template/cmake
rapidsai_public_repos/rapids-triton-template/cmake/thirdparty/get_gtest.cmake
#============================================================================= # Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #============================================================================= function(find_and_configure_gtest) include(${rapids-cmake-dir}/cpm/gtest.cmake) rapids_cpm_gtest() endfunction() find_and_configure_gtest()
0
rapidsai_public_repos/rapids-triton-template/cmake
rapidsai_public_repos/rapids-triton-template/cmake/thirdparty/get_rapids-triton.cmake
#============================================================================= # Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #============================================================================= function(find_and_configure_rapids_triton) set(oneValueArgs VERSION FORK PINNED_TAG) cmake_parse_arguments(PKG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) rapids_cpm_find(rapids_triton ${PKG_VERSION} GLOBAL_TARGETS rapids_triton::rapids_triton BUILD_EXPORT_SET ${BACKEND_TARGET}-exports INSTALL_EXPORT_SET ${BACKEND_TARGET}-exports CPM_ARGS GIT_REPOSITORY https://github.com/${PKG_FORK}/rapids-triton.git GIT_TAG ${PKG_PINNED_TAG} SOURCE_SUBDIR cpp OPTIONS "BUILD_TESTS OFF" "BUILD_EXAMPLE OFF" ) message(VERBOSE "RAPIDS_TRITON_BACKEND: Using RAPIDS-Triton located in ${rapids_triton_SOURCE_DIR}") endfunction() # Change pinned tag here to test a commit in CI # To use a different RAFT locally, set the CMake variable # CPM_raft_SOURCE=/path/to/local/raft find_and_configure_rapids_triton(VERSION 21.10 FORK rapidsai PINNED_TAG branch-21.10 )
0
rapidsai_public_repos/rapids-triton-template
rapidsai_public_repos/rapids-triton-template/src/api.cc
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <model.h> #include <names.h> #include <shared_state.h> #include <stdint.h> #include <triton/backend/backend_common.h> #include <triton/backend/backend_model.h> #include <triton/backend/backend_model_instance.h> #include <rapids_triton/triton/api/execute.hpp> #include <rapids_triton/triton/api/initialize.hpp> #include <rapids_triton/triton/api/instance_finalize.hpp> #include <rapids_triton/triton/api/instance_initialize.hpp> #include <rapids_triton/triton/api/model_finalize.hpp> #include <rapids_triton/triton/api/model_initialize.hpp> #include <rapids_triton/triton/model_instance_state.hpp> #include <rapids_triton/triton/model_state.hpp> namespace triton { namespace backend { namespace NAMESPACE { using ModelState = rapids::TritonModelState<RapidsSharedState>; using ModelInstanceState = rapids::ModelInstanceState<RapidsModel, RapidsSharedState>; extern "C" { /** Confirm that backend is compatible with Triton's backend API version */ TRITONSERVER_Error* TRITONBACKEND_Initialize(TRITONBACKEND_Backend* backend) { return rapids::triton_api::initialize(backend); } TRITONSERVER_Error* TRITONBACKEND_ModelInitialize(TRITONBACKEND_Model* model) { return rapids::triton_api::model_initialize<ModelState>(model); } TRITONSERVER_Error* TRITONBACKEND_ModelFinalize(TRITONBACKEND_Model* model) { return rapids::triton_api::model_finalize<ModelState>(model); } TRITONSERVER_Error* TRITONBACKEND_ModelInstanceInitialize( TRITONBACKEND_ModelInstance* instance) { return rapids::triton_api::instance_initialize<ModelState, ModelInstanceState>(instance); } TRITONSERVER_Error* TRITONBACKEND_ModelInstanceFinalize( TRITONBACKEND_ModelInstance* instance) { return rapids::triton_api::instance_finalize<ModelInstanceState>(instance); } TRITONSERVER_Error* TRITONBACKEND_ModelInstanceExecute( TRITONBACKEND_ModelInstance* instance, TRITONBACKEND_Request** raw_requests, uint32_t const request_count) { return rapids::triton_api::execute<ModelState, ModelInstanceState>( instance, raw_requests, static_cast<std::size_t>(request_count)); } } // extern "C" } // namespace NAMESPACE } // namespace backend } // namespace triton
0
rapidsai_public_repos/rapids-triton-template
rapidsai_public_repos/rapids-triton-template/src/shared_state.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <names.h> #include <memory> #include <rapids_triton/model/shared_state.hpp> namespace triton { namespace backend { namespace NAMESPACE { struct RapidsSharedState : rapids::SharedModelState { RapidsSharedState(std::unique_ptr<common::TritonJson::Value>&& config) : rapids::SharedModelState{std::move(config)} {} // TODO(template): Define the following only if necessary for your backend /* void load() {} void unload() {} */ }; } // namespace NAMESPACE } // namespace backend } // namespace triton
0
rapidsai_public_repos/rapids-triton-template
rapidsai_public_repos/rapids-triton-template/src/model.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <names.h> #include <shared_state.h> #include <rapids_triton/batch/batch.hpp> // rapids::Batch #include <rapids_triton/model/model.hpp> // rapids::Model #include <rapids_triton/triton/deployment.hpp> // rapids::DeploymentType #include <rapids_triton/triton/device.hpp> // rapids::device_id_t namespace triton { namespace backend { namespace NAMESPACE { struct RapidsModel : rapids::Model<RapidsSharedState> { RapidsModel(std::shared_ptr<RapidsSharedState> shared_state, rapids::device_id_t device_id, cudaStream_t default_stream, rapids::DeploymentType deployment_type, std::string const& filepath) : rapids::Model<RapidsSharedState>(shared_state, device_id, default_stream, deployment_type, filepath) {} void predict(rapids::Batch& batch) const { // TODO(template): Add prediction logic } // TODO(template): Define any of the following only if necessary for your // backend /* void load() {} void unload() {} std::optional<rapids::MemoryType> preferred_mem_type(rapids::Batch& batch) const { } cudaStream_t get_stream() const {} */ }; } // namespace NAMESPACE } // namespace backend } // namespace triton
0
rapidsai_public_repos/rapids-triton-template
rapidsai_public_repos/rapids-triton-template/src/names.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once // TODO(template): Insert the name of your backend below #define NAMESPACE REPLACE_ME
0
rapidsai_public_repos/rapids-triton-template/qa
rapidsai_public_repos/rapids-triton-template/qa/L0_e2e/test_model.py
# Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import pytest from rapids_triton import Client from rapids_triton.testing import array_close @pytest.fixture def model_inputs(): # TODO(template): Add data generation/retrieval for model tests @pytest.fixture def model_output_sizes(): # TODO(template): Compute size (in bytes) of outputs and return as # dictionary mapping output names to sizes def get_ground_truth(inputs): #TODO(template): Return ground truth expected for given inputs #TODO(template): Provide names of each model to test @pytest.mark.parametrize( "model_name", ['REPLACE_ME'] ) def test_model(model_name, model_inputs, model_output_sizes): client = Client() result = client.predict(model_name, model_inputs, model_output_sizes) shm_result = client.predict( model_name, model_inputs, model_output_sizes, shared_mem='cuda' ) ground_truth = get_ground_truth(model_inputs) for output_name in sorted(ground_truth.keys()): arrays_close( result[output_name], ground_truth[output_name], atol=1e-5, assert_close=True ) arrays_close( shm_result[output_name], ground_truth[output_name], atol=1e-5, assert_close=True )
0
rapidsai_public_repos/rapids-triton-template/qa/L0_e2e/model_repository
rapidsai_public_repos/rapids-triton-template/qa/L0_e2e/model_repository/example/config.pbtxt
# TODO(template): Replace backend name backend: "REPLACE_ME" max_batch_size: 32768 # TODO(template): Replace input specifications input [ { name: "input__0" data_type: TYPE_FP32 dims: [ 4 ] }, { name: "input__1" data_type: TYPE_FP32 dims: [ 4 ] } ] # TODO(template): Replace output specifications output [ { name: "output__0" data_type: TYPE_FP32 dims: [ 4 ] } ] # TODO(template): Specify how this model should be deployed instance_group [{ kind: KIND_GPU }] # TODO(template): Add parameters if neeeded parameters [ ] dynamic_batching { max_queue_delay_microseconds: 100 }
0
rapidsai_public_repos/rapids-triton-template/qa/L0_e2e/model_repository/example
rapidsai_public_repos/rapids-triton-template/qa/L0_e2e/model_repository/example/1/serialized_model.txt
TODO(template): Replace this with serialized model for your backend
0
rapidsai_public_repos
rapidsai_public_repos/ptxcompiler/setup.cfg
# COPYRIGHT (c) 2021, NVIDIA CORPORATION. [versioneer] VCS = git style = pep440 versionfile_source = ptxcompiler/_version.py versionfile_build = ptxcompiler/_version.py tag_prefix = parentdir_prefix = ptxcompiler-
0
rapidsai_public_repos
rapidsai_public_repos/ptxcompiler/README.md
# Static PTX Compiler Python binding and Numba patch This package provides a Python binding for the `libptxcompiler_static.a` library and a Numba patch that fixes it to use the static library for compiling PTX instead of the linker. This enables Numba to support CUDA enhanced compatibility for scenarios where a single PTX file is compiled and linked as part of the compilation process. This covers all use cases, except: - Using Cooperative Groups. - Debugging features - this includes debug and lineinfo generation, and exception checking inside CUDA kernels. ## Numba support Numba 0.54.1 and above are supported. ## Installation Install with either: ``` python setup.py develop ``` or ``` python setup.py install ``` ## Testing Run ``` pytest ``` or ``` python ptxcompiler/tests/test_lib.py ``` ## Usage ### Numba >= 0.57 To configure Numba to use ptxcompiler, set the environment variable `NUMBA_CUDA_ENABLE_MINOR_VERSION_COMPATIBILITY=1`. See the Numba [CUDA Minor Version Compatibility documentation](https://numba.readthedocs.io/en/stable/cuda/minor_version_compatibility.html) for further information. ### Numba versions < 0.57 Numba versions < 0.57 need to be monkey patched to use ptxcompiler if required. To apply the monkey patch if needed, call the `patch_numba_codegen_if_needed()` function: ```python from ptxcompiler.patch import patch_numba_codegen_if_needed patch_numba_codegen_if_needed() ``` This function spawns a new process to check the CUDA Driver and Runtime versions, so it can be safely called at any point in a process. It will only patch Numba when the Runtime version exceeds the Driver version. Under certain circumstances (for example running with InfiniBand network stacks), spawning a subprocess might not be possible. For these cases, the patching behaviour can be controlled using two environment variables: - `PTXCOMPILER_CHECK_NUMBA_CODEGEN_PATCH_NEEDED`: if set to a truthy integer then a subprocess will be spawned to check if patching Numba is necessary. Default value: True (the subprocess check is carried out) - `PTXCOMPILER_APPLY_NUMBA_CODEGEN_PATCH`: if it is known that patching is necessary, but spawning a subprocess is not possible, set this to a truthy integer to unconditionally patch Numba. Default value: False (Numba is not unconditionally patched).
0
rapidsai_public_repos
rapidsai_public_repos/ptxcompiler/versioneer.py
# Version: 0.21 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/python-versioneer/python-versioneer * Brian Warner * License: Public Domain * Compatible with: Python 3.6, 3.7, 3.8, 3.9 and pypy3 * [![Latest Version][pypi-image]][pypi-url] * [![Build Status][travis-image]][travis-url] This is a tool for managing a recorded version number in distutils-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install * `pip install versioneer` to somewhere in your $PATH * add a `[versioneer]` section to your setup.cfg (see [Install](INSTALL.md)) * run `versioneer install` in your source tree, commit the results * Verify version information with `python setup.py version` ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS keyword ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes). The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. To allow `setup.py` to compute a version too, a `versioneer.py` is added to the top level of your source tree, next to `setup.py` and the `setup.cfg` that configures it. This overrides several distutils/setuptools commands to compute the version when invoked, and changes `setup.py build` and `setup.py sdist` to replace `_version.py` with a small static file that contains just the generated version data. ## Installation See [INSTALL.md](./INSTALL.md) for detailed installation instructions. ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different flavors of version information: * `['version']`: A condensed version string, rendered using the selected style. This is the most commonly used value for the project's version string. The default "pep440" style yields strings like `0.11`, `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section below for alternative styles. * `['full-revisionid']`: detailed revision identifier. For Git, this is the full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the commit date in ISO 8601 format. This will be None if the date is not available. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that this is only accurate if run in a VCS checkout, otherwise it is likely to be False or None * `['error']`: if the version string could not be computed, this will be set to a string describing the problem, otherwise it will be None. It may be useful to throw an exception in setup.py if this is set, to avoid e.g. creating tarballs with a version string of "unknown". Some variants are more useful than others. Including `full-revisionid` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. The installer adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version__ = get_versions()['version'] del get_versions ## Styles The setup.cfg `style=` configuration controls how the VCS information is rendered into a version string. The default style, "pep440", produces a PEP440-compliant string, equal to the un-prefixed tag name for actual releases, and containing an additional "local version" section with more detail for in-between builds. For Git, this is TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and that this commit is two revisions ("+2") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". Other styles are available. See [details.md](details.md) in the Versioneer source tree for descriptions. ## Debugging Versioneer tries to avoid fatal errors: if something goes wrong, it will tend to return a version of "0+unknown". To investigate the problem, run `setup.py version`, which will run the version-lookup code in a verbose mode, and will display the full contents of `get_versions()` (including the `error` string, which may help identify what went wrong). ## Known Limitations Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github [issues page](https://github.com/python-versioneer/python-versioneer/issues). ### Subprojects Versioneer has limited support for source trees in which `setup.py` is not in the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are two common reasons why `setup.py` might not be in the root: * Source trees which contain multiple subprojects, such as [Buildbot](https://github.com/buildbot/buildbot), which contains both "master" and "slave" subprojects, each with their own `setup.py`, `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also provide bindings to Python (and perhaps other languages) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs and implementation details which frequently cause `pip install .` from a subproject directory to fail to find a correct version string (so it usually defaults to `0+unknown`). `pip install --editable .` should work correctly. `setup.py install` might work too. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. [Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve pip to let Versioneer work correctly. Versioneer-0.16 and earlier only looked for a `.git` directory next to the `setup.cfg`, so subprojects were completely unsupported with those releases. ### Editable installs with setuptools <= 18.5 `setup.py develop` and `pip install --editable .` allow you to install a project into a virtualenv once, then continue editing the source code (and test) without re-installing after every change. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a convenient way to specify executable scripts that should be installed along with the python package. These both work as expected when using modern setuptools. When using setuptools-18.5 or earlier, however, certain operations will cause `pkg_resources.DistributionNotFound` errors when running the entrypoint script, which must be resolved by re-installing the package. This happens when the install happens with one version, then the egg_info data is regenerated while a different version is checked out. Many setup.py commands cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. [Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * edit `setup.cfg`, if necessary, to include any new configuration settings indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. * re-run `versioneer install` in your source tree, to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## Similar projects * [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time dependency * [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of versioneer * [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools plugin ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. Specifically, both are released under the Creative Commons "Public Domain Dedication" license (CC0-1.0), as described in https://creativecommons.org/publicdomain/zero/1.0/ . [pypi-image]: https://img.shields.io/pypi/v/versioneer.svg [pypi-url]: https://pypi.python.org/pypi/versioneer/ [travis-image]: https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg [travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer """ # pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring # pylint:disable=missing-class-docstring,too-many-branches,too-many-statements # pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error # pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with # pylint:disable=attribute-defined-outside-init,too-many-arguments import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. my_path = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(my_path)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(my_path), versioneer_py)) except NameError: pass return root def get_config_from_root(root): """Read the project setup.cfg file to determine Versioneer config.""" # This might raise OSError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.ConfigParser() with open(setup_cfg, "r") as cfg_file: parser.read_file(cfg_file) VCS = parser.get("versioneer", "VCS") # mandatory # Dict-like interface for non-mandatory entries section = parser["versioneer"] cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = section.get("style", "") cfg.versionfile_source = section.get("versionfile_source") cfg.versionfile_build = section.get("versionfile_build") cfg.tag_prefix = section.get("tag_prefix") if cfg.tag_prefix in ("''", '""'): cfg.tag_prefix = "" cfg.parentdir_prefix = section.get("parentdir_prefix") cfg.verbose = section.get("verbose") return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" # these dictionaries contain VCS-specific tools LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" HANDLERS.setdefault(vcs, {})[method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen([command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, process.returncode return stdout, process.returncode LONG_VERSION_PY['git'] = r''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.21 (https://github.com/python-versioneer/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys from typing import Callable, Dict def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen([command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, process.returncode return stdout, process.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r'\d', r): continue if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] TAG_PREFIX_REGEX = "*" if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] TAG_PREFIX_REGEX = r"\*" _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%%s%%s" %% (tag_prefix, TAG_PREFIX_REGEX)], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces): """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%%d.dev%%d" %% (post_version+1, pieces["distance"]) else: rendered += ".post0.dev%%d" %% (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_post_branch(pieces): """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r'\d', r): continue if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] TAG_PREFIX_REGEX = "*" if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] TAG_PREFIX_REGEX = r"\*" _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s%s" % (tag_prefix, TAG_PREFIX_REGEX)], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: my_path = __file__ if my_path.endswith(".pyc") or my_path.endswith(".pyo"): my_path = os.path.splitext(my_path)[0] + ".py" versioneer_file = os.path.relpath(my_path) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: with open(".gitattributes", "r") as fobj: for line in fobj: if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True break except OSError: pass if not present: with open(".gitattributes", "a+") as fobj: fobj.write(f"{versionfile_source} export-subst\n") files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.21) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename): """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() except OSError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces): """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%d.dev%d" % (post_version+1, pieces["distance"]) else: rendered += ".post0.dev%d" % (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_post_branch(pieces): """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} def get_version(): """Get the short version string for this project.""" return get_versions()["version"] def get_cmdclass(cmdclass=None): """Get the custom setuptools/distutils subclasses used by Versioneer. If the package uses a different cmdclass (e.g. one from numpy), it should be provide as an argument. """ if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/python-versioneer/python-versioneer/issues/52 cmds = {} if cmdclass is None else cmdclass.copy() # we add "version" to both distutils and setuptools from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if 'build_py' in cmds: _build_py = cmds['build_py'] elif "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if 'build_ext' in cmds: _build_ext = cmds['build_ext'] elif "setuptools" in sys.modules: from setuptools.command.build_ext import build_ext as _build_ext else: from distutils.command.build_ext import build_ext as _build_ext class cmd_build_ext(_build_ext): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_ext.run(self) if self.inplace: # build_ext --inplace will only build extensions in # build/lib<..> dir with no _version.py to write to. # As in place builds will already have a _version.py # in the module dir, we do not need to write one. return # now locate _version.py in the new build/ directory and replace # it with an updated value target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_ext"] = cmd_build_ext if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? from py2exe.distutils_buildexe import py2exe as _py2exe class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if 'sdist' in cmds: _sdist = cmds['sdist'] elif "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ OLD_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ INIT_PY_SNIPPET = """ from . import {0} __version__ = {0}.get_versions()['version'] """ def do_setup(): """Do main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (OSError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except OSError: old = "" module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] snippet = INIT_PY_SNIPPET.format(module) if OLD_SNIPPET in old: print(" replacing boilerplate in %s" % ipy) with open(ipy, "w") as f: f.write(old.replace(OLD_SNIPPET, snippet)) elif snippet not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(snippet) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except OSError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0 def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass()" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": errors = do_setup() errors += scan_setup_py() if errors: sys.exit(1)
0
rapidsai_public_repos
rapidsai_public_repos/ptxcompiler/MANIFEST.in
include versioneer.py include ptxcompiler/_version.py
0
rapidsai_public_repos
rapidsai_public_repos/ptxcompiler/setup.py
# Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import os.path import shutil import versioneer from distutils.sysconfig import get_config_var, get_python_inc from setuptools import setup, Extension include_dirs=[os.path.dirname(get_python_inc())] library_dirs=[get_config_var("LIBDIR")] # Find and add CUDA include paths CUDA_HOME = os.environ.get("CUDA_HOME", False) if not CUDA_HOME: path_to_cuda_gdb = shutil.which("cuda-gdb") if path_to_cuda_gdb is None: raise OSError( "Could not locate CUDA. " "Please set the environment variable " "CUDA_HOME to the path to the CUDA installation " "and try again." ) CUDA_HOME = os.path.dirname(os.path.dirname(path_to_cuda_gdb)) if not os.path.isdir(CUDA_HOME): raise OSError(f"Invalid CUDA_HOME: directory does not exist: {CUDA_HOME}") include_dirs.append(os.path.join(CUDA_HOME, "include")) library_dirs.append(os.path.join(CUDA_HOME, "lib64")) module = Extension( 'ptxcompiler._ptxcompilerlib', sources=['ptxcompiler/_ptxcompilerlib.cpp'], include_dirs=include_dirs, libraries=['nvptxcompiler_static'], library_dirs=library_dirs, extra_compile_args=['-Wall', '-Werror', '-std=c++11'], ) if "RAPIDS_PY_WHEEL_VERSIONEER_OVERRIDE" in os.environ: orig_get_versions = versioneer.get_versions version_override = os.environ["RAPIDS_PY_WHEEL_VERSIONEER_OVERRIDE"] if version_override == "": raise RuntimeError( "RAPIDS_PY_WHEEL_VERSIONEER_OVERRIDE in environment but empty" ) def get_versions(): data = orig_get_versions() data["version"] = version_override return data versioneer.get_versions = get_versions setup( name=f"ptxcompiler{os.getenv('RAPIDS_PY_WHEEL_CUDA_SUFFIX', default='')}", version=versioneer.get_version(), license="Apache 2.0", cmdclass=versioneer.get_cmdclass(), description='NVIDIA PTX Compiler binding', ext_modules=[module], packages=['ptxcompiler', 'ptxcompiler.tests'], extras_require={"test": ["pytest", "numba"]}, )
0
rapidsai_public_repos
rapidsai_public_repos/ptxcompiler/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 NVIDIA Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
rapidsai_public_repos/ptxcompiler
rapidsai_public_repos/ptxcompiler/ptxcompiler/patch.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import math import os import subprocess import sys import warnings from ptxcompiler.api import compile_ptx _numba_version_ok = False _numba_error = None min_numba_ver = (0, 54) max_numba_ver = (0, 56) NO_DRIVER = (math.inf, math.inf) mvc_docs_url = ("https://numba.readthedocs.io/en/stable/cuda/" "minor_version_compatibility.html") try: import numba ver = numba.version_info.short if ver < min_numba_ver: _numba_error = ( f"version {numba.__version__} is insufficient for " "ptxcompiler patching - at least " "%s.%s is needed." % min_numba_ver ) elif ver > max_numba_ver: _numba_error = ( f"version {numba.__version__} should not be patched. " "Set the environment variable " "NUMBA_CUDA_ENABLE_MINOR_VERSION_COMPATIBILITY=1 instead. " f"See {mvc_docs_url} for more details.") else: _numba_version_ok = True except ImportError as ie: _numba_error = f"failed to import Numba: {ie}." if _numba_version_ok: from numba.cuda import codegen from numba.cuda.codegen import CUDACodeLibrary from numba.cuda.cudadrv import devices else: # Prevent the definition of PTXStaticCompileCodeLibrary failing if we have # no Numba CUDACodeLibrary - it won't be used anyway CUDACodeLibrary = object _logger = None # Create a logger that reports messages based on the value of Numba's config # variable NUMBA_CUDA_LOG_LEVEL, so we can trace patching when tracing other # CUDA operations. def get_logger(): global _logger if _logger: return _logger logger = logging.getLogger(__name__) # Create a default configuration if none exists already if not logger.hasHandlers(): lvl = str(numba.config.CUDA_LOG_LEVEL).upper() lvl = getattr(logging, lvl, None) if not isinstance(lvl, int): # Default to critical level lvl = logging.CRITICAL logger.setLevel(lvl) # Did user specify a level? if numba.config.CUDA_LOG_LEVEL: # Create a simple handler that prints to stderr handler = logging.StreamHandler(sys.stderr) fmt = ( "== CUDA (ptxcompiler) [%(relativeCreated)d] " "%(levelname)5s -- %(message)s" ) handler.setFormatter(logging.Formatter(fmt=fmt)) logger.addHandler(handler) else: # Otherwise, put a null handler logger.addHandler(logging.NullHandler()) _logger = logger return logger class PTXStaticCompileCodeLibrary(CUDACodeLibrary): def get_cubin(self, cc=None): if cc is None: ctx = devices.get_context() device = ctx.device cc = device.compute_capability cubin = self._cubin_cache.get(cc, None) if cubin: return cubin ptxes = self._get_ptxes(cc=cc) if len(ptxes) > 1: msg = "Cannot link multiple PTX files with forward compatibility" raise RuntimeError(msg) arch = f"sm_{cc[0]}{cc[1]}" options = [f"--gpu-name={arch}"] if self._max_registers: options.append(f"--maxrregcount={self._max_registers}") # Compile PTX to cubin ptx = ptxes[0] res = compile_ptx(ptx, options) cubin = res.compiled_program return cubin CMD = """\ from ctypes import c_int, byref from numba import cuda dv = c_int(0) cuda.cudadrv.driver.driver.cuDriverGetVersion(byref(dv)) drv_major = dv.value // 1000 drv_minor = (dv.value - (drv_major * 1000)) // 10 run_major, run_minor = cuda.runtime.get_version() print(f'{drv_major} {drv_minor} {run_major} {run_minor}') """ def patch_forced_by_user(): logger = get_logger() # The patch is needed if the user explicitly forced it with an environment # variable. apply = os.getenv("PTXCOMPILER_APPLY_NUMBA_CODEGEN_PATCH") if apply is not None: logger.debug(f"PTXCOMPILER_APPLY_NUMBA_CODEGEN_PATCH={apply}") try: apply = int(apply) except ValueError: apply = False return bool(apply) def check_disabled_in_env(): logger = get_logger() # We should avoid checking whether the patch is needed if the user # requested that we don't check (e.g. in a non-fork-safe environment) check = os.getenv("PTXCOMPILER_CHECK_NUMBA_CODEGEN_PATCH_NEEDED") if check is not None: logger.debug(f"PTXCOMPILER_CHECK_NUMBA_CODEGEN_PATCH_NEEDED={check}") try: check = int(check) except ValueError: check = False else: check = True return not check def patch_needed(): # If Numba is not present, we don't need the patch. # We also can't use it to check driver and runtime versions, so exit early. if not _numba_version_ok: return False if patch_forced_by_user(): return True if check_disabled_in_env(): return False else: # Check whether the patch is needed by comparing the driver and runtime # versions - it is needed if the runtime version exceeds the driver # version. driver_version, runtime_version = get_versions() return driver_version < runtime_version def get_versions(): logger = get_logger() cp = subprocess.run([sys.executable, "-c", CMD], capture_output=True) if cp.returncode: msg = ( f"Error getting driver and runtime versions:\n\nstdout:\n\n" f"{cp.stdout.decode()}\n\nstderr:\n\n{cp.stderr.decode()}\n\n" "Not patching Numba" ) logger.error(msg) return NO_DRIVER versions = [int(s) for s in cp.stdout.strip().split()] driver_version = tuple(versions[:2]) runtime_version = tuple(versions[2:]) logger.debug("CUDA Driver version %s.%s" % driver_version) logger.debug("CUDA Runtime version %s.%s" % runtime_version) return driver_version, runtime_version def safe_get_versions(): """ Return a 2-tuple of deduced driver and runtime versions. To ensure that this function does not initialize a CUDA context, calls to the runtime and driver are made in a subprocess. If PTXCOMPILER_CHECK_NUMBA_CODEGEN_PATCH_NEEDED is set in the environment, then this subprocess call is not launched. To specify the driver and runtime versions of the environment in this case, set PTXCOMPILER_KNOWN_DRIVER_VERSION and PTXCOMPILER_KNOWN_RUNTIME_VERSION appropriately. """ if check_disabled_in_env(): try: # allow user to specify driver/runtime versions manually, if necessary driver_version = os.environ["PTXCOMPILER_KNOWN_DRIVER_VERSION"].split(".") runtime_version = os.environ["PTXCOMPILER_KNOWN_RUNTIME_VERSION"].split(".") driver_version, runtime_version = ( tuple(map(int, driver_version)), tuple(map(int, runtime_version)) ) except (KeyError, ValueError): warnings.warn( "No way to determine driver and runtime versions for patching, " "set PTXCOMPILER_KNOWN_DRIVER_VERSION/PTXCOMPILER_KNOWN_RUNTIME_VERSION" ) return NO_DRIVER else: driver_version, runtime_version = get_versions() return driver_version, runtime_version def patch_numba_codegen_if_needed(): if not _numba_version_ok: msg = f"Cannot patch Numba: {_numba_error}" raise RuntimeError(msg) logger = get_logger() if patch_needed(): logger.debug("Patching Numba codegen for forward compatibility") codegen.JITCUDACodegen._library_class = PTXStaticCompileCodeLibrary else: logger.debug("Not patching Numba codegen")
0
rapidsai_public_repos/ptxcompiler
rapidsai_public_repos/ptxcompiler/ptxcompiler/_version.py
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.21 (https://github.com/python-versioneer/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys from typing import Callable, Dict def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "ptxcompiler-" cfg.versionfile_source = "ptxcompiler/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen([command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, process.returncode return stdout, process.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r'\d', r): continue if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] TAG_PREFIX_REGEX = "*" if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] TAG_PREFIX_REGEX = r"\*" _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s%s" % (tag_prefix, TAG_PREFIX_REGEX)], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces): """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%d.dev%d" % (post_version+1, pieces["distance"]) else: rendered += ".post0.dev%d" % (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_post_branch(pieces): """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None}
0
rapidsai_public_repos/ptxcompiler
rapidsai_public_repos/ptxcompiler/ptxcompiler/api.py
# Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ptxcompiler import _ptxcompilerlib from collections import namedtuple PTXCompilerResult = namedtuple( 'PTXCompilerResult', ('compiled_program', 'info_log') ) def compile_ptx(ptx, options): options = tuple(options) handle = _ptxcompilerlib.create(ptx) try: _ptxcompilerlib.compile(handle, options) except RuntimeError: error_log = _ptxcompilerlib.get_error_log(handle) _ptxcompilerlib.destroy(handle) raise RuntimeError(error_log) try: compiled_program = _ptxcompilerlib.get_compiled_program(handle) info_log = _ptxcompilerlib.get_info_log(handle) finally: _ptxcompilerlib.destroy(handle) return PTXCompilerResult(compiled_program=compiled_program, info_log=info_log)
0
rapidsai_public_repos/ptxcompiler
rapidsai_public_repos/ptxcompiler/ptxcompiler/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ptxcompiler.api import compile_ptx # noqa: F401 from . import _version __version__ = _version.get_versions()['version']
0
rapidsai_public_repos/ptxcompiler
rapidsai_public_repos/ptxcompiler/ptxcompiler/_ptxcompilerlib.cpp
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define PY_SSIZE_T_CLEAN #include <Python.h> #include <new> #include <nvPTXCompiler.h> #include <string.h> static const char *nvPTXGetErrorEnum(nvPTXCompileResult error) { switch (error) { case NVPTXCOMPILE_SUCCESS: return "NVPTXCOMPILE_SUCCESS"; case NVPTXCOMPILE_ERROR_INVALID_COMPILER_HANDLE: return "NVPTXCOMPILE_ERROR_INVALID_COMPILER_HANDLE"; case NVPTXCOMPILE_ERROR_INVALID_INPUT: return "NVPTXCOMPILE_ERROR_INVALID_INPUT"; case NVPTXCOMPILE_ERROR_COMPILATION_FAILURE: return "NVPTXCOMPILE_ERROR_COMPILATION_FAILURE"; case NVPTXCOMPILE_ERROR_INTERNAL: return "NVPTXCOMPILE_ERROR_INTERNAL"; case NVPTXCOMPILE_ERROR_OUT_OF_MEMORY: return "NVPTXCOMPILE_ERROR_OUT_OF_MEMORY"; case NVPTXCOMPILE_ERROR_COMPILER_INVOCATION_INCOMPLETE: return "NVPTXCOMPILE_ERROR_COMPILER_INVOCATION_INCOMPLETE"; case NVPTXCOMPILE_ERROR_UNSUPPORTED_PTX_VERSION: return "NVPTXCOMPILE_ERROR_UNSUPPORTED_PTX_VERSION"; default: return "<unknown>"; } } void set_exception(PyObject *exception_type, const char* message_format, nvPTXCompileResult error) { char exception_message[256]; sprintf(exception_message, message_format, nvPTXGetErrorEnum(error)); PyErr_SetString(exception_type, exception_message); } static PyObject *get_version(PyObject *self) { unsigned int major, minor; nvPTXCompileResult res = nvPTXCompilerGetVersion(&major, &minor); if (res != NVPTXCOMPILE_SUCCESS) { set_exception(PyExc_RuntimeError, "%s error when calling nvPTXCompilerGetVersion", res); return nullptr; } return Py_BuildValue("(II)", major, minor); } static PyObject *create(PyObject *self, PyObject *args) { PyObject *ret = nullptr; char *ptx_code; nvPTXCompilerHandle *compiler; if (!PyArg_ParseTuple(args, "s", &ptx_code)) return nullptr; try { compiler = new nvPTXCompilerHandle; } catch (const std::bad_alloc &) { PyErr_NoMemory(); return nullptr; } nvPTXCompileResult res = nvPTXCompilerCreate(compiler, strlen(ptx_code), ptx_code); if (res != NVPTXCOMPILE_SUCCESS) { set_exception(PyExc_RuntimeError, "%s error when calling nvPTXCompilerCreate", res); goto error; } if ((ret = PyLong_FromUnsignedLongLong((unsigned long long)compiler)) == nullptr) { // Attempt to destroy the compiler - since we're already in an error // condition, there's no point in checking the return code and taking any // further action based on it though. nvPTXCompilerDestroy(compiler); goto error; } return ret; error: delete compiler; return nullptr; } static PyObject *destroy(PyObject *self, PyObject *args) { nvPTXCompilerHandle *compiler; if (!PyArg_ParseTuple(args, "K", &compiler)) return nullptr; nvPTXCompileResult res = nvPTXCompilerDestroy(compiler); if (res != NVPTXCOMPILE_SUCCESS) { set_exception(PyExc_RuntimeError, "%s error when calling nvPTXCompilerDestroy", res); return nullptr; } delete compiler; Py_RETURN_NONE; } static PyObject *compile(PyObject *self, PyObject *args) { nvPTXCompilerHandle *compiler; PyObject *options; if (!PyArg_ParseTuple(args, "KO!", &compiler, &PyTuple_Type, &options)) return nullptr; Py_ssize_t n_options = PyTuple_Size(options); const char **compile_options = new char const *[n_options]; for (Py_ssize_t i = 0; i < n_options; i++) { PyObject *item = PyTuple_GetItem(options, i); compile_options[i] = PyUnicode_AsUTF8AndSize(item, nullptr); } nvPTXCompileResult res = nvPTXCompilerCompile(*compiler, n_options, compile_options); delete[] compile_options; if (res != NVPTXCOMPILE_SUCCESS) { set_exception(PyExc_RuntimeError, "%s error when calling nvPTXCompilerCompile", res); return nullptr; } Py_RETURN_NONE; } static PyObject *get_error_log(PyObject *self, PyObject *args) { nvPTXCompilerHandle *compiler; if (!PyArg_ParseTuple(args, "K", &compiler)) return nullptr; size_t error_log_size; nvPTXCompileResult res = nvPTXCompilerGetErrorLogSize(*compiler, &error_log_size); if (res != NVPTXCOMPILE_SUCCESS) { set_exception(PyExc_RuntimeError, "%s error when calling nvPTXCompilerGetErrorLogSize", res); return nullptr; } // The size returned doesn't include a trailing null byte char *error_log = new char[error_log_size + 1]; res = nvPTXCompilerGetErrorLog(*compiler, error_log); if (res != NVPTXCOMPILE_SUCCESS) { set_exception(PyExc_RuntimeError, "%s error when calling nvPTXCompilerGetErrorLog", res); return nullptr; } PyObject *py_log = PyUnicode_FromStringAndSize(error_log, error_log_size); // Once we've copied the log to a Python object we can delete it - we don't // need to check whether creation of the Unicode object succeeded, because we // delete the log either way. delete[] error_log; return py_log; } static PyObject *get_info_log(PyObject *self, PyObject *args) { nvPTXCompilerHandle *compiler; if (!PyArg_ParseTuple(args, "K", &compiler)) return nullptr; size_t info_log_size; nvPTXCompileResult res = nvPTXCompilerGetInfoLogSize(*compiler, &info_log_size); if (res != NVPTXCOMPILE_SUCCESS) { set_exception(PyExc_RuntimeError, "%s error when calling nvPTXCompilerGetInfoLogSize", res); return nullptr; } // The size returned doesn't include a trailing null byte char *info_log = new char[info_log_size + 1]; res = nvPTXCompilerGetInfoLog(*compiler, info_log); if (res != NVPTXCOMPILE_SUCCESS) { set_exception(PyExc_RuntimeError, "%s error when calling nvPTXCompilerGetInfoLog", res); return nullptr; } PyObject *py_log = PyUnicode_FromStringAndSize(info_log, info_log_size); // Once we've copied the log to a Python object we can delete it - we don't // need to check whether creation of the Unicode object succeeded, because we // delete the log either way. delete[] info_log; return py_log; } static PyObject *get_compiled_program(PyObject *self, PyObject *args) { nvPTXCompilerHandle *compiler; if (!PyArg_ParseTuple(args, "K", &compiler)) return nullptr; size_t compiled_program_size; nvPTXCompileResult res = nvPTXCompilerGetCompiledProgramSize(*compiler, &compiled_program_size); if (res != NVPTXCOMPILE_SUCCESS) { set_exception(PyExc_RuntimeError, "%s error when calling nvPTXCompilerGetCompiledProgramSize", res); return nullptr; } char *compiled_program = new char[compiled_program_size]; res = nvPTXCompilerGetCompiledProgram(*compiler, compiled_program); if (res != NVPTXCOMPILE_SUCCESS) { set_exception(PyExc_RuntimeError, "%s error when calling nvPTXCompilerGetCompiledProgram", res); return nullptr; } PyObject *py_prog = PyBytes_FromStringAndSize(compiled_program, compiled_program_size); // Once we've copied the compiled program to a Python object we can delete it // - we don't need to check whether creation of the Unicode object succeeded, // because we delete the compiled program either way. delete[] compiled_program; return py_prog; } static PyMethodDef ext_methods[] = { {"get_version", (PyCFunction)get_version, METH_NOARGS, "Returns a tuple giving the version"}, {"create", (PyCFunction)create, METH_VARARGS, "Returns a handle to a new compiler object"}, {"destroy", (PyCFunction)destroy, METH_VARARGS, "Given a handle, destroy a compiler object"}, {"compile", (PyCFunction)compile, METH_VARARGS, "Given a handle, compile the PTX"}, {"get_error_log", (PyCFunction)get_error_log, METH_VARARGS, "Given a handle, return the error log"}, {"get_info_log", (PyCFunction)get_info_log, METH_VARARGS, "Given a handle, return the info log"}, {"get_compiled_program", (PyCFunction)get_compiled_program, METH_VARARGS, "Given a handle, return the compiled program"}, {nullptr}}; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "ptxcompiler", "Provides access to PTX compiler API methods", -1, ext_methods}; PyMODINIT_FUNC PyInit__ptxcompilerlib(void) { PyObject *m = PyModule_Create(&moduledef); return m; }
0
rapidsai_public_repos/ptxcompiler/ptxcompiler
rapidsai_public_repos/ptxcompiler/ptxcompiler/tests/test_lib.py
# Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest import sys from ptxcompiler import _ptxcompilerlib PTX_CODE = """\ .version 7.4 .target sm_52 .address_size 64 // .globl _Z1kPf .visible .entry _Z1kPf( .param .u64 _Z1kPf_param_0 ) { .reg .b32 %r<2>; .reg .b64 %rd<3>; ld.param.u64 %rd1, [_Z1kPf_param_0]; cvta.to.global.u64 %rd2, %rd1; mov.u32 %r1, 1065353216; st.global.u32 [%rd2], %r1; ret; } """ OPTIONS = ('--gpu-name=sm_75',) def test_get_version(): major, minor = _ptxcompilerlib.get_version() # Any version less than 11.1 indicates an issue, since the library was # first available in 11.1 assert (major, minor) >= (11, 1) def test_create(): handle = _ptxcompilerlib.create(PTX_CODE) assert handle != 0 def test_destroy(): handle = _ptxcompilerlib.create(PTX_CODE) _ptxcompilerlib.destroy(handle) def test_compile(): # Check that compile does not error handle = _ptxcompilerlib.create(PTX_CODE) _ptxcompilerlib.compile(handle, OPTIONS) def test_compile_options(): options = ('--gpu-name=sm_75', '--device-debug') handle = _ptxcompilerlib.create(PTX_CODE) _ptxcompilerlib.compile(handle, options) compiled_program = _ptxcompilerlib.get_compiled_program(handle) assert b'nv_debug' in compiled_program def test_compile_options_bad_option(): options = ('--gpu-name=sm_75', '--bad-option') handle = _ptxcompilerlib.create(PTX_CODE) with pytest.raises(RuntimeError, match="NVPTXCOMPILE_ERROR_COMPILATION_FAILURE error"): _ptxcompilerlib.compile(handle, options) error_log = _ptxcompilerlib.get_error_log(handle) assert "Unknown option" in error_log def test_get_error_log(): bad_ptx = ".target sm_52" handle = _ptxcompilerlib.create(bad_ptx) with pytest.raises(RuntimeError): _ptxcompilerlib.compile(handle, OPTIONS) error_log = _ptxcompilerlib.get_error_log(handle) assert "Missing .version directive" in error_log def test_get_info_log(): handle = _ptxcompilerlib.create(PTX_CODE) _ptxcompilerlib.compile(handle, OPTIONS) info_log = _ptxcompilerlib.get_info_log(handle) # Info log is empty assert "" == info_log def test_get_compiled_program(): handle = _ptxcompilerlib.create(PTX_CODE) _ptxcompilerlib.compile(handle, OPTIONS) compiled_program = _ptxcompilerlib.get_compiled_program(handle) # Check the compiled program is an ELF file by looking for the ELF header assert compiled_program[:4] == b'\x7fELF' if __name__ == '__main__': sys.exit(pytest.main())
0
rapidsai_public_repos/ptxcompiler/ptxcompiler
rapidsai_public_repos/ptxcompiler/ptxcompiler/tests/test_patch.py
# Copyright (c) 2022, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest from ptxcompiler import patch from ptxcompiler.patch import (_numba_version_ok, patch_numba_codegen_if_needed, min_numba_ver, PTXStaticCompileCodeLibrary) from unittest.mock import patch as mock_patch def test_numba_patching_numba_not_ok(): with mock_patch.multiple( patch, _numba_version_ok=False, _numba_error='<error>'): with pytest.raises(RuntimeError, match='Cannot patch Numba: <error>'): patch_numba_codegen_if_needed() @pytest.mark.skipif( not _numba_version_ok, reason=f"Requires Numba >= {min_numba_ver[0]}.{min_numba_ver[1]}" ) def test_numba_patching(): # We import the codegen here rather than at the top level because the # import may fail if if Numba is not present or an unsupported version. from numba.cuda.codegen import JITCUDACodegen # Force application of the patch so we can test application regardless of # whether it is needed. os.environ['PTXCOMPILER_APPLY_NUMBA_CODEGEN_PATCH'] = '1' patch_numba_codegen_if_needed() assert JITCUDACodegen._library_class is PTXStaticCompileCodeLibrary
0
rapidsai_public_repos/ptxcompiler/ptxcompiler
rapidsai_public_repos/ptxcompiler/ptxcompiler/tests/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
0
rapidsai_public_repos/ptxcompiler/conda/recipes
rapidsai_public_repos/ptxcompiler/conda/recipes/ptxcompiler/conda_build_config.yaml
c_compiler_version: # [linux] - 9 # [linux] cxx_compiler_version: # [linux] - 9 # [linux] fortran_compiler_version: # [linux] - 9 # [linux] cuda_compiler: - nvcc
0
rapidsai_public_repos/ptxcompiler/conda/recipes
rapidsai_public_repos/ptxcompiler/conda/recipes/ptxcompiler/meta.yaml
# Copyright (c) 2021-2023, NVIDIA CORPORATION. {% set version = environ.get('GIT_DESCRIBE_TAG', '0.0.0.dev').lstrip('v') + environ.get('VERSION_SUFFIX', '') %} {% set py_version=environ.get('CONDA_PY', 38) %} {% set cuda_major_minor = ".".join(environ['CUDA_VER'].split(".")[:2]) %} {% set cuda_major = cuda_major_minor.split(".")[0] %} package: name: ptxcompiler version: {{ version }} source: git_url: ../../.. build: number: {{ GIT_DESCRIBE_NUMBER }} ignore_run_exports_from: - {{ compiler("cuda") }} string: cuda_{{ cuda_major }}_py{{ py_version }}_{{ GIT_DESCRIBE_HASH }}_{{ GIT_DESCRIBE_NUMBER }} script: {{ PYTHON }} -m pip install . -vv requirements: build: - {{ compiler("c") }} - {{ compiler("cxx") }} - {{ compiler("cuda") }} host: - python - pip - cudatoolkit {{ cuda_major_minor }} run: - python - numba >=0.54 - cudatoolkit >={{ cuda_major ~ ".0" }},<={{ cuda_major_minor }} run_constrained: - __cuda >={{ cuda_major ~ ".0" }} test: requires: - pip - pytest commands: - pip check - pytest -v --pyargs ptxcompiler about: home: https://rapids.ai/ license: Apache-2.0 license_family: Apache license_file: LICENSE summary: PTX Static compiler and Numba patch
0
rapidsai_public_repos
rapidsai_public_repos/jenkins-shared-library/README.md
# jenkins-shared-library
0
rapidsai_public_repos/jenkins-shared-library
rapidsai_public_repos/jenkins-shared-library/vars/generateStage.groovy
import groovy.transform.Field @Field final PR_TEST_STAGE = "pr_test" @Field final NIGHTLY_TEST_STAGE = "nightly_test" @Field final CUDA_BUILD_STAGE = "cuda_build" @Field final PYTHON_BUILD_STAGE = "python_build" def call(stage, Closure steps) { parallels_config = [ pr_test: [ [label: "driver-495-arm", cuda_ver: "11.5", py_ver: "3.9", os: "ubuntu20.04", arch: "arm64"], [label: "driver-450", cuda_ver: "11.0", py_ver: "3.8", os: "centos7", arch: "amd64"], [label: "driver-495", cuda_ver: "11.2", py_ver: "3.9", os: "ubuntu18.04", arch: "amd64"], [label: "driver-495", cuda_ver: "11.5", py_ver: "3.9", os: "ubuntu20.04", arch: "amd64"], ], nightly_test: [ [label: "driver-495-arm", cuda_ver: "11.5", py_ver: "3.9", os: "ubuntu20.04", arch: "arm64"], [label: "driver-450", cuda_ver: "11.0", py_ver: "3.8", os: "centos7", arch: "amd64"], [label: "driver-495", cuda_ver: "11.2", py_ver: "3.9", os: "ubuntu18.04", arch: "amd64"], [label: "driver-495", cuda_ver: "11.5", py_ver: "3.9", os: "ubuntu20.04", arch: "amd64"], // [label: "wsl2", cuda_ver: "11.5", py_ver: "3.9", os: "ubuntu20.04", arch: "amd64"], ], cuda_build: [ [arch: "arm64", label: "cpu4-arm64", os: "ubuntu18.04", cuda_ver: "11.5"], [arch: "amd64", label: "cpu4-amd64", os: "centos7", cuda_ver: "11.5"] ], python_build: [ [arch: "arm64", py_ver: "3.8", label: "cpu-arm64", cuda_ver: "11.5", os: "ubuntu18.04"], [arch: "arm64", py_ver: "3.9", label: "cpu-arm64", cuda_ver: "11.5", os: "ubuntu18.04"], [arch: "amd64", py_ver: "3.8", label: "cpu", cuda_ver: "11.5", os: "centos7"], [arch: "amd64", py_ver: "3.9", label: "cpu", cuda_ver: "11.5", os: "centos7"], ] ] return generateStage(stage, parallels_config, steps) } def generateTestStage(test_config, steps) { return { stage("Test - ${test_config.label} - ${test_config.cuda_ver} - ${test_config.py_ver} - ${test_config.os}") { node(test_config.label) { docker .image(getStageImg(test_config, false)) .inside(""" --runtime=nvidia --pull=always -e NVIDIA_VISIBLE_DEVICES=$EXECUTOR_NUMBER -e ARCH=${test_config.arch} -e CUDA=${test_config.cuda_ver} -e PY_VER=${test_config.py_ver} -e HOME=$WORKSPACE """) { cleanWs ( deleteDirs: true, externalDelete: 'sudo rm -rf %s' ) checkout scm runStepsWithNotify(steps, test_config, PR_TEST_STAGE) } } } } } def generateNightlyTestStage(test_config, steps) { return { stage("Nightly Test - ${test_config.label} - ${test_config.cuda_ver} - ${test_config.py_ver} - ${test_config.os}") { node(test_config.label) { docker .image(getStageImg(test_config, false)) .inside(""" --runtime=nvidia --pull=always -e NVIDIA_VISIBLE_DEVICES=$EXECUTOR_NUMBER -e ARCH=${test_config.arch} -e CUDA=${test_config.cuda_ver} -e PY_VER=${test_config.py_ver} -e HOME=$WORKSPACE """) { cleanWs ( deleteDirs: true, externalDelete: 'sudo rm -rf %s' ) checkout scm runStepsWithNotify(steps, test_config, NIGHTLY_TEST_STAGE) } } } } } def generateCudaBuildStage(test_config, steps) { return { stage("C++ build - ${test_config.label}") { node(test_config.label) { docker .image(getStageImg(test_config, true)) .inside(""" --pull=always -e ARCH=${test_config.arch} -e CUDA=${test_config.cuda_ver} -e HOME=$WORKSPACE """) { cleanWs ( deleteDirs: true, externalDelete: 'sudo rm -rf %s' ) checkout scm runStepsWithNotify(steps, test_config, CUDA_BUILD_STAGE) } } } } } def generatePythonBuildStage(test_config, steps) { return { stage("Python build - ${test_config.label}") { node(test_config.label) { docker .image(getStageImg(test_config, true)) .inside(""" --pull=always -e ARCH=${test_config.arch} -e PY_VER=${test_config.py_ver} -e CUDA=${test_config.cuda_ver} -e HOME=$WORKSPACE """) { cleanWs ( deleteDirs: true, externalDelete: 'sudo rm -rf %s' ) checkout scm runStepsWithNotify(steps, test_config, PYTHON_BUILD_STAGE) } } } } } def generateStage(stage, parallels_config, steps) { switch(stage) { case PR_TEST_STAGE: def stages = parallels_config[stage].collectEntries { ["${it.arch}: ${it.label} - ${it.cuda_ver} - ${it.py_ver} - ${it.os}" : generateTestStage(it, steps)] } stages.failFast = true return stages case NIGHTLY_TEST_STAGE: def stages = parallels_config[stage].collectEntries { ["${it.arch}: ${it.label} - ${it.cuda_ver} - ${it.py_ver} - ${it.os}" : generateNightlyTestStage(it, steps)] } stages.failFast = true return stages case CUDA_BUILD_STAGE: def stages = parallels_config[stage].collectEntries { ["${it.arch}: ${it.label} - ${it.os} - ${it.cuda_ver}" : generateCudaBuildStage(it, steps)] } stages.failFast = true return stages case PYTHON_BUILD_STAGE: def stages = parallels_config[stage].collectEntries { ["${it.arch}: ${it.label} - ${it.py_ver} - ${it.os} - ${it.cuda_ver}" : generatePythonBuildStage(it, steps)] } stages.failFast = true return stages default: throw new Exception("Invalid stage name provided") } } def getStageImg(config, is_build_stage) { String img = "rapidsai" String os = config.os String cuda_ver = config.cuda_ver String py_ver = config.getOrDefault("py_ver", "3.9") // CUDA builds don't require specific Python version, so default to an arbitrary version if (is_build_stage) { img += "-driver" } if (config.arch == "arm64") { img += "-arm64" } return "gpuci/${img}:22.08-cuda${cuda_ver}-devel-${os}-py${py_ver}" } def runStepsWithNotify(Closure steps, test_config, String stage) { String ctx = generateContext(stage, test_config) try { githubNotify description: "Build ${BUILD_NUMBER} is now pending", status: 'PENDING', context: ctx, targetUrl: env.RUN_DISPLAY_URL withCredentials([[ $class: 'AmazonWebServicesCredentialsBinding', credentialsId: "aws-s3-gpuci", accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY' ]]) { steps() } githubNotify description: "Build ${BUILD_NUMBER} succeeded", status: 'SUCCESS', context: ctx, targetUrl: env.RUN_DISPLAY_URL } catch (e) { githubNotify description: "Build ${BUILD_NUMBER} failed", status: 'FAILURE', context: ctx, targetUrl: env.RUN_DISPLAY_URL error e } } def generateContext(String stage, test_config) { switch(stage) { case PR_TEST_STAGE: return "test/cuda/${test_config.arch}/${test_config.cuda_ver}/${test_config.label}/python/${test_config.py_ver}/${test_config.os}" case NIGHTLY_TEST_STAGE: return "test/cuda/${test_config.arch}/${test_config.cuda_ver}/${test_config.label}/python/${test_config.py_ver}/${test_config.os}" case CUDA_BUILD_STAGE: return "build/cuda/${test_config.arch}/${test_config.cuda_ver}" case PYTHON_BUILD_STAGE: return "build/python/${test_config.py_ver}/${test_config.cuda_ver}/cuda/${test_config.arch}/${test_config.cuda_ver}" default: throw new Exception("Invalid stage name provided") } }
0
rapidsai_public_repos
rapidsai_public_repos/cudf/.pre-commit-config.yaml
# Copyright (c) 2019-2022, NVIDIA CORPORATION. repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: trailing-whitespace exclude: | (?x)^( ^python/cudf/cudf/tests/data/subword_tokenizer_data/.* ) - id: end-of-file-fixer exclude: | (?x)^( ^python/cudf/cudf/tests/data/subword_tokenizer_data/.* ) - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort # Use the config file specific to each subproject so that each # project can specify its own first/third-party packages. args: ["--config-root=python/", "--resolve-all-configs"] files: python/.* types_or: [python, cython, pyi] - repo: https://github.com/psf/black rev: 22.3.0 hooks: - id: black files: python/.* # Explicitly specify the pyproject.toml at the repo root, not per-project. args: ["--config", "pyproject.toml"] - repo: https://github.com/MarcoGorelli/cython-lint rev: v0.15.0 hooks: - id: cython-lint - repo: https://github.com/pre-commit/mirrors-mypy rev: 'v1.3.0' hooks: - id: mypy additional_dependencies: [types-cachetools] args: ["--config-file=pyproject.toml", "python/cudf/cudf", "python/custreamz/custreamz", "python/cudf_kafka/cudf_kafka", "python/dask_cudf/dask_cudf"] pass_filenames: false - repo: https://github.com/PyCQA/pydocstyle rev: 6.1.1 hooks: - id: pydocstyle # https://github.com/PyCQA/pydocstyle/issues/603 additional_dependencies: [toml] args: ["--config=pyproject.toml"] exclude: | (?x)^( ^python/cudf/cudf/pandas/scripts/.*| ^python/cudf/cudf_pandas_tests/.* ) - repo: https://github.com/nbQA-dev/nbQA rev: 1.6.3 hooks: - id: nbqa-isort # Use the cudf_kafka isort orderings in notebooks so that dask # and RAPIDS packages have their own sections. args: ["--settings-file=python/cudf_kafka/pyproject.toml"] - id: nbqa-black # Explicitly specify the pyproject.toml at the repo root, not per-project. args: ["--config=pyproject.toml"] - repo: https://github.com/pre-commit/mirrors-clang-format rev: v16.0.6 hooks: - id: clang-format types_or: [c, c++, cuda] args: ["-fallback-style=none", "-style=file", "-i"] - repo: https://github.com/sirosen/texthooks rev: 0.4.0 hooks: - id: fix-smartquotes exclude: | (?x)^( ^cpp/include/cudf_test/cxxopts.hpp| ^python/cudf/cudf/tests/data/subword_tokenizer_data/.*| ^python/cudf/cudf/tests/text/test_text_methods.py ) - repo: local hooks: - id: no-deprecationwarning name: no-deprecationwarning description: 'Enforce that DeprecationWarning is not introduced (use FutureWarning instead)' entry: '(category=|\s)DeprecationWarning[,)]' language: pygrep types_or: [python, cython] - id: no-programmatic-xfail name: no-programmatic-xfail description: 'Enforce that pytest.xfail is not introduced (see dev docs for details)' entry: 'pytest\.xfail' language: pygrep types: [python] - id: cmake-format name: cmake-format entry: ./cpp/scripts/run-cmake-format.sh cmake-format language: python types: [cmake] # Note that pre-commit autoupdate does not update the versions # of dependencies, so we'll have to update this manually. additional_dependencies: - cmakelang==0.6.13 verbose: true require_serial: true - id: cmake-lint name: cmake-lint entry: ./cpp/scripts/run-cmake-format.sh cmake-lint language: python types: [cmake] # Note that pre-commit autoupdate does not update the versions # of dependencies, so we'll have to update this manually. additional_dependencies: - cmakelang==0.6.13 verbose: true require_serial: true - id: copyright-check name: copyright-check entry: python ./ci/checks/copyright.py --git-modified-only --update-current-year language: python pass_filenames: false additional_dependencies: [gitpython] - id: doxygen-check name: doxygen-check entry: ./ci/checks/doxygen.sh files: ^cpp/include/ types_or: [file] language: system pass_filenames: false verbose: true - repo: https://github.com/codespell-project/codespell rev: v2.2.2 hooks: - id: codespell additional_dependencies: [tomli] args: ["--toml", "pyproject.toml"] exclude: | (?x)^( .*test.*| ^CHANGELOG.md$ ) - repo: https://github.com/rapidsai/dependency-file-generator rev: v1.7.1 hooks: - id: rapids-dependency-file-generator args: ["--clean"] - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.0.278 hooks: - id: ruff files: python/.*$ default_language_version: python: python3
0
rapidsai_public_repos
rapidsai_public_repos/cudf/pyproject.toml
[tool.black] line-length = 79 target-version = ["py39"] include = '\.py?$' force-exclude = ''' /( thirdparty | \.eggs | \.git | \.hg | \.mypy_cache | \.tox | \.venv | _build | buck-out | build | dist )/ ''' [tool.pydocstyle] # Due to https://github.com/PyCQA/pydocstyle/issues/363, we must exclude rather # than include using match-dir. Note that as discussed in # https://stackoverflow.com/questions/65478393/how-to-filter-directories-using-the-match-dir-flag-for-pydocstyle, # unlike the match option above this match-dir will have no effect when # pydocstyle is invoked from pre-commit. Therefore this exclusion list must # also be maintained in the pre-commit config file. match-dir = "^(?!(ci|cpp|conda|docs|java|notebooks|python/cudf/cudf/pandas/scripts|python/cudf/cudf_pandas_tests)).*$" # Allow missing docstrings for docutils ignore-decorators = ".*(docutils|doc_apply|copy_docstring).*" select = "D201, D204, D206, D207, D208, D209, D210, D211, D214, D215, D300, D301, D302, D403, D405, D406, D407, D408, D409, D410, D411, D412, D414, D418" # Would like to enable the following rules in the future: # D200, D202, D205, D400 [tool.mypy] ignore_missing_imports = true # If we don't specify this, then mypy will check excluded files if # they are imported by a checked file. follow_imports = "skip" exclude = [ "cudf/_lib/", "cudf/cudf/benchmarks/", "cudf/cudf/tests/", "cudf/cudf/utils/metadata/orc_column_statistics_pb2.py", "custreamz/custreamz/tests/", "dask_cudf/dask_cudf/tests/", ] [tool.codespell] # note: pre-commit passes explicit lists of files here, which this skip file list doesn't override - # this is only to allow you to run codespell interactively skip = "./.git,./.github,./cpp/build,.*egg-info.*,./.mypy_cache,./cpp/tests,./python/cudf/cudf/tests,./java/src/test,./cpp/include/cudf_test/cxxopts.hpp" # ignore short words, and typename parameters like OffsetT ignore-regex = "\\b(.{1,4}|[A-Z]\\w*T)\\b" ignore-words-list = "inout,unparseable,falsy" builtin = "clear" quiet-level = 3 [tool.ruff] select = ["E", "F", "W"] ignore = [ # whitespace before : "E203", ] fixable = ["ALL"] exclude = [ # TODO: Remove this in a follow-up where we fix __all__. "__init__.py", ] line-length = 79 [tool.ruff.per-file-ignores] # Lots of pytest implicitly injected attributes in conftest-patch.py "python/cudf/cudf/pandas/scripts/conftest-patch.py" = ["F821"]
0
rapidsai_public_repos
rapidsai_public_repos/cudf/fetch_rapids.cmake
# ============================================================================= # Copyright (c) 2018-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. # ============================================================================= if(NOT EXISTS ${CMAKE_CURRENT_BINARY_DIR}/CUDF_RAPIDS.cmake) file(DOWNLOAD https://raw.githubusercontent.com/rapidsai/rapids-cmake/branch-24.02/RAPIDS.cmake ${CMAKE_CURRENT_BINARY_DIR}/CUDF_RAPIDS.cmake ) endif() include(${CMAKE_CURRENT_BINARY_DIR}/CUDF_RAPIDS.cmake)
0