Repository navigation
Expand file tree
/
Copy pathsparse_tensor.h
More file actions
1876 lines (1666 loc) · 66.5 KB
/
Copy pathsparse_tensor.h
File metadata and controls
1876 lines (1666 loc) · 66.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
/*
Copyright (C) 2024-2026 Zhenjie Li (Li, Zhenjie)
This file is part of SparseRREF. The SparseRREF is free software:
you can redistribute it and/or modify it under the terms of the MIT
License.
*/
#ifndef SPARSE_TENSOR_H
#define SPARSE_TENSOR_H
#include "sparse_type.h"
#include <cstdint>
#include <cstring>
#include <limits>
namespace SparseRREF {
// A and B need not be sorted: gen_perm() visits both in index order, so the index tuples are
// concatenated in lexicographic order and C is sorted as well. The entries of C are written
// directly: the row of A with permutation position r owns the slice [r * B.nnz(), (r + 1) *
// B.nnz()) of C, so the slices do not overlap, their boundaries are known before any entry is
// computed, and the parallel version needs neither a per block tensor nor a merge
template <typename index_t, typename T>
sparse_tensor<T, index_t, SPARSE_COO> tensor_product(
const sparse_tensor<T, index_t, SPARSE_COO>& A,
const sparse_tensor<T, index_t, SPARSE_COO>& B, const field_t& F,
thread_pool* pool = nullptr) {
std::vector<size_t> dimsB = B.dims();
std::vector<size_t> dimsC = A.dims();
dimsC.insert(dimsC.end(), dimsB.begin(), dimsB.end());
sparse_tensor<T, index_t, SPARSE_COO> C(dimsC);
if (A.nnz() == 0 || B.nnz() == 0) {
return C;
}
const size_t rankA = A.rank();
const size_t rankB = B.rank();
const size_t rank = rankA + rankB;
const size_t nnzA = A.nnz();
const size_t nnzB = B.nnz();
// every pair of entries gives one entry of the result, and the number of pairs can leave the
// range of size_t: the capacity below would then be smaller than what the fill writes
if (nnzA > std::numeric_limits<size_t>::max() / nnzB) {
report_error("tensor_product: the result would hold more entries than size_t can count");
return C;
}
C.reserve(nnzA * nnzB);
C.resize(nnzA * nnzB);
// an already ordered tensor needs no permutation at all, and that is the usual case: the check
// is one cheap pass over the indices, and when it succeeds the permutation (one size_t per
// entry) is never built
const bool idA = A.is_ordered_by(), idB = B.is_ordered_by();
auto permA = idA ? std::vector<size_t>() : A.gen_perm(pool);
auto permB = idB ? std::vector<size_t>() : B.gen_perm(pool);
auto permA_at = [&](const size_t k) -> size_t { return idA ? k : permA[k]; };
auto permB_at = [&](const size_t k) -> size_t { return idB ? k : permB[k]; };
auto fill_row = [&](const size_t r) {
const auto posA = permA_at(r);
const auto indexA = A.index(posA);
const auto valA = A.val(posA);
index_t* colptr = C.data.colptr + r * nnzB * rank;
T* valptr = C.data.valptr + r * nnzB;
for (size_t k = 0; k < nnzB; k++) {
const auto posB = permB_at(k);
s_copy(colptr + k * rank, indexA, rankA);
s_copy(colptr + k * rank + rankA, B.index(posB), rankB);
valptr[k] = scalar_mul(valA, B.val(posB), F);
}
};
// every row costs the same, so handing out the rows hands out the work evenly
if (pool != nullptr && nnzA * nnzB >= product_parallel_threshold) {
const size_t nthread = pool->get_thread_count();
if (nnzA >= 2 * nthread) {
const size_t nblocks = nnzA < 64 * nthread ? nthread : 8 * nthread;
pool->detach_loop(0, nnzA, fill_row, nblocks);
pool->wait();
return C;
}
}
for (size_t r = 0; r < nnzA; r++)
fill_row(r);
return C;
}
// returned tensor is sorted
template <typename index_t, typename T>
sparse_tensor<T, index_t, SPARSE_COO> tensor_add(
const sparse_tensor<T, index_t, SPARSE_COO>& A,
const sparse_tensor<T, index_t, SPARSE_COO>& B,
const field_t& F) {
// if one of the tensors is empty, it is ok that dims of A or B are not defined
if (A.alloc() == 0)
return B;
if (B.alloc() == 0)
return A;
if (A.rank() != B.rank()) {
std::cerr << "Error: tensor_add: The dimensions of the two tensors do not match." << std::endl;
return sparse_tensor<T, index_t, SPARSE_COO>();
}
for (size_t i = 0; i < A.rank(); i++) {
if (A.dim(i) != B.dim(i)) {
std::cerr << "Error: tensor_add: The dimensions of the two tensors do not match." << std::endl;
return sparse_tensor<T, index_t, SPARSE_COO>();
}
}
auto rank = A.rank();
// if one of the tensors is zero
if (A.nnz() == 0)
return B;
if (B.nnz() == 0)
return A;
sparse_tensor<T, index_t, SPARSE_COO> C(A.dims(), A.nnz() + B.nnz());
// an already ordered tensor needs no permutation at all: the check is one cheap pass over the
// indices, and when it succeeds the permutation (one size_t per entry) is never built
const bool idA = A.is_ordered_by(), idB = B.is_ordered_by();
auto Aperm = idA ? std::vector<size_t>() : A.gen_perm();
auto Bperm = idB ? std::vector<size_t>() : B.gen_perm();
auto Aperm_at = [&](const size_t k) -> size_t { return idA ? k : Aperm[k]; };
auto Bperm_at = [&](const size_t k) -> size_t { return idB ? k : Bperm[k]; };
// double pointer
size_t i = 0, j = 0;
// C.zero();
while (i < A.nnz() && j < B.nnz()) {
auto posA = Aperm_at(i);
auto posB = Bperm_at(j);
auto indexA = A.index(posA);
auto indexB = B.index(posB);
int cmp = lexico_compare(indexA, indexB, rank);
if (cmp < 0) {
C.push_back(indexA, A.val(posA));
i++;
}
else if (cmp > 0) {
C.push_back(indexB, B.val(posB));
j++;
}
else {
auto val = scalar_add(A.val(posA), B.val(posB), F);
if (val != 0)
C.push_back(indexA, val);
i++; j++;
}
}
while (i < A.nnz()) {
auto posA = Aperm_at(i);
C.push_back(A.index(posA), A.val(posA));
i++;
}
while (j < B.nnz()) {
auto posB = Bperm_at(j);
C.push_back(B.index(posB), B.val(posB));
j++;
}
// the capacity was sized for the worst case, A.nnz() + B.nnz(); the entries that cancelled and
// the ones only one of the two tensors holds leave part of it unused
C.shrink_to_fit();
return C;
}
// A += B, we assume that A and B are sorted
template <typename index_t, typename T>
void tensor_sum_replace(
sparse_tensor<T, index_t, SPARSE_COO>& A,
const sparse_tensor<T, index_t, SPARSE_COO>& B, const field_t& F) {
// if one of the tensors is empty, it is ok that dims of A or B are not defined
if (A.alloc() == 0) {
A = B;
return;
}
if (B.alloc() == 0)
return;
auto dimsC = A.dims();
auto rank = A.rank();
if (A.rank() != B.rank()) {
std::cerr << "Error: tensor_sum_replace: The dimensions of the two tensors do not match." << std::endl;
return;
}
for (size_t i = 0; i < A.rank(); i++) {
if (A.dim(i) != B.dim(i)) {
std::cerr << "Error: tensor_sum_replace: The dimensions of the two tensors do not match." << std::endl;
return;
}
}
if (!(A.check_sorted() && B.check_sorted())) {
std::cerr << "Error: tensor_sum_replace: tensor_sum_replace: Both tensors must be sorted." << std::endl;
return;
}
// if one of the tensors is zero
if (A.nnz() == 0) {
A = B;
return;
}
if (B.nnz() == 0)
return;
if (&A == &B) {
for (size_t i = 0; i < A.nnz(); i++) {
A.val(i) = scalar_add(A.val(i), A.val(i), F);
}
return;
}
// double pointer, from the end to the beginning
size_t ptr1 = A.nnz(), ptr2 = B.nnz();
size_t ptr = A.nnz() + B.nnz();
A.resize(ptr);
while (ptr1 > 0 && ptr2 > 0) {
int order = lexico_compare(A.index(ptr1 - 1), B.index(ptr2 - 1), rank);
if (order == 0) {
auto entry = scalar_add(A.val(ptr1 - 1), B.val(ptr2 - 1), F);
if (entry != 0) {
s_copy(A.index(ptr - 1), A.index(ptr1 - 1), rank);
A.val(ptr - 1) = std::move(entry);
ptr--;
}
ptr1--;
ptr2--;
}
else if (order < 0) {
s_copy(A.index(ptr - 1), B.index(ptr2 - 1), rank);
A.val(ptr - 1) = B.val(ptr2 - 1);
ptr2--;
ptr--;
}
else {
s_copy(A.index(ptr - 1), A.index(ptr1 - 1), rank);
A.val(ptr - 1) = std::move(A.val(ptr1 - 1));
ptr1--;
ptr--;
}
}
while (ptr2 > 0) {
s_copy(A.index(ptr - 1), B.index(ptr2 - 1), rank);
A.val(ptr - 1) = B.val(ptr2 - 1);
ptr2--;
ptr--;
}
// the merged entries were written at the end and A's untouched prefix is at the front,
// so [ptr1, ptr) only holds stale copies: slide the merged part down to close the gap
const size_t total = A.nnz();
for (size_t i = 0; i < total - ptr; i++) {
s_copy(A.index(ptr1 + i), A.index(ptr + i), rank);
A.val(ptr1 + i) = std::move(A.val(ptr + i));
}
A.resize(ptr1 + (total - ptr));
}
// the result is sorted
template <typename index_t, typename T>
sparse_tensor<T, index_t, SPARSE_COO> tensor_contract(
const sparse_tensor<T, index_t, SPARSE_COO>& A,
const sparse_tensor<T, index_t, SPARSE_COO>& B,
const std::vector<size_t>& i1, const std::vector<size_t>& i2,
const field_t& F, thread_pool* pool = nullptr) {
using index_v = std::vector<index_t>;
using index_p = index_t*;
if (i1.size() != i2.size()) {
std::cerr << "Error: tensor_contract: The size of the two contract sets do not match." << std::endl;
return sparse_tensor<T, index_t, SPARSE_COO>();
}
if (i1.size() == 0) {
return tensor_product(A, B, F, pool);
}
// the indices of a contract set have to be in range and pairwise distinct: a repeated index
// would make the tail of the index vector a non permutation and silently misplace the entries
if (!in_range_and_distinct(i1, A.rank()) || !in_range_and_distinct(i2, B.rank())) {
std::cerr << "Error: tensor_contract: The contract indices are out of range or repeated." << std::endl;
return sparse_tensor<T, index_t, SPARSE_COO>();
}
auto dimsA = A.dims();
auto dimsB = B.dims();
for (size_t k = 0; k < i1.size(); k++) {
if (dimsA[i1[k]] != dimsB[i2[k]]) {
std::cerr << "Error: tensor_contract: The dimensions of the two tensors do not match." << std::endl;
return sparse_tensor<T, index_t, SPARSE_COO>();
}
}
// the dimensions of the result
std::vector<size_t> dimsC, index_perm_A, index_perm_B;
for (size_t k = 0; k < dimsA.size(); k++) {
// if k is not in i1, we add it to dimsC and index_perm_A
if (std::find(i1.begin(), i1.end(), k) == i1.end()) {
dimsC.push_back(dimsA[k]);
index_perm_A.push_back(k);
}
}
index_perm_A.insert(index_perm_A.end(), i1.begin(), i1.end());
for (size_t k = 0; k < dimsB.size(); k++) {
// if k is not in i2, we add it to dimsC and index_perm_B
if (std::find(i2.begin(), i2.end(), k) == i2.end()) {
dimsC.push_back(dimsB[k]);
index_perm_B.push_back(k);
}
}
// B is ordered by its contract tuple first: the entries that share one are then consecutive, so
// a row of the result is built by looking each entry of A up in B instead of matching every pair
// of rows
index_perm_B.insert(index_perm_B.begin(), i2.begin(), i2.end());
// an empty operand leaves the result empty: nothing below has to be built for it, and in
// particular the other operand is not ordered
sparse_tensor<T, index_t, SPARSE_COO> C(dimsC);
if (A.nnz() == 0 || B.nnz() == 0)
return C;
// a tensor that already is in the contracted order needs no permutation, which is what the
// callers hand in: the check is one cheap pass, and when it succeeds the permutation -- one
// size_t per entry -- is never built
const bool idA = A.is_ordered_by(&index_perm_A), idB = B.is_ordered_by(&index_perm_B);
auto permA = idA ? std::vector<size_t>() : A.gen_perm(index_perm_A, pool);
auto permB = idB ? std::vector<size_t>() : B.gen_perm(index_perm_B, pool);
auto permA_at = [&](const size_t k) -> size_t { return idA ? k : permA[k]; };
auto permB_at = [&](const size_t k) -> size_t { return idB ? k : permB[k]; };
auto i1i2_size = i1.size();
auto left_size_A = A.rank() - i1i2_size;
auto left_size_B = B.rank() - i1i2_size;
// the contract and free tuples of every entry, in the order of the permutations, so that the
// loops below compare neighbouring entries without following an index permutation. A tuple is
// packed into a mixed radix number when its dimensions allow it, so that it compares with one
// comparison and the keys of the runs sit in one flat array; a tuple that does not fit keeps its
// cache and is compared position by position
// what a slot of the direct lookup table holds while no run of B starts at that tuple
constexpr uint32_t no_run = std::numeric_limits<uint32_t>::max();
std::vector<size_t> cstride(i1i2_size, 1), stride_leftA(left_size_A, 1), stride_leftB(left_size_B, 1);
bool keyed_contract = i1i2_size > 0, keyed_leftA = left_size_A > 0, keyed_leftB = left_size_B > 0;
for (size_t l = i1i2_size; l-- > 1;) {
const size_t dim = dimsA[i1[l]];
if (dim == 0 || cstride[l] > std::numeric_limits<size_t>::max() / dim) {
keyed_contract = false;
break;
}
cstride[l - 1] = cstride[l] * dim;
}
for (size_t l = left_size_A; l-- > 1;) {
const size_t dim = dimsA[index_perm_A[l]];
if (dim == 0 || stride_leftA[l] > std::numeric_limits<size_t>::max() / dim) {
keyed_leftA = false;
break;
}
stride_leftA[l - 1] = stride_leftA[l] * dim;
}
for (size_t l = left_size_B; l-- > 1;) {
const size_t dim = dimsB[index_perm_B[i1i2_size + l]];
if (dim == 0 || stride_leftB[l] > std::numeric_limits<size_t>::max() / dim) {
keyed_leftB = false;
break;
}
stride_leftB[l - 1] = stride_leftB[l] * dim;
}
// the loops above build the product of the dimensions past the first axis, and a key also adds
// value * stride[0] of the first one: a key space that does not fit in a word would wrap around
// and let two tuples share a key, so the packing is dropped and the tuples are compared
constexpr size_t size_max = std::numeric_limits<size_t>::max();
if (keyed_contract && (dimsA[i1[0]] == 0 || cstride[0] > size_max / dimsA[i1[0]]))
keyed_contract = false;
if (keyed_leftA && left_size_A >= 2
&& (dimsA[index_perm_A[0]] == 0 || stride_leftA[0] > size_max / dimsA[index_perm_A[0]]))
keyed_leftA = false;
if (keyed_leftB && left_size_B >= 2
&& (dimsB[index_perm_B[i1i2_size]] == 0 || stride_leftB[0] > size_max / dimsB[index_perm_B[i1i2_size]]))
keyed_leftB = false;
std::vector<index_t> index_A_cache, index_B_cache;
std::vector<index_t> index_leftB_cache(left_size_B * B.nnz());
std::vector<size_t> key_contract_A, key_contract_B, key_leftA, key_leftB;
if (keyed_contract) {
key_contract_A.resize(A.nnz());
key_contract_B.resize(B.nnz());
}
// the key of a free part that is a single index is that index, which is already in hand, so
// those key arrays are not built and key_leftA_at / key_leftB_at read the index where it is
const bool single_leftA = left_size_A == 1;
const bool single_leftB = left_size_B == 1;
if (keyed_leftA && !single_leftA)
key_leftA.resize(A.nnz());
if (keyed_leftB && !single_leftB)
key_leftB.resize(B.nnz());
// a label below zero does not order like the packed tuple, so the keys are dropped then
std::atomic<bool> negative{ false };
for (size_t k = 0; k < A.nnz() && (keyed_contract || keyed_leftA); k++) {
auto ptr = A.index(permA_at(k));
if (keyed_contract) {
size_t key = 0;
for (size_t l = 0; l < i1i2_size; l++) {
const auto value = ptr[i1[l]];
if (value < 0)
negative.store(true, std::memory_order_relaxed);
key += static_cast<size_t>(value) * cstride[l];
}
key_contract_A[k] = key;
}
if (keyed_leftA) {
if (single_leftA) {
// a single free index is its own key, so only its sign is left to report
if (ptr[index_perm_A[0]] < 0)
negative.store(true, std::memory_order_relaxed);
}
else {
size_t key = 0;
for (size_t l = 0; l < left_size_A; l++) {
const auto value = ptr[index_perm_A[l]];
if (value < 0)
negative.store(true, std::memory_order_relaxed);
key += static_cast<size_t>(value) * stride_leftA[l];
}
key_leftA[k] = key;
}
}
}
// the same work on B, which holds most of the entries of the pair: the entries of B are the
// inner loop of the contraction, so this pass is the longest serial stretch left in the
// parallel path and it is handed to the pool
auto pack_B = [&](const size_t k) {
auto ptr = B.index(permB_at(k));
for (size_t l = 0; l < left_size_B; l++)
index_leftB_cache[k * left_size_B + l] = ptr[index_perm_B[i1i2_size + l]];
if (keyed_contract) {
size_t key = 0;
for (size_t l = 0; l < i1i2_size; l++) {
const auto value = ptr[i2[l]];
if (value < 0)
negative.store(true, std::memory_order_relaxed);
key += static_cast<size_t>(value) * cstride[l];
}
key_contract_B[k] = key;
}
if (keyed_leftB) {
if (single_leftB) {
// same as A: the free index is the key, and it has just been copied to the cache
if (index_leftB_cache[k] < 0)
negative.store(true, std::memory_order_relaxed);
}
else {
size_t key = 0;
for (size_t l = 0; l < left_size_B; l++) {
const auto value = ptr[index_perm_B[i1i2_size + l]];
if (value < 0)
negative.store(true, std::memory_order_relaxed);
key += static_cast<size_t>(value) * stride_leftB[l];
}
key_leftB[k] = key;
}
}
};
const size_t nthread = pool == nullptr ? 1 : pool->get_thread_count();
if (pool != nullptr && B.nnz() >= pack_parallel_threshold) {
pool->detach_loop(0, B.nnz(), pack_B, 4 * nthread);
pool->wait();
}
else {
for (size_t k = 0; k < B.nnz(); k++)
pack_B(k);
}
if (negative.load(std::memory_order_relaxed)) {
keyed_contract = false;
keyed_leftA = false;
keyed_leftB = false;
key_contract_A.clear();
key_contract_B.clear();
key_leftA.clear();
key_leftB.clear();
}
// the key of an entry in the order of the permutations, from the key array or, for a free part
// that is a single index, from the index itself
const bool keyed_leftA_single = keyed_leftA && single_leftA;
const bool keyed_leftB_single = keyed_leftB && single_leftB;
auto key_leftA_at = [&](const size_t k) -> size_t {
return keyed_leftA_single ? static_cast<size_t>(A.index(permA_at(k))[index_perm_A[0]]) : key_leftA[k];
};
auto key_leftB_at = [&](const size_t k) -> size_t {
return keyed_leftB_single ? static_cast<size_t>(index_leftB_cache[k * left_size_B]) : key_leftB[k];
};
if (!keyed_contract) {
index_A_cache.resize(i1i2_size * A.nnz());
index_B_cache.resize(i1i2_size * B.nnz());
for (size_t k = 0; k < A.nnz(); k++) {
auto ptr = A.index(permA_at(k));
for (size_t l = 0; l < i1i2_size; l++)
index_A_cache[k * i1i2_size + l] = ptr[i1[l]];
}
for (size_t k = 0; k < B.nnz(); k++) {
auto ptr = B.index(permB_at(k));
for (size_t l = 0; l < i1i2_size; l++)
index_B_cache[k * i1i2_size + l] = ptr[i2[l]];
}
}
// the values of B in the order of the permutation: the merge below walks the runs of B in that
// order, so reading them through the permutation would gather at random; the values of A are
// read once per run, which a gather is fine for, so they are not copied
std::vector<T> val_B;
if (!idB) {
val_B.resize(B.nnz());
if (pool != nullptr && B.nnz() >= pack_parallel_threshold) {
pool->detach_loop(0, B.nnz(), [&](const size_t k) { val_B[k] = B.val(permB_at(k)); }, 4 * nthread);
pool->wait();
}
else {
for (size_t k = 0; k < B.nnz(); k++)
val_B[k] = B.val(permB_at(k));
}
}
// the value at a position of the permuted order, from the copy or from the tensor itself
auto val_A_at = [&](const size_t k) -> const T& { return A.val(permA_at(k)); };
auto val_B_at = [&](const size_t k) -> const T& { return idB ? B.val(k) : val_B[k]; };
auto equal_except = [](const index_t* a, const index_t* b, const std::vector<size_t>& perm, const size_t len) {
for (size_t i = 0; i < len; i++) {
if (a[perm[i]] != b[perm[i]])
return false;
}
return true;
};
// the rows of A: consecutive entries that share the free part, which the keys of A tell apart
// without touching the index vectors again
std::vector<size_t> rowptrA;
rowptrA.push_back(0);
if (keyed_leftA) {
for (size_t k = 1; k < A.nnz(); k++) {
if (key_leftA_at(k) != key_leftA_at(k - 1))
rowptrA.push_back(k);
}
}
else {
for (size_t k = 1; k < A.nnz(); k++) {
if (!equal_except(A.index(permA_at(rowptrA.back())), A.index(permA_at(k)), index_perm_A, left_size_A))
rowptrA.push_back(k);
}
}
rowptrA.push_back(A.nnz());
// the runs of B: consecutive entries that share the contract tuple
std::vector<size_t> rowptrB;
rowptrB.push_back(0);
if (keyed_contract) {
for (size_t k = 1; k < B.nnz(); k++) {
if (key_contract_B[k] != key_contract_B[k - 1])
rowptrB.push_back(k);
}
}
else {
for (size_t k = 1; k < B.nnz(); k++) {
if (lexico_compare(index_B_cache.data() + (k - 1) * i1i2_size,
index_B_cache.data() + k * i1i2_size, i1i2_size) != 0)
rowptrB.push_back(k);
}
}
rowptrB.push_back(B.nnz());
const size_t runsB = rowptrB.size() - 1;
// the contract tuple of the entries that start the runs, so that the search below reads one flat
// array, and, when the tuple space is small enough to address directly, the run of each tuple,
// so that looking the run of an entry of A up is one array read and not a binary search
std::vector<size_t> run_key;
std::vector<uint32_t> run_of_key;
if (keyed_contract) {
run_key.resize(runsB);
for (size_t r = 0; r < runsB; r++)
run_key[r] = key_contract_B[rowptrB[r]];
// a run index is 32 bits, so a tensor with more runs keeps the binary search; the two caps
// keep the table within 64 bytes per run and 64 MB in total, since a wide but sparsely used
// tuple space is answered by the search anyway
constexpr size_t max_run_table = 1u << 24;
const size_t first_dim = dimsA[i1[0]];
const bool tuples_fit = first_dim != 0 && cstride[0] <= std::numeric_limits<size_t>::max() / first_dim;
const size_t tuples = tuples_fit ? cstride[0] * first_dim : 0;
if (runsB < no_run && tuples_fit && tuples <= max_run_table && tuples <= 16 * runsB + (1u << 16)) {
run_of_key.assign(tuples, no_run);
for (size_t r = 0; r < runsB; r++) {
// an index outside its dimension, which a hand made tensor can hold, falls outside
// the table: such a run is left out, as the search skips a tuple no run holds
if (run_key[r] < tuples)
run_of_key[run_key[r]] = static_cast<uint32_t>(r);
}
}
}
// when there is no table, the run of an entry of A costs a search, and the three passes look it
// up again each time: the first one remembers it here and the other two read it back. Only the
// run index is stored, its boundaries follow from rowptrB
std::vector<uint32_t> run_of_entry;
// only the parallel path looks a run up more than once, so only it keeps the cache
if (run_of_key.empty() && runsB < no_run && pool != nullptr && rowptrA.size() - 1 >= 2 * nthread)
run_of_entry.assign(A.nnz(), no_run);
// the runs of B that a row of A reaches: the entries of a row are ordered by their contract
// tuple, so its run is found by binary search, starting at the run of the previous entry, or by
// one read of the lookup table when the tuple space is small enough.
// The work of a row is the number of entries of B it reads, which is what the rows are handed
// out by when the contraction runs on several threads
auto select = [&](const size_t k, std::vector<size_t>& run_first, std::vector<size_t>& run_last,
std::vector<T>* run_val, const bool work_only = false) {
const bool tabulated = !run_of_key.empty();
// the passes after the work pass read the run of an entry back instead of searching it,
// so the test is hoisted out of the loop
const bool cached_runs = !run_of_entry.empty();
size_t work = 0;
size_t lo = 0;
for (size_t ptrA = rowptrA[k]; ptrA < rowptrA[k + 1]; ptrA++) {
size_t run;
// the passes after the one that searched read the run back from the cache
if (!work_only && cached_runs) {
const uint32_t cached = run_of_entry[ptrA];
if (cached == no_run)
continue;
run = cached;
}
else {
if (tabulated) {
const size_t key = key_contract_A[ptrA];
if (key >= run_of_key.size())
continue;
const uint32_t r = run_of_key[key];
if (r == no_run)
continue;
run = r;
}
else if (keyed_contract) {
const size_t key = key_contract_A[ptrA];
size_t low = lo, high = runsB;
while (low < high) {
const size_t mid = low + (high - low) / 2;
if (key > run_key[mid])
low = mid + 1;
else
high = mid;
}
// every remaining contract tuple of the row is larger than every one of B
if (low == runsB)
break;
lo = low;
if (key != run_key[low])
continue;
run = low;
}
else {
auto key = index_A_cache.data() + ptrA * i1i2_size;
size_t low = lo, high = runsB;
while (low < high) {
const size_t mid = low + (high - low) / 2;
if (lexico_compare(index_B_cache.data() + rowptrB[mid] * i1i2_size, key, i1i2_size) < 0)
low = mid + 1;
else
high = mid;
}
if (low == runsB)
break;
lo = low;
if (lexico_compare(index_B_cache.data() + rowptrB[low] * i1i2_size, key, i1i2_size) != 0)
continue;
run = low;
}
// the pass that searched remembers the run for the passes that follow it
if (cached_runs)
run_of_entry[ptrA] = static_cast<uint32_t>(run);
}
// the contract tuples of a row are distinct, so the runs it reaches are disjoint
if (!work_only) {
run_first.push_back(rowptrB[run]);
run_last.push_back(rowptrB[run + 1]);
}
work += rowptrB[run + 1] - rowptrB[run];
if (run_val != nullptr)
run_val->push_back(val_A_at(ptrA));
}
return work;
};
// what the row loop below writes to: the result itself, or, in the parallel path, a first pass
// that only counts positions, since a block has to know where its slice starts to write into it
struct count_sink {
// counts merged positions: no value is computed and no tuple copied for this sink
size_t n = 0;
void push_back(const index_v&, const T&) { n++; }
};
struct slice_sink {
sparse_tensor<T, index_t, SPARSE_COO>* target = nullptr;
size_t pos = 0;
void push_back(const index_v& l, const T& val) {
s_copy(target->data.colptr + pos * target->rank(), l.data(), target->rank());
target->data.valptr[pos] = val;
pos++;
};
};
auto method = [&]<typename Sink>(Sink& C, size_t ss, size_t ee) {
// the pass that only counts positions is the one that counts into count_sink
constexpr bool structural = std::is_same_v<Sink, count_sink>;
index_v indexC(dimsC.size());
// the row that is being built: the runs of B it reaches, the entry of A that reaches each of
// them, the entry of B each run is read at, and the heap that merges them; reused per row
std::vector<size_t> run_first, run_last, pos;
std::vector<std::pair<size_t, size_t>> heap;
std::vector<T> run_val;
// the value the counting sink never reads
[[maybe_unused]] const T dummy = 0;
// hand the entry at free_part to the sink: the structural pass counts it, the pass that fills
// the result computes its value and writes it when it does not cancel
auto emit = [&](const index_p free_part, auto&& value) {
if constexpr (structural) {
C.push_back(indexC, dummy);
}
else {
const T& entry = value(); // a reference, so a computed temporary is not copied
if (entry != 0) {
if (left_size_B != 0)
s_copy(indexC.data() + left_size_A, free_part, left_size_B);
C.push_back(indexC, entry);
}
}
};
for (size_t k = ss; k < ee; k++) {
// from rowptrA[k] to rowptrA[k + 1] are the same
auto startA = rowptrA[k];
for (size_t l = 0; l < left_size_A; l++)
indexC[l] = A.index(permA_at(startA))[index_perm_A[l]];
run_first.clear();
run_last.clear();
run_val.clear();
// the structural pass does not need the values of A
select(k, run_first, run_last, structural ? nullptr : &run_val);
const size_t m = run_first.size();
if (m == 0)
continue;
// a run holds ordered distinct free tuples, so a row that reaches one is written as is
if (m == 1 && left_size_B > 0) {
for (size_t ptrB = run_first[0]; ptrB < run_last[0]; ptrB++)
emit(index_leftB_cache.data() + ptrB * left_size_B,
[&] { return scalar_mul(run_val[0], val_B_at(ptrB), F); });
}
// with no free index a run holds the entries that share the whole index vector, so the
// row adds up to a single position and there is nothing to merge
else if (left_size_B == 0) {
emit(nullptr, [&] { // one position at most: there is no free tuple to merge
T entry = 0;
for (size_t j = 0; j < m; j++) {
for (size_t ptrB = run_first[j]; ptrB < run_last[j]; ptrB++)
entry = scalar_add(entry, scalar_mul(run_val[j], val_B_at(ptrB), F), F);
}
return entry;
});
}
// two runs merge with two pointers, which beats a heap of two entries
else if (m == 2) {
size_t p0 = run_first[0], p1 = run_first[1];
const bool keyed = keyed_leftB;
auto advance = [&](const size_t j, const size_t ptrB) {
emit(index_leftB_cache.data() + ptrB * left_size_B,
[&] { return scalar_mul(run_val[j], val_B_at(ptrB), F); });
};
auto compare_free = [&](const size_t a, const size_t b) {
if (keyed)
return key_leftB_at(a) < key_leftB_at(b) ? -1 : key_leftB_at(a) > key_leftB_at(b) ? 1 : 0;
return lexico_compare(index_leftB_cache.data() + a * left_size_B,
index_leftB_cache.data() + b * left_size_B, left_size_B);
};
while (p0 < run_last[0] && p1 < run_last[1]) {
const int cmp = compare_free(p0, p1);
if (cmp < 0) {
advance(0, p0);
p0++;
}
else if (cmp > 0) {
advance(1, p1);
p1++;
}
else {
emit(index_leftB_cache.data() + p0 * left_size_B, [&] {
return scalar_add(scalar_mul(run_val[0], val_B_at(p0), F),
scalar_mul(run_val[1], val_B_at(p1), F), F);
});
p0++;
p1++;
}
}
while (p0 < run_last[0])
advance(0, p0++);
while (p1 < run_last[1])
advance(1, p1++);
}
// several runs are merged: the smallest of the entries that wait at their fronts comes
// first, and the ones that share a free tuple are added up
else {
pos.resize(m);
const bool keyed = keyed_leftB;
// the heap holds the key of the entry at the front of a run next to the slot of that
// run, so that two runs compare with one comparison; without keys their free tuples
// are walked instead
heap.clear();
for (size_t j = 0; j < m; j++) {
pos[j] = run_first[j];
heap.emplace_back(keyed ? key_leftB_at(pos[j]) : 0, j);
}
auto free_front = [&](const size_t j) {
return index_leftB_cache.data() + pos[j] * left_size_B;
};
auto later = [&](const std::pair<size_t, size_t>& a, const std::pair<size_t, size_t>& b) {
if (keyed)
return a.first > b.first;
return lexico_compare(free_front(a.second), free_front(b.second), left_size_B) > 0;
};
// restore the heap after its front has been replaced: one sift down, where popping and
// pushing would adjust it twice
auto sift_down = [&](size_t i) {
const size_t n = heap.size();
for (;;) {
size_t c = 2 * i + 1;
if (c >= n)
break;
if (c + 1 < n && later(heap[c], heap[c + 1]))
c++;
if (!later(heap[i], heap[c]))
break;
std::swap(heap[i], heap[c]);
i = c;
}
};
std::make_heap(heap.begin(), heap.end(), later);
while (!heap.empty()) {
// free_min stays valid: only the positions move below, not the cache
const index_p free_min = free_front(heap.front().second);
const size_t key_min = heap.front().first;
T entry = 0;
// the runs whose front holds the smallest free tuple share one entry
do {
const size_t j = heap.front().second;
const size_t ptr = pos[j];
// a run that still has entries keeps its place, an exhausted one loses its front
if (++pos[j] < run_last[j]) {
heap.front() = { keyed ? key_leftB_at(pos[j]) : 0, j };
sift_down(0);
}
else {
std::pop_heap(heap.begin(), heap.end(), later);
heap.pop_back();
}
if constexpr (!structural)
entry = scalar_add(entry, scalar_mul(run_val[j], val_B_at(ptr), F), F);
} while (!heap.empty() && (keyed ? heap.front().first == key_min
: lexico_compare(free_front(heap.front().second), free_min, left_size_B) == 0));
emit(free_min, [&]() -> const T& { return entry; });
}
}
}
};
// parallel version
if (pool != nullptr) {
const size_t rows = rowptrA.size() - 1;
if (rows < 2 * nthread) {
method(C, 0, rows);
// this path grows C by push_back, so its capacity can be twice what it holds
C.shrink_to_fit();
return C;
}
size_t nblocks = rows < 64 * nthread ? nthread : 8 * nthread;
// the work of a row is the number of entries of B that it reads, which varies widely from
// row to row, so the rows are handed to the blocks by that work instead of by their number
std::vector<size_t> work_till(rows + 1, 0);
pool->detach_loop(0, rows, [&](const size_t k) {
// only the work is needed, so the two vectors stay empty and no row allocates
std::vector<size_t> run_first, run_last;
work_till[k + 1] = select(k, run_first, run_last, nullptr, true);
}, nblocks);
pool->wait();
for (size_t k = 0; k < rows; k++)
work_till[k + 1] += work_till[k];
const size_t allwork = work_till[rows];
std::vector<std::pair<size_t, size_t>> ranges(nblocks);
size_t start = 0;
for (size_t i = 0; i < nblocks; i++) {
const size_t target = static_cast<size_t>(static_cast<unsigned long long>(allwork) * (i + 1) / nblocks);
size_t end = start;
while (end < rows && work_till[end] < target)
end++;
if (end == start && end < rows)
end++;
ranges[i] = { start, end };
start = end;
}
ranges[nblocks - 1].second = rows;
// count the positions of every block first -- an upper bound, since a position whose sum
// cancels is not written -- so that each block can then write compactly into its own slice.
// The counts are stored as the offsets, so the count of a block is the difference of two
std::vector<size_t> start_pos(nblocks + 1, 0);
pool->detach_sequence(0, nblocks, [&](const size_t i) {
count_sink sink;
method(sink, ranges[i].first, ranges[i].second);
start_pos[i + 1] = sink.n;
});
pool->wait();
for (size_t i = 0; i < nblocks; i++)
start_pos[i + 1] += start_pos[i];
C.reserve(start_pos[nblocks]);
C.resize(start_pos[nblocks]);
std::vector<size_t> written(nblocks, 0);
pool->detach_sequence(0, nblocks, [&](const size_t i) {
slice_sink sink{ &C, start_pos[i] };
method(sink, ranges[i].first, ranges[i].second);
written[i] = sink.pos - start_pos[i];
});
pool->wait();
// a cancelled position leaves a hole at the end of the slice of its block, so the slices
// behind the first hole slide down; without a hole this only walks the blocks
size_t hole = 0;
for (size_t i = 0; i < nblocks; i++) {
if (hole != 0) {
// element wise, not a memmove: a memmove bit copies the values, and the copies it
// leaves in the moved-from slots are destroyed by release() as well, which frees
// their data twice for a type with a destructor
const size_t dst = start_pos[i] - hole;
std::move(C.data.colptr + start_pos[i] * C.rank(),
C.data.colptr + (start_pos[i] + written[i]) * C.rank(),
C.data.colptr + dst * C.rank());
std::move(C.data.valptr + start_pos[i], C.data.valptr + start_pos[i] + written[i],
C.data.valptr + dst);
}