Skip to content

implement dpnp.piecewise #2550

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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* Added `timeout-minutes` property to GitHub jobs [#2526](https://github.com/IntelPython/dpnp/pull/2526)
* Added implementation of `dpnp.ndarray.data` and `dpnp.ndarray.data.ptr` attributes [#2521](https://github.com/IntelPython/dpnp/pull/2521)
* Added `dpnp.ndarray.__contains__` method [#2534](https://github.com/IntelPython/dpnp/pull/2534)
* Added implementation of `dpnp.piecewise` [#2550](https://github.com/IntelPython/dpnp/pull/2550)

### Changed

Expand Down
1 change: 1 addition & 0 deletions dpnp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ endfunction()
add_subdirectory(backend)
add_subdirectory(backend/extensions/blas)
add_subdirectory(backend/extensions/fft)
add_subdirectory(backend/extensions/functional)
add_subdirectory(backend/extensions/indexing)
add_subdirectory(backend/extensions/lapack)
add_subdirectory(backend/extensions/statistics)
Expand Down
90 changes: 90 additions & 0 deletions dpnp/backend/extensions/functional/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# *****************************************************************************
# Copyright (c) 2025, 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.
# *****************************************************************************


set(python_module_name _functional_impl)
set(_module_src
${CMAKE_CURRENT_SOURCE_DIR}/piecewise.cpp
${CMAKE_CURRENT_SOURCE_DIR}/functional_py.cpp
)

pybind11_add_module(${python_module_name} MODULE ${_module_src})
add_sycl_to_target(TARGET ${python_module_name} SOURCES ${_module_src})

if(_dpnp_sycl_targets)
# make fat binary
target_compile_options(
${python_module_name}
PRIVATE
${_dpnp_sycl_target_compile_options}
)
target_link_options(
${python_module_name}
PRIVATE
${_dpnp_sycl_target_link_options}
)
endif()

if (WIN32)
if (${CMAKE_VERSION} VERSION_LESS "3.27")
# this is a work-around for target_link_options inserting option after -link option, cause
# linker to ignore it.
set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS} -fsycl-device-code-split=per_kernel")
endif()
endif()

set_target_properties(${python_module_name} PROPERTIES CMAKE_POSITION_INDEPENDENT_CODE ON)

target_include_directories(${python_module_name} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../include)
target_include_directories(${python_module_name} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../src)

target_include_directories(${python_module_name} PUBLIC ${Dpctl_INCLUDE_DIR})
target_include_directories(${python_module_name} PUBLIC ${Dpctl_TENSOR_INCLUDE_DIR})

if (WIN32)
target_compile_options(${python_module_name} PRIVATE
/clang:-fno-approx-func
/clang:-fno-finite-math-only
)
else()
target_compile_options(${python_module_name} PRIVATE
-fno-approx-func
-fno-finite-math-only
)
endif()

target_link_options(${python_module_name} PUBLIC -fsycl-device-code-split=per_kernel)

if (DPNP_GENERATE_COVERAGE)
target_link_options(${python_module_name} PRIVATE -fprofile-instr-generate -fcoverage-mapping)
endif()

if (DPNP_WITH_REDIST)
set_target_properties(${python_module_name} PROPERTIES INSTALL_RPATH "$ORIGIN/../../../../../../")
endif()

install(TARGETS ${python_module_name}
DESTINATION "dpnp/backend/extensions/functional"
)
48 changes: 48 additions & 0 deletions dpnp/backend/extensions/functional/functional_py.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//*****************************************************************************
// Copyright (c) 2025, 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.
//*****************************************************************************
//
// This file defines functions of dpnp.backend._functional_impl extensions
//
//*****************************************************************************

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#include "piecewise.hpp"

namespace functional_ns = dpnp::extensions::functional;
namespace py = pybind11;

PYBIND11_MODULE(_functional_impl, m)
{
{
functional_ns::init_piecewise_dispatch_vectors();

m.def("_piecewise", functional_ns::py_piecewise,
"Call piecewise kernel", py::arg("sycl_queue"), py::arg("value"),
py::arg("condition"), py::arg("result"),
py::arg("depends") = py::list());
}
}
215 changes: 215 additions & 0 deletions dpnp/backend/extensions/functional/piecewise.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
//*****************************************************************************
// Copyright (c) 2025, 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 "piecewise.hpp"

#include "utils/output_validation.hpp"
#include "utils/type_dispatch.hpp"
#include "utils/type_utils.hpp"

#include <pybind11/numpy.h>
#include <sycl/sycl.hpp>

namespace dpnp::extensions::functional
{
namespace dpctl_td_ns = dpctl::tensor::type_dispatch;

typedef sycl::event (*piecewise_fn_ptr_t)(sycl::queue &,
const py::object &,
const std::size_t,
const char *,
char *,
const std::vector<sycl::event> &);

static piecewise_fn_ptr_t piecewise_dispatch_vector[dpctl_td_ns::num_types];

template <typename T>
class PiecewiseFunctor
{
private:
const T val;
const bool *cond = nullptr;
T *res = nullptr;

public:
PiecewiseFunctor(const T val, const bool *cond, T *res)
: val(val), cond(cond), res(res)
{
}

void operator()(sycl::id<1> id) const
{
const auto i = id.get(0);
if (cond[i]) {
res[i] = val;
}
}
};

template <typename T>
sycl::event piecewise_impl(sycl::queue &exec_q,
const py::object &value,
const std::size_t nelems,
const char *condition,
char *result,
const std::vector<sycl::event> &depends)
{
dpctl::tensor::type_utils::validate_type_for_device<T>(exec_q);

py::object type_obj = py::type::of(value);
std::string type_name = py::str(type_obj.attr("__name__"));

T *res = reinterpret_cast<T *>(result);
const bool *cond = reinterpret_cast<const bool *>(condition);
T val = py::cast<const T>(value);

sycl::event piecewise_ev = exec_q.submit([&](sycl::handler &cgh) {
cgh.depends_on(depends);

using PiecewiseKernel = PiecewiseFunctor<T>;
cgh.parallel_for<PiecewiseKernel>(sycl::range<1>(nelems),
PiecewiseKernel(val, cond, res));
});

return piecewise_ev;
}

/**
* @brief A factory to define pairs of supported types for which
* piecewise function is available.
*
* @tparam T Type of input vector `a` and of result vector `y`.
*/
template <typename T>
struct PiecewiseOutputType
{
using value_type = typename std::disjunction<
dpctl_td_ns::TypeMapResultEntry<T, bool>,
dpctl_td_ns::TypeMapResultEntry<T, std::uint8_t>,
dpctl_td_ns::TypeMapResultEntry<T, std::int8_t>,
dpctl_td_ns::TypeMapResultEntry<T, std::uint16_t>,
dpctl_td_ns::TypeMapResultEntry<T, std::int16_t>,
dpctl_td_ns::TypeMapResultEntry<T, std::uint32_t>,
dpctl_td_ns::TypeMapResultEntry<T, std::int32_t>,
dpctl_td_ns::TypeMapResultEntry<T, std::uint64_t>,
dpctl_td_ns::TypeMapResultEntry<T, std::int64_t>,
dpctl_td_ns::TypeMapResultEntry<T, sycl::half>,
dpctl_td_ns::TypeMapResultEntry<T, float>,
dpctl_td_ns::TypeMapResultEntry<T, double>,
dpctl_td_ns::TypeMapResultEntry<T, std::complex<float>>,
dpctl_td_ns::TypeMapResultEntry<T, std::complex<double>>,
dpctl_td_ns::DefaultResultEntry<void>>::result_type;
};

template <typename fnT, typename T>
struct PiecewiseFactory
{
fnT get()
{
if constexpr (std::is_same_v<
typename PiecewiseOutputType<T>::value_type, void>) {
return nullptr;
}
else {
return piecewise_impl<T>;
}
}
};

std::pair<sycl::event, sycl::event>
py_piecewise(sycl::queue &exec_q,
const py::object &value,
const dpctl::tensor::usm_ndarray &condition,
const dpctl::tensor::usm_ndarray &result,
const std::vector<sycl::event> &depends)
{
dpctl::tensor::validation::CheckWritable::throw_if_not_writable(result);

const int res_nd = result.get_ndim();
const int cond_nd = condition.get_ndim();
if (res_nd != cond_nd) {
throw py::value_error(
"Condition and result arrays must have the same dimension.");
}

if (!dpctl::utils::queues_are_compatible(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you use check_queue from common validation utils?

exec_q, {condition.get_queue(), result.get_queue()}))
{
throw py::value_error(
"Execution queue is not compatible with allocation queue.");
}

const bool is_result_c_contig = result.is_c_contiguous();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think condition should also be C-contig to keep the kernel running correctly

In [1]: import dpnp

In [2]: import numpy

In [3]: a = numpy.arange(8).reshape(2,2,2)

In [4]: cond = numpy.array(a>3, order="F")

In [5]: a_dp = dpnp.array(a)

In [6]: cond_dp = dpnp.array(cond, order="F")

In [7]: numpy.piecewise(a, [cond], [1])
Out[7]: 
array([[[0, 0],
        [0, 0]],

       [[1, 1],
        [1, 1]]])

In [8]: dpnp.piecewise(a_dp,[cond_dp],[1])
Out[8]: 
array([[[0, 1],
        [0, 1]],

       [[0, 1],
        [0, 1]]])

if (!is_result_c_contig) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same
check_c_contig

throw py::value_error("The result array is not c-contiguous.");
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we check for no memory overlap?

const py::ssize_t *res_shape = result.get_shape_raw();
const py::ssize_t *cond_shape = condition.get_shape_raw();

const bool shapes_equal =
std::equal(res_shape, res_shape + res_nd, cond_shape);
if (!shapes_equal) {
throw py::value_error(
"Condition and result arrays must have the same shape.");
}

const std::size_t nelems = result.get_size();
if (nelems == 0) {
return std::make_pair(sycl::event{}, sycl::event{});
}

const int result_typenum = result.get_typenum();
auto array_types = dpctl_td_ns::usm_ndarray_types();
const int result_type_id = array_types.typenum_to_lookup_id(result_typenum);
auto piecewise_fn = piecewise_dispatch_vector[result_type_id];

if (piecewise_fn == nullptr) {
throw std::runtime_error("Type of given array is not supported");
}

const char *condition_typeless_ptr = condition.get_data();
char *result_typeless_ptr = result.get_data();

sycl::event piecewise_ev =
piecewise_fn(exec_q, value, nelems, condition_typeless_ptr,
result_typeless_ptr, depends);
sycl::event args_ev =
dpctl::utils::keep_args_alive(exec_q, {result}, {piecewise_ev});

return std::make_pair(args_ev, piecewise_ev);
}

void init_piecewise_dispatch_vectors(void)
{
dpctl_td_ns::DispatchVectorBuilder<piecewise_fn_ptr_t, PiecewiseFactory,
dpctl_td_ns::num_types>
contig;
contig.populate_dispatch_vector(piecewise_dispatch_vector);

return;
}

} // namespace dpnp::extensions::functional
Loading
Loading