-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathlinalg.py
2853 lines (2330 loc) · 90.3 KB
/
linalg.py
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
"""
Implementation of linear algebra operations.
"""
import contextlib
import warnings
from llvmlite import ir
import numpy as np
import operator
from numba.core.imputils import (lower_builtin, impl_ret_borrowed,
impl_ret_new_ref, impl_ret_untracked)
from numba.core.typing import signature
from numba.core.extending import intrinsic, overload, register_jitable
from numba.core import types, cgutils, config
from numba.core.errors import TypingError, NumbaTypeError, \
NumbaPerformanceWarning
from .arrayobj import make_array, _empty_nd_impl, array_copy
from numba.np import numpy_support as np_support
ll_char = ir.IntType(8)
ll_char_p = ll_char.as_pointer()
ll_void_p = ll_char_p
ll_intc = ir.IntType(32)
ll_intc_p = ll_intc.as_pointer()
intp_t = cgutils.intp_t
ll_intp_p = intp_t.as_pointer()
# fortran int type, this needs to match the F_INT C declaration in
# _lapack.c and is present to accommodate potential future 64bit int
# based LAPACK use.
F_INT_nptype = np.int32
if config.USE_LEGACY_TYPE_SYSTEM:
F_INT_nbtype = types.int32
# BLAS kinds as letters
_blas_kinds = {
types.float32: 's',
types.float64: 'd',
types.complex64: 'c',
types.complex128: 'z',
}
else:
F_INT_nbtype = types.np_int32
# BLAS kinds as letters
_blas_kinds = {
types.np_float32: 's',
types.np_float64: 'd',
types.np_complex64: 'c',
types.np_complex128: 'z',
}
def get_blas_kind(dtype, func_name="<BLAS function>"):
kind = _blas_kinds.get(dtype)
if kind is None:
raise NumbaTypeError("unsupported dtype for %s()" % (func_name,))
return kind
def ensure_blas():
try:
import scipy.linalg.cython_blas
except ImportError:
raise ImportError("scipy 0.16+ is required for linear algebra")
def ensure_lapack():
try:
import scipy.linalg.cython_lapack
except ImportError:
raise ImportError("scipy 0.16+ is required for linear algebra")
def make_constant_slot(context, builder, ty, val):
const = context.get_constant_generic(builder, ty, val)
return cgutils.alloca_once_value(builder, const)
class _BLAS:
"""
Functions to return type signatures for wrapped
BLAS functions.
"""
def __init__(self):
ensure_blas()
@classmethod
def numba_xxnrm2(cls, dtype):
rtype = getattr(dtype, "underlying_float", dtype)
sig = types.intc(types.char, # kind
types.intp, # n
types.CPointer(dtype), # x
types.intp, # incx
types.CPointer(rtype)) # returned
return types.ExternalFunction("numba_xxnrm2", sig)
@classmethod
def numba_xxgemm(cls, dtype):
sig = types.intc(
types.char, # kind
types.char, # transa
types.char, # transb
types.intp, # m
types.intp, # n
types.intp, # k
types.CPointer(dtype), # alpha
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(dtype), # b
types.intp, # ldb
types.CPointer(dtype), # beta
types.CPointer(dtype), # c
types.intp # ldc
)
return types.ExternalFunction("numba_xxgemm", sig)
class _LAPACK:
"""
Functions to return type signatures for wrapped
LAPACK functions.
"""
def __init__(self):
ensure_lapack()
@classmethod
def numba_xxgetrf(cls, dtype):
sig = types.intc(types.char, # kind
types.intp, # m
types.intp, # n
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(F_INT_nbtype) # ipiv
)
return types.ExternalFunction("numba_xxgetrf", sig)
@classmethod
def numba_ez_xxgetri(cls, dtype):
sig = types.intc(types.char, # kind
types.intp, # n
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(F_INT_nbtype) # ipiv
)
return types.ExternalFunction("numba_ez_xxgetri", sig)
@classmethod
def numba_ez_rgeev(cls, dtype):
sig = types.intc(types.char, # kind
types.char, # jobvl
types.char, # jobvr
types.intp, # n
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(dtype), # wr
types.CPointer(dtype), # wi
types.CPointer(dtype), # vl
types.intp, # ldvl
types.CPointer(dtype), # vr
types.intp # ldvr
)
return types.ExternalFunction("numba_ez_rgeev", sig)
@classmethod
def numba_ez_cgeev(cls, dtype):
sig = types.intc(types.char, # kind
types.char, # jobvl
types.char, # jobvr
types.intp, # n
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(dtype), # w
types.CPointer(dtype), # vl
types.intp, # ldvl
types.CPointer(dtype), # vr
types.intp # ldvr
)
return types.ExternalFunction("numba_ez_cgeev", sig)
@classmethod
def numba_ez_xxxevd(cls, dtype):
wtype = getattr(dtype, "underlying_float", dtype)
sig = types.intc(types.char, # kind
types.char, # jobz
types.char, # uplo
types.intp, # n
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(wtype), # w
)
return types.ExternalFunction("numba_ez_xxxevd", sig)
@classmethod
def numba_xxpotrf(cls, dtype):
sig = types.intc(types.char, # kind
types.char, # uplo
types.intp, # n
types.CPointer(dtype), # a
types.intp # lda
)
return types.ExternalFunction("numba_xxpotrf", sig)
@classmethod
def numba_ez_gesdd(cls, dtype):
stype = getattr(dtype, "underlying_float", dtype)
sig = types.intc(
types.char, # kind
types.char, # jobz
types.intp, # m
types.intp, # n
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(stype), # s
types.CPointer(dtype), # u
types.intp, # ldu
types.CPointer(dtype), # vt
types.intp # ldvt
)
return types.ExternalFunction("numba_ez_gesdd", sig)
@classmethod
def numba_ez_geqrf(cls, dtype):
sig = types.intc(
types.char, # kind
types.intp, # m
types.intp, # n
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(dtype), # tau
)
return types.ExternalFunction("numba_ez_geqrf", sig)
@classmethod
def numba_ez_xxgqr(cls, dtype):
sig = types.intc(
types.char, # kind
types.intp, # m
types.intp, # n
types.intp, # k
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(dtype), # tau
)
return types.ExternalFunction("numba_ez_xxgqr", sig)
@classmethod
def numba_ez_gelsd(cls, dtype):
rtype = getattr(dtype, "underlying_float", dtype)
sig = types.intc(
types.char, # kind
types.intp, # m
types.intp, # n
types.intp, # nrhs
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(dtype), # b
types.intp, # ldb
types.CPointer(rtype), # S
types.float64, # rcond
types.CPointer(types.intc) # rank
)
return types.ExternalFunction("numba_ez_gelsd", sig)
@classmethod
def numba_xgesv(cls, dtype):
sig = types.intc(
types.char, # kind
types.intp, # n
types.intp, # nhrs
types.CPointer(dtype), # a
types.intp, # lda
types.CPointer(F_INT_nbtype), # ipiv
types.CPointer(dtype), # b
types.intp # ldb
)
return types.ExternalFunction("numba_xgesv", sig)
@contextlib.contextmanager
def make_contiguous(context, builder, sig, args):
"""
Ensure that all array arguments are contiguous, if necessary by
copying them.
A new (sig, args) tuple is yielded.
"""
newtys = []
newargs = []
copies = []
for ty, val in zip(sig.args, args):
if not isinstance(ty, types.Array) or ty.layout in 'CF':
newty, newval = ty, val
else:
newty = ty.copy(layout='C')
copysig = signature(newty, ty)
newval = array_copy(context, builder, copysig, (val,))
copies.append((newty, newval))
newtys.append(newty)
newargs.append(newval)
yield signature(sig.return_type, *newtys), tuple(newargs)
for ty, val in copies:
context.nrt.decref(builder, ty, val)
def check_c_int(context, builder, n):
"""
Check whether *n* fits in a C `int`.
"""
_maxint = 2**31 - 1
def impl(n):
if n > _maxint:
raise OverflowError("array size too large to fit in C int")
context.compile_internal(builder, impl,
signature(types.none, types.intp), (n,))
def check_blas_return(context, builder, res):
"""
Check the integer error return from one of the BLAS wrappers in
_helperlib.c.
"""
with builder.if_then(cgutils.is_not_null(builder, res), likely=False):
# Those errors shouldn't happen, it's easier to just abort the process
pyapi = context.get_python_api(builder)
pyapi.gil_ensure()
pyapi.fatal_error("BLAS wrapper returned with an error")
def check_lapack_return(context, builder, res):
"""
Check the integer error return from one of the LAPACK wrappers in
_helperlib.c.
"""
with builder.if_then(cgutils.is_not_null(builder, res), likely=False):
# Those errors shouldn't happen, it's easier to just abort the process
pyapi = context.get_python_api(builder)
pyapi.gil_ensure()
pyapi.fatal_error("LAPACK wrapper returned with an error")
def call_xxdot(context, builder, conjugate, dtype,
n, a_data, b_data, out_data):
"""
Call the BLAS vector * vector product function for the given arguments.
"""
fnty = ir.FunctionType(ir.IntType(32),
[ll_char, ll_char, intp_t, # kind, conjugate, n
ll_void_p, ll_void_p, ll_void_p, # a, b, out
])
fn = cgutils.get_or_insert_function(builder.module, fnty, "numba_xxdot")
kind = get_blas_kind(dtype)
kind_val = ir.Constant(ll_char, ord(kind))
conjugate = ir.Constant(ll_char, int(conjugate))
res = builder.call(fn, (kind_val, conjugate, n,
builder.bitcast(a_data, ll_void_p),
builder.bitcast(b_data, ll_void_p),
builder.bitcast(out_data, ll_void_p)))
check_blas_return(context, builder, res)
def call_xxgemv(context, builder, do_trans,
m_type, m_shapes, m_data, v_data, out_data):
"""
Call the BLAS matrix * vector product function for the given arguments.
"""
fnty = ir.FunctionType(ir.IntType(32),
[ll_char, ll_char, # kind, trans
intp_t, intp_t, # m, n
ll_void_p, ll_void_p, intp_t, # alpha, a, lda
ll_void_p, ll_void_p, ll_void_p, # x, beta, y
])
fn = cgutils.get_or_insert_function(builder.module, fnty, "numba_xxgemv")
dtype = m_type.dtype
alpha = make_constant_slot(context, builder, dtype, 1.0)
beta = make_constant_slot(context, builder, dtype, 0.0)
if m_type.layout == 'F':
m, n = m_shapes
lda = m_shapes[0]
else:
n, m = m_shapes
lda = m_shapes[1]
kind = get_blas_kind(dtype)
kind_val = ir.Constant(ll_char, ord(kind))
trans = ir.Constant(ll_char, ord('t') if do_trans else ord('n'))
res = builder.call(fn, (kind_val, trans, m, n,
builder.bitcast(alpha, ll_void_p),
builder.bitcast(m_data, ll_void_p), lda,
builder.bitcast(v_data, ll_void_p),
builder.bitcast(beta, ll_void_p),
builder.bitcast(out_data, ll_void_p)))
check_blas_return(context, builder, res)
def call_xxgemm(context, builder,
x_type, x_shapes, x_data,
y_type, y_shapes, y_data,
out_type, out_shapes, out_data):
"""
Call the BLAS matrix * matrix product function for the given arguments.
"""
fnty = ir.FunctionType(ir.IntType(32),
[ll_char, # kind
ll_char, ll_char, # transa, transb
intp_t, intp_t, intp_t, # m, n, k
ll_void_p, ll_void_p, intp_t, # alpha, a, lda
ll_void_p, intp_t, ll_void_p, # b, ldb, beta
ll_void_p, intp_t, # c, ldc
])
fn = cgutils.get_or_insert_function(builder.module, fnty, "numba_xxgemm")
m, k = x_shapes
_k, n = y_shapes
dtype = x_type.dtype
alpha = make_constant_slot(context, builder, dtype, 1.0)
beta = make_constant_slot(context, builder, dtype, 0.0)
trans = ir.Constant(ll_char, ord('t'))
notrans = ir.Constant(ll_char, ord('n'))
def get_array_param(ty, shapes, data):
return (
# Transpose if layout different from result's
notrans if ty.layout == out_type.layout else trans,
# Size of the inner dimension in physical array order
shapes[1] if ty.layout == 'C' else shapes[0],
# The data pointer, unit-less
builder.bitcast(data, ll_void_p),
)
transa, lda, data_a = get_array_param(y_type, y_shapes, y_data)
transb, ldb, data_b = get_array_param(x_type, x_shapes, x_data)
_, ldc, data_c = get_array_param(out_type, out_shapes, out_data)
kind = get_blas_kind(dtype)
kind_val = ir.Constant(ll_char, ord(kind))
res = builder.call(fn, (kind_val, transa, transb, n, m, k,
builder.bitcast(alpha, ll_void_p), data_a, lda,
data_b, ldb, builder.bitcast(beta, ll_void_p),
data_c, ldc))
check_blas_return(context, builder, res)
def dot_2_mm(context, builder, sig, args):
"""
np.dot(matrix, matrix)
"""
def dot_impl(a, b):
m, k = a.shape
_k, n = b.shape
if k == 0:
return np.zeros((m, n), a.dtype)
out = np.empty((m, n), a.dtype)
return np.dot(a, b, out)
res = context.compile_internal(builder, dot_impl, sig, args)
return impl_ret_new_ref(context, builder, sig.return_type, res)
def dot_2_vm(context, builder, sig, args):
"""
np.dot(vector, matrix)
"""
def dot_impl(a, b):
m, = a.shape
_m, n = b.shape
if m == 0:
return np.zeros((n, ), a.dtype)
out = np.empty((n, ), a.dtype)
return np.dot(a, b, out)
res = context.compile_internal(builder, dot_impl, sig, args)
return impl_ret_new_ref(context, builder, sig.return_type, res)
def dot_2_mv(context, builder, sig, args):
"""
np.dot(matrix, vector)
"""
def dot_impl(a, b):
m, n = a.shape
_n, = b.shape
if n == 0:
return np.zeros((m, ), a.dtype)
out = np.empty((m, ), a.dtype)
return np.dot(a, b, out)
res = context.compile_internal(builder, dot_impl, sig, args)
return impl_ret_new_ref(context, builder, sig.return_type, res)
def dot_2_vv(context, builder, sig, args, conjugate=False):
"""
np.dot(vector, vector)
np.vdot(vector, vector)
"""
aty, bty = sig.args
dtype = sig.return_type
a = make_array(aty)(context, builder, args[0])
b = make_array(bty)(context, builder, args[1])
n, = cgutils.unpack_tuple(builder, a.shape)
def check_args(a, b):
m, = a.shape
n, = b.shape
if m != n:
raise ValueError("incompatible array sizes for np.dot(a, b) "
"(vector * vector)")
context.compile_internal(builder, check_args,
signature(types.none, *sig.args), args)
check_c_int(context, builder, n)
out = cgutils.alloca_once(builder, context.get_value_type(dtype))
call_xxdot(context, builder, conjugate, dtype, n, a.data, b.data, out)
return builder.load(out)
@overload(np.dot)
def dot_2(left, right):
"""
np.dot(a, b)
"""
return dot_2_impl('np.dot()', left, right)
@overload(operator.matmul)
def matmul_2(left, right):
"""
a @ b
"""
return dot_2_impl("'@'", left, right)
def dot_2_impl(name, left, right):
if isinstance(left, types.Array) and isinstance(right, types.Array):
@intrinsic
def _impl(typingcontext, left, right):
ndims = (left.ndim, right.ndim)
def _dot2_codegen(context, builder, sig, args):
ensure_blas()
with make_contiguous(context, builder, sig, args) as (sig, args):
if ndims == (2, 2):
return dot_2_mm(context, builder, sig, args)
elif ndims == (2, 1):
return dot_2_mv(context, builder, sig, args)
elif ndims == (1, 2):
return dot_2_vm(context, builder, sig, args)
elif ndims == (1, 1):
return dot_2_vv(context, builder, sig, args)
else:
raise AssertionError('unreachable')
if left.dtype != right.dtype:
raise TypingError(
"%s arguments must all have the same dtype" % name)
if ndims == (2, 2):
return_type = types.Array(left.dtype, 2, 'C')
elif ndims == (2, 1) or ndims == (1, 2):
return_type = types.Array(left.dtype, 1, 'C')
elif ndims == (1, 1):
return_type = left.dtype
else:
raise TypingError(("%s: inputs must have compatible "
"dimensions") % name)
return signature(return_type, left, right), _dot2_codegen
if left.layout not in 'CF' or right.layout not in 'CF':
warnings.warn(
"%s is faster on contiguous arrays, called on %s" % (
name, (left, right),), NumbaPerformanceWarning)
return lambda left, right: _impl(left, right)
@overload(np.vdot)
def vdot(left, right):
"""
np.vdot(a, b)
"""
if isinstance(left, types.Array) and isinstance(right, types.Array):
@intrinsic
def _impl(typingcontext, left, right):
def codegen(context, builder, sig, args):
ensure_blas()
with make_contiguous(context, builder, sig, args) as\
(sig, args):
return dot_2_vv(context, builder, sig, args, conjugate=True)
if left.ndim != 1 or right.ndim != 1:
raise TypingError("np.vdot() only supported on 1-D arrays")
if left.dtype != right.dtype:
raise TypingError(
"np.vdot() arguments must all have the same dtype")
return signature(left.dtype, left, right), codegen
if left.layout not in 'CF' or right.layout not in 'CF':
warnings.warn(
"np.vdot() is faster on contiguous arrays, called on %s"
% ((left, right),), NumbaPerformanceWarning)
return lambda left, right: _impl(left, right)
def dot_3_vm_check_args(a, b, out):
m, = a.shape
_m, n = b.shape
if m != _m:
raise ValueError("incompatible array sizes for "
"np.dot(a, b) (vector * matrix)")
if out.shape != (n,):
raise ValueError("incompatible output array size for "
"np.dot(a, b, out) (vector * matrix)")
def dot_3_mv_check_args(a, b, out):
m, _n = a.shape
n, = b.shape
if n != _n:
raise ValueError("incompatible array sizes for np.dot(a, b) "
"(matrix * vector)")
if out.shape != (m,):
raise ValueError("incompatible output array size for "
"np.dot(a, b, out) (matrix * vector)")
def dot_3_vm(context, builder, sig, args):
"""
np.dot(vector, matrix, out)
np.dot(matrix, vector, out)
"""
xty, yty, outty = sig.args
assert outty == sig.return_type
dtype = xty.dtype
x = make_array(xty)(context, builder, args[0])
y = make_array(yty)(context, builder, args[1])
out = make_array(outty)(context, builder, args[2])
x_shapes = cgutils.unpack_tuple(builder, x.shape)
y_shapes = cgutils.unpack_tuple(builder, y.shape)
out_shapes = cgutils.unpack_tuple(builder, out.shape)
if xty.ndim < yty.ndim:
# Vector * matrix
# Asked for x * y, we will compute y.T * x
mty = yty
m_shapes = y_shapes
v_shape = x_shapes[0]
lda = m_shapes[1]
do_trans = yty.layout == 'F'
m_data, v_data = y.data, x.data
check_args = dot_3_vm_check_args
else:
# Matrix * vector
# We will compute x * y
mty = xty
m_shapes = x_shapes
v_shape = y_shapes[0]
lda = m_shapes[0]
do_trans = xty.layout == 'C'
m_data, v_data = x.data, y.data
check_args = dot_3_mv_check_args
context.compile_internal(builder, check_args,
signature(types.none, *sig.args), args)
for val in m_shapes:
check_c_int(context, builder, val)
zero = context.get_constant(types.intp, 0)
both_empty = builder.icmp_signed('==', v_shape, zero)
matrix_empty = builder.icmp_signed('==', lda, zero)
is_empty = builder.or_(both_empty, matrix_empty)
with builder.if_else(is_empty, likely=False) as (empty, nonempty):
with empty:
cgutils.memset(builder, out.data,
builder.mul(out.itemsize, out.nitems), 0)
with nonempty:
call_xxgemv(context, builder, do_trans, mty, m_shapes, m_data,
v_data, out.data)
return impl_ret_borrowed(context, builder, sig.return_type,
out._getvalue())
def dot_3_mm(context, builder, sig, args):
"""
np.dot(matrix, matrix, out)
"""
xty, yty, outty = sig.args
assert outty == sig.return_type
dtype = xty.dtype
x = make_array(xty)(context, builder, args[0])
y = make_array(yty)(context, builder, args[1])
out = make_array(outty)(context, builder, args[2])
x_shapes = cgutils.unpack_tuple(builder, x.shape)
y_shapes = cgutils.unpack_tuple(builder, y.shape)
out_shapes = cgutils.unpack_tuple(builder, out.shape)
m, k = x_shapes
_k, n = y_shapes
# The only case Numpy supports
assert outty.layout == 'C'
def check_args(a, b, out):
m, k = a.shape
_k, n = b.shape
if k != _k:
raise ValueError("incompatible array sizes for np.dot(a, b) "
"(matrix * matrix)")
if out.shape != (m, n):
raise ValueError("incompatible output array size for "
"np.dot(a, b, out) (matrix * matrix)")
context.compile_internal(builder, check_args,
signature(types.none, *sig.args), args)
check_c_int(context, builder, m)
check_c_int(context, builder, k)
check_c_int(context, builder, n)
x_data = x.data
y_data = y.data
out_data = out.data
# If eliminated dimension is zero, set all entries to zero and return
zero = context.get_constant(types.intp, 0)
both_empty = builder.icmp_signed('==', k, zero)
x_empty = builder.icmp_signed('==', m, zero)
y_empty = builder.icmp_signed('==', n, zero)
is_empty = builder.or_(both_empty, builder.or_(x_empty, y_empty))
with builder.if_else(is_empty, likely=False) as (empty, nonempty):
with empty:
cgutils.memset(builder, out.data,
builder.mul(out.itemsize, out.nitems), 0)
with nonempty:
# Check if any of the operands is really a 1-d vector represented
# as a (1, k) or (k, 1) 2-d array. In those cases, it is pessimal
# to call the generic matrix * matrix product BLAS function.
one = context.get_constant(types.intp, 1)
is_left_vec = builder.icmp_signed('==', m, one)
is_right_vec = builder.icmp_signed('==', n, one)
with builder.if_else(is_right_vec) as (r_vec, r_mat):
with r_vec:
with builder.if_else(is_left_vec) as (v_v, m_v):
with v_v:
# V * V
call_xxdot(context, builder, False, dtype,
k, x_data, y_data, out_data)
with m_v:
# M * V
do_trans = xty.layout == outty.layout
call_xxgemv(context, builder, do_trans,
xty, x_shapes, x_data, y_data, out_data)
with r_mat:
with builder.if_else(is_left_vec) as (v_m, m_m):
with v_m:
# V * M
do_trans = yty.layout != outty.layout
call_xxgemv(context, builder, do_trans,
yty, y_shapes, y_data, x_data, out_data)
with m_m:
# M * M
call_xxgemm(context, builder,
xty, x_shapes, x_data,
yty, y_shapes, y_data,
outty, out_shapes, out_data)
return impl_ret_borrowed(context, builder, sig.return_type,
out._getvalue())
@overload(np.dot)
def dot_3(left, right, out):
"""
np.dot(a, b, out)
"""
if (isinstance(left, types.Array) and isinstance(right, types.Array) and
isinstance(out, types.Array)):
@intrinsic
def _impl(typingcontext, left, right, out):
def codegen(context, builder, sig, args):
ensure_blas()
with make_contiguous(context, builder, sig, args) as (sig,
args):
ndims = set(x.ndim for x in sig.args[:2])
if ndims == {2}:
return dot_3_mm(context, builder, sig, args)
elif ndims == {1, 2}:
return dot_3_vm(context, builder, sig, args)
else:
raise AssertionError('unreachable')
if left.dtype != right.dtype or left.dtype != out.dtype:
raise TypingError(
"np.dot() arguments must all have the same dtype")
return signature(out, left, right, out), codegen
if left.layout not in 'CF' or right.layout not in 'CF' or out.layout\
not in 'CF':
warnings.warn(
"np.vdot() is faster on contiguous arrays, called on %s"
% ((left, right),), NumbaPerformanceWarning)
return lambda left, right, out: _impl(left, right, out)
if config.USE_LEGACY_TYPE_SYSTEM:
fatal_error_func = types.ExternalFunction("numba_fatal_error", types.intc())
else:
fatal_error_func = types.ExternalFunction("numba_fatal_error", types.c_intp())
@register_jitable
def _check_finite_matrix(a):
for v in np.nditer(a):
if not np.isfinite(v.item()):
raise np.linalg.LinAlgError(
"Array must not contain infs or NaNs.")
def _check_linalg_matrix(a, func_name, la_prefix=True):
# la_prefix is present as some functions, e.g. np.trace()
# are documented under "linear algebra" but aren't in the
# module
prefix = "np.linalg" if la_prefix else "np"
interp = (prefix, func_name)
# Unpack optional type
if isinstance(a, types.Optional):
a = a.type
if not isinstance(a, types.Array):
msg = "%s.%s() only supported for array types" % interp
raise TypingError(msg, highlighting=False)
if not a.ndim == 2:
msg = "%s.%s() only supported on 2-D arrays." % interp
raise TypingError(msg, highlighting=False)
if not isinstance(a.dtype, (types.Float, types.Complex)):
msg = "%s.%s() only supported on "\
"float and complex arrays." % interp
raise TypingError(msg, highlighting=False)
def _check_homogeneous_types(func_name, *types):
t0 = types[0].dtype
for t in types[1:]:
if t.dtype != t0:
msg = "np.linalg.%s() only supports inputs that have homogeneous dtypes." % func_name
raise TypingError(msg, highlighting=False)
def _copy_to_fortran_order():
pass
@overload(_copy_to_fortran_order)
def ol_copy_to_fortran_order(a):
# This function copies the array 'a' into a new array with fortran order.
# This exists because the copy routines don't take order flags yet.
F_layout = a.layout == 'F'
A_layout = a.layout == 'A'
def impl(a):
if F_layout:
# it's F ordered at compile time, just copy
acpy = np.copy(a)
elif A_layout:
# decide based on runtime value
flag_f = a.flags.f_contiguous
if flag_f:
# it's already F ordered, so copy but in a round about way to
# ensure that the copy is also F ordered
acpy = np.copy(a.T).T
else:
# it's something else ordered, so let asfortranarray deal with
# copying and making it fortran ordered
acpy = np.asfortranarray(a)
else:
# it's C ordered at compile time, asfortranarray it.
acpy = np.asfortranarray(a)
return acpy
return impl
@register_jitable
def _inv_err_handler(r):
if r != 0:
if r < 0:
fatal_error_func()
assert 0 # unreachable
if r > 0:
raise np.linalg.LinAlgError(
"Matrix is singular to machine precision.")
@register_jitable
def _dummy_liveness_func(a):
"""pass a list of variables to be preserved through dead code elimination"""
return a[0]
@overload(np.linalg.inv)
def inv_impl(a):
ensure_lapack()
_check_linalg_matrix(a, "inv")
numba_xxgetrf = _LAPACK().numba_xxgetrf(a.dtype)
numba_xxgetri = _LAPACK().numba_ez_xxgetri(a.dtype)
kind = ord(get_blas_kind(a.dtype, "inv"))
def inv_impl(a):
n = a.shape[-1]
if a.shape[-2] != n:
msg = "Last 2 dimensions of the array must be square."
raise np.linalg.LinAlgError(msg)
_check_finite_matrix(a)
acpy = _copy_to_fortran_order(a)
if n == 0:
return acpy
ipiv = np.empty(n, dtype=F_INT_nptype)
r = numba_xxgetrf(kind, n, n, acpy.ctypes, n, ipiv.ctypes)
_inv_err_handler(r)
r = numba_xxgetri(kind, n, acpy.ctypes, n, ipiv.ctypes)
_inv_err_handler(r)
# help liveness analysis
_dummy_liveness_func([acpy.size, ipiv.size])
return acpy
return inv_impl
@register_jitable
def _handle_err_maybe_convergence_problem(r):
if r != 0:
if r < 0:
fatal_error_func()
assert 0 # unreachable
if r > 0:
raise ValueError("Internal algorithm failed to converge.")
def _check_linalg_1_or_2d_matrix(a, func_name, la_prefix=True):
# la_prefix is present as some functions, e.g. np.trace()
# are documented under "linear algebra" but aren't in the
# module
prefix = "np.linalg" if la_prefix else "np"
interp = (prefix, func_name)
# checks that a matrix is 1 or 2D
if not isinstance(a, types.Array):
raise TypingError("%s.%s() only supported for array types "
% interp)
if not a.ndim <= 2:
raise TypingError("%s.%s() only supported on 1 and 2-D arrays "
% interp)
if not isinstance(a.dtype, (types.Float, types.Complex)):
raise TypingError("%s.%s() only supported on "
"float and complex arrays." % interp)
@overload(np.linalg.cholesky)
def cho_impl(a):
ensure_lapack()
_check_linalg_matrix(a, "cholesky")
numba_xxpotrf = _LAPACK().numba_xxpotrf(a.dtype)
kind = ord(get_blas_kind(a.dtype, "cholesky"))
UP = ord('U')
LO = ord('L')