Skip to content

Commit

Permalink
use dpctl.tensor.round functions in dpnp
Browse files Browse the repository at this point in the history
  • Loading branch information
vtavana committed Aug 22, 2023
1 parent 79ac2b0 commit eeae83a
Show file tree
Hide file tree
Showing 15 changed files with 241 additions and 190 deletions.
78 changes: 78 additions & 0 deletions dpnp/backend/extensions/vm/round.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
//*****************************************************************************
// Copyright (c) 2023, Intel 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 HOLDER 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.
//*****************************************************************************

#pragma once

#include <CL/sycl.hpp>

#include "common.hpp"
#include "types_matrix.hpp"

namespace dpnp
{
namespace backend
{
namespace ext
{
namespace vm
{
template <typename T>
sycl::event round_contig_impl(sycl::queue exec_q,
const std::int64_t n,
const char *in_a,
char *out_y,
const std::vector<sycl::event> &depends)
{
type_utils::validate_type_for_device<T>(exec_q);

const T *a = reinterpret_cast<const T *>(in_a);
T *y = reinterpret_cast<T *>(out_y);

return mkl_vm::rint(exec_q,
n, // number of elements to be calculated
a, // pointer `a` containing input vector of size n
y, // pointer `y` to the output vector of size n
depends);
}

template <typename fnT, typename T>
struct RoundContigFactory
{
fnT get()
{
if constexpr (std::is_same_v<
typename types::RoundOutputType<T>::value_type, void>)
{
return nullptr;
}
else {
return round_contig_impl<T>;
}
}
};
} // namespace vm
} // namespace ext
} // namespace backend
} // namespace dpnp
15 changes: 15 additions & 0 deletions dpnp/backend/extensions/vm/types_matrix.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,21 @@ struct MulOutputType
dpctl_td_ns::DefaultResultEntry<void>>::result_type;
};

/**
* @brief A factory to define pairs of supported types for which
* MKL VM library provides support in oneapi::mkl::vm::rint<T> function.
*
* @tparam T Type of input vector `a` and of result vector `y`.
*/
template <typename T>
struct RoundOutputType
{
using value_type = typename std::disjunction<
dpctl_td_ns::TypeMapResultEntry<T, double, double>,
dpctl_td_ns::TypeMapResultEntry<T, float, float>,
dpctl_td_ns::DefaultResultEntry<void>>::result_type;
};

/**
* @brief A factory to define pairs of supported types for which
* MKL VM library provides support in oneapi::mkl::vm::sin<T> function.
Expand Down
30 changes: 30 additions & 0 deletions dpnp/backend/extensions/vm/vm_py.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
#include "floor.hpp"
#include "ln.hpp"
#include "mul.hpp"
#include "round.hpp"
#include "sin.hpp"
#include "sqr.hpp"
#include "sqrt.hpp"
Expand All @@ -60,6 +61,7 @@ static unary_impl_fn_ptr_t floor_dispatch_vector[dpctl_td_ns::num_types];
static unary_impl_fn_ptr_t conj_dispatch_vector[dpctl_td_ns::num_types];
static unary_impl_fn_ptr_t ln_dispatch_vector[dpctl_td_ns::num_types];
static binary_impl_fn_ptr_t mul_dispatch_vector[dpctl_td_ns::num_types];
static unary_impl_fn_ptr_t round_dispatch_vector[dpctl_td_ns::num_types];
static unary_impl_fn_ptr_t sin_dispatch_vector[dpctl_td_ns::num_types];
static unary_impl_fn_ptr_t sqr_dispatch_vector[dpctl_td_ns::num_types];
static unary_impl_fn_ptr_t sqrt_dispatch_vector[dpctl_td_ns::num_types];
Expand Down Expand Up @@ -301,6 +303,34 @@ PYBIND11_MODULE(_vm_impl, m)
py::arg("dst"));
}

// UnaryUfunc: ==== Round(x) ====
{
vm_ext::init_ufunc_dispatch_vector<unary_impl_fn_ptr_t,
vm_ext::RoundContigFactory>(
round_dispatch_vector);

auto round_pyapi = [&](sycl::queue exec_q, arrayT src, arrayT dst,
const event_vecT &depends = {}) {
return vm_ext::unary_ufunc(exec_q, src, dst, depends,
round_dispatch_vector);
};
m.def("_round", round_pyapi,
"Call `rint` function from OneMKL VM library to compute "
"the rounded value of vector elements",
py::arg("sycl_queue"), py::arg("src"), py::arg("dst"),
py::arg("depends") = py::list());

auto round_need_to_call_pyapi = [&](sycl::queue exec_q, arrayT src,
arrayT dst) {
return vm_ext::need_to_call_unary_ufunc(exec_q, src, dst,
round_dispatch_vector);
};
m.def("_mkl_round_to_call", round_need_to_call_pyapi,
"Check input arguments to answer if `rint` function from "
"OneMKL VM library can be used",
py::arg("sycl_queue"), py::arg("src"), py::arg("dst"));
}

// UnaryUfunc: ==== Sin(x) ====
{
vm_ext::init_ufunc_dispatch_vector<unary_impl_fn_ptr_t,
Expand Down
2 changes: 0 additions & 2 deletions dpnp/backend/include/dpnp_iface_fptr.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,6 @@ enum class DPNPFuncName : size_t
DPNP_FN_ARGSORT_EXT, /**< Used in numpy.argsort() impl, requires extra
parameters */
DPNP_FN_AROUND, /**< Used in numpy.around() impl */
DPNP_FN_AROUND_EXT, /**< Used in numpy.around() impl, requires extra
parameters */
DPNP_FN_ASTYPE, /**< Used in numpy.astype() impl */
DPNP_FN_ASTYPE_EXT, /**< Used in numpy.astype() impl, requires extra
parameters */
Expand Down
18 changes: 0 additions & 18 deletions dpnp/backend/kernels/dpnp_krnl_mathematical.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,15 +109,6 @@ template <typename _DataType>
void (*dpnp_around_default_c)(const void *, void *, const size_t, const int) =
dpnp_around_c<_DataType>;

