Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add implementation of dpnp.nextafter function #1938

Merged
merged 7 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dpnp/backend/extensions/vm/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ set(_elementwise_sources
${CMAKE_CURRENT_SOURCE_DIR}/log1p.cpp
${CMAKE_CURRENT_SOURCE_DIR}/log2.cpp
${CMAKE_CURRENT_SOURCE_DIR}/mul.cpp
${CMAKE_CURRENT_SOURCE_DIR}/nextafter.cpp
${CMAKE_CURRENT_SOURCE_DIR}/pow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/rint.cpp
${CMAKE_CURRENT_SOURCE_DIR}/sin.cpp
Expand Down
167 changes: 167 additions & 0 deletions dpnp/backend/extensions/vm/nextafter.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
//*****************************************************************************
// Copyright (c) 2024, 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.
//*****************************************************************************

#include <oneapi/mkl.hpp>
#include <sycl/sycl.hpp>

#include "dpctl4pybind11.hpp"

#include "common.hpp"
#include "nextafter.hpp"

// include a local copy of elementwise common header from dpctl tensor:
// dpctl/tensor/libtensor/source/elementwise_functions/elementwise_functions.hpp
// TODO: replace by including dpctl header once available
#include "../elementwise_functions/elementwise_functions.hpp"

// dpctl tensor headers
#include "kernels/elementwise_functions/common.hpp"
#include "utils/type_dispatch.hpp"
#include "utils/type_utils.hpp"

namespace dpnp::extensions::vm
{
namespace ew_cmn_ns = dpctl::tensor::kernels::elementwise_common;
antonwolfy marked this conversation as resolved.
Show resolved Hide resolved
namespace py = pybind11;
namespace py_int = dpnp::extensions::py_internal;
namespace td_ns = dpctl::tensor::type_dispatch;
namespace tu_ns = dpctl::tensor::type_utils;

namespace impl
{
// OneMKL namespace with VM functions
namespace mkl_vm = oneapi::mkl::vm;

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

template <typename T1, typename T2>
static sycl::event
nextafter_contig_impl(sycl::queue &exec_q,
std::size_t in_n,
const char *in_a,
py::ssize_t a_offset,
const char *in_b,
py::ssize_t b_offset,
char *out_y,
py::ssize_t out_offset,
const std::vector<sycl::event> &depends)
{
tu_ns::validate_type_for_device<T1>(exec_q);
tu_ns::validate_type_for_device<T2>(exec_q);

if ((a_offset != 0) || (b_offset != 0) || (out_offset != 0)) {
throw std::runtime_error("Arrays offsets have to be equals to 0");
}

std::int64_t n = static_cast<std::int64_t>(in_n);
const T1 *a = reinterpret_cast<const T1 *>(in_a);
const T2 *b = reinterpret_cast<const T2 *>(in_b);

using resTy = typename OutputType<T1, T2>::value_type;
resTy *y = reinterpret_cast<resTy *>(out_y);

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

using ew_cmn_ns::binary_contig_impl_fn_ptr_t;
using ew_cmn_ns::binary_contig_matrix_contig_row_broadcast_impl_fn_ptr_t;
using ew_cmn_ns::binary_contig_row_contig_matrix_broadcast_impl_fn_ptr_t;
using ew_cmn_ns::binary_strided_impl_fn_ptr_t;

static int output_typeid_vector[td_ns::num_types][td_ns::num_types];
static binary_contig_impl_fn_ptr_t contig_dispatch_vector[td_ns::num_types]
[td_ns::num_types];

MACRO_POPULATE_DISPATCH_TABLES(nextafter);
} // namespace impl

void init_nextafter(py::module_ m)
{
using arrayT = dpctl::tensor::usm_ndarray;
using event_vecT = std::vector<sycl::event>;

impl::populate_dispatch_tables();
using impl::contig_dispatch_vector;
using impl::output_typeid_vector;

auto nextafter_pyapi = [&](sycl::queue &exec_q, const arrayT &src1,
const arrayT &src2, const arrayT &dst,
const event_vecT &depends = {}) {
return py_int::py_binary_ufunc(
src1, src2, dst, exec_q, depends, output_typeid_vector,
contig_dispatch_vector,
// no support of strided implementation in OneMKL
td_ns::NullPtrTable<impl::binary_strided_impl_fn_ptr_t>{},
// no support of C-contig row with broadcasting in OneMKL
td_ns::NullPtrTable<
impl::
binary_contig_matrix_contig_row_broadcast_impl_fn_ptr_t>{},
td_ns::NullPtrTable<
impl::
binary_contig_row_contig_matrix_broadcast_impl_fn_ptr_t>{});
};
m.def(
"_nextafter", nextafter_pyapi,
"Call `nextafter` function from OneMKL VM library to return `dst` of "
"elements containing the next representable floating-point values "
"following the values from the elements of `src1` in the direction of "
"the corresponding elements of `src2`",
py::arg("sycl_queue"), py::arg("src1"), py::arg("src2"), py::arg("dst"),
py::arg("depends") = py::list());

auto nextafter_need_to_call_pyapi = [&](sycl::queue &exec_q,
const arrayT &src1,
const arrayT &src2,
const arrayT &dst) {
return py_internal::need_to_call_binary_ufunc(exec_q, src1, src2, dst,
output_typeid_vector,
contig_dispatch_vector);
};
m.def("_mkl_nextafter_to_call", nextafter_need_to_call_pyapi,
"Check input arguments to answer if `nextafter` function from "
"OneMKL VM library can be used",
py::arg("sycl_queue"), py::arg("src1"), py::arg("src2"),
py::arg("dst"));
}
} // namespace dpnp::extensions::vm
35 changes: 35 additions & 0 deletions dpnp/backend/extensions/vm/nextafter.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//*****************************************************************************
// Copyright (c) 2024, 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 <pybind11/pybind11.h>

namespace py = pybind11;

namespace dpnp::extensions::vm
{
void init_nextafter(py::module_ m);
} // namespace dpnp::extensions::vm
2 changes: 2 additions & 0 deletions dpnp/backend/extensions/vm/vm_py.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
#include "log1p.hpp"
#include "log2.hpp"
#include "mul.hpp"
#include "nextafter.hpp"
#include "pow.hpp"
#include "rint.hpp"
#include "sin.hpp"
Expand Down Expand Up @@ -98,6 +99,7 @@ PYBIND11_MODULE(_vm_impl, m)
vm_ns::init_log1p(m);
vm_ns::init_log2(m);
vm_ns::init_mul(m);
vm_ns::init_nextafter(m);
vm_ns::init_pow(m);
vm_ns::init_rint(m);
vm_ns::init_sin(m);
Expand Down
58 changes: 58 additions & 0 deletions dpnp/dpnp_iface_mathematical.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
"modf",
"multiply",
"negative",
"nextafter",
"positive",
"power",
"prod",
Expand Down Expand Up @@ -2359,6 +2360,63 @@ def modf(x1, **kwargs):
)


_NEXTAFTER_DOCSTRING = """
Return the next floating-point value after `x1` towards `x2`, element-wise.

For full documentation refer to :obj:`numpy.nextafter`.

Parameters
----------
x1 : {dpnp.ndarray, usm_ndarray, scalar}
Values to find the next representable value of.
Both inputs `x1` and `x2` can not be scalars at the same time.
x2 : {dpnp.ndarray, usm_ndarray, scalar}
The direction where to look for the next representable value of `x1`.
vtavana marked this conversation as resolved.
Show resolved Hide resolved
Both inputs `x1` and `x2` can not be scalars at the same time.
out : {None, dpnp.ndarray, usm_ndarray}, optional
Output array to populate. Array must have the correct shape and
the expected data type.
Default: ``None``.
order : {"C", "F", "A", "K"}, optional
Output array, if parameter `out` is ``None``.
antonwolfy marked this conversation as resolved.
Show resolved Hide resolved
Default: ``"K"``.

Returns
-------
out : dpnp.ndarray
The next representable values of `x1` in the direction of `x2`. The data
type of the returned array is determined by the Type Promotion Rules.

Limitations
-----------
Parameters `where` and `subok` are supported with their default values.
Keyword argument `kwargs` is currently unsupported.
Otherwise ``NotImplementedError`` exception will be raised.

Examples
--------
>>> import dpnp as np
>>> eps = np.finfo(np.float64).eps
antonwolfy marked this conversation as resolved.
Show resolved Hide resolved
>>> np.nextafter(np.array(1), 2) == eps + 1
array(True)

>>> a = np.array([1, 2])
>>> b = np.array([2, 1])
>>> c = np.array([eps + 1, 2 - eps])
>>> np.nextafter(a, b) == c
array([ True, True])
"""

nextafter = DPNPBinaryFunc(
"nextafter",
ti._nextafter_result_type,
ti._nextafter,
_NEXTAFTER_DOCSTRING,
mkl_fn_to_call=vmi._mkl_nextafter_to_call,
mkl_impl_fn=vmi._nextafter,
)


_POSITIVE_DOCSTRING = """
Computes the numerical positive for each element `x_i` of input array `x`.

Expand Down
7 changes: 0 additions & 7 deletions tests/skipped_tests.tbl
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ tests/test_umath.py::test_umaths[('ldexp', 'di')]
tests/test_umath.py::test_umaths[('ldexp', 'dl')]
tests/test_umath.py::test_umaths[('logaddexp2', 'ff')]
tests/test_umath.py::test_umaths[('logaddexp2', 'dd')]
tests/test_umath.py::test_umaths[('nextafter', 'ff')]
tests/test_umath.py::test_umaths[('nextafter', 'dd')]
tests/test_umath.py::test_umaths[('spacing', 'f')]
tests/test_umath.py::test_umaths[('spacing', 'd')]

Expand Down Expand Up @@ -217,11 +215,6 @@ tests/third_party/cupy/manipulation_tests/test_dims.py::TestInvalidBroadcast_par
tests/third_party/cupy/math_tests/test_explog.py::TestExplog::test_logaddexp2
tests/third_party/cupy/math_tests/test_explog.py::TestExplog::test_logaddexp2_infinities

tests/third_party/cupy/math_tests/test_floating.py::TestFloating::test_frexp
tests/third_party/cupy/math_tests/test_floating.py::TestFloating::test_ldexp
tests/third_party/cupy/math_tests/test_floating.py::TestFloating::test_nextafter_combination
tests/third_party/cupy/math_tests/test_floating.py::TestFloating::test_nextafter_float

tests/third_party/cupy/math_tests/test_misc.py::TestMisc::test_nan_to_num
tests/third_party/cupy/math_tests/test_misc.py::TestMisc::test_nan_to_num_negative
tests/third_party/cupy/math_tests/test_misc.py::TestMisc::test_nan_to_num_for_old_numpy
Expand Down
7 changes: 0 additions & 7 deletions tests/skipped_tests_gpu.tbl
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ tests/test_umath.py::test_umaths[('ldexp', 'di')]
tests/test_umath.py::test_umaths[('ldexp', 'dl')]
tests/test_umath.py::test_umaths[('logaddexp2', 'ff')]
tests/test_umath.py::test_umaths[('logaddexp2', 'dd')]
tests/test_umath.py::test_umaths[('nextafter', 'ff')]
tests/test_umath.py::test_umaths[('nextafter', 'dd')]
tests/test_umath.py::test_umaths[('spacing', 'f')]
tests/test_umath.py::test_umaths[('spacing', 'd')]

Expand Down Expand Up @@ -268,11 +266,6 @@ tests/third_party/cupy/manipulation_tests/test_dims.py::TestInvalidBroadcast_par
tests/third_party/cupy/math_tests/test_explog.py::TestExplog::test_logaddexp2
tests/third_party/cupy/math_tests/test_explog.py::TestExplog::test_logaddexp2_infinities

tests/third_party/cupy/math_tests/test_floating.py::TestFloating::test_frexp
tests/third_party/cupy/math_tests/test_floating.py::TestFloating::test_ldexp
tests/third_party/cupy/math_tests/test_floating.py::TestFloating::test_nextafter_combination
tests/third_party/cupy/math_tests/test_floating.py::TestFloating::test_nextafter_float

tests/third_party/cupy/math_tests/test_misc.py::TestMisc::test_nan_to_num
tests/third_party/cupy/math_tests/test_misc.py::TestMisc::test_nan_to_num_negative
tests/third_party/cupy/math_tests/test_misc.py::TestMisc::test_nan_to_num_for_old_numpy
Expand Down
Loading
Loading