Skip to content

Commit 1638bf4

Browse files
lkdvosclaude
andcommitted
Route all sparse destination blocks through the allocator
- Contract into a sparse `C` through a temporary holding only the product blocks unless `C` is a valid BLAS destination, instead of copying all blocks of `C`. - Allocate missing blocks of sparse destinations lazily through the operation's allocator (as non-temporaries), so that adding a differently-patterned tensor into an allocator-backed temporary stays consistent. - Deduplicate the block keys in `tensoralloc_add`, which projects several source blocks onto the same output block for traces. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9cf39b1 commit 1638bf4

5 files changed

Lines changed: 89 additions & 30 deletions

File tree

‎src/tensors/abstractblocktensor/abstractarray.jl‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ end
8888
getindex!(parent(t), I...)
8989
@propagate_inbounds getindex!(t::AbstractBlockTensorMap, I::CartesianIndex{N}) where {N} =
9090
getindex!(parent(t), I)
91+
# missing blocks of a destination are obtained from the allocator of the operation
92+
@propagate_inbounds getindex!(t::AbstractBlockTensorMap, I::CartesianIndex, allocator) = t[I]
9193

9294
# slicing getindex needs to correctly allocate output blocktensor:
9395
@propagate_inbounds Base.getindex(t::AbstractBlockTensorMap, indices::Vararg{SliceIndex}) =