template <typename _DataType>
DPCTLSyclEventRef (*dpnp_around_ext_c)(DPCTLSyclQueueRef,
const void *,
void *,
const size_t,
const int,
const DPCTLEventVectorRef) =
dpnp_around_c<_DataType>;

template <typename _KernelNameSpecialization1,
typename _KernelNameSpecialization2>
class dpnp_elemwise_absolute_c_kernel;
Expand Down Expand Up @@ -1184,15 +1175,6 @@ void func_map_init_mathematical(func_map_t &fmap)
fmap[DPNPFuncName::DPNP_FN_AROUND][eft_DBL][eft_DBL] = {
eft_DBL, (void *)dpnp_around_default_c<double>};

fmap[DPNPFuncName::DPNP_FN_AROUND_EXT][eft_INT][eft_INT] = {
eft_INT, (void *)dpnp_around_ext_c<int32_t>};
fmap[DPNPFuncName::DPNP_FN_AROUND_EXT][eft_LNG][eft_LNG] = {
eft_LNG, (void *)dpnp_around_ext_c<int64_t>};
fmap[DPNPFuncName::DPNP_FN_AROUND_EXT][eft_FLT][eft_FLT] = {
eft_FLT, (void *)dpnp_around_ext_c<float>};
fmap[DPNPFuncName::DPNP_FN_AROUND_EXT][eft_DBL][eft_DBL] = {
eft_DBL, (void *)dpnp_around_ext_c<double>};

