-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsparse_tensor.h
More file actions
1688 lines (1485 loc) · 56.8 KB
/
Copy pathsparse_tensor.h
File metadata and controls
1688 lines (1485 loc) · 56.8 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 <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();
C.reserve(nnzA * nnzB);
C.resize(nnzA * nnzB);
auto permA = A.gen_perm(pool);
auto permB = B.gen_perm(pool);
auto fill_row = [&](const size_t r) {
const auto posA = permA[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[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
constexpr size_t par_product_threshold = 1u << 17;
if (pool != nullptr && nnzA * nnzB >= par_product_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());
auto Aperm = A.gen_perm();
auto Bperm = B.gen_perm();
// double pointer
size_t i = 0, j = 0;
// C.zero();
while (i < A.nnz() && j < B.nnz()) {
auto posA = Aperm[i];
auto posB = Bperm[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[i];
C.push_back(A.index(posA), A.val(posA));
i++;
}
while (j < B.nnz()) {
auto posB = Bperm[j];
C.push_back(B.index(posB), B.val(posB));
j++;
}
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 the contract tuple and then by its free indices, so that the entries that
// share a contract tuple are consecutive and a row of the result is built by looking up the
// contract tuple of each of its entries in B, instead of by matching every pair of rows of A
// and B
index_perm_B.insert(index_perm_B.begin(), i2.begin(), i2.end());
auto permA = A.gen_perm(index_perm_A, pool);
auto permB = B.gen_perm(index_perm_B, pool);
sparse_tensor<T, index_t, SPARSE_COO> C(dimsC);
auto i1i2_size = i1.size();
auto left_size_A = A.rank() - i1i2_size;
auto left_size_B = B.rank() - i1i2_size;
// an empty operand leaves the caches below empty, so there is nothing to read from them
if (A.nnz() == 0 || B.nnz() == 0)
return C;
// the contract tuple and the free tuple of every entry, in the order of the permutations: the
// loops below then compare neighbouring entries without following an index permutation
// a tuple is packed into a number in mixed radix whenever its dimensions allow it, because a
// packed key compares with one comparison instead of one per position, and because the keys of
// the entries that start a run can be kept in a flat array, which makes the binary searches
// below walk that array instead of chasing rowptrB. A tuple that does not fit keeps its cache
// and is compared position by position
constexpr size_t max_buckets = 1u << 20;
constexpr size_t par_pack_threshold = 1u << 17;
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;
}
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());
}
if (keyed_leftA)
key_leftA.resize(A.nnz());
if (keyed_leftB)
key_leftB.resize(B.nnz());
// a label below zero would not order like the tuple once packed, so the keys are dropped when
// an entry says otherwise, and the tuples are then compared position by position
std::atomic<bool> negative{ false };
for (size_t k = 0; k < A.nnz() && (keyed_contract || keyed_leftA); k++) {
auto ptr = A.index(permA[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) {
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[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) {
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() >= par_pack_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();
}
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[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[k]);
for (size_t l = 0; l < i1i2_size; l++)
index_B_cache[k * i1i2_size + l] = ptr[i2[l]];
}
}
// the values of the entries in the order of the permutations: the loops below walk the runs in
// that order, so reading the values through the permutation would gather them at random and
// miss the cache on every step; the copy that builds these arrays is sequential
std::vector<T> val_A(A.nnz()), val_B(B.nnz());
for (size_t k = 0; k < A.nnz(); k++)
val_A[k] = A.val(permA[k]);
if (pool != nullptr && B.nnz() >= par_pack_threshold) {
pool->detach_loop(0, B.nnz(), [&](const size_t k) { val_B[k] = B.val(permB[k]); }, 4 * nthread);
pool->wait();
}
else {
for (size_t k = 0; k < B.nnz(); k++)
val_B[k] = B.val(permB[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 the free part
// 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[k] != key_leftA[k - 1])
rowptrA.push_back(k);
}
}
else {
for (size_t k = 1; k < A.nnz(); k++) {
if (!equal_except(A.index(permA[rowptrA.back()]), A.index(permA[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 contract tuple is a single label that is small enough, the run
// that holds each label, so that the search of the run of an entry of A is one array read
std::vector<size_t> run_key, run_of_value;
if (keyed_contract) {
run_key.resize(runsB);
for (size_t r = 0; r < runsB; r++)
run_key[r] = key_contract_B[rowptrB[r]];
}
if (keyed_contract && i1i2_size == 1 && dimsA[i1[0]] > 0 && dimsA[i1[0]] <= max_buckets) {
run_of_value.assign(dimsA[i1[0]], std::numeric_limits<size_t>::max());
for (size_t r = 0; r < runsB; r++)
run_of_value[run_key[r]] = r;
}
// the runs of B that a row of A reaches: the entries of a row are ordered by their contract
// tuple, so the run of B that holds a contract tuple is found by binary search, and the search
// of the next entry starts at the run found for the previous one; when the contract tuple is a
// single small label the lookup table answers in one read, and no search is needed at all.
// The work of a row is the number of entries of B it reads, which 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 tabulated = !run_of_value.empty();
size_t work = 0;
size_t lo = 0;
for (size_t ptrA = rowptrA[k]; ptrA < rowptrA[k + 1]; ptrA++) {
size_t run;
if (tabulated) {
const size_t value = key_contract_A[ptrA];
if (value >= run_of_value.size())
continue;
run = run_of_value[value];
if (run == std::numeric_limits<size_t>::max())
continue;
}
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 contract tuples of a row are distinct, so the runs it reaches are disjoint
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[ptrA]);
}
return work;
};
auto method = [&](sparse_tensor<T, index_t>& C, size_t ss, size_t ee) {
index_v indexC(dimsC.size());
// the runs of B that the row that is being built reaches, the entry of A that reaches each
// of them, the entry of B each run is read at, and the heap that merges the runs; the
// buffers are reused across the rows
std::vector<size_t> run_first, run_last, pos;
std::vector<std::pair<size_t, size_t>> heap;
std::vector<T> run_val;
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[startA])[index_perm_A[l]];
run_first.clear();
run_last.clear();
run_val.clear();
select(k, run_first, run_last, &run_val);
const size_t m = run_first.size();
if (m == 0)
continue;
// the free tuples of a run are ordered and distinct, so a row that reaches a single run
// that keeps at least one free index is written out as it is
if (m == 1 && left_size_B > 0) {
for (size_t ptrB = run_first[0]; ptrB < run_last[0]; ptrB++) {
const T entry = scalar_mul(run_val[0], val_B[ptrB], F);
if (entry != 0) {
s_copy(indexC.data() + left_size_A, index_leftB_cache.data() + ptrB * left_size_B,
left_size_B);
C.push_back(indexC, entry);
}
}
}
// the runs of such a contraction hold one entry each, since a run is a maximal group of
// entries that share the whole index vector when there is no free index, so the row adds
// up to one entry of the result and there is nothing to merge
else if (left_size_B == 0) {
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[ptrB], F), F);
}
if (entry != 0)
C.push_back(indexC, 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 = !key_leftB.empty();
auto advance = [&](const size_t j, const size_t ptrB) {
const T entry = scalar_mul(run_val[j], val_B[ptrB], F);
if (entry != 0) {
s_copy(indexC.data() + left_size_A, index_leftB_cache.data() + ptrB * left_size_B,
left_size_B);
C.push_back(indexC, entry);
}
};
auto compare_free = [&](const size_t a, const size_t b) {
if (keyed)
return key_leftB[a] < key_leftB[b] ? -1 : key_leftB[a] > key_leftB[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 {
const T entry = scalar_add(scalar_mul(run_val[0], val_B[p0], F),
scalar_mul(run_val[1], val_B[p1], F), F);
if (entry != 0) {
s_copy(indexC.data() + left_size_A, index_leftB_cache.data() + p0 * left_size_B,
left_size_B);
C.push_back(indexC, entry);
}
p0++;
p1++;
}
}
while (p0 < run_last[0])
advance(0, p0++);
while (p1 < run_last[1])
advance(1, p1++);
}
// a row that reaches several runs, or a run that keeps no free index, is built by merging
// them: the free tuples of one run are ordered, so the smallest of the entries that wait
// at the front of the runs comes first, and the entries that share a free tuple are added
// up
else {
pos.resize(m);
const bool keyed = !key_leftB.empty();
// the heap holds the key of the entry that waits at the front of a run next to the
// slot of that run: the order of two runs is then one comparison of two words that
// sit in the same array, where reading the key through the position table is a load
// that depends on the heap entry; a run whose free tuple has no key is ordered by
// walking its tuple
heap.clear();
for (size_t j = 0; j < m; j++) {
pos[j] = run_first[j];
heap.emplace_back(keyed ? key_leftB[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;
};
std::make_heap(heap.begin(), heap.end(), later);
while (!heap.empty()) {
// free_min stays valid: the cache is not modified below, only the positions are
const index_p free_min = free_front(heap.front().second);
const size_t key_min = heap.front().first;
T entry = 0;
// every run whose front holds the smallest free tuple contributes to the same
// entry of the result
do {
const size_t j = heap.front().second;
std::pop_heap(heap.begin(), heap.end(), later);
heap.pop_back();
entry = scalar_add(entry, scalar_mul(run_val[j], val_B[pos[j]], F), F);
if (++pos[j] < run_last[j]) {
heap.emplace_back(keyed ? key_leftB[pos[j]] : 0, j);
std::push_heap(heap.begin(), heap.end(), later);
}
} while (!heap.empty() && (keyed ? heap.front().first == key_min
: lexico_compare(free_front(heap.front().second), free_min, left_size_B) == 0));
if (entry != 0) {
s_copy(indexC.data() + left_size_A, free_min, left_size_B);
C.push_back(indexC, entry);
}
}
}
}
};
// parallel version
if (pool != nullptr) {
const size_t rows = rowptrA.size() - 1;
if (rows < 2 * nthread) {
method(C, 0, rows);
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) {
std::vector<size_t> run_first, run_last;
work_till[k + 1] = select(k, run_first, run_last, nullptr);
}, 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;
std::vector<sparse_tensor<T, index_t, SPARSE_COO>> Cs(nblocks, C);
pool->detach_sequence(0, nblocks, [&](size_t i) {
method(Cs[i], ranges[i].first, ranges[i].second);
});
pool->wait();
// merge the results
size_t allnnz = 0;
std::vector<size_t> start_pos(nblocks);
for (size_t i = 0; i < nblocks; i++) {
start_pos[i] = allnnz;
allnnz += Cs[i].nnz();
}
C.reserve(allnnz);
C.resize(allnnz);
pool->detach_loop(0, nblocks, [&](size_t i) {
const auto tmpnnz = Cs[i].nnz();
T* valptr = C.data.valptr + start_pos[i];
index_p colptr = C.data.colptr + start_pos[i] * C.rank();
s_copy(colptr, Cs[i].data.colptr, tmpnnz * C.rank());
s_copy(valptr, Cs[i].data.valptr, tmpnnz);
Cs[i].clear();
});
pool->wait();
return C;
}
else {
method(C, 0, rowptrA.size() - 1);
return C;
}
}
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 size_t i, const size_t j, const field_t& F, thread_pool* pool = nullptr) {
return tensor_contract(A, B, std::vector<size_t>{ i }, std::vector<size_t>{ j }, F, pool);
}
// contract the a-th index of A with the 0-th index of B, then move the remaining indices of B into
// the slot of the contracted index: the result has rank A.rank() + B.rank() - 2 and the order
// [A[0..a-1], B[1], A[a+1..], B[2..]], so that contracting with a matrix reads like a matrix
// product. The result is sorted unless sort_ind is false.
template <typename index_t, typename T>
sparse_tensor<T, index_t, SPARSE_COO> tensor_contract_2(
const sparse_tensor<T, index_t, SPARSE_COO>& A,
const sparse_tensor<T, index_t, SPARSE_COO>& B,
const size_t a, const field_t& F, thread_pool* pool = nullptr, const bool sort_ind = true) {
const size_t rankA = A.rank();
const size_t rankB = B.rank();
if (rankA == 0 || rankB == 0 || a >= rankA) {
std::cerr << "Error: tensor_contract_2: cannot contract index " << a << " of a rank " << rankA
<< " tensor with a rank " << rankB << " tensor." << std::endl;
return sparse_tensor<T, index_t, SPARSE_COO>();
}
// tensor_contract returns the order [A except a] ++ [B except 0], so perm[i] is the old slot of
// the new slot i, and the rank of the result fixes the size of perm
auto C = tensor_contract(A, B, a, 0, F, pool);
std::vector<size_t> perm;
perm.reserve(rankA + rankB - 2);
for (size_t k = 0; k < a; k++)
perm.push_back(k);
if (rankB > 1)
perm.push_back(rankA - 1);
for (size_t k = a; k + 1 < rankA; k++)
perm.push_back(k);
for (size_t k = rankA; k + 1 < rankA + rankB - 1; k++)
perm.push_back(k);
C.transpose_replace(perm, pool, sort_ind);
return C;
}
// self contraction: C[rest] = sum_k A[..., i=k, ..., j=k, ...], requires i != j
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 size_t i, const size_t j, const field_t& F, thread_pool* pool = nullptr) {
using index_v = std::vector<index_t>;
using index_p = index_t*;
if (i >= A.rank() || j >= A.rank()) {
std::cerr << "Error: tensor_contract: cannot contract index " << i << " and " << j << " of a rank "
<< A.rank() << " tensor." << std::endl;
return sparse_tensor<T, index_t, SPARSE_COO>();
}
if (i == j) {
std::cerr << "Error: tensor_contract: The two contraction indices must be different." << std::endl;
return sparse_tensor<T, index_t, SPARSE_COO>();
}
if (i > j)
return tensor_contract(A, j, i, F, pool);
// then i < j
std::vector<size_t> dimsA = A.dims();
auto rank = A.rank();
std::vector<size_t> dimsC;
for (size_t k = 0; k < dimsA.size(); k++) {
if (k != i && k != j)
dimsC.push_back(dimsA[k]);
}
std::vector<size_t> equal_ind_list;
// search for the same indices
constexpr size_t par_scan_threshold = 1u << 17;
if (pool != nullptr && A.nnz() >= par_scan_threshold) {
// the scan is a plain pass over the tensor and is what the serial version spends most of
// its time on, so above the threshold it is worth handing its blocks to the pool
const size_t nthread = pool->get_thread_count();
const size_t nblocks = A.nnz() < 64 * nthread ? nthread : 8 * nthread;
std::vector<std::vector<size_t>> parts(nblocks);
pool->detach_loop(0, nblocks, [&](const size_t blk) {
const size_t first = A.nnz() * blk / nblocks;
const size_t last = A.nnz() * (blk + 1) / nblocks;
auto& part = parts[blk];
for (size_t k = first; k < last; k++) {
if (A.index(k)[i] == A.index(k)[j])
part.push_back(k);
}
}, nblocks);
pool->wait();
size_t total = 0;
for (auto& part : parts)
total += part.size();
equal_ind_list.reserve(total);
// the blocks cover increasing ranges of k, so the concatenation keeps the order
for (auto& part : parts) {
equal_ind_list.insert(equal_ind_list.end(), part.begin(), part.end());
std::vector<size_t>().swap(part);
}
}
else {
for (size_t k = 0; k < A.nnz(); k++) {
if (A.index(k)[i] == A.index(k)[j]) {
equal_ind_list.push_back(k);
}
}
}
std::vector<size_t> index_perm;
for (size_t k = 0; k < rank; k++) {
if (k != i && k != j)
index_perm.push_back(k);
}
index_perm.push_back(i);
index_perm.push_back(j);
auto perm = perm_init(equal_ind_list.size());
auto by_index = [&](size_t a, size_t b) {
return lexico_compare(A.index(equal_ind_list[a]), A.index(equal_ind_list[b]), index_perm) < 0;
};
parallel_sort(perm.begin(), perm.end(), by_index, pool);
std::vector<size_t> rowptr;
rowptr.push_back(0);
auto equal_except_ij = [&](const index_t* a, const index_t* b) {
// do not compare the i-th and j-th index
for (size_t k = 0; k < rank; k++)
if (k != i && k != j && a[k] != b[k])
return false;
return true;
};
for (size_t k = 1; k < equal_ind_list.size(); k++) {
if (!equal_except_ij(A.index(equal_ind_list[perm[k]]), A.index(equal_ind_list[perm[rowptr.back()]])))
rowptr.push_back(k);
}
rowptr.push_back(equal_ind_list.size());