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

Implement asynchronous fill method using dpctl kernels #2055

Merged
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
f955945
Enhance `dpnp_array.fill` method
ndgrigorian Sep 17, 2024
13edd84
Fix missing disclaimer in dpnp_arraycreation.py
ndgrigorian Sep 17, 2024
4976a24
Import `dpnp_array` directly
ndgrigorian Sep 17, 2024
978a081
Skip `test_fill_with_numpy_scalar_ndarray`
ndgrigorian Sep 17, 2024
2686af9
Add dependencies to zeros and full kernels in `dpnp_fill`
ndgrigorian Sep 18, 2024
2a826b2
Remove redundant validation of first `dpnp_fill` argument
ndgrigorian Sep 18, 2024
6e2193b
Improve `dpnp_fill` array/scalar path logic
ndgrigorian Sep 18, 2024
08b6c26
Disallow inputs to `dpnp_fill` on separate queues
ndgrigorian Sep 18, 2024
c64dc0b
Adjust skip message for `test_fill_with_numpy_scalar_ndarray`
ndgrigorian Oct 14, 2024
9691cf0
Tweak error messages in `dpnp_fill`
ndgrigorian Oct 14, 2024
957b93a
Add tests for new `fill` method
ndgrigorian Oct 14, 2024
87e6560
Update docstring for `fill` method
ndgrigorian Oct 14, 2024
985b4fa
Fix pre-commit in cupy fill tests
ndgrigorian Oct 14, 2024
d8a3e65
Change `asarray` to `astype` in `dpnp_fill`
ndgrigorian Oct 22, 2024
70618e1
Expand TEST_SCOPE to include `test_fill.py`
ndgrigorian Oct 22, 2024
478397f
Remove redundant check from `dpnp_fill`
ndgrigorian Oct 22, 2024
f782d1c
Use `_cast_fill_val` private function from `dpctl.tensor._ctors`
ndgrigorian Oct 22, 2024
e29685e
Add tests per PR review by @antonwolfy
ndgrigorian Oct 22, 2024
bd30f85
Improve validation of `val` for `fill` method
ndgrigorian Oct 23, 2024
865867a
Add to permit NumPy bools as `dpnp_fill` scalar fill values
ndgrigorian Oct 24, 2024
4ba7186
Use `dpnp.bool` in `dpnp_fill` and make `isinstance` check more effic…
ndgrigorian Oct 24, 2024
48c8051
Replace branching for `fill` scalar type with `_cast_fill_value`
ndgrigorian Oct 24, 2024
8adc06a
Add additional tests for `fill`
ndgrigorian Oct 24, 2024
c91ab47
Merge branch 'master' into implement-efficient-fill-method
antonwolfy Oct 24, 2024
c4e0481
Merge branch 'master' into implement-efficient-fill-method
ndgrigorian Oct 24, 2024
387b542
Merge branch 'master' into implement-efficient-fill-method
ndgrigorian Oct 25, 2024
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 .github/workflows/conda-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ env:
test_copy.py
test_counting.py
test_fft.py
test_fill.py
test_flat.py
test_histogram.py
test_indexing.py
Expand Down
26 changes: 26 additions & 0 deletions dpnp/dpnp_algo/dpnp_arraycreation.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,29 @@
# -*- coding: utf-8 -*-
# *****************************************************************************
# Copyright (c) 2016-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.
# *****************************************************************************

import math
import operator

Expand Down
86 changes: 86 additions & 0 deletions dpnp/dpnp_algo/dpnp_fill.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# -*- coding: utf-8 -*-
# *****************************************************************************
# Copyright (c) 2016-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.
# *****************************************************************************

from numbers import Number

import dpctl.tensor as dpt
import dpctl.utils as dpu
import numpy as np
from dpctl.tensor._ctors import _cast_fill_val
from dpctl.tensor._tensor_impl import (
_copy_usm_ndarray_into_usm_ndarray,
_full_usm_ndarray,
_zeros_usm_ndarray,
)

import dpnp


def dpnp_fill(arr, val):
arr = dpnp.get_usm_ndarray(arr)
exec_q = arr.sycl_queue

# if val is an array, process it
if dpnp.is_supported_array_type(val):
val = dpnp.get_usm_ndarray(val)
if val.shape != ():
raise ValueError("`val` must be a scalar or 0D-array")
if dpu.get_execution_queue((exec_q, val.sycl_queue)) is None:
raise dpu.ExecutionPlacementError(
"Input arrays have incompatible queues."
)
a_val = dpt.astype(val, arr.dtype)
a_val = dpt.broadcast_to(a_val, arr.shape)
_manager = dpu.SequentialOrderManager[exec_q]
dep_evs = _manager.submitted_events
h_ev, c_ev = _copy_usm_ndarray_into_usm_ndarray(
src=a_val, dst=arr, sycl_queue=exec_q, depends=dep_evs
)
_manager.add_event_pair(h_ev, c_ev)
return
elif not isinstance(val, Number) and not isinstance(val, np.bool_):
raise TypeError(
f"array cannot be filled with `val` of type {type(val)}"
)

