-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathdpnp_utils_linalg.py
More file actions
2871 lines (2323 loc) · 80.9 KB
/
dpnp_utils_linalg.py
File metadata and controls
2871 lines (2323 loc) · 80.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# *****************************************************************************
# Copyright (c) 2023-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.
# *****************************************************************************
"""
Helping functions to implement the Linear Algebra interface.
These include assertion functions to validate input arrays and
functions with the main implementation part to fulfill the interface.
The main computational work is performed by enabling LAPACK functions
available as a pybind11 extension.
"""
# pylint: disable=invalid-name
# pylint: disable=no-name-in-module
# pylint: disable=protected-access
# pylint: disable=useless-import-alias
from typing import NamedTuple
import dpctl.tensor._tensor_impl as ti
import dpctl.utils as dpu
import numpy
from dpctl.tensor._numpy_helper import normalize_axis_index
from numpy import prod
import dpnp
import dpnp.backend.extensions.lapack._lapack_impl as li
from dpnp.dpnp_utils import get_usm_allocations
from dpnp.linalg import LinAlgError as LinAlgError
__all__ = [
"assert_2d",
"assert_stacked_2d",
"assert_stacked_square",
"dpnp_cholesky",
"dpnp_cond",
"dpnp_det",
"dpnp_eigh",
"dpnp_inv",
"dpnp_lstsq",
"dpnp_matrix_power",
"dpnp_matrix_rank",
"dpnp_multi_dot",
"dpnp_norm",
"dpnp_pinv",
"dpnp_qr",
"dpnp_slogdet",
"dpnp_solve",
"dpnp_svd",
]
# pylint:disable=missing-class-docstring
class EighResult(NamedTuple):
eigenvalues: dpnp.ndarray
eigenvectors: dpnp.ndarray
class QRResult(NamedTuple):
Q: dpnp.ndarray
R: dpnp.ndarray
class SlogdetResult(NamedTuple):
sign: dpnp.ndarray
logabsdet: dpnp.ndarray
class SVDResult(NamedTuple):
U: dpnp.ndarray
S: dpnp.ndarray
Vh: dpnp.ndarray
_jobz = {"N": 0, "V": 1}
_upper_lower = {"U": 0, "L": 1}
_real_types_map = {
"float32": "float32", # single : single
"float64": "float64", # double : double
"complex64": "float32", # csingle : csingle
"complex128": "float64", # cdouble : cdouble
}
def _batched_eigh(a, UPLO, eigen_mode, w_type, v_type):
"""
_batched_eigh(a, UPLO, eigen_mode, w_type, v_type)
Return the eigenvalues and eigenvectors of each matrix in a batch of
a complex Hermitian (conjugate symmetric) or a real symmetric matrix.
Can return both eigenvalues and eigenvectors (`eigen_mode="V"`) or
only eigenvalues (`eigen_mode="N"`).
The main calculation is done by calling an extension function
for LAPACK library of OneMKL. Depending on input type of `a` array,
it will be either ``heevd`` (for complex types) or ``syevd`` (for others).
"""
# `eigen_mode` can be either "N" or "V", specifying the computation mode
# for OneMKL LAPACK `syevd` and `heevd` routines.
# "V" (default) means both eigenvectors and eigenvalues will be calculated
# "N" means only eigenvalues will be calculated
jobz = _jobz[eigen_mode]
uplo = _upper_lower[UPLO]
# Get LAPACK function (_syevd_batch for real or _heevd_batch
# for complex data types)
# to compute all eigenvalues and, optionally, all eigenvectors
lapack_func = (
"_heevd_batch"
if dpnp.issubdtype(v_type, dpnp.complexfloating)
else "_syevd_batch"
)
a_sycl_queue = a.sycl_queue
a_orig_shape = a.shape
a_orig_order = "C" if a.flags.c_contiguous else "F"
# get 3d input array by reshape
a = dpnp.reshape(a, (-1, a_orig_shape[-2], a_orig_shape[-1]))
a_new_shape = a.shape
# Reorder the elements by moving the last two axes of `a` to the front
# to match fortran-like array order which is assumed by syevd/heevd.
a = dpnp.moveaxis(a, (-2, -1), (0, 1))
a_usm_arr = dpnp.get_usm_ndarray(a)
_manager = dpu.SequentialOrderManager[a_sycl_queue]
dep_evs = _manager.submitted_events
a_copy = dpnp.empty_like(a, dtype=v_type, order="F")
ht_ev, a_copy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=a_usm_arr,
dst=a_copy.get_array(),
sycl_queue=a_sycl_queue,
depends=dep_evs,
)
_manager.add_event_pair(ht_ev, a_copy_ev)
w_orig_shape = a_orig_shape[:-1]
# allocate a memory for 2d dpnp array of eigenvalues
w = dpnp.empty_like(a, shape=a_new_shape[:-1], dtype=w_type)
ht_ev, evd_batch_ev = getattr(li, lapack_func)(
a_sycl_queue,
jobz,
uplo,
a_copy.get_array(),
w.get_array(),
depends=[a_copy_ev],
)
_manager.add_event_pair(ht_ev, evd_batch_ev)
w = w.reshape(w_orig_shape)
if eigen_mode == "V":
# syevd/heevd call overwrites `a` in Fortran order, reorder the axes
# to match C order by moving the last axis to the front and
# reshape it back to the original shape of `a`.
v = dpnp.moveaxis(a_copy, -1, 0).reshape(a_orig_shape)
# Convert to contiguous to align with NumPy
if a_orig_order == "C":
v = dpnp.ascontiguousarray(v)
return EighResult(w, v)
return w
def _batched_inv(a, res_type):
"""
_batched_inv(a, res_type)
Return the inverses of each matrix in a batch of matrices `a`.
The inverse of a matrix is such that if it is multiplied by the original
matrix, it results in the identity matrix. This function computes the
inverses of a batch of square matrices.
"""
orig_shape = a.shape
# get 3d input arrays by reshape
a = dpnp.reshape(a, (-1, orig_shape[-2], orig_shape[-1]))
batch_size = a.shape[0]
a_usm_arr = dpnp.get_usm_ndarray(a)
a_sycl_queue = a.sycl_queue
a_usm_type = a.usm_type
n = a.shape[1]
# oneMKL LAPACK getri_batch overwrites `a`
a_h = dpnp.empty_like(a, order="C", dtype=res_type, usm_type=a_usm_type)
ipiv_h = dpnp.empty(
(batch_size, n),
dtype=dpnp.int64,
usm_type=a_usm_type,
sycl_queue=a_sycl_queue,
)
dev_info = [0] * batch_size
_manager = dpu.SequentialOrderManager[a_sycl_queue]
# use DPCTL tensor function to fill the matrix array
# with content from the input array `a`
ht_ev, copy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=a_usm_arr,
dst=a_h.get_array(),
sycl_queue=a.sycl_queue,
depends=_manager.submitted_events,
)
_manager.add_event_pair(ht_ev, copy_ev)
ipiv_stride = n
a_stride = a_h.strides[0]
# Call the LAPACK extension function _getrf_batch
# to perform LU decomposition of a batch of general matrices
ht_ev, getrf_ev = li._getrf_batch(
a_sycl_queue,
a_h.get_array(),
ipiv_h.get_array(),
dev_info,
n,
a_stride,
ipiv_stride,
batch_size,
depends=[copy_ev],
)
_manager.add_event_pair(ht_ev, getrf_ev)
_check_lapack_dev_info(dev_info)
# Call the LAPACK extension function _getri_batch
# to compute the inverse of a batch of matrices using the results
# from the LU decomposition performed by _getrf_batch
ht_ev, getri_ev = li._getri_batch(
a_sycl_queue,
a_h.get_array(),
ipiv_h.get_array(),
dev_info,
n,
a_stride,
ipiv_stride,
batch_size,
depends=[getrf_ev],
)
_manager.add_event_pair(ht_ev, getri_ev)
_check_lapack_dev_info(dev_info)
return a_h.reshape(orig_shape)
def _batched_solve(a, b, exec_q, res_usm_type, res_type):
"""
_batched_solve(a, b, exec_q, res_usm_type, res_type)
Return the solution to the system of linear equations of each square
coefficient matrix in a batch of matrices `a` and multiple dependent
variables array `b`.
"""
a_shape = a.shape
b_shape = b.shape
# gesv_batch expects `a` to be a 3D array and
# `b` to be either a 2D or 3D array.
if a.ndim == b.ndim:
b = dpnp.reshape(b, (-1, b_shape[-2], b_shape[-1]))
else:
b = dpnp.reshape(b, (-1, b_shape[-1]))
a = dpnp.reshape(a, (-1, a_shape[-2], a_shape[-1]))
# Reorder the elements by moving the last two axes of `a` to the front
# to match fortran-like array order which is assumed by gesv.
a = dpnp.moveaxis(a, (-2, -1), (0, 1))
# The same for `b` if it is 3D;
# if it is 2D, transpose it.
if b.ndim > 2:
b = dpnp.moveaxis(b, (-2, -1), (0, 1))
else:
b = b.T
a_usm_arr = dpnp.get_usm_ndarray(a)
b_usm_arr = dpnp.get_usm_ndarray(b)
_manager = dpu.SequentialOrderManager[exec_q]
dep_evs = _manager.submitted_events
# oneMKL LAPACK gesv destroys `a` and assumes fortran-like array
# as input.
a_f = dpnp.empty_like(a, dtype=res_type, order="F", usm_type=res_usm_type)
ht_ev, a_copy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=a_usm_arr,
dst=a_f.get_array(),
sycl_queue=exec_q,
depends=dep_evs,
)
_manager.add_event_pair(ht_ev, a_copy_ev)
# oneMKL LAPACK gesv overwrites `b` and assumes fortran-like array
# as input.
b_f = dpnp.empty_like(b, order="F", dtype=res_type, usm_type=res_usm_type)
ht_ev, b_copy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=b_usm_arr,
dst=b_f.get_array(),
sycl_queue=exec_q,
depends=dep_evs,
)
_manager.add_event_pair(ht_ev, b_copy_ev)
ht_ev, gesv_batch_ev = li._gesv_batch(
exec_q,
a_f.get_array(),
b_f.get_array(),
depends=[a_copy_ev, b_copy_ev],
)
_manager.add_event_pair(ht_ev, gesv_batch_ev)
# Gesv call overwtires `b` in Fortran order, reorder the axes
# to match C order by moving the last axis to the front and
# reshape it back to the original shape of `b`.
v = dpnp.moveaxis(b_f, -1, 0).reshape(b_shape)
# dpnp.moveaxis can make the array non-contiguous if it is not 2D
# Convert to contiguous to align with NumPy
if b.ndim > 2:
v = dpnp.ascontiguousarray(v)
return v
def _batched_qr(a, mode="reduced"):
"""
_batched_qr(a, mode="reduced")
Return the batched qr factorization of `a` matrix.
"""
m, n = a.shape[-2:]
k = min(m, n)
batch_shape = a.shape[:-2]
batch_size = prod(batch_shape)
res_type = _common_type(a)
if batch_size == 0 or k == 0:
return _zero_batched_qr(a, mode, m, n, k, res_type)
a_sycl_queue = a.sycl_queue
# get 3d input arrays by reshape
a = dpnp.reshape(a, (-1, m, n))
a = a.swapaxes(-2, -1)
a_usm_arr = dpnp.get_usm_ndarray(a)
a_t = dpnp.empty_like(a, order="C", dtype=res_type)
_manager = dpu.SequentialOrderManager[a_sycl_queue]
# use DPCTL tensor function to fill the matrix array
# with content from the input array `a`
ht_ev, copy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=a_usm_arr,
dst=a_t.get_array(),
sycl_queue=a_sycl_queue,
depends=_manager.submitted_events,
)
_manager.add_event_pair(ht_ev, copy_ev)
tau_h = dpnp.empty_like(
a_t,
shape=(batch_size, k),
dtype=res_type,
)
a_stride = a_t.strides[0]
tau_stride = tau_h.strides[0]
# Call the LAPACK extension function _geqrf_batch to compute
# the QR factorization of a general m x n matrix.
ht_ev, geqrf_ev = li._geqrf_batch(
a_sycl_queue,
a_t.get_array(),
tau_h.get_array(),
m,
n,
a_stride,
tau_stride,
batch_size,
depends=[copy_ev],
)
# w/a to avoid raice conditional on CUDA during multiple runs
# TODO: Remove it ones the OneMath issue is resolved
# https://github.com/uxlfoundation/oneMath/issues/626
if dpnp.is_cuda_backend(a_sycl_queue): # pragma: no cover
ht_ev.wait()
else:
_manager.add_event_pair(ht_ev, geqrf_ev)
if mode in ["r", "raw"]:
if mode == "r":
r = a_t[..., :k].swapaxes(-2, -1)
r = _triu_inplace(r)
return r.reshape(batch_shape + r.shape[-2:])
# mode=="raw"
q = a_t.reshape(batch_shape + a_t.shape[-2:])
r = tau_h.reshape(batch_shape + tau_h.shape[-1:])
return (q, r)
if mode == "complete" and m > n:
mc = m
q = dpnp.empty_like(
a_t,
shape=(batch_size, m, m),
dtype=res_type,
order="C",
)
else:
mc = k
q = dpnp.empty_like(
a_t,
shape=(batch_size, n, m),
dtype=res_type,
order="C",
)
# use DPCTL tensor function to fill the matrix array `q[..., :n, :]`
# with content from the array `a_t` overwritten by geqrf_batch
ht_ev, copy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=a_t.get_array(),
dst=q[..., :n, :].get_array(),
sycl_queue=a_sycl_queue,
depends=[geqrf_ev],
)
_manager.add_event_pair(ht_ev, copy_ev)
q_stride = q.strides[0]
tau_stride = tau_h.strides[0]
# Get LAPACK function (_orgqr_batch for real or _ungqf_batch for complex
# data types) for QR factorization
lapack_func = (
"_ungqr_batch"
if dpnp.issubdtype(res_type, dpnp.complexfloating)
else "_orgqr_batch"
)
# Call the LAPACK extension function _orgqr_batch/ to generate the real
# orthogonal/complex unitary matrices `Qi` of the QR factorization
# for a batch of general matrices.
ht_ev, lapack_ev = getattr(li, lapack_func)(
a_sycl_queue,
q.get_array(),
tau_h.get_array(),
m,
mc,
k,
q_stride,
tau_stride,
batch_size,
depends=[copy_ev],
)
_manager.add_event_pair(ht_ev, lapack_ev)
q = q[..., :mc, :].swapaxes(-2, -1)
r = a_t[..., :mc].swapaxes(-2, -1)
r = _triu_inplace(r)
return QRResult(
q.reshape(batch_shape + q.shape[-2:]),
r.reshape(batch_shape + r.shape[-2:]),
)
# pylint: disable=too-many-locals
def _batched_svd(
a,
uv_type,
s_type,
usm_type,
exec_q,
full_matrices=True,
compute_uv=True,
):
"""
_batched_svd(
a,
uv_type,
s_type,
usm_type,
exec_q,
full_matrices=True,
compute_uv=True,
)
Return the batched singular value decomposition (SVD) of a stack
of matrices.
"""
a_shape = a.shape
a_ndim = a.ndim
batch_shape_orig = a_shape[:-2]
a = dpnp.reshape(a, (prod(batch_shape_orig), a_shape[-2], a_shape[-1]))
batch_size = a.shape[0]
if batch_size == 0:
return _zero_batched_svd(
a,
uv_type,
s_type,
full_matrices,
compute_uv,
exec_q,
usm_type,
batch_shape_orig,
)
m, n = a.shape[-2:]
if m == 0 or n == 0:
return _zero_m_n_batched_svd(
a,
uv_type,
s_type,
full_matrices,
compute_uv,
exec_q,
usm_type,
batch_shape_orig,
)
# Transpose if m < n:
# 1. cuSolver gesvd supports only m >= n
# 2. Reducing a matrix with m >= n to bidiagonal form is more efficient
if m < n:
n, m = a.shape[-2:]
trans_flag = True
else:
trans_flag = False
u_shape, vt_shape, s_shape, jobu, jobvt = _get_svd_shapes_and_flags(
m, n, compute_uv, full_matrices, batch_size=batch_size
)
_manager = dpu.SequentialOrderManager[exec_q]
dep_evs = _manager.submitted_events
# Reorder the elements by moving the last two axes of `a` to the front
# to match fortran-like array order which is assumed by gesvd.
if trans_flag:
# Transpose axes for cuSolver and to optimize reduction
# to bidiagonal form
a = dpnp.moveaxis(a, (-1, -2), (0, 1))
else:
a = dpnp.moveaxis(a, (-2, -1), (0, 1))
# oneMKL LAPACK gesvd destroys `a` and assumes fortran-like array
# as input.
a_f = dpnp.empty_like(a, dtype=uv_type, order="F", usm_type=usm_type)
ht_ev, a_copy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=a.get_array(),
dst=a_f.get_array(),
sycl_queue=exec_q,
depends=dep_evs,
)
_manager.add_event_pair(ht_ev, a_copy_ev)
u_h = dpnp.empty(
u_shape,
order="F",
dtype=uv_type,
usm_type=usm_type,
sycl_queue=exec_q,
)
vt_h = dpnp.empty(
vt_shape,
order="F",
dtype=uv_type,
usm_type=usm_type,
sycl_queue=exec_q,
)
s_h = dpnp.empty(
s_shape,
dtype=s_type,
order="C",
usm_type=usm_type,
sycl_queue=exec_q,
)
ht_ev, gesvd_batch_ev = li._gesvd_batch(
exec_q,
jobu,
jobvt,
a_f.get_array(),
s_h.get_array(),
u_h.get_array(),
vt_h.get_array(),
depends=[a_copy_ev],
)
_manager.add_event_pair(ht_ev, gesvd_batch_ev)
s = s_h.reshape(batch_shape_orig + s_h.shape[-1:])
if compute_uv:
# gesvd call writes `u_h` and `vt_h` in Fortran order;
# reorder the axes to match C order by moving the last axis
# to the front
if trans_flag:
# Transpose axes to restore U and V^T for the original matrix
u = dpnp.moveaxis(u_h, (0, -1), (-1, 0))
vt = dpnp.moveaxis(vt_h, (0, -1), (-1, 0))
else:
u = dpnp.moveaxis(u_h, -1, 0)
vt = dpnp.moveaxis(vt_h, -1, 0)
if a_ndim > 3:
u = u.reshape(batch_shape_orig + u.shape[-2:])
vt = vt.reshape(batch_shape_orig + vt.shape[-2:])
# dpnp.moveaxis can make the array non-contiguous if it is not 2D
# Convert to contiguous to align with NumPy
u = dpnp.ascontiguousarray(u)
vt = dpnp.ascontiguousarray(vt)
# Swap `u` and `vt` for transposed input to restore correct order
return SVDResult(vt, s, u) if trans_flag else SVDResult(u, s, vt)
return s
def _calculate_determinant_sign(ipiv, diag, res_type, n):
"""
Calculate the sign of the determinant based on row exchanges and diagonal
values.
Parameters
-----------
ipiv : {dpnp.ndarray, usm_ndarray}
The pivot indices from LU decomposition.
diag : {dpnp.ndarray, usm_ndarray}
The diagonal elements of the LU decomposition matrix.
res_type : dpnp.dtype
The common data type for linalg operations.
n : int
The size of the last two dimensions of the array.
Returns
-------
sign : {dpnp.ndarray, usm_ndarray}
The sign of the determinant.
"""
# Checks for row exchanges in LU decomposition affecting determinant sign.
ipiv_diff = ipiv != dpnp.arange(
1, n + 1, usm_type=ipiv.usm_type, sycl_queue=ipiv.sycl_queue
)
# Counts row exchanges from 'ipiv_diff'.
non_zero = dpnp.count_nonzero(ipiv_diff, axis=-1)
# For floating types, adds count of negative diagonal elements
# to determine determinant sign.
if dpnp.issubdtype(res_type, dpnp.floating):
non_zero += dpnp.count_nonzero(diag < 0, axis=-1)
sign = (non_zero % 2) * -2 + 1
# For complex types, compute sign from the phase of diagonal elements.
if dpnp.issubdtype(res_type, dpnp.complexfloating):
sign = sign * dpnp.prod(diag / dpnp.abs(diag), axis=-1)
return sign.astype(res_type)
def _check_lapack_dev_info(dev_info, error_msg=None):
"""
Check `dev_info` from OneMKL LAPACK routines, raising an error for failures.
Parameters
----------
dev_info : list of ints
Each element of the list indicates the status of OneMKL LAPACK routine
calls. A non-zero value signifies a failure.
error_message : str, optional
Custom error message for detected LAPACK errors.
Default: `Singular matrix`
Raises
------
dpnp.linalg.LinAlgError
On non-zero elements in dev_info, indicating LAPACK errors.
"""
if any(dev_info):
error_msg = error_msg or "Singular matrix"
raise LinAlgError(error_msg)
def _common_type(*arrays):
"""
Common type for linear algebra operations.
This function determines the common data type for linalg operations.
It's designed to be similar in logic to `numpy.linalg.linalg._commonType`.
Key differences from `numpy.common_type`:
- It accepts ``bool_`` arrays.
- The default floating-point data type is determined by the capabilities of
the device on which `arrays` are created, as indicated
by `dpnp.default_float_type()`.
Parameters
----------
arrays : {dpnp.ndarray, usm_ndarray}
A sequence of input arrays.
Returns
-------
dtype_common : dpnp.dtype
The common data type for linalg operations.
This returned value is applicable both as the precision to be used
in linalg calls and as the dtype of (possibly complex) output(s).
"""
dtypes = [arr.dtype for arr in arrays]
_, sycl_queue = get_usm_allocations(arrays)
default = dpnp.default_float_type(sycl_queue=sycl_queue)
dtype_common = _common_inexact_type(default, *dtypes)
return dtype_common
def _common_inexact_type(default_dtype, *dtypes):
"""
Determines the common 'inexact' data type for linear algebra operations.
This function selects an 'inexact' data type appropriate for the device's
capabilities. It defaults to `default_dtype` when provided types are not
'inexact'.
Parameters
----------
default_dtype : dpnp.dtype
The default data type. This is determined by the capabilities of
the device and is used when none of the provided types are 'inexact'.
*dtypes: A variable number of data types to be evaluated to find
the common 'inexact' type.
Returns
-------
dpnp.result_type : dpnp.dtype
The resultant 'inexact' data type for linalg operations,
ensuring computational compatibility.
"""
inexact_dtypes = [
dt if dpnp.issubdtype(dt, dpnp.inexact) else default_dtype
for dt in dtypes
]
return dpnp.result_type(*inexact_dtypes)
def _get_svd_shapes_and_flags(m, n, compute_uv, full_matrices, batch_size=None):
"""Return the shapes and flags for SVD computations."""
k = min(m, n)
if compute_uv:
if full_matrices:
u_shape = (m, m)
vt_shape = (n, n)
jobu = ord("A")
jobvt = ord("A")
else:
u_shape = (m, k)
vt_shape = (k, n)
jobu = ord("S")
jobvt = ord("S")
else:
u_shape = vt_shape = ()
jobu = ord("N")
jobvt = ord("N")
s_shape = (k,)
if batch_size is not None:
if compute_uv:
u_shape += (batch_size,)
vt_shape += (batch_size,)
s_shape = (batch_size,) + s_shape
return u_shape, vt_shape, s_shape, jobu, jobvt
def _hermitian_svd(a, compute_uv):
"""
_hermitian_svd(a, compute_uv)
Return the singular value decomposition (SVD) of Hermitian matrix `a`.
"""
assert_stacked_square(a)
# _gesvd returns eigenvalues with s ** 2 sorted descending,
# but dpnp.linalg.eigh returns s sorted ascending so we re-order
# the eigenvalues and related arrays to have the correct order
if compute_uv:
s, u = dpnp_eigh(a, eigen_mode="V")
sgn = dpnp.sign(s)
s = dpnp.abs(s, out=s)
sidx = dpnp.argsort(s)[..., ::-1]
# Rearrange the signs according to sorted indices
sgn = dpnp.take_along_axis(sgn, sidx, axis=-1)
# Sort the singular values in descending order
s = dpnp.take_along_axis(s, sidx, axis=-1)
# Rearrange the eigenvectors according to sorted indices
u = dpnp.take_along_axis(u, sidx[..., None, :], axis=-1)
# Singular values are unsigned, move the sign into v
# Compute V^T adjusting for the sign and conjugating
vt = dpnp.transpose(u * sgn[..., None, :]).conjugate()
return SVDResult(u, s, vt)
s = dpnp_eigh(a, eigen_mode="N")
s = dpnp.abs(s, out=s)
return dpnp.sort(s)[..., ::-1]
def _is_empty_2d(arr):
# check size first for efficiency
return arr.size == 0 and numpy.prod(arr.shape[-2:]) == 0
def _lu_factor(a, res_type):
"""
Compute pivoted LU decomposition.
Decompose a given batch of square matrices. Inputs and outputs are
transposed.
Parameters
----------
a : (..., M, M) {dpnp.ndarray, usm_ndarray}
Input array containing the matrices to be decomposed.
res_type : dpnp.dtype
Specifies the data type of the result.
Acceptable data types are float32, float64, complex64, or complex128.
Returns
-------
tuple:
lu_t : (..., N, N) {dpnp.ndarray, usm_ndarray}
Combined 'L' and 'U' matrices from LU decomposition
excluding the diagonal of 'L'.
piv : (..., N) {dpnp.ndarray, usm_ndarray}
1-origin pivot indices indicating row permutations during
decomposition.
dev_info : (...) {dpnp.ndarray, usm_ndarray}
Information on `getrf` or `getrf_batch` computation success
(0 for success).
"""
n = a.shape[-2]
a_sycl_queue = a.sycl_queue
a_usm_type = a.usm_type
# TODO: Find out at which array sizes the best performance is obtained
# getrf_batch implementation shows slow results with large arrays on GPU.
# Use getrf_batch only on CPU.
# On GPU call getrf for each two-dimensional array by loop
use_batch = a.sycl_device.has_aspect_cpu
_manager = dpu.SequentialOrderManager[a_sycl_queue]
if a.ndim > 2:
orig_shape = a.shape
# get 3d input arrays by reshape
a = dpnp.reshape(a, (-1, n, n))
batch_size = a.shape[0]
a_usm_arr = dpnp.get_usm_ndarray(a)
if use_batch:
# `a` must be copied because getrf_batch destroys the input matrix
a_h = dpnp.empty_like(a, order="C", dtype=res_type)
ipiv_h = dpnp.empty(
(batch_size, n),
dtype=dpnp.int64,
order="C",
usm_type=a_usm_type,
sycl_queue=a_sycl_queue,
)
dev_info_h = [0] * batch_size
ht_ev, copy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=a_usm_arr,
dst=a_h.get_array(),
sycl_queue=a_sycl_queue,
depends=_manager.submitted_events,
)
_manager.add_event_pair(ht_ev, copy_ev)
ipiv_stride = n
a_stride = a_h.strides[0]
# Call the LAPACK extension function _getrf_batch
# to perform LU decomposition of a batch of general matrices
ht_ev, getrf_ev = li._getrf_batch(
a_sycl_queue,
a_h.get_array(),
ipiv_h.get_array(),
dev_info_h,
n,
a_stride,
ipiv_stride,
batch_size,
depends=[copy_ev],
)
_manager.add_event_pair(ht_ev, getrf_ev)
dev_info_array = dpnp.array(
dev_info_h, usm_type=a_usm_type, sycl_queue=a_sycl_queue
)
# Reshape the results back to their original shape
a_h = a_h.reshape(orig_shape)
ipiv_h = ipiv_h.reshape(orig_shape[:-1])
dev_info_array = dev_info_array.reshape(orig_shape[:-2])
return (a_h, ipiv_h, dev_info_array)
# Initialize lists for storing arrays and events for each batch
a_vecs = [None] * batch_size
ipiv_vecs = [None] * batch_size
dev_info_vecs = [None] * batch_size
dep_evs = _manager.submitted_events
# Process each batch
for i in range(batch_size):
# Copy each 2D slice to a new array because getrf will destroy
# the input matrix
a_vecs[i] = dpnp.empty_like(a[i], order="C", dtype=res_type)
ht_ev, copy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=a_usm_arr[i],
dst=a_vecs[i].get_array(),
sycl_queue=a_sycl_queue,
depends=dep_evs,
)
_manager.add_event_pair(ht_ev, copy_ev)
ipiv_vecs[i] = dpnp.empty(
(n,),
dtype=dpnp.int64,
order="C",
usm_type=a_usm_type,
sycl_queue=a_sycl_queue,
)