‎src/tensors/indexmanipulations.jl‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ end
2424
@inbounds for (I, v) in nonzero_pairs(tsrc)
2525
I′ = CartesianIndex(TT.getindices(I.I, p_lin))
2626
tdst[I′] = TK.add_transform!(
27-
tdst[I′], v, p_lin, transformer, α, One(), backend, allocator
27+
getindex!(tdst, I′, allocator), v, p_lin, transformer, α, One(), backend, allocator
2828
)
2929
end
3030
return tdst
@@ -39,7 +39,7 @@ function TK.add_transform!(
3939
@inbounds for (I, v) in nonzero_pairs(tsrc)
4040
I′ = CartesianIndex(TT.getindices(I.I, p_lin))
4141
tdst[I′] = TK.add_transform!(
42-
tdst[I′], v, p, transformer, α, One(), backend, allocator
42+
getindex!(tdst, I′, allocator), v, p, transformer, α, One(), backend, allocator
4343
)
4444
end
4545
return tdst
@@ -88,7 +88,9 @@ for f in (:permute, :transpose)
8888
p_lin = (p[1]..., p[2]...)
8989
@inbounds for (I, v) in nonzero_pairs(tsrc)
9090
I′ = CartesianIndex(TT.getindices(I.I, p_lin))
91-
tdst[I′] = TK.$f!(tdst[I′], v, p, α, One(), backend, allocator)
91+
tdst[I′] = TK.$f!(
92+
getindex!(tdst, I′, allocator), v, p, α, One(), backend, allocator
93+
)
9294
end
9395
return tdst
9496
end
@@ -101,7 +103,9 @@ for f in (:permute, :transpose)
101103
p_lin = (p[1]..., p[2]...)
102104
@inbounds for (I, v) in nonzero_pairs(tsrc)
103105
I′ = CartesianIndex(TT.getindices(I.I, p))
104-
tdst[I′] = TK.$f!(tdst[I′], v, (p₁, p₂), α, One(), backend, allocator)
106+
tdst[I′] = TK.$f!(
107+
getindex!(tdst, I′, allocator), v, (p₁, p₂), α, One(), backend, allocator
108+
)
105109
end
106110
return tdst
107111
end
@@ -147,7 +151,9 @@ end
147151
p_lin = (p[1]..., p[2]...)
148152
@inbounds for (I, v) in nonzero_pairs(tsrc)
149153
I′ = CartesianIndex(TT.getindices(I.I, p_lin))
150-
tdst[I′] = TK.braid!(tdst[I′], v, p, levels, α, One(), backend, allocator)
154+
tdst[I′] = TK.braid!(
155+
getindex!(tdst, I′, allocator), v, p, levels, α, One(), backend, allocator
156+
)
151157
end
152158
return tdst
153159
end
@@ -160,7 +166,9 @@ function TK.braid!(
160166
p_lin = (p[1]..., p[2]...)
161167
@inbounds for (I, v) in nonzero_pairs(tsrc)
162168
I′ = CartesianIndex(TT.getindices(I.I, p_lin))
163-
tdst[I′] = TK.braid!(tdst[I′], v, p, levels, α, One(), backend, allocator)
169+
tdst[I′] = TK.braid!(
170+
getindex!(tdst, I′, allocator), v, p, levels, α, One(), backend, allocator
171+
)
164172
end
165173
return tdst
166174
end

‎src/tensors/sparseblocktensor.jl‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,16 @@ function Base.delete!(t::SparseBlockTensorMap{TT}, I::Vararg{Int, N}) where {TT,
189189
return delete!(t, CartesianIndex(I...))
190190
end
191191

192+
# missing blocks of a destination are obtained from the allocator of the operation
193+
@propagate_inbounds getindex!(
194+
t::SparseBlockTensorMap, I::CartesianIndex, ::TO.DefaultAllocator
195+
) = getindex!(t, I)
196+
@propagate_inbounds function getindex!(t::SparseBlockTensorMap, I::CartesianIndex, allocator)
197+
haskey(t, I) && return t[I]
198+
tI = TO.tensoralloc(eltype(t), eachspace(t)[I], Val(false), allocator)
199+
return t[I] = zerovector!(tI)
200+
end
201+
192202
# Show
193203
# ----
194204
function Base.showarg(io::IO, t::SparseBlockTensorMap, toplevel::Bool)

‎src/tensors/tensoroperations.jl‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ function TO.tensoradd!(
2525
p_lin = (pA[1]..., pA[2]...)
2626
@inbounds for (I, v) in nonzero_pairs(A)
2727
I′ = CartesianIndex(TT.getindices(I.I, p_lin))
28-
C[I′] = TO.tensoradd!(C[I′], v, pA, conjA, α, One(), backend, allocator)
28+
C[I′] = TO.tensoradd!(
29+
getindex!(C, I′, allocator), v, pA, conjA, α, One(), backend, allocator
30+
)
2931
end
3032
return C
3133
end
@@ -116,7 +118,7 @@ function _tensoralloc(
116118
C = ttype(undef_blocks, structure)
117119
Vs = eachspace(C)
118120
for I in keys
119-
C[I] = TO.tensoralloc(eltype(C), Vs[I], istemp, allocator)
121+
haskey(C, I) || (C[I] = TO.tensoralloc(eltype(C), Vs[I], istemp, allocator))
120122
end
121123
return C
122124
end
@@ -160,16 +162,30 @@ function TO.tensoralloc_contract(
160162
return _tensoralloc(ttype, structure, keys, istemp, allocator)
161163
end
162164

163-
# temporaries derived from `C` must already contain every block the contraction produces
165+
# contract directly into `C` when it is a valid BLAS destination, otherwise go through a
166+
# temporary holding only the product blocks instead of a copy of all blocks of `C`
164167
function TO.tensorcontract!(
165168
C::SparseBlockTensorMap,
166169
A::BlockOrAdjoint, pA::Index2Tuple, conjA::Bool,
167170
B::BlockOrAdjoint, pB::Index2Tuple, conjB::Bool,
168171
pAB::Index2Tuple, α::Number, β::Number, backend, allocator
169172
)
170-
for I in contract_keys(A, pA, B, pB, pAB)
171-
getindex!(C, I)
173+
ipAB = TO.oindABinC(pAB, pA, pB)
174+
if TO.isblasdestination(C, ipAB) || TO.isblasdestination(C, reverse(ipAB))
175+
foreach(I -> getindex!(C, I, allocator), contract_keys(A, pA, B, pB, pAB))
176+
return _tensorcontract!(C, A, pA, conjA, B, pB, conjB, pAB, α, β, backend, allocator)
172177
end
178+
N₁ = length(pA[1])
179+
pAB′ = (ntuple(identity, N₁), ntuple(i -> N₁ + i, length(pB[2])))
180+
AB = TO.tensoralloc_contract(
181+
scalartype(C), A, pA, conjA, B, pB, conjB, pAB′, Val(true), allocator
182+
)
183+
_tensorcontract!(AB, A, pA, conjA, B, pB, conjB, pAB′, One(), Zero(), backend, allocator)
184+
TO.tensoradd!(C, AB, pAB, false, α, β, backend, allocator)
185+
TO.tensorfree!(AB, allocator)
186+
return C
187+
end
188+
function _tensorcontract!(C, A, pA, conjA, B, pB, conjB, pAB, α, β, backend, allocator)
173189
return @invoke TO.tensorcontract!(
174190
C::AbstractTensorMap,
175191
A::AbstractTensorMap, pA::Index2Tuple, conjA::Bool,

‎test/linalg/tensoroperations.jl‎

Lines changed: 42 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -154,15 +154,17 @@ end
154154
##
155155

156156
struct TrackingAllocator
157-
live::Set{UInt}
158-
foreign::Base.RefValue{Int}
157+
live::Set{UInt} # handed out and not freed yet
158+
temps::Set{UInt} # handed out as temporaries
159+
foreign::Base.RefValue{Int} # freed arrays that were not handed out by the allocator
159160
end
160-
TrackingAllocator() = TrackingAllocator(Set{UInt}(), Ref(0))
161+
TrackingAllocator() = TrackingAllocator(Set{UInt}(), Set{UInt}(), Ref(0))
161162
function TensorOperations.tensoralloc(
162-
::Type{A}, structure, ::Val, allocator::TrackingAllocator
163-
) where {A <: AbstractArray}
163+
::Type{A}, structure, ::Val{istemp}, allocator::TrackingAllocator
164+
) where {A <: AbstractArray, istemp}
164165
x = fill!(TensorOperations.tensoralloc(A, structure, Val(false)), NaN)
165166
push!(allocator.live, objectid(x))
167+
istemp && push!(allocator.temps, objectid(x))
166168
return x
167169
end
168170
function TensorOperations.tensorfree!(x::AbstractArray, allocator::TrackingAllocator)
@@ -173,6 +175,12 @@ function TensorOperations.tensorfree!(x::AbstractArray, allocator::TrackingAlloc
173175
end
174176
return nothing
175177
end
178+
function check_allocator(f)
179+
allocator = TrackingAllocator()
180+
@test f(allocator) ≈ f(TensorOperations.DefaultAllocator())
181+
@test allocator.foreign[] == 0
182+
return @test isdisjoint(allocator.live, allocator.temps)
183+
end
176184

177185
@testset "allocator only frees what it allocated ($(sectortype(a)))" for (a, b, c) in (
178186
(SumSpace(ℂ^2, ℂ^1), SumSpace(ℂ^1, ℂ^2, ℂ^1), SumSpace(ℂ^2, ℂ^3)),
@@ -185,20 +193,35 @@ end
185193
A = sprand(Float64, a ⊗ b ← c, 0.4)
186194
B = sprand(Float64, c ⊗ b' ← a, 0.4)
187195
D = sprand(Float64, a ← b, 0.4)
196+
E = sprand(Float64, a ← b, 0.4)
197+
X = sprand(Float64, a ⊗ b ← a ⊗ b, 0.5)
188198

189-
allocator = TrackingAllocator()
190-
@tensor allocator = allocator E[x; q] := A[x z; w] * B[w z; y] * D[y; q]
191-
@tensor Eref[x; q] := A[x z; w] * B[w z; y] * D[y; q]
192-
@test E ≈ Eref
193-
@test allocator.foreign[] == 0
199+
check_allocator() do al
200+
return @tensor allocator = al R[x; q] := A[x z; w] * B[w z; y] * D[y; q]
201+
end
202+
check_allocator() do al # temporary receiving blocks outside of its initial pattern
203+
return @tensor allocator = al R[x; q] := A[x z; w] * B[w z; y] * (D[y; q] + 2 * E[y; q])
204+
end
205+
check_allocator() do al # several blocks of `X` are traced into the same output block
206+
return @tensor allocator = al R[x; q] := X[x z; y z] * D[y; q]
207+
end
208+
check_allocator() do al
209+
return @planar allocator = al R[x; q] := A[x z; w] * B[w z; y] * D[y; q]
210+
end
194211

195-
@tensor C[x y; p q] := A[x q; w] * B[w p; y]
196-
C = spzeros(Float64, space(C))
197-
C[1, 1, 1, 1] = randn(Float64, space(C[1, 1, 1, 1]))
198-
Cref = copy(C)
199-
allocator = TrackingAllocator()
200-
@tensor allocator = allocator C[x y; p q] += A[x q; w] * B[w p; y]
201-
@tensor Cref[x y; p q] += A[x q; w] * B[w p; y]
202-
@test C ≈ Cref
203-
@test allocator.foreign[] == 0
212+
# permuted and BLAS-compatible destinations, without and with blocks outside of the product
213+
@tensor C1[x y; p q] := A[x q; w] * B[w p; y]
214+
@tensor C2[x q; p y] := A[x q; w] * B[w p; y]
215+
for C in (spzeros(Float64, space(C1)), sprand(Float64, space(C1), 1.0))
216+
check_allocator() do al
217+
C′ = copy(C)
218+
return @tensor allocator = al C′[x y; p q] += A[x q; w] * B[w p; y]
219+
end
220+
end
221+
for C in (spzeros(Float64, space(C2)), sprand(Float64, space(C2), 1.0))
222+
check_allocator() do al
223+
C′ = copy(C)
224+
return @tensor allocator = al C′[x q; p y] += A[x q; w] * B[w p; y]
225+
end
226+
end
204227
end

0 commit comments

Comments
 (0)