dt = arr.dtype
val_type = type(val)
if val_type in [float, complex] and dpnp.issubdtype(dt, dpnp.integer):
val = int(val.real)
elif val_type is complex and dpnp.issubdtype(dt, dpnp.floating):
val = val.real
elif val_type is int and dpnp.issubdtype(dt, dpnp.integer):
val = _cast_fill_val(val, dt)

_manager = dpu.SequentialOrderManager[exec_q]
dep_evs = _manager.submitted_events
# can leverage efficient memset when val is 0
if arr.flags["FORC"] and val == 0:
h_ev, zeros_ev = _zeros_usm_ndarray(arr, exec_q, depends=dep_evs)
_manager.add_event_pair(h_ev, zeros_ev)
else:
h_ev, fill_ev = _full_usm_ndarray(val, arr, exec_q, depends=dep_evs)
_manager.add_event_pair(h_ev, fill_ev)
11 changes: 8 additions & 3 deletions dpnp/dpnp_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -885,13 +885,16 @@ def fill(self, value):
"""
Fill the array with a scalar value.

For full documentation refer to :obj:`numpy.ndarray.fill`.

Parameters
----------
value : scalar
value : {dpnp.ndarray, usm_ndarray, scalar}
All elements of `a` will be assigned this value.

Examples
--------
>>> import dpnp as np
>>> a = np.array([1, 2])
>>> a.fill(0)
>>> a
Expand All @@ -903,8 +906,10 @@ def fill(self, value):

"""

for i in range(self.size):
self.flat[i] = value
# lazy import avoids circular imports
from .dpnp_algo.dpnp_fill import dpnp_fill

dpnp_fill(self, value)

@property
def flags(self):
Expand Down
78 changes: 78 additions & 0 deletions tests/test_fill.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import dpctl
import numpy as np
import pytest
from dpctl.utils import ExecutionPlacementError
from numpy.testing import assert_array_equal

import dpnp as dnp


def test_fill_non_scalar():
a = dnp.ones(5, dtype="i4")
val = dnp.ones(2, dtype="i4")

with pytest.raises(ValueError):
a.fill(val)

with pytest.raises(TypeError):
a.fill(dict())


def test_fill_compute_follows_data():
q1 = dpctl.SyclQueue()
q2 = dpctl.SyclQueue()

a = dnp.ones(5, dtype="i4", sycl_queue=q1)
val = dnp.ones((), dtype=a.dtype, sycl_queue=q2)

with pytest.raises(ExecutionPlacementError):
a.fill(val)


def test_fill_strided_array():
a = dnp.zeros(100, dtype="i4")
b = a[::-2]

expected = dnp.tile(dnp.asarray([0, 1], dtype=a.dtype), 50)

b.fill(1)
assert_array_equal(b, 1)
assert_array_equal(a, expected)


@pytest.mark.parametrize("order", ["C", "F"])
def test_fill_strided_2d_array(order):
a = dnp.zeros((10, 10), dtype="i4", order=order)
b = a[::-2, ::2]

expected = dnp.copy(a)
expected[::-2, ::2] = 1

b.fill(1)
assert_array_equal(b, 1)
assert_array_equal(a, expected)


@pytest.mark.parametrize("order", ["C", "F"])
def test_fill_memset(order):
a = dnp.ones((10, 10), dtype="i4", order=order)
a.fill(0)

assert_array_equal(a, 0)


def test_fill_float_complex_to_int():
a = dnp.ones((10, 10), dtype="i4")

a.fill(complex(2, 0))
assert_array_equal(a, 2)

a.fill(float(3))
assert_array_equal(a, 3)


def test_fill_complex_to_float():
a = dnp.ones((10, 10), dtype="f4")

a.fill(complex(2, 0))
assert_array_equal(a, 2)
Original file line number Diff line number Diff line change
Expand Up @@ -274,9 +274,7 @@ def test_fill(self, xp, dtype):
a.fill(1)
return a

@testing.with_requires("numpy>=1.24.0")
@testing.for_all_dtypes_combination(("dtype1", "dtype2"))
@testing.numpy_cupy_array_equal(accept_error=ComplexWarning)
@pytest.mark.skip("Numpy allows Numpy scalar arrays as fill value")
def test_fill_with_numpy_scalar_ndarray(self, xp, dtype1, dtype2):
a = testing.shaped_arange((2, 3, 4), xp, dtype1)
a.fill(numpy.ones((), dtype=dtype2))
Expand Down
Loading