Repository navigation
Add solve_triangular to dpnp.scipy.linalg - #3200
antonwolfy wants to merge 3 commits into
Conversation
Add the SciPy-compatible `solve_triangular`, including batched input as in SciPy 1.18 (#3096). It solves with oneMKL `trsm_batch` on every path: a 2-D system is a batch of one, and a single matrix with a batched right-hand side folds the batch into the columns or shares the matrix across the batch (stride 0, float64 on Intel GPUs only). The `trsm_batch` binding gets a `unit_diag` argument. A zero on the diagonal raises `LinAlgError` with SciPy's message, checked on the device and read together with the `check_finite` results. The layout and batching code of `cho_solve` becomes a shared helper, `_batched_tri_solve`, and `_cho_factor_f` becomes `_factor_f`.
|
Array API standard conformance tests for dpnp=0.22.0dev3=np2py314h8d9cdd5_59 ran successfully. |
|
View rendered docs @ https://intelpython.github.io/dpnp/pull/3200/index.html |
dpnp solves with trsm_batch, so the trtrs algorithm switch at n = 32 doesn't apply to it.
`_fold_rhs_batch` and `_fold_tri_rhs` share the matrix across the batch because oneMKL `trsm` slows down above 16 right-hand-side columns on Intel GPUs, now reported as MKLD-20503.
vlad-perevezentsev
left a comment
There was a problem hiding this comment.
I tested it on UHD 770 and UHD 730 (no fp64), an Arc B570 and two OpenCL CPUs: the results match SciPy for every option, layout and batch shape, the new tests pass, and it is 2-150x faster than dpnp.linalg.solve. Two performance comments and two nits below.
| _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, | ||
| ) |
There was a problem hiding this comment.
On the B570, float64 trsm with more than 16 columns is slow (MKLD-20503), and here all columns of a 2-D b go to one call. Solving the same columns as blocks of 16 with the shared a is 2.3-3.6x faster (blocks of 32 gain nothing):
b (float64) one trsm 16-column blocks
(4096, 64) 25.5 ms 7.0 ms
(4096, 256) 16.0 ms 7.0 ms
(1024, 256) 1.70 ms 0.53 ms
Could this path view b_f as (n, 16, k // 16) (order F, no copy), like the batched path does for a RHS batch?
| a_f, flipped, a_is_complex = _factor_f(a, res_type) | ||
| conj = flipped and trans == 2 and a_is_complex |
There was a problem hiding this comment.
With complex64 on UHD 770 and UHD 730, oneMKL trsm with op T or C is about 2.5x slower than with op N. A C-ordered a (the default) with trans=0 is passed as a.T with op T, so it gets the slow one:
import time, numpy, dpnp
from dpnp.scipy.linalg import solve_triangular
n, k = 2048, 512
rng = numpy.random.default_rng(0)
a = numpy.tril(rng.random((n, n)) + 1j * rng.random((n, n))) / n + 1.5 * numpy.eye(n)
a_c = dpnp.asarray(a, dtype=dpnp.complex64) # C order, as created by default
a_f = dpnp.asfortranarray(a_c)
b = dpnp.asarray(rng.random((n, k)), dtype=dpnp.complex64, order="F")
for name, x in [("C", a_c), ("F", a_f)]:
solve_triangular(x, b, lower=True)
b.sycl_queue.wait()
t = time.perf_counter()
for _ in range(10):
solve_triangular(x, b, lower=True)
b.sycl_queue.wait()
print(name, f"{(time.perf_counter() - t) * 100:.1f} ms")
# UHD 770: C 46.7 ms, F 17.0 ms; UHD 730: C 50.0 ms, F 22.2 ms; OpenCL CPU: C 21.9 ms, F 21.8 msAn F-ordered a with trans=1 or 2 is slow the same way. Copying a into the op N layout pays off for a wide b. Is this known to oneMKL?
| # 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 |
There was a problem hiding this comment.
Nit: This comment does not match _fold_tri_rhs: only float64 uses the shared a, when batch * nrhs > 16 and batch <= 32; float32 and complex types are always folded. Could it say that, as the cho_solve test does at line 623?
| 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) |
There was a problem hiding this comment.
Nit: This copy-or-overwrite block is the same as the one in dpnp_cho_solve (lines 817-839), comments included. A small helper, e.g. _rhs_f(b, a, overwrite_b, conj, res_type, res_usm_type, exec_q), would keep the two in sync.
Add SciPy-compatible
dpnp.scipy.linalg.solve_triangular, including batched input as in SciPy 1.18 (#3096).Implementation
trsm_batchbinding, which gets aunit_diagargument (defaultFalse, socho_solveis unchanged). A 2-D system is solved as a batch of one: on the GPUs and CPUs tested, a 2-Dtrsmandtrsm_batchwith a batch of one take the same time, so no 2-D binding is added.trtrs: with oneMKL 2026.2 (USM API),trtrsdoesn't raise for a zero on the diagonal, neither on the GPU nor on the CPU, and unlike LAPACK'strtrsits documentation doesn't list that case (reported to the oneMKL team). For n ≤ 32 (and on the CPU at any n) it leavesbunchanged and storesinfoonly in the scratchpad. On the GPU for n > 32 it doesn't detect the zero, andbbecomes inf/NaN. It also blocks the host for n ≤ 32 on both devices, and for larger n it does the same work astrsm. So dpnp checks the diagonal itself.check_finite=True,isfinite(a).all(),isfinite(b).all()andall(diagonal(a))are all submitted before the first read, so a call waits once. The singular check runs unlessunit_diagonal=True, whatevercheck_finiteis, as inlu_factor,cho_factoranddpnp.linalg.solve. A zero raisesLinAlgError("singular matrix: resolution failed at diagonal i")with SciPy's index (the first singular matrix of a batch). All checks run before the solve, sobis never modified when an error is raised.ais used as is. Otherwise its C-contiguous version (the input itself when it is C-contiguous) is passed transposed, withlowerflipped and trans N and T swapped. Trans C on a transposed complexasolves for conj(b) and conjugates the solution back.trsmreads one triangle only, so the other one is never copied or zeroed.cho_solve. A single matrix (2-D, or with size-1 batch dimensions) is not broadcast to a batchedb: the batch is folded into the columns of onetrsmcall. For float64 on Intel GPUs, with a batch of at most 32 and more than 16 columns in total (the rule ofcho_solve), the matrix is instead shared by the batch (stride 0), because oneMKLtrsmgets up to 3.8x slower in float64 above 16 right-hand-side columns on these GPUs (reported to the oneMKL team). In float32, stride 0 is up to 1.9x slower on Iris Xe and at most 1.3x faster elsewhere, and in complex64 it gains at most 1.4x, so the other dtypes always fold.overwrite_b=Truesolves in place of a 1-D or 2-Dbunder SciPy's rule (F-contiguous, of the result dtype), when it is also writable, of the result USM type and doesn't overlapa. A batchedbis always copied.cho_solveis now shared (_batched_tri_solve,_factor_f);cho_solveruns the same kernels as before.Differences from SciPy
Documented in the docstring and covered by tests:
transother than 0, 1, 2,'N','T'or'C'raisesValueError. SciPy solves the transposed system for a C-orderedaand raises an f2py error for an F-ordered one.DeprecationWarningfor boolean input. SciPy 1.18 uses float64 for integers and float32 for booleans.Other changes
doc/reference/scipy_linalg.rst: a new "Basics" section, as on SciPy's page.test_solve_triangular.py. Since dpnp follows SciPy, where a (..., M)bis a matrix and not a batch of vectors, the batched checks pass the vectors asb[..., None]. The upstream xfail oftest_solve_batchwise(not implemented) is kept only for the parameters where the test also fails with SciPy, for example because SciPy 1.18 withoverwrite_b=Truesolves a 1-Dbin place for each matrix of a batch, so all solutions of the batch come out equal.Testing
TestSolveTriangularintest_linalg.py: values against a NumPy reference for all dtypes, everytrans,lowerandunit_diagonal, C, F, strided and negative-stridea, n ≤ 32 and n > 32, mixed dtypes, batching and broadcasting, both paths for a 2-Dawith a batchedb(forced on every device),overwrite_b, singular, empty and invalid input. Also new tests intest_sycl_queue.pyandtest_usm_type.py, plus the CuPy tests.trans,lower,unit_diagonal, batching, broadcasting,overwrite_b,check_finiteand error cases (8861 cases per device, 4627 on Iris Xe) finds no differences other than the documented ones, on all ten devices.--onemathbuild passes the same tests on the Max 1100 system.--onemathbuild shows the existingoneapi::mklnamespace deprecation warnings, which now also cover the newdiaglines.Performance
Median of at least 15 calls with a queue wait after each, in 3-6 rounds of fresh processes, median over rounds; oneAPI 2026.2 (oneMKL 2026.2) on Linux, default
check_finite=True. "-": no fp64 on Iris Xe.Against
dpnp.linalg.solve(LU) on the same GPU,linalg.solvetime /solve_triangulartime (> 1:solve_triangularis faster):solve_triangularis 2.0-7.2x faster than LU, and at n ≥ 4096 with k ≤ 64 it is 4.8-42x faster. With k = n both are O(n³), and at n ≥ 4096 the gain is 2.8-7.3x. The one loss is complex64 n = k = 4096 on Iris Xe (0.88x).Batched, on the GPU: SciPy 1.18.1's loop over the batch on the host CPU / dpnp, and batched
dpnp.linalg.solve/solve_triangular:solve_triangularis 10-1000x faster on every GPU. Against SciPy's loop, the GPU is 2.1-68x faster for 1000-10000 small matrices and 0.29-5.4x for 16-100 larger ones.Against SciPy 1.18.1 on the host CPU of the same system (the faster of its MKL and OpenBLAS builds per case), C-ordered
aandb, SciPy time / dpnp time, with the data on the device / includingdpnp.asarrayofaandbanddpnp.asnumpyofx. The host CPUs are the ones listed under Testing; the Panther Lake H and Lunar Lake CPUs are pre-production samples:solve_triangularpays off when the data already live on the device.Latency in ms on the GPU: default (
check_finite=True) /check_finite=False/ alsounit_diagonal=True/dpnp.linalg.solve:dpnp.linalg.solve, which syncs once ingesv. Withcheck_finite=Falseandunit_diagonal=Truethe call doesn't sync and costs the same as the copy ofbplustrsm_batch.trsm_batchis slow.cho_solveon the shared helper, against master: GPU 0.99-1.00 (median per device), CPU device 0.99-1.00, with the per-case ranges spanning 1.0.