From 52f501725c270314ec534e5a4940e988b2dc3bf6 Mon Sep 17 00:00:00 2001 From: lkdvos Date: Wed, 28 Oct 2026 08:42:36 -0400 Subject: [PATCH 1/4] Fold the twist of fermionic contraction operands into their permutation The operand that `blas_contract!` twists for fermionic sectors is always copied first, so the twist is now folded into the recoupling coefficients of that copy through a cached `treepermuter`, instead of a separate `twist!` pass over the copied operand (#595). Co-Authored-By: Claude Opus 5.5 --- docs/src/Changelog.md | 1 + ext/TensorKitEnzymeExt/utility.jl | 2 ++ ext/TensorKitGPUArraysExt.jl | 12 ++++++++++++ src/tensors/tensoroperations.jl | 27 +++++++++++++++++++++++---- src/tensors/treetransformers.jl | 23 ++++++++++++++++++++--- 5 files changed, 58 insertions(+), 7 deletions(-) diff --git a/docs/src/Changelog.md b/docs/src/Changelog.md index 3148dae0c..60de33c6a 100644 --- a/docs/src/Changelog.md +++ b/docs/src/Changelog.md @@ -44,6 +44,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec - `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 +- 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)) ## [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..28e202bd7 100644 --- a/ext/TensorKitEnzymeExt/utility.jl +++ b/ext/TensorKitEnzymeExt/utility.jl @@ -154,6 +154,8 @@ end @inline EnzymeRules.inactive(::typeof(TensorKit.device_treebraider), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.device_treetracer), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.device_treetwister), ::Any...) = nothing +@inline EnzymeRules.inactive(::typeof(TensorKit.treepermuter), ::Any...) = nothing +@inline EnzymeRules.inactive(::typeof(TensorKit.device_treepermuter), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.insertleftunit), ::HomSpace, ::Any) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.insertrightunit), ::HomSpace, ::Any) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.removeunit), ::HomSpace, ::Any) = nothing diff --git a/ext/TensorKitGPUArraysExt.jl b/ext/TensorKitGPUArraysExt.jl index c99a78fe9..6367078fe 100644 --- a/ext/TensorKitGPUArraysExt.jl +++ b/ext/TensorKitGPUArraysExt.jl @@ -379,6 +379,10 @@ TensorKit.treebraider( TensorKit.treetransposer( A::Type{<:AnyGPUVector}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, conjsrc::Bool ) = TensorKit.device_treetransposer(A, Vdst, Vsrc, p, conjsrc) +TensorKit.treepermuter( + A::Type{<:AnyGPUVector}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, + conjsrc::Bool, twistmask::NTuple{N, Bool} +) where {N} = TensorKit.device_treepermuter(A, Vdst, Vsrc, p, conjsrc, twistmask) TensorKit.treetracer( A::Type{<:AnyGPUVector}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, q::Index2Tuple ) = TensorKit.device_treetracer(A, Vdst, Vsrc, p, q) @@ -403,6 +407,14 @@ end return device_transformer(A, host, linearize(p)) end +@cached function TensorKit.device_treepermuter( + A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, + conjsrc::Bool, twistmask::NTuple{N, Bool} + ) where {TA <: AnyGPUVector, N} + host = TensorKit.treepermuter(Vector{scalartype(A)}, Vdst, Vsrc, p, conjsrc, twistmask) + return device_transformer(A, host, linearize(p)) +end + @cached function TensorKit.device_treetracer( A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, q::Index2Tuple ) where {TA <: AnyGPUVector} diff --git a/src/tensors/tensoroperations.jl b/src/tensors/tensoroperations.jl index c0f530be9..e3186eec1 100644 --- a/src/tensors/tensoroperations.jl +++ b/src/tensors/tensoroperations.jl @@ -390,6 +390,19 @@ function TO.isblasdestination(A::AbstractTensorMap, ipAB::Index2Tuple) return scalartype(A) <: LinearAlgebra.BlasFloat && has_shared_permute(A, ipAB) end +# `tdst = twist(permute(tsrc, p), inds)`, with the twist folded into the coefficients of the permutation +function permute_twist!(tdst::TensorMap, tsrc::AbstractTensorMap, p::Index2Tuple, inds, backend, allocator) + tsrc′, p′, _, conjsrc = _unwrap_source(tsrc, p, nothing, false) + # other tensor types, such as diagonal GPU tensors, rely on the dispatch of `tensoradd!` + if !(tsrc′ isa TensorMap) + TO.tensoradd!(tdst, tsrc, p, false, One(), Zero(), backend, allocator) + return twist!(tdst, inds) + end + twistmask = ntuple(in(inds), numind(tdst)) + transformer = treepermuter(storagetype(tdst), space(tdst), space(tsrc′), p′, conjsrc, twistmask) + return add_transform!(tdst, tsrc′, p′, conjsrc, transformer, One(), Zero(), backend, allocator) +end + function blas_contract!( C::AbstractTensorMap, A::AbstractTensorMap, pA::Index2Tuple, @@ -426,8 +439,11 @@ function blas_contract!( # Bring A in the correct form for BLAS contraction if copyA Anew = @timeit_debug GLOBAL_TIMER "alloc: buffers" TO.tensoralloc_add(TC, A, pA, false, Val(true), allocator) - Anew = TO.tensoradd!(Anew, A, pA, false, One(), Zero(), backend, allocator) - twistA && twist!(Anew, filter(!isdual ∘ Base.Fix1(space, Anew), domainind(Anew))) + if twistA + permute_twist!(Anew, A, pA, filter(!isdual ∘ Base.Fix1(space, Anew), domainind(Anew)), backend, allocator) + else + Anew = TO.tensoradd!(Anew, A, pA, false, One(), Zero(), backend, allocator) + end else Anew = permute(A, pA) end @@ -436,8 +452,11 @@ function blas_contract!( # Bring B in the correct form for BLAS contraction if copyB Bnew = @timeit_debug GLOBAL_TIMER "alloc: buffers" TO.tensoralloc_add(TC, B, pB, false, Val(true), allocator) - Bnew = TO.tensoradd!(Bnew, B, pB, false, One(), Zero(), backend, allocator) - twistB && twist!(Bnew, filter(isdual ∘ Base.Fix1(space, Bnew), codomainind(Bnew))) + if twistB + permute_twist!(Bnew, B, pB, filter(isdual ∘ Base.Fix1(space, Bnew), codomainind(Bnew)), backend, allocator) + else + Bnew = TO.tensoradd!(Bnew, B, pB, false, One(), Zero(), backend, allocator) + end else Bnew = permute(B, pB) end diff --git a/src/tensors/treetransformers.jl b/src/tensors/treetransformers.jl index 5a990d528..55f183a37 100644 --- a/src/tensors/treetransformers.jl +++ b/src/tensors/treetransformers.jl @@ -224,6 +224,20 @@ end return TreeTransformer(A, fusiontreetransform, p, Vdst, Vsrc, conjsrc) end +# permutation for symmetric braidings followed by a twist of the destination legs in `twistmask`, +# which is diagonal in the fusion tree basis and therefore folded into the recoupling coefficients +@cached function treepermuter( + A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, conjsrc::Bool, + twistmask::NTuple{N, Bool} + )::treetransformertype(A, Vdst, Vsrc) where {TA, N} + p′ = conjsrc ? adjointtensorindices(Vsrc, p) : p + function fusiontreepermuter(f) + f′, U = permute(f, p′) + return f′, U * last(twist(f′, twistmask)) + end + return TreeTransformer(A, fusiontreepermuter, p, Vdst, Vsrc, conjsrc) +end + """ TraceTransformer{T, N₁, N₂} @@ -346,27 +360,30 @@ end """ device_treebraider(A, Vdst, Vsrc, p, conjsrc, levels) device_treetransposer(A, Vdst, Vsrc, p, conjsrc) + device_treepermuter(A, Vdst, Vsrc, p, conjsrc, twistmask) device_treetracer(A, Vdst, Vsrc, p, q) device_treetwister(A, Vdst, Vsrc, p, conjsrc, twistmask, inv) Tree transformers for device storage types `A`, to which `treebraider`, `treetransposer`, -`treetracer` and `treetwister` forward. Their methods are added by package extensions. Being +`treepermuter`, `treetracer` and `treetwister` forward. Their methods are added by package extensions. Being separate functions, the device transformers have their own caches, which can be configured independently of the host ones. """ function device_treebraider end function device_treetransposer end +function device_treepermuter end function device_treetracer end function device_treetwister end @doc (@doc device_treebraider) device_treetransposer +@doc (@doc device_treebraider) device_treepermuter @doc (@doc device_treebraider) device_treetracer @doc (@doc device_treebraider) device_treetwister # Keep TensorKit's profiling categories for the phases instrumented by MemoizationKit. const TensorKitCachedFunction = Union{ typeof(fusiontreebraid), typeof(fusiontreetranspose), - typeof(treebraider), typeof(treetransposer), typeof(treetracer), typeof(treetwister), - typeof(device_treebraider), typeof(device_treetransposer), typeof(device_treetracer), typeof(device_treetwister), + typeof(treebraider), typeof(treetransposer), typeof(treepermuter), typeof(treetracer), typeof(treetwister), + typeof(device_treebraider), typeof(device_treetransposer), typeof(device_treepermuter), typeof(device_treetracer), typeof(device_treetwister), typeof(sectorstructure), typeof(degeneracystructure), } MemoizationKit.instrument_label(f::TensorKitCachedFunction, ::Val{:lookup}) = "bookkeeping: cache $(nameof(f))" From 2d1027957b69a6b3046c59e11db5fd0051f850f0 Mon Sep 17 00:00:00 2001 From: lkdvos Date: Thu, 5 Nov 2026 10:33:27 -0500 Subject: [PATCH 2/4] Generalize `treebraider` with a twist mask instead of a separate `treepermuter` `blas_contract!` now computes the twist masks of both operands in `contraction_twistmasks` and always copies through `permute_twist!`, with an all-false mask when no twist is needed. Co-Authored-By: Claude Opus 5.5 --- docs/src/Changelog.md | 2 +- ext/TensorKitEnzymeExt/utility.jl | 2 -- ext/TensorKitGPUArraysExt.jl | 28 +++++----------- src/tensors/indexmanipulations.jl | 13 ++++--- src/tensors/tensoroperations.jl | 56 +++++++++++-------------------- src/tensors/treetransformers.jl | 45 ++++++++++++------------- 6 files changed, 58 insertions(+), 88 deletions(-) diff --git a/docs/src/Changelog.md b/docs/src/Changelog.md index 60de33c6a..6d5d66292 100644 --- a/docs/src/Changelog.md +++ b/docs/src/Changelog.md @@ -40,11 +40,11 @@ When releasing a new version, move the "Unreleased" changes to a new version sec ### Performance - `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)) +- 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 -- 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)) ## [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 28e202bd7..4eac157db 100644 --- a/ext/TensorKitEnzymeExt/utility.jl +++ b/ext/TensorKitEnzymeExt/utility.jl @@ -154,8 +154,6 @@ end @inline EnzymeRules.inactive(::typeof(TensorKit.device_treebraider), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.device_treetracer), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.device_treetwister), ::Any...) = nothing -@inline EnzymeRules.inactive(::typeof(TensorKit.treepermuter), ::Any...) = nothing -@inline EnzymeRules.inactive(::typeof(TensorKit.device_treepermuter), ::Any...) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.insertleftunit), ::HomSpace, ::Any) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.insertrightunit), ::HomSpace, ::Any) = nothing @inline EnzymeRules.inactive(::typeof(TensorKit.removeunit), ::HomSpace, ::Any) = nothing diff --git a/ext/TensorKitGPUArraysExt.jl b/ext/TensorKitGPUArraysExt.jl index 6367078fe..b125f6654 100644 --- a/ext/TensorKitGPUArraysExt.jl +++ b/ext/TensorKitGPUArraysExt.jl @@ -379,10 +379,6 @@ TensorKit.treebraider( TensorKit.treetransposer( A::Type{<:AnyGPUVector}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, conjsrc::Bool ) = TensorKit.device_treetransposer(A, Vdst, Vsrc, p, conjsrc) -TensorKit.treepermuter( - A::Type{<:AnyGPUVector}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, - conjsrc::Bool, twistmask::NTuple{N, Bool} -) where {N} = TensorKit.device_treepermuter(A, Vdst, Vsrc, p, conjsrc, twistmask) TensorKit.treetracer( A::Type{<:AnyGPUVector}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, q::Index2Tuple ) = TensorKit.device_treetracer(A, Vdst, Vsrc, p, q) @@ -394,9 +390,9 @@ TensorKit.treetwister( # Cache the device transformer directly, constructing the cached host version only on a miss. @cached function TensorKit.device_treebraider( A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, - conjsrc::Bool, levels::IndexTuple - ) where {TA <: AnyGPUVector} - host = TensorKit.treebraider(Vector{scalartype(A)}, Vdst, Vsrc, p, conjsrc, levels) + conjsrc::Bool, levels::IndexTuple, twistmask::NTuple{N, Bool} + ) where {TA <: AnyGPUVector, N} + host = TensorKit.treebraider(Vector{scalartype(A)}, Vdst, Vsrc, p, conjsrc, levels, twistmask) return device_transformer(A, host, linearize(p)) end @@ -407,14 +403,6 @@ end return device_transformer(A, host, linearize(p)) end -@cached function TensorKit.device_treepermuter( - A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, - conjsrc::Bool, twistmask::NTuple{N, Bool} - ) where {TA <: AnyGPUVector, N} - host = TensorKit.treepermuter(Vector{scalartype(A)}, Vdst, Vsrc, p, conjsrc, twistmask) - return device_transformer(A, host, linearize(p)) -end - @cached function TensorKit.device_treetracer( A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, q::Index2Tuple ) where {TA <: AnyGPUVector} @@ -733,9 +721,9 @@ end # Transformers for diagonal sources share the cache of the other device transformers. @cached function TensorKit.device_treebraider( A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, - conjsrc::Bool, levels::IndexTuple, dstdiagonal::Bool - ) where {TA <: AnyGPUVector} - host = TensorKit.treebraider(Vector{scalartype(A)}, Vdst, Vsrc, p, conjsrc, levels) + conjsrc::Bool, levels::IndexTuple, twistmask::NTuple{N, Bool}, dstdiagonal::Bool + ) where {TA <: AnyGPUVector, N} + host = TensorKit.treebraider(Vector{scalartype(A)}, Vdst, Vsrc, p, conjsrc, levels, twistmask) return diagonal_device_transformer(A, host, dstdiagonal) end @@ -768,12 +756,12 @@ end Base.@propagate_inbounds function TensorKit._braid!( tdst::Union{GPUTensorMap, GPUDiagonalTensorMap}, tsrc::GPUDiagonalTensorMap, - p::Index2Tuple, conjsrc::Bool, levels::IndexTuple, α, β, backend, allocator + p::Index2Tuple, conjsrc::Bool, levels::IndexTuple, twistmask::Tuple{Vararg{Bool}}, α, β, backend, allocator ) Vdst, Vsrc = space(tdst), space(tsrc) @boundscheck TensorKit.spacecheck_transform(permute, Vdst, Vsrc, p, conjsrc) transformer = TensorKit.device_treebraider( - storagetype(tdst), Vdst, Vsrc, p, conjsrc, levels, tdst isa DiagonalTensorMap + storagetype(tdst), Vdst, Vsrc, p, conjsrc, levels, twistmask, tdst isa DiagonalTensorMap ) return _add_diagonal!(tdst, tsrc, conjsrc, transformer, α, β) end diff --git a/src/tensors/indexmanipulations.jl b/src/tensors/indexmanipulations.jl index 78a7d82fe..1b768de52 100644 --- a/src/tensors/indexmanipulations.jl +++ b/src/tensors/indexmanipulations.jl @@ -241,7 +241,7 @@ See also [`permute`](@ref) for creating a new tensor. @boundscheck spacecheck_transform(permute, space(tdst), space(tsrc), p) @timeit_debug GLOBAL_TIMER "permute!/braid!" begin tdst′, tsrc′, p′, _, conjsrc′, α′, β′ = unwrap_adjoints(tdst, tsrc, p, nothing, false, α, β) - @inbounds _braid!(tdst′, tsrc′, p′, conjsrc′, allind(tsrc′), α′, β′, backend, allocator) + @inbounds _braid!(tdst′, tsrc′, p′, conjsrc′, allind(tsrc′), _notwist(tdst′), α′, β′, backend, allocator) end return tdst end @@ -331,7 +331,7 @@ See also [`braid`](@ref) for creating a new tensor. @boundscheck spacecheck_transform(braid, space(tdst), space(tsrc), p, levels) @timeit_debug GLOBAL_TIMER "permute!/braid!" begin tdst′, tsrc′, p′, levels′, conjsrc′, α′, β′ = unwrap_adjoints(tdst, tsrc, p, levels, false, α, β) - @inbounds _braid!(tdst′, tsrc′, p′, conjsrc′, levels′, α′, β′, backend, allocator) + @inbounds _braid!(tdst′, tsrc′, p′, conjsrc′, levels′, _notwist(tdst′), α′, β′, backend, allocator) end return tdst end @@ -637,14 +637,17 @@ function _dense_transform!(tdst, tsrc, p::Index2Tuple, conjsrc::Bool, α, β, ba return tdst end +_notwist(t) = ntuple(Returns(false), numind(t)) + +# `twistmask` selects the destination legs that are twisted after braiding @propagate_inbounds function _braid!( - tdst, tsrc, p::Index2Tuple, conjsrc::Bool, levels::IndexTuple, α, β, backend, allocator + tdst, tsrc, p::Index2Tuple, conjsrc::Bool, levels::IndexTuple, twistmask::Tuple{Vararg{Bool}}, α, β, backend, allocator ) Vdst, Vsrc = space(tdst), space(tsrc) @boundscheck spacecheck_transform(permute, Vdst, Vsrc, p, conjsrc) all(has_array_view, (tdst, tsrc)) && return _dense_transform!(tdst, tsrc, p, conjsrc, α, β, backend, allocator) - _is_trivial_transform(tsrc, p, conjsrc) && return add!(tdst, tsrc, α, β) - transformer = treebraider(storagetype(tdst), Vdst, Vsrc, p, conjsrc, levels) + !any(twistmask) && _is_trivial_transform(tsrc, p, conjsrc) && return add!(tdst, tsrc, α, β) + transformer = treebraider(storagetype(tdst), Vdst, Vsrc, p, conjsrc, levels, twistmask) return add_transform!(tdst, tsrc, p, conjsrc, transformer, α, β, backend, allocator) end diff --git a/src/tensors/tensoroperations.jl b/src/tensors/tensoroperations.jl index e3186eec1..8ca3c63b6 100644 --- a/src/tensors/tensoroperations.jl +++ b/src/tensors/tensoroperations.jl @@ -48,7 +48,7 @@ function TO.tensoradd!( backend, allocator ) tdst, tsrc, p, _, conjA′, α′, β′ = unwrap_adjoints(C, A, _canonicalize(pA, C), nothing, conjA, α, β) - _braid!(tdst, tsrc, p, conjA′, allind(tsrc), α′, β′, backend, allocator) + _braid!(tdst, tsrc, p, conjA′, allind(tsrc), _notwist(tdst), α′, β′, backend, allocator) return C end @@ -390,17 +390,21 @@ function TO.isblasdestination(A::AbstractTensorMap, ipAB::Index2Tuple) return scalartype(A) <: LinearAlgebra.BlasFloat && has_shared_permute(A, ipAB) end -# `tdst = twist(permute(tsrc, p), inds)`, with the twist folded into the coefficients of the permutation -function permute_twist!(tdst::TensorMap, tsrc::AbstractTensorMap, p::Index2Tuple, inds, backend, allocator) +# `tdst = twist(permute(tsrc, p), twistmask)`, with the twist folded into the coefficients of the permutation +function permute_twist!(tdst::AbstractTensorMap, tsrc::AbstractTensorMap, p::Index2Tuple, twistmask, backend, allocator) tsrc′, p′, _, conjsrc = _unwrap_source(tsrc, p, nothing, false) - # other tensor types, such as diagonal GPU tensors, rely on the dispatch of `tensoradd!` - if !(tsrc′ isa TensorMap) - TO.tensoradd!(tdst, tsrc, p, false, One(), Zero(), backend, allocator) - return twist!(tdst, inds) - end - twistmask = ntuple(in(inds), numind(tdst)) - transformer = treepermuter(storagetype(tdst), space(tdst), space(tsrc′), p′, conjsrc, twistmask) - return add_transform!(tdst, tsrc′, p′, conjsrc, transformer, One(), Zero(), backend, allocator) + return _braid!(tdst, tsrc′, p′, conjsrc, allind(tsrc′), twistmask, One(), Zero(), backend, allocator) +end + +# fermionic contractions need a twist of the contracted legs of either `A` or `B`: +# twist the one that is copied anyway, or the smallest if neither or both are copied +function contraction_twistmasks(A, pA, B, pB, copyA, copyB) + twists = map(isdual ∘ Base.Fix1(space, B), pB[1]) + notwistA, notwistB = map(Returns(false), linearize(pA)), map(Returns(false), linearize(pB)) + (BraidingStyle(sectortype(B)) isa Fermionic && any(twists)) || return notwistA, notwistB + twistA = copyA ⊻ copyB ? copyA : dim(A) < dim(B) + return twistA ? ((map(Returns(false), pA[1])..., twists...), notwistB) : + (notwistA, (twists..., map(Returns(false), pB[2])...)) end function blas_contract!( @@ -419,31 +423,15 @@ function blas_contract!( copyA = !(TO.isblascontractable(A, pA) && scalartype(A) === TC) copyB = !(TO.isblascontractable(B, pB) && scalartype(B) === TC) - if bstyle isa Fermionic && any(isdual ∘ Base.Fix1(space, B), pB[1]) - # twist smallest object if neither or both already have to be permuted - # otherwise twist the one that already is copied - if !(copyA ⊻ copyB) - twistA = dim(A) < dim(B) - else - twistA = copyA - end - twistB = !twistA - copyA |= twistA - copyB |= twistB - else - twistA = false - twistB = false - end + twistmaskA, twistmaskB = contraction_twistmasks(A, pA, B, pB, copyA, copyB) + copyA |= any(twistmaskA) + copyB |= any(twistmaskB) cp = TO.allocator_checkpoint!(allocator) # Bring A in the correct form for BLAS contraction if copyA Anew = @timeit_debug GLOBAL_TIMER "alloc: buffers" TO.tensoralloc_add(TC, A, pA, false, Val(true), allocator) - if twistA - permute_twist!(Anew, A, pA, filter(!isdual ∘ Base.Fix1(space, Anew), domainind(Anew)), backend, allocator) - else - Anew = TO.tensoradd!(Anew, A, pA, false, One(), Zero(), backend, allocator) - end + permute_twist!(Anew, A, pA, twistmaskA, backend, allocator) else Anew = permute(A, pA) end @@ -452,11 +440,7 @@ function blas_contract!( # Bring B in the correct form for BLAS contraction if copyB Bnew = @timeit_debug GLOBAL_TIMER "alloc: buffers" TO.tensoralloc_add(TC, B, pB, false, Val(true), allocator) - if twistB - permute_twist!(Bnew, B, pB, filter(isdual ∘ Base.Fix1(space, Bnew), codomainind(Bnew)), backend, allocator) - else - Bnew = TO.tensoradd!(Bnew, B, pB, false, One(), Zero(), backend, allocator) - end + permute_twist!(Bnew, B, pB, twistmaskB, backend, allocator) else Bnew = permute(B, pB) end diff --git a/src/tensors/treetransformers.jl b/src/tensors/treetransformers.jl index 55f183a37..3ccfe1af1 100644 --- a/src/tensors/treetransformers.jl +++ b/src/tensors/treetransformers.jl @@ -202,16 +202,30 @@ function TreeTransformer( GenericTreeTransformer(A, transform, p, Vdst, Vsrc, conjsrc) end -# braid is special because it has levels +# 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 + +# 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 @cached function treebraider( - A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, conjsrc::Bool, levels::IndexTuple - )::treetransformertype(A, Vdst, Vsrc) where {TA} + A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, conjsrc::Bool, levels::IndexTuple, + twistmask::NTuple{N, Bool} + )::treetransformertype(A, Vdst, Vsrc) where {TA, N} Vsrc′, p′ = conjsrc ? (Vsrc', adjointtensorindices(Vsrc, p)) : (Vsrc, p) # 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′))) T = recoupling_scalartype(A, sectorscalartype(sectortype(Vdst))) - fusiontreebraider(f) = _braid(T, f, p′, levels″) + function fusiontreebraider(f) + f′, U = _braid(T, f, p′, levels″) + any(twistmask) || return f′, U + return f′, _twistrecoupling(U, last(twist(f′, twistmask))) + end return TreeTransformer(A, fusiontreebraider, p, Vdst, Vsrc, conjsrc) end @@ -224,20 +238,6 @@ end return TreeTransformer(A, fusiontreetransform, p, Vdst, Vsrc, conjsrc) end -# permutation for symmetric braidings followed by a twist of the destination legs in `twistmask`, -# which is diagonal in the fusion tree basis and therefore folded into the recoupling coefficients -@cached function treepermuter( - A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, conjsrc::Bool, - twistmask::NTuple{N, Bool} - )::treetransformertype(A, Vdst, Vsrc) where {TA, N} - p′ = conjsrc ? adjointtensorindices(Vsrc, p) : p - function fusiontreepermuter(f) - f′, U = permute(f, p′) - return f′, U * last(twist(f′, twistmask)) - end - return TreeTransformer(A, fusiontreepermuter, p, Vdst, Vsrc, conjsrc) -end - """ TraceTransformer{T, N₁, N₂} @@ -360,30 +360,27 @@ end """ device_treebraider(A, Vdst, Vsrc, p, conjsrc, levels) device_treetransposer(A, Vdst, Vsrc, p, conjsrc) - device_treepermuter(A, Vdst, Vsrc, p, conjsrc, twistmask) device_treetracer(A, Vdst, Vsrc, p, q) device_treetwister(A, Vdst, Vsrc, p, conjsrc, twistmask, inv) Tree transformers for device storage types `A`, to which `treebraider`, `treetransposer`, -`treepermuter`, `treetracer` and `treetwister` forward. Their methods are added by package extensions. Being +`treetracer` and `treetwister` forward. Their methods are added by package extensions. Being separate functions, the device transformers have their own caches, which can be configured independently of the host ones. """ function device_treebraider end function device_treetransposer end -function device_treepermuter end function device_treetracer end function device_treetwister end @doc (@doc device_treebraider) device_treetransposer -@doc (@doc device_treebraider) device_treepermuter @doc (@doc device_treebraider) device_treetracer @doc (@doc device_treebraider) device_treetwister # Keep TensorKit's profiling categories for the phases instrumented by MemoizationKit. const TensorKitCachedFunction = Union{ typeof(fusiontreebraid), typeof(fusiontreetranspose), - typeof(treebraider), typeof(treetransposer), typeof(treepermuter), typeof(treetracer), typeof(treetwister), - typeof(device_treebraider), typeof(device_treetransposer), typeof(device_treepermuter), typeof(device_treetracer), typeof(device_treetwister), + typeof(treebraider), typeof(treetransposer), typeof(treetracer), typeof(treetwister), + typeof(device_treebraider), typeof(device_treetransposer), typeof(device_treetracer), typeof(device_treetwister), typeof(sectorstructure), typeof(degeneracystructure), } MemoizationKit.instrument_label(f::TensorKitCachedFunction, ::Val{:lookup}) = "bookkeeping: cache $(nameof(f))" From 0e856de383109313af1f588212c83a26a3c0ec13 Mon Sep 17 00:00:00 2001 From: Jutho <4162102+Jutho@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:17:58 +0000 Subject: [PATCH 3/4] Fix treebraider calls in cache tests Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- test/other/caches.jl | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/other/caches.jl b/test/other/caches.jl index 269cb5c91..1c6d73c0d 100644 --- a/test/other/caches.jl +++ b/test/other/caches.jl @@ -25,7 +25,8 @@ end V = GradedSpace{I}(labels[1] => 2, labels[2] => 2) W = V ⊗ V ← V ⊗ V p, levels = ((2, 1), (4, 3)), (1, 2, 3, 4) - transformer = TensorKit.treebraider(Vector{Float64}, W, W, p, false, levels) + twistmask = (false, false, false, false) + transformer = TensorKit.treebraider(Vector{Float64}, W, W, p, false, levels, twistmask) for value in (sectorstructure(W), degeneracystructure(W), transformer) bytes = @constinferred MemoizationKit.cachesize(value) @test 0 < bytes <= Base.summarysize(value) @@ -39,8 +40,8 @@ end # retain its own size budget even if the degeneracy cache has been cleared. MemoizationKit.set_cache_size!(TensorKit.treebraider, MemoizationKit.cachesize(transformer); by = MemoizationKit.cachesize) try - TensorKit.treebraider(Vector{Float64}, W, W, p, false, levels) - TensorKit.treebraider(Vector{Float64}, W, W, ((1, 2), (3, 4)), false, levels) + TensorKit.treebraider(Vector{Float64}, W, W, p, false, levels, twistmask) + TensorKit.treebraider(Vector{Float64}, W, W, ((1, 2), (3, 4)), false, levels, twistmask) MemoizationKit.empty_caches!(degeneracystructure) cache = only(MemoizationKit.cache_info(TensorKit.treebraider)).second stats = MemoizationKit.cache_stats(cache) @@ -51,7 +52,7 @@ end MemoizationKit.set_cache_size!(TensorKit.treebraider, 0; by = MemoizationKit.cachesize) @test isempty(cache) - @test TensorKit.treebraider(Vector{Float64}, W, W, p, false, levels).data == transformer.data + @test TensorKit.treebraider(Vector{Float64}, W, W, p, false, levels, twistmask).data == transformer.data @test isempty(cache) finally MemoizationKit.set_cache_size!(TensorKit.treebraider, 10_000) From 04250d7c1bdccd58251a5583c06df2ca8d5174ba Mon Sep 17 00:00:00 2001 From: Jutho Haegeman Date: Sat, 21 Nov 2026 00:40:13 +0100 Subject: [PATCH 4/4] Forward `twistmask` in the GPU `treebraider` method The GPU method still had the old six-argument signature, so the new seven-argument call from `_braid!` fell back to the host `treebraider` and built a host transformer for GPU storage, which `add_transform_kernel!` in the GPU extension does not accept. Co-Authored-By: Claude Opus 5.5 --- ext/TensorKitGPUArraysExt.jl | 4 ++-- src/tensors/treetransformers.jl | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ext/TensorKitGPUArraysExt.jl b/ext/TensorKitGPUArraysExt.jl index b125f6654..df719f061 100644 --- a/ext/TensorKitGPUArraysExt.jl +++ b/ext/TensorKitGPUArraysExt.jl @@ -374,8 +374,8 @@ end TensorKit.treebraider( A::Type{<:AnyGPUVector}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, - conjsrc::Bool, levels::IndexTuple -) = TensorKit.device_treebraider(A, Vdst, Vsrc, p, conjsrc, levels) + conjsrc::Bool, levels::IndexTuple, twistmask::NTuple{N, Bool} +) where {N} = TensorKit.device_treebraider(A, Vdst, Vsrc, p, conjsrc, levels, twistmask) TensorKit.treetransposer( A::Type{<:AnyGPUVector}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, conjsrc::Bool ) = TensorKit.device_treetransposer(A, Vdst, Vsrc, p, conjsrc) diff --git a/src/tensors/treetransformers.jl b/src/tensors/treetransformers.jl index 3ccfe1af1..37d9df181 100644 --- a/src/tensors/treetransformers.jl +++ b/src/tensors/treetransformers.jl @@ -358,7 +358,7 @@ end end """ - device_treebraider(A, Vdst, Vsrc, p, conjsrc, levels) + device_treebraider(A, Vdst, Vsrc, p, conjsrc, levels, twistmask) device_treetransposer(A, Vdst, Vsrc, p, conjsrc) device_treetracer(A, Vdst, Vsrc, p, q) device_treetwister(A, Vdst, Vsrc, p, conjsrc, twistmask, inv)