diff --git a/docs/src/Changelog.md b/docs/src/Changelog.md index 152b50d33..dd8b77de6 100644 --- a/docs/src/Changelog.md +++ b/docs/src/Changelog.md @@ -47,8 +47,8 @@ When releasing a new version, move the "Unreleased" changes to a new version sec - Contractions of fermionic tensors fold the twist of one of the operands into the permutation that copies it, instead of twisting the copy in a separate pass ([#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 +- Tree transformers for sectors with multiple fusion channels store every recoupling matrix as a scalar factor times a matrix of the cached braids and transposes of fusion tree blocks, which they share instead of storing one copy per transformer. For product sectors with `UniqueFusion` factors, such as `FermionParity ⊠ U1Irrep ⊠ SU2Irrep`, the matrix is that of the block of the other factors, such that blocks that only differ in their `UniqueFusion` sectors share it without assembling it; twists and single-tree blocks only change the scalar factor +- 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, and their caches are bounded by memory size instead of by number of entries ## [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 4eac157db..12bfdcb9e 100644 --- a/ext/TensorKitEnzymeExt/utility.jl +++ b/ext/TensorKitEnzymeExt/utility.jl @@ -146,6 +146,9 @@ end @inline EnzymeRules.inactive(::typeof(TensorKit.artin_braid), ::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.factored_transform), ::Any...) = nothing +@inline EnzymeRules.inactive(::typeof(TensorKit.productbraid), ::Any...) = nothing +@inline EnzymeRules.inactive(::typeof(TensorKit.producttranspose), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.treetransposer), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.treebraider), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.treetracer), ::Any...) = nothing diff --git a/ext/TensorKitGPUArraysExt.jl b/ext/TensorKitGPUArraysExt.jl index df719f061..14abf7c7b 100644 --- a/ext/TensorKitGPUArraysExt.jl +++ b/ext/TensorKitGPUArraysExt.jl @@ -236,11 +236,11 @@ function DeviceGenericTreeTransformer( structs_src = TreeStructure{N}[] (; structure_dst, structure_src) = transformer - for (U, inds_dst, inds_src) in transformer.data + for (coeff, U, inds_dst, inds_src) in transformer.data if length(U) == 1 # same as the unique (Abelian) case push!( unique_blocks, _unique_block( - only(U), structure_dst[only(inds_dst)], structure_src[only(inds_src)], p + coeff * only(U), structure_dst[only(inds_dst)], structure_src[only(inds_src)], p ) ) else @@ -252,7 +252,8 @@ function DeviceGenericTreeTransformer( length(coeffs), length(structs_dst), length(structs_src) ) ) - append!(coeffs, U) + # the scalar factor is applied while flattening, which copies `U` anyway + append!(coeffs, Iterators.map(u -> coeff * u, U)) for idst in inds_dst _, strides_dst, offset_dst = structure_dst[idst] push!(structs_dst, (strides_dst, offset_dst)) @@ -700,7 +701,7 @@ _diagonal_offsets(structure) = first(_work_offsets(first(first(s)) for s in stru _diagonal_entries(transformer::UniqueTreeTransformer) = transformer.data # `V ← V` and any rearrangement of its two indices have a single tree for every subblock _diagonal_entries(transformer::GenericTreeTransformer) = - ((only(U), only(inds_dst), only(inds_src)) for (U, inds_dst, inds_src) in transformer.data) + ((coeff * only(U), only(inds_dst), only(inds_src)) for (coeff, U, inds_dst, inds_src) in transformer.data) function diagonal_device_transformer(A, transformer, dstdiagonal::Bool) (; structure_dst, structure_src) = transformer diff --git a/src/fusiontrees/braiding_manipulations.jl b/src/fusiontrees/braiding_manipulations.jl index 79fe4c068..d656e9c4d 100644 --- a/src/fusiontrees/braiding_manipulations.jl +++ b/src/fusiontrees/braiding_manipulations.jl @@ -294,20 +294,50 @@ be obtained by combining such operations. 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 +# the braid of a tree pair, or of a block with its recoupling matrix in scalar type `T` 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(T, src, p, levels) + (src isa FusionTreeBlock && _isfactorable(src)) || return _cachedbraid(T, src, p, levels) + dst, (coeff, U) = _braid_factored(T, src, p, levels) + # a new matrix, since `U` is shared by many blocks + return dst => scale(U, coeff) end -function _braid(::Type{T}, src::ProductSectorBlock, p::Index2Tuple, levels::Index2Tuple) where {T} - isempty(src) && return fusiontreebraid(T, src, p, levels) + +# The braid of the tree pair `src` as `dst => coeff`, or of the block `src` as `dst => (coeff, U)` +# with recoupling matrix `coeff * U` in scalar type `T`, where `U` is cached by `fusiontreebraid`. +# For product sectors with a `UniqueFusion` part, `U` is the cached matrix of the other part, +# such that all blocks that only differ in their `UniqueFusion` sectors share it. The coefficient +# of a tree pair does not depend on `T`, so it is computed and cached as that of `braid`. +_braid_factored(::Type, src::FusionTreePair, p::Index2Tuple, levels::Index2Tuple) = + fusiontreebraid(sectorscalartype(sectortype(src)), src, p, levels) +function _braid_factored(::Type{T}, src::FusionTreeBlock, p::Index2Tuple, levels::Index2Tuple) where {T} + if !_isfactorable(src) + dst, U = _cachedbraid(T, src, p, levels) + # a single-tree block is described by its scalar, such that it shares the unit matrix + return length(U) == 1 ? dst => (only(U), _unitmatrix(T)) : dst => (one(T), U) + end # the return type is asserted since inference gives up on the recursion on older Julia versions - dst, U = product_transform(T, src) do x - return braid(x, p, levels) - end::fusiontreebraidtype(T, src, p) - return dst => recouplingmatrix(U) + return factored_transform(T, src) do x + return _braid_factored(T, x, p, levels) + end::_factoredtype(fusiontreebraidtype(T, src, p)) +end + +# The cached braid of a tree pair or block, where that of a product block is computed as the +# Kronecker product of those of its parts, which is cached separately such that inference does +# not need to recurse through `fusiontreebraid`. The parts of a block that is not factorable (see +# `_isfactorable`) are not factorable either. +_cachedbraid(::Type{T}, src, p::Index2Tuple, levels::Index2Tuple) where {T} = fusiontreebraid(T, src, p, levels) +_cachedbraid(::Type{T}, src::ProductSectorBlock, p::Index2Tuple, levels::Index2Tuple) where {T} = + isempty(src) ? fusiontreebraid(T, src, p, levels) : productbraid(T, src, p, levels) + +@cached function productbraid( + ::Type{T}, src::ProductSectorBlock, p::Index2Tuple{N₁, N₂}, levels::Index2Tuple + )::fusiontreebraidtype(T, src, p) where {T, N₁, N₂} + return product_transform(T, src) do x + return _cachedbraid(T, x, p, levels) + end end # Braiding can promote real fusion coefficients to complex values. Keep the result @@ -332,7 +362,7 @@ end 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′]) => recouplingmatrix(fill(convert(T, coeff), 1, 1)) + return FusionTreeBlock([f′]) => fill(convert(T, coeff), 1, 1) end p₁, p₂ = p @@ -359,9 +389,9 @@ end levels = TupleTools.setindex(levels, l, s + 1) end - N₂ == 0 && return dst => recouplingmatrix(convert(Matrix{T}, U)) + N₂ == 0 && return dst => convert(Matrix{T}, U) dst, U_bend = repartition(dst::FusionTreeBlock{I}, Val(N₁)) - return dst => recouplingmatrix(convert(Matrix{T}, U_bend * U)) + return dst => convert(Matrix{T}, U_bend * U) end end @@ -377,6 +407,14 @@ end CacheStyle(::typeof(fusiontreebraid), ::Type, src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, args...) where {I} = FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache() +# TensorKit itself never calls this with `UniqueFusion` sectors, whose fusion tree manipulations +# work with tree pairs instead of blocks; the `NoCache()` branch only guards a manually constructed +# block of such sectors, and could be dropped in favour of the default `GlobalCache()`. +CacheStyle(::typeof(productbraid), ::Type, src::FusionTreeBlock{I}, args...) where {I} = + FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache() +# the recoupling matrices of tree transformers are those of these caches, so their size is that of the matrices +MemoizationKit.default_cache_settings(::typeof(fusiontreebraid)) = (; measure = "bytes", maxsize = 2^28) +MemoizationKit.default_cache_settings(::typeof(productbraid)) = (; measure = "bytes", maxsize = 2^28) """ permute((f₁, f₂)::FusionTreePair, (p1, p2)::Index2Tuple) diff --git a/src/fusiontrees/duality_manipulations.jl b/src/fusiontrees/duality_manipulations.jl index 99de22c48..a979ec70f 100644 --- a/src/fusiontrees/duality_manipulations.jl +++ b/src/fusiontrees/duality_manipulations.jl @@ -487,21 +487,48 @@ repartitioning and permuting the tree such that sectors `p1` become outgoing and 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 +# the transpose of a tree pair, or of a block with its recoupling matrix in scalar type `T` 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(T, src, p) + (src isa FusionTreeBlock && _isfactorable(src)) || return _cachedtranspose(T, src, p) + dst, (coeff, U) = _transpose_factored(T, src, p) + # a new matrix, since `U` is shared by many blocks + return dst => scale(U, coeff) end -function _transpose(::Type{T}, src::ProductSectorBlock, p::Index2Tuple) where {T} - isempty(src) && return fusiontreetranspose(T, src, p) + +# The transpose of the tree pair `src` as `dst => coeff`, or of the block `src` as `dst => (coeff, U)` +# with recoupling matrix `coeff * U` in scalar type `T`, where `U` is cached by `fusiontreetranspose`; +# see `_braid_factored`. The coefficient of a tree pair does not depend on `T`, so it is computed and +# cached as that of `transpose`. +_transpose_factored(::Type, src::FusionTreePair, p::Index2Tuple) = + fusiontreetranspose(fusionscalartype(sectortype(src)), src, p) +function _transpose_factored(::Type{T}, src::FusionTreeBlock, p::Index2Tuple) where {T} + if !_isfactorable(src) + dst, U = _cachedtranspose(T, src, p) + # a single-tree block is described by its scalar, such that it shares the unit matrix + return length(U) == 1 ? dst => (only(U), _unitmatrix(T)) : dst => (one(T), U) + end # the return type is asserted since inference gives up on the recursion on older Julia versions - dst, U = product_transform(T, src) do x - return transpose(x, p) - end::fusiontreetransposetype(T, src, p) - return dst => recouplingmatrix(U) + return factored_transform(T, src) do x + return _transpose_factored(T, x, p) + end::_factoredtype(fusiontreetransposetype(T, src, p)) +end + +# The cached transpose of a tree pair or block, with that of a product block cached separately; +# see `_cachedbraid`. +_cachedtranspose(::Type{T}, src, p::Index2Tuple) where {T} = fusiontreetranspose(T, src, p) +_cachedtranspose(::Type{T}, src::ProductSectorBlock, p::Index2Tuple) where {T} = + isempty(src) ? fusiontreetranspose(T, src, p) : producttranspose(T, src, p) + +@cached function producttranspose( + ::Type{T}, src::ProductSectorBlock, p::Index2Tuple{N₁, N₂} + )::fusiontreetransposetype(T, src, p) where {T, N₁, N₂} + return product_transform(T, src) do x + return _cachedtranspose(T, x, p) + end end Base.@assume_effects :foldable function fusiontreetransposetype( @@ -543,12 +570,20 @@ end return dst => _withscalartype(T, U) end -# 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)) +# the recoupling matrix of a block in scalar type `T`, the coefficient of a tree pair as is +_withscalartype(::Type{T}, U::AbstractMatrix) where {T} = 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() +# TensorKit itself never calls this with `UniqueFusion` sectors, whose fusion tree manipulations +# work with tree pairs instead of blocks; the `NoCache()` branch only guards a manually constructed +# block of such sectors, and could be dropped in favour of the default `GlobalCache()`. +CacheStyle(::typeof(producttranspose), ::Type, src::FusionTreeBlock{I}, args...) where {I} = + FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache() +# the recoupling matrices of tree transformers are those of these caches, so their size is that of the matrices +MemoizationKit.default_cache_settings(::typeof(fusiontreetranspose)) = (; measure = "bytes", maxsize = 2^28) +MemoizationKit.default_cache_settings(::typeof(producttranspose)) = (; measure = "bytes", maxsize = 2^28) # COMPOSITE DUALITY MANIPULATIONS PART 2: Planar traces #------------------------------------------------------------------- diff --git a/src/fusiontrees/fusiontrees.jl b/src/fusiontrees/fusiontrees.jl index 4d95791c8..f14b145da 100644 --- a/src/fusiontrees/fusiontrees.jl +++ b/src/fusiontrees/fusiontrees.jl @@ -424,12 +424,6 @@ 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/fusiontrees/producttrees.jl b/src/fusiontrees/producttrees.jl index 0fba6aec4..c2351b491 100644 --- a/src/fusiontrees/producttrees.jl +++ b/src/fusiontrees/producttrees.jl @@ -130,21 +130,40 @@ function _unique_transform(transform::F, ::Type{T}, src::FusionTreeBlock) where return FusionTreeBlock(map(first, dst)) => LinearAlgebra.diagm(convert.(T, last.(dst))) end +# whether the recoupling matrices of the block `src` factor into a scalar of its `UniqueFusion` part +# and the matrix of its other part, which is then shared by all blocks that only differ in the former +_isfactorable(::FusionTreeBlock) = false +function _isfactorable(src::ProductSectorBlock) + I = sectortype(src) + FusionStyle(I) isa UniqueFusion && return false + return FusionStyle(last(deconstructsectortype(I))) isa UniqueFusion && numind(src) > 0 && !isempty(src) +end + +# the recoupling matrix of every single-tree block, which is then fully described by its scalar factor +@cached function _unitmatrix(::Type{T})::Matrix{T} where {T} + return fill(one(T), 1, 1) +end + +# the type of `dst => (coeff, U)` for a transform with result type `Pair{D, Matrix{T}}` +_factoredtype(::Type{Pair{D, Matrix{T}}}) where {D, T} = Pair{D, Tuple{T, Matrix{T}}} + +# apply `transform` to a factorable block `src` (see `_isfactorable`) through its parts, where +# `transform` maps a tree pair to `dst => coeff` and a block to `dst => (coeff, U)`; the result is +# `dst => (coeff, U)` with recoupling matrix `coeff * U`, where `U` is that of the block of the first part +# and `coeff` the product of its factor and the coefficient of the single tree pair of the second part +function factored_transform(transform::F, ::Type{T}, src::FusionTreeBlock{I}) where {F, T, I} + (g₁, g₂), coeff₂ = transform(last(_deconstructtrees(first(fusiontrees(src))))) + dst₁, (coeff₁, U) = transform(FusionTreeBlock(map(first ∘ _deconstructtrees, fusiontrees(src)))) + dst = FusionTreeBlock( + map(((f₁, f₂),) -> (reconstructtree(I, f₁, g₁), reconstructtree(I, f₂, g₂)), fusiontrees(dst₁)) + ) + return dst => (convert(T, coeff₁ * coeff₂), U) +end + # apply `transform` to the block `src` through its parts, with the recoupling matrix with scalar type `T` +# as the Kronecker product of those of its parts function product_transform(transform::F, ::Type{T}, src::FusionTreeBlock{I}) where {F, T, I} - if FusionStyle(I) isa UniqueFusion - return _unique_transform(transform, T, src) - elseif FusionStyle(last(deconstructsectortype(I))) isa UniqueFusion && numind(src) > 0 - # the second part holds the `UniqueFusion` sectors of a mixed product, with a single tree pair - (g₁, g₂), coeff = transform(last(_deconstructtrees(first(fusiontrees(src))))) - dst₁, U₁ = transform(FusionTreeBlock(map(first ∘ _deconstructtrees, fusiontrees(src)))) - dst = FusionTreeBlock( - map(((f₁, f₂),) -> (reconstructtree(I, f₁, g₁), reconstructtree(I, f₂, g₂)), fusiontrees(dst₁)) - ) - U = Matrix{T}(undef, size(U₁)) - U .= coeff .* U₁ - return dst => U - end + FusionStyle(I) isa UniqueFusion && return _unique_transform(transform, T, src) src₁, cols₁ = _distincttrees(map(first ∘ _deconstructtrees, fusiontrees(src))) src₂, cols₂ = _distincttrees(map(last ∘ _deconstructtrees, fusiontrees(src))) dst₁, U₁ = _unique_transform(transform, T, FusionTreeBlock(src₁)) diff --git a/src/tensors/indexmanipulations.jl b/src/tensors/indexmanipulations.jl index 887825dd0..d30423e51 100644 --- a/src/tensors/indexmanipulations.jl +++ b/src/tensors/indexmanipulations.jl @@ -724,8 +724,8 @@ function add_transform_kernel!( ) bufsize = buffersize(transformer) if bufsize == 0 # no recoupling needed: every block consists of a single tree - taskforeach(transformer.data, ntasks) do (U, inds_dst, inds_src) - _add_transform_block!(dst, src, p, conjsrc, U, inds_dst, inds_src, nothing, α, β, backend, allocator) + taskforeach(transformer.data, ntasks) do data + _add_transform_block!(dst, src, p, conjsrc, _blockdata(data)..., nothing, α, β, backend, allocator) end else # One max-sized workspace per task (a single one that is reused by all blocks when @@ -736,8 +736,8 @@ function add_transform_kernel!( TO.tensoralloc(storagetype(dst), bufsize, Val(true), allocator) for _ in 1:min(length(transformer.data), ntasks) ] - taskforeach(transformer.data, buffers) do (U, inds_dst, inds_src), buffer - _add_transform_block!(dst, src, p, conjsrc, U, inds_dst, inds_src, buffer, α, β, backend, allocator) + taskforeach(transformer.data, buffers) do data, buffer + _add_transform_block!(dst, src, p, conjsrc, _blockdata(data)..., buffer, α, β, backend, allocator) end foreach(Base.Fix2(TO.tensorfree!, allocator), buffers) TO.allocator_reset!(allocator, cp) @@ -745,15 +745,19 @@ 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). +# `(coeff, U, inds_dst, inds_src)` of a transformer entry, where `U` is either a scalar coefficient +# with integer positions (unique fusion), or a recoupling matrix with vectors of positions (generic) +_blockdata((U, idst, isrc)::UniqueTransformerData) = (One(), U, idst, isrc) +_blockdata(data::GenericTransformerData) = data + +# the recoupling coefficients are `coeff * U`, where the scalar `coeff` is applied with `α` function _add_transform_block!( - dst::TransformSubblocks, src::TransformSubblocks, p, conjsrc::Bool, U, inds_dst, inds_src, buffer, + dst::TransformSubblocks, src::TransformSubblocks, p, conjsrc::Bool, coeff, 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[only(inds_dst)], src[only(inds_src)], p, conjsrc, α * (coeff * only(U)), β, backend, allocator ) else # Multi-tree block: pack → recoupling matmul → unpack. rows, cols = size(U) @@ -777,11 +781,12 @@ function _add_transform_block!( @timeit_debug GLOBAL_TIMER "dense: recouple mul!" _recouple!(buffer, buffer_dst, buffer_src, U) # 3. Insert: scatter column j of buffer_dst into the destination, applying the - # actual index permutation p and the scaling α in the same tensoradd! call. + # actual index permutation p and the scaling α * coeff in the same tensoradd! call. + α′ = α * coeff @timeit_debug GLOBAL_TIMER "dense: unpack" @inbounds for (j, idst) in enumerate(inds_dst) TO.tensoradd!( dst[idst], sreshape(view(buffer_dst, :, j), sz_src), - p, false, α, β, backend, allocator + p, false, α′, β, backend, allocator ) end end diff --git a/src/tensors/treetransformers.jl b/src/tensors/treetransformers.jl index 37d9df181..4327a1ed7 100644 --- a/src/tensors/treetransformers.jl +++ b/src/tensors/treetransformers.jl @@ -51,15 +51,18 @@ struct UniqueTreeTransformer{T, N} <: TreeTransformer structure_src::Vector{StridedStructure{N}} end -# (recoupling matrix, destination positions, source positions) -const GenericTransformerData{T} = Tuple{Matrix{T}, Vector{Int}, Vector{Int}} +# (scalar factor, recoupling matrix, destination positions, source positions) +const GenericTransformerData{T} = Tuple{T, Matrix{T}, Vector{Int}, Vector{Int}} """ GenericTreeTransformer{T, N} <: TreeTransformer Tree transformation for sectors with multiple fusion channels, where the subblocks of a [`FusionTreeBlock`](@ref) map onto the subblocks of the transformed block through a recoupling -matrix, stored as `(U, inds_dst, inds_src)`, where `U[j, i]` maps source `i` onto destination `j`. +matrix, stored as `(coeff, U, inds_dst, inds_src)`, where `coeff * U[j, i]` maps source `i` onto +destination `j`. The matrices `U` are those cached for the fusion tree blocks, and are shared +between transformers and between blocks that only differ by a scalar factor, such as the blocks +of a product sector that only differ in their `UniqueFusion` sectors. The subblock structures of the destination and source spaces are kept alongside, such that the [`StridedSubblocks`](@ref) of both tensors can be created without further lookups. """ @@ -76,14 +79,12 @@ _cache_structure_size(t) = sizeof(t.structure_src) + MemoizationKit.cachesize(t::UniqueTreeTransformer) = sizeof(t) + _cache_payload_size(t.data) + _cache_structure_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; matrices::Bool = true) +# The recoupling matrices are shared with other transformers and counted by the caches of +# `fusiontreebraid`, `fusiontreetranspose`, `productbraid` and `producttranspose`. +function MemoizationKit.cachesize(t::GenericTreeTransformer) bytes = sizeof(t) + sizeof(t.data) + _cache_structure_size(t) - for (U, inds_dst, inds_src) in t.data - bytes += (matrices ? _cache_payload_size(U) : 0) + sizeof(inds_src) + - (inds_src === inds_dst ? 0 : sizeof(inds_dst)) + for (_, _, inds_dst, inds_src) in t.data + bytes += sizeof(inds_src) + (inds_src === inds_dst ? 0 : sizeof(inds_dst)) end return bytes end @@ -132,7 +133,7 @@ function GenericTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::H @timeit_debug GLOBAL_TIMER "symmetry: recoupling matrices" begin taskforeach(1:nblocks, nthreads) do i fs_src = fblocks[i] - fs_dst, U = transform(fs_src) + fs_dst, (coeff, U) = transform(fs_src) @timeit_debug GLOBAL_TIMER "bookkeeping: subblock positions" begin # the token into the fusion tree `Indices` is the subblock position inds_src = map(fusiontrees(fs_src)) do (f₁, f₂) @@ -144,7 +145,7 @@ function GenericTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::H return idst end end - data[i] = (convert(Matrix{T}, U), inds_dst, inds_src) + data[i] = (convert(T, coeff), 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]) @@ -163,8 +164,8 @@ function GenericTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::H @debug( lazy"TreeTransformer for $Vsrc to $Vdst via $p", conjsrc, nblocks = nblocks, - sz_median = nblocks > 0 ? size(data[cld(end, 2)][1], 1) : 0, - sz_max = nblocks > 0 ? size(data[1][1], 1) : 0, + sz_median = nblocks > 0 ? size(data[cld(end, 2)][2], 1) : 0, + sz_max = nblocks > 0 ? size(data[1][2], 1) : 0, Δt ) @@ -181,7 +182,7 @@ the recoupling matrix. buffersize(::UniqueTreeTransformer) = 0 function buffersize(transformer::GenericTreeTransformer) structure_src = transformer.structure_src - return maximum(transformer.data; init = 0) do (U, _, inds_src) + return maximum(transformer.data; init = 0) do (_, U, _, inds_src) return length(U) == 1 ? 0 : prod(structure_src[first(inds_src)][1]) * sum(size(U)) end end @@ -202,13 +203,10 @@ function TreeTransformer( GenericTreeTransformer(A, transform, p, Vdst, Vsrc, conjsrc) end -# the recoupling coefficients `U` followed by the twist factor `θ`; a twisted recoupling matrix -# only depends on the sectors as well, so it is shared through `recouplingmatrix` like `U` itself -_twistrecoupling(U::Number, θ::Number) = U * θ -function _twistrecoupling(U::Matrix{T}, θ::Number) where {T} - isone(θ) && return U - return recouplingmatrix(scale(U, convert(T, θ))) -end +# the recoupling coefficients followed by the twist factor `θ`, which is shared by all trees of a block +# and therefore only changes the scalar factor of a recoupling matrix, which is kept shared +_twistrecoupling(coeff::Number, θ::Number) = coeff * θ +_twistrecoupling((coeff, U)::Tuple{T, Matrix{T}}, θ::Number) where {T} = (coeff * convert(T, θ), U) # braid is special because it has levels; the destination legs in `twistmask` are twisted afterwards, # which is diagonal in the fusion tree basis and therefore folded into the recoupling coefficients @@ -222,7 +220,7 @@ end levels″ = (TupleTools.getindices(levels′, codomainind(Vsrc′)), TupleTools.getindices(levels′, domainind(Vsrc′))) T = recoupling_scalartype(A, sectorscalartype(sectortype(Vdst))) function fusiontreebraider(f) - f′, U = _braid(T, f, p′, levels″) + f′, U = _braid_factored(T, f, p′, levels″) any(twistmask) || return f′, U return f′, _twistrecoupling(U, last(twist(f′, twistmask))) end @@ -234,10 +232,12 @@ end )::treetransformertype(A, Vdst, Vsrc) where {TA} p′ = conjsrc ? adjointtensorindices(Vsrc, p) : p T = recoupling_scalartype(A, sectorscalartype(sectortype(Vdst))) - fusiontreetransform(f) = _transpose(T, f, p′) + fusiontreetransform(f) = _transpose_factored(T, f, p′) return TreeTransformer(A, fusiontreetransform, p, Vdst, Vsrc, conjsrc) end +# (recoupling matrix, destination positions, source positions) +const TraceTransformerData{T} = Tuple{Matrix{T}, Vector{Int}, Vector{Int}} """ TraceTransformer{T, N₁, N₂} @@ -251,12 +251,18 @@ spaces are kept alongside, such that the [`StridedSubblocks`](@ref) of both tens created without further lookups. """ struct TraceTransformer{T, N₁, N₂} - data::Vector{GenericTransformerData{T}} + data::Vector{TraceTransformerData{T}} structure_dst::Vector{StridedStructure{N₁}} structure_src::Vector{StridedStructure{N₂}} end -MemoizationKit.cachesize(t::TraceTransformer) = _cache_generic_size(t) +function MemoizationKit.cachesize(t::TraceTransformer) + 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)) + end + return bytes +end VectorInterface.scalartype( ::Type{<:Union{UniqueTreeTransformer{T}, GenericTreeTransformer{T}, TraceTransformer{T}}} @@ -297,7 +303,7 @@ 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] + data = TraceTransformerData{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)) @@ -378,7 +384,7 @@ function device_treetwister end # Keep TensorKit's profiling categories for the phases instrumented by MemoizationKit. const TensorKitCachedFunction = Union{ - typeof(fusiontreebraid), typeof(fusiontreetranspose), + typeof(fusiontreebraid), typeof(fusiontreetranspose), typeof(productbraid), typeof(producttranspose), typeof(treebraider), typeof(treetransposer), typeof(treetracer), typeof(treetwister), typeof(device_treebraider), typeof(device_treetransposer), typeof(device_treetracer), typeof(device_treetwister), typeof(sectorstructure), typeof(degeneracystructure), diff --git a/test/other/caches.jl b/test/other/caches.jl index 1c6d73c0d..4ad65a0c1 100644 --- a/test/other/caches.jl +++ b/test/other/caches.jl @@ -19,6 +19,31 @@ using TensorKit: MemoizationKit, sectorstructure, degeneracystructure @test length(only(MemoizationKit.cache_info(degeneracystructure)).second) == 2 end +@testset "Shared recoupling matrices of product sectors" begin + s(p, n, j) = FermionParity(p) ⊠ U1Irrep(n) ⊠ SU2Irrep(j) + I = typeof(s(0, 0, 0)) + V = Vect[I](s(0, 0, 0) => 1, s(1, 1, 1 // 2) => 1, s(1, -1, 1 // 2) => 1, s(0, 2, 0) => 1, s(0, 0, 1) => 1) + W = V ⊗ V ← V ⊗ V + p, levels = ((3, 1), (4, 2)), (1, 2, 3, 4) + empty_globalcaches!() + for twistmask in ((false, false, false, false), (false, true, true, false)) + transformer = TensorKit.treebraider(Vector{Float64}, permute(W, p), W, p, false, levels, twistmask) + # blocks that only differ in their `UniqueFusion` sectors share the matrix of their `SU2Irrep` part + matrices = [U for (_, U, _, _) in transformer.data] + sizes = unique(size.(matrices)) + @test length(unique(objectid, matrices)) < length(matrices) + @test (1, 1) ∉ sizes || count(U -> size(U) == (1, 1), unique(objectid, matrices)) == 1 + # the stored factorization reproduces the recoupling matrix of every block + for fs_src in TensorKit.fusionblocks(W) + fs_dst, U = braid(fs_src, p, ((1, 2), (3, 4))) + any(twistmask) && (U = U * last(twist(fs_dst, twistmask))) + inds_src = map(f -> TensorKit.gettoken(TensorKit.fusiontrees(W), f)[2][2], TensorKit.fusiontrees(fs_src)) + coeff, U′, _, _ = only(filter(d -> d[4] == inds_src, transformer.data)) + @test coeff * U′ ≈ U + end + end +end + @testset "TensorKit cached-value sizes" begin for I in (Z2Irrep, SU2Irrep, A4Irrep, FibonacciAnyon) labels = collect(Iterators.take(values(I), 2))