Skip to content

Commit 82c08e1

Browse files
lkdvosclaude
andauthored
Make sparse block tensors consistent with TensorOperations allocators (#82)
* Allocate sparse block tensors consistently through the allocator Sparse temporaries are marked with an `istemp` flag, obtain their blocks from the allocator of each operation and keep them until `tensorfree!`, which only releases the blocks of temporaries. Blocks are stored as the type the allocator hands out, and `tensoralloc_add`/ `tensoralloc_contract` allocate the blocks an operation writes up front. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Bump version to v0.3.21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6eb7893 commit 82c08e1

7 files changed

Lines changed: 244 additions & 21 deletions

File tree

‎Project.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name = "BlockTensorKit"
22
uuid = "5f87ffc2-9cf1-4a46-8172-465d160bd8cd"
3-
version = "0.3.20"
3+
version = "0.3.21"
44
authors = ["Lukas Devos <ldevos98@gmail.com> and contributors"]
55

66
[deps]

‎src/linalg/linalg.jl‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,8 @@ end
118118
)
119119
return if haskey(C, I)
120120
C[I] = _mul!!(C[I], A, B, α, β)
121+
elseif istemp(C)
122+
C[I] = _mul!!(newblock(C, I), A, B, α, Zero())
121123
else
122124
C[I] = _mul!!(nothing, A, B, α, β)
123125
end

‎src/tensors/abstractblocktensor/abstracttensormap.jl‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,10 +122,10 @@ function _blockdims(P::ProductSumSpace{S, N}, c::Sector) where {S, N}
122122
end
123123

124124
zeroblock(::Type{TT}, d₁::Int, d₂::Int) where {TT <: AbstractTensorMap} =
125-
zerovector!(similar(storagetype(TT), d₁, d₂))
125+
zerovector!(similar(storagetype(TT), d₁, d₂))::TK.blocktype(TT)
126126
function zeroblock(::Type{TT}, d₁::Int, d₂::Int) where {TT <: TensorMap}
127127
data = zerovector!(similar(storagetype(TT), d₁ * d₂))
128-
return reshape(view(data, 1:(d₁ * d₂)), (d₁, d₂))
128+
return reshape(view(data, 1:(d₁ * d₂)), (d₁, d₂))::TK.blocktype(TT)
129129
end
130130
zeroblock(::Type{<:AdjointTensorMap{<:Any, <:Any, <:Any, <:Any, TT}}, d₁::Int, d₂::Int) where {TT} =
131131
zeroblock(TT, d₂, d₁)'

