-
Notifications
You must be signed in to change notification settings - Fork 19.7k
Expand file tree
/
Copy pathnumpy.py
More file actions
3611 lines (2967 loc) · 109 KB
/
numpy.py
File metadata and controls
3611 lines (2967 loc) · 109 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
import builtins
import collections
import functools
import math
import string
import warnings
import numpy as np
import tensorflow as tf
from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops
from tensorflow.python.ops.math_ops import is_nan
from keras.src import tree
from keras.src.backend import config
from keras.src.backend import standardize_dtype
from keras.src.backend.common import dtypes
from keras.src.backend.common.backend_utils import canonicalize_axis
from keras.src.backend.common.backend_utils import to_tuple_or_list
from keras.src.backend.common.backend_utils import vectorize_impl
from keras.src.backend.tensorflow import sparse
from keras.src.backend.tensorflow.core import cast
from keras.src.backend.tensorflow.core import convert_to_tensor
from keras.src.backend.tensorflow.core import shape as shape_op
def rot90(array, k=1, axes=(0, 1)):
"""Rotate an array by 90 degrees in the specified plane.
Args:
array: Input tensor
k: Number of 90-degree rotations (default=1)
axes: Tuple of two axes that define the plane of rotation.
Defaults to (0, 1).
Returns:
Rotated tensor with correct shape transformation
"""
array = convert_to_tensor(array)
if array.shape.rank < 2:
raise ValueError(
f"Input array must have at least 2 dimensions. "
f"Received: array.ndim={array.shape.rank}"
)
if len(axes) != 2 or axes[0] == axes[1]:
raise ValueError(
f"Invalid axes: {axes}. Axes must be a tuple of "
"two different dimensions."
)
k = k % 4
if k == 0:
return array
axes = tuple(
axis if axis >= 0 else array.shape.rank + axis for axis in axes
)
perm = [i for i in range(array.shape.rank) if i not in axes]
perm.extend(axes)
array = tf.transpose(array, perm)
shape = tf.shape(array)
non_rot_shape = shape[:-2]
h, w = shape[-2], shape[-1]
array = tf.reshape(array, tf.concat([[-1], [h, w]], axis=0))
array = tf.reverse(array, axis=[2])
array = tf.transpose(array, [0, 2, 1])
if k % 2 == 1:
final_h, final_w = w, h
else:
final_h, final_w = h, w
if k > 1:
array = tf.reshape(array, tf.concat([[-1], [final_h, final_w]], axis=0))
for _ in range(k - 1):
array = tf.reverse(array, axis=[2])
array = tf.transpose(array, [0, 2, 1])
final_shape = tf.concat([non_rot_shape, [final_h, final_w]], axis=0)
array = tf.reshape(array, final_shape)
inv_perm = [0] * len(perm)
for i, p in enumerate(perm):
inv_perm[p] = i
array = tf.transpose(array, inv_perm)
return array
@sparse.elementwise_binary_union(tf.sparse.add)
def add(x1, x2):
if not isinstance(x1, (int, float)):
x1 = convert_to_tensor(x1)
if not isinstance(x2, (int, float)):
x2 = convert_to_tensor(x2)
dtype = dtypes.result_type(
getattr(x1, "dtype", type(x1)),
getattr(x2, "dtype", type(x2)),
)
x1 = convert_to_tensor(x1, dtype)
x2 = convert_to_tensor(x2, dtype)
# Special case of `tf.add`: `tf.nn.bias_add`
# `BiasAdd` can be fused with `MatMul` and `Conv*` kernels
# Expecting `x1` to be `inputs` and `x2` to be `bias` (no swapping)
x2_squeeze_shape = [d for d in x2.shape.as_list() if d is None or d > 1]
if (
# `x2` looks like bias (can be squeezed to vector)
1 == len(x2_squeeze_shape)
# `x1` looks like input tensor (rank >= 2)
and len(x1.shape) > 1
# `x2` non-squeezable dimension defined
and x2_squeeze_shape[0] is not None
# `x2` non-squeezable dimension match `x1` channel dimension
and x2_squeeze_shape[0]
in {x1.shape.as_list()[1], x1.shape.as_list()[-1]}
):
if x1.shape[-1] == x2_squeeze_shape[0]:
data_format = "NHWC"
else:
data_format = "NCHW"
if len(x2.shape) > 1:
x2 = tf.squeeze(x2)
return tf.nn.bias_add(x1, x2, data_format=data_format)
return tf.add(x1, x2)
def bartlett(x):
x = convert_to_tensor(x, dtype=config.floatx())
if x == 0:
return tf.constant([])
if x == 1:
return tf.ones([1])
n = tf.range(x)
half = (x - 1) / 2
window = tf.where(n <= half, 2.0 * n / (x - 1), 2.0 - 2.0 * n / (x - 1))
return window
def hamming(x):
x = convert_to_tensor(x, dtype=tf.int32)
return tf.signal.hamming_window(x, periodic=False)
def hanning(x):
x = convert_to_tensor(x, dtype=tf.int32)
return tf.signal.hann_window(x, periodic=False)
def heaviside(x1, x2):
x1 = convert_to_tensor(x1)
x2 = convert_to_tensor(x2)
dtype = dtypes.result_type(x1.dtype, x2.dtype)
if dtype in ["int8", "int16", "int32", "uint8", "uint16", "uint32"]:
dtype = config.floatx()
elif dtype in ["int64"]:
dtype = "float64"
x1 = tf.cast(x1, dtype)
x2 = tf.cast(x2, dtype)
return tf.where(
x1 < 0,
tf.zeros_like(x1),
tf.where(x1 > 0, tf.ones_like(x1), x2),
)
def kaiser(x, beta):
x = convert_to_tensor(x, dtype=tf.int32)
return tf.signal.kaiser_window(x, beta=beta)
def bincount(x, weights=None, minlength=0, sparse=False):
x = convert_to_tensor(x)
dtypes_to_resolve = [x.dtype]
if standardize_dtype(x.dtype) not in ["int32", "int64"]:
x = tf.cast(x, tf.int32)
if weights is not None:
weights = convert_to_tensor(weights)
dtypes_to_resolve.append(weights.dtype)
dtype = dtypes.result_type(*dtypes_to_resolve)
if standardize_dtype(weights.dtype) not in [
"int32",
"int64",
"float32",
"float64",
]:
if "int" in standardize_dtype(weights.dtype):
weights = tf.cast(weights, tf.int32)
else:
weights = tf.cast(weights, tf.float32)
else:
dtype = "int32"
if sparse or isinstance(x, tf.SparseTensor):
output = tf.sparse.bincount(
x,
weights=weights,
minlength=minlength,
axis=-1,
)
actual_length = output.shape[-1]
if actual_length is None:
actual_length = tf.shape(output)[-1]
output = cast(output, dtype)
if x.shape.rank == 1:
output_shape = (actual_length,)
else:
batch_size = output.shape[0]
if batch_size is None:
batch_size = tf.shape(output)[0]
output_shape = (batch_size, actual_length)
return tf.SparseTensor(
indices=output.indices,
values=output.values,
dense_shape=output_shape,
)
return tf.cast(
tf.math.bincount(x, weights=weights, minlength=minlength, axis=-1),
dtype,
)
@functools.lru_cache(512)
def _normalize_einsum_subscripts(subscripts):
# string.ascii_letters
mapping = {}
normalized_subscripts = ""
for c in subscripts:
if c in string.ascii_letters:
if c not in mapping:
mapping[c] = string.ascii_letters[len(mapping)]
normalized_subscripts += mapping[c]
else:
normalized_subscripts += c
return normalized_subscripts
def einsum(subscripts, *operands, **kwargs):
operands = tree.map_structure(convert_to_tensor, operands)
subscripts = _normalize_einsum_subscripts(subscripts)
def is_valid_for_custom_ops(subscripts, *operands):
# Check that `subscripts` is supported and the shape of operands is not
# `None`.
if subscripts in [
"a,b->ab",
"ab,b->a",
"ab,bc->ac",
"ab,cb->ac",
"abc,cd->abd",
"abc,dc->abd",
"abcd,abde->abce",
"abcd,abed->abce",
"abcd,acbe->adbe",
"abcd,adbe->acbe",
"abcd,aecd->acbe",
"abcd,aecd->aceb",
]:
# These subscripts don't require the shape information
return True
elif subscripts == "abc,cde->abde":
_, b1, c1 = operands[0].shape
c2, d2, e2 = operands[1].shape
b, c, d, e = b1, c1 or c2, d2, e2
if None in (b, c, d, e):
return False
return True
elif subscripts == "abc,dce->abde":
_, b1, c1 = operands[0].shape
d2, c2, e2 = operands[1].shape
b, c, d, e = b1, c1 or c2, d2, e2
if None in (b, c, d, e):
return False
return True
elif subscripts == "abc,dec->abde":
_, b1, c1 = operands[0].shape
d2, e2, c2 = operands[1].shape
b, c, d, e = b1, c1 or c2, d2, e2
if None in (b, c, d, e):
return False
return True
elif subscripts == "abcd,cde->abe":
_, b1, c1, d1 = operands[0].shape
c2, d2, e2 = operands[1].shape
b, c, d, e = b1, c1 or c2, d1 or d2, e2
if None in (b, c, d, e):
return False
return True
elif subscripts == "abcd,ced->abe":
_, b1, c1, d1 = operands[0].shape
c2, e2, d2 = operands[1].shape
b, c, d, e = b1, c1 or c2, d1 or d2, e2
if None in (b, c, d, e):
return False
return True
elif subscripts == "abcd,ecd->abe":
_, b1, c1, d1 = operands[0].shape
e2, c2, d2 = operands[1].shape
b, c, d, e = b1, c1 or c2, d1 or d2, e2
if None in (b, c, d, e):
return False
return True
elif subscripts == "abcde,aebf->adbcf":
_, b1, c1, d1, e1 = operands[0].shape
_, e2, b2, f2 = operands[1].shape
b, c, d, e, f = b1 or b2, c1, d1, e1 or e2, f2
if None in (b, c, d, e, f):
return False
return True
elif subscripts == "abcde,afce->acdbf":
_, b1, c1, d1, e1 = operands[0].shape
_, f2, c2, e2 = operands[1].shape
b, c, d, e, f = b1, c1 or c2, d1, e1 or e2, f2
if None in (b, c, d, e, f):
return False
return True
else:
# No match in subscripts
return False
def use_custom_ops(subscripts, *operands, output_type):
# Replace tf.einsum with custom ops to utilize hardware-accelerated
# matmul
x, y = operands[0], operands[1]
if subscripts == "a,b->ab":
x = tf.expand_dims(x, axis=-1)
y = tf.expand_dims(y, axis=0)
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "ab,b->a":
y = tf.expand_dims(y, axis=-1)
result = tf.matmul(x, y, output_type=output_type)
return tf.squeeze(result, axis=-1)
elif subscripts == "ab,bc->ac":
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "ab,cb->ac":
y = tf.transpose(y, [1, 0])
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "abc,cd->abd":
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "abc,cde->abde":
_, b1, c1 = x.shape
c2, d2, e2 = y.shape
b, c, d, e = b1, c1 or c2, d2, e2
y = tf.reshape(y, [c, -1])
result = tf.matmul(x, y, output_type=output_type)
return tf.reshape(result, [-1, b, d, e])
elif subscripts == "abc,dc->abd":
y = tf.transpose(y, [1, 0])
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "abc,dce->abde":
_, b1, c1 = x.shape
d2, c2, e2 = y.shape
b, c, d, e = b1, c1 or c2, d2, e2
y = tf.transpose(y, [1, 0, 2]) # cde
y = tf.reshape(y, [c, -1])
result = tf.matmul(x, y, output_type=output_type)
return tf.reshape(result, [-1, b, d, e])
elif subscripts == "abc,dec->abde":
_, b1, c1 = x.shape
d2, e2, c2 = y.shape
b, c, d, e = b1, c1 or c2, d2, e2
y = tf.transpose(y, [2, 0, 1]) # cde
y = tf.reshape(y, [c, -1])
result = tf.matmul(x, y, output_type=output_type)
return tf.reshape(result, [-1, b, d, e])
elif subscripts == "abcd,abde->abce":
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "abcd,abed->abce":
y = tf.transpose(y, [0, 1, 3, 2])
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "abcd,acbe->adbe":
x = tf.transpose(x, [0, 1, 3, 2])
y = tf.transpose(y, [0, 2, 1, 3])
result = tf.matmul(x, y, output_type=output_type)
return tf.transpose(result, [0, 2, 1, 3])
elif subscripts == "abcd,adbe->acbe":
y = tf.transpose(y, [0, 2, 1, 3]) # abde
result = tf.matmul(x, y, output_type=output_type) # abce
return tf.transpose(result, [0, 2, 1, 3])
elif subscripts == "abcd,aecd->acbe":
x = tf.transpose(x, [0, 2, 1, 3]) # acbd
y = tf.transpose(y, [0, 2, 3, 1]) # acde
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "abcd,aecd->aceb":
x = tf.transpose(x, [0, 2, 1, 3])
y = tf.transpose(y, [0, 2, 3, 1])
result = tf.matmul(x, y, output_type=output_type) # acbe
return tf.transpose(result, [0, 1, 3, 2])
elif subscripts == "abcd,cde->abe":
_, b1, c1, d1 = x.shape
c2, d2, e2 = y.shape
b, c, d, e = b1, c1 or c2, d1 or d2, e2
x = tf.reshape(x, [-1, b, c * d])
y = tf.reshape(y, [-1, e])
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "abcd,ced->abe":
_, b1, c1, d1 = x.shape
c2, e2, d2 = y.shape
b, c, d, e = b1, c1 or c2, d1 or d2, e2
x = tf.reshape(x, [-1, b, c * d])
y = tf.transpose(y, [0, 2, 1])
y = tf.reshape(y, [-1, e])
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "abcd,ecd->abe":
_, b1, c1, d1 = x.shape
e2, c2, d2 = y.shape
b, c, d, e = b1, c1 or c2, d1 or d2, e2
x = tf.reshape(x, [-1, b, c * d])
y = tf.transpose(y, [1, 2, 0])
y = tf.reshape(y, [-1, e])
return tf.matmul(x, y, output_type=output_type)
elif subscripts == "abcde,aebf->adbcf":
_, b1, c1, d1, e1 = x.shape
_, e2, b2, f2 = y.shape
b, c, d, e, f = b1 or b2, c1, d1, e1 or e2, f2
x = tf.reshape(x, [-1, b, c * d, e]) # ab(cd)e
y = tf.transpose(y, [0, 2, 1, 3]) # abef
result = tf.matmul(x, y, output_type=output_type) # ab(cd)f
result = tf.reshape(result, [-1, b, c, d, f]) # abcdf
return tf.transpose(result, [0, 3, 1, 2, 4])
elif subscripts == "abcde,afce->acdbf":
_, b1, c1, d1, e1 = x.shape
_, f2, c2, e2 = y.shape
b, c, d, e, f = b1, c1 or c2, d1, e1 or e2, f2
x = tf.transpose(x, [0, 2, 3, 1, 4]) # acdbe
x = tf.reshape(x, [-1, c, d * b, e]) # ac(db)e
y = tf.transpose(y, [0, 2, 3, 1]) # acef
result = tf.matmul(x, y, output_type=output_type) # ac(db)f
return tf.reshape(result, [-1, c, d, b, f])
else:
raise NotImplementedError
dtypes_to_resolve = list(set(standardize_dtype(x.dtype) for x in operands))
# When operands are of int8, we cast the result to int32 to align with
# the behavior of jax.
if len(dtypes_to_resolve) == 1 and dtypes_to_resolve[0] == "int8":
compute_dtype = "int8"
result_dtype = "int32"
output_type = "int32"
else:
result_dtype = dtypes.result_type(*dtypes_to_resolve)
compute_dtype = result_dtype
output_type = None
# TODO: Remove the condition once `tf.einsum` supports int8xint8->int32
if is_valid_for_custom_ops(subscripts, *operands) and not kwargs:
# TODO: tf.matmul doesn't support integer dtype if not specifying
# output_type="int32"
if "int" in compute_dtype and output_type is None:
compute_dtype = config.floatx()
operands = tree.map_structure(
lambda x: tf.cast(x, compute_dtype), operands
)
result = use_custom_ops(subscripts, *operands, output_type=output_type)
else:
# TODO: tf.einsum doesn't support integer dtype with gpu
if "int" in compute_dtype:
compute_dtype = config.floatx()
operands = tree.map_structure(
lambda x: tf.cast(x, compute_dtype), operands
)
result = tf.einsum(subscripts, *operands, **kwargs)
return tf.cast(result, result_dtype)
@sparse.elementwise_binary_union(sparse.sparse_subtract)
def subtract(x1, x2):
if not isinstance(x1, (int, float)):
x1 = convert_to_tensor(x1)
if not isinstance(x2, (int, float)):
x2 = convert_to_tensor(x2)
dtype = dtypes.result_type(
getattr(x1, "dtype", type(x1)),
getattr(x2, "dtype", type(x2)),
)
x1 = convert_to_tensor(x1, dtype)
x2 = convert_to_tensor(x2, dtype)
return tf.subtract(x1, x2)
def matmul(x1, x2):
x1 = convert_to_tensor(x1)
x2 = convert_to_tensor(x2)
x1_shape = x1.shape
x2_shape = x2.shape
x1_sparse = isinstance(x1, tf.SparseTensor)
x2_sparse = isinstance(x2, tf.SparseTensor)
# When both x1 and x2 are of int8 and dense tensor, specifying `output_type`
# as int32 to enable hardware-accelerated matmul
x1_dtype = standardize_dtype(x1.dtype)
x2_dtype = standardize_dtype(x2.dtype)
if (
x1_dtype == "int8"
and x2_dtype == "int8"
and not x1_sparse
and not x2_sparse
and x1_shape.rank != 1 # TODO: support tf.tensordot
and x2_shape.rank != 1 # TODO: support tf.tensordot
):
compute_dtype = "int8"
result_dtype = "int32"
output_type = result_dtype
else:
# TODO: Typically, GPU and XLA only support float types
compute_dtype = dtypes.result_type(x1.dtype, x2.dtype, float)
result_dtype = dtypes.result_type(x1.dtype, x2.dtype)
output_type = None
x1 = tf.cast(x1, compute_dtype)
x2 = tf.cast(x2, compute_dtype)
def with_combined_batch_dimensions(a, b, output_shape, fn_3d):
a_sparse = isinstance(a, tf.SparseTensor)
b_sparse = isinstance(b, tf.SparseTensor)
batch_shape = b.shape[:-2] if b_sparse else a.shape[:-2]
batch_size = math.prod(batch_shape)
a3d_shape = [batch_size] + a.shape[-2:]
a_3d = (
tf.sparse.reshape(a, a3d_shape)
if a_sparse
else tf.reshape(a, a3d_shape)
)
b3d_shape = [batch_size] + b.shape[-2:]
b_3d = (
tf.sparse.reshape(b, b3d_shape)
if b_sparse
else tf.reshape(b, b3d_shape)
)
result_3d = fn_3d(a_3d, b_3d)
return (
tf.sparse.reshape(result_3d, output_shape)
if isinstance(result_3d, tf.SparseTensor)
else tf.reshape(result_3d, output_shape)
)
def sparse_sparse_matmul(a, b):
dtype = a.values.dtype
# Convert SparseTensors to CSR SparseMatrix.
a_csr = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
a.indices, a.values, a.dense_shape
)
b_csr = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
b.indices, b.values, b.dense_shape
)
# Compute the CSR SparseMatrix matrix multiplication.
result_csr = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul(
a_csr, b_csr, dtype
)
# Convert the CSR SparseMatrix to a SparseTensor.
res = sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor(
result_csr, dtype
)
return tf.SparseTensor(res.indices, res.values, res.dense_shape)
def embedding_lookup_sparse_dense_matmul(a, b):
# We need at least one id per rows for embedding_lookup_sparse,
# otherwise there will be missing rows in the output.
a, _ = tf.sparse.fill_empty_rows(a, 0)
# We need to split x1 into separate ids and weights tensors. The ids
# should be the column indices of x1 and the values of the weights
# can continue to be the actual x1. The column arrangement of ids
# and weights does not matter as we sum over columns. See details in
# the documentation for sparse_ops.sparse_tensor_dense_matmul.
ids = tf.SparseTensor(
indices=a.indices,
values=a.indices[:, 1],
dense_shape=a.dense_shape,
)
return tf.nn.embedding_lookup_sparse(b, ids, a, combiner="sum")
# Either a or b is sparse
def sparse_dense_matmul_3d(a, b):
return tf.map_fn(
lambda x: tf.sparse.sparse_dense_matmul(x[0], x[1]),
elems=(a, b),
fn_output_signature=a.dtype,
)
if x1_sparse or x2_sparse:
from keras.src.ops.operation_utils import compute_matmul_output_shape
output_shape = compute_matmul_output_shape(x1_shape, x2_shape)
if x1_sparse and x2_sparse:
if x1_shape.rank <= 3:
output = sparse_sparse_matmul(x1, x2)
else:
output = with_combined_batch_dimensions(
x1, x2, output_shape, sparse_sparse_matmul
)
else:
# Sparse * dense or dense * sparse
sparse_rank = x1_shape.rank if x1_sparse else x2_shape.rank
# Special case: embedding_lookup_sparse for sparse * dense, rank 2
if x1_sparse and sparse_rank == 2:
output = embedding_lookup_sparse_dense_matmul(x1, x2)
elif sparse_rank == 2:
output = tf.sparse.sparse_dense_matmul(x1, x2)
elif sparse_rank == 3:
output = sparse_dense_matmul_3d(x1, x2)
else:
output = with_combined_batch_dimensions(
x1, x2, output_shape, sparse_dense_matmul_3d
)
output = tf.cast(output, result_dtype)
output.set_shape(output_shape)
return output
else:
if x1_shape.rank == 2 and x2_shape.rank == 2:
output = tf.matmul(x1, x2, output_type=output_type)
elif x2_shape.rank == 1:
output = tf.tensordot(x1, x2, axes=1)
elif x1_shape.rank == 1:
output = tf.tensordot(x1, x2, axes=[[0], [-2]])
else:
output = tf.matmul(x1, x2, output_type=output_type)
return tf.cast(output, result_dtype)
@sparse.elementwise_binary_intersection
def multiply(x1, x2):
if not isinstance(x1, (int, float)):
x1 = convert_to_tensor(x1)
if not isinstance(x2, (int, float)):
x2 = convert_to_tensor(x2)
dtype = dtypes.result_type(
getattr(x1, "dtype", type(x1)),
getattr(x2, "dtype", type(x2)),
)
x1 = convert_to_tensor(x1, dtype)
x2 = convert_to_tensor(x2, dtype)
return tf.multiply(x1, x2)
def mean(x, axis=None, keepdims=False):
if isinstance(x, tf.IndexedSlices):
if axis is None:
# Reduce against all axes, result is a single value and dense.
# The denominator has to account for `dense_shape`.
sum = tf.reduce_sum(x.values, keepdims=keepdims)
return sum / tf.cast(tf.reduce_prod(x.dense_shape), dtype=sum.dtype)
axis = to_tuple_or_list(axis)
if not axis:
# Empty axis tuple, this is a no-op
return x
dense_shape = tf.convert_to_tensor(x.dense_shape)
rank = tf.shape(dense_shape)[0]
# Normalize axis: convert negative values and sort
axis = [canonicalize_axis(a, rank) for a in axis]
axis.sort()
if axis == [0]:
# Reduce against `axis=0` only, result is dense.
# The denominator has to account for `dense_shape[0]`.
sum = tf.reduce_sum(x.values, axis=0, keepdims=keepdims)
return sum / tf.cast(dense_shape[0], dtype=sum.dtype)
elif axis[0] == 0:
# Reduce against axis 0 and other axes, result is dense.
# We do `axis=0` separately first. The denominator has to account
# for `dense_shape[0]`.
# We use `keepdims=True` in `reduce_sum`` so that we can leave the
# 0 in axis and do `reduce_mean` with `keepdims` to apply it for all
# axes.
sum = tf.reduce_sum(x.values, axis=0, keepdims=True)
axis_0_mean = sum / tf.cast(dense_shape[0], dtype=sum.dtype)
return tf.reduce_mean(axis_0_mean, axis=axis, keepdims=keepdims)
elif keepdims:
# With `keepdims=True`, result is an `IndexedSlices` with the same
# indices since axis 0 is not touched. The only thing to do is to
# correct `dense_shape` to account for dimensions that became 1.
new_values = tf.reduce_mean(x.values, axis=axis, keepdims=True)
new_dense_shape = tf.concat(
[dense_shape[0:1], new_values.shape[1:]], axis=0
)
return tf.IndexedSlices(new_values, x.indices, new_dense_shape)
elif rank == len(axis) + 1:
# `keepdims=False` and reducing against all axes except 0, result is
# a 1D tensor, which cannot be `IndexedSlices`. We have to scatter
# the computed means to construct the correct dense tensor.
return tf.scatter_nd(
tf.expand_dims(x.indices, axis=1),
tf.reduce_mean(x.values, axis=axis),
[dense_shape[0]],
)
else:
# `keepdims=False`, not reducing against axis 0 and there is at
# least one other axis we are not reducing against. We simply need
# to fix `dense_shape` to remove dimensions that were reduced.
gather_indices = [i for i in range(rank) if i not in axis]
return tf.IndexedSlices(
tf.reduce_mean(x.values, axis=axis),
x.indices,
tf.gather(x.dense_shape, gather_indices, axis=0),
)
x = convert_to_tensor(x)
ori_dtype = standardize_dtype(x.dtype)
compute_dtype = dtypes.result_type(x.dtype, "float32")
# `tf.reduce_mean` does not handle low precision (e.g., float16) overflow
# correctly, so we compute with float32 and cast back to the original type.
if "int" in ori_dtype or ori_dtype == "bool":
result_dtype = compute_dtype
else:
result_dtype = ori_dtype
output = tf.reduce_mean(
tf.cast(x, compute_dtype), axis=axis, keepdims=keepdims
)
return tf.cast(output, result_dtype)
def max(x, axis=None, keepdims=False, initial=None):
x = convert_to_tensor(x)
# The TensorFlow numpy API implementation doesn't support `initial` so we
# handle it manually here.
if initial is not None:
if standardize_dtype(x.dtype) == "bool":
x = tf.reduce_any(x, axis=axis, keepdims=keepdims)
x = tf.math.maximum(tf.cast(x, "int32"), tf.cast(initial, "int32"))
return tf.cast(x, "bool")
else:
x = tf.reduce_max(x, axis=axis, keepdims=keepdims)
return tf.math.maximum(x, initial)
# TensorFlow returns -inf by default for an empty list, but for consistency
# with other backends and the numpy API we want to throw in this case.
if tf.executing_eagerly():
size_x = size(x)
tf.assert_greater(
size_x,
tf.constant(0, dtype=size_x.dtype),
message="Cannot compute the max of an empty tensor.",
)
if standardize_dtype(x.dtype) == "bool":
return tf.reduce_any(x, axis=axis, keepdims=keepdims)
else:
return tf.reduce_max(x, axis=axis, keepdims=keepdims)
def ones(shape, dtype=None):
dtype = dtype or config.floatx()
return tf.ones(shape, dtype=dtype)
def zeros(shape, dtype=None):
dtype = dtype or config.floatx()
return tf.zeros(shape, dtype=dtype)
@sparse.elementwise_unary
def absolute(x):
x = convert_to_tensor(x)
# uintx and bool are always non-negative
dtype = standardize_dtype(x.dtype)
if "uint" in dtype or dtype == "bool":
return x
return tf.abs(x)
def abs(x):
return absolute(x)
def all(x, axis=None, keepdims=False):
x = tf.cast(x, "bool")
return tf.reduce_all(x, axis=axis, keepdims=keepdims)
def angle(x):
x = convert_to_tensor(x)
if standardize_dtype(x.dtype) == "int64":
dtype = config.floatx()
else:
dtype = dtypes.result_type(x.dtype, float)
x = tf.cast(x, dtype)
return tf.math.angle(x)
def any(x, axis=None, keepdims=False):
x = tf.cast(x, "bool")
return tf.reduce_any(x, axis=axis, keepdims=keepdims)
def amax(x, axis=None, keepdims=False):
return max(x, axis=axis, keepdims=keepdims)
def amin(x, axis=None, keepdims=False):
return min(x, axis=axis, keepdims=keepdims)
def append(x1, x2, axis=None):
x1 = convert_to_tensor(x1)
x2 = convert_to_tensor(x2)
dtype = dtypes.result_type(x1.dtype, x2.dtype)
x1 = tf.cast(x1, dtype)
x2 = tf.cast(x2, dtype)
if axis is None:
return tf.concat([tf.reshape(x1, [-1]), tf.reshape(x2, [-1])], axis=0)
else:
return tf.concat([x1, x2], axis=axis)
def arange(start, stop=None, step=None, dtype=None):
if dtype is None:
dtypes_to_resolve = [getattr(start, "dtype", type(start))]
if stop is not None:
dtypes_to_resolve.append(getattr(stop, "dtype", type(stop)))
if step is not None:
dtypes_to_resolve.append(getattr(step, "dtype", type(step)))
dtype = dtypes.result_type(*dtypes_to_resolve)
dtype = standardize_dtype(dtype)
if step is None:
step = 1
try:
out = tf.range(start, stop, delta=step, dtype=dtype)
except tf.errors.NotFoundError:
# Some dtypes may not work in eager mode on CPU or GPU.
out = tf.range(start, stop, delta=step, dtype="float32")
out = tf.cast(out, dtype)
return out
@sparse.densifying_unary(0.5 * np.pi)
def arccos(x):
x = convert_to_tensor(x)
if standardize_dtype(x.dtype) == "int64":
dtype = config.floatx()
else:
dtype = dtypes.result_type(x.dtype, float)
x = tf.cast(x, dtype)
return tf.math.acos(x)
@sparse.densifying_unary(np.nan)
def arccosh(x):
x = convert_to_tensor(x)
if standardize_dtype(x.dtype) == "int64":
dtype = config.floatx()
else:
dtype = dtypes.result_type(x.dtype, float)
x = tf.cast(x, dtype)
return tf.math.acosh(x)
@sparse.elementwise_unary
def arcsin(x):
x = convert_to_tensor(x)
if standardize_dtype(x.dtype) == "int64":
dtype = config.floatx()
else:
dtype = dtypes.result_type(x.dtype, float)
x = tf.cast(x, dtype)
return tf.math.asin(x)
@sparse.elementwise_unary
def arcsinh(x):
x = convert_to_tensor(x)
if standardize_dtype(x.dtype) == "int64":
dtype = config.floatx()
else:
dtype = dtypes.result_type(x.dtype, float)
x = tf.cast(x, dtype)
return tf.math.asinh(x)
@sparse.elementwise_unary
def arctan(x):
x = convert_to_tensor(x)
if standardize_dtype(x.dtype) == "int64":
dtype = config.floatx()
else:
dtype = dtypes.result_type(x.dtype, float)
x = tf.cast(x, dtype)
return tf.math.atan(x)
def arctan2(x1, x2):
x1 = convert_to_tensor(x1)
x2 = convert_to_tensor(x2)
dtype = dtypes.result_type(x1.dtype, x2.dtype, float)
x1 = tf.cast(x1, dtype)
x2 = tf.cast(x2, dtype)
return tf.math.atan2(x1, x2)
@sparse.elementwise_unary
def arctanh(x):
x = convert_to_tensor(x)
if standardize_dtype(x.dtype) == "int64":
dtype = config.floatx()
else:
dtype = dtypes.result_type(x.dtype, float)
x = tf.cast(x, dtype)
return tf.math.atanh(x)
def _keepdims(x, y, axis):
if axis is None:
shape = [1 for _ in range(len(x.shape))]
else:
shape = list(shape_op(x))
for axis in tree.flatten(axis):
shape[axis] = 1
y = tf.reshape(y, shape)
return y
def argmax(x, axis=None, keepdims=False):
x = convert_to_tensor(x)
dtype = standardize_dtype(x.dtype)
if "float" not in dtype or x.ndim == 0:
_x = x
if axis is None:
x = tf.reshape(x, [-1])
y = tf.argmax(x, axis=axis, output_type="int32")
if keepdims:
y = _keepdims(_x, y, axis)
return y
# Fix the flush-to-zero (FTZ) issue based on this issue:
# https://github.com/jax-ml/jax/issues/24280
dtype = dtypes.result_type(dtype, "float32")
x = cast(x, dtype)
is_negative_zero = tf.logical_and(tf.equal(x, 0.0), signbit(x))
x = tf.where(
is_negative_zero, -np.finfo(standardize_dtype(x.dtype)).tiny, x
)
_x = x
if axis is None:
x = tf.reshape(x, [-1])
y = tf.argmax(x, axis=axis, output_type="int32")
if keepdims:
y = _keepdims(_x, y, axis)
return y
def argmin(x, axis=None, keepdims=False):
x = convert_to_tensor(x)
dtype = standardize_dtype(x.dtype)
if "float" not in dtype or x.ndim == 0:
_x = x
if axis is None:
x = tf.reshape(x, [-1])
y = tf.argmin(x, axis=axis, output_type="int32")
if keepdims:
y = _keepdims(_x, y, axis)
return y
# Fix the flush-to-zero (FTZ) issue based on this issue:
# https://github.com/jax-ml/jax/issues/24280
dtype = dtypes.result_type(dtype, "float32")
x = cast(x, dtype)
is_negative_zero = tf.logical_and(tf.equal(x, 0.0), signbit(x))
x = tf.where(
is_negative_zero, -np.finfo(standardize_dtype(x.dtype)).tiny, x
)
_x = x
if axis is None:
x = tf.reshape(x, [-1])
y = tf.argmin(x, axis=axis, output_type="int32")
if keepdims:
y = _keepdims(_x, y, axis)
return y
def argsort(x, axis=-1):
x = convert_to_tensor(x)
if standardize_dtype(x.dtype) == "bool":
x = tf.cast(x, "uint8")
x_shape = x.shape
if x_shape.rank == 0:
return tf.cast([0], "int32")
if axis is None:
x = tf.reshape(x, [-1])
axis = 0
return tf.argsort(x, axis=axis)
def array(x, dtype=None):
return convert_to_tensor(x, dtype=dtype)
def view(x, dtype=None):
from keras.src import backend