fmap[DPNPFuncName::DPNP_FN_CROSS][eft_INT][eft_INT] = {
eft_INT, (void *)dpnp_cross_default_c<int32_t, int32_t, int32_t>};
fmap[DPNPFuncName::DPNP_FN_CROSS][eft_INT][eft_LNG] = {
Expand Down
2 changes: 0 additions & 2 deletions dpnp/dpnp_algo/dpnp_algo.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,6 @@ cdef extern from "dpnp_iface_fptr.hpp" namespace "DPNPFuncName": # need this na
DPNP_FN_ARGMIN_EXT
DPNP_FN_ARGSORT
DPNP_FN_ARGSORT_EXT
DPNP_FN_AROUND
DPNP_FN_AROUND_EXT
DPNP_FN_ASTYPE
DPNP_FN_ASTYPE_EXT
DPNP_FN_CBRT
Expand Down
2 changes: 1 addition & 1 deletion dpnp/dpnp_algo/dpnp_algo.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ cpdef utils.dpnp_descriptor dpnp_flatten(utils.dpnp_descriptor x1):

cpdef utils.dpnp_descriptor dpnp_init_val(shape, dtype, value):
"""
same as dpnp_full(). TODO remove code dumplication
same as dpnp_full(). TODO remove code duplication
"""
cdef DPNPFuncType param1_type = dpnp_dtype_to_DPNPFuncType(dtype)

Expand Down
36 changes: 0 additions & 36 deletions dpnp/dpnp_algo/dpnp_algo_mathematical.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ and the rest of the library
__all__ += [
"dpnp_absolute",
"dpnp_arctan2",
"dpnp_around",
"dpnp_copysign",
"dpnp_cross",
"dpnp_cumprod",
Expand Down Expand Up @@ -72,9 +71,6 @@ ctypedef c_dpctl.DPCTLSyclEventRef(*fptr_1in_2out_t)(c_dpctl.DPCTLSyclQueueRef,
ctypedef c_dpctl.DPCTLSyclEventRef(*ftpr_custom_trapz_2in_1out_with_2size_t)(c_dpctl.DPCTLSyclQueueRef,
void *, void * , void * , double, size_t, size_t,
const c_dpctl.DPCTLEventVectorRef)
ctypedef c_dpctl.DPCTLSyclEventRef(*ftpr_custom_around_1in_1out_t)(c_dpctl.DPCTLSyclQueueRef,
const void * , void * , const size_t, const int,
const c_dpctl.DPCTLEventVectorRef)


cpdef utils.dpnp_descriptor dpnp_absolute(utils.dpnp_descriptor x1):
Expand Down Expand Up @@ -120,38 +116,6 @@ cpdef utils.dpnp_descriptor dpnp_arctan2(utils.dpnp_descriptor x1_obj,
return call_fptr_2in_1out_strides(DPNP_FN_ARCTAN2_EXT, x1_obj, x2_obj, dtype, out, where, func_name="arctan2")


cpdef utils.dpnp_descriptor dpnp_around(utils.dpnp_descriptor x1, int decimals):

cdef DPNPFuncType param1_type = dpnp_dtype_to_DPNPFuncType(x1.dtype)

cdef DPNPFuncData kernel_data = get_dpnp_function_ptr(DPNP_FN_AROUND_EXT, param1_type, param1_type)

x1_obj = x1.get_array()

# ceate result array with type given by FPTR data
cdef shape_type_c result_shape = x1.shape
cdef utils.dpnp_descriptor result = utils.create_output_descriptor(result_shape,
kernel_data.return_type,
None,
device=x1_obj.sycl_device,
usm_type=x1_obj.usm_type,
sycl_queue=x1_obj.sycl_queue)

result_sycl_queue = result.get_array().sycl_queue

cdef c_dpctl.SyclQueue q = <c_dpctl.SyclQueue> result_sycl_queue
cdef c_dpctl.DPCTLSyclQueueRef q_ref = q.get_queue_ref()

cdef ftpr_custom_around_1in_1out_t func = <ftpr_custom_around_1in_1out_t > kernel_data.ptr

cdef c_dpctl.DPCTLSyclEventRef event_ref = func(q_ref, x1.get_data(), result.get_data(), x1.size, decimals, NULL)

with nogil: c_dpctl.DPCTLEvent_WaitAndThrow(event_ref)
c_dpctl.DPCTLEvent_Delete(event_ref)

return result


cpdef utils.dpnp_descriptor dpnp_copysign(utils.dpnp_descriptor x1_obj,
utils.dpnp_descriptor x2_obj,
object dtype=None,
Expand Down
52 changes: 52 additions & 0 deletions dpnp/dpnp_algo/dpnp_elementwise_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
"dpnp_not_equal",
"dpnp_remainder",
"dpnp_right_shift",
"dpnp_round",
"dpnp_sin",
"dpnp_sqrt",
"dpnp_square",
Expand Down Expand Up @@ -1568,6 +1569,57 @@ def dpnp_right_shift(x1, x2, out=None, order="K"):
return dpnp_array._create_from_usm_ndarray(res_usm)


_round_docstring = """
round(x, out=None, order='K')
Rounds each element `x_i` of the input array `x` to
the nearest integer-valued number.
Args:
x (dpnp.ndarray):
Input array, expected to have numeric data type.
out ({None, dpnp.ndarray}, optional):
Output array to populate. Array must have the correct
shape and the expected data type.
order ("C","F","A","K", optional): memory layout of the new
output array, if parameter `out` is `None`.
Default: "K".
Return:
dpnp.ndarray:
An array containing the element-wise rounded value. The data type
of the returned array is determined by the Type Promotion Rules.
"""


def _call_round(src, dst, sycl_queue, depends=None):
"""A callback to register in UnaryElementwiseFunc class of dpctl.tensor"""

if depends is None:
depends = []

if vmi._mkl_round_to_call(sycl_queue, src, dst):
# call pybind11 extension for round() function from OneMKL VM
return vmi._round(sycl_queue, src, dst, depends)
return ti._round(src, dst, sycl_queue, depends)


round_func = UnaryElementwiseFunc(
"round", ti._round_result_type, _call_round, _round_docstring
)


def dpnp_round(x, out=None, order="K"):
"""
Invokes round() function from pybind11 extension of OneMKL VM if possible.
Otherwise fully relies on dpctl.tensor implementation for round() function.
"""
# dpctl.tensor only works with usm_ndarray
x1_usm = dpnp.get_usm_ndarray(x)
out_usm = None if out is None else dpnp.get_usm_ndarray(out)

res_usm = round_func(x1_usm, out=out_usm, order=order)
return dpnp_array._create_from_usm_ndarray(res_usm)


_sign_docstring = """
sign(x, out=None, order="K")
Expand Down
Loading

0 comments on commit eeae83a

Please sign in to comment.