Skip to content

Commit 8aa4d68

Browse files
lkdvosclaude
andauthored
perf: invert index maps when slicing and assigning block tensors (#72)
* fix: use cartesian keys in `nonzero_pairs` `pairs(A::AbstractVector)` uses linear indices, so `nonzero_pairs` yielded `Int` keys for the parent of a one-dimensional dense `BlockTensorMap`, inconsistent with `nonzero_keys`. Consumers comparing against `CartesianIndex` then silently matched nothing, which made `t[:]` and `t[1:2]` return uninitialized blocks. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf: invert index maps when slicing block tensors Slicing `getindex` scanned the whole source index grid once per stored block, making it `O(nnz * prod(length.(indices)))` and materializing the slice region as an `Array{CartesianIndex}`. Invert the index maps per dimension instead, so each stored block finds its destinations in `O(1)`: n nnz before after speedup 16 16 0.0045 ms 0.0015 ms 3x 64 64 0.1452 ms 0.0036 ms 40x 256 256 8.9455 ms 0.0107 ms 836x 512 512 71.1836 ms 0.0188 ms 3786x (banded sparse block tensor, sliced to every other channel; the dense `BlockTensorMap` variant goes from 7.94 ms to 0.087 ms at n = 64.) `SparseTensorArray` had a second copy of the same logic for slicing the parent array; both now share `_copyslice!`. Along the way this fixes four bugs in the old index handling: - Repeated indices dropped blocks instead of duplicating them, and for a dense destination the dropped slot was returned as uninitialized memory. They now duplicate, as they do for `AbstractArray`. - Single-index slicing of one-dimensional block tensors (`t[:]`, `t[1:2]`) returned uninitialized blocks. - `Integer` indices other than `Int` threw: `t[UInt(1), 1:2, 1]` a `BoundsError`, `t[Int8(1), Int8(1), Int8(1)]` a `MethodError`. - Logical masks threw `CanonicalIndexError` on the parent array path, `parent(t)[[true, false, true], :, :]`. The `Vararg{Strided.SliceIndex}` methods are kept: they disambiguate against TensorKit's own `getindex`/`setindex!` for `AbstractTensorMap`, so removing them turns `t[:, :, :]` into a `MethodError`. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf: make sparse slice assignment scale with nnz The three `SparseTensorArray` `copyto!` methods all walked the assigned region rather than the stored blocks, so `t[inds...] = v` and `cat` cost `O(prod(length.(inds)))` regardless of how little was stored — the mirror image of the `getindex` problem in #67. Reuse the inverted index maps instead: shape region nnz before after speedup 2d n=64 3_844 64 0.150 ms 0.015 ms 10x 2d n=256 64_516 256 2.267 ms 0.036 ms 63x 2d n=512 260_100 512 13.752 ms 0.051 ms 269x 4d n=24 234_256 24 9.459 ms 0.009 ms 1040x 4d n=48 4_477_456 48 140.997 ms 0.013 ms 10600x narrow 4 512 0.005 ms 0.004 ms 1x `copyto!(dst, view(parent(t), inds...))` improves likewise, 14.6 ms to 0.041 ms for a 260_100-block region. The narrow row matters: a small assignment into a large sparse array must not become proportional to the destination's stored blocks. `_deletemissing!` therefore sweeps whichever of the two is smaller, making it `O(nnz(src) + min(region, nnz(dst)))` — never worse than before. `copyto!(t::SparseTensorArray, ::SubArray)` needs no sweep at all: the destination spans exactly the viewed region, so everything not copied is dropped. Also fix the `nonzero_*` accessors for `SparseTensorArray`, which fell through to the `AbstractArray` fallbacks and reported every index rather than the stored ones. `nonzero_keys` and `nonzero_length` were always wrong this way; `nonzero_pairs` became wrong when it started going through `pairs(IndexCartesian(), A)`, which bypasses `Base.pairs(::SparseTensorArray)`. The visible effects were that slicing the parent array densified its result and that `copyto!` over regions stored explicitly-zero blocks. Verified semantics-preserving: the stored-key sets after slice assignment, `copyto!` from a view, region-to-region `copyto!` and `cat` are identical to the previous implementation once the accessors are fixed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 079418b commit 8aa4d68

7 files changed

Lines changed: 347 additions & 182 deletions

File tree

‎docs/src/blocktensors.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ s[1] += 2 * s[1]
7171
Slicing operations are also supported, and the `AbstractBlockTensorMap` can be sliced in the same way as an `AbstractArray{AbstractTensorMap}`.
7272
There is however one elementary difference: as the slices still contain tensors with the same amount of legs, there can be no reduction in the number of dimensions.
7373
In particular, in contrast to `AbstractArray`, scalar dimensions are not discarded, and as a result, linear index slicing is not allowed.
74+
Repeated indices duplicate the selected tensors, as they would for an `AbstractArray`.
7475

7576
```@repl blocktensors
7677
ndims(t[1, 1, :]) == 3

‎src/BlockTensorKit.jl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import TupleTools as TT
3838
import MatrixAlgebraKit as MAK
3939

4040
include("auxiliary/blockarrays.jl")
41+
include("auxiliary/sliceindices.jl")
4142

4243
# Spaces
4344
include("vectorspaces/sumspace.jl")

‎src/auxiliary/sliceindices.jl‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Slice indices
2+
# -------------
3+
# inverting index maps, to copy sliced blocks in `O(nnz)` instead of `O(nnz * length(dst))`
4+
5+
const SliceIndex = Union{Strided.SliceIndex, AbstractVector{<:Integer}}
6+
7+
_key_tuple(I::CartesianIndex) = I.I
8+
_key_tuple(i::Integer) = (Int(i),)
9+
10+
"""
11+
_invert_index(n::Int, ind) -> m
12+
13+
Invert an index into a dimension of length `n`, such that `_dstrange(m, i)` yields all
14+
destination coordinates selecting source coordinate `i`.
15+
"""
16+
_invert_index(::Int, i::Integer) = Int(i)
17+
_invert_index(::Int, r::AbstractUnitRange{Int}) = r
18+
function _invert_index(n::Int, ind)
19+
ptr = zeros(Int, n + 1)
20+
for i in ind
21+
1 ≤ i ≤ n || throw(BoundsError(Base.OneTo(n), i))
22+
ptr[i + 1] += 1
23+
end
24+
cumsum!(ptr, ptr)
25+
dsts = Vector{Int}(undef, length(ind))
26+
pos = copy(ptr)
27+
for (j, i) in enumerate(ind)
28+
dsts[pos[i] += 1] = j
29+
end
30+
return ptr, dsts
31+
end
32+
33+
_dstrange(m::Int, i::Int) = i == m ? (1:1) : (1:0)
34+
function _dstrange(m::AbstractUnitRange{Int}, i::Int)
35+
j = i - first(m) + 1
36+
return 1 ≤ j ≤ length(m) ? (j:j) : (1:0)
37+
end
38+
_dstrange((ptr, dsts)::Tuple{Vector{Int}, Vector{Int}}, i::Int) =
39+
view(dsts, (ptr[i] + 1):ptr[i + 1])
40+
41+
"""
42+
_copyslice!(tdst, tsrc, inds::NTuple{N,Any}) -> tdst
43+
44+
Copy the nonzero blocks of `tsrc` selected by `inds` into `tdst`, where `inds` holds one
45+
normalized index per dimension of `tsrc`.
46+
"""
47+
function _copyslice!(tdst, tsrc, inds::NTuple{N, Any}) where {N}
48+
maps = map(_invert_index, size(tsrc), inds)
49+
for (I, v) in nonzero_pairs(tsrc)
50+
rs = map(_dstrange, maps, _key_tuple(I))
51+
any(isempty, rs) && continue
52+
for J in Iterators.product(rs...)
53+
tdst[J...] = v
54+
end
55+
end
56+
return tdst
57+
end

‎src/auxiliary/sparsetensorarray.jl‎

Lines changed: 40 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ Base.pairs(A::SparseTensorArray) = pairs(A.data)
3434
Base.keys(A::SparseTensorArray) = keys(A.data)
3535
Base.values(A::SparseTensorArray) = values(A.data)
3636

37+
nonzero_keys(A::SparseTensorArray) = keys(A.data)
38+
nonzero_values(A::SparseTensorArray) = values(A.data)
39+
nonzero_pairs(A::SparseTensorArray) = pairs(A.data)
40+
nonzero_length(A::SparseTensorArray) = length(A.data)
41+
3742
TensorKit.space(A::SparseTensorArray) = A.space
3843
TensorKit.codomain(A::SparseTensorArray) = codomain(space(A))
3944
TensorKit.domain(A::SparseTensorArray) = domain(space(A))
@@ -100,38 +105,42 @@ function Base.similar(
100105
return SparseTensorArray{S, N₁, N₂, T, N}(Dict{CartesianIndex{N}, T}(), spaces)
101106
end
102107

103-
Base.@propagate_inbounds function Base.copyto!(
104-
t::SparseTensorArray, v::SubArray{T, N, A}
105-
) where {T, N, A <: SparseTensorArray}
106-
undropped_parentindices = map(Base.parentindices(v)) do I
107-
I isa Base.ScalarIndex ? (I:I) : I
108-
end
108+
_undropped(inds::Tuple) = map(I -> I isa Base.ScalarIndex ? (I:I) : I, inds)
109109

110-
for I in eachindex(IndexCartesian(), t)
111-
parentI = CartesianIndex(Base.reindex(undropped_parentindices, I.I))
112-
if haskey(parent(v), parentI)
113-
t[I] = parent(v)[parentI]
114-
else
115-
delete!(t, I)
110+
# clear the entries of `A` selected by `inds` that `v` does not store
111+
function _deletemissing!(A::SparseTensorArray, inds::Tuple, v)
112+
# sweep whichever of the selected region and the stored entries is smaller
113+
if length(v) ≤ nonzero_length(A)
114+
for I in eachindex(IndexCartesian(), v)
115+
haskey(v, I) || delete!(A, CartesianIndex(Base.reindex(inds, I.I)))
116+
end
117+
else
118+
maps = map(_invert_index, size(A), inds)
119+
for J in collect(nonzero_keys(A))
120+
rs = map(_dstrange, maps, J.I)
121+
any(isempty, rs) && continue
122+
any(P -> haskey(v, CartesianIndex(P)), Iterators.product(rs...)) && continue
123+
delete!(A, J)
116124
end
117125
end
118-
return t
126+
return A
119127
end
120128

129+
# the destination spans exactly the viewed region, so everything not copied is dropped
121130
Base.@propagate_inbounds function Base.copyto!(
122-
t::SubArray{T, N, A}, v::SparseTensorArray
131+
t::SparseTensorArray, v::SubArray{T, N, A}
123132
) where {T, N, A <: SparseTensorArray}
124-
undropped_parentindices = map(Base.parentindices(t)) do I
125-
I isa Base.ScalarIndex ? (I:I) : I
126-
end
133+
empty!(t)
134+
return _copyslice!(t, parent(v), _undropped(Base.parentindices(v)))
135+
end
127136

128-
for I in eachindex(IndexCartesian(), v)
129-
if haskey(v, I)
130-
t[I] = v[I]
131-
else
132-
parentI = CartesianIndex(Base.reindex(undropped_parentindices, I.I))
133-
delete!(parent(t), parentI)
134-
end
137+
Base.@propagate_inbounds function Base.copyto!(
138+
t::SubArray{T, N, A}, v::SparseTensorArray
139+
) where {T, N, A <: SparseTensorArray}
140+
inds = _undropped(Base.parentindices(t))
141+
_deletemissing!(parent(t), inds, v)
142+
for (I, x) in nonzero_pairs(v)
143+
parent(t)[Base.reindex(inds, I.I)...] = x
135144
end
136145
return t
137146
end
@@ -154,12 +163,12 @@ Base.@propagate_inbounds function Base.copyto!(
154163
checkbounds(src, first(Rsrc))
155164
checkbounds(src, last(Rsrc))
156165
end
157-
CRdest = CartesianIndices(Rdest)
158-
CRsrc = CartesianIndices(Rsrc)
159-
ΔI = first(CRdest) - first(CRsrc)
160-
for I in CRsrc
161-
if Rsrc[I] in nonzero_keys(src)
162-
dest[Rdest[I + ΔI]] = src[Rsrc[I]]
166+
maps = map(_invert_index, size(src), Rsrc.indices)
167+
for (I, x) in nonzero_pairs(src)
168+
rs = map(_dstrange, maps, I.I)
169+
any(isempty, rs) && continue
170+
for P in Iterators.product(rs...)
171+
dest[Rdest[P...]] = x
163172
end
164173
end
165174
return dest
@@ -168,33 +177,12 @@ end
168177
# non-scalar indexing
169178
# -------------------
170179
# specialisations to have non-scalar indexing behave as expected
171-
172-
_newindex(i::Int, range::Int) = i == range ? (1,) : nothing
173-
function _newindex(i::Int, range::AbstractVector{Int})
174-
k = findfirst(==(i), range)
175-
return k === nothing ? nothing : (k,)
176-
end
177-
_newindices(::Tuple{}, ::Tuple{}) = ()
178-
function _newindices(I::Tuple, indices::Tuple)
179-
i = _newindex(I[1], indices[1])
180-
Itail = _newindices(Base.tail(I), Base.tail(indices))
181-
(i === nothing || Itail === nothing) && return nothing
182-
return (i..., Itail...)
183-
end
184-
185180
function Base._unsafe_getindex(
186181
::IndexCartesian,
187182
t::SparseTensorArray{S, N₁, N₂, T, N}, I::Vararg{Union{Real, AbstractArray}, N},
188183
) where {S, N₁, N₂, T, N}
189184
dest = similar(t, eltype(t), space(eachspace(t)[I...]))
190-
indices = Base.to_indices(t, I)
191-
for (k, v) in t.data
192-
newI = _newindices(k.I, indices)
193-
if newI !== nothing
194-
dest[newI...] = v
195-
end
196-
end
197-
return dest
185+
return _copyslice!(dest, t, Base.to_indices(t, I))
198186
end
199187

200188
# Space checking

‎src/tensors/abstractblocktensor/abstractarray.jl‎

Lines changed: 38 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -90,51 +90,30 @@ end
9090
getindex!(parent(t), I)
9191

9292
# slicing getindex needs to correctly allocate output blocktensor:
93-
const SliceIndex = Union{Strided.SliceIndex, AbstractVector{<:Union{Integer, Bool}}}
94-
95-
Base.@propagate_inbounds function Base.getindex(
96-
t::AbstractBlockTensorMap, indices::Vararg{SliceIndex}
97-
)
98-
V = space(eachspace(t)[indices...])
99-
tdst = similar(t, V)
93+
@propagate_inbounds Base.getindex(t::AbstractBlockTensorMap, indices::Vararg{SliceIndex}) =
94+
_slice_getindex(t, indices...)
95+
# disambiguate: TensorKit/src/tensors/abstracttensor.jl:540
96+
@propagate_inbounds Base.getindex(t::AbstractBlockTensorMap, indices::Vararg{Strided.SliceIndex}) =
97+
_slice_getindex(t, indices...)
98+
99+
@propagate_inbounds function _slice_getindex(
100+
t::AbstractBlockTensorMap, indices::Vararg{Any, M}
101+
) where {M}
102+
M == numind(t) || return _slice_getindex_single(t, indices...)
103+
inds = Base.to_indices(t, indices)
104+
inds isa NTuple{M, Int} && return parent(t)[inds...]
105+
tdst = similar(t, space(eachspace(t)[inds...]))
100106
length(tdst) == 0 && return tdst
101-
102-
# prevent discarding of singleton dimensions
103-
indices′ = map(indices) do ind
104-
return ind isa Int ? (ind:ind) : ind
105-
end
106-
Rsrc = CartesianIndices(t)[indices′...]
107-
Rdst = CartesianIndices(tdst)
108-
109-
for (I, v) in nonzero_pairs(t)
110-
j = findfirst(==(I), Rsrc)
111-
isnothing(j) && continue
112-
tdst[Rdst[j]] = v
113-
end
114-
return tdst
107+
return _copyslice!(tdst, t, inds)
115108
end
116109

117-
# disambiguate:
118-
@propagate_inbounds function Base.getindex(
119-
t::AbstractBlockTensorMap, indices::Vararg{Strided.SliceIndex}
120-
)
121-
V = space(eachspace(t)[indices...])
122-
tdst = similar(t, V)
123-
length(tdst) == 0 && return tdst
124-
125-
# prevent discarding of singleton dimensions
126-
indices′ = map(indices) do ind
127-
return ind isa Int ? (ind:ind) : ind
128-
end
129-
Rsrc = CartesianIndices(t)[indices′...]
130-
Rdst = CartesianIndices(tdst)
131-
132-
for (I, v) in nonzero_pairs(t)
133-
j = findfirst(==(I), Rsrc)
134-
isnothing(j) && continue
135-
tdst[Rdst[j]] = v
136-
end
137-
return tdst
110+
# a single index is only supported when it selects a single nontrivial dimension
111+
@noinline function _slice_getindex_single(
112+
t::AbstractBlockTensorMap, indices::Vararg{Any, M}
113+
) where {M}
114+
space(eachspace(t)[indices...]) # errors as before if unsupported
115+
d = something(findfirst(>(1), size(t)), 1)
116+
return _slice_getindex(t, ntuple(i -> i == d ? only(indices) : 1, numind(t))...)
138117
end
139118

140119
# TODO: check if this fallback is fair
@@ -151,49 +130,34 @@ function Base.setindex!(::AbstractBlockTensorMap, ::AbstractTensorMap, ::FusionT
151130
end
152131

153132
# setindex verifies structure is correct
154-
@inline function Base.setindex!(
155-
t::AbstractBlockTensorMap, v::AbstractTensorMap, indices::Vararg{SliceIndex}
156-
)
133+
@propagate_inbounds Base.setindex!(
134+
t::AbstractBlockTensorMap, v::AbstractTensorMap, indices::Vararg{SliceIndex}
135+
) = _slice_setindex!(t, v, indices...)
136+
@propagate_inbounds Base.setindex!(
137+
t::AbstractBlockTensorMap, v::AbstractBlockTensorMap, indices::Vararg{SliceIndex}
138+
) = _slice_setindex!(t, v, indices...)
139+
# disambiguate: TensorKit/src/tensors/abstracttensor.jl:552
140+
@propagate_inbounds Base.setindex!(
141+
t::AbstractBlockTensorMap, v::AbstractTensorMap, indices::Vararg{Strided.SliceIndex}
142+
) = _slice_setindex!(t, v, indices...)
143+
@propagate_inbounds Base.setindex!(
144+
t::AbstractBlockTensorMap, v::AbstractBlockTensorMap, indices::Vararg{Strided.SliceIndex}
145+
) = _slice_setindex!(t, v, indices...)
146+
147+
@inline function _slice_setindex!(t::AbstractBlockTensorMap, v::AbstractTensorMap, indices...)
157148
@boundscheck begin
158149
checkbounds(t, indices...)
159150
checkspaces(t, v, indices...)
160151
end
161152
@inbounds parent(t)[indices...] = v
162153
return t
163154
end
164-
# setindex with blocktensor needs to correctly slice-assign
165-
@inline function Base.setindex!(
166-
t::AbstractBlockTensorMap, v::AbstractBlockTensorMap, indices::Vararg{SliceIndex}
167-
)
155+
# a blocktensor needs to be slice-assigned
156+
@inline function _slice_setindex!(t::AbstractBlockTensorMap, v::AbstractBlockTensorMap, indices...)
168157
@boundscheck begin
169158
checkbounds(t, indices...)
170159
checkspaces(t, v, indices...)
171160
end
172-
173-
@inbounds copyto!(view(parent(t), indices...), parent(v))
174-
return t
175-
end
176-
177-
# disambiguate
178-
@inline function Base.setindex!(
179-
t::AbstractBlockTensorMap, v::AbstractTensorMap, indices::Vararg{Strided.SliceIndex}
180-
)
181-
@boundscheck begin
182-
checkbounds(t, indices...)
183-
checkspaces(t, v, indices...)
184-
end
185-
@inbounds parent(t)[indices...] = v
186-
return t
187-
end
188-
# disambiguate
189-
@inline function Base.setindex!(
190-
t::AbstractBlockTensorMap, v::AbstractBlockTensorMap, indices::Vararg{Strided.SliceIndex},
191-
)
192-
@boundscheck begin
193-
checkbounds(t, indices...)
194-
checkspaces(t, v, indices...)
195-
end
196-
197161
@inbounds copyto!(view(parent(t), indices...), parent(v))
198162
return t
199163
end

‎src/tensors/abstractblocktensor/sparsity.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ nonzero_length(t::AbstractBlockTensorMap) = nonzero_length(parent(t))
77

88
nonzero_values(A::AbstractArray) = values(A)
99
nonzero_keys(A::AbstractArray) = eachindex(IndexCartesian(), A)
10-
nonzero_pairs(A::AbstractArray) = pairs(A)
10+
nonzero_pairs(A::AbstractArray) = pairs(IndexCartesian(), A)
1111
nonzero_length(A::AbstractArray) = length(A)
1212

1313
issparse(t::AbstractTensorMap) = false

0 commit comments

Comments
 (0)