Repository navigation
Expand file tree
/
Copy pathsaps_smart.py
More file actions
1844 lines (1590 loc) · 65.5 KB
/
Copy pathsaps_smart.py
File metadata and controls
1844 lines (1590 loc) · 65.5 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 operator
import types
from itertools import product
from math import prod
import numpy as np
import scipy.sparse as sps
import scipy.sparse.linalg as spla
import array_api_compat
import array_api_compat.numpy as compat_np
import sparse as sp
from binsparse import (
CSRMatrix,
CustomTensor,
DenseLevel,
DMATCMatrix,
DMATRMatrix,
DVECVector,
ElementLevel,
)
from binsparse.conversions import from_numpy, from_sparse, to_numpy, to_scipy, to_sparse
from saps_framework import (
Framework,
normalize_pad_width,
normalize_unfold_args,
normalize_unfold_padding,
unfold_output_shape,
)
from saps_framework.einsum import Access, nary_ops, parse_einsum, reduction_ops
# Tests import frameworks as a package; the harness loads them from their folder.
try:
from frameworks.saps_numpy import NumpyFramework
except ImportError:
from saps_numpy import NumpyFramework # type: ignore[no-redef]
_EINSUM_BLOCK_SIZE = 65_536
_EINSUM_DENSE_BYTES = 64 * 1024**2
# Convolve a sparse input site by site when at most this fraction of its
# (batch, *spatial) sites store a value. Measured against densifying and using
# BLAS, site by site wins below 3-10% depending on the channels and kernel.
_CONV_SITE_DENSITY = 0.05
class SmartSparseLinalg:
@staticmethod
def _dense(array):
if hasattr(array, "todense"):
return np.asarray(array.todense())
if hasattr(array, "toarray"):
return np.asarray(array.toarray())
return np.asarray(array)
@staticmethod
def _scipy_sparse(array):
if hasattr(array, "to_scipy_sparse"):
if array.ndim == 2:
return array.to_scipy_sparse()
if array.ndim == 1:
return array.reshape((array.shape[0], 1)).to_scipy_sparse()
raise ValueError(
"SciPy sparse linalg only supports one- or two-dimensional arrays."
)
array = np.asarray(array)
if array.ndim == 1:
return sps.coo_matrix(array.reshape((-1, 1)))
if array.ndim == 2:
return sps.coo_matrix(array)
raise ValueError(
"SciPy sparse linalg only supports one- or two-dimensional arrays."
)
@staticmethod
def _wrap_result(result):
if sps.issparse(result):
return sp.asarray(result)
if isinstance(result, np.ndarray):
return sp.asarray(result)
if isinstance(result, tuple):
return tuple(SmartSparseLinalg._wrap_result(item) for item in result)
return result
@staticmethod
def solve(A, b):
A = SmartSparseLinalg._scipy_sparse(A).tocsr()
b = SmartSparseLinalg._scipy_sparse(b)
# A triangular system, like an LU factor, needs only substitution.
# spsolve would factor it again, with pivoting that loses accuracy.
for lower, outside in ((True, sps.triu(A, 1)), (False, sps.tril(A, -1))):
if outside.count_nonzero() == 0:
x = spla.spsolve_triangular(A, b.toarray(), lower=lower)
return SmartSparseLinalg._wrap_result(
x.ravel() if x.shape[1] == 1 else x
)
x = spla.spsolve(A.tocsc(), b)
return SmartSparseLinalg._wrap_result(x)
@staticmethod
def pinv(A, **kwargs):
return np.linalg.pinv(SmartSparseLinalg._dense(A), **kwargs)
@staticmethod
def lstsq(A, b, **kwargs):
return np.linalg.lstsq(
SmartSparseLinalg._dense(A), SmartSparseLinalg._dense(b), **kwargs
)
@staticmethod
def svd(A, full_matrices=False, k=None, **kwargs):
# svds only finds k < min(A.shape) singular triplets, so anything but a
# truncated SVD of a sparse matrix (a full reduced SVD, full_matrices,
# or a matrix too thin to truncate) is computed densely instead.
sparse_ok = (
isinstance(A, sp.SparseArray)
and not full_matrices
and k is not None
and k < min(A.shape)
)
if not sparse_ok:
A = np.asarray(SmartSparseLinalg._dense(A))
if A.dtype.kind not in "fc":
A = A.astype(np.float64)
U, S, Vt = np.linalg.svd(A, full_matrices=full_matrices, **kwargs)
if k is not None:
U = U[:, :k]
S = S[:k]
Vt = Vt[:k, :]
return U, S, Vt
A = SmartSparseLinalg._scipy_sparse(A)
if A.dtype.kind not in "fc":
A = A.astype(np.float64)
U, S, Vt = spla.svds(A, k=k, **kwargs)
order = np.argsort(S)[::-1]
return (
sp.asarray(U[:, order]),
sp.asarray(S[order]),
sp.asarray(Vt[order, :]),
)
def __getattr__(self, name):
attr = getattr(spla, name)
def wrapped(*args, **kwargs):
args = tuple(
self._scipy_sparse(arg) if hasattr(arg, "ndim") else arg for arg in args
)
kwargs = {
key: self._scipy_sparse(value) if hasattr(value, "ndim") else value
for key, value in kwargs.items()
}
return self._wrap_result(attr(*args, **kwargs))
return wrapped
def _value_is_zero(value) -> bool:
array = np.asarray(value)
return array.shape == () and array.item() == 0
def _axis_unfold_map(input_size, output_size, kernel_index, stride, dilation, dtype):
positions = np.arange(output_size) * stride + kernel_index * dilation
return sp.eye(input_size, dtype=dtype, format="coo")[positions]
def _kron_all(arrays):
result = arrays[0]
for array in arrays[1:]:
result = sp.kron(result, array)
return result
def _unfold_block_coords(flat_rows, output_core_shape, kernel_index, output_rank):
nnz = len(flat_rows)
coords = np.empty((output_rank, nnz), dtype=np.intp)
for axis, axis_coords in enumerate(np.unravel_index(flat_rows, output_core_shape)):
coords[axis] = axis_coords
for axis, kernel_axis_index in enumerate(
kernel_index, start=len(output_core_shape)
):
coords[axis].fill(kernel_axis_index)
return coords
def _sparse_unfold_with_diagonals(
array,
kernel_shape,
axes,
strides,
dilations,
):
input_shape = tuple(int(dim) for dim in array.shape)
output_shape = unfold_output_shape(
input_shape,
kernel_shape,
axes,
strides,
dilations,
)
output_core_shape = output_shape[: array.ndim]
axis_positions = {axis: i for i, axis in enumerate(axes)}
flat_input = array.reshape((int(np.prod(input_shape)), 1))
coords = []
data = []
for kernel_index in product(*(range(size) for size in kernel_shape)):
axis_maps = []
for axis, input_size in enumerate(input_shape):
if axis in axis_positions:
position = axis_positions[axis]
axis_maps.append(
_axis_unfold_map(
input_size,
output_core_shape[axis],
kernel_index[position],
strides[position],
dilations[position],
array.dtype,
)
)
else:
axis_maps.append(sp.eye(input_size, dtype=array.dtype, format="coo"))
selected = (_kron_all(axis_maps) @ flat_input).asformat("coo")
if selected.nnz == 0:
continue
coords.append(
_unfold_block_coords(
selected.coords[0],
output_core_shape,
kernel_index,
len(output_shape),
)
)
data.append(selected.data)
if coords:
output_coords = np.concatenate(coords, axis=1)
output_data = np.concatenate(data)
else:
output_coords = np.empty((len(output_shape), 0), dtype=np.intp)
output_data = np.asarray([], dtype=array.dtype)
return sp.COO(output_coords, output_data, shape=output_shape)
def _is_full_slice(index) -> bool:
return (
isinstance(index, slice)
and index.start in (None, 0)
and index.stop is None
and index.step in (None, 1)
)
class _MutableCOO(sp.COO):
"""COO arithmetic with indexed assignment through a temporary DOK builder."""
def __setitem__(self, key, value):
if isinstance(key, tuple):
key = tuple(
SmartSparseKernels._dense(index)
if isinstance(index, sp.SparseArray)
else index
for index in key
)
elif isinstance(key, sp.SparseArray):
key = SmartSparseKernels._dense(key)
if isinstance(value, sp.SparseArray):
value = SmartSparseKernels._dense(value)
# Scattering into an empty array with no repeated coordinates is
# exactly building a COO from these coordinates -- construct it
# directly (vectorized) instead of going through DOK, whose own
# __setitem__ is a pure-Python loop over every index (see
# sparse.numba_backend._dok.DOK._fancy_setitem), which dominates
# runtime at realistic sizes regardless of how few entries are
# actually being set. COO sums duplicate coordinates instead of
# this class's (and DOK's) last-write-wins, so this only applies
# once verified duplicate-free -- itself a cheap vectorized check,
# unlike the Python loop it's replacing.
if (
self.nnz == 0
and isinstance(key, tuple)
and len(key) == self.ndim
and all(isinstance(index, np.ndarray) and index.ndim == 1 for index in key)
):
flat = np.ravel_multi_index(key, self.shape)
if len(np.unique(flat)) == len(flat):
coords = np.stack(key)
data = np.broadcast_to(
np.asarray(value, dtype=self.dtype), (coords.shape[1],)
)
updated = sp.COO(
coords,
data,
shape=self.shape,
fill_value=self.fill_value,
has_duplicates=False,
)
self.coords = updated.coords
self.data = updated.data
self._cache = None
return
# A full slice on one axis and a scalar on the other (Q[:, i] = ...,
# row-major equivalent) is a whole-row/column replace: filter out
# that row/column's existing coordinates and append the new ones,
# vectorized, instead of DOK's element-by-element Python loop. This
# is the pattern iterative solvers hit rewriting one Krylov basis
# column per step -- and it's a *replace*, so old entries at that
# index must be dropped, not summed with the new ones the way COO
# construction would.
if self.ndim == 2 and isinstance(key, tuple) and len(key) == 2:
if _is_full_slice(key[0]) and isinstance(key[1], (int, np.integer)):
varying_axis, fixed_axis, fixed_index = 0, 1, int(key[1])
elif isinstance(key[0], (int, np.integer)) and _is_full_slice(key[1]):
varying_axis, fixed_axis, fixed_index = 1, 0, int(key[0])
else:
varying_axis = None
if varying_axis is not None:
value = np.broadcast_to(
np.asarray(value, dtype=self.dtype), (self.shape[varying_axis],)
)
keep = self.coords[fixed_axis] != fixed_index
nonfill = np.flatnonzero(value != self.fill_value)
new_coords = np.empty((2, len(nonfill)), dtype=self.coords.dtype)
new_coords[varying_axis] = nonfill
new_coords[fixed_axis] = fixed_index
# COO operations assume sorted coordinates, which appending the
# new row/column breaks; the constructor restores the order.
updated = sp.COO(
np.concatenate([self.coords[:, keep], new_coords], axis=1),
np.concatenate([self.data[keep], value[nonfill]]),
shape=self.shape,
fill_value=self.fill_value,
has_duplicates=False,
)
self.coords = updated.coords
self.data = updated.data
self._cache = None
return
builder = sp.DOK.from_coo(self)
builder[key] = value
updated = builder.to_coo()
self.coords = updated.coords
self.data = updated.data
self._cache = None
class SmartSparseKernels(Framework):
_sparse_first: set[str] = set()
_dtype_attrs = {
"bool",
"float32",
"float64",
"int8",
"int16",
"int32",
"int64",
"uint8",
"uint16",
"uint32",
"uint64",
}
def __init__(self):
self._modules = [sp, compat_np, np]
self._numpy = NumpyFramework()
@staticmethod
def _is_sparse(arg):
# Sequence arguments (e.g. concat's array list) count too, or a mixed
# list would dispatch to NumPy and reach pydata/sparse's concatenate
# through __array_function__ with its dense members unconverted.
if isinstance(arg, list | tuple):
return any(isinstance(item, sp.SparseArray) for item in arg)
return isinstance(arg, sp.SparseArray)
@classmethod
def _has_sparse_arg(cls, *args, **kwargs):
return any(cls._is_sparse(arg) for arg in args) or any(
cls._is_sparse(value) for value in kwargs.values()
)
@staticmethod
def _array_namespace(*arrays):
return array_api_compat.array_namespace(*arrays, use_compat=True)
@staticmethod
def _fill_value_is_zero(array):
fill_value = getattr(array, "fill_value", 0)
return np.all(np.asarray(fill_value) == 0)
@staticmethod
def _dense(array):
if hasattr(array, "todense"):
return np.asarray(array.todense())
if hasattr(array, "toarray"):
return np.asarray(array.toarray())
return np.asarray(array)
@staticmethod
def _sparse_compatible_arg(arg):
if isinstance(arg, np.ndarray):
return sp.asarray(arg)
if isinstance(arg, list | tuple):
return type(arg)(
sp.asarray(item) if isinstance(item, np.ndarray) else item
for item in arg
)
return arg
def from_binsparse(self, array):
match array:
case DVECVector() | DMATRMatrix() | DMATCMatrix():
return to_numpy(array)
case CustomTensor(shape=(), transpose=None, level=ElementLevel()):
return to_numpy(array)
case CustomTensor(
shape=shape,
transpose=None,
level=DenseLevel(rank=rank, level=ElementLevel()),
) if rank == len(shape):
return to_numpy(array)
case CSRMatrix(): # also matches CSCMatrix, a CSRMatrix subclass
# to_sparse only reads COO; go through SciPy (which reads
# CSR/CSC/COO) and into GCXS instead of densifying via COO.
return sp.GCXS.from_scipy_sparse(to_scipy(array))
case _:
return to_sparse(array)
def to_binsparse(self, array):
if isinstance(array, sp.COO):
if array.ndim == 0:
return from_numpy(self._dense(array))
return from_sparse(array)
if isinstance(array, sp.SparseArray):
if array.ndim == 0:
return from_numpy(self._dense(array))
return self.to_binsparse(array.tocoo())
if isinstance(array, np.ndarray):
return from_numpy(array)
if np.isscalar(array):
return from_numpy(np.asarray(array))
raise ValueError("Unsupported array type: " + str(type(array)))
def lazy(self, array):
return array
def compute(self, array):
return array
def to_dense(self, array):
# A sparse array can carry a nonzero fill value (e.g. downstream of
# a boolean mask that's mostly True) without being sparse in any
# useful sense; densifying is then both cheap and the only way to
# feed it to ordinary elementwise ops without tripping pydata/
# sparse's mixed sparse-dense guard.
if hasattr(array, "todense"):
return array.todense()
return array
def sum(self, x, axis=None, **kwargs):
# A reduced axis can still contain millions of elements. Preserve the
# sparse result and its fill value; WrappedArray handles mixed operands.
if isinstance(x, sp.SparseArray):
return sp.sum(x, axis=axis, **kwargs)
xp = self._array_namespace(x)
return xp.sum(x, axis=axis, **kwargs)
def where(self, condition, x, y):
# A sparse boolean condition selecting from a dense x with a scalar
# fill y (e.g. an LSH candidate mask picking real distances out of
# a dense distance matrix, else infinity) never needs the dense
# result materialized: gather x's values at condition's stored
# (true, since fill_value is falsy) coordinates and hand them back
# in a COO with fill_value=y -- O(nnz) instead of O(condition.size).
# The generic dispatch below would instead sparsify x, since it
# sparsifies every argument once any one of them is sparse.
if (
isinstance(condition, sp.SparseArray)
and condition.ndim == 2
and not condition.fill_value
and not isinstance(x, sp.SparseArray)
and getattr(x, "shape", None) == condition.shape
and np.isscalar(y)
):
coo = (
condition
if isinstance(condition, sp.COO)
else condition.asformat("coo")
)
rows, cols = coo.coords
x = np.asarray(x)
return sp.COO(
coo.coords,
x[rows, cols],
shape=condition.shape,
fill_value=x.dtype.type(y),
)
if self._has_sparse_arg(condition, x, y):
condition, x, y = (
self._sparse_compatible_arg(arg) for arg in (condition, x, y)
)
return sp.where(condition, x, y)
return compat_np.where(condition, x, y)
def einsum(self, prgm, **kwargs):
if not self._has_sparse_arg(**kwargs):
return self._numpy.einsum(prgm, **kwargs)
parsed = parse_einsum(prgm)
result = self._masked_einsum(parsed, kwargs)
if result is NotImplemented:
result = self._blocked_einsum(parsed, kwargs)
if result is not NotImplemented:
return result
kwargs = {
key: self._sparse_compatible_arg(value) for key, value in kwargs.items()
}
result = parsed.run_native(sp, kwargs)
return parsed.run(sp, kwargs) if result is NotImplemented else result
def _masked_einsum(self, parsed, kwargs):
"""Contract C[i,j] * A[i,f] * B[j,f] (in any order) over f only at the
entries a sparse mask C stores, as a sampled matrix product.
The other pairs are zero in the result anyway, so this never forms
A @ B.T, which can be dense even when C is very sparse.
"""
contraction = parsed.native_contraction()
if contraction is NotImplemented or parsed.op not in {"+", "add", "sum"}:
return NotImplemented
_, leaves, bitwise = contraction
out = parsed.idxs
if (
bitwise
or len(leaves) != 3
or len(out) != 2
or not all(isinstance(leaf, Access) for leaf in leaves)
):
return NotImplemented
masks = [
leaf
for leaf in leaves
if sorted(leaf.idxs) == sorted(out)
and isinstance(kwargs[leaf.tns], sp.SparseArray)
]
if not masks:
return NotImplemented
mask = masks[0]
a, b = (leaf for leaf in leaves if leaf is not mask)
i, j = out
if i not in a.idxs:
a, b = b, a
reduced = [idx for idx in a.idxs if idx != i]
if (
len(a.idxs) != 2
or len(b.idxs) != 2
or len(reduced) != 1
or sorted(a.idxs) != sorted([i, *reduced])
or sorted(b.idxs) != sorted([j, *reduced])
):
return NotImplemented
arrays = [kwargs[leaf.tns] for leaf in (mask, a, b)]
if not all(self._fill_value_is_zero(array) for array in arrays):
return NotImplemented
def matrix(leaf, row):
"""leaf's array with row indexed first, as CSR if sparse."""
array = kwargs[leaf.tns]
if isinstance(array, sp.SparseArray):
array = self._to_scipy_sparse(array).tocsr()
else:
array = np.asarray(array)
return array if leaf.idxs[0] == row else array.T
left, right = matrix(a, i), matrix(b, j)
if sps.issparse(left) and left.format != "csr":
left = left.tocsr()
if sps.issparse(right) and right.format != "csr":
right = right.tocsr()
coo = arrays[0].asformat("coo")
rows, cols = coo.coords if mask.idxs == out else coo.coords[::-1]
dtype = np.result_type(*(array.dtype for array in arrays))
values = np.empty(len(rows), dtype=dtype)
# Bound the rows gathered at once by their stored entries.
width = max(
(x.nnz / max(x.shape[0], 1) if sps.issparse(x) else x.shape[1])
for x in (left, right)
)
step = max(1, int(_EINSUM_DENSE_BYTES // (16 * max(width, 1))))
for start in range(0, len(rows), step):
r, c = rows[start : start + step], cols[start : start + step]
x, y = left[r], right[c]
if sps.issparse(y):
x, y = y, x
if sps.issparse(x):
products = np.asarray(x.multiply(y).sum(axis=1)).ravel()
else:
products = np.einsum("pk,pk->p", x, y)
values[start : start + step] = products
values *= coo.data.astype(dtype, copy=False)
return sp.COO(
np.stack([rows, cols]),
values,
shape=tuple(
kwargs[leaf.tns].shape[leaf.idxs.index(idx)]
for leaf, idx in ((a, i), (b, j))
),
)
def topk(self, x, k, *, axis=-1, largest=True):
"""Sort only the stored entries of a sparse matrix's rows, when each
row stores at least k entries that beat its fill value."""
if not (isinstance(x, sp.SparseArray) and x.ndim == 2 and axis in (1, -1)):
return super().topk(x, k, axis=axis, largest=largest)
coo = x.asformat("coo")
rows, cols = coo.coords
fill = coo.fill_value
better = coo.data > fill if largest else coo.data < fill
if np.any(np.bincount(rows[better], minlength=x.shape[0]) < k):
return super().topk(self._dense(x), k, axis=axis, largest=largest)
rows, cols, data = rows[better], cols[better], coo.data[better]
# Sort by row, then value, then column so ties keep index order.
order = np.lexsort((cols, -data if largest else data, rows))
starts = np.searchsorted(rows[order], np.arange(x.shape[0]))
picks = order[starts[:, None] + np.arange(k)]
return data[picks], cols[picks].astype(np.int64)
def _blocked_einsum(self, parsed, kwargs):
"""Contract zero-fill sparse entries in bounded batches.
A sparse operand must cover all reduced indices. Other indices enumerate
output slices (for example, CP rank). Small factors and outputs may be
dense; large factors/outputs and general expressions use the fallback.
"""
contraction = parsed.native_contraction()
if contraction is NotImplemented:
return NotImplemented
_, leaves, bitwise = contraction
operands = [
kwargs[leaf.tns] if isinstance(leaf, Access) else np.asarray(leaf.value)
for leaf in leaves
]
operands = [
operand if isinstance(operand, sp.SparseArray) else np.asarray(operand)
for operand in operands
]
indices = [leaf.idxs if isinstance(leaf, Access) else [] for leaf in leaves]
if any(not self._fill_value_is_zero(operand) for operand in operands):
return NotImplemented
boolean = all(operand.dtype.kind == "b" for operand in operands)
logical = parsed.op in {"|", "or"}
if (bitwise or logical) and not boolean:
return NotImplemented
sizes = {}
for operand, term in zip(operands, indices, strict=True):
for idx, size in zip(term, operand.shape, strict=True):
if sizes.setdefault(idx, size) != size:
return NotImplemented
reduced = set(sizes) - set(parsed.idxs)
candidates = [
i
for i, operand in enumerate(operands)
if isinstance(operand, sp.SparseArray)
and reduced.issubset(indices[i])
and len(indices[i]) == len(set(indices[i]))
]
if not candidates or len(parsed.idxs) != len(set(parsed.idxs)):
return NotImplemented
anchor_index = min(candidates, key=lambda i: operands[i].nnz)
dtype = np.result_type(*(operand.dtype for operand in operands))
output_dtype = (
np.dtype(bool) if logical else np.zeros((), dtype=dtype).sum().dtype
)
shape = tuple(sizes[idx] for idx in parsed.idxs)
dense_bytes = prod(shape) * output_dtype.itemsize
for i, operand in enumerate(operands):
if i != anchor_index and isinstance(operand, sp.SparseArray):
dense_bytes += prod(operand.shape) * operand.dtype.itemsize
if dense_bytes > _EINSUM_DENSE_BYTES:
return NotImplemented
anchor = operands[anchor_index].asformat("coo")
factors = [
(term, self._dense(operand))
for i, (operand, term) in enumerate(zip(operands, indices, strict=True))
if i != anchor_index
]
# Skipping implicit zeros is only valid when 0 * factor stays zero.
if any(
not np.isfinite(factor.flat[start : start + _EINSUM_BLOCK_SIZE]).all()
for _, factor in factors
for start in range(0, factor.size, _EINSUM_BLOCK_SIZE)
):
return NotImplemented
anchor_indices = indices[anchor_index]
free = [idx for idx in parsed.idxs if idx not in anchor_indices]
scatter = any(idx in anchor_indices for idx in parsed.idxs)
result = np.zeros(shape, dtype=output_dtype)
if anchor.nnz == 0:
return result
for free_coords in np.ndindex(*(sizes[idx] for idx in free)):
positions = dict(zip(free, free_coords, strict=True))
for start in range(0, anchor.nnz, _EINSUM_BLOCK_SIZE):
block = slice(start, start + _EINSUM_BLOCK_SIZE)
positions.update(
(idx, anchor.coords[axis, block])
for axis, idx in enumerate(anchor_indices)
)
values = anchor.data[block].astype(dtype, copy=True)
for term, factor in factors:
values *= factor[tuple(positions[idx] for idx in term)]
target = tuple(positions[idx] for idx in parsed.idxs)
if scatter:
if logical:
np.logical_or.at(result, target, values)
else:
np.add.at(result, target, values)
elif logical:
result[target] |= values.any()
else:
result[target] += values.sum(dtype=output_dtype)
return result
def conv(self, x, w, **kwargs):
# Weights are small next to activations, and dense weights let a
# dense input use BLAS even when most of them are zero.
w = self._dense(w)
if not isinstance(x, sp.SparseArray):
return self._numpy.conv(x, w, **kwargs)
result = self._sparse_conv(x, w, **kwargs)
if result is NotImplemented:
return self._numpy.conv(self._dense(x), w, **kwargs)
return result
def _sparse_conv(
self,
x,
w,
*,
strides=None,
dilations=None,
padding=None,
padding_mode="constant",
fill_value=0,
group=1,
combine="*",
reduce="+",
):
"""Convolve the stored sites of x, a zero-fill sparse (N, C, *spatial).
Each kernel offset maps every stored input site to at most one output
site, so the offset contributes one matmul of the stored sites' channels
with its weights. Summing the contributions per output site gives a
sparse output.
"""
batch, channels, *spatial = x.shape
out_channels, group_channels, *kernel = w.shape
axes = tuple(range(2, x.ndim))
pad_width = normalize_unfold_padding(x.ndim, padding, axes)[2:]
if (
nary_ops[combine] != "multiply"
or reduction_ops[reduce] != "sum"
or x.ndim != w.ndim
or x.ndim < 3
or channels != group * group_channels
or out_channels % group != 0
or not self._fill_value_is_zero(x)
or np.result_type(x.dtype, w.dtype).kind not in "fc"
or (padding_mode != "constant" or fill_value != 0)
and any(pair != (0, 0) for pair in pad_width)
):
return NotImplemented
_, strides_t, dilations_t = normalize_unfold_args(
x.ndim, kernel, axes, strides, dilations
)
x = x.asformat("coo")
n, c, *s = x.coords
sites, site = np.unique(
np.ravel_multi_index((n, *s), (batch, *spatial)), return_inverse=True
)
if len(sites) > _CONV_SITE_DENSITY * batch * prod(spatial):
return NotImplemented
dtype = np.result_type(x.dtype, w.dtype)
values = np.zeros((group, len(sites), group_channels), dtype=dtype)
values[c // group_channels, site, c % group_channels] = x.data
n, *s = np.unravel_index(sites, (batch, *spatial))
out_spatial = unfold_output_shape(
[
size + before + after
for size, (before, after) in zip(spatial, pad_width, strict=True)
],
kernel,
range(len(kernel)),
strides_t,
dilations_t,
)[: len(kernel)]
# (G, M / G, C / G, *kernel), with each offset's weights as (C / G, M / G).
w = w.reshape(group, out_channels // group, group_channels, *kernel)
targets = []
contributions = []
for offset in np.ndindex(*kernel):
# Input s feeds output o where o * stride = s + before - k * dilation.
o = [
si + before - k * dilation
for si, (before, _), k, dilation in zip(
s, pad_width, offset, dilations_t, strict=True
)
]
hit = np.ones(len(sites), dtype=bool)
for oi, stride, size in zip(o, strides_t, out_spatial, strict=True):
hit &= (oi >= 0) & (oi < size * stride) & (oi % stride == 0)
targets.append(
np.ravel_multi_index(
(
n[hit],
*(
oi[hit] // stride
for oi, stride in zip(o, strides_t, strict=True)
),
),
(batch, *out_spatial),
)
)
product = np.matmul(values[:, hit], np.swapaxes(w[(..., *offset)], 1, 2))
contributions.append(np.swapaxes(product, 0, 1).reshape(-1, out_channels))
targets = np.concatenate(targets)
out_sites, target = np.unique(targets, return_inverse=True)
# Sum the contributions landing on each output site.
scatter = sps.csr_array(
(np.ones(len(targets), dtype=dtype), (target, np.arange(len(targets)))),
shape=(len(out_sites), len(targets)),
)
out_values = scatter @ np.concatenate(contributions)
n, *o = np.unravel_index(out_sites, (batch, *out_spatial))
# The sites are sorted by batch, then position. COO order puts the
# channel between them, so site u of a batch whose sites start at
# `start` and number `count` holds channel m at
# start * M + m * count + (u - start).
start = np.searchsorted(n, n)
count = np.bincount(n, minlength=batch)[n]
order = (
(start * out_channels)[:, None]
+ np.arange(out_channels) * count[:, None]
+ (np.arange(len(out_sites)) - start)[:, None]
)
coords = np.empty((x.ndim, order.size), dtype=np.intp)
for axis, index in enumerate((n, np.arange(out_channels), *o)):
coords[axis, order] = index[:, None] if axis != 1 else index
data = np.empty(order.size, dtype=out_values.dtype)
data[order] = out_values
return sp.COO(
coords,
data,
shape=(batch, out_channels, *out_spatial),
has_duplicates=False,
sorted=True,
)
def pool(self, x, kernel_shape, **kwargs):
if isinstance(x, sp.SparseArray):
return super().pool(x, kernel_shape, **kwargs)
return self._numpy.pool(x, kernel_shape, **kwargs)
def pad_constant(self, x, pad_width, *, fill_value=0):
pad_width = normalize_pad_width(np.ndim(x), pad_width)
if not isinstance(x, sp.SparseArray):
return np.pad(x, pad_width, mode="constant", constant_values=fill_value)
# pydata/sparse only pads with the array's fill value.
if np.asarray(fill_value) == x.fill_value:
return sp.pad(x.asformat("coo"), pad_width, constant_values=fill_value)
return super().pad_constant(x, pad_width, fill_value=fill_value)
# pydata/sparse.pad only supports constant mode, so sparse arrays fall back
# to concatenating slices.
def pad_reflect(self, x, pad_width):
if isinstance(x, sp.SparseArray):
return super().pad_reflect(x, pad_width)
return np.pad(x, normalize_pad_width(np.ndim(x), pad_width), mode="reflect")
def pad_edge(self, x, pad_width):
if isinstance(x, sp.SparseArray):
return super().pad_edge(x, pad_width)
return np.pad(x, normalize_pad_width(np.ndim(x), pad_width), mode="edge")
def pad_wrap(self, x, pad_width):
if isinstance(x, sp.SparseArray):
return super().pad_wrap(x, pad_width)
return np.pad(x, normalize_pad_width(np.ndim(x), pad_width), mode="wrap")
def unfold(self, x, kernel_shape, *, axes=None, strides=None, dilations=None):
kernel_t = tuple(int(size) for size in kernel_shape)
if isinstance(x, sp.SparseArray):
axes_t, strides_t, dilations_t = normalize_unfold_args(
x.ndim, kernel_t, axes, strides, dilations
)
return _sparse_unfold_with_diagonals(
x.asformat("coo"), kernel_t, axes_t, strides_t, dilations_t
)
array = np.asarray(x)
axes_t, strides_t, dilations_t = normalize_unfold_args(
array.ndim,
kernel_t,
axes,
strides,
dilations,
)
effective_kernel = tuple(
(kernel - 1) * dilation + 1
for kernel, dilation in zip(kernel_t, dilations_t, strict=True)
)
windows = np.lib.stride_tricks.sliding_window_view( # type: ignore[call-overload]
array,
effective_kernel,
axis=axes_t,
)
slices: list[slice] = [slice(None)] * windows.ndim
for axis, step in zip(axes_t, strides_t, strict=True):
slices[axis] = slice(None, None, step)
for window_axis, dilation in enumerate(dilations_t, start=array.ndim):
slices[window_axis] = slice(None, None, dilation)
return windows[tuple(slices)]
def diagonal(self, a, *args, **kwargs):
if isinstance(a, sp.SparseArray):
# sparse.diagonal reads COO coordinates, which GCXS lacks.
return sp.diagonal(sp.COO(a), *args, **kwargs)
xp = self._array_namespace(a)
return xp.diagonal(a, *args, **kwargs)
def matmul(self, x1, x2, /, **kwargs):
if isinstance(x1, sp.SparseArray) or isinstance(x2, sp.SparseArray):
# sparse.matmul (unlike the array-api namespace below) takes no
# kwargs at all, so a caller-requested dtype has to be applied
# as a cast afterward instead of steering the contraction
# itself -- unlike the dense path, this can't avoid computing
# in whatever wider dtype the contraction naturally uses first.
dtype = kwargs.pop("dtype", None)
if kwargs:
raise TypeError(
f"SmartSparseKernels.matmul doesn't support {sorted(kwargs)} "
"for sparse operands"
)
if (
isinstance(x1, sp.SparseArray)
and isinstance(x2, sp.SparseArray)
and x1.ndim == 2
and x2.ndim == 2
):
# Two genuinely sparse (as opposed to formally sparse, e.g.
# LSH bucket indicators) 2D operands: go through SciPy's
# CSR-CSR product instead of pydata/sparse's own `@`. That
# path (sparse/_coo/core.py's linear_loc-based reshape/
# tensordot machinery, flagged by its own "this self.size
# enforces a 2**64 limit to array size" TODO) is built for
# general N-D contractions, not tuned for the very wide,
# very sparse 2D case -- SciPy's is.
result = self._to_scipy_sparse(x1) @ self._to_scipy_sparse(x2)
result = sp.GCXS.from_scipy_sparse(result.tocsr())
return result if dtype is None else result.astype(dtype)
if (
x1.ndim == 2
and x2.ndim <= 2
and (not isinstance(x2, sp.SparseArray) or x2.ndim == 2)
and not (
isinstance(x1, sp.SparseArray) and isinstance(x2, sp.SparseArray)
)
):
# A 2D sparse matrix times a dense matrix or vector (or the
# reverse, with a 2D sparse operand): SciPy's kernels are faster than
# pydata/sparse's general `@`, and both produce a dense result.
lhs, rhs = (
self._to_scipy_sparse(x) if isinstance(x, sp.SparseArray) else x
for x in (x1, x2)
)
result = np.asarray(lhs @ rhs)
return result if dtype is None else result.astype(dtype)
result = x1 @ x2
return result if dtype is None else result.astype(dtype)
xp = self._array_namespace(x1, x2)
return xp.matmul(x1, x2, **kwargs)
@staticmethod
def _to_scipy_sparse(array):
if hasattr(array, "to_scipy_sparse"):
return array.to_scipy_sparse()
return sps.coo_matrix(np.asarray(array))
def zeros(self, shape, *args, **kwargs):
# Vectors also serve as dense index and scalar buffers in the suite.
if not isinstance(shape, tuple | list) or len(shape) < 2:
return compat_np.zeros(shape, *args, **kwargs)
return _MutableCOO(sp.zeros(shape, *args, **kwargs))