‎src/tensors/sparseblocktensor.jl‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,30 @@
22
struct SparseBlockTensorMap{TT<:AbstractTensorMap{E,S,N₁,N₂}} <: AbstractBlockTensorMap{E,S,N₁,N₂}
33
44
Sparse `SparseBlockTensorMap` type that stores tensors of type `TT` in a sparse dictionary.
5+
Temporaries of TensorOperations are marked by `istemp`, as their blocks are obtained from and
6+
released to the allocator of the operation.
57
"""
68
struct SparseBlockTensorMap{TT <: AbstractTensorMap, E, S, N₁, N₂, N} <:
79
AbstractBlockTensorMap{E, S, N₁, N₂}
810
data::Dict{CartesianIndex{N}, TT}
911
space::TensorMapSumSpace{S, N₁, N₂}
12+
istemp::Bool
1013

1114
# uninitialized constructor
1215
function SparseBlockTensorMap{TT, E, S, N₁, N₂, N}(
13-
::UndefBlocksInitializer, space::TensorMapSumSpace{S, N₁, N₂}
16+
::UndefBlocksInitializer, space::TensorMapSumSpace{S, N₁, N₂}; istemp::Bool = false
1417
) where {E, S, N₁, N₂, N, TT <: AbstractTensorMap{E, S, N₁, N₂}}
1518
@assert N₁ + N₂ == N "SparseBlockTensorMap: data has wrong number of dimensions"
1619
data = Dict{CartesianIndex{N}, TT}()
17-
return new{TT, E, S, N₁, N₂, N}(data, space)
20+
return new{TT, E, S, N₁, N₂, N}(data, space, istemp)
1821
end
1922

2023
# constructor from data
2124
function SparseBlockTensorMap{TT, E, S, N₁, N₂, N}(
2225
data::Dict{CartesianIndex{N}, TT}, space::TensorMapSumSpace{S, N₁, N₂}
2326
) where {E, S, N₁, N₂, N, TT <: AbstractTensorMap{E, S, N₁, N₂}}
2427
@assert N₁ + N₂ == N "SparseBlockTensorMap: data has wrong number of dimensions"
25-
return new{TT, E, S, N₁, N₂, N}(data, space)
28+
return new{TT, E, S, N₁, N₂, N}(data, space, false)
2629
end
2730
end
2831

@@ -34,10 +37,11 @@ end
3437

3538
# uninitialized constructor
3639
function SparseBlockTensorMap{TT}(
37-
::Union{UndefBlocksInitializer, UndefInitializer}, space::TensorMapSumSpace{S, N₁, N₂}
40+
::Union{UndefBlocksInitializer, UndefInitializer}, space::TensorMapSumSpace{S, N₁, N₂};
41+
kwargs...
3842
) where {E, S, N₁, N₂, TT <: AbstractTensorMap{E, S, N₁, N₂}}
3943
N = N₁ + N₂
40-
return SparseBlockTensorMap{TT, E, S, N₁, N₂, N}(undef_blocks, space)
44+
return SparseBlockTensorMap{TT, E, S, N₁, N₂, N}(undef_blocks, space; kwargs...)
4145
end
4246

4347
# constructor from data
@@ -189,7 +193,7 @@ end
189193
# `blocks` first store the (nonempty) entries they write to.
190194
function storeentries!(t::SparseBlockTensorMap, keep = Returns(true))
191195
for (I, V) in pairs(eachspace(t))
192-
!haskey(t, I) && dim(V) > 0 && keep(I) && (t[I] = zerovector!(similar(eltype(t), V)))
196+
!haskey(t, I) && dim(V) > 0 && keep(I) && (t[I] = zerovector!(newblock(t, I)))
193197
end
194198
return t
195199
end
@@ -213,7 +217,7 @@ for f in (:(TK.one!), :(TK.isomorphism!), :(TK.isometry!))
213217
@eval function $f(t::SparseBlockTensorMap)
214218
diagonal = diagonalentries(t)
215219
invoke($f, Tuple{AbstractTensorMap}, storeentries!(t, in(diagonal)))
216-
filter!(in(diagonal) ∘ first, t.data)
220+
istemp(t) || filter!(in(diagonal) ∘ first, t.data)
217221
return t
218222
end
219223
end
@@ -222,6 +226,19 @@ for f in (:(Random.rand!), :(Random.randn!), :(Random.randexp!), :(TK.randisomet
222226
invoke($f, Tuple{Random.AbstractRNG, AbstractTensorMap}, rng, storeentries!(t))
223227
end
224228

229+
# blocks of temporaries are obtained from (and released to) the allocator of the operation,
230+
# so kernels without allocator cannot add them
231+
istemp(t::AbstractBlockTensorMap) = false
232+
istemp(t::SparseBlockTensorMap) = t.istemp
233+
234+
function newblock(t::AbstractBlockTensorMap, I::CartesianIndex, allocator = nothing)
235+
V = eachspace(t)[I]
236+
istemp(t) || return TO.tensoralloc(eltype(t), V, Val(false), something(allocator, TO.DefaultAllocator()))
237+
isnothing(allocator) &&
238+
throw(ArgumentError("cannot add block $I to a temporary without its allocator"))
239+
return TO.tensoralloc(eltype(t), V, Val(true), allocator)
240+
end
241+
225242
# Show
226243
# ----
227244
function Base.showarg(io::IO, t::SparseBlockTensorMap, toplevel::Bool)

‎src/tensors/tensoroperations.jl‎

Lines changed: 110 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,24 +97,129 @@ function similarblocktype(::Type{A}, ::Type{TT}) where {A, TT}
9797
return Core.Compiler.return_type(similar, Tuple{A, Type{TT}, NTuple{numind(TT), Int}})
9898
end
9999

100+
# blocks are stored as the type the allocator hands out, e.g. `PtrArray`-backed temporaries
101+
function allocated_blocktype(::Type{TT}, structure, istemp::Val, allocator) where {TT}
102+
V = eltype(SumSpaceIndices(structure))
103+
TT′ = Base.promote_op(TO.tensoralloc, Type{TT}, V, typeof(istemp), typeof(allocator))
104+
TA = AbstractTensorMap{scalartype(TT), spacetype(TT), numout(TT), numin(TT)}
105+
return typeintersect(TT′, TA)
106+
end
107+
100108
function TO.tensoralloc(
101109
::Type{BT}, structure::TensorMapSumSpace, istemp::Val, allocator = TO.DefaultAllocator()
102110
) where {BT <: AbstractBlockTensorMap}
103-
C = BT(undef_blocks, structure)
104-
issparse(C) && return C # don't fill up sparse blocks
105-
blockallocator(V) = TO.tensoralloc(eltype(C), V, istemp, allocator)
106-
map!(blockallocator, parent(C), eachspace(C))
111+
TT = eltype(BT)
112+
C = BlockTensorMap{allocated_blocktype(TT, structure, istemp, allocator)}(
113+
undef_blocks, structure
114+
)
115+
map!(V -> TO.tensoralloc(TT, V, istemp, allocator), parent(C), eachspace(C))
107116
return C
108117
end
109118

119+
# sparse tensors start out empty
120+
function TO.tensoralloc(
121+
::Type{BT}, structure::TensorMapSumSpace, istemp::Val, allocator = TO.DefaultAllocator()
122+
) where {BT <: SparseBlockTensorMap}
123+
TT = allocated_blocktype(eltype(BT), structure, istemp, allocator)
124+
return SparseBlockTensorMap{TT}(
125+
undef_blocks, structure; istemp = istemp === Val(true)
126+
)
127+
end
128+
129+
# sparse results allocate the blocks that will be written up front
130+
const BlockOrAdjoint = Union{AbstractBlockTensorMap, AdjointBlockTensorMap}
131+
132+
_tensoralloc(ttype, structure, keys, istemp::Val, allocator) =
133+
TO.tensoralloc(ttype, structure, istemp, allocator)
134+
function _tensoralloc(
135+
ttype::Type{<:SparseBlockTensorMap}, structure, keys, istemp::Val, allocator
136+
)
137+
C = TO.tensoralloc(ttype, structure, istemp, allocator)
138+
foreach(I -> haskey(C, I) || (C[I] = newblock(C, I, allocator)), keys)
139+
return C
140+
end
141+
142+
function contract_keys(A, pA::Index2Tuple, B, pB::Index2Tuple, pAB::Index2Tuple)
143+
OB = NTuple{length(pB[2]), Int}
144+
openB = Dict{NTuple{length(pB[1]), Int}, Vector{OB}}()
145+
for IB in nonzero_keys(B)
146+
push!(get!(Vector{OB}, openB, TT.getindices(IB.I, pB[1])), TT.getindices(IB.I, pB[2]))
147+
end
148+
p = TO.linearize(pAB)
149+
keys = Set{CartesianIndex{length(p)}}()
150+
for IA in nonzero_keys(A)
151+
oA = TT.getindices(IA.I, pA[1])
152+
for oB in get(openB, TT.getindices(IA.I, pA[2]), ())
153+
push!(keys, CartesianIndex(TT.getindices((oA..., oB...), p)))
154+
end
155+
end
156+
return keys
157+
end
158+
159+
function TO.tensoralloc_add(
160+
TC, A::BlockOrAdjoint, pA::Index2Tuple, conjA::Bool,
161+
istemp::Val = Val(false), allocator = TO.DefaultAllocator()
162+
)
163+
ttype = TO.tensoradd_type(TC, A, pA, conjA)
164+
structure = TO.tensoradd_structure(A, pA, conjA)
165+
p = TO.linearize(pA)
166+
keys = (CartesianIndex(TT.getindices(I.I, p)) for I in nonzero_keys(A))
167+
return _tensoralloc(ttype, structure, keys, istemp, allocator)
168+
end
169+
170+
function TO.tensoralloc_contract(
171+
TC, A::BlockOrAdjoint, pA::Index2Tuple, conjA::Bool,
172+
B::BlockOrAdjoint, pB::Index2Tuple, conjB::Bool,
173+
pAB::Index2Tuple, istemp::Val = Val(false), allocator = TO.DefaultAllocator()
174+
)
175+
ttype = TO.tensorcontract_type(TC, A, pA, conjA, B, pB, conjB, pAB)
176+
structure = TO.tensorcontract_structure(A, pA, conjA, B, pB, conjB, pAB)
177+
keys = contract_keys(A, pA, B, pB, pAB)
178+
return _tensoralloc(ttype, structure, keys, istemp, allocator)
179+
end
180+
181+
# contract directly into `C` when it is a valid BLAS destination, otherwise go through a
182+
# temporary holding only the product blocks instead of a copy of all blocks of `C`
183+
function TO.tensorcontract!(
184+
C::SparseBlockTensorMap,
185+
A::BlockOrAdjoint, pA::Index2Tuple, conjA::Bool,
186+
B::BlockOrAdjoint, pB::Index2Tuple, conjB::Bool,
187+
pAB::Index2Tuple, α::Number, β::Number, backend, allocator
188+
)
189+
ipAB = TO.oindABinC(pAB, pA, pB)
190+
if TO.isblasdestination(C, ipAB) || TO.isblasdestination(C, reverse(ipAB))
191+
for I in contract_keys(A, pA, B, pB, pAB)
192+
haskey(C, I) || (C[I] = zerovector!(newblock(C, I, allocator)))
193+
end
194+
return _tensorcontract!(C, A, pA, conjA, B, pB, conjB, pAB, α, β, backend, allocator)
195+
end
196+
N₁ = length(pA[1])
197+
pAB′ = (ntuple(identity, N₁), ntuple(i -> N₁ + i, length(pB[2])))
198+
AB = TO.tensoralloc_contract(
199+
scalartype(C), A, pA, conjA, B, pB, conjB, pAB′, Val(true), allocator
200+
)
201+
_tensorcontract!(AB, A, pA, conjA, B, pB, conjB, pAB′, One(), Zero(), backend, allocator)
202+
TO.tensoradd!(C, AB, pAB, false, α, β, backend, allocator)
203+
TO.tensorfree!(AB, allocator)
204+
return C
205+
end
206+
function _tensorcontract!(C, A, pA, conjA, B, pB, conjB, pAB, α, β, backend, allocator)
207+
return @invoke TO.tensorcontract!(
208+
C::AbstractTensorMap,
209+
A::AbstractTensorMap, pA::Index2Tuple, conjA::Bool,
210+
B::AbstractTensorMap, pB::Index2Tuple, conjB::Bool,
211+
pAB::Index2Tuple, α::Number, β::Number, backend::Any, allocator::Any
212+
)
213+
end
214+
110215
# tensorfree!
111216
# -----------
112217
function TO.tensorfree!(t::BlockTensorMap, allocator = TO.DefaultAllocator())
113218
foreach(Base.Fix2(TO.tensorfree!, allocator), parent(t))
114219
return nothing
115220
end
116221
function TO.tensorfree!(t::SparseBlockTensorMap, allocator = TO.DefaultAllocator())
117-
foreach(Base.Fix2(TO.tensorfree!, allocator), nonzero_values(t))
222+
istemp(t) && foreach(Base.Fix2(TO.tensorfree!, allocator), nonzero_values(t))
118223
return nothing
119224
end
120225

‎src/tensors/vectorinterface.jl‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
# zerovector
22
# ----------
33
VI.zerovector!(t::AbstractBlockTensorMap) = (zerovector!(parent(t)); t)
4-
VI.zerovector!(t::SparseBlockTensorMap) = (empty!(t.data); t)
4+
# blocks of temporaries belong to an allocator, and are kept until `tensorfree!`
5+
function VI.zerovector!(t::SparseBlockTensorMap)
6+
istemp(t) ? foreach(zerovector!, nonzero_values(t)) : empty!(t.data)
7+
return t
8+
end
59

610
# scale
711
# -----
@@ -49,12 +53,12 @@ end
4953
# blockwise updates
5054
# -----------------
5155
@inline function _addblock!(
52-
f, t::AbstractBlockTensorMap, I::CartesianIndex, β::Number = One(), allocator = TO.DefaultAllocator()
56+
f, t::AbstractBlockTensorMap, I::CartesianIndex, β::Number = One(), allocator = nothing
5357
)
5458
t[I] = if haskey(t, I)
5559
f(t[I], isone(β) ? One() : β)
5660
else
57-
f(TO.tensoralloc(eltype(t), eachspace(t)[I], Val(false), allocator), Zero())
61+
f(newblock(t, I, allocator), Zero())
5862
end
5963
return t
6064
end
@@ -65,11 +69,11 @@ function _scale_untouched!(
6569
(issparse(tsrc) && !isone(β)) || return t
6670
q = TT.invperm(p)
6771
istouched(I) = haskey(tsrc, CartesianIndex(TT.getindices(I.I, q)))
68-
if issparse(t) && iszero(β)
72+
if issparse(t) && iszero(β) && !istemp(t)
6973
filter!(istouched ∘ first, parent(t))
7074
else
7175
for (I, v) in nonzero_pairs(t)
72-
istouched(I) || scale!(v, β)
76+
istouched(I) || (iszero(β) ? zerovector!(v) : scale!(v, β))
7377
end
7478
end
7579
return t

0 commit comments

Comments
 (0)