diff --git a/CHANGELOG.md b/CHANGELOG.md index 24442cb0da7a..fd2147010c04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi * Added implementation of `dpnp.scipy.linalg.cho_factor` and `dpnp.scipy.linalg.cho_solve` (SciPy-compatible) [#3116](https://github.com/IntelPython/dpnp/pull/3116) * Added the `dpnp.random.Generator` API with `default_rng`, `BitGenerator`, `SeedSequence` and the `Philox4x3210` bit generator, sampling on the device with the device RNG API of oneMKL or oneMath [#3157](https://github.com/IntelPython/dpnp/pull/3157) * Added `dpnp.argpartition` and `dpnp.ndarray.argpartition` to return the indices that would partition an array [#3138](https://github.com/IntelPython/dpnp/pull/3138) +* Added implementation of `dpnp.scipy.linalg.solve_triangular` (SciPy-compatible) [#3200](https://github.com/IntelPython/dpnp/pull/3200) ### Changed diff --git a/doc/reference/scipy_linalg.rst b/doc/reference/scipy_linalg.rst index 3a1b8e27514c..1c86adc9d83a 100644 --- a/doc/reference/scipy_linalg.rst +++ b/doc/reference/scipy_linalg.rst @@ -5,6 +5,15 @@ Linear algebra (:mod:`dpnp.scipy.linalg`) .. hint:: `SciPy API Reference: Linear algebra (scipy.linalg) `_ +Basics +------ + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + solve_triangular + Decompositions -------------- diff --git a/dpnp/libtensor/extensions/blas/blas_py.cpp b/dpnp/libtensor/extensions/blas/blas_py.cpp index 0e33b7fd19be..0d56c14819cd 100644 --- a/dpnp/libtensor/extensions/blas/blas_py.cpp +++ b/dpnp/libtensor/extensions/blas/blas_py.cpp @@ -169,10 +169,11 @@ PYBIND11_MODULE(_blas_impl, m, py::mod_gil_not_used()) "Call `trsm_batch` from oneMKL BLAS library to solve " "op(A) X = B for a batch of triangular matrices A " "(a 2-D A is shared by the batch). " - "trans_op picks op(A): 0=N, 1=T, 2=C.", + "trans_op picks op(A): 0=N, 1=T, 2=C. With unit_diag, " + "the diagonal of A is assumed to be 1 and is not referenced.", py::arg("sycl_queue"), py::arg("matrixA"), py::arg("matrixB"), py::arg("upper_lower"), py::arg("trans_op") = 0, - py::arg("depends") = py::list()); + py::arg("unit_diag") = false, py::arg("depends") = py::list()); } { diff --git a/dpnp/libtensor/extensions/blas/trsm.hpp b/dpnp/libtensor/extensions/blas/trsm.hpp index fb55f5e681fc..33c7c2fca5c6 100644 --- a/dpnp/libtensor/extensions/blas/trsm.hpp +++ b/dpnp/libtensor/extensions/blas/trsm.hpp @@ -45,6 +45,7 @@ extern std::pair const dpnp::tensor::usm_ndarray &matrixB, const std::int8_t upper_lower, const int trans_op, + const bool unit_diag, const std::vector &depends); extern void init_trsm_batch_dispatch_vector(void); diff --git a/dpnp/libtensor/extensions/blas/trsm_batch.cpp b/dpnp/libtensor/extensions/blas/trsm_batch.cpp index a2d1f0382402..3f49ccaf77cb 100644 --- a/dpnp/libtensor/extensions/blas/trsm_batch.cpp +++ b/dpnp/libtensor/extensions/blas/trsm_batch.cpp @@ -59,6 +59,7 @@ typedef sycl::event (*trsm_batch_impl_fn_ptr_t)( sycl::queue &, const oneapi::mkl::uplo, const oneapi::mkl::transpose, + const oneapi::mkl::diag, const std::int64_t, // m const std::int64_t, // n const char *, // a @@ -77,6 +78,7 @@ template static sycl::event trsm_batch_impl(sycl::queue &exec_q, const oneapi::mkl::uplo upper_lower, const oneapi::mkl::transpose trans, + const oneapi::mkl::diag unit_diag, const std::int64_t m, const std::int64_t n, const char *matrixA, @@ -106,9 +108,10 @@ static sycl::event trsm_batch_impl(sycl::queue &exec_q, exec_q, oneapi::mkl::side::left, // op(A) is on the left: op(A) X = B upper_lower, // Whether A is upper or lower triangular. - trans, // Defines op(A): 'N' for A, 'T' for A^T, or 'C' - // for A^H. - oneapi::mkl::diag::nonunit, // A is not unit triangular. + trans, // Defines op(A): 'N' for A, 'T' for A^T, or 'C' + // for A^H. + unit_diag, // Whether A is unit triangular: its diagonal is + // assumed to be 1 and is not referenced. m, // Number of rows of B, and the order of A. n, // Number of columns of B. T(1), // Scaling factor for B. @@ -147,6 +150,7 @@ std::pair const dpnp::tensor::usm_ndarray &matrixB, const std::int8_t upper_lower, const int trans_op, + const bool unit_diag, const std::vector &depends) { const int a_nd = matrixA.get_ndim(); @@ -238,10 +242,12 @@ std::pair (trans_op == 0) ? oneapi::mkl::transpose::N : (trans_op == 1) ? oneapi::mkl::transpose::T : oneapi::mkl::transpose::C; + const oneapi::mkl::diag diag_val = + unit_diag ? oneapi::mkl::diag::unit : oneapi::mkl::diag::nonunit; sycl::event trsm_batch_ev = trsm_batch_fn( - exec_q, uplo_val, trans, m, n, matrixA.get_data(), lda, stride_a, - matrixB.get_data(), ldb, stride_b, batch_size, depends); + exec_q, uplo_val, trans, diag_val, m, n, matrixA.get_data(), lda, + stride_a, matrixB.get_data(), ldb, stride_b, batch_size, depends); sycl::event args_ev = dpnp::utils::keep_args_alive( exec_q, {matrixA, matrixB}, {trsm_batch_ev}); diff --git a/dpnp/scipy/linalg/__init__.py b/dpnp/scipy/linalg/__init__.py index 01af1433e796..634954fecf93 100644 --- a/dpnp/scipy/linalg/__init__.py +++ b/dpnp/scipy/linalg/__init__.py @@ -35,6 +35,7 @@ """ +from ._basic import solve_triangular from ._decomp_cholesky import cho_factor, cho_solve from ._decomp_lu import lu, lu_factor, lu_solve @@ -44,4 +45,5 @@ "lu", "lu_factor", "lu_solve", + "solve_triangular", ] diff --git a/dpnp/scipy/linalg/_basic.py b/dpnp/scipy/linalg/_basic.py new file mode 100644 index 000000000000..02c7d1a012d0 --- /dev/null +++ b/dpnp/scipy/linalg/_basic.py @@ -0,0 +1,202 @@ +# ***************************************************************************** +# Copyright (c) 2026, 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. +# - Neither the name of the copyright holder 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 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. +# ***************************************************************************** + + +""" +Interface of the SciPy-compatible Linear Algebra subset for DPNP. + +Notes +----- +This module exposes the public API for ``dpnp.scipy.linalg``. +It contains: + - SciPy-like interface functions + - documentation for the functions + +""" + +import operator + +import dpnp + +from ._decomp_cholesky import _lower_to_bool +from ._utils import dpnp_solve_triangular + + +def _trans_to_int(trans): + """Convert `trans` of solve_triangular to 0 (N), 1 (T) or 2 (C).""" + + if isinstance(trans, str): + res = {"N": 0, "T": 1, "C": 2}.get(trans) + else: + try: + res = operator.index(trans) + except TypeError: + res = None + + if res not in (0, 1, 2): + raise ValueError( + f"`trans` must be 0, 1, 2, 'N', 'T' or 'C', got {trans!r}." + ) + return res + + +def solve_triangular( + a, + b, + trans=0, + lower=False, + unit_diagonal=False, + overwrite_b=False, + check_finite=True, +): + """ + Solve the equation ``a x = b`` for `x`, assuming `a` is a triangular + matrix. + + For full documentation refer to :obj:`scipy.linalg.solve_triangular`. + + Parameters + ---------- + a : (..., M, M) {dpnp.ndarray, usm_ndarray} + A triangular matrix. + b : {(M,), (..., M, N)} {dpnp.ndarray, usm_ndarray} + Right-hand side matrix in ``a x = b``. + trans : {0, 1, 2, 'N', 'T', 'C'}, optional + Type of system to solve: + + ======== ========= + trans system + ======== ========= + 0 or 'N' a x = b + 1 or 'T' a^T x = b + 2 or 'C' a^H x = b + ======== ========= + + Default: ``0``. + lower : {bool, array_like of bool}, optional + Use only data contained in the lower triangle of `a`, instead of the + upper one. An array or a sequence is accepted if all its values are + equal. + + Default: ``False``. + unit_diagonal : bool, optional + If ``True``, diagonal elements of `a` are assumed to be 1 and will not + be referenced. + + Default: ``False``. + overwrite_b : bool, optional + Allow overwriting data in `b` (may enhance performance). + + Default: ``False``. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Default: ``True``. + + Returns + ------- + x : {(M,), (..., M, N)} dpnp.ndarray + Solution to the system ``a x = b``. Its shape is the shape of `b`, + with the batch dimensions of `a` and `b` broadcast. + + Raises + ------ + dpnp.linalg.LinAlgError + If `a` is singular: it has a zero on the diagonal and + ``unit_diagonal=False``. + ValueError + If `a` is not square, if `b` is 0-D, if the shapes of `a` and `b` are + incompatible, if `trans` is none of the values above, if `lower` is + empty, not bool or its values are not all equal, or if + ``check_finite=True`` and `a` or `b` contains infinities or NaNs. + + Warnings + -------- + This function synchronizes in order to check the diagonal of `a` for + zeros unless ``unit_diagonal=True``, to validate array elements when + ``check_finite=True``, and to read `lower` or `unit_diagonal` given as + a dpnp array. + + See Also + -------- + :func:`dpnp.scipy.linalg.cho_solve` : Solve a linear set equations using + the Cholesky factorization of + a matrix. + :func:`dpnp.scipy.linalg.lu_solve` : Solve a linear set equations using + the LU factorization of a matrix. + :func:`dpnp.linalg.solve` : Solve a linear matrix equation. + + Notes + ----- + Unlike SciPy: + + - a zero-size batch is supported and gives an empty solution; + - a `trans` other than the values above raises ``ValueError``, while + SciPy may solve the transposed system for it; + - integer and boolean inputs are treated as arrays of the default + floating point data type of the device, as in the other linear algebra + functions of DPNP, with no ``DeprecationWarning`` for boolean input. + + Examples + -------- + Solve the lower triangular system ``a x = b``, where:: + + [3 0 0 0] [4] + a = [2 1 0 0] b = [2] + [1 0 1 0] [4] + [1 1 1 1] [2] + + >>> import dpnp as np + >>> a = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]]) + >>> b = np.array([4, 2, 4, 2]) + >>> x = np.scipy.linalg.solve_triangular(a, b, lower=True) + >>> x + array([ 1.33333333, -0.66666667, 2.66666667, -1.33333333]) + >>> a @ x # Check the result + array([4., 2., 4., 2.]) + + """ + + dpnp.check_supported_arrays_type(a, b) + + if a.ndim < 2 or a.shape[-1] != a.shape[-2]: + raise ValueError("expected square matrix") + if b.ndim < 1: + raise ValueError("expected `b` to have at least one dimension") + + return dpnp_solve_triangular( + a, + b, + trans=_trans_to_int(trans), + lower=_lower_to_bool(lower), + unit_diagonal=bool(unit_diagonal), + overwrite_b=overwrite_b, + check_finite=check_finite, + ) diff --git a/dpnp/scipy/linalg/_utils.py b/dpnp/scipy/linalg/_utils.py index 6554571688f6..bcd959369e59 100644 --- a/dpnp/scipy/linalg/_utils.py +++ b/dpnp/scipy/linalg/_utils.py @@ -356,46 +356,60 @@ def _batched_lu_solve(lu, piv, b, res_type, trans=0): def _batched_cho_solve(c, lower, b, res_type, res_usm_type, exec_q): """Solve a batched equation system given Cholesky factors.""" - b_ndim_orig = b.ndim - # a single factor, also with size-1 batch dimensions, is not broadcast - c_2d = ( - dpnp.reshape(c, c.shape[-2:]) - if all(dim == 1 for dim in c.shape[:-2]) - else None + def solve(c_f, b_f, uplo, _): + n, nrhs, batch_size = b_f.shape + if c_f.ndim == 2 and _fold_rhs_batch( + exec_q, res_type, batch_size, nrhs + ): + _potrs(c_f, dpnp.reshape(b_f, (n, -1), order="F"), uplo, exec_q) + else: + _cho_solve_trsm(c_f, b_f, uplo, exec_q) + + # a transposed complex factor is solved with conj(A), see `_factor_f` + return _batched_tri_solve( + c, b, lower, True, solve, res_type, res_usm_type, exec_q ) - c, b = _align_lu_solve_broadcast(c, b) + + +def _batched_tri_solve( + a, b, lower, conj_flipped, solve, res_type, res_usm_type, exec_q +): + """ + Solve with the triangular matrices or factors `a` (..., n, n) for `b` + (n,) or (..., n, nrhs), one of them at least being batched. + + The batch dimensions are broadcast, but an `a` with only size-1 batch + dimensions stays 2-D and is shared by the RHS batch. + `solve(a_f, b_f, uplo, flipped)` solves in place of the (n, nrhs, batch) + F-contiguous `b_f`, given `a_f`, `flipped` from `_factor_f` and `uplo` + for `a_f`. With `conj_flipped`, a flipped complex `a` is solved for + conj(b), and the solution is conjugated back. + + """ + + b_ndim_orig = b.ndim + a_bcast, b = _align_lu_solve_broadcast(a, b) if b.size == 0: return dpnp.empty( b.shape, dtype=res_type, usm_type=res_usm_type, sycl_queue=exec_q ) - n = c.shape[-1] + n = a.shape[-1] nrhs = b.shape[-1] if b_ndim_orig > 1 else 1 - batch_size = c.size // (n * n) + batch_size = a_bcast.size // (n * n) - if c_2d is not None: - c_f, uplo, conj = _cho_factor_f(c_2d, lower, res_type) - fold = _fold_rhs_batch(exec_q, res_type, batch_size, nrhs) + # a single matrix, also with size-1 batch dimensions, is not broadcast + if a.size == n * n: + a = dpnp.reshape(a, (n, n)) else: - fold = False - c = dpnp.reshape(c, (batch_size, n, n)) - c_is_complex = dpnp.issubdtype(c.dtype, dpnp.complexfloating) - c = dpnp.astype(c, res_type, copy=False) - - # oneMKL expects each factor in column-major order: (n, n, batch) - c_f = dpnp.transpose(c, (1, 2, 0)) - if c_f.flags.f_contiguous: - uplo, conj = int(lower), False - else: - # pass C-contiguous factors transposed, see `dpnp_cho_solve` - c = dpnp.ascontiguousarray(c) - c_f = dpnp.transpose(c, (2, 1, 0)) - uplo, conj = int(not lower), c_is_complex + a = dpnp.reshape(a_bcast, (batch_size, n, n)) + a_f, flipped, a_is_complex = _factor_f(a, res_type) + conj = conj_flipped and flipped and a_is_complex # the solves overwrite `b`: copy it to (n, nrhs, batch) layout, # through a view in its shape, so a broadcast `b` is not materialized - b_h = dpnp.empty( + b_f = dpnp.empty( (n, nrhs, batch_size), dtype=res_type, order="F", @@ -403,16 +417,13 @@ def _batched_cho_solve(c, lower, b, res_type, res_usm_type, exec_q): sycl_queue=exec_q, ) b_nd = b if b_ndim_orig > 1 else b[..., None] - x = dpnp.reshape(dpnp.moveaxis(b_h, -1, 0), b_nd.shape, copy=False) + x = dpnp.reshape(dpnp.moveaxis(b_f, -1, 0), b_nd.shape, copy=False) _copy_rhs(b_nd, x, conj, exec_q) - if fold: - _potrs(c_f, dpnp.reshape(b_h, (n, -1), order="F"), uplo, exec_q) - else: - _cho_solve_trsm(c_f, b_h, uplo, exec_q) + solve(a_f, b_f, int(lower != flipped), flipped) if conj: - dpnp.conj(b_h, out=b_h) + dpnp.conj(b_f, out=b_f) return x if b_ndim_orig > 1 else x[..., 0] @@ -432,38 +443,38 @@ def _cho_solve_trsm(c_f, b_f, uplo, exec_q): # A = F^H F for an upper factor F and A = F F^H for a lower one # (oneapi::mkl::uplo: upper=0, lower=1; trans_op: 0=N, 2=C) - _manager = dpu.SequentialOrderManager[exec_q] - c_usm = dpnp.get_usm_ndarray(c_f) for trans_op in (2, 0) if uplo == 0 else (0, 2): - # Call the BLAS extension function _trsm_batch - # to solve the systems with triangular matrices - ht_ev, trsm_ev = bi._trsm_batch( - exec_q, - c_usm, - dpnp.get_usm_ndarray(b_f), - uplo, - trans_op=trans_op, - depends=_manager.submitted_events, - ) - _manager.add_event_pair(ht_ev, trsm_ev) + _trsm(c_f, b_f, uplo, trans_op, False, exec_q) -def _cho_factor_f(c, lower, res_type): +def _factor_f(a, res_type): """ - Return a 2-D factor `c` in the layout expected by oneMKL potrs and trsm. + Return the matrix `a` (n, n), or the stack `a` (batch, n, n), cast to + `res_type` in the column-major layout of oneMKL: an F-contiguous (n, n) + or (n, n, batch) array. - oneMKL is column-major: an F-contiguous `c` is used as is, otherwise - `c.T` is passed with flipped `uplo`, so the solves are with conj(A) - for a complex factor and the RHS and the solution have to be conjugated - (a real factor cast to a complex type needs none). + An F-ordered `a` is used as is, otherwise its C-contiguous copy is passed + transposed (flipped), so `uplo` is flipped and op(A) changes. A flipped + complex `a` gives conj(A) for op C, so the solves with it are done for + the conjugated RHS and solution (a real `a` cast to a complex type needs + none). + Also returns whether `a` is flipped and whether it was complex. """ - c_is_complex = dpnp.issubdtype(c.dtype, dpnp.complexfloating) - c = dpnp.astype(c, res_type, copy=False) - if c.flags.f_contiguous: - return c, int(lower), False - return dpnp.ascontiguousarray(c).T, int(not lower), c_is_complex + a_is_complex = dpnp.issubdtype(a.dtype, dpnp.complexfloating) + a = dpnp.astype(a, res_type, copy=False) + + if a.ndim == 2: + if a.flags.f_contiguous: + return a, False, a_is_complex + return dpnp.ascontiguousarray(a).T, True, a_is_complex + + a_f = dpnp.transpose(a, (1, 2, 0)) + if a_f.flags.f_contiguous: + return a_f, False, a_is_complex + a = dpnp.ascontiguousarray(a) + return dpnp.transpose(a, (2, 1, 0)), True, a_is_complex def _fold_rhs_batch(exec_q, res_type, batch_size, nrhs): @@ -472,8 +483,8 @@ def _fold_rhs_batch(exec_q, res_type, batch_size, nrhs): folded into the columns. Otherwise, for a real type on GPU and a small batch, where oneMKL potrs - slows down above 16 columns, the factor is shared by the batch in - trsm_batch (stride 0). + and trsm slow down above 16 columns (internal MKLD-20503), the factor is + shared by the batch in trsm_batch (stride 0). The cutoffs were measured with oneMKL 2026.2 on Intel GPUs (PVC, Battlemage, Panther Lake), so CUDA and HIP devices always fold. @@ -489,6 +500,24 @@ def _fold_rhs_batch(exec_q, res_type, batch_size, nrhs): ) +def _fold_tri_rhs(exec_q, res_type, batch_size, nrhs): + """ + Whether to solve with a 2-D triangular matrix in one trsm call, with the + RHS batch folded into the columns. + + The rule of `_fold_rhs_batch` for float64 only: for a single trsm with + oneMKL 2026.2, the shared matrix (stride 0) pays off in float64 on Intel + GPUs (PVC, Battlemage, Lunar Lake, Panther Lake; internal MKLD-20503), + while in float32 it is up to 1.9x slower on Alder Lake and at most 1.3x + faster elsewhere. + + """ + + return res_type != dpnp.float64 or _fold_rhs_batch( + exec_q, res_type, batch_size, nrhs + ) + + def _potrs(c_f, b_f, uplo, exec_q): """Solve ``A X = B`` in place of the F-contiguous `b_f` with potrs.""" @@ -506,6 +535,41 @@ def _potrs(c_f, b_f, uplo, exec_q): _manager.add_event_pair(ht_ev, potrs_ev) +def _trsm(a_f, b_f, uplo, trans_op, unit_diagonal, exec_q): + """ + Solve ``op(A) X = B`` in place of the (n, nrhs, batch) F-contiguous `b_f` + for the F-contiguous (n, n, batch) or shared (n, n) `a_f`. + + """ + + # Call the BLAS extension function _trsm_batch + # to solve the systems with triangular matrices + _manager = dpu.SequentialOrderManager[exec_q] + ht_ev, trsm_ev = bi._trsm_batch( + exec_q, + dpnp.get_usm_ndarray(a_f), + dpnp.get_usm_ndarray(b_f), + uplo, + trans_op=trans_op, + unit_diag=unit_diagonal, + depends=_manager.submitted_events, + ) + _manager.add_event_pair(ht_ev, trsm_ev) + + +def _tri_trans_op(trans, flipped): + """ + Return op(A) for oneMKL, given `trans` (0, 1 or 2) of `solve_triangular`. + + For a flipped `a` (see `_factor_f`), oneMKL sees `a.T`: it is solved with + its transpose for trans N, and with it for trans T and C (for a complex + `a`, the conjugated system is solved for trans C). + + """ + + return int(trans == 0) if flipped else trans + + def _copy_rhs(src, dst, conj, exec_q): """Copy `src` into `dst`, conjugating it if `conj` is ``True``.""" @@ -747,7 +811,8 @@ def dpnp_cho_solve(c, lower, b, overwrite_b=False, check_finite=True): if b.size == 0: return dpnp.empty_like(b, dtype=res_type, usm_type=res_usm_type) - c_f, uplo, conj = _cho_factor_f(c, lower, res_type) + c_f, flipped, c_is_complex = _factor_f(c, res_type) + uplo, conj = int(lower != flipped), flipped and c_is_complex # SciPy-compatible behavior # Copy is required if: @@ -1124,3 +1189,120 @@ def dpnp_lu_solve(lu, piv, b, trans=0, overwrite_b=False, check_finite=True): _manager.add_event_pair(ht_ev, getrs_ev) return b_h + + +def dpnp_solve_triangular( + a, + b, + trans=0, + lower=False, + unit_diagonal=False, + overwrite_b=False, + check_finite=True, +): + """ + dpnp_solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False, + overwrite_b=False, check_finite=True) + + Solve the equation ``a x = b`` for `x`, assuming `a` is a triangular + matrix (SciPy-compatible behavior). + + This function mimics the behavior of `scipy.linalg.solve_triangular` + including support for `overwrite_b` and `check_finite`, with `trans` + given as 0, 1 or 2. + + """ + + res_usm_type, exec_q = get_usm_allocations([a, b]) + res_type = _common_type(a, b) + + # as SciPy, report the shapes of a single system + b_core = b.shape if b.ndim < 2 else b.shape[-2:] + if a.shape[-1] != b_core[0]: + raise ValueError( + f"shapes of a {a.shape[-2:]} and b {b_core} are incompatible" + ) + batch_shape = dpnp.broadcast_shapes(a.shape[:-2], b.shape[:-2]) + is_empty = 0 in batch_shape or 0 in b_core + + # submit all checks before waiting for the first result + is_finite = ( + (dpnp.isfinite(a).all(), dpnp.isfinite(b).all()) if check_finite else () + ) + # as SciPy, the diagonal is read only to solve a non-empty system + is_nonsingular = ( + unit_diagonal + or is_empty + or dpnp.all(dpnp.diagonal(a, axis1=-2, axis2=-1)) + ) + + if not all(is_finite): + raise ValueError("array must not contain infs or NaNs") + if not is_nonsingular: + # the first zero of the first singular matrix, as SciPy reports it + is_zero = dpnp.diagonal(a, axis1=-2, axis2=-1) == 0 + idx = int(dpnp.argmax(dpnp.ravel(is_zero))) % a.shape[-1] + raise dpnp.linalg.LinAlgError( + f"singular matrix: resolution failed at diagonal {idx}" + ) + + if a.ndim > 2 or b.ndim > 2: + + def solve(a_f, b_f, uplo, flipped): + n, nrhs, batch_size = b_f.shape + if a_f.ndim == 2 and _fold_tri_rhs( + exec_q, res_type, batch_size, nrhs + ): + b_f = dpnp.reshape(b_f, (n, -1, 1), order="F") + trans_op = _tri_trans_op(trans, flipped) + _trsm(a_f, b_f, uplo, trans_op, unit_diagonal, exec_q) + + # `overwrite_b` only permits overwriting: a batched `b` is copied + return _batched_tri_solve( + a, b, lower, trans == 2, solve, res_type, res_usm_type, exec_q + ) + + # accommodate empty arrays + if is_empty: + return dpnp.empty_like(b, dtype=res_type, usm_type=res_usm_type) + + a_f, flipped, a_is_complex = _factor_f(a, res_type) + conj = flipped and trans == 2 and a_is_complex + + # SciPy-compatible behavior + # Copy is required if: + # - overwrite_b is False (always copy), + # - dtype mismatch, + # - not F-contiguous, + # - not writeable, + # - USM type differs from the result one, + # - b overlaps `a` (e.g. `solve_triangular(a, a)`) + if ( + not overwrite_b + or b.usm_type != res_usm_type + or _is_copy_required(b, res_type) + or ti._array_overlap(dpnp.get_usm_ndarray(a), dpnp.get_usm_ndarray(b)) + ): + b_f = dpnp.empty_like( + b, order="F", dtype=res_type, usm_type=res_usm_type + ) + _copy_rhs(b, b_f, conj, exec_q) + else: + # input is suitable for in-place modification + b_f = dpnp.get_result_array(b) + if conj: + dpnp.conj(b_f, out=b_f) + + _trsm( + a_f, + dpnp.reshape(b_f, (a.shape[0], -1, 1), order="F"), + int(lower != flipped), + _tri_trans_op(trans, flipped), + unit_diagonal, + exec_q, + ) + + if conj: + dpnp.conj(b_f, out=b_f) + + return b_f diff --git a/dpnp/tests/test_linalg.py b/dpnp/tests/test_linalg.py index 98044b4263fb..5c725927b323 100644 --- a/dpnp/tests/test_linalg.py +++ b/dpnp/tests/test_linalg.py @@ -1,3 +1,4 @@ +import itertools import warnings import dpctl @@ -169,6 +170,55 @@ def _make_hpd_np(shape, dtype, order="C"): return numpy.array(a, order=order) +def _make_tri_np(shape, dtype, lower): + """ + Random triangular matrix (or a batch of them), well conditioned also with + a unit diagonal, with large values in the other triangle, which must not + be read. The diagonal is ``n + 1``: wrong if read with a unit diagonal. + + """ + + n = shape[-1] + if numpy.issubdtype(dtype, numpy.inexact): + # a small triangle keeps a unit diagonal dominant + a = generate_random_numpy_array(shape, dtype, low=-1, high=1) + a /= max(n, 1) + big = 1e3 + else: + # integers are truncated: [-2, 2) gives -1, 0 and 1 + a = generate_random_numpy_array(shape, dtype, low=-2, high=2) + big = 100 + used = numpy.tri(n, k=-1, dtype=bool) + a = numpy.where(used if lower else used.T, a, numpy.asarray(big, dtype)) + a[..., numpy.eye(n, dtype=bool)] = n + 1 + return a + + +def _solve_tri_np(a, b, trans=0, lower=False, unit_diagonal=False): + """NumPy reference of `solve_triangular`.""" + t = numpy.tril(a) if lower else numpy.triu(a) + if unit_diagonal: + t[..., numpy.eye(a.shape[-1], dtype=bool)] = 1 + if trans in (1, "T"): + t = numpy.swapaxes(t, -1, -2) + elif trans in (2, "C"): + t = numpy.swapaxes(t, -1, -2).conj() + return numpy.linalg.solve(t, b) + + +def _with_layout(x_np, layout): + """dpnp copy of `x_np` in the C, F, strided or negative-stride layout.""" + if layout in ("C", "F"): + return dpnp.array(x_np, order=layout) + if layout == "strided": + step = (slice(None, None, 2),) * x_np.ndim + base = numpy.zeros(tuple(2 * d for d in x_np.shape), x_np.dtype) + base[step] = x_np + return dpnp.array(base)[step] + flip = (slice(None, None, -1),) * x_np.ndim + return dpnp.array(x_np[flip])[flip] + + def _tri(a, lower): xp = numpy if isinstance(a, numpy.ndarray) else dpnp return xp.tril(a) if lower else xp.triu(a) @@ -822,6 +872,480 @@ def test_errors(self): ) +class TestSolveTriangular: + @pytest.mark.parametrize("trans", [0, 1, 2, "N", "T", "C"]) + @pytest.mark.parametrize("lower", [True, False]) + @pytest.mark.parametrize("unit_diagonal", [True, False]) + @pytest.mark.parametrize("dtype", get_all_dtypes(no_none=True)) + def test_solve_triangular(self, trans, lower, unit_diagonal, dtype): + a_np = _make_tri_np((5, 5), dtype, lower) + a = dpnp.array(a_np) + + for b_shape in [(5,), (5, 1), (5, 3)]: + b_np = generate_random_numpy_array(b_shape, dtype) + b = dpnp.array(b_np) + + x = dpnp.scipy.linalg.solve_triangular( + a, b, trans=trans, lower=lower, unit_diagonal=unit_diagonal + ) + expected = _solve_tri_np(a_np, b_np, trans, lower, unit_diagonal) + assert_dtype_allclose(x, expected, check_only_type_kind=True) + assert_array_equal(b, b_np) + assert_array_equal(a, a_np) + + @pytest.mark.parametrize("layout", ["C", "F", "strided", "negative"]) + @pytest.mark.parametrize("trans", [0, 1, 2]) + @pytest.mark.parametrize("lower", [True, False]) + @pytest.mark.parametrize("dtype", get_float_complex_dtypes()) + def test_layout(self, layout, trans, lower, dtype): + a_np = _make_tri_np((4, 4), dtype, lower) + a = _with_layout(a_np, layout) + + for b_shape in [(4,), (4, 1), (4, 17)]: + b_np = generate_random_numpy_array(b_shape, dtype) + b = _with_layout(b_np, layout) + + x = dpnp.scipy.linalg.solve_triangular( + a, b, trans=trans, lower=lower + ) + assert_dtype_allclose(x, _solve_tri_np(a_np, b_np, trans, lower)) + assert_array_equal(b, b_np) + assert_array_equal(a, a_np) + + @pytest.mark.parametrize("n", [1, 32, 33, 64]) + @pytest.mark.parametrize("lower", [True, False]) + @pytest.mark.parametrize("unit_diagonal", [True, False]) + @pytest.mark.parametrize("dtype", get_float_complex_dtypes()) + def test_sizes(self, n, lower, unit_diagonal, dtype): + a_np = _make_tri_np((n, n), dtype, lower) + b_np = generate_random_numpy_array((n, 3), dtype) + a, b = dpnp.array(a_np), dpnp.array(b_np, order="F") + + for trans in [0, 1, 2]: + x = dpnp.scipy.linalg.solve_triangular( + a, b, trans=trans, lower=lower, unit_diagonal=unit_diagonal + ) + expected = _solve_tri_np(a_np, b_np, trans, lower, unit_diagonal) + assert_dtype_allclose(x, expected) + + @pytest.mark.parametrize("diag", [0, numpy.inf, numpy.nan]) + @pytest.mark.parametrize("order", ["C", "F"]) + @pytest.mark.parametrize("dtype", get_float_complex_dtypes()) + def test_unit_diagonal_not_read(self, diag, order, dtype): + # a zero is not singular, and NaN is fine without check_finite + a_np = _make_tri_np((4, 4), dtype, lower=True) + numpy.fill_diagonal(a_np, diag) + b_np = generate_random_numpy_array((4, 2), dtype) + a = dpnp.array(a_np, order=order) + + for trans in [0, 1, 2]: + x = dpnp.scipy.linalg.solve_triangular( + a, + dpnp.array(b_np), + trans=trans, + lower=True, + unit_diagonal=True, + check_finite=False, + ) + expected = _solve_tri_np(a_np, b_np, trans, True, True) + assert_dtype_allclose(x, expected) + + @pytest.mark.parametrize("a_shape", [(4, 4), (2, 4, 4)]) + @pytest.mark.parametrize("order", ["C", "F"]) + @pytest.mark.parametrize("a_dtype", get_float_complex_dtypes()) + @pytest.mark.parametrize("b_dtype", get_float_complex_dtypes()) + def test_mixed_dtypes(self, a_shape, order, a_dtype, b_dtype): + # the conjugation for trans C is decided from the dtype of `a` + a_np = _make_tri_np(a_shape, a_dtype, lower=False) + b_np = generate_random_numpy_array(a_shape[:-1] + (2,), b_dtype) + a = dpnp.array(a_np, order=order) + + for trans in [0, 1, 2]: + x = dpnp.scipy.linalg.solve_triangular( + a, dpnp.array(b_np), trans=trans + ) + assert_dtype_allclose(x, _solve_tri_np(a_np, b_np, trans)) + + @pytest.mark.parametrize( + "a_shape, b_shape", + [ + ((1, 4, 4), (4,)), + ((3, 4, 4), (4,)), + ((3, 4, 4), (4, 2)), + ((3, 4, 4), (3, 4, 2)), + ((3, 4, 4), (1, 4, 2)), + ((2, 1, 4, 4), (1, 3, 4, 2)), + ((2, 3, 4, 4), (2, 1, 4, 2)), + ((3, 4, 4), (1, 1, 4, 2)), + ((4, 4), (2, 4, 3)), + ((4, 4), (2, 3, 4, 1)), + ((1, 1, 4, 4), (2, 4, 3)), + ], + ) + @pytest.mark.parametrize("lower", [True, False]) + @pytest.mark.parametrize("order", ["C", "F"]) + @pytest.mark.parametrize("dtype", get_float_complex_dtypes()) + def test_batched(self, a_shape, b_shape, lower, order, dtype): + a_np = _make_tri_np(a_shape, dtype, lower) + b_np = generate_random_numpy_array(b_shape, dtype, order) + a, b = dpnp.array(a_np, order=order), dpnp.array(b_np, order=order) + + for trans, unit_diagonal in itertools.product([0, 1, 2], [True, False]): + x = dpnp.scipy.linalg.solve_triangular( + a, + b, + trans=trans, + lower=lower, + unit_diagonal=unit_diagonal, + overwrite_b=True, + ) + expected = _solve_tri_np(a_np, b_np, trans, lower, unit_diagonal) + assert x.shape == expected.shape + assert_dtype_allclose(x, expected) + # a batched `b` is always copied + assert_array_equal(b, b_np) + + @pytest.mark.parametrize("lower", [True, False]) + @pytest.mark.parametrize("dtype", get_float_complex_dtypes()) + def test_batched_column_major(self, lower, dtype): + # each matrix F-contiguous: passed to oneMKL without a copy + a_np = _make_tri_np((3, 4, 4), dtype, lower) + b_np = generate_random_numpy_array((3, 4, 2), dtype) + a = dpnp.ascontiguousarray(dpnp.array(a_np).mT).mT + + for trans in [0, 1, 2]: + x = dpnp.scipy.linalg.solve_triangular( + a, dpnp.array(b_np), trans=trans, lower=lower + ) + assert_dtype_allclose(x, _solve_tri_np(a_np, b_np, trans, lower)) + + def test_broadcast_a(self): + dtype = dpnp.default_float_type() + a_np = _make_tri_np((4, 4), dtype, lower=True) + b_np = generate_random_numpy_array((3, 4, 2), dtype) + a = dpnp.broadcast_to(dpnp.array(a_np), (3, 4, 4)) + + x = dpnp.scipy.linalg.solve_triangular(a, dpnp.array(b_np), lower=True) + assert_dtype_allclose(x, _solve_tri_np(a_np, b_np, lower=True)) + + # on GPU, a real type with a small batch and at least 16 columns uses + # a shared `a` (also f64 with batch <= 8), the rest is folded into one + # solve + @pytest.mark.parametrize( + "b_shape", + [ + (2, 3, 4, 2), + (2, 4, 16), + (8, 4, 4), + (9, 4, 4), + (32, 4, 1), + (33, 4, 16), + ], + ) + @pytest.mark.parametrize("order", ["C", "F"]) + @pytest.mark.parametrize("a_dtype", get_float_complex_dtypes()) + @pytest.mark.parametrize("b_dtype", get_float_complex_dtypes()) + def test_2d_a_batched_b(self, b_shape, order, a_dtype, b_dtype): + # a 2-D `a` is not broadcast to the RHS batch + a_np = _make_tri_np((4, 4), a_dtype, lower=False) + b_np = generate_random_numpy_array(b_shape, b_dtype) + a, b = dpnp.array(a_np, order=order), dpnp.array(b_np) + + for trans in [0, 1, 2]: + x = dpnp.scipy.linalg.solve_triangular(a, b, trans=trans) + assert_dtype_allclose(x, _solve_tri_np(a_np, b_np, trans)) + assert_array_equal(b, b_np) + + @pytest.mark.parametrize("a_shape", [(4, 4), (1, 4, 4), (1, 1, 4, 4)]) + @pytest.mark.parametrize("fold", [True, False]) + @pytest.mark.parametrize("lower", [True, False]) + @pytest.mark.parametrize("order", ["C", "F"]) + @pytest.mark.parametrize("dtype", get_float_complex_dtypes()) + def test_2d_a_batched_b_path( + self, monkeypatch, a_shape, fold, lower, order, dtype + ): + # the shared `a` is chosen on GPU only: force each path + calls = [] + monkeypatch.setattr( + "dpnp.scipy.linalg._utils._fold_tri_rhs", + lambda *args: calls.append(args) or fold, + ) + a_np = _make_tri_np(a_shape, dtype, lower) + b_np = generate_random_numpy_array((3, 4, 2), dtype) + a, b = dpnp.array(a_np, order=order), dpnp.array(b_np) + + for trans in [0, 1, 2]: + x = dpnp.scipy.linalg.solve_triangular( + a, b, trans=trans, lower=lower + ) + assert_dtype_allclose(x, _solve_tri_np(a_np, b_np, trans, lower)) + # an `a` with size-1 batch dimensions is not broadcast either + assert len(calls) == 3 + + @pytest.mark.parametrize("b_shape", [(4,), (4, 3)]) + @pytest.mark.parametrize("trans", [0, 1, 2]) + @pytest.mark.parametrize("order", ["C", "F"]) + @pytest.mark.parametrize("dtype", get_float_complex_dtypes()) + def test_overwrite_inplace(self, b_shape, trans, order, dtype): + a_np = _make_tri_np((4, 4), dtype, lower=True) + b_np = generate_random_numpy_array(b_shape, dtype) + a, b = dpnp.array(a_np, order=order), dpnp.array(b_np, order="F") + + x = dpnp.scipy.linalg.solve_triangular( + a, b, trans=trans, lower=True, overwrite_b=True + ) + assert x is b + assert_dtype_allclose(x, _solve_tri_np(a_np, b_np, trans, True)) + + @pytest.mark.parametrize("case", ["C-contig", "int", "strided"]) + def test_overwrite_copy(self, case): + if case == "C-contig": + b = dpnp.ones((3, 2), order="C") + elif case == "int": + b = dpnp.ones((3, 2), dtype=dpnp.int32, order="F") + else: + b = dpnp.ones((6, 2), order="F")[::2] + b_orig = b.copy() + + x = dpnp.scipy.linalg.solve_triangular( + 4 * dpnp.eye(3), b, overwrite_b=True + ) + assert x is not b + assert_array_equal(b, b_orig) + assert_allclose(x, b_orig / 4) + + def test_overwrite_read_only(self): + b = dpnp.ones(2) + b.flags["W"] = False + + x = dpnp.scipy.linalg.solve_triangular( + 4 * dpnp.eye(2), b, overwrite_b=True + ) + assert x is not b + assert_allclose(x, numpy.full(2, 0.25)) + + def test_overwrite_b_overlaps_a(self): + # SciPy overwrites `a` here, dpnp solves in a copy + a_np = _make_tri_np((3, 3), dpnp.default_float_type(), lower=False) + a = dpnp.array(a_np, order="F") + + x = dpnp.scipy.linalg.solve_triangular(a, a, overwrite_b=True) + assert x is not a + assert_array_equal(a, a_np) + assert_dtype_allclose(x, _solve_tri_np(a_np, a_np)) + + # partially overlapping view of `a` + x = dpnp.scipy.linalg.solve_triangular(a, a[:, :2], overwrite_b=True) + assert_array_equal(a, a_np) + assert_dtype_allclose(x, _solve_tri_np(a_np, a_np[:, :2])) + + @pytest.mark.parametrize("overwrite_b", [False, True]) + def test_usm_ndarray(self, overwrite_b): + dtype = dpnp.default_float_type() + a_np = _make_tri_np((3, 3), dtype, lower=False) + b_np = generate_random_numpy_array((3, 2), dtype, order="F") + a, b = dpt.asarray(a_np), dpt.asarray(b_np, order="F") + + x = dpnp.scipy.linalg.solve_triangular(a, b, overwrite_b=overwrite_b) + assert isinstance(x, dpnp.ndarray) + assert_dtype_allclose(x, _solve_tri_np(a_np, b_np)) + assert numpy.array_equal(dpt.asnumpy(b), b_np) is not overwrite_b + + # a batch + a_np = _make_tri_np((2, 3, 3), dtype, lower=False) + x = dpnp.scipy.linalg.solve_triangular(dpt.asarray(a_np), b) + assert isinstance(x, dpnp.ndarray) + assert_dtype_allclose(x, _solve_tri_np(a_np, dpt.asnumpy(b))) + + @pytest.mark.parametrize("trans", [True, numpy.int64(2), numpy.uint8(0)]) + def test_trans_integer_types(self, trans): + dtype = dpnp.default_float_type() + a_np = _make_tri_np((3, 3), dtype, lower=False) + b_np = generate_random_numpy_array((3,), dtype) + + x = dpnp.scipy.linalg.solve_triangular( + dpnp.array(a_np), dpnp.array(b_np), trans=trans + ) + assert_dtype_allclose(x, _solve_tri_np(a_np, b_np, int(trans))) + + # SciPy accepts some of them, solves the transposed system for others + # or raises an error of its Fortran wrapper + @pytest.mark.parametrize("trans", [3, -1, "X", "n", "", 1.0, None, [0]]) + def test_trans_invalid(self, trans): + assert_raises_regex( + ValueError, + "`trans` must be 0, 1, 2", + dpnp.scipy.linalg.solve_triangular, + dpnp.eye(2), + dpnp.ones(2), + trans=trans, + ) + + @pytest.mark.parametrize("lower", [True, False]) + def test_lower_array(self, lower): + dtype = dpnp.default_float_type() + a_np = _make_tri_np((3, 3), dtype, lower) + b_np = generate_random_numpy_array((3,), dtype) + expected = _solve_tri_np(a_np, b_np, lower=lower) + + for low in [dpnp.array(lower), numpy.full(2, lower), [lower]]: + x = dpnp.scipy.linalg.solve_triangular( + dpnp.array(a_np), dpnp.array(b_np), lower=low + ) + assert_dtype_allclose(x, expected) + + @pytest.mark.parametrize("low", ["False", None, [True, False], []]) + def test_lower_invalid(self, low): + assert_raises( + ValueError, + dpnp.scipy.linalg.solve_triangular, + dpnp.eye(2), + dpnp.ones(2), + lower=low, + ) + + @pytest.mark.parametrize("idx", [0, 2, 4]) + @pytest.mark.parametrize("zero", [0.0, -0.0]) + @pytest.mark.parametrize("check_finite", [True, False]) + @pytest.mark.parametrize("dtype", get_float_complex_dtypes()) + def test_singular(self, idx, zero, check_finite, dtype): + a_np = _make_tri_np((5, 5), dtype, lower=True) + a_np[idx, idx] = zero + b = dpnp.ones((5, 2), dtype=dtype, order="F") + + # as SciPy, the 0-based index is reported, before `b` is overwritten + for order in ["C", "F"]: + assert_raises_regex( + dpnp.linalg.LinAlgError, + f"singular matrix: resolution failed at diagonal {idx}$", + dpnp.scipy.linalg.solve_triangular, + dpnp.array(a_np, order=order), + b, + lower=True, + overwrite_b=True, + check_finite=check_finite, + ) + assert_array_equal(b, numpy.ones((5, 2), dtype=dtype)) + + def test_singular_batched(self): + # as SciPy, the first singular matrix of the batch is reported + a_np = _make_tri_np((2, 3, 4, 4), dpnp.default_float_type(), False) + a_np[0, 2, 1, 1] = 0 + a_np[1, 0, 3, 3] = 0 + a = dpnp.array(a_np) + + for b in [dpnp.ones(4), dpnp.ones((2, 1, 4, 2))]: + assert_raises_regex( + dpnp.linalg.LinAlgError, + "resolution failed at diagonal 1$", + dpnp.scipy.linalg.solve_triangular, + a, + b, + ) + + @pytest.mark.parametrize("dtype", get_float_complex_dtypes()) + def test_nan_diagonal_not_singular(self, dtype): + a = dpnp.eye(3, dtype=dtype) + a[1, 1] = dpnp.nan + + x = dpnp.scipy.linalg.solve_triangular( + a, dpnp.ones(3, dtype=dtype), check_finite=False + ) + assert dpnp.isnan(x[1]) and x[2] == 1 + + @pytest.mark.parametrize( + "a_shape, b_shape, x_shape", + [ + ((0, 0), (0,), (0,)), + ((0, 0), (0, 2), (0, 2)), + ((2, 2), (2, 0), (2, 0)), + ((2, 0, 0), (0,), (2, 0)), + ((2, 0, 0), (2, 0, 3), (2, 0, 3)), + ((2, 2, 2), (2, 2, 0), (2, 2, 0)), + # SciPy raises for a zero-size batch + ((0, 2, 2), (2,), (0, 2)), + ((2, 2), (0, 2, 1), (0, 2, 1)), + ((1, 2, 2), (0, 2, 1), (0, 2, 1)), + ], + ) + @pytest.mark.parametrize("dtype", [dpnp.int32, dpnp.float32]) + def test_empty(self, a_shape, b_shape, x_shape, dtype): + # as SciPy, a singular `a` is not reported for an empty solution + a = dpnp.zeros(a_shape, dtype=dtype) + b = dpnp.ones(b_shape, dtype=dtype) + + x = dpnp.scipy.linalg.solve_triangular(a, b) + assert x.shape == x_shape + if dtype == dpnp.int32: + assert x.dtype == dpnp.default_float_type(sycl_queue=a.sycl_queue) + else: + assert x.dtype == dtype + + @pytest.mark.parametrize("bad", [numpy.inf, -numpy.inf, numpy.nan]) + @pytest.mark.parametrize("where", ["used", "unused", "diag", "b"]) + @pytest.mark.parametrize("a_shape", [(3, 3), (2, 3, 3)]) + def test_check_finite(self, bad, where, a_shape): + a = dpnp.eye(3) + dpnp.zeros(a_shape) + b = dpnp.ones(3) + if where == "b": + b[1] = bad + else: + ij = {"used": (0, 2), "unused": (2, 0), "diag": (1, 1)}[where] + a[(...,) + ij] = bad + + # as SciPy, the whole `a` is checked + assert_raises_regex( + ValueError, + "array must not contain infs or NaNs", + dpnp.scipy.linalg.solve_triangular, + a, + b, + ) + if where == "unused": + x = dpnp.scipy.linalg.solve_triangular(a, b, check_finite=False) + assert_array_equal(x, numpy.ones(a_shape[:-1])) + + def test_check_finite_empty_b(self): + a = dpnp.full((2, 2), dpnp.nan) + assert_raises( + ValueError, dpnp.scipy.linalg.solve_triangular, a, dpnp.ones((2, 0)) + ) + + @pytest.mark.parametrize( + "a_shape, b_shape, match", + [ + ((3, 3), (2,), r"shapes of a \(3, 3\) and b \(2,\) are incompat"), + ((3, 3), (2, 2), r"a \(3, 3\) and b \(2, 2\)"), + ((), (1,), "expected square matrix"), + ((3,), (3,), "expected square matrix"), + ((3, 2), (3,), "expected square matrix"), + ((2, 3, 4), (3,), "expected square matrix"), + # SciPy raises IndexError + ((3, 3), (), "at least one dimension"), + # as SciPy, the shapes of a single system are reported + ((2, 3, 3), (2, 3), r"a \(3, 3\) and b \(2, 3\)"), + ((2, 3, 3), (2, 2, 1), r"a \(3, 3\) and b \(2, 1\)"), + ((2, 4, 4), (2,), r"a \(4, 4\) and b \(2,\)"), + ((4, 4), (2, 3, 1), r"a \(4, 4\) and b \(3, 1\)"), + ((2, 4, 4), (3, 4, 1), "Shape mismatch"), + ], + ) + def test_shape_errors(self, a_shape, b_shape, match): + a, b = dpnp.ones(a_shape), dpnp.ones(b_shape) + assert_raises_regex( + ValueError, match, dpnp.scipy.linalg.solve_triangular, a, b + ) + + def test_errors(self): + a, b = dpnp.eye(2), dpnp.ones(2) + assert_raises( + TypeError, dpnp.scipy.linalg.solve_triangular, numpy.eye(2), b + ) + assert_raises( + TypeError, dpnp.scipy.linalg.solve_triangular, a, numpy.ones(2) + ) + + class TestCholesky: @pytest.mark.parametrize( "array", diff --git a/dpnp/tests/test_sycl_queue.py b/dpnp/tests/test_sycl_queue.py index 6ec999a6ea7c..2d505e4833f1 100644 --- a/dpnp/tests/test_sycl_queue.py +++ b/dpnp/tests/test_sycl_queue.py @@ -1866,6 +1866,33 @@ def test_cho_solve_diff_queue(self, c_shape, device): with assert_raises((ValueError, ExecutionPlacementError)): dpnp.scipy.linalg.cho_solve((c, False), b) + @pytest.mark.parametrize( + "a_data, b_data", + [ + ([[2.0, 1.0], [0.0, 3.0]], [1.0, 2.0]), + ([[2.0, 1.0], [0.0, 3.0]], numpy.empty((2, 0))), + ([[[2.0, 1.0], [0.0, 3.0]]], [1.0, 2.0]), + ([[2.0, 1.0], [0.0, 3.0]], [[[1.0], [2.0]]]), + ([[[2.0, 1.0], [0.0, 3.0]]], numpy.empty((1, 2, 0))), + ], + ) + def test_solve_triangular(self, a_data, b_data, device): + a = dpnp.array(a_data, device=device) + b = dpnp.array(b_data, device=device) + + result = dpnp.scipy.linalg.solve_triangular(a, b) + + assert_sycl_queue_equal(result.sycl_queue, a.sycl_queue) + assert_sycl_queue_equal(result.sycl_queue, b.sycl_queue) + + @pytest.mark.parametrize("a_shape", [(2, 2), (1, 2, 2)]) + def test_solve_triangular_diff_queue(self, a_shape, device): + a = dpnp.full(a_shape, 2.0, device=device) + b = dpnp.ones(2, sycl_queue=dpctl.SyclQueue(device)) + + with assert_raises((ValueError, ExecutionPlacementError)): + dpnp.scipy.linalg.solve_triangular(a, b) + @pytest.mark.parametrize("n", [-1, 0, 1, 2, 3]) def test_matrix_power(self, n, device): x = dpnp.array([[1.0, 2.0], [3.0, 5.0]], device=device) diff --git a/dpnp/tests/test_usm_type.py b/dpnp/tests/test_usm_type.py index c7e1971a6157..108723b375cb 100644 --- a/dpnp/tests/test_usm_type.py +++ b/dpnp/tests/test_usm_type.py @@ -1662,6 +1662,41 @@ def test_cho_solve_overwrite_b(self, usm_type, usm_type_rhs): # `b` is overwritten only if it has the USM type of the result assert (result is b) == (usm_type_rhs == res_usm_type) + @pytest.mark.parametrize("usm_type_rhs", list_of_usm_types) + @pytest.mark.parametrize( + "a_data, b_data", + [ + ([[2.0, 1.0], [0.0, 3.0]], [1.0, 2.0]), + ([[2.0, 1.0], [0.0, 3.0]], numpy.empty((2, 0))), + ([[[2.0, 1.0], [0.0, 3.0]]], [1.0, 2.0]), + ([[2.0, 1.0], [0.0, 3.0]], [[[1.0], [2.0]]]), + ([[[2.0, 1.0], [0.0, 3.0]]], numpy.empty((1, 2, 0))), + ], + ) + def test_solve_triangular(self, a_data, b_data, usm_type, usm_type_rhs): + a = dpnp.array(a_data, usm_type=usm_type) + b = dpnp.array(b_data, usm_type=usm_type_rhs) + + result = dpnp.scipy.linalg.solve_triangular(a, b) + + assert a.usm_type == usm_type + assert b.usm_type == usm_type_rhs + assert result.usm_type == dpt.get_coerced_usm_type( + [usm_type, usm_type_rhs] + ) + + @pytest.mark.parametrize("usm_type_rhs", list_of_usm_types) + def test_solve_triangular_overwrite_b(self, usm_type, usm_type_rhs): + a = dpnp.array([[2.0, 1.0], [0.0, 3.0]], usm_type=usm_type) + b = dpnp.ones((2, 1), order="F", usm_type=usm_type_rhs) + + result = dpnp.scipy.linalg.solve_triangular(a, b, overwrite_b=True) + + res_usm_type = dpt.get_coerced_usm_type([usm_type, usm_type_rhs]) + assert result.usm_type == res_usm_type + # `b` is overwritten only if it has the USM type of the result + assert (result is b) == (usm_type_rhs == res_usm_type) + @pytest.mark.parametrize("n", [-1, 0, 1, 2, 3]) def test_matrix_power(self, n, usm_type): a = dpnp.array([[1, 2], [3, 5]], usm_type=usm_type) diff --git a/dpnp/tests/third_party/cupyx/scipy_tests/linalg_tests/test_solve_triangular.py b/dpnp/tests/third_party/cupyx/scipy_tests/linalg_tests/test_solve_triangular.py new file mode 100644 index 000000000000..421e1bbb3721 --- /dev/null +++ b/dpnp/tests/third_party/cupyx/scipy_tests/linalg_tests/test_solve_triangular.py @@ -0,0 +1,205 @@ +from __future__ import annotations + +import unittest + +import numpy +import pytest + +import dpnp as cupy +import dpnp as cupyx +from dpnp.tests.third_party.cupy import testing + +# import cupyx.scipy.linalg + +try: + import scipy.linalg + + _scipy_available = True +except ImportError: + _scipy_available = False + + +@testing.parameterize( + *testing.product( + { + "trans": [0, 1, 2, "N", "T", "C"], + "lower": [True, False], + "unit_diagonal": [True, False], + "overwrite_b": [True, False], + "check_finite": [True, False], + } + ) +) +@testing.with_requires("scipy") +class TestSolveTriangular(unittest.TestCase): + + @testing.for_dtypes("fdFD") + def check_x(self, a_shape, b_shape, dtype): + a_cpu = numpy.random.randint(1, 10, size=a_shape).astype(dtype) + b_cpu = numpy.random.randint(1, 10, size=b_shape).astype(dtype) + a_cpu = numpy.tril(a_cpu) + + if self.lower is False: + a_cpu = a_cpu.T + if self.unit_diagonal is True: + numpy.fill_diagonal(a_cpu, 1) + + a_gpu = cupy.asarray(a_cpu) + b_gpu = cupy.asarray(b_cpu) + a_gpu_copy = a_gpu.copy() + b_gpu_copy = b_gpu.copy() + result_cpu = scipy.linalg.solve_triangular( + a_cpu, + b_cpu, + trans=self.trans, + lower=self.lower, + unit_diagonal=self.unit_diagonal, + overwrite_b=self.overwrite_b, + check_finite=self.check_finite, + ) + result_gpu = cupyx.scipy.linalg.solve_triangular( + a_gpu, + b_gpu, + trans=self.trans, + lower=self.lower, + unit_diagonal=self.unit_diagonal, + overwrite_b=self.overwrite_b, + check_finite=self.check_finite, + ) + assert result_cpu.dtype == result_gpu.dtype + testing.assert_allclose(result_cpu, result_gpu, atol=1e-3) + testing.assert_array_equal(a_gpu_copy, a_gpu) + if not self.overwrite_b: + testing.assert_array_equal(b_gpu_copy, b_gpu) + + def test_solve(self): + self.check_x((4, 4), (4,)) + self.check_x((5, 5), (5, 2)) + self.check_x((5, 5), (5, 5)) + + # dpnp supports batches as SciPy does, so the test passes for + # lower=True, unit_diagonal=False and overwrite_b=False; in the other + # cases it fails by itself: a 3-D `.T` makes the matrices singular, + # `fill_diagonal` needs equal dimensions, and SciPy 1.18 solves a 1-D `b` + # in place for each matrix, so the solutions of the batch are all equal + # @pytest.mark.xfail(strict=True, reason="not implemented") + def test_solve_batchwise(self): + if not self.lower or self.unit_diagonal or self.overwrite_b: + pytest.xfail("the test fails with SciPy too") + self.check_x((3, 3, 3), (3,)) + self.check_x((3, 3, 3), (3, 2)) + self.check_x((8, 3, 3), (3, 2)) + self.check_x((3, 3), (8, 3, 2)) + self.check_x((8, 3, 3), (8, 3, 2)) + self.check_x((2, 1, 3, 3), (1, 4, 3, 2)) + + def check_shape(self, a_shape, b_shape): + for xp, sp in ((numpy, scipy), (cupy, cupyx.scipy)): + a = xp.random.rand(*a_shape) + b = xp.random.rand(*b_shape) + with pytest.raises(ValueError): + sp.linalg.solve_triangular( + a, + b, + trans=self.trans, + lower=self.lower, + unit_diagonal=self.unit_diagonal, + overwrite_b=self.overwrite_b, + check_finite=self.check_finite, + ) + + def test_invalid_shape(self): + self.check_shape((2, 3), (4,)) + self.check_shape((3, 3), (2,)) + self.check_shape((3, 3), (2, 2)) + self.check_shape((3, 3, 4), (3,)) + self.check_shape((3, 3, 3), (2, 3)) + + def check_infinite(self, a_shape, b_shape): + for xp, sp in ((numpy, scipy), (cupy, cupyx.scipy)): + a = xp.random.rand(*a_shape) + b = xp.random.rand(*b_shape) + a[(0,) * a.ndim] = numpy.inf + b[(0,) * b.ndim] = numpy.inf + with pytest.raises(ValueError): + sp.linalg.solve_triangular( + a, + b, + trans=self.trans, + lower=self.lower, + unit_diagonal=self.unit_diagonal, + overwrite_b=self.overwrite_b, + check_finite=self.check_finite, + ) + + def test_infinite(self): + if self.check_finite: + self.check_infinite((4, 4), (4,)) + self.check_infinite((5, 5), (5, 2)) + self.check_infinite((5, 5), (5, 5)) + + @testing.for_dtypes("fdFD") + def check_batched(self, a_shape, b_shape, dtype): + a_cpu = numpy.random.randint(1, 10, size=a_shape).astype(dtype) + b_cpu = numpy.random.randint(1, 10, size=b_shape).astype(dtype) + a_cpu = numpy.tril(a_cpu) + + if self.lower is False: + a_dim = tuple(range(len(a_cpu.shape))) + a_dim = a_dim[:-2] + (a_dim[-1], a_dim[-2]) + a_cpu = numpy.transpose(a_cpu, a_dim) + if self.unit_diagonal is True: + for i in range(a_cpu.shape[0]): + numpy.fill_diagonal(a_cpu[i], 1) + + a_gpu = cupy.asarray(a_cpu) + b_gpu = cupy.asarray(b_cpu) + a_gpu_copy = a_gpu.copy() + b_gpu_copy = b_gpu.copy() + + result_cpu = [] + for i in range(a_cpu.shape[0]): + result_cpu_single = scipy.linalg.solve_triangular( + a_cpu[i], + b_cpu[i], + trans=self.trans, + lower=self.lower, + unit_diagonal=self.unit_diagonal, + overwrite_b=self.overwrite_b, + check_finite=self.check_finite, + ) + result_cpu.append(result_cpu_single) + result_cpu = numpy.array(result_cpu) + # result_gpu = cupyx.scipy.linalg.solve_triangular( + # a_gpu, + # b_gpu, + # trans=self.trans, + # lower=self.lower, + # unit_diagonal=self.unit_diagonal, + # overwrite_b=self.overwrite_b, + # check_finite=self.check_finite, + # ) + # unlike CuPy, dpnp follows SciPy, where a (..., M) `b` is a matrix, + # not a batch of vectors: pass the vectors as (..., M, 1) + is_vec = b_gpu.ndim == a_gpu.ndim - 1 + result_gpu = cupyx.scipy.linalg.solve_triangular( + a_gpu, + b_gpu[..., None] if is_vec else b_gpu, + trans=self.trans, + lower=self.lower, + unit_diagonal=self.unit_diagonal, + overwrite_b=self.overwrite_b, + check_finite=self.check_finite, + ) + if is_vec: + result_gpu = result_gpu[..., 0] + assert result_cpu.dtype == result_gpu.dtype + testing.assert_allclose(result_cpu, result_gpu, atol=1e-3) + testing.assert_array_equal(a_gpu_copy, a_gpu) + if not self.overwrite_b: + testing.assert_array_equal(b_gpu_copy, b_gpu) + + def test_solve_batched(self): + self.check_batched((4, 4, 4), (4, 4)) + self.check_batched((5, 5, 5), (5, 5, 2)) + self.check_batched((5, 5, 5), (5, 5, 5))