Skip to content

Commit f687a06

Browse files
lkdvosclaude
andcommitted
Store the subblock structure per splitting and fusion tree
`degeneracystructure` now stores the sizes, strides and offset of every splitting and fusion tree, zero-padded such that the structure of a subblock is their sum, instead of the structure of every subblock. The strides follow in closed form from the column-major layout of the blocks. The tree transformers address subblocks by the tokens of their fusion tree pairs, which index these per-tree structures directly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9a2ebbf commit f687a06

9 files changed

Lines changed: 149 additions & 105 deletions

File tree

‎docs/src/Changelog.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec
4141

4242
- `twist!` and `twist` on a `TensorMap`, a `DiagonalTensorMap` or their adjoints use a cached tree transformer and the index manipulation kernel instead of a loop over all fusion trees, which removes the per-subblock bookkeeping and turns a twist of a GPU tensor, diagonal or not, into a single kernel launch ([#595](https://github.com/QuantumKitHub/TensorKit.jl/issues/595))
4343
- `fusiontrees(W)` stores the splitting and fusion trees of every coupled sector instead of every pair, and `fusionblocks` combines the trees of both sides with the same uncoupled sectors (internal) ([#600](https://github.com/QuantumKitHub/TensorKit.jl/pull/600))
44+
- `degeneracystructure(W)` stores the sizes, strides and offsets of the splitting and fusion trees instead of those of every subblock, from which the structure of a subblock is computed on access, and the tree transformers address subblocks by the tokens of their fusion tree pairs. This makes the cached structures considerably smaller and cheaper to build (internal) ([#600](https://github.com/QuantumKitHub/TensorKit.jl/pull/600))
4445

4546
## [0.17.3](https://github.com/QuantumKitHub/TensorKit.jl/compare/v0.17.2...v0.17.3) - 2026-10-30
4647

‎ext/TensorKitGPUArraysExt.jl‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -670,7 +670,8 @@ function diagonal_device_transformer(A, transformer, dstdiagonal::Bool)
670670
n = first(sz)
671671
return UniqueTransformerBlock{typeof(coeff), 1}(
672672
coeff, (n,), (1,), dstdiagonal ? (1,) : (sum(strides_dst),),
673-
dstdiagonal ? offsets_dst[idst] : offset_dst, (1,), offsets_src[isrc]
673+
dstdiagonal ? offsets_dst[TensorKit.pairposition(structure_dst, idst)] : offset_dst, (1,),
674+
offsets_src[TensorKit.pairposition(structure_src, isrc)]
674675
)
675676
end
676677
work_offsets, nwork = _work_offsets(blk.sz[1] for blk in blocks)

‎src/pullbacks/tensoroperations.jl‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,9 @@ function _planartrace_pullback_ΔA!(
9090
ΔA, ΔC, transformer::TraceTransformer, (p₁, p₂), (q₁, q₂), α, backend, allocator
9191
)
9292
lp = (p₁..., p₂...)
93-
dims_dst = [dim(f₁.coupled) for (f₁, _) in fusiontrees(ΔC)]
94-
dims_src = [dim(f₁.coupled) for (f₁, _) in fusiontrees(ΔA)]
93+
trees_dst, trees_src = fusiontrees(ΔC), fusiontrees(ΔA)
94+
dims_dst = [dim(f₁.coupled) for (f₁, _) in trees_dst]
95+
dims_src = [dim(f₁.coupled) for (f₁, _) in trees_src]
9596
dst, src = _transform_subblocks(ΔC, ΔA, transformer)
9697
for (U, inds_dst, inds_src) in transformer.data, (j, isrc) in enumerate(inds_src)
9798
# the traced diagonal of the source subblock, with the remaining legs permuted by `p`
@@ -112,7 +113,7 @@ function _planartrace_pullback_ΔA!(
112113
parent(c), (size(c)..., sz_traced...), (strides(c)..., map(zero, sz_traced)...),
113114
c.offset, c.op
114115
)
115-
coeff = conj(α * U[i, j]) * (dims_dst[idst] / dims_src[isrc])
116+
coeff = conj(α * U[i, j]) * (dims_dst[pairposition(trees_dst, idst)] / dims_src[pairposition(trees_src, isrc)])
116117
TO.tensoradd!(diag, ΔCi, pdiag, false, coeff, One(), backend, allocator)
117118
end
118119
end

‎src/spaces/structure.jl‎

Lines changed: 85 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -69,16 +69,25 @@ The position of a fusion tree pair in the canonical order of `t`, from its token
6969
itself, which must be present.
7070
"""
7171
pairposition(t::FusionTreePairs, (i₁, i₂)::Tuple{Int, Int}) = @inbounds t.positions₂[i₂] + t.positions₁[i₁]
72-
function pairposition(t::FusionTreePairs, f::FusionTreePair)
72+
pairposition(t::FusionTreePairs, f::FusionTreePair) = pairposition(t, pairtoken(t, f))
73+
74+
"""
75+
pairtoken(t::FusionTreePairs, i::Int) -> Tuple{Int, Int}
76+
pairtoken(t::FusionTreePairs, (f₁, f₂)) -> Tuple{Int, Int}
77+
78+
The token of a fusion tree pair of `t`, from its position or from the pair itself, which must be
79+
present.
80+
"""
81+
pairtoken(t::FusionTreePairs, i::Int) = _pairtoken(t.ranges₁, t.ranges₂, t.offsets, i)
82+
function pairtoken(t::FusionTreePairs, f::FusionTreePair)
7383
found, token = gettoken(t, f)
7484
found || throw(KeyError(f))
75-
return pairposition(t, token)
85+
return token
7686
end
77-
# the token of the pair at position `i`
78-
function pairtoken(t::FusionTreePairs, i::Int)
79-
b = searchsortedlast(t.offsets, i - 1)
80-
r₁, r₂ = t.ranges₁[b], t.ranges₂[b]
81-
j₂, j₁ = divrem(i - 1 - t.offsets[b], length(r₁))
87+
function _pairtoken(ranges₁, ranges₂, offsets, i::Int)
88+
b = searchsortedlast(offsets, i - 1)
89+
r₁, r₂ = ranges₁[b], ranges₂[b]
90+
j₂, j₁ = divrem(i - 1 - offsets[b], length(r₁))
8291
return (first(r₁) + j₁, first(r₂) + j₂)
8392
end
8493

@@ -136,17 +145,18 @@ function Base.iterate(t::FusionTreePairs, state...)
136145
end
137146

138147
# values for every fusion tree pair, stored by position
139-
struct FusionTreePairDict{K, V, T <: FusionTreePairs} <: AbstractDictionary{K, V}
148+
struct FusionTreePairDict{K, V, T <: FusionTreePairs, A <: AbstractVector{V}} <: AbstractDictionary{K, V}
140149
keys::T
141-
values::Vector{V}
150+
values::A
142151
end
143-
FusionTreePairDict(keys::T, values::Vector{V}) where {T <: FusionTreePairs, V} =
144-
FusionTreePairDict{eltype(T), V, T}(keys, values)
152+
FusionTreePairDict(keys::T, values::AbstractVector{V}) where {T <: FusionTreePairs, V} =
153+
FusionTreePairDict{eltype(T), V, T, typeof(values)}(keys, values)
145154
Base.keys(d::FusionTreePairDict) = d.keys
146155
Dictionaries.istokenizable(::FusionTreePairDict) = true
147156
Dictionaries.istokenassigned(::FusionTreePairDict, _) = true
148157
Dictionaries.gettokenvalue(d::FusionTreePairDict, i::Int) = d.values[i]
149-
Dictionaries.gettokenvalue(d::FusionTreePairDict, token::Tuple{Int, Int}) = d.values[pairposition(d.keys, token)]
158+
Dictionaries.gettokenvalue(d::FusionTreePairDict, token::Tuple{Int, Int}) = _tokenvalue(d.values, d.keys, token)
159+
_tokenvalue(values::AbstractVector, keys, token) = values[pairposition(keys, token)]
150160

151161
MemoizationKit.cachesize(s::SectorStructure) =
152162
sizeof(s) + _cache_payload_size(s.blocksectors) + _cache_payload_size(s.fusiontrees)
@@ -180,6 +190,48 @@ MemoizationKit.cachekey(::typeof(sectorstructure), W::HomSpace) = (Hashed(W, sec
180190

181191
# DegeneracyStructure: degeneracy-dependent characterization of HomSpaces
182192
# -----------------------------------------------------------------------
193+
"""
194+
SubblockStructure{N} <: AbstractVector{StridedStructure{N}}
195+
196+
The [`StridedStructure`](@ref) `(sizes, strides, offset)` of the subblock of every fusion tree pair
197+
of a `HomSpace`, in the canonical order of [`fusiontrees`](@ref). The subblock of `(f₁, f₂)` holds
198+
the rows of `f₁` and the columns of `f₂` within the block of their coupled sector, such that only
199+
the structures of the splitting and fusion trees are stored, and that of a pair is computed when it
200+
is accessed. Besides its position, a pair can also be indexed with its token `(i₁, i₂)`.
201+
"""
202+
struct SubblockStructure{N} <: AbstractVector{StridedStructure{N}}
203+
# the codomain legs of every splitting tree, padded with zeros for the domain legs
204+
trees₁::Vector{StridedStructure{N}}
205+
# the domain legs of every fusion tree, padded with zeros for the codomain legs
206+
trees₂::Vector{StridedStructure{N}}
207+
# shared with the `FusionTreePairs`, to convert between positions and tokens
208+
ranges₁::Vector{UnitRange{Int}}
209+
ranges₂::Vector{UnitRange{Int}}
210+
positions₁::Vector{Int}
211+
positions₂::Vector{Int}
212+
offsets::Vector{Int}
213+
end
214+
SubblockStructure(trees₁, trees₂, t::FusionTreePairs) =
215+
SubblockStructure(trees₁, trees₂, t.ranges₁, t.ranges₂, t.positions₁, t.positions₂, t.offsets)
216+
217+
# the token `(i₁, i₂)` of a fusion tree pair, which also addresses its subblock
218+
const SubblockToken = Tuple{Int, Int}
219+
220+
Base.size(s::SubblockStructure) = (last(s.offsets),)
221+
Base.IndexStyle(::Type{<:SubblockStructure}) = IndexLinear()
222+
Base.@propagate_inbounds Base.getindex(s::SubblockStructure, i::Int) =
223+
s[_pairtoken(s.ranges₁, s.ranges₂, s.offsets, i)]
224+
Base.@propagate_inbounds function Base.getindex(s::SubblockStructure, (i₁, i₂)::SubblockToken)
225+
sz₁, str₁, offset₁ = s.trees₁[i₁]
226+
sz₂, str₂, offset₂ = s.trees₂[i₂]
227+
return (sz₁ .+ sz₂, str₁ .+ str₂, offset₁ + offset₂)
228+
end
229+
_tokenvalue(values::SubblockStructure, keys, token) = values[token]
230+
pairposition(s::SubblockStructure, (i₁, i₂)::SubblockToken) = @inbounds s.positions₂[i₂] + s.positions₁[i₁]
231+
232+
# the arrays shared with the `FusionTreePairs` are accounted for in the `sectorstructure` cache
233+
_cache_payload_size(s::SubblockStructure) = sizeof(s) + sizeof(s.trees₁) + sizeof(s.trees₂)
234+
183235
"""
184236
DegeneracyStructure{N}
185237
@@ -191,18 +243,19 @@ strides that depend on the degeneracy (multiplicity) dimensions. Specific to a g
191243
- `totaldim`: total number of elements in the flat data vector.
192244
- `blockstructure`: `Vector` of `((d₁, d₂), range)` values, one per coupled sector, in the
193245
same order as [`sectorstructure`](@ref)`.blocksectors`.
194-
- `subblockstructure`: `Vector` of [`StridedStructure`](@ref) `(sizes, strides, offset)`
195-
values, one per fusion tree pair, in the same order as [`sectorstructure`](@ref)`.fusiontrees`.
246+
- `subblockstructure`: [`SubblockStructure`](@ref) of the `(sizes, strides, offset)` of every
247+
fusion tree pair, in the same order as [`sectorstructure`](@ref)`.fusiontrees`.
196248
197249
See also [`degeneracystructure`](@ref), [`SectorStructure`](@ref).
198250
"""
199251
struct DegeneracyStructure{N}
200252
totaldim::Int
201253
blockstructure::Vector{Tuple{Tuple{Int, Int}, UnitRange{Int}}}
202-
subblockstructure::Vector{StridedStructure{N}}
254+
subblockstructure::SubblockStructure{N}
203255
end
204256

205-
MemoizationKit.cachesize(s::DegeneracyStructure) = sizeof(s) + sizeof(s.blockstructure) + sizeof(s.subblockstructure)
257+
MemoizationKit.cachesize(s::DegeneracyStructure) =
258+
sizeof(s) + sizeof(s.blockstructure) + _cache_payload_size(s.subblockstructure)
206259

207260
function degeneracystructuretype(W::HomSpace)
208261
N = length(codomain(W)) + length(domain(W))
@@ -219,57 +272,42 @@ since degeneracy dimensions affect the block sizes and offsets).
219272
See also [`sectorstructure`](@ref), [`blockstructure`](@ref), [`subblockstructure`](@ref).
220273
""" degeneracystructure(::HomSpace)
221274
@cached function degeneracystructure(W::HomSpace)::degeneracystructuretype(W)
222-
codom = codomain(W)
223-
dom = domain(W)
224-
N = length(codom) + length(dom)
275+
codom, dom = codomain(W), domain(W)
276+
N₁, N₂ = length(codom), length(dom)
277+
zeros₁, zeros₂ = ntuple(Returns(0), N₁), ntuple(Returns(0), N₂)
225278

226279
ss = sectorstructure(W)
227280
ts = ss.fusiontrees
228-
structurevalues = sizehint!(Vector{StridedStructure{N}}(), length(ts))
281+
trees₁ = Vector{StridedStructure{N₁ + N₂}}(undef, length(ts.trees₁))
282+
trees₂ = Vector{StridedStructure{N₁ + N₂}}(undef, length(ts.trees₂))
229283
blockvalues = Vector{Tuple{Tuple{Int, Int}, UnitRange{Int}}}(undef, length(ss.blocksectors))
230284

231-
# the subblocks of every coupled sector, from the degeneracies of the trees of both sides;
232-
# filling a reused buffer is noticeably faster than `map` for the subblock loop below
233-
splittingstructure = Vector{NTuple{numout(W), Int}}()
285+
# every block is column major, with the rows of its splitting trees and the columns of its
286+
# fusion trees, both in order; the legs of a tree are column major within its rows or columns
234287
blockoffset = 0
235288
for (block_index, (r₁, r₂)) in enumerate(zip(ts.ranges₁, ts.ranges₂))
236-
empty!(splittingstructure)
237289
blockdim₁ = 0
238290
for i in r₁
239291
d₁s = dims(codom, gettokenvalue(ts.trees₁, i).uncoupled)
292+
@assert !any(==(0), d₁s)
293+
trees₁[i] = ((d₁s..., zeros₂...), (_colmajorstrides(d₁s, 1)..., zeros₂...), blockdim₁)
240294
blockdim₁ += prod(d₁s)
241-
push!(splittingstructure, d₁s)
242295
end
243-
strides = (1, blockdim₁)
244296
blockdim₂ = 0
245297
for i in r₂
246298
d₂s = dims(dom, gettokenvalue(ts.trees₂, i).uncoupled)
247-
d₂ = prod(d₂s)
248-
offset₁ = 0
249-
for d₁s in splittingstructure
250-
d₁ = prod(d₁s)
251-
totaloffset = blockoffset + blockdim₂ * blockdim₁ + offset₁
252-
subsz = (d₁s..., d₂s...)
253-
@assert !any(==(0), subsz)
254-
substr = _subblock_strides(subsz, (d₁, d₂), strides)
255-
push!(structurevalues, (subsz, substr, totaloffset))
256-
offset₁ += d₁
257-
end
258-
blockdim₂ += d₂
299+
@assert !any(==(0), d₂s)
300+
trees₂[i] = ((zeros₁..., d₂s...), (zeros₁..., _colmajorstrides(d₂s, blockdim₁)...), blockoffset + blockdim₂ * blockdim₁)
301+
blockdim₂ += prod(d₂s)
259302
end
260303
blockrange = (blockoffset + 1):(blockoffset + blockdim₁ * blockdim₂)
261304
blockvalues[block_index] = ((blockdim₁, blockdim₂), blockrange)
262305
blockoffset = last(blockrange)
263306
end
264307

265-
return DegeneracyStructure(blockoffset, blockvalues, structurevalues)
266-
end
267-
268-
function _subblock_strides(subsz, sz, str)
269-
sz_simplify = Strided.StridedViews._simplifydims(sz, str)
270-
strides = Strided.StridedViews._computereshapestrides(subsz, sz_simplify...)
271-
isnothing(strides) &&
272-
throw(ArgumentError("unexpected error in computing subblock strides"))
273-
return strides
308+
subblockvalues = SubblockStructure(trees₁, trees₂, ts)
309+
return DegeneracyStructure(blockoffset, blockvalues, subblockvalues)
274310
end
275311

312+
# the strides of legs with sizes `ds` that are column major, starting from `stride`
313+
_colmajorstrides(ds::Tuple, stride::Int) = Base.front(cumprod((stride, ds...)))

‎src/tensors/blockiterators.jl‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ end
108108

109109
# Positional subblock collections
110110
# -------------------------------
111-
# These address subblocks by their position in the canonical order of `fusiontrees(space(t))`,
112-
# hoisting the space-level lookups out of the individual accesses.
111+
# These address subblocks by their position in the canonical order of `fusiontrees(space(t))`, or
112+
# by the token of their fusion tree pair, hoisting the space-level lookups out of the accesses.
113113

114114
"""
115115
struct SubblockIterator{T <: AbstractTensorMap, S}
@@ -144,6 +144,8 @@ Base.isdone(iter::SubblockIterator, i::Int = 1) = i > length(iter)
144144
@propagate_inbounds Base.getindex(iter::SubblockIterator, i::Int) =
145145
subblock(iter.t, gettokenvalue(keys(iter.structure), i))
146146
@propagate_inbounds Base.getindex(iter::SubblockIterator, f::FusionTreePair) = subblock(iter.t, f)
147+
@propagate_inbounds Base.getindex(iter::SubblockIterator, token::SubblockToken) =
148+
subblock(iter.t, gettokenvalue(keys(iter.structure), token))
147149

148150
function Base.iterate(iter::SubblockIterator, i::Int = 1)
149151
i > length(iter) && return nothing
@@ -202,9 +204,9 @@ As a result, the kernels do not have to be recompiled for each new symmetry type
202204
"""
203205
struct StridedSubblocks{A <: DenseVector, N}
204206
data::A
205-
structure::Vector{StridedStructure{N}}
207+
structure::SubblockStructure{N}
206208
# store the data as `StridedView` parents it, so that `A` is also the parent type of the views
207-
function StridedSubblocks(data::DenseVector, structure::Vector{StridedStructure{N}}) where {N}
209+
function StridedSubblocks(data::DenseVector, structure::SubblockStructure{N}) where {N}
208210
data′ = parent(StridedView(data))
209211
return new{typeof(data′), N}(data′, structure)
210212
end
@@ -217,7 +219,8 @@ Base.firstindex(s::StridedSubblocks) = 1
217219
Base.lastindex(s::StridedSubblocks) = length(s)
218220
Base.eltype(::Type{StridedSubblocks{A, N}}) where {A, N} = StridedView{eltype(A), N, A, typeof(identity)}
219221

220-
Base.@propagate_inbounds function Base.getindex(s::StridedSubblocks, i::Int)
222+
# by position, or by the token of the fusion tree pair
223+
Base.@propagate_inbounds function Base.getindex(s::StridedSubblocks, i::Union{Int, SubblockToken})
221224
sz, str, offset = s.structure[i]
222225
return StridedView(s.data, sz, str, offset)
223226
end

‎src/tensors/indexmanipulations.jl‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -726,15 +726,17 @@ function add_transform_kernel!(
726726
return nothing
727727
end
728728

729-
# `U` is either a scalar coefficient with integer positions (unique fusion), or a recoupling
730-
# matrix with vectors of positions (generic).
729+
# `U` is either a scalar coefficient with single tokens (unique fusion), or a recoupling matrix
730+
# with vectors of tokens (generic).
731+
_onlytoken(token::SubblockToken) = token
732+
_onlytoken(tokens::AbstractVector{SubblockToken}) = only(tokens)
731733
function _add_transform_block!(
732734
dst::TransformSubblocks, src::TransformSubblocks, p, conjsrc::Bool, U, inds_dst, inds_src, buffer,
733735
α, β, backend, allocator
734736
)
735737
if length(U) == 1 # single tree: no matmul needed
736738
@timeit_debug GLOBAL_TIMER "dense: tensoradd" @inbounds TO.tensoradd!(
737-
dst[only(inds_dst)], src[only(inds_src)], p, conjsrc, α * only(U), β, backend, allocator
739+
dst[_onlytoken(inds_dst)], src[_onlytoken(inds_src)], p, conjsrc, α * only(U), β, backend, allocator
738740
)
739741
else # Multi-tree block: pack → recoupling matmul → unpack.
740742
rows, cols = size(U)

‎src/tensors/tensor.jl‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -497,7 +497,7 @@ end
497497
# Getting and setting the data at the subblock level
498498
# --------------------------------------------------
499499
StridedSubblocks(t::TensorMap) = StridedSubblocks(t.data, degeneracystructure(space(t)).subblockstructure)
500-
StridedSubblocks(t::TensorMap, structure::Vector{<:StridedStructure}) = StridedSubblocks(t.data, structure)
500+
StridedSubblocks(t::TensorMap, structure::SubblockStructure) = StridedSubblocks(t.data, structure)
501501

502502
# the subblocks of a `TensorMap` are strided views into its flat data, which the subblock
503503
# structure of its space describes directly
@@ -513,6 +513,10 @@ SubblockIterator(t::TensorMap) = SubblockIterator(t, subblockstructure(space(t))
513513
@inbounds sz, str, offset = gettokenvalue(iter.structure, i)
514514
return StridedView(iter.t.data, sz, str, offset)
515515
end
516+
@propagate_inbounds function Base.getindex(iter::SubblockIterator{<:TensorMap}, token::SubblockToken)
517+
sz, str, offset = gettokenvalue(iter.structure, token)
518+
return StridedView(iter.t.data, sz, str, offset)
519+
end
516520
@propagate_inbounds function Base.getindex(iter::SubblockIterator{<:TensorMap}, f::FusionTreePair)
517521
found, token = gettoken(iter.structure, f)
518522
@boundscheck found || _throw_subblock_missing(f)

0 commit comments

Comments
 (0)