From 8a1d17d3a95d2f4d9f2bbf636b05b5c21d6d3c58 Mon Sep 17 00:00:00 2001 From: leburgel Date: Wed, 28 Oct 2026 19:01:20 +0100 Subject: [PATCH 1/6] Store the fusion trees of both sides instead of every fusion tree pair `fusiontrees(W)` is a `FusionTreePairs`, an `AbstractIndices` holding the splitting and fusion trees of every coupled sector; the position of a pair follows from those of its trees, and is its token. `subblockstructure(W)` shares these tokens. `fusionblocks` groups the trees of each side by their uncoupled sectors, combines the groups in the order in which they first occur, and fills every block once at its final size; `degeneracystructure` loops over the trees of both sides. Co-Authored-By: Claude Opus 5.5 --- docs/src/Changelog.md | 1 + src/TensorKit.jl | 2 +- src/spaces/homspace.jl | 57 ++++++++---- src/spaces/structure.jl | 186 ++++++++++++++++++++++------------------ 4 files changed, 146 insertions(+), 100 deletions(-) diff --git a/docs/src/Changelog.md b/docs/src/Changelog.md index 63d293e9b..2c8b54327 100644 --- a/docs/src/Changelog.md +++ b/docs/src/Changelog.md @@ -41,6 +41,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec - `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)) - `foreachblock` with several tensors is type stable, which removes the dynamic dispatch on every call to it and to the factorizations that go through it +- `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)) ## [0.17.3](https://github.com/QuantumKitHub/TensorKit.jl/compare/v0.17.2...v0.17.3) - 2026-10-30 diff --git a/src/TensorKit.jl b/src/TensorKit.jl index 97031a665..4d3542dcc 100644 --- a/src/TensorKit.jl +++ b/src/TensorKit.jl @@ -118,7 +118,7 @@ const TO = TensorOperations using MatrixAlgebraKit -using Dictionaries: Dictionaries, Dictionary, Indices, gettoken, gettokenvalue +using Dictionaries: Dictionaries, AbstractDictionary, AbstractIndices, Dictionary, Indices, gettoken, gettokenvalue using OhMyThreads using ScopedValues using TimerOutputs: TimerOutputs, TimerOutput, @timeit_debug diff --git a/src/spaces/homspace.jl b/src/spaces/homspace.jl index 38bf7eb60..9b001a213 100644 --- a/src/spaces/homspace.jl +++ b/src/spaces/homspace.jl @@ -179,10 +179,11 @@ See also [`degeneracystructure`](@ref), [`subblockstructure`](@ref). blockstructure(W::HomSpace) = Dictionary(blocksectors(W), degeneracystructure(W).blockstructure) """ - fusiontrees(W::HomSpace) -> Indices{Tuple{F₁,F₂}} + fusiontrees(W::HomSpace) -> FusionTreePairs{F₁,F₂} -Return an `Indices` of all valid fusion tree pairs `(f₁, f₂)` for `W`, providing a -bijection to sequential integer positions via `gettoken`/`gettokenvalue`. The result is +Return the `FusionTreePairs` of all valid fusion tree pairs `(f₁, f₂)` for `W`, an +`AbstractIndices` providing a bijection to sequential integer positions via +`gettoken`/`gettokenvalue`. The result is cached based on the sector structure of `W` (ignoring degeneracy dimensions), so `HomSpace`s that share the same sectors, dualities, and index count will reuse the same object. @@ -192,14 +193,14 @@ See also [`sectorstructure`](@ref), [`subblockstructure`](@ref). fusiontrees(W::HomSpace) = sectorstructure(W).fusiontrees """ - subblockstructure(W::HomSpace) -> Dictionary + subblockstructure(W::HomSpace) -> AbstractDictionary -Return a `Dictionary` mapping each fusion tree pair `(f₁, f₂)` to its +Return an `AbstractDictionary` mapping each fusion tree pair `(f₁, f₂)` to its [`StridedStructure`](@ref) `(sizes, strides, offset)`. See also [`degeneracystructure`](@ref), [`blockstructure`](@ref). """ -subblockstructure(W::HomSpace) = Dictionary(fusiontrees(W), degeneracystructure(W).subblockstructure) +subblockstructure(W::HomSpace) = FusionTreePairDict(fusiontrees(W), degeneracystructure(W).subblockstructure) """ fusionblocks(W::HomSpace) @@ -211,19 +212,41 @@ function fusionblocks(W::HomSpace) I = sectortype(W) N₁, N₂ = numout(W), numin(W) F = fusiontreetype(I, N₁, N₂) - # group the (cached) fusion trees of `W` by their uncoupled sectors, - # in the order in which these first occur - blocks = FusionTreeBlock{I, N₁, N₂, F}[] - trees_of = Dict{Tuple{NTuple{N₁, I}, NTuple{N₂, I}}, Vector{F}}() - for (f₁, f₂) in fusiontrees(W) - trees = get!(trees_of, (f₁.uncoupled, f₂.uncoupled)) do - newtrees = F[] - push!(blocks, FusionTreeBlock(newtrees)) - return newtrees + ts = fusiontrees(W) + # group the (cached) splitting and fusion trees of every coupled sector of `W` by their + # uncoupled sectors: a block combines the groups of both sides with the same uncoupled + # sectors, in the order in which these first occur in `fusiontrees(W)` + parts = Vector{Tuple{Vector{Int}, Vector{Int}}}[] + part_of = Dict{Tuple{NTuple{N₁, I}, NTuple{N₂, I}}, Int}() + for (r₁, r₂) in zip(ts.ranges₁, ts.ranges₂) + g₁ = _groupbyuncoupled(NTuple{N₁, I}, ts.trees₁, r₁) + g₂ = _groupbyuncoupled(NTuple{N₂, I}, ts.trees₂, r₂) + for (u₂, is₂) in pairs(g₂), (u₁, is₁) in pairs(g₁) + k = get!(part_of, (u₁, u₂)) do + push!(parts, Tuple{Vector{Int}, Vector{Int}}[]) + return length(parts) + end + push!(parts[k], (is₂, is₁)) end - push!(trees, (f₁, f₂)) end - return blocks + # every block is filled once, at its final size + return map(parts) do ps + trees = Vector{F}(undef, sum(((is₂, is₁),) -> length(is₂) * length(is₁), ps)) + k = 0 + for (is₂, is₁) in ps, i₂ in is₂, i₁ in is₁ + trees[k += 1] = (gettokenvalue(ts.trees₁, i₁), gettokenvalue(ts.trees₂, i₂)) + end + return FusionTreeBlock(trees) + end +end +# the positions in `r` of `trees`, grouped by their uncoupled sectors in the order in which +# these first occur +function _groupbyuncoupled(::Type{U}, trees, r) where {U} + groups = Dictionary{U, Vector{Int}}() + for i in r + push!(get!(Vector{Int}, groups, gettokenvalue(trees, i).uncoupled), i) + end + return groups end function diagonalblockstructure(W::HomSpace) diff --git a/src/spaces/structure.jl b/src/spaces/structure.jl index 1485e4691..21999eefe 100644 --- a/src/spaces/structure.jl +++ b/src/spaces/structure.jl @@ -12,63 +12,118 @@ depending only on which sectors appear (not their degeneracy dimensions). Shared ## Fields - `blocksectors`: `Indices` of all coupled sectors `c::I`. -- `fusiontrees`: `Indices` of all valid fusion tree pairs `(f₁, f₂)`, in canonical order. +- `fusiontrees`: `FusionTreePairs` of all valid fusion tree pairs `(f₁, f₂)`, in canonical order. See also [`sectorstructure`](@ref), [`DegeneracyStructure`](@ref). """ -struct SectorStructure{I <: Sector, F <: FusionTreePair{I}} +struct SectorStructure{I <: Sector, F <: FusionTreePair{I}, T <: AbstractIndices{F}} blocksectors::Indices{I} - fusiontrees::Indices{F} + fusiontrees::T end +""" + FusionTreePairs{F₁, F₂} <: AbstractIndices{Tuple{F₁, F₂}} + +The fusion tree pairs `(f₁, f₂)` of a `HomSpace`, ordered by coupled sector, then `f₂`, then `f₁`, +stored as the splitting trees `f₁` and the fusion trees `f₂` of every coupled sector. The token of +a pair is its position. +""" +struct FusionTreePairs{F₁, F₂} <: AbstractIndices{Tuple{F₁, F₂}} + trees₁::Indices{F₁} # splitting trees, grouped by coupled sector + trees₂::Indices{F₂} # fusion trees, grouped by coupled sector + blocks₁::Vector{Int} # the coupled sector of every splitting tree + blocks₂::Vector{Int} # the coupled sector of every fusion tree + ranges₁::Vector{UnitRange{Int}} # the splitting trees of every coupled sector + ranges₂::Vector{UnitRange{Int}} # the fusion trees of every coupled sector + offsets::Vector{Int} # the number of pairs before every coupled sector, and in total +end + +# from the trees of both sides of every coupled sector +function FusionTreePairs{F₁, F₂}(sides₁, sides₂) where {F₁, F₂} + lengths(ss) = map(length, ss) + ranges(ss) = map((n, l) -> (n - l + 1):n, cumsum(lengths(ss)), lengths(ss)) + blocks(ss) = Int[b for (b, ts) in enumerate(ss) for _ in ts] + offsets = cumsum(vcat(0, lengths(sides₁) .* lengths(sides₂))) + return FusionTreePairs{F₁, F₂}( + Indices(F₁[f for ts in sides₁ for f in ts]), Indices(F₂[f for ts in sides₂ for f in ts]), + blocks(sides₁), blocks(sides₂), ranges(sides₁), ranges(sides₂), offsets + ) +end + +_cache_payload_size(t::FusionTreePairs) = + sum(f -> (x = getfield(t, f); x isa Indices ? _cache_payload_size(x) : sizeof(x)), fieldnames(typeof(t))) + +Base.length(t::FusionTreePairs) = last(t.offsets) +Dictionaries.istokenizable(::FusionTreePairs) = true +Dictionaries.tokentype(::FusionTreePairs) = Int +Dictionaries.iteratetoken(t::FusionTreePairs, i::Int = 0) = i < length(t) ? (i + 1, i + 1) : nothing +# tokens as returned by `gettoken` look like those of `Indices`, with the position second +function Dictionaries.gettoken(t::FusionTreePairs, (f₁, f₂)) + found₁, (_, i₁) = gettoken(t.trees₁, f₁) + found₂, (_, i₂) = gettoken(t.trees₂, f₂) + (found₁ && found₂ && t.blocks₁[i₁] == t.blocks₂[i₂]) || return false, (0, 0) + b = t.blocks₁[i₁] + r₁, r₂ = t.ranges₁[b], t.ranges₂[b] + return true, (0, t.offsets[b] + (i₂ - first(r₂)) * length(r₁) + (i₁ - first(r₁)) + 1) +end +Dictionaries.gettokenvalue(t::FusionTreePairs, (_, i)::Tuple{Int, Int}) = gettokenvalue(t, i) +function Dictionaries.gettokenvalue(t::FusionTreePairs, i::Int) + b = searchsortedlast(t.offsets, i - 1) + r₁, r₂ = t.ranges₁[b], t.ranges₂[b] + j₂, j₁ = divrem(i - 1 - t.offsets[b], length(r₁)) + return (gettokenvalue(t.trees₁, first(r₁) + j₁), gettokenvalue(t.trees₂, first(r₂) + j₂)) +end +Base.iterate(t::FusionTreePairs) = iterate(t, (1, 0, 1)) +function Base.iterate(t::FusionTreePairs, (b, i₁, i₂)) + while b <= length(t.ranges₁) + r₁, r₂ = t.ranges₁[b], t.ranges₂[b] + i₁ += 1 + i₁ > length(r₁) && (i₁ = 1; i₂ += 1) + i₂ <= length(r₂) && !isempty(r₁) && + return (gettokenvalue(t.trees₁, first(r₁) + i₁ - 1), gettokenvalue(t.trees₂, first(r₂) + i₂ - 1)), (b, i₁, i₂) + b, i₁, i₂ = b + 1, 0, 1 + end + return nothing +end + +# values for every fusion tree pair, sharing the tokens of `FusionTreePairs` +struct FusionTreePairDict{K, V, T <: FusionTreePairs} <: AbstractDictionary{K, V} + keys::T + values::Vector{V} +end +FusionTreePairDict(keys::T, values::Vector{V}) where {T <: FusionTreePairs, V} = + FusionTreePairDict{eltype(T), V, T}(keys, values) +Base.keys(d::FusionTreePairDict) = d.keys +Dictionaries.istokenizable(::FusionTreePairDict) = true +Dictionaries.istokenassigned(::FusionTreePairDict, _) = true +Dictionaries.gettokenvalue(d::FusionTreePairDict, i::Int) = d.values[i] +Dictionaries.gettokenvalue(d::FusionTreePairDict, (_, i)::Tuple{Int, Int}) = d.values[i] + MemoizationKit.cachesize(s::SectorStructure) = sizeof(s) + _cache_payload_size(s.blocksectors) + _cache_payload_size(s.fusiontrees) Base.@assume_effects :foldable function sectorstructuretype(::S) where {S <: HomSpace} I = sectortype(S) - F = fusiontreetype(I, numout(S), numin(S)) - return SectorStructure{I, F} + F₁, F₂ = fusiontreetype(I, numout(S)), fusiontreetype(I, numin(S)) + return SectorStructure{I, Tuple{F₁, F₂}, FusionTreePairs{F₁, F₂}} end """ sectorstructure(W::HomSpace) -> SectorStructure -Return the [`SectorStructure`](@ref) for `W`, containing the coupled sectors and fusion tree -pairs as `Indices`. The result is cached based on the sector structure of `W` (ignoring +Return the [`SectorStructure`](@ref) for `W`, containing the coupled sectors as `Indices` and the +fusion tree pairs as `FusionTreePairs`. The result is cached based on the sector structure of `W` (ignoring degeneracy dimensions). See also [`degeneracystructure`](@ref), [`fusiontrees`](@ref), [`blocksectors`](@ref). """ @cached function sectorstructure(W::S)::sectorstructuretype(W) where {S <: HomSpace} - codom, dom = codomain(W), domain(W) - - I = sectortype(S) - F = fusiontreetype(I, numout(S), numin(S)) - bs = Vector{I}() - trees = Vector{F}() - - for c in _blocksectors(W) - push!(bs, c) - offset = length(trees) - n₁ = 0 - for f₂ in fusiontrees(dom, c) - if n₁ == 0 - # First f₂ for this sector: enumerate codomain trees and record how many there are. - for f₁ in fusiontrees(codom, c) - push!(trees, (f₁, f₂)) - end - n₁ = length(trees) - offset - else - # Subsequent f₂s: the codomain trees are already in the list at - # offset .+ (1:n₁), so read them back instead of recomputing. - for j in offset .+ (1:n₁) - push!(trees, (trees[j][1], f₂)) - end - end - end - end - - return SectorStructure{I, F}(Indices(bs), Indices(trees)) + # the trees of both sides of every coupled sector; the pairs are not stored + bs = collect(_blocksectors(W)) + F₁, F₂ = fusiontreetype(sectortype(S), numout(S)), fusiontreetype(sectortype(S), numin(S)) + sides₁ = map(c -> collect(fusiontrees(codomain(W), c)), bs) + sides₂ = map(c -> collect(fusiontrees(domain(W), c)), bs) + return sectorstructuretype(W)(Indices(bs), FusionTreePairs{F₁, F₂}(sides₁, sides₂)) end MemoizationKit.cachekey(::typeof(sectorstructure), W::HomSpace) = (Hashed(W, sectorhash, sectorequal),) @@ -119,72 +174,38 @@ See also [`sectorstructure`](@ref), [`blockstructure`](@ref), [`subblockstructur N = length(codom) + length(dom) ss = sectorstructure(W) - treelist = ss.fusiontrees - L = length(treelist) - structurevalues = sizehint!(Vector{StridedStructure{N}}(), L) + ts = ss.fusiontrees + structurevalues = Vector{StridedStructure{N}}(undef, length(ts)) blockvalues = Vector{Tuple{Tuple{Int, Int}, UnitRange{Int}}}(undef, length(ss.blocksectors)) - # temporary data structures - splittingstructure = Vector{NTuple{numout(W), Int}}() - + # the subblocks of every coupled sector, from the degeneracies of the trees of both sides blockoffset = 0 - tree_index = 1 - block_index = 1 - while tree_index <= L - f₁, f₂ = gettokenvalue(treelist, tree_index) - c = f₁.coupled - - # compute subblock structure - # splitting tree data - empty!(splittingstructure) - offset₁ = 0 - for i in tree_index:L - f₁′, f₂′ = gettokenvalue(treelist, i) - f₂′ == f₂ || break - s₁ = f₁′.uncoupled - d₁s = dims(codom, s₁) - d₁ = prod(d₁s) - offset₁ += d₁ - push!(splittingstructure, d₁s) - end - blockdim₁ = offset₁ - n₁ = length(splittingstructure) + tree_index = 0 + for (block_index, (r₁, r₂)) in enumerate(zip(ts.ranges₁, ts.ranges₂)) + d₁ss = map(i -> dims(codom, gettokenvalue(ts.trees₁, i).uncoupled), r₁) + d₂ss = map(i -> dims(dom, gettokenvalue(ts.trees₂, i).uncoupled), r₂) + blockdim₁ = sum(prod, d₁ss; init = 0) + blockdim₂ = sum(prod, d₂ss; init = 0) strides = (1, blockdim₁) - - # fusion tree data and combine offset₂ = 0 - n₂ = 0 - for i in tree_index:n₁:L - f₁′, f₂′ = gettokenvalue(treelist, i) - f₂′.coupled == c || break - n₂ += 1 - s₂ = f₂′.uncoupled - d₂s = dims(dom, s₂) + for d₂s in d₂ss d₂ = prod(d₂s) offset₁ = 0 - for d₁s in splittingstructure + for d₁s in d₁ss d₁ = prod(d₁s) totaloffset = blockoffset + offset₂ * blockdim₁ + offset₁ subsz = (d₁s..., d₂s...) @assert !any(==(0), subsz) substr = _subblock_strides(subsz, (d₁, d₂), strides) - push!(structurevalues, (subsz, substr, totaloffset)) + structurevalues[tree_index += 1] = (subsz, substr, totaloffset) offset₁ += d₁ end offset₂ += d₂ end - - # compute block structure - blockdim₂ = offset₂ blockrange = (blockoffset + 1):(blockoffset + blockdim₁ * blockdim₂) blockvalues[block_index] = ((blockdim₁, blockdim₂), blockrange) - - # reset blockoffset = last(blockrange) - tree_index += n₁ * n₂ - block_index += 1 end - @assert length(structurevalues) == L return DegeneracyStructure(blockoffset, blockvalues, structurevalues) end @@ -196,3 +217,4 @@ function _subblock_strides(subsz, sz, str) throw(ArgumentError("unexpected error in computing subblock strides")) return strides end + From 2a6e75e76d71645c9a60dbbe15cbd1ce6da6e0e7 Mon Sep 17 00:00:00 2001 From: leburgel Date: Wed, 28 Oct 2026 19:46:35 +0100 Subject: [PATCH 2/6] Support spaces without indices and the reverse iteration of FusionTreePairs The units of a product sector, the block sectors of a space without indices, come with a shape, and showing a FusionTreePairs iterates it in reverse. Co-Authored-By: Claude Opus 5.5 --- src/spaces/structure.jl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/spaces/structure.jl b/src/spaces/structure.jl index 21999eefe..f33cb114e 100644 --- a/src/spaces/structure.jl +++ b/src/spaces/structure.jl @@ -57,6 +57,7 @@ Base.length(t::FusionTreePairs) = last(t.offsets) Dictionaries.istokenizable(::FusionTreePairs) = true Dictionaries.tokentype(::FusionTreePairs) = Int Dictionaries.iteratetoken(t::FusionTreePairs, i::Int = 0) = i < length(t) ? (i + 1, i + 1) : nothing +Dictionaries.iteratetoken_reverse(t::FusionTreePairs, i::Int = length(t) + 1) = i > 1 ? (i - 1, i - 1) : nothing # tokens as returned by `gettoken` look like those of `Indices`, with the position second function Dictionaries.gettoken(t::FusionTreePairs, (f₁, f₂)) found₁, (_, i₁) = gettoken(t.trees₁, f₁) @@ -119,7 +120,7 @@ See also [`degeneracystructure`](@ref), [`fusiontrees`](@ref), [`blocksectors`]( """ @cached function sectorstructure(W::S)::sectorstructuretype(W) where {S <: HomSpace} # the trees of both sides of every coupled sector; the pairs are not stored - bs = collect(_blocksectors(W)) + bs = vec(collect(_blocksectors(W))) # `vec`: the units of a product sector have a shape F₁, F₂ = fusiontreetype(sectortype(S), numout(S)), fusiontreetype(sectortype(S), numin(S)) sides₁ = map(c -> collect(fusiontrees(codomain(W), c)), bs) sides₂ = map(c -> collect(fusiontrees(domain(W), c)), bs) From 32d8c4e09718eb9548d0db2da3b97b74f6708ff5 Mon Sep 17 00:00:00 2001 From: lkdvos Date: Fri, 6 Nov 2026 13:21:22 -0500 Subject: [PATCH 3/6] Use the tokens of the splitting and fusion trees for FusionTreePairs Replace the per-tree block indices by the coupled sectors, and use the pair of tree positions as the token, with `pairposition` converting it into the position of the pair. Co-Authored-By: Claude Opus 5.5 --- src/spaces/homspace.jl | 6 +- src/spaces/structure.jl | 127 ++++++++++++++++++++++---------- src/tensors/treetransformers.jl | 14 ++-- 3 files changed, 98 insertions(+), 49 deletions(-) diff --git a/src/spaces/homspace.jl b/src/spaces/homspace.jl index 9b001a213..4dcfe0356 100644 --- a/src/spaces/homspace.jl +++ b/src/spaces/homspace.jl @@ -179,11 +179,11 @@ See also [`degeneracystructure`](@ref), [`subblockstructure`](@ref). blockstructure(W::HomSpace) = Dictionary(blocksectors(W), degeneracystructure(W).blockstructure) """ - fusiontrees(W::HomSpace) -> FusionTreePairs{F₁,F₂} + fusiontrees(W::HomSpace) -> FusionTreePairs{I,F₁,F₂} Return the `FusionTreePairs` of all valid fusion tree pairs `(f₁, f₂)` for `W`, an -`AbstractIndices` providing a bijection to sequential integer positions via -`gettoken`/`gettokenvalue`. The result is +`AbstractIndices` in canonical order. `gettokenvalue` with an integer returns the pair at that +position, and `pairposition` returns the position of a pair. The result is cached based on the sector structure of `W` (ignoring degeneracy dimensions), so `HomSpace`s that share the same sectors, dualities, and index count will reuse the same object. diff --git a/src/spaces/structure.jl b/src/spaces/structure.jl index f33cb114e..38c7c1e5b 100644 --- a/src/spaces/structure.jl +++ b/src/spaces/structure.jl @@ -22,31 +22,35 @@ struct SectorStructure{I <: Sector, F <: FusionTreePair{I}, T <: AbstractIndices end """ - FusionTreePairs{F₁, F₂} <: AbstractIndices{Tuple{F₁, F₂}} + FusionTreePairs{I, F₁, F₂} <: AbstractIndices{Tuple{F₁, F₂}} The fusion tree pairs `(f₁, f₂)` of a `HomSpace`, ordered by coupled sector, then `f₂`, then `f₁`, -stored as the splitting trees `f₁` and the fusion trees `f₂` of every coupled sector. The token of -a pair is its position. +stored as the coupled sectors and the splitting trees `f₁` and fusion trees `f₂` of every coupled +sector. The token of a pair is `(i₁, i₂)`, the positions of `f₁` and `f₂` among all splitting and +fusion trees; `pairposition` converts it into the position of the pair. """ -struct FusionTreePairs{F₁, F₂} <: AbstractIndices{Tuple{F₁, F₂}} +struct FusionTreePairs{I, F₁, F₂} <: AbstractIndices{Tuple{F₁, F₂}} + blocksectors::Indices{I} trees₁::Indices{F₁} # splitting trees, grouped by coupled sector trees₂::Indices{F₂} # fusion trees, grouped by coupled sector - blocks₁::Vector{Int} # the coupled sector of every splitting tree - blocks₂::Vector{Int} # the coupled sector of every fusion tree ranges₁::Vector{UnitRange{Int}} # the splitting trees of every coupled sector ranges₂::Vector{UnitRange{Int}} # the fusion trees of every coupled sector + positions₁::Vector{Int} # the position of every splitting tree within its coupled sector + positions₂::Vector{Int} # the number of pairs before the first pair with every fusion tree offsets::Vector{Int} # the number of pairs before every coupled sector, and in total end # from the trees of both sides of every coupled sector -function FusionTreePairs{F₁, F₂}(sides₁, sides₂) where {F₁, F₂} +function FusionTreePairs{I, F₁, F₂}(blocksectors::Indices{I}, sides₁, sides₂) where {I, F₁, F₂} lengths(ss) = map(length, ss) ranges(ss) = map((n, l) -> (n - l + 1):n, cumsum(lengths(ss)), lengths(ss)) - blocks(ss) = Int[b for (b, ts) in enumerate(ss) for _ in ts] offsets = cumsum(vcat(0, lengths(sides₁) .* lengths(sides₂))) - return FusionTreePairs{F₁, F₂}( + positions₁ = Int[j for ts in sides₁ for j in eachindex(ts)] + positions₂ = Int[offsets[b] + (j - 1) * length(sides₁[b]) for (b, ts) in enumerate(sides₂) for j in eachindex(ts)] + return FusionTreePairs{I, F₁, F₂}( + blocksectors, Indices(F₁[f for ts in sides₁ for f in ts]), Indices(F₂[f for ts in sides₂ for f in ts]), - blocks(sides₁), blocks(sides₂), ranges(sides₁), ranges(sides₂), offsets + ranges(sides₁), ranges(sides₂), positions₁, positions₂, offsets ) end @@ -55,39 +59,83 @@ _cache_payload_size(t::FusionTreePairs) = Base.length(t::FusionTreePairs) = last(t.offsets) Dictionaries.istokenizable(::FusionTreePairs) = true -Dictionaries.tokentype(::FusionTreePairs) = Int -Dictionaries.iteratetoken(t::FusionTreePairs, i::Int = 0) = i < length(t) ? (i + 1, i + 1) : nothing -Dictionaries.iteratetoken_reverse(t::FusionTreePairs, i::Int = length(t) + 1) = i > 1 ? (i - 1, i - 1) : nothing -# tokens as returned by `gettoken` look like those of `Indices`, with the position second -function Dictionaries.gettoken(t::FusionTreePairs, (f₁, f₂)) - found₁, (_, i₁) = gettoken(t.trees₁, f₁) - found₂, (_, i₂) = gettoken(t.trees₂, f₂) - (found₁ && found₂ && t.blocks₁[i₁] == t.blocks₂[i₂]) || return false, (0, 0) - b = t.blocks₁[i₁] - r₁, r₂ = t.ranges₁[b], t.ranges₂[b] - return true, (0, t.offsets[b] + (i₂ - first(r₂)) * length(r₁) + (i₁ - first(r₁)) + 1) +Dictionaries.tokentype(::FusionTreePairs) = Tuple{Int, Int} + +""" + pairposition(t::FusionTreePairs, token) -> Int + pairposition(t::FusionTreePairs, (f₁, f₂)) -> Int + +The position of a fusion tree pair in the canonical order of `t`, from its token or from the pair +itself, which must be present. +""" +pairposition(t::FusionTreePairs, (i₁, i₂)::Tuple{Int, Int}) = @inbounds t.positions₂[i₂] + t.positions₁[i₁] +function pairposition(t::FusionTreePairs, f::FusionTreePair) + found, token = gettoken(t, f) + found || throw(KeyError(f)) + return pairposition(t, token) end -Dictionaries.gettokenvalue(t::FusionTreePairs, (_, i)::Tuple{Int, Int}) = gettokenvalue(t, i) -function Dictionaries.gettokenvalue(t::FusionTreePairs, i::Int) +# the token of the pair at position `i` +function pairtoken(t::FusionTreePairs, i::Int) b = searchsortedlast(t.offsets, i - 1) r₁, r₂ = t.ranges₁[b], t.ranges₂[b] j₂, j₁ = divrem(i - 1 - t.offsets[b], length(r₁)) - return (gettokenvalue(t.trees₁, first(r₁) + j₁), gettokenvalue(t.trees₂, first(r₂) + j₂)) + return (first(r₁) + j₁, first(r₂) + j₂) end -Base.iterate(t::FusionTreePairs) = iterate(t, (1, 0, 1)) -function Base.iterate(t::FusionTreePairs, (b, i₁, i₂)) + +# iterate over the tokens, with the state `(b, i₁, i₂)`: the coupled sector and the tokens of the +# current pair, or those before the first pair (forward) or after the last pair (reverse) +function Dictionaries.iteratetoken(t::FusionTreePairs, (b, i₁, i₂) = (1, 0, 0)) while b <= length(t.ranges₁) r₁, r₂ = t.ranges₁[b], t.ranges₂[b] - i₁ += 1 - i₁ > length(r₁) && (i₁ = 1; i₂ += 1) - i₂ <= length(r₂) && !isempty(r₁) && - return (gettokenvalue(t.trees₁, first(r₁) + i₁ - 1), gettokenvalue(t.trees₂, first(r₂) + i₂ - 1)), (b, i₁, i₂) - b, i₁, i₂ = b + 1, 0, 1 + if !(isempty(r₁) || isempty(r₂)) + if i₁ < first(r₁) # before the first pair of `b` + i₁, i₂ = first(r₁), first(r₂) + return (i₁, i₂), (b, i₁, i₂) + elseif i₁ < last(r₁) + return (i₁ + 1, i₂), (b, i₁ + 1, i₂) + elseif i₂ < last(r₂) + return (first(r₁), i₂ + 1), (b, first(r₁), i₂ + 1) + end + end + b, i₁, i₂ = b + 1, 0, 0 end return nothing end +function Dictionaries.iteratetoken_reverse(t::FusionTreePairs, (b, i₁, i₂) = (length(t.ranges₁), typemax(Int), typemax(Int))) + while b >= 1 + r₁, r₂ = t.ranges₁[b], t.ranges₂[b] + if !(isempty(r₁) || isempty(r₂)) + if i₁ > last(r₁) # after the last pair of `b` + i₁, i₂ = last(r₁), last(r₂) + return (i₁, i₂), (b, i₁, i₂) + elseif i₁ > first(r₁) + return (i₁ - 1, i₂), (b, i₁ - 1, i₂) + elseif i₂ > first(r₂) + return (last(r₁), i₂ - 1), (b, last(r₁), i₂ - 1) + end + end + b, i₁, i₂ = b - 1, typemax(Int), typemax(Int) + end + return nothing +end +function Dictionaries.gettoken(t::FusionTreePairs, (f₁, f₂)) + f₁.coupled == f₂.coupled || return false, (0, 0) + found₁, (_, i₁) = gettoken(t.trees₁, f₁) + found₂, (_, i₂) = gettoken(t.trees₂, f₂) + return found₁ & found₂, (i₁, i₂) +end +Dictionaries.gettokenvalue(t::FusionTreePairs, (i₁, i₂)::Tuple{Int, Int}) = + (gettokenvalue(t.trees₁, i₁), gettokenvalue(t.trees₂, i₂)) +# the pair at position `i` +Dictionaries.gettokenvalue(t::FusionTreePairs, i::Int) = gettokenvalue(t, pairtoken(t, i)) +function Base.iterate(t::FusionTreePairs, state...) + next = Dictionaries.iteratetoken(t, state...) + isnothing(next) && return nothing + token, newstate = next + return gettokenvalue(t, token), newstate +end -# values for every fusion tree pair, sharing the tokens of `FusionTreePairs` +# values for every fusion tree pair, stored by position struct FusionTreePairDict{K, V, T <: FusionTreePairs} <: AbstractDictionary{K, V} keys::T values::Vector{V} @@ -98,7 +146,7 @@ Base.keys(d::FusionTreePairDict) = d.keys Dictionaries.istokenizable(::FusionTreePairDict) = true Dictionaries.istokenassigned(::FusionTreePairDict, _) = true Dictionaries.gettokenvalue(d::FusionTreePairDict, i::Int) = d.values[i] -Dictionaries.gettokenvalue(d::FusionTreePairDict, (_, i)::Tuple{Int, Int}) = d.values[i] +Dictionaries.gettokenvalue(d::FusionTreePairDict, token::Tuple{Int, Int}) = d.values[pairposition(d.keys, token)] MemoizationKit.cachesize(s::SectorStructure) = sizeof(s) + _cache_payload_size(s.blocksectors) + _cache_payload_size(s.fusiontrees) @@ -106,7 +154,7 @@ MemoizationKit.cachesize(s::SectorStructure) = Base.@assume_effects :foldable function sectorstructuretype(::S) where {S <: HomSpace} I = sectortype(S) F₁, F₂ = fusiontreetype(I, numout(S)), fusiontreetype(I, numin(S)) - return SectorStructure{I, Tuple{F₁, F₂}, FusionTreePairs{F₁, F₂}} + return SectorStructure{I, Tuple{F₁, F₂}, FusionTreePairs{I, F₁, F₂}} end """ @@ -120,11 +168,12 @@ See also [`degeneracystructure`](@ref), [`fusiontrees`](@ref), [`blocksectors`]( """ @cached function sectorstructure(W::S)::sectorstructuretype(W) where {S <: HomSpace} # the trees of both sides of every coupled sector; the pairs are not stored - bs = vec(collect(_blocksectors(W))) # `vec`: the units of a product sector have a shape - F₁, F₂ = fusiontreetype(sectortype(S), numout(S)), fusiontreetype(sectortype(S), numin(S)) - sides₁ = map(c -> collect(fusiontrees(codomain(W), c)), bs) - sides₂ = map(c -> collect(fusiontrees(domain(W), c)), bs) - return sectorstructuretype(W)(Indices(bs), FusionTreePairs{F₁, F₂}(sides₁, sides₂)) + I = sectortype(S) + bs = Indices(vec(collect(_blocksectors(W)))) # `vec`: the units of a product sector have a shape + F₁, F₂ = fusiontreetype(I, numout(S)), fusiontreetype(I, numin(S)) + sides₁ = map(c -> collect(fusiontrees(codomain(W), c)), bs.values) + sides₂ = map(c -> collect(fusiontrees(domain(W), c)), bs.values) + return sectorstructuretype(W)(bs, FusionTreePairs{I, F₁, F₂}(bs, sides₁, sides₂)) end MemoizationKit.cachekey(::typeof(sectorstructure), W::HomSpace) = (Hashed(W, sectorhash, sectorequal),) diff --git a/src/tensors/treetransformers.jl b/src/tensors/treetransformers.jl index 81a96ad34..224de14d7 100644 --- a/src/tensors/treetransformers.jl +++ b/src/tensors/treetransformers.jl @@ -97,7 +97,7 @@ function UniqueTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::Ho @timeit_debug GLOBAL_TIMER "symmetry: tree transform" for (isrc, (f₁, f₂)) in enumerate(src_trees) f_dst, coeff = transform(conjsrc ? (f₂, f₁) : (f₁, f₂)) - _, (_, idst) = gettoken(dst_trees, f_dst) + idst = pairposition(dst_trees, f_dst) data[isrc] = (convert(T, coeff), idst, isrc) end @@ -132,13 +132,13 @@ function GenericTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::H fs_src = fblocks[i] fs_dst, U = transform(fs_src) @timeit_debug GLOBAL_TIMER "bookkeeping: subblock positions" begin - # the token into the fusion tree `Indices` is the subblock position + # the position of a fusion tree pair is that of its subblock inds_src = map(fusiontrees(fs_src)) do (f₁, f₂) - _, (_, isrc) = gettoken(src_trees, conjsrc ? (f₂, f₁) : (f₁, f₂)) + isrc = pairposition(src_trees, conjsrc ? (f₂, f₁) : (f₁, f₂)) return isrc end inds_dst = map(fusiontrees(fs_dst)) do f - _, (_, idst) = gettoken(dst_trees, f) + idst = pairposition(dst_trees, f) return idst end end @@ -262,7 +262,7 @@ function TraceTransformer(::Type{A}, Vdst::HomSpace, Vsrc::HomSpace, p::Index2Tu for (isrc, f) in enumerate(src_trees) trace_sectors_match(f, q) || continue f′, coeff = planar_trace(f, p, q) - _, (_, idst) = gettoken(dst_trees, f′) + idst = pairposition(dst_trees, f′) addcolumn!([idst], [convert(T, coeff)], isrc) end else @@ -270,11 +270,11 @@ function TraceTransformer(::Type{A}, Vdst::HomSpace, Vsrc::HomSpace, p::Index2Tu trace_sectors_match(fs_src, q) || continue fs_dst, U = planar_trace(fs_src, p, q) inds_dst = map(fusiontrees(fs_dst)) do f - _, (_, idst) = gettoken(dst_trees, f) + idst = pairposition(dst_trees, f) return idst end for (i, f) in enumerate(fusiontrees(fs_src)) - _, (_, isrc) = gettoken(src_trees, f) + isrc = pairposition(src_trees, f) addcolumn!(inds_dst, convert(Vector{T}, U[:, i]), isrc) end end From dca9a93ba39a0cb67b85afa85682a20cab6d051e Mon Sep 17 00:00:00 2001 From: lkdvos Date: Fri, 6 Nov 2026 13:44:25 -0500 Subject: [PATCH 4/6] Fill a reused buffer with the splitting tree degeneracies in degeneracystructure Collecting them with `map` made the subblock loop 10-15% slower than on main, independently of how the strided structures are stored. Co-Authored-By: Claude Opus 5.5 --- src/spaces/structure.jl | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/src/spaces/structure.jl b/src/spaces/structure.jl index 38c7c1e5b..87f86466b 100644 --- a/src/spaces/structure.jl +++ b/src/spaces/structure.jl @@ -225,32 +225,37 @@ See also [`sectorstructure`](@ref), [`blockstructure`](@ref), [`subblockstructur ss = sectorstructure(W) ts = ss.fusiontrees - structurevalues = Vector{StridedStructure{N}}(undef, length(ts)) + structurevalues = sizehint!(Vector{StridedStructure{N}}(), length(ts)) blockvalues = Vector{Tuple{Tuple{Int, Int}, UnitRange{Int}}}(undef, length(ss.blocksectors)) - # the subblocks of every coupled sector, from the degeneracies of the trees of both sides + # the subblocks of every coupled sector, from the degeneracies of the trees of both sides; + # filling a reused buffer is noticeably faster than `map` for the subblock loop below + splittingstructure = Vector{NTuple{numout(W), Int}}() blockoffset = 0 - tree_index = 0 for (block_index, (r₁, r₂)) in enumerate(zip(ts.ranges₁, ts.ranges₂)) - d₁ss = map(i -> dims(codom, gettokenvalue(ts.trees₁, i).uncoupled), r₁) - d₂ss = map(i -> dims(dom, gettokenvalue(ts.trees₂, i).uncoupled), r₂) - blockdim₁ = sum(prod, d₁ss; init = 0) - blockdim₂ = sum(prod, d₂ss; init = 0) + empty!(splittingstructure) + blockdim₁ = 0 + for i in r₁ + d₁s = dims(codom, gettokenvalue(ts.trees₁, i).uncoupled) + blockdim₁ += prod(d₁s) + push!(splittingstructure, d₁s) + end strides = (1, blockdim₁) - offset₂ = 0 - for d₂s in d₂ss + blockdim₂ = 0 + for i in r₂ + d₂s = dims(dom, gettokenvalue(ts.trees₂, i).uncoupled) d₂ = prod(d₂s) offset₁ = 0 - for d₁s in d₁ss + for d₁s in splittingstructure d₁ = prod(d₁s) - totaloffset = blockoffset + offset₂ * blockdim₁ + offset₁ + totaloffset = blockoffset + blockdim₂ * blockdim₁ + offset₁ subsz = (d₁s..., d₂s...) @assert !any(==(0), subsz) substr = _subblock_strides(subsz, (d₁, d₂), strides) - structurevalues[tree_index += 1] = (subsz, substr, totaloffset) + push!(structurevalues, (subsz, substr, totaloffset)) offset₁ += d₁ end - offset₂ += d₂ + blockdim₂ += d₂ end blockrange = (blockoffset + 1):(blockoffset + blockdim₁ * blockdim₂) blockvalues[block_index] = ((blockdim₁, blockdim₂), blockrange) From 776ac93d831cebaf087c3482c3c715e7b8e0d030 Mon Sep 17 00:00:00 2001 From: lkdvos Date: Tue, 10 Nov 2026 13:26:18 -0500 Subject: [PATCH 5/6] 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 --- docs/src/Changelog.md | 1 + ext/TensorKitGPUArraysExt.jl | 3 +- src/pullbacks/tensoroperations.jl | 7 +- src/spaces/structure.jl | 132 +++++++++++++++++++----------- src/tensors/blockiterators.jl | 13 +-- src/tensors/indexmanipulations.jl | 8 +- src/tensors/tensor.jl | 6 +- src/tensors/treetransformers.jl | 76 ++++++++--------- test/other/caches.jl | 8 +- 9 files changed, 149 insertions(+), 105 deletions(-) diff --git a/docs/src/Changelog.md b/docs/src/Changelog.md index 2c8b54327..51b40c3b5 100644 --- a/docs/src/Changelog.md +++ b/docs/src/Changelog.md @@ -42,6 +42,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec - `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)) - `foreachblock` with several tensors is type stable, which removes the dynamic dispatch on every call to it and to the factorizations that go through it - `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)) +- `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)) ## [0.17.3](https://github.com/QuantumKitHub/TensorKit.jl/compare/v0.17.2...v0.17.3) - 2026-10-30 diff --git a/ext/TensorKitGPUArraysExt.jl b/ext/TensorKitGPUArraysExt.jl index d4f682160..cfb7aa72b 100644 --- a/ext/TensorKitGPUArraysExt.jl +++ b/ext/TensorKitGPUArraysExt.jl @@ -670,7 +670,8 @@ function diagonal_device_transformer(A, transformer, dstdiagonal::Bool) n = first(sz) return UniqueTransformerBlock{typeof(coeff), 1}( coeff, (n,), (1,), dstdiagonal ? (1,) : (sum(strides_dst),), - dstdiagonal ? offsets_dst[idst] : offset_dst, (1,), offsets_src[isrc] + dstdiagonal ? offsets_dst[TensorKit.pairposition(structure_dst, idst)] : offset_dst, (1,), + offsets_src[TensorKit.pairposition(structure_src, isrc)] ) end work_offsets, nwork = _work_offsets(blk.sz[1] for blk in blocks) diff --git a/src/pullbacks/tensoroperations.jl b/src/pullbacks/tensoroperations.jl index c157b0987..6e266b9f2 100644 --- a/src/pullbacks/tensoroperations.jl +++ b/src/pullbacks/tensoroperations.jl @@ -90,8 +90,9 @@ function _planartrace_pullback_ΔA!( ΔA, ΔC, transformer::TraceTransformer, (p₁, p₂), (q₁, q₂), α, backend, allocator ) lp = (p₁..., p₂...) - dims_dst = [dim(f₁.coupled) for (f₁, _) in fusiontrees(ΔC)] - dims_src = [dim(f₁.coupled) for (f₁, _) in fusiontrees(ΔA)] + trees_dst, trees_src = fusiontrees(ΔC), fusiontrees(ΔA) + dims_dst = [dim(f₁.coupled) for (f₁, _) in trees_dst] + dims_src = [dim(f₁.coupled) for (f₁, _) in trees_src] dst, src = _transform_subblocks(ΔC, ΔA, transformer) for (U, inds_dst, inds_src) in transformer.data, (j, isrc) in enumerate(inds_src) # the traced diagonal of the source subblock, with the remaining legs permuted by `p` @@ -112,7 +113,7 @@ function _planartrace_pullback_ΔA!( parent(c), (size(c)..., sz_traced...), (strides(c)..., map(zero, sz_traced)...), c.offset, c.op ) - coeff = conj(α * U[i, j]) * (dims_dst[idst] / dims_src[isrc]) + coeff = conj(α * U[i, j]) * (dims_dst[pairposition(trees_dst, idst)] / dims_src[pairposition(trees_src, isrc)]) TO.tensoradd!(diag, ΔCi, pdiag, false, coeff, One(), backend, allocator) end end diff --git a/src/spaces/structure.jl b/src/spaces/structure.jl index 87f86466b..d507eedc7 100644 --- a/src/spaces/structure.jl +++ b/src/spaces/structure.jl @@ -69,16 +69,25 @@ The position of a fusion tree pair in the canonical order of `t`, from its token itself, which must be present. """ pairposition(t::FusionTreePairs, (i₁, i₂)::Tuple{Int, Int}) = @inbounds t.positions₂[i₂] + t.positions₁[i₁] -function pairposition(t::FusionTreePairs, f::FusionTreePair) +pairposition(t::FusionTreePairs, f::FusionTreePair) = pairposition(t, pairtoken(t, f)) + +""" + pairtoken(t::FusionTreePairs, i::Int) -> Tuple{Int, Int} + pairtoken(t::FusionTreePairs, (f₁, f₂)) -> Tuple{Int, Int} + +The token of a fusion tree pair of `t`, from its position or from the pair itself, which must be +present. +""" +pairtoken(t::FusionTreePairs, i::Int) = _pairtoken(t.ranges₁, t.ranges₂, t.offsets, i) +function pairtoken(t::FusionTreePairs, f::FusionTreePair) found, token = gettoken(t, f) found || throw(KeyError(f)) - return pairposition(t, token) + return token end -# the token of the pair at position `i` -function pairtoken(t::FusionTreePairs, i::Int) - b = searchsortedlast(t.offsets, i - 1) - r₁, r₂ = t.ranges₁[b], t.ranges₂[b] - j₂, j₁ = divrem(i - 1 - t.offsets[b], length(r₁)) +function _pairtoken(ranges₁, ranges₂, offsets, i::Int) + b = searchsortedlast(offsets, i - 1) + r₁, r₂ = ranges₁[b], ranges₂[b] + j₂, j₁ = divrem(i - 1 - offsets[b], length(r₁)) return (first(r₁) + j₁, first(r₂) + j₂) end @@ -136,17 +145,18 @@ function Base.iterate(t::FusionTreePairs, state...) end # values for every fusion tree pair, stored by position -struct FusionTreePairDict{K, V, T <: FusionTreePairs} <: AbstractDictionary{K, V} +struct FusionTreePairDict{K, V, T <: FusionTreePairs, A <: AbstractVector{V}} <: AbstractDictionary{K, V} keys::T - values::Vector{V} + values::A end -FusionTreePairDict(keys::T, values::Vector{V}) where {T <: FusionTreePairs, V} = - FusionTreePairDict{eltype(T), V, T}(keys, values) +FusionTreePairDict(keys::T, values::AbstractVector{V}) where {T <: FusionTreePairs, V} = + FusionTreePairDict{eltype(T), V, T, typeof(values)}(keys, values) Base.keys(d::FusionTreePairDict) = d.keys Dictionaries.istokenizable(::FusionTreePairDict) = true Dictionaries.istokenassigned(::FusionTreePairDict, _) = true Dictionaries.gettokenvalue(d::FusionTreePairDict, i::Int) = d.values[i] -Dictionaries.gettokenvalue(d::FusionTreePairDict, token::Tuple{Int, Int}) = d.values[pairposition(d.keys, token)] +Dictionaries.gettokenvalue(d::FusionTreePairDict, token::Tuple{Int, Int}) = _tokenvalue(d.values, d.keys, token) +_tokenvalue(values::AbstractVector, keys, token) = values[pairposition(keys, token)] MemoizationKit.cachesize(s::SectorStructure) = 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 # DegeneracyStructure: degeneracy-dependent characterization of HomSpaces # ----------------------------------------------------------------------- +""" + SubblockStructure{N} <: AbstractVector{StridedStructure{N}} + +The [`StridedStructure`](@ref) `(sizes, strides, offset)` of the subblock of every fusion tree pair +of a `HomSpace`, in the canonical order of [`fusiontrees`](@ref). The subblock of `(f₁, f₂)` holds +the rows of `f₁` and the columns of `f₂` within the block of their coupled sector, such that only +the structures of the splitting and fusion trees are stored, and that of a pair is computed when it +is accessed. Besides its position, a pair can also be indexed with its token `(i₁, i₂)`. +""" +struct SubblockStructure{N} <: AbstractVector{StridedStructure{N}} + # the codomain legs of every splitting tree, padded with zeros for the domain legs + trees₁::Vector{StridedStructure{N}} + # the domain legs of every fusion tree, padded with zeros for the codomain legs + trees₂::Vector{StridedStructure{N}} + # shared with the `FusionTreePairs`, to convert between positions and tokens + ranges₁::Vector{UnitRange{Int}} + ranges₂::Vector{UnitRange{Int}} + positions₁::Vector{Int} + positions₂::Vector{Int} + offsets::Vector{Int} +end +SubblockStructure(trees₁, trees₂, t::FusionTreePairs) = + SubblockStructure(trees₁, trees₂, t.ranges₁, t.ranges₂, t.positions₁, t.positions₂, t.offsets) + +# the token `(i₁, i₂)` of a fusion tree pair, which also addresses its subblock +const SubblockToken = Tuple{Int, Int} + +Base.size(s::SubblockStructure) = (last(s.offsets),) +Base.IndexStyle(::Type{<:SubblockStructure}) = IndexLinear() +Base.@propagate_inbounds Base.getindex(s::SubblockStructure, i::Int) = + s[_pairtoken(s.ranges₁, s.ranges₂, s.offsets, i)] +Base.@propagate_inbounds function Base.getindex(s::SubblockStructure, (i₁, i₂)::SubblockToken) + sz₁, str₁, offset₁ = s.trees₁[i₁] + sz₂, str₂, offset₂ = s.trees₂[i₂] + return (sz₁ .+ sz₂, str₁ .+ str₂, offset₁ + offset₂) +end +_tokenvalue(values::SubblockStructure, keys, token) = values[token] +pairposition(s::SubblockStructure, (i₁, i₂)::SubblockToken) = @inbounds s.positions₂[i₂] + s.positions₁[i₁] + +# the arrays shared with the `FusionTreePairs` are accounted for in the `sectorstructure` cache +_cache_payload_size(s::SubblockStructure) = sizeof(s) + sizeof(s.trees₁) + sizeof(s.trees₂) + """ DegeneracyStructure{N} @@ -191,18 +243,19 @@ strides that depend on the degeneracy (multiplicity) dimensions. Specific to a g - `totaldim`: total number of elements in the flat data vector. - `blockstructure`: `Vector` of `((d₁, d₂), range)` values, one per coupled sector, in the same order as [`sectorstructure`](@ref)`.blocksectors`. -- `subblockstructure`: `Vector` of [`StridedStructure`](@ref) `(sizes, strides, offset)` - values, one per fusion tree pair, in the same order as [`sectorstructure`](@ref)`.fusiontrees`. +- `subblockstructure`: [`SubblockStructure`](@ref) of the `(sizes, strides, offset)` of every + fusion tree pair, in the same order as [`sectorstructure`](@ref)`.fusiontrees`. See also [`degeneracystructure`](@ref), [`SectorStructure`](@ref). """ struct DegeneracyStructure{N} totaldim::Int blockstructure::Vector{Tuple{Tuple{Int, Int}, UnitRange{Int}}} - subblockstructure::Vector{StridedStructure{N}} + subblockstructure::SubblockStructure{N} end -MemoizationKit.cachesize(s::DegeneracyStructure) = sizeof(s) + sizeof(s.blockstructure) + sizeof(s.subblockstructure) +MemoizationKit.cachesize(s::DegeneracyStructure) = + sizeof(s) + sizeof(s.blockstructure) + _cache_payload_size(s.subblockstructure) function degeneracystructuretype(W::HomSpace) N = length(codomain(W)) + length(domain(W)) @@ -219,57 +272,42 @@ since degeneracy dimensions affect the block sizes and offsets). See also [`sectorstructure`](@ref), [`blockstructure`](@ref), [`subblockstructure`](@ref). """ degeneracystructure(::HomSpace) @cached function degeneracystructure(W::HomSpace)::degeneracystructuretype(W) - codom = codomain(W) - dom = domain(W) - N = length(codom) + length(dom) + codom, dom = codomain(W), domain(W) + N₁, N₂ = length(codom), length(dom) + zeros₁, zeros₂ = ntuple(Returns(0), N₁), ntuple(Returns(0), N₂) ss = sectorstructure(W) ts = ss.fusiontrees - structurevalues = sizehint!(Vector{StridedStructure{N}}(), length(ts)) + trees₁ = Vector{StridedStructure{N₁ + N₂}}(undef, length(ts.trees₁)) + trees₂ = Vector{StridedStructure{N₁ + N₂}}(undef, length(ts.trees₂)) blockvalues = Vector{Tuple{Tuple{Int, Int}, UnitRange{Int}}}(undef, length(ss.blocksectors)) - # the subblocks of every coupled sector, from the degeneracies of the trees of both sides; - # filling a reused buffer is noticeably faster than `map` for the subblock loop below - splittingstructure = Vector{NTuple{numout(W), Int}}() + # every block is column major, with the rows of its splitting trees and the columns of its + # fusion trees, both in order; the legs of a tree are column major within its rows or columns blockoffset = 0 for (block_index, (r₁, r₂)) in enumerate(zip(ts.ranges₁, ts.ranges₂)) - empty!(splittingstructure) blockdim₁ = 0 for i in r₁ d₁s = dims(codom, gettokenvalue(ts.trees₁, i).uncoupled) + @assert !any(==(0), d₁s) + trees₁[i] = ((d₁s..., zeros₂...), (_colmajorstrides(d₁s, 1)..., zeros₂...), blockdim₁) blockdim₁ += prod(d₁s) - push!(splittingstructure, d₁s) end - strides = (1, blockdim₁) blockdim₂ = 0 for i in r₂ d₂s = dims(dom, gettokenvalue(ts.trees₂, i).uncoupled) - d₂ = prod(d₂s) - offset₁ = 0 - for d₁s in splittingstructure - d₁ = prod(d₁s) - totaloffset = blockoffset + blockdim₂ * blockdim₁ + offset₁ - subsz = (d₁s..., d₂s...) - @assert !any(==(0), subsz) - substr = _subblock_strides(subsz, (d₁, d₂), strides) - push!(structurevalues, (subsz, substr, totaloffset)) - offset₁ += d₁ - end - blockdim₂ += d₂ + @assert !any(==(0), d₂s) + trees₂[i] = ((zeros₁..., d₂s...), (zeros₁..., _colmajorstrides(d₂s, blockdim₁)...), blockoffset + blockdim₂ * blockdim₁) + blockdim₂ += prod(d₂s) end blockrange = (blockoffset + 1):(blockoffset + blockdim₁ * blockdim₂) blockvalues[block_index] = ((blockdim₁, blockdim₂), blockrange) blockoffset = last(blockrange) end - return DegeneracyStructure(blockoffset, blockvalues, structurevalues) -end - -function _subblock_strides(subsz, sz, str) - sz_simplify = Strided.StridedViews._simplifydims(sz, str) - strides = Strided.StridedViews._computereshapestrides(subsz, sz_simplify...) - isnothing(strides) && - throw(ArgumentError("unexpected error in computing subblock strides")) - return strides + subblockvalues = SubblockStructure(trees₁, trees₂, ts) + return DegeneracyStructure(blockoffset, blockvalues, subblockvalues) end +# the strides of legs with sizes `ds` that are column major, starting from `stride` +_colmajorstrides(ds::Tuple, stride::Int) = Base.front(cumprod((stride, ds...))) diff --git a/src/tensors/blockiterators.jl b/src/tensors/blockiterators.jl index 88583e1bd..c7b2a4c5f 100644 --- a/src/tensors/blockiterators.jl +++ b/src/tensors/blockiterators.jl @@ -108,8 +108,8 @@ end # Positional subblock collections # ------------------------------- -# These address subblocks by their position in the canonical order of `fusiontrees(space(t))`, -# hoisting the space-level lookups out of the individual accesses. +# These address subblocks by their position in the canonical order of `fusiontrees(space(t))`, or +# by the token of their fusion tree pair, hoisting the space-level lookups out of the accesses. """ struct SubblockIterator{T <: AbstractTensorMap, S} @@ -144,6 +144,8 @@ Base.isdone(iter::SubblockIterator, i::Int = 1) = i > length(iter) @propagate_inbounds Base.getindex(iter::SubblockIterator, i::Int) = subblock(iter.t, gettokenvalue(keys(iter.structure), i)) @propagate_inbounds Base.getindex(iter::SubblockIterator, f::FusionTreePair) = subblock(iter.t, f) +@propagate_inbounds Base.getindex(iter::SubblockIterator, token::SubblockToken) = + subblock(iter.t, gettokenvalue(keys(iter.structure), token)) function Base.iterate(iter::SubblockIterator, i::Int = 1) 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 """ struct StridedSubblocks{A <: DenseVector, N} data::A - structure::Vector{StridedStructure{N}} + structure::SubblockStructure{N} # store the data as `StridedView` parents it, so that `A` is also the parent type of the views - function StridedSubblocks(data::DenseVector, structure::Vector{StridedStructure{N}}) where {N} + function StridedSubblocks(data::DenseVector, structure::SubblockStructure{N}) where {N} data′ = parent(StridedView(data)) return new{typeof(data′), N}(data′, structure) end @@ -217,7 +219,8 @@ Base.firstindex(s::StridedSubblocks) = 1 Base.lastindex(s::StridedSubblocks) = length(s) Base.eltype(::Type{StridedSubblocks{A, N}}) where {A, N} = StridedView{eltype(A), N, A, typeof(identity)} -Base.@propagate_inbounds function Base.getindex(s::StridedSubblocks, i::Int) +# by position, or by the token of the fusion tree pair +Base.@propagate_inbounds function Base.getindex(s::StridedSubblocks, i::Union{Int, SubblockToken}) sz, str, offset = s.structure[i] return StridedView(s.data, sz, str, offset) end diff --git a/src/tensors/indexmanipulations.jl b/src/tensors/indexmanipulations.jl index 78a7d82fe..9bfcfe6f4 100644 --- a/src/tensors/indexmanipulations.jl +++ b/src/tensors/indexmanipulations.jl @@ -726,15 +726,17 @@ function add_transform_kernel!( return nothing end -# `U` is either a scalar coefficient with integer positions (unique fusion), or a recoupling -# matrix with vectors of positions (generic). +# `U` is either a scalar coefficient with single tokens (unique fusion), or a recoupling matrix +# with vectors of tokens (generic). +_onlytoken(token::SubblockToken) = token +_onlytoken(tokens::AbstractVector{SubblockToken}) = only(tokens) function _add_transform_block!( dst::TransformSubblocks, src::TransformSubblocks, p, conjsrc::Bool, U, inds_dst, inds_src, buffer, α, β, backend, allocator ) if length(U) == 1 # single tree: no matmul needed @timeit_debug GLOBAL_TIMER "dense: tensoradd" @inbounds TO.tensoradd!( - dst[only(inds_dst)], src[only(inds_src)], p, conjsrc, α * only(U), β, backend, allocator + dst[_onlytoken(inds_dst)], src[_onlytoken(inds_src)], p, conjsrc, α * only(U), β, backend, allocator ) else # Multi-tree block: pack → recoupling matmul → unpack. rows, cols = size(U) diff --git a/src/tensors/tensor.jl b/src/tensors/tensor.jl index d094c40c9..bd5bd7f68 100644 --- a/src/tensors/tensor.jl +++ b/src/tensors/tensor.jl @@ -497,7 +497,7 @@ end # Getting and setting the data at the subblock level # -------------------------------------------------- StridedSubblocks(t::TensorMap) = StridedSubblocks(t.data, degeneracystructure(space(t)).subblockstructure) -StridedSubblocks(t::TensorMap, structure::Vector{<:StridedStructure}) = StridedSubblocks(t.data, structure) +StridedSubblocks(t::TensorMap, structure::SubblockStructure) = StridedSubblocks(t.data, structure) # the subblocks of a `TensorMap` are strided views into its flat data, which the subblock # structure of its space describes directly @@ -513,6 +513,10 @@ SubblockIterator(t::TensorMap) = SubblockIterator(t, subblockstructure(space(t)) @inbounds sz, str, offset = gettokenvalue(iter.structure, i) return StridedView(iter.t.data, sz, str, offset) end +@propagate_inbounds function Base.getindex(iter::SubblockIterator{<:TensorMap}, token::SubblockToken) + sz, str, offset = gettokenvalue(iter.structure, token) + return StridedView(iter.t.data, sz, str, offset) +end @propagate_inbounds function Base.getindex(iter::SubblockIterator{<:TensorMap}, f::FusionTreePair) found, token = gettoken(iter.structure, f) @boundscheck found || _throw_subblock_missing(f) diff --git a/src/tensors/treetransformers.jl b/src/tensors/treetransformers.jl index 224de14d7..be98b474d 100644 --- a/src/tensors/treetransformers.jl +++ b/src/tensors/treetransformers.jl @@ -3,9 +3,9 @@ Supertype for structures containing the data for a tree transformation. -The transformers only store how subblocks map onto each other in terms of their positions in -[`StridedSubblocks`](@ref) (the canonical order of [`fusiontrees`](@ref)), together with the recoupling -coefficients, and are therefore independent of the sectortype once constructed. The +The transformers only store how subblocks map onto each other in terms of the tokens `(i₁, i₂)` of +their fusion tree pairs in [`fusiontrees`](@ref), which index the [`StridedSubblocks`](@ref), together +with the recoupling coefficients, and are therefore independent of the sectortype once constructed. The transformation is that of `permutedims(conjsrc ? conj(tsrc) : tsrc, p)` where `p` indexes the legs of `tsrc` itself; when `conjsrc` is `true` the fusion trees that are transformed are those of `adjoint(space(tsrc))`, which read the subblocks of `tsrc` with the tree pair swapped. @@ -33,8 +33,8 @@ function recoupling_scalartype(::Type{A}, ::Type{Tₛ}) where {A, Tₛ <: Number return Tₛ <: Real ? real(T) : complex(T) end -# (coefficient, destination position, source position) -const UniqueTransformerData{T} = Tuple{T, Int, Int} +# (coefficient, destination token, source token) +const UniqueTransformerData{T} = Tuple{T, SubblockToken, SubblockToken} """ UniqueTreeTransformer{T, N} <: TreeTransformer @@ -46,12 +46,12 @@ structures of the destination and source spaces are kept alongside, such that th """ struct UniqueTreeTransformer{T, N} <: TreeTransformer data::Vector{UniqueTransformerData{T}} - structure_dst::Vector{StridedStructure{N}} - structure_src::Vector{StridedStructure{N}} + structure_dst::SubblockStructure{N} + structure_src::SubblockStructure{N} end -# (recoupling matrix, destination positions, source positions) -const GenericTransformerData{T} = Tuple{Matrix{T}, Vector{Int}, Vector{Int}} +# (recoupling matrix, destination tokens, source tokens) +const GenericTransformerData{T} = Tuple{Matrix{T}, Vector{SubblockToken}, Vector{SubblockToken}} """ GenericTreeTransformer{T, N} <: TreeTransformer @@ -64,14 +64,14 @@ The subblock structures of the destination and source spaces are kept alongside, """ struct GenericTreeTransformer{T, N} <: TreeTransformer data::Vector{GenericTransformerData{T}} - structure_dst::Vector{StridedStructure{N}} - structure_src::Vector{StridedStructure{N}} + structure_dst::SubblockStructure{N} + structure_src::SubblockStructure{N} end # Both structure arrays are retained by the transformer, even when another cache also # holds them. Within an entry, identical source/destination arrays are counted only once. -_cache_structure_size(t) = sizeof(t.structure_src) + - (t.structure_src === t.structure_dst ? 0 : sizeof(t.structure_dst)) +_cache_structure_size(t) = _cache_payload_size(t.structure_src) + + (t.structure_src === t.structure_dst ? 0 : _cache_payload_size(t.structure_dst)) MemoizationKit.cachesize(t::UniqueTreeTransformer) = sizeof(t) + _cache_payload_size(t.data) + _cache_structure_size(t) @@ -95,10 +95,10 @@ function UniqueTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::Ho T = recoupling_scalartype(A, sectorscalartype(sectortype(Vdst))) data = Vector{UniqueTransformerData{T}}(undef, length(src_trees)) - @timeit_debug GLOBAL_TIMER "symmetry: tree transform" for (isrc, (f₁, f₂)) in enumerate(src_trees) + @timeit_debug GLOBAL_TIMER "symmetry: tree transform" for (k, isrc) in enumerate(Dictionaries.tokens(src_trees)) + f₁, f₂ = gettokenvalue(src_trees, isrc) f_dst, coeff = transform(conjsrc ? (f₂, f₁) : (f₁, f₂)) - idst = pairposition(dst_trees, f_dst) - data[isrc] = (convert(T, coeff), idst, isrc) + data[k] = (convert(T, coeff), pairtoken(dst_trees, f_dst), isrc) end structure_dst = degeneracystructure(Vdst).subblockstructure @@ -132,15 +132,9 @@ function GenericTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::H fs_src = fblocks[i] fs_dst, U = transform(fs_src) @timeit_debug GLOBAL_TIMER "bookkeeping: subblock positions" begin - # the position of a fusion tree pair is that of its subblock - inds_src = map(fusiontrees(fs_src)) do (f₁, f₂) - isrc = pairposition(src_trees, conjsrc ? (f₂, f₁) : (f₁, f₂)) - return isrc - end - inds_dst = map(fusiontrees(fs_dst)) do f - idst = pairposition(dst_trees, f) - return idst - end + # the token of a fusion tree pair also addresses its subblock + inds_src = map(((f₁, f₂),) -> pairtoken(src_trees, conjsrc ? (f₂, f₁) : (f₁, f₂)), fusiontrees(fs_src)) + inds_dst = map(f -> pairtoken(dst_trees, f), fusiontrees(fs_dst)) end data[i] = (convert(Matrix{T}, U), inds_dst, inds_src) # cost model: L input blocks each going to L output blocks of a given length @@ -234,8 +228,8 @@ created without further lookups. """ struct TraceTransformer{T, N₁, N₂} data::Vector{GenericTransformerData{T}} - structure_dst::Vector{StridedStructure{N₁}} - structure_src::Vector{StridedStructure{N₂}} + structure_dst::SubblockStructure{N₁} + structure_src::SubblockStructure{N₂} end MemoizationKit.cachesize(t::TraceTransformer) = _cache_generic_size(t) @@ -249,42 +243,40 @@ function TraceTransformer(::Type{A}, Vdst::HomSpace, Vsrc::HomSpace, p::Index2Tu src_trees, dst_trees = fusiontrees(Vsrc), fusiontrees(Vdst) T = recoupling_scalartype(A, sectorscalartype(sectortype(Vdst))) - # destination positions => (columns of the recoupling matrix, source positions) - groups = Dict{Vector{Int}, Tuple{Vector{Vector{T}}, Vector{Int}}}() + # destination tokens => (columns of the recoupling matrix, source tokens) + groups = Dict{Vector{SubblockToken}, Tuple{Vector{Vector{T}}, Vector{SubblockToken}}}() function addcolumn!(inds_dst, u, isrc) any(!iszero, u) || return nothing - us, inds_src = get!(() -> (Vector{T}[], Int[]), groups, inds_dst) + us, inds_src = get!(() -> (Vector{T}[], SubblockToken[]), groups, inds_dst) push!(us, u) push!(inds_src, isrc) return nothing end @timeit_debug GLOBAL_TIMER "symmetry: trace coefficients" if FusionStyle(sectortype(Vdst)) isa UniqueFusion - for (isrc, f) in enumerate(src_trees) + for isrc in Dictionaries.tokens(src_trees) + f = gettokenvalue(src_trees, isrc) trace_sectors_match(f, q) || continue f′, coeff = planar_trace(f, p, q) - idst = pairposition(dst_trees, f′) - addcolumn!([idst], [convert(T, coeff)], isrc) + addcolumn!([pairtoken(dst_trees, f′)], [convert(T, coeff)], isrc) end else for fs_src in fusionblocks(Vsrc) trace_sectors_match(fs_src, q) || continue fs_dst, U = planar_trace(fs_src, p, q) - inds_dst = map(fusiontrees(fs_dst)) do f - idst = pairposition(dst_trees, f) - return idst - end + inds_dst = map(f -> pairtoken(dst_trees, f), fusiontrees(fs_dst)) for (i, f) in enumerate(fusiontrees(fs_src)) - isrc = pairposition(src_trees, f) - addcolumn!(inds_dst, convert(Vector{T}, U[:, i]), isrc) + addcolumn!(inds_dst, convert(Vector{T}, U[:, i]), pairtoken(src_trees, f)) end end end data = GenericTransformerData{T}[(reduce(hcat, us), inds_dst, inds_src) for (inds_dst, (us, inds_src)) in groups] # destination subblocks without contributions are only scaled covered = falses(length(dst_trees)) - foreach(inds_dst -> covered[inds_dst] .= true, keys(groups)) - for idst in findall(!, covered) - push!(data, (zeros(T, 1, 0), [idst], Int[])) + for inds_dst in keys(groups), idst in inds_dst + covered[pairposition(dst_trees, idst)] = true + end + for i in findall(!, covered) + push!(data, (zeros(T, 1, 0), [pairtoken(dst_trees, i)], SubblockToken[])) end structure_dst = degeneracystructure(Vdst).subblockstructure diff --git a/test/other/caches.jl b/test/other/caches.jl index ec750d48e..99f98b8c6 100644 --- a/test/other/caches.jl +++ b/test/other/caches.jl @@ -60,10 +60,12 @@ end # An empty transformer still costs space, and arbitrary-precision coefficients # include their referenced storage instead of just the array's pointer slots. - strides = TensorKit.StridedStructure{2}[] - empty_transformer = TensorKit.UniqueTreeTransformer(Tuple{Float64, Int, Int}[], strides, strides) + V = SU2Space(0 => 1) + strides = degeneracystructure(V ← V).subblockstructure + token = only(TensorKit.Dictionaries.tokens(fusiontrees(V ← V))) + empty_transformer = TensorKit.UniqueTreeTransformer(Tuple{Float64, TensorKit.SubblockToken, TensorKit.SubblockToken}[], strides, strides) @test MemoizationKit.cachesize(empty_transformer) > 0 - big_transformer = TensorKit.UniqueTreeTransformer([(BigFloat(1), 1, 1)], strides, strides) + big_transformer = TensorKit.UniqueTreeTransformer([(BigFloat(1), token, token)], strides, strides) @test MemoizationKit.cachesize(big_transformer) >= Base.summarysize(big_transformer.data) end From 6baaf9ee4c444cefc8dee049ccb98f32d5ad4898 Mon Sep 17 00:00:00 2001 From: leburgel Date: Fri, 20 Nov 2026 11:21:38 +0100 Subject: [PATCH 6/6] Keep the subblock tokens of all blocks of a transformer in one vector of Int32 pairs Co-Authored-By: Claude Opus 5.5 --- docs/src/Changelog.md | 1 + src/tensors/treetransformers.jl | 62 ++++++++++++++++++++++++++------- 2 files changed, 51 insertions(+), 12 deletions(-) diff --git a/docs/src/Changelog.md b/docs/src/Changelog.md index 51b40c3b5..16ef13a7f 100644 --- a/docs/src/Changelog.md +++ b/docs/src/Changelog.md @@ -43,6 +43,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec - `foreachblock` with several tensors is type stable, which removes the dynamic dispatch on every call to it and to the factorizations that go through it - `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)) - `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)) +- Tree and trace transformers for sectors with multiple fusion channels keep the subblock tokens of all their blocks in one vector of `Int32` pairs, instead of two `Vector{Tuple{Int, Int}}` per block ## [0.17.3](https://github.com/QuantumKitHub/TensorKit.jl/compare/v0.17.2...v0.17.3) - 2026-10-30 diff --git a/src/tensors/treetransformers.jl b/src/tensors/treetransformers.jl index be98b474d..42101e840 100644 --- a/src/tensors/treetransformers.jl +++ b/src/tensors/treetransformers.jl @@ -50,8 +50,43 @@ struct UniqueTreeTransformer{T, N} <: TreeTransformer structure_src::SubblockStructure{N} end +""" + SubblockIndices <: AbstractVector{SubblockToken} + +The subblock tokens of one block of a transformer, as a range of the `Int32` pairs that hold those +of all its blocks, such that a transformer keeps one vector of tokens instead of two per block. +""" +struct SubblockIndices <: AbstractVector{SubblockToken} + parent::Vector{NTuple{2, Int32}} + offset::Int32 + length::Int32 +end +Base.size(s::SubblockIndices) = (Int(s.length),) +Base.@propagate_inbounds function Base.getindex(s::SubblockIndices, i::Int) + @boundscheck checkbounds(s, i) + i₁, i₂ = @inbounds s.parent[s.offset + i] + return (Int(i₁), Int(i₂)) +end + # (recoupling matrix, destination tokens, source tokens) -const GenericTransformerData{T} = Tuple{Matrix{T}, Vector{SubblockToken}, Vector{SubblockToken}} +const GenericTransformerData{T} = Tuple{Matrix{T}, SubblockIndices, SubblockIndices} + +# the blocks `(U, inds_dst, inds_src)` with their tokens moved into one shared vector +function _pack_tokens(::Type{T}, blocks) where {T} + tokens = Vector{NTuple{2, Int32}}(undef, sum(((_, d, s),) -> length(d) + length(s), blocks; init = 0)) + data = Vector{GenericTransformerData{T}}(undef, length(blocks)) + k = 0 + for (n, (U, inds_dst, inds_src)) in enumerate(blocks) + tokens[(k + 1):(k + length(inds_dst))] .= inds_dst + dst = SubblockIndices(tokens, k, length(inds_dst)) + k += length(inds_dst) + tokens[(k + 1):(k + length(inds_src))] .= inds_src + src = SubblockIndices(tokens, k, length(inds_src)) + k += length(inds_src) + data[n] = (U, dst, src) + end + return data +end """ GenericTreeTransformer{T, N} <: TreeTransformer @@ -78,10 +113,11 @@ MemoizationKit.cachesize(t::UniqueTreeTransformer) = sizeof(t) + _cache_payload_ MemoizationKit.cachesize(t::GenericTreeTransformer) = _cache_generic_size(t) function _cache_generic_size(t) - bytes = sizeof(t) + sizeof(t.data) + _cache_structure_size(t) - for (U, inds_dst, inds_src) in t.data - bytes += _cache_payload_size(U) + sizeof(inds_src) + - (inds_src === inds_dst ? 0 : sizeof(inds_dst)) + # the tokens of all blocks share one vector + bytes = sizeof(t) + sizeof(t.data) + _cache_structure_size(t) + + (isempty(t.data) ? 0 : sizeof(t.data[1][2].parent)) + for (U, _, _) in t.data + bytes += _cache_payload_size(U) end return bytes end @@ -123,7 +159,7 @@ function GenericTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::H fblocks = @timeit_debug GLOBAL_TIMER "bookkeeping: fusionblocks" fusionblocks(Vsrc′) nblocks = length(fblocks) - data = Vector{GenericTransformerData{T}}(undef, nblocks) + blocks = Vector{Tuple{Matrix{T}, Vector{SubblockToken}, Vector{SubblockToken}}}(undef, nblocks) weights = Vector{Int}(undef, nblocks) nthreads = get_num_manipulation_threads() @@ -136,7 +172,7 @@ function GenericTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::H inds_src = map(((f₁, f₂),) -> pairtoken(src_trees, conjsrc ? (f₂, f₁) : (f₁, f₂)), fusiontrees(fs_src)) inds_dst = map(f -> pairtoken(dst_trees, f), fusiontrees(fs_dst)) end - data[i] = (convert(Matrix{T}, U), inds_dst, inds_src) + blocks[i] = (convert(Matrix{T}, U), inds_dst, inds_src) # cost model: L input blocks each going to L output blocks of a given length weights[i] = length(U) * prod(structure_dst[first(inds_dst)][1]) @@ -148,7 +184,8 @@ function GenericTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::H end # sort by (approximate) weight to facilitate multi-threading strategies - @timeit_debug GLOBAL_TIMER "bookkeeping: sort" Base.permute!(data, sortperm(weights; rev = true)) + @timeit_debug GLOBAL_TIMER "bookkeeping: sort" Base.permute!(blocks, sortperm(weights; rev = true)) + data = _pack_tokens(T, blocks) transformer = GenericTreeTransformer{T, numind(Vdst)}(data, structure_dst, structure_src) Δt = Base.time() - t₀ @@ -269,23 +306,24 @@ function TraceTransformer(::Type{A}, Vdst::HomSpace, Vsrc::HomSpace, p::Index2Tu end end end - data = GenericTransformerData{T}[(reduce(hcat, us), inds_dst, inds_src) for (inds_dst, (us, inds_src)) in groups] + blocks = Tuple{Matrix{T}, Vector{SubblockToken}, Vector{SubblockToken}}[(reduce(hcat, us), inds_dst, inds_src) for (inds_dst, (us, inds_src)) in groups] # destination subblocks without contributions are only scaled covered = falses(length(dst_trees)) for inds_dst in keys(groups), idst in inds_dst covered[pairposition(dst_trees, idst)] = true end for i in findall(!, covered) - push!(data, (zeros(T, 1, 0), [pairtoken(dst_trees, i)], SubblockToken[])) + push!(blocks, (zeros(T, 1, 0), [pairtoken(dst_trees, i)], SubblockToken[])) end structure_dst = degeneracystructure(Vdst).subblockstructure structure_src = degeneracystructure(Vsrc).subblockstructure # sort by (approximate) weight to facilitate multi-threading strategies - weights = map(data) do (U, inds_dst, _) + weights = map(blocks) do (U, inds_dst, _) return length(U) * prod(structure_dst[first(inds_dst)][1]) end - Base.permute!(data, sortperm(weights; rev = true)) + Base.permute!(blocks, sortperm(weights; rev = true)) + data = _pack_tokens(T, blocks) transformer = TraceTransformer(data, structure_dst, structure_src) Δt = Base.time() - t₀