Skip to content

Commit 34a27f5

Browse files
lkdvosclaude
andauthored
Slice dense block tensors without allocating blocks (#88)
Slicing a `BlockTensorMap` allocated every block of the destination through `similar`, only for `_copyslice!` to replace each of them by the block of the source it selects. Build the slice directly from the sliced parent array instead: the result shares the blocks of the source, as before, without allocating new ones. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 55ff73c commit 34a27f5

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

‎src/tensors/blocktensor.jl‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,18 @@ function BlockTensorMap(
9999
return BlockTensorMap(data, codom ← dom)
100100
end
101101

102+
# Slicing
103+
# -------
104+
# a dense slice holds the blocks of `t` itself, so its own are never allocated
105+
function _slice_getindex_full(t::BlockTensorMap, inds::Tuple)
106+
V = space(eachspace(t)[inds...])
107+
return typeof(t)(parent(t)[map(_keepdim, inds)...], V)
108+
end
109+
@propagate_inbounds _slice_getindex_full(t::BlockTensorMap, inds::NTuple{M, Int}) where {M} =
110+
parent(t)[inds...]
111+
_keepdim(i::Integer) = i:i
112+
_keepdim(i) = i
113+
102114
# AbstractBlockTensorMap -> BlockTensorMap
103115
function BlockTensorMap(t::AbstractBlockTensorMap)
104116
t isa BlockTensorMap && return t # TODO: should this copy?

‎test/abstracttensor/indexing.jl‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,18 @@ end
236236
@test @allocated(tb[inds...]) < 2_000_000
237237
end
238238

239+
# a dense slice shares the blocks of its parent, without allocating any of its own
240+
@testset "dense slicing shares blocks" begin
241+
D = 64
242+
t = rand(SumSpace(ℂ^16) ⊗ SumSpace(fill(ℂ^2, D)...) ← SumSpace(ℂ^16))
243+
inds = (1:1, 2:(D - 1), 1:1)
244+
s = t[inds...]
245+
@test space(s) == space(eachspace(t)[inds...])
246+
@test all(i -> s[1, i, 1] === t[1, i + 1, 1], 1:(D - 2))
247+
@test t[1, 3, :] isa BlockTensorMap && t[1, 3, :][1, 1, 1] === t[1, 3, 1]
248+
@test @allocated(t[inds...]) < sum(b -> sizeof(b.data), parent(t)) ÷ 4
249+
end
250+
239251
# guard against assignment work proportional to the assigned region
240252
@testset "assignment scales with nnz" begin
241253
D = 48

0 commit comments

Comments
 (0)