This repository has been archived by the owner on Dec 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
blocksparsetensor.jl
1229 lines (1082 loc) · 36 KB
/
blocksparsetensor.jl
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
#
# BlockSparseTensor (Tensor using BlockSparse storage)
#
const BlockSparseTensor{ElT,N,StoreT,IndsT} =
Tensor{ElT,N,StoreT,IndsT} where {StoreT<:BlockSparse}
nonzeros(T::Tensor) = data(T)
# Special version for BlockSparseTensor
# Generic version doesn't work since BlockSparse us parametrized by
# the Tensor order
function similartype(
::Type{<:Tensor{ElT,NT,<:BlockSparse{ElT,VecT},<:Any}}, ::Type{IndsR}
) where {NT,ElT,VecT,IndsR}
NR = length(IndsR)
return Tensor{ElT,NR,BlockSparse{ElT,VecT,NR},IndsR}
end
function similartype(
::Type{<:Tensor{ElT,NT,<:BlockSparse{ElT,VecT},<:Any}}, ::Type{IndsR}
) where {NT,ElT,VecT,IndsR<:NTuple{NR}} where {NR}
return Tensor{ElT,NR,BlockSparse{ElT,VecT,NR},IndsR}
end
function BlockSparseTensor(
::Type{ElT}, ::UndefInitializer, boffs::BlockOffsets, inds
) where {ElT<:Number}
nnz_tot = nnz(boffs, inds)
storage = BlockSparse(ElT, undef, boffs, nnz_tot)
return tensor(storage, inds)
end
function BlockSparseTensor(
::Type{ElT}, ::UndefInitializer, blocks::Vector{BlockT}, inds
) where {ElT<:Number,BlockT<:Union{Block,NTuple}}
boffs, nnz = blockoffsets(blocks, inds)
storage = BlockSparse(ElT, undef, boffs, nnz)
return tensor(storage, inds)
end
"""
BlockSparseTensor(::UndefInitializer, blocks, inds)
Construct a block sparse tensor with uninitialized memory
from indices and locations of non-zero blocks.
"""
function BlockSparseTensor(::UndefInitializer, blockoffsets, inds)
return BlockSparseTensor(Float64, undef, blockoffsets, inds)
end
function BlockSparseTensor(
::Type{ElT}, blockoffsets::BlockOffsets{N}, inds
) where {ElT<:Number,N}
nnz_tot = nnz(blockoffsets, inds)
storage = BlockSparse(ElT, blockoffsets, nnz_tot)
return tensor(storage, inds)
end
function BlockSparseTensor(blockoffsets::BlockOffsets, inds)
return BlockSparseTensor(Float64, blockoffsets, inds)
end
"""
BlockSparseTensor(inds)
Construct a block sparse tensor with no blocks.
"""
BlockSparseTensor(inds) = BlockSparseTensor(BlockOffsets{length(inds)}(), inds)
function BlockSparseTensor(::Type{ElT}, inds) where {ElT<:Number,N}
return BlockSparseTensor(ElT, BlockOffsets{length(inds)}(), inds)
end
"""
BlockSparseTensor(inds)
Construct a block sparse tensor with no blocks.
"""
function BlockSparseTensor(inds::Vararg{DimT,N}) where {DimT,N}
return BlockSparseTensor(BlockOffsets{N}(), inds)
end
"""
BlockSparseTensor(blocks::Vector{Block{N}}, inds)
Construct a block sparse tensor with the specified blocks.
Defaults to setting structurally non-zero blocks to zero.
"""
function BlockSparseTensor(blocks::Vector{BlockT}, inds) where {BlockT<:Union{Block,NTuple}}
return BlockSparseTensor(Float64, blocks, inds)
end
function BlockSparseTensor(
::Type{ElT}, blocks::Vector{BlockT}, inds
) where {ElT<:Number,BlockT<:Union{Block,NTuple}}
boffs, nnz = blockoffsets(blocks, inds)
storage = BlockSparse(ElT, boffs, nnz)
return tensor(storage, inds)
end
#complex(::Type{BlockSparseTensor{ElT,N,StoreT,IndsT}}) where {ElT<:Number,N,StoreT<:BlockSparse
# = Tensor{ElT,N,StoreT,IndsT} where {StoreT<:BlockSparse}
function randn(
::Type{<:BlockSparseTensor{ElT,N}}, blocks::Vector{<:BlockT}, inds
) where {ElT,BlockT<:Union{Block{N},NTuple{N,<:Integer}}} where {N}
boffs, nnz = blockoffsets(blocks, inds)
storage = randn(BlockSparse{ElT}, boffs, nnz)
return tensor(storage, inds)
end
# XXX: use the syntax:
# BlockSparseTensor(randn, ElT, blocks, inds)
function randomBlockSparseTensor(
::Type{ElT}, blocks::Vector{<:BlockT}, inds
) where {ElT,BlockT<:Union{Block{N},NTuple{N,<:Integer}}} where {N}
return randn(BlockSparseTensor{ElT,N}, blocks, inds)
end
function randomBlockSparseTensor(blocks::Vector, inds)
return randomBlockSparseTensor(Float64, blocks, inds)
end
"""
BlockSparseTensor(blocks::Vector{Block{N}},
inds::BlockDims...)
Construct a block sparse tensor with the specified blocks.
Defaults to setting structurally non-zero blocks to zero.
"""
function BlockSparseTensor(
blocks::Vector{BlockT}, inds::Vararg{BlockDim,N}
) where {BlockT<:Union{Block{N},NTuple{N,<:Integer}}} where {N}
return BlockSparseTensor(blocks, inds)
end
function similar(
::BlockSparseTensor{ElT,N}, blockoffsets::BlockOffsets{N}, inds
) where {ElT,N}
return BlockSparseTensor(ElT, undef, blockoffsets, inds)
end
function similar(
::Type{<:BlockSparseTensor{ElT,N}}, blockoffsets::BlockOffsets{N}, inds
) where {ElT,N}
return BlockSparseTensor(ElT, undef, blockoffsets, inds)
end
# This version of similar creates a tensor with no blocks
function similar(::Type{TensorT}, inds::Tuple) where {TensorT<:BlockSparseTensor}
return similar(TensorT, BlockOffsets{ndims(TensorT)}(), inds)
end
function zeros(
::BlockSparseTensor{ElT,N}, blockoffsets::BlockOffsets{N}, inds
) where {ElT,N}
return BlockSparseTensor(ElT, blockoffsets, inds)
end
function zeros(
::Type{<:BlockSparseTensor{ElT,N}}, blockoffsets::BlockOffsets{N}, inds
) where {ElT,N}
return BlockSparseTensor(ElT, blockoffsets, inds)
end
function zeros(::BlockSparseTensor{ElT,N}, inds) where {ElT,N}
return BlockSparseTensor(ElT, inds)
end
function zeros(::Type{<:BlockSparseTensor{ElT,N}}, inds) where {ElT,N}
return BlockSparseTensor(ElT, inds)
end
# Basic functionality for AbstractArray interface
IndexStyle(::Type{<:BlockSparseTensor}) = IndexCartesian()
# Get the CartesianIndices for the range of indices
# of the specified
function blockindices(T::BlockSparseTensor{ElT,N}, block) where {ElT,N}
return CartesianIndex(blockstart(T, block)):CartesianIndex(blockend(T, block))
end
"""
indexoffset(T::BlockSparseTensor,i::Int...) -> offset,block,blockoffset
Get the offset in the data of the specified
CartesianIndex. If it falls in a block that doesn't
exist, return nothing for the offset.
Also returns the block the index is found in and the offset
within the block.
"""
function indexoffset(T::BlockSparseTensor{ElT,N}, i::Vararg{Int,N}) where {ElT,N}
index_within_block, block = blockindex(T, i...)
block_dims = blockdims(T, block)
offset_within_block = LinearIndices(block_dims)[CartesianIndex(index_within_block)]
offset_of_block = offset(T, block)
offset_of_i = isnothing(offset_of_block) ? nothing : offset_of_block + offset_within_block
return offset_of_i, block, offset_within_block
end
# TODO: Add a checkbounds
# TODO: write this nicer in terms of blockview?
# Could write:
# block,index_within_block = blockindex(T,i...)
# return blockview(T,block)[index_within_block]
@propagate_inbounds function getindex(
T::BlockSparseTensor{ElT,N}, i::Vararg{Int,N}
) where {ElT,N}
offset, _ = indexoffset(T, i...)
isnothing(offset) && return zero(ElT)
return storage(T)[offset]
end
@propagate_inbounds function getindex(T::BlockSparseTensor{ElT,0}) where {ElT}
nnzblocks(T) == 0 && return zero(ElT)
return storage(T)[]
end
# These may not be valid if the Tensor has no blocks
#@propagate_inbounds getindex(T::BlockSparseTensor{<:Number,1},ind::Int) = storage(T)[ind]
#@propagate_inbounds getindex(T::BlockSparseTensor{<:Number,0}) = storage(T)[1]
# Add the specified block to the BlockSparseTensor
# Insert it such that the blocks remain ordered.
# Defaults to adding zeros.
# Returns the offset of the new block added.
# XXX rename to insertblock!, no need to return offset
function insertblock_offset!(T::BlockSparseTensor{ElT,N}, newblock::Block{N}) where {ElT,N}
newdim = blockdim(T, newblock)
newoffset = nnz(T)
insert!(blockoffsets(T), newblock, newoffset)
# Insert new block into data
splice!(data(storage(T)), (newoffset + 1):newoffset, zeros(ElT, newdim))
return newoffset
end
function insertblock!(T::BlockSparseTensor{<:Number,N}, block::Block{N}) where {N}
insertblock_offset!(T, block)
return T
end
insertblock!(T::BlockSparseTensor, block) = insertblock!(T, Block(block))
# TODO: Add a checkbounds
@propagate_inbounds function setindex!(
T::BlockSparseTensor{ElT,N}, val, i::Vararg{Int,N}
) where {ElT,N}
offset, block, offset_within_block = indexoffset(T, i...)
if isnothing(offset)
offset_of_block = insertblock_offset!(T, block)
offset = offset_of_block + offset_within_block
end
storage(T)[offset] = val
return T
end
hasblock(T::Tensor, block::Block) = isassigned(blockoffsets(T), block)
@propagate_inbounds function setindex!(
T::BlockSparseTensor{ElT,N}, val, b::Block{N}
) where {ElT,N}
if !hasblock(T, b)
insertblock!(T, b)
end
Tb = T[b]
Tb .= val
return T
end
getindex(T::BlockSparseTensor, block::Block) = blockview(T, block)
to_indices(T::Tensor{<:Any,N}, b::Tuple{Block{N}}) where {N} = blockindices(T, b...)
function blockview(T::BlockSparseTensor, block::Block)
return blockview(T, BlockOffset(block, offset(T, block)))
end
blockview(T::BlockSparseTensor, block) = blockview(T, Block(block))
function blockview(T::BlockSparseTensor, bof::BlockOffset)
blockT, offsetT = bof
blockdimsT = blockdims(T, blockT)
blockdimT = prod(blockdimsT)
dataTslice = @view data(storage(T))[(offsetT + 1):(offsetT + blockdimT)]
return tensor(Dense(dataTslice), blockdimsT)
end
view(T::BlockSparseTensor, b::Block) = blockview(T, b)
# convert to Dense
function dense(T::TensorT) where {TensorT<:BlockSparseTensor}
R = zeros(dense(TensorT), inds(T))
for block in keys(blockoffsets(T))
# TODO: make sure this assignment is efficient
R[blockindices(T, block)] = blockview(T, block)
end
return R
end
#
# Operations
#
# TODO: extend to case with different block structures
function +(T1::BlockSparseTensor{<:Number,N}, T2::BlockSparseTensor{<:Number,N}) where {N}
inds(T1) ≠ inds(T2) &&
error("Cannot add block sparse tensors with different block structure")
R = copy(T1)
return permutedims!!(R, T2, ntuple(identity, Val(N)), +)
end
function permutedims(T::BlockSparseTensor{<:Number,N}, perm::NTuple{N,Int}) where {N}
blockoffsetsR, indsR = permutedims(blockoffsets(T), inds(T), perm)
R = similar(T, blockoffsetsR, indsR)
permutedims!(R, T, perm)
return R
end
function _permute_combdims(combdims::NTuple{NC,Int}, perm::NTuple{NP,Int}) where {NC,NP}
res = MVector{NC,Int}(undef)
iperm = invperm(perm)
for i in 1:NC
res[i] = iperm[combdims[i]]
end
return Tuple(res)
end
#
# These are functions to help with combining and uncombining
#
# Note that combdims is expected to be contiguous and ordered
# smallest to largest
function combine_dims(blocks::Vector{Block{N}}, inds, combdims::NTuple{NC,Int}) where {N,NC}
nblcks = nblocks(inds, combdims)
blocks_comb = Vector{Block{N - NC + 1}}(undef, length(blocks))
for (i, block) in enumerate(blocks)
blocks_comb[i] = combine_dims(block, inds, combdims)
end
return blocks_comb
end
function combine_dims(block::Block, inds, combdims::NTuple{NC,Int}) where {NC}
nblcks = nblocks(inds, combdims)
slice = getindices(block, combdims)
slice_comb = LinearIndices(nblcks)[slice...]
block_comb = deleteat(block, combdims)
block_comb = insertafter(block_comb, tuple(slice_comb), minimum(combdims) - 1)
return block_comb
end
# In the dimension dim, permute the blocks
function perm_blocks(blocks::Blocks{N}, dim::Int, perm) where {N}
blocks_perm = Blocks{N}(undef, nnzblocks(blocks))
iperm = invperm(perm)
for (i, block) in enumerate(blocks)
blocks_perm[i] = setindex(block, iperm[block[dim]], dim)
end
return blocks_perm
end
# In the dimension dim, permute the block
function perm_block(block::Block, dim::Int, perm) where {N}
iperm = invperm(perm)
return setindex(block, iperm[block[dim]], dim)
end
# In the dimension dim, combine the specified blocks
function combine_blocks(blocks::Blocks, dim::Int, blockcomb::Vector{Int})
blocks_comb = copy(blocks)
nnz_comb = nnzblocks(blocks)
for (i, block) in enumerate(blocks)
dimval = block[dim]
blocks_comb[i] = setindex(block, blockcomb[dimval], dim)
end
unique!(blocks_comb)
return blocks_comb
end
function permutedims_combine_output(
T::BlockSparseTensor{ElT,N},
is,
perm::NTuple{N,Int},
combdims::NTuple{NC,Int},
blockperm::Vector{Int},
blockcomb::Vector{Int},
) where {ElT,N,NC}
# Permute the indices
indsT = inds(T)
inds_perm = permute(indsT, perm)
# Now that the indices are permuted, compute
# which indices are now combined
combdims_perm = sort(_permute_combdims(combdims, perm))
# Permute the nonzero blocks (dimension-wise)
blocks = nzblocks(T)
blocks_perm = permutedims(blocks, perm)
# Combine the nonzero blocks (dimension-wise)
blocks_perm_comb = combine_dims(blocks_perm, inds_perm, combdims_perm)
# Permute the blocks (within the newly combined dimension)
comb_ind_loc = minimum(combdims_perm)
blocks_perm_comb = perm_blocks(blocks_perm_comb, comb_ind_loc, blockperm)
blocks_perm_comb = sort(blocks_perm_comb; lt=isblockless)
# Combine the blocks (within the newly combined and permuted dimension)
blocks_perm_comb = combine_blocks(blocks_perm_comb, comb_ind_loc, blockcomb)
return BlockSparseTensor(ElT, blocks_perm_comb, is)
end
function permutedims_combine(
T::BlockSparseTensor{ElT,N},
is,
perm::NTuple{N,Int},
combdims::NTuple{NC,Int},
blockperm::Vector{Int},
blockcomb::Vector{Int},
) where {ElT,N,NC}
R = permutedims_combine_output(T, is, perm, combdims, blockperm, blockcomb)
# Permute the indices
inds_perm = permute(inds(T), perm)
# Now that the indices are permuted, compute
# which indices are now combined
combdims_perm = sort(_permute_combdims(combdims, perm))
comb_ind_loc = minimum(combdims_perm)
# Determine the new index before combining
inds_to_combine = getindices(inds_perm, combdims_perm)
ind_comb = ⊗(inds_to_combine...)
ind_comb = permuteblocks(ind_comb, blockperm)
for bof in pairs(blockoffsets(T))
Tb = blockview(T, bof)
b = nzblock(bof)
b_perm = permute(b, perm)
b_perm_comb = combine_dims(b_perm, inds_perm, combdims_perm)
b_perm_comb = perm_block(b_perm_comb, comb_ind_loc, blockperm)
b_in_combined_dim = b_perm_comb[comb_ind_loc]
new_b_in_combined_dim = blockcomb[b_in_combined_dim]
offset = 0
pos_in_new_combined_block = 1
while b_in_combined_dim - pos_in_new_combined_block > 0 &&
blockcomb[b_in_combined_dim - pos_in_new_combined_block] == new_b_in_combined_dim
offset += blockdim(ind_comb, b_in_combined_dim - pos_in_new_combined_block)
pos_in_new_combined_block += 1
end
b_new = setindex(b_perm_comb, new_b_in_combined_dim, comb_ind_loc)
Rb_total = blockview(R, b_new)
dimsRb_tot = dims(Rb_total)
subind = ntuple(
i -> if i == comb_ind_loc
range(1 + offset; stop=offset + blockdim(ind_comb, b_in_combined_dim))
else
range(1; stop=dimsRb_tot[i])
end,
N - NC + 1,
)
Rb = @view array(Rb_total)[subind...]
# XXX Are these equivalent?
#Tb_perm = permutedims(Tb,perm)
#copyto!(Rb,Tb_perm)
# XXX Not sure what this was for
Rb = reshape(Rb, permute(dims(Tb), perm))
Tbₐ = convert(Array, Tb)
@strided Rb .= permutedims(Tbₐ, perm)
end
return R
end
# TODO: optimize by avoiding findfirst
function _number_uncombined(blockval::Integer, blockcomb::Vector)
if blockval == blockcomb[end]
return length(blockcomb) - findfirst(==(blockval), blockcomb) + 1
end
return findfirst(==(blockval + 1), blockcomb) - findfirst(==(blockval), blockcomb)
end
# TODO: optimize by avoiding findfirst
function _number_uncombined_shift(blockval::Integer, blockcomb::Vector)
if blockval == 1
return 0
end
ncomb_shift = 0
for i in 1:(blockval - 1)
ncomb_shift += findfirst(==(i + 1), blockcomb) - findfirst(==(i), blockcomb) - 1
end
return ncomb_shift
end
# Uncombine the blocks along the dimension dim
# according to the pattern in blockcomb (for example, blockcomb
# is [1,2,2,3] and dim = 2, so the blocks (1,2),(2,3) get
# split into (1,2),(1,3),(2,4))
function uncombine_blocks(blocks::Blocks{N}, dim::Int, blockcomb::Vector{Int}) where {N}
blocks_uncomb = Blocks{N}()
ncomb_tot = 0
for i in 1:length(blocks)
block = blocks[i]
blockval = block[dim]
ncomb = _number_uncombined(blockval, blockcomb)
ncomb_shift = _number_uncombined_shift(blockval, blockcomb)
push!(blocks_uncomb, setindex(block, blockval + ncomb_shift, dim))
for j in 1:(ncomb - 1)
push!(blocks_uncomb, setindex(block, blockval + ncomb_shift + j, dim))
end
end
return blocks_uncomb
end
function uncombine_block(block::Block{N}, dim::Int, blockcomb::Vector{Int}) where {N}
blocks_uncomb = Blocks{N}()
ncomb_tot = 0
blockval = block[dim]
ncomb = _number_uncombined(blockval, blockcomb)
ncomb_shift = _number_uncombined_shift(blockval, blockcomb)
push!(blocks_uncomb, setindex(block, blockval + ncomb_shift, dim))
for j in 1:(ncomb - 1)
push!(blocks_uncomb, setindex(block, blockval + ncomb_shift + j, dim))
end
return blocks_uncomb
end
function uncombine_output(
T::BlockSparseTensor{ElT,N},
is,
combdim::Int,
blockperm::Vector{Int},
blockcomb::Vector{Int},
) where {ElT<:Number,N}
ind_uncomb_perm = ⊗(setdiff(is, inds(T))...)
inds_uncomb_perm = insertat(inds(T), ind_uncomb_perm, combdim)
# Uncombine the blocks of T
blocks_uncomb = uncombine_blocks(nzblocks(T), combdim, blockcomb)
blocks_uncomb_perm = perm_blocks(blocks_uncomb, combdim, invperm(blockperm))
boffs_uncomb_perm, nnz_uncomb_perm = blockoffsets(blocks_uncomb_perm, inds_uncomb_perm)
T_uncomb_perm = tensor(
BlockSparse(ElT, boffs_uncomb_perm, nnz_uncomb_perm), inds_uncomb_perm
)
R = reshape(T_uncomb_perm, is)
return R
end
function reshape(blockT::Block{NT}, indsT, indsR) where {NT}
nblocksT = nblocks(indsT)
nblocksR = nblocks(indsR)
blockR = Tuple(
CartesianIndices(nblocksR)[LinearIndices(nblocksT)[CartesianIndex(blockT)]]
)
return blockR
end
function uncombine(
T::BlockSparseTensor{<:Number,NT},
is,
combdim::Int,
blockperm::Vector{Int},
blockcomb::Vector{Int},
) where {NT}
NR = length(is)
R = uncombine_output(T, is, combdim, blockperm, blockcomb)
invblockperm = invperm(blockperm)
# This is needed for reshaping the block
# It is already calculated in uncombine_output, use it from there
ind_uncomb_perm = ⊗(setdiff(is, inds(T))...)
ind_uncomb = permuteblocks(ind_uncomb_perm, blockperm)
# Same as inds(T) but with the blocks uncombined
inds_uncomb = insertat(inds(T), ind_uncomb, combdim)
inds_uncomb_perm = insertat(inds(T), ind_uncomb_perm, combdim)
for bof in pairs(blockoffsets(T))
b = nzblock(bof)
Tb_tot = blockview(T, bof)
dimsTb_tot = dims(Tb_tot)
bs_uncomb = uncombine_block(b, combdim, blockcomb)
offset = 0
for i in 1:length(bs_uncomb)
b_uncomb = bs_uncomb[i]
b_uncomb_perm = perm_block(b_uncomb, combdim, invblockperm)
b_uncomb_perm_reshape = reshape(b_uncomb_perm, inds_uncomb_perm, is)
Rb = blockview(R, b_uncomb_perm_reshape)
b_uncomb_in_combined_dim = b_uncomb_perm[combdim]
start = offset + 1
stop = offset + blockdim(ind_uncomb_perm, b_uncomb_in_combined_dim)
subind = ntuple(
i -> i == combdim ? range(start; stop=stop) : range(1; stop=dimsTb_tot[i]), NT
)
offset = stop
Tb = @view array(Tb_tot)[subind...]
# Alternative (but maybe slower):
#copyto!(Rb,Tb)
if length(Tb) == 1
Rb[1] = Tb[1]
else
# XXX: this used to be:
# Rbₐᵣ = ReshapedArray(parent(Rbₐ), size(Tb), ())
# however that doesn't work with subarrays
Rbₐ = convert(Array, Rb)
Rbₐᵣ = ReshapedArray(Rbₐ, size(Tb), ())
@strided Rbₐᵣ .= Tb
end
end
end
return R
end
function copyto!(R::BlockSparseTensor, T::BlockSparseTensor)
for bof in pairs(blockoffsets(T))
copyto!(blockview(R, nzblock(bof)), blockview(T, bof))
end
return R
end
# TODO: handle case where:
# f(zero(ElR),zero(ElT)) != promote_type(ElR,ElT)
function permutedims!!(
R::BlockSparseTensor{ElR,N},
T::BlockSparseTensor{ElT,N},
perm::NTuple{N,Int},
f::Function=(r, t) -> t,
) where {ElR,ElT,N}
RR = convert(promote_type(typeof(R), typeof(T)), R)
#@timeit_debug timer "block sparse permutedims!!" begin
bofsRR = blockoffsets(RR)
bofsT = blockoffsets(T)
# Determine if bofsRR has been copied
copy_bofsRR = false
new_nnz = nnz(RR)
for (blockT, offsetT) in pairs(bofsT)
blockTperm = permute(blockT, perm)
if !isassigned(bofsRR, blockTperm)
if !copy_bofsRR
bofsRR = deepcopy(bofsRR)
copy_bofsRR = true
end
insert!(bofsRR, blockTperm, new_nnz)
new_nnz += blockdim(T, blockT)
end
end
## RR = BlockSparseTensor(promote_type(ElR,ElT), undef,
## bofsRR, inds(R))
## # Directly copy the data since it is the same blocks
## # and offsets
## copyto!(data(RR), data(R))
if new_nnz > nnz(RR)
dataRR = append!(data(RR), zeros(new_nnz - nnz(RR)))
RR = Tensor(BlockSparse(dataRR, bofsRR), inds(RR))
end
permutedims!(RR, T, perm, f)
return RR
#end
end
# <fermions>
scale_blocks!(T, compute_fac::Function=(b) -> 1) = T
# <fermions>
function scale_blocks!(
T::BlockSparseTensor{<:Number,N}, compute_fac::Function=(b) -> 1
) where {N}
for blockT in keys(blockoffsets(T))
fac = compute_fac(blockT)
if fac != 1
Tblock = blockview(T, blockT)
scale!(Tblock, fac)
end
end
return T
end
# <fermions>
permfactor(perm, block, inds) = 1.0
# Version where it is known that R has the same blocks
# as T
function permutedims!(
R::BlockSparseTensor{<:Number,N},
T::BlockSparseTensor{<:Number,N},
perm::NTuple{N,Int},
f::Function=(r, t) -> t,
) where {N}
for blockT in keys(blockoffsets(T))
# Loop over non-zero blocks of T/R
Tblock = blockview(T, blockT)
Rblock = blockview(R, permute(blockT, perm))
# <fermions>
pfac = permfactor(perm, blockT, inds(T))
fac_f = (r, t) -> f(r, pfac * t)
permutedims!(Rblock, Tblock, perm, fac_f)
end
return R
end
#
# Contraction
#
# TODO: complete this function: determine the output blocks from the input blocks
# Also, save the contraction list (which block-offsets contract with which),
# may not be generic with other contraction functions!
function contraction_output(
T1::TensorT1, T2::TensorT2, indsR::IndsR
) where {TensorT1<:BlockSparseTensor,TensorT2<:BlockSparseTensor,IndsR}
TensorR = contraction_output_type(TensorT1, TensorT2, IndsR)
return similar(TensorR, blockoffsetsR, indsR)
end
"""
find_matching_positions(t1,t2) -> t1_to_t2
In a tuple of length(t1), store the positions in t2
where the element of t1 is found. Otherwise, store 0
to indicate that the element of t1 is not in t2.
For example, for all t1[pos1] == t2[pos2], t1_to_t2[pos1] == pos2,
otherwise t1_to_t2[pos1] == 0.
"""
function find_matching_positions(t1, t2)
t1_to_t2 = @MVector zeros(Int, length(t1))
for pos1 in 1:length(t1)
for pos2 in 1:length(t2)
if t1[pos1] == t2[pos2]
t1_to_t2[pos1] = pos2
end
end
end
return Tuple(t1_to_t2)
end
function contract_labels(labels1, labels2, labelsR)
labels1_to_labels2 = find_matching_positions(labels1, labels2)
labels1_to_labelsR = find_matching_positions(labels1, labelsR)
labels2_to_labelsR = find_matching_positions(labels2, labelsR)
return labels1_to_labels2, labels1_to_labelsR, labels2_to_labelsR
end
function are_blocks_contracted(
block1::Block{N1}, block2::Block{N2}, labels1_to_labels2::NTuple{N1,Int}
) where {N1,N2}
t1 = Tuple(block1)
t2 = Tuple(block2)
for i1 in 1:N1
i2 = @inbounds labels1_to_labels2[i1]
if i2 > 0
# This dimension is contracted
if @inbounds t1[i1] != @inbounds t2[i2]
return false
end
end
end
return true
end
function contract_blocks(
block1::Block{N1}, labels1_to_labelsR, block2::Block{N2}, labels2_to_labelsR, ::Val{NR}
) where {N1,N2,NR}
blockR = ntuple(_ -> UInt(0), Val(NR))
t1 = Tuple(block1)
t2 = Tuple(block2)
for i1 in 1:N1
iR = @inbounds labels1_to_labelsR[i1]
if iR > 0
blockR = @inbounds setindex(blockR, t1[i1], iR)
end
end
for i2 in 1:N2
iR = @inbounds labels2_to_labelsR[i2]
if iR > 0
blockR = @inbounds setindex(blockR, t2[i2], iR)
end
end
return Block{NR}(blockR)
end
function _contract_blockoffsets(
boffs1::BlockOffsets{N1},
inds1,
labels1,
boffs2::BlockOffsets{N2},
inds2,
labels2,
indsR,
labelsR,
) where {N1,N2}
NR = length(labelsR)
ValNR = ValLength(labelsR)
labels1_to_labels2, labels1_to_labelsR, labels2_to_labelsR = contract_labels(
labels1, labels2, labelsR
)
blockoffsetsR = BlockOffsets{NR}()
nnzR = 0
contraction_plan = Tuple{Block{N1},Block{N2},Block{NR}}[]
# Reserve some capacity
# In theory the maximum is length(boffs1) * length(boffs2)
# but in practice that is too much
sizehint!(contraction_plan, max(length(boffs1), length(boffs2)))
for block1 in keys(boffs1)
for block2 in keys(boffs2)
if are_blocks_contracted(block1, block2, labels1_to_labels2)
blockR = contract_blocks(
block1, labels1_to_labelsR, block2, labels2_to_labelsR, ValNR
)
push!(contraction_plan, (block1, block2, blockR))
if !isassigned(blockoffsetsR, blockR)
insert!(blockoffsetsR, blockR, nnzR)
nnzR += blockdim(indsR, blockR)
end
end
end
end
return blockoffsetsR, contraction_plan
end
function _threaded_contract_blockoffsets(
boffs1::BlockOffsets{N1},
inds1,
labels1,
boffs2::BlockOffsets{N2},
inds2,
labels2,
indsR,
labelsR,
) where {N1,N2}
NR = length(labelsR)
ValNR = ValLength(labelsR)
labels1_to_labels2, labels1_to_labelsR, labels2_to_labelsR = contract_labels(
labels1, labels2, labelsR
)
contraction_plans = [Tuple{Block{N1},Block{N2},Block{NR}}[] for _ in 1:nthreads()]
#
# Reserve some capacity
# In theory the maximum is length(boffs1) * length(boffs2)
# but in practice that is too much
#for contraction_plan in contraction_plans
# sizehint!(contraction_plan, max(length(boffs1), length(boffs2)))
#end
#
blocks1 = keys(boffs1)
blocks2 = keys(boffs2)
if length(blocks1) > length(blocks2)
@sync for blocks1_partition in
Iterators.partition(blocks1, max(1, length(blocks1) ÷ nthreads()))
@spawn for block1 in blocks1_partition
for block2 in blocks2
if are_blocks_contracted(block1, block2, labels1_to_labels2)
blockR = contract_blocks(
block1, labels1_to_labelsR, block2, labels2_to_labelsR, ValNR
)
push!(contraction_plans[threadid()], (block1, block2, blockR))
end
end
end
end
else
@sync for blocks2_partition in
Iterators.partition(blocks2, max(1, length(blocks2) ÷ nthreads()))
@spawn for block2 in blocks2_partition
for block1 in blocks1
if are_blocks_contracted(block1, block2, labels1_to_labels2)
blockR = contract_blocks(
block1, labels1_to_labelsR, block2, labels2_to_labelsR, ValNR
)
push!(contraction_plans[threadid()], (block1, block2, blockR))
end
end
end
end
end
contraction_plan = vcat(contraction_plans...)
blockoffsetsR = BlockOffsets{NR}()
nnzR = 0
for (_, _, blockR) in contraction_plan
if !isassigned(blockoffsetsR, blockR)
insert!(blockoffsetsR, blockR, nnzR)
nnzR += blockdim(indsR, blockR)
end
end
return blockoffsetsR, contraction_plan
end
function contract_blockoffsets(args...)
if using_threaded_blocksparse() && nthreads() > 1
return _threaded_contract_blockoffsets(args...)
end
return _contract_blockoffsets(args...)
end
function contraction_output(
T1::TensorT1, labelsT1, T2::TensorT2, labelsT2, labelsR
) where {TensorT1<:BlockSparseTensor,TensorT2<:BlockSparseTensor}
indsR = contract_inds(inds(T1), labelsT1, inds(T2), labelsT2, labelsR)
TensorR = contraction_output_type(TensorT1, TensorT2, typeof(indsR))
blockoffsetsR, contraction_plan = contract_blockoffsets(
blockoffsets(T1),
inds(T1),
labelsT1,
blockoffsets(T2),
inds(T2),
labelsT2,
indsR,
labelsR,
)
R = similar(TensorR, blockoffsetsR, indsR)
return R, contraction_plan
end
function contract(
T1::BlockSparseTensor{<:Any,N1},
labelsT1,
T2::BlockSparseTensor{<:Any,N2},
labelsT2,
labelsR=contract_labels(labelsT1, labelsT2),
) where {N1,N2}
#@timeit_debug timer "Block sparse contract" begin
R, contraction_plan = contraction_output(T1, labelsT1, T2, labelsT2, labelsR)
R = contract!(R, labelsR, T1, labelsT1, T2, labelsT2, contraction_plan)
return R
#end
end
# <fermions>
function compute_alpha(
ElR, labelsR, blockR, indsR, labelsT1, blockT1, indsT1, labelsT2, blockT2, indsT2
)
return one(ElR)
end
# XXX: this is not thread safe, divide into groups of
# contractions that contract into the same block
function _threaded_contract!(
R::BlockSparseTensor{ElR,NR},
labelsR,
T1::BlockSparseTensor{ElT1,N1},
labelsT1,
T2::BlockSparseTensor{ElT2,N2},
labelsT2,
contraction_plan,
) where {ElR,ElT1,ElT2,N1,N2,NR}
# Sort the contraction plan by the output blocks
# This is to help determine which output blocks are the result
# of multiple contractions
sort!(contraction_plan; by=last)
# Ranges of contractions to the same block
repeats = Vector{UnitRange{Int}}(undef, nnzblocks(R))
ncontracted = 1
posR = last(contraction_plan[1])
posR_unique = posR
for n in 1:(nnzblocks(R) - 1)
start = ncontracted
while posR == posR_unique
ncontracted += 1
posR = last(contraction_plan[ncontracted])
end
posR_unique = posR
repeats[n] = start:(ncontracted - 1)
end
repeats[end] = ncontracted:length(contraction_plan)
contraction_plan_blocks = Vector{Tuple{Tensor,Tensor,Tensor}}(
undef, length(contraction_plan)
)
for ncontracted in 1:length(contraction_plan)
block1, block2, blockR = contraction_plan[ncontracted]
T1block = T1[block1]
T2block = T2[block2]
Rblock = R[blockR]
contraction_plan_blocks[ncontracted] = (T1block, T2block, Rblock)
end
α = one(ElR)
@sync for repeats_partition in
Iterators.partition(repeats, max(1, length(repeats) ÷ nthreads()))
@spawn for ncontracted_range in repeats_partition
# Overwrite the block since it hasn't been written to
# R .= α .* (T1 * T2)
β = zero(ElR)