diff --git a/docs/src/Changelog.md b/docs/src/Changelog.md index 0216f9b33..3148dae0c 100644 --- a/docs/src/Changelog.md +++ b/docs/src/Changelog.md @@ -42,6 +42,8 @@ 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 - `taskforeach` with a single worker is a plain loop without an atomic counter, which lowers the cost per subblock of single-threaded index manipulations and planar traces +- Tree transformers for sectors with multiple fusion channels share equal recoupling matrices, which only depend on the sectors, instead of storing one copy per transformer +- The cached braids and transposes of fusion tree blocks keep their recoupling matrices in the scalar type of the tree transformers that use them, instead of a copy in that type for every transformer ## [0.17.3](https://github.com/QuantumKitHub/TensorKit.jl/compare/v0.17.2...v0.17.3) - 2026-10-30 diff --git a/ext/TensorKitEnzymeExt/utility.jl b/ext/TensorKitEnzymeExt/utility.jl index e76eafff1..4eac157db 100644 --- a/ext/TensorKitEnzymeExt/utility.jl +++ b/ext/TensorKitEnzymeExt/utility.jl @@ -142,9 +142,9 @@ end @inline EnzymeRules.inactive(::typeof(TensorKit.fusiontrees), ::Any) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.fusiontrees), ::Any, ::Any) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.fusiontrees), ::Any, ::Any, ::Any) = nothing -@inline EnzymeRules.inactive(::typeof(TensorKit.fusiontreebraid), ::Any, ::Any, ::Any) = nothing +@inline EnzymeRules.inactive(::typeof(TensorKit.fusiontreebraid), ::Any, ::Any, ::Any, ::Any) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.artin_braid), ::Any, ::Any) = nothing -@inline EnzymeRules.inactive(::typeof(TensorKit.fusiontreetranspose), ::Any, ::Any) = nothing +@inline EnzymeRules.inactive(::typeof(TensorKit.fusiontreetranspose), ::Any, ::Any, ::Any) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.product_transform), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.treetransposer), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.treebraider), ::Any...) = nothing diff --git a/src/fusiontrees/braiding_manipulations.jl b/src/fusiontrees/braiding_manipulations.jl index e732ca199..9152319ff 100644 --- a/src/fusiontrees/braiding_manipulations.jl +++ b/src/fusiontrees/braiding_manipulations.jl @@ -291,28 +291,32 @@ respectively, which determines how indices braid. In particular, if `i` and `j` levels[j]`. This does not allow to encode the most general braid, but a general braid can be obtained by combining such operations. """ -function braid(src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple, levels::Index2Tuple) +braid(src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple, levels::Index2Tuple) = + _braid(sectorscalartype(sectortype(src)), src, p, levels) + +# the braid with the recoupling matrix of a block in scalar type `T`, which is cached as such +function _braid(::Type{T}, src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple, levels::Index2Tuple) where {T} @assert numind(src) == length(p[1]) + length(p[2]) @assert numout(src) == length(levels[1]) && numin(src) == length(levels[2]) @assert TupleTools.isperm((p[1]..., p[2]...)) - return fusiontreebraid(src, p, levels) + return fusiontreebraid(T, src, p, levels) end -function braid(src::ProductSectorBlock, p::Index2Tuple, levels::Index2Tuple) - isempty(src) && return fusiontreebraid(src, p, levels) +function _braid(::Type{T}, src::ProductSectorBlock, p::Index2Tuple, levels::Index2Tuple) where {T} + isempty(src) && return fusiontreebraid(T, src, p, levels) # the return type is asserted since inference gives up on the recursion on older Julia versions - return product_transform(sectorscalartype(sectortype(src)), src) do x + dst, U = product_transform(T, src) do x return braid(x, p, levels) - end::fusiontreebraidtype(src, p) + end::fusiontreebraidtype(T, src, p) + return dst => recouplingmatrix(U) end # Braiding can promote real fusion coefficients to complex values. Keep the result # type explicit so all braid paths remain inferred, including anyonic sectors. Base.@assume_effects :foldable function fusiontreebraidtype( - src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, ::Index2Tuple{N₁, N₂} - ) where {I, N₁, N₂} - T = sectorscalartype(I) + ::Type{T}, src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, ::Index2Tuple{N₁, N₂} + ) where {T, I, N₁, N₂} if src isa FusionTreePair - return Pair{fusiontreetype(I, N₁, N₂), T} + return Pair{fusiontreetype(I, N₁, N₂), sectorscalartype(I)} else F = Tuple{fusiontreetype(I, N₁), fusiontreetype(I, N₂)} return Pair{FusionTreeBlock{I, N₁, N₂, F}, Matrix{T}} @@ -320,15 +324,15 @@ Base.@assume_effects :foldable function fusiontreebraidtype( end @cached function fusiontreebraid( - src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, + ::Type{T}, src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, p::Index2Tuple{N₁, N₂}, levels::Index2Tuple - )::fusiontreebraidtype(src, p) where {I, N₁, N₂} + )::fusiontreebraidtype(T, src, p) where {T, I, N₁, N₂} if src isa FusionTreePair return _braid_single(src, p, levels) else if length(src) == 1 # then so is every intermediate block: the braid is a product of scalars f′, coeff = _braid_single(only(fusiontrees(src)), p, levels) - return FusionTreeBlock([f′]) => fill(coeff, 1, 1) + return FusionTreeBlock([f′]) => recouplingmatrix(fill(convert(T, coeff), 1, 1)) end p₁, p₂ = p @@ -336,10 +340,10 @@ end p′ = linearizepermutation(p₁, p₂, numout(src), numin(src)) levels = (l₁..., reverse(l₂)...) - T = sectorscalartype(I) + Tₛ = sectorscalartype(I) dst, U = repartition(src, Val(numind(src))) - # the bends have `fusionscalartype(I)`, which can be narrower than `T` - U = convert(Matrix{T}, U) + # the bends have `fusionscalartype(I)`, which can be narrower than `Tₛ` + U = convert(Matrix{Tₛ}, U) # the swaps keep the size of the block, so that the matrices of the previous step are recycled U_tmp = similar(U) @@ -355,9 +359,9 @@ end levels = TupleTools.setindex(levels, l, s + 1) end - N₂ == 0 && return dst => U + N₂ == 0 && return dst => recouplingmatrix(convert(Matrix{T}, U)) dst, U_bend = repartition(dst::FusionTreeBlock{I}, Val(N₁)) - return dst => U_bend * U + return dst => recouplingmatrix(convert(Matrix{T}, U_bend * U)) end end @@ -371,7 +375,7 @@ function _braid_single((f₁, f₂)::FusionTreePair, (p₁, p₂)::Index2Tuple{N return (f₁′, f₂′) => coeff₁ * coeff₂ * coeff₃ end -CacheStyle(::typeof(fusiontreebraid), src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, args...) where {I} = +CacheStyle(::typeof(fusiontreebraid), ::Type, src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, args...) where {I} = FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache() """ diff --git a/src/fusiontrees/duality_manipulations.jl b/src/fusiontrees/duality_manipulations.jl index df465be40..99de22c48 100644 --- a/src/fusiontrees/duality_manipulations.jl +++ b/src/fusiontrees/duality_manipulations.jl @@ -484,27 +484,31 @@ outgoing (`t1`) and incoming sectors (`t2`) respectively (with identical coupled repartitioning and permuting the tree such that sectors `p1` become outgoing and sectors `p2` become incoming. """ -function Base.transpose(src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple) +Base.transpose(src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple) = + _transpose(fusionscalartype(sectortype(src)), src, p) + +# the transpose with the recoupling matrix of a block in scalar type `T`, which is cached as such +function _transpose(::Type{T}, src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple) where {T} N = numind(src) N == length(p[1]) + length(p[2]) || throw(ArgumentError("invalid permutation p = $p of length N = $N")) p′ = linearizepermutation(p..., numout(src), numin(src)) iscyclicpermutation(p′) || throw(ArgumentError("invalid cyclic or planar permutation p = $p")) - return fusiontreetranspose(src, p) + return fusiontreetranspose(T, src, p) end -function Base.transpose(src::ProductSectorBlock, p::Index2Tuple) - isempty(src) && return fusiontreetranspose(src, p) +function _transpose(::Type{T}, src::ProductSectorBlock, p::Index2Tuple) where {T} + isempty(src) && return fusiontreetranspose(T, src, p) # the return type is asserted since inference gives up on the recursion on older Julia versions - return product_transform(fusionscalartype(sectortype(src)), src) do x + dst, U = product_transform(T, src) do x return transpose(x, p) - end::fusiontreetransposetype(src, p) + end::fusiontreetransposetype(T, src, p) + return dst => recouplingmatrix(U) end Base.@assume_effects :foldable function fusiontreetransposetype( - src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, ::Index2Tuple{N₁, N₂} - ) where {I, N₁, N₂} - T = fusionscalartype(I) + ::Type{T}, src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, ::Index2Tuple{N₁, N₂} + ) where {T, I, N₁, N₂} if src isa FusionTreePair - return Pair{fusiontreetype(I, N₁, N₂), T} + return Pair{fusiontreetype(I, N₁, N₂), fusionscalartype(I)} else F = Tuple{fusiontreetype(I, N₁), fusiontreetype(I, N₂)} return Pair{FusionTreeBlock{I, N₁, N₂, F}, Matrix{T}} @@ -512,17 +516,17 @@ Base.@assume_effects :foldable function fusiontreetransposetype( end @cached function fusiontreetranspose( - src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, p::Index2Tuple{N₁, N₂} - )::fusiontreetransposetype(src, p) where {I, N₁, N₂} + ::Type{T}, src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, p::Index2Tuple{N₁, N₂} + )::fusiontreetransposetype(T, src, p) where {T, I, N₁, N₂} p₁, p₂ = p N = N₁ + N₂ p = linearizepermutation(p₁, p₂, numout(src), numin(src)) dst, U = repartition(src, N₁) - length(p) == 0 && return dst => U + length(p) == 0 && return dst => _withscalartype(T, U) i1 = findfirst(==(1), p)::Int - i1 == 1 && return dst => U + i1 == 1 && return dst => _withscalartype(T, U) Nhalf = N >> 1 while 1 < i1 ≤ Nhalf @@ -536,10 +540,14 @@ end i1 = mod1(i1 + 1, N) end - return dst => U + return dst => _withscalartype(T, U) end -CacheStyle(::typeof(fusiontreetranspose), src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, args...) where {I} = +# the recoupling matrix of a block in scalar type `T`, shared by value, the coefficient of a tree pair as is +_withscalartype(::Type{T}, U::AbstractMatrix) where {T} = recouplingmatrix(convert(Matrix{T}, U)) +_withscalartype(::Type, coeff::Number) = coeff + +CacheStyle(::typeof(fusiontreetranspose), ::Type, src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, args...) where {I} = FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache() # COMPOSITE DUALITY MANIPULATIONS PART 2: Planar traces diff --git a/src/fusiontrees/fusiontrees.jl b/src/fusiontrees/fusiontrees.jl index f14b145da..4d95791c8 100644 --- a/src/fusiontrees/fusiontrees.jl +++ b/src/fusiontrees/fusiontrees.jl @@ -424,6 +424,12 @@ function Base.show(io::IO, t::FusionTree{I}) where {I <: Sector} end end +# `U`, or an equal matrix returned before: a recoupling matrix only depends on the sectors, so transforms share them +@cached function recouplingmatrix(U::Matrix{T})::Matrix{T} where {T} + return U +end +MemoizationKit.default_cache_settings(::typeof(recouplingmatrix)) = (; measure = "bytes", maxsize = 2^28) + # Fusion tree iterators include("iterator.jl") diff --git a/src/tensors/treetransformers.jl b/src/tensors/treetransformers.jl index 12b02cb4d..5a990d528 100644 --- a/src/tensors/treetransformers.jl +++ b/src/tensors/treetransformers.jl @@ -76,12 +76,13 @@ _cache_structure_size(t) = sizeof(t.structure_src) + MemoizationKit.cachesize(t::UniqueTreeTransformer) = sizeof(t) + _cache_payload_size(t.data) + _cache_structure_size(t) -MemoizationKit.cachesize(t::GenericTreeTransformer) = _cache_generic_size(t) +# The recoupling matrices are shared with other transformers and counted by the cache of `recouplingmatrix`. +MemoizationKit.cachesize(t::GenericTreeTransformer) = _cache_generic_size(t; matrices = false) -function _cache_generic_size(t) +function _cache_generic_size(t; matrices::Bool = true) 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) + + bytes += (matrices ? _cache_payload_size(U) : 0) + sizeof(inds_src) + (inds_src === inds_dst ? 0 : sizeof(inds_dst)) end return bytes @@ -209,7 +210,8 @@ end # levels are attached to the legs, so they follow the same relabeling as the permutation levels′ = conjsrc ? TupleTools.getindices(levels, adjointtensorindices(Vsrc′, allind(Vsrc′))) : levels levels″ = (TupleTools.getindices(levels′, codomainind(Vsrc′)), TupleTools.getindices(levels′, domainind(Vsrc′))) - fusiontreebraider(f) = braid(f, p′, levels″) + T = recoupling_scalartype(A, sectorscalartype(sectortype(Vdst))) + fusiontreebraider(f) = _braid(T, f, p′, levels″) return TreeTransformer(A, fusiontreebraider, p, Vdst, Vsrc, conjsrc) end @@ -217,7 +219,8 @@ end A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, conjsrc::Bool )::treetransformertype(A, Vdst, Vsrc) where {TA} p′ = conjsrc ? adjointtensorindices(Vsrc, p) : p - fusiontreetransform(f) = transpose(f, p′) + T = recoupling_scalartype(A, sectorscalartype(sectortype(Vdst))) + fusiontreetransform(f) = _transpose(T, f, p′) return TreeTransformer(A, fusiontreetransform, p, Vdst, Vsrc, conjsrc) end diff --git a/test/other/caches.jl b/test/other/caches.jl index ec750d48e..269cb5c91 100644 --- a/test/other/caches.jl +++ b/test/other/caches.jl @@ -31,7 +31,7 @@ end @test 0 < bytes <= Base.summarysize(value) end for src in TensorKit.fusionblocks(W) - result = TensorKit.fusiontreebraid(src, p, ((1, 2), (3, 4))) + result = TensorKit.fusiontreebraid(sectorscalartype(I), src, p, ((1, 2), (3, 4))) @test 0 < (@constinferred MemoizationKit.cachesize(result)) <= Base.summarysize(result) end