Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/src/Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions ext/TensorKitEnzymeExt/utility.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 5 additions & 4 deletions ext/TensorKitGPUArraysExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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))
Expand Down Expand Up @@ -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
Expand Down
60 changes: 49 additions & 11 deletions src/fusiontrees/braiding_manipulations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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

Expand All @@ -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)
Expand Down
55 changes: 45 additions & 10 deletions src/fusiontrees/duality_manipulations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
#-------------------------------------------------------------------
Expand Down
6 changes: 0 additions & 6 deletions src/fusiontrees/fusiontrees.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
45 changes: 32 additions & 13 deletions src/fusiontrees/producttrees.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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₁))
Expand Down
Loading
Loading