From 52f501725c270314ec534e5a4940e988b2dc3bf6 Mon Sep 17 00:00:00 2001 From: lkdvos Date: Wed, 28 Oct 2026 08:42:36 -0400 Subject: [PATCH 01/11] 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 02/11] 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 03/11] 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 04/11] 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) From d17e80e2fad084a9b8df91808fb84a7ce08e063c Mon Sep 17 00:00:00 2001 From: lkdvos Date: Mon, 9 Nov 2026 10:19:56 -0500 Subject: [PATCH 05/11] Convert twist indices to a mask and forward backend/allocator in AD rules Follow-up to the review comments on #599: - `twist`/`twist!` convert `inds` to an `NTuple{numind, Bool}` mask on entry, dispatching to a mask method, which also removes the ambiguity workaround in `spacecheck_transform` and lets tensors accept a mask like fusion trees do. - Enzyme and Mooncake rules for `permute!`/`transpose!`/`braid!`/`twist!` forward `backend` and `allocator` to the intermediate out-of-place call, which now also always copies. Co-Authored-By: Claude Opus 5.5 --- docs/src/Changelog.md | 4 ++ ext/TensorKitEnzymeExt/indexmanipulations.jl | 9 ++-- .../indexmanipulations.jl | 6 +-- src/fusiontrees/braiding_manipulations.jl | 18 +++++-- src/pullbacks/indexmanipulations.jl | 5 ++ src/tensors/indexmanipulations.jl | 48 ++++++++++++------- 6 files changed, 64 insertions(+), 26 deletions(-) diff --git a/docs/src/Changelog.md b/docs/src/Changelog.md index 6d5d66292..152b50d33 100644 --- a/docs/src/Changelog.md +++ b/docs/src/Changelog.md @@ -28,6 +28,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec ### Changed +- `twist` and `twist!` on tensors also accept a `Bool` mask over all indices, like the fusion tree `twist`; any collection of indices is converted to such a mask first, so the rest of the implementation is compiled once per number of indices - `planartrace!` precomputes and caches a `TraceTransformer` with the subblock positions and recoupling coefficients, and executes it with a kernel shared by all sectortypes, analogous to the index manipulations; `planar_trace` is now also defined for `FusionTreeBlock`s, and GPU tensors use a dedicated kernel (internal) - Caching is provided by [MemoizationKit.jl](https://github.com/QuantumKitHub/MemoizationKit.jl), which can inspect, resize and configure TensorKit's caches, also by memory size; this replaces the internal `@cached` machinery and the LRUCache.jl dependency @@ -37,6 +38,9 @@ When releasing a new version, move the "Unreleased" changes to a new version sec ### Fixed +- The Enzyme and Mooncake rules of `permute!`, `transpose!`, `braid!` and `twist!` forward the `backend` and `allocator` to the intermediate out-of-place call, which now also always copies +- `twist` of a fusion tree pair or block throws for a `Bool` mask of the wrong length, instead of interpreting it as indices + ### 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)) diff --git a/ext/TensorKitEnzymeExt/indexmanipulations.jl b/ext/TensorKitEnzymeExt/indexmanipulations.jl index 9908ede18..17bb6b783 100644 --- a/ext/TensorKitEnzymeExt/indexmanipulations.jl +++ b/ext/TensorKitEnzymeExt/indexmanipulations.jl @@ -21,7 +21,8 @@ for transform in (:permute, :transpose) # without copy=true, this may just alias A if # the permutation is an identity or the space # is Trivial and has_shared_permute is true - Ap = $transform(A.val, p.val; copy = true) + bavs = map(a -> a.val, ba) + Ap = $transform(A.val, p.val; copy = true, TK.backend_kwargs(bavs...)...) add!(C.val, Ap, α.val, β.val) Ap else @@ -113,7 +114,8 @@ function EnzymeRules.augmented_primal( # and store that instead of repeating the permutation in the pullback each time. # effectively, we replace `add_permute` by `add ∘ permute`. Ap = if !isa(α, Const) - Ap = braid(A.val, p.val, levels.val) + bavs = map(a -> a.val, ba) + Ap = braid(A.val, p.val, levels.val; copy = true, TK.backend_kwargs(bavs...)...) add!(C.val, Ap, α.val, β.val) Ap else @@ -204,7 +206,8 @@ function EnzymeRules.augmented_primal( # and store that instead of repeating the twist in the pullback each time. # effectively, we replace `twist!` by `add ∘ twist`. Ap = if !isa(α, Const) - Ap = twist(A.val, inds.val; inv, copy = true) + bavs = map(a -> a.val, ba) + Ap = twist(A.val, inds.val; inv, copy = true, TK.backend_kwargs(bavs...)...) add!(C.val, Ap, α.val, β.val) Ap else diff --git a/ext/TensorKitMooncakeExt/indexmanipulations.jl b/ext/TensorKitMooncakeExt/indexmanipulations.jl index cd7dd63be..56e968035 100644 --- a/ext/TensorKitMooncakeExt/indexmanipulations.jl +++ b/ext/TensorKitMooncakeExt/indexmanipulations.jl @@ -33,7 +33,7 @@ for transform in (:permute, :transpose) # and store that instead of repeating the permutation in the pullback each time. # effectively, we replace `permute!/transpose!` by `add ∘ permute/transpose`. Ap = if _needs_tangent(α) - Ap = $transform(A, p) + Ap = $transform(A, p; copy = true, TK.backend_kwargs(ba...)...) add!(C, Ap, α, β) Ap else @@ -91,7 +91,7 @@ function Mooncake.rrule!!( # and store that instead of repeating the permutation in the pullback each time. # effectively, we replace `braid!` by `add ∘ braid`. Ap = if _needs_tangent(α) - Ap = braid(A, p, levels) + Ap = braid(A, p, levels; copy = true, TK.backend_kwargs(ba...)...) add!(C, Ap, α, β) Ap else @@ -222,7 +222,7 @@ function twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, inv, args_Δargs) # and store that instead of repeating the twist in the pullback each time. # effectively, we replace `twist!` by `add ∘ twist`. Ap = if _needs_tangent(α) - Ap = twist(A, inds; inv, copy = true) + Ap = twist(A, inds; inv, copy = true, TK.backend_kwargs(ba...)...) add!(C, Ap, α, β) Ap else diff --git a/src/fusiontrees/braiding_manipulations.jl b/src/fusiontrees/braiding_manipulations.jl index 9152319ff..79fe4c068 100644 --- a/src/fusiontrees/braiding_manipulations.jl +++ b/src/fusiontrees/braiding_manipulations.jl @@ -396,19 +396,31 @@ function permute(src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple) return braid(src, p, (levels1, levels2)) end +# convert the indices to twist into a mask over all `N` indices, such that the code +# after this conversion is compiled only once for every `N` +function _twistmask(::Val{N}, mask::Tuple{Bool, Vararg{Bool}}) where {N} + length(mask) == N || + throw(ArgumentError(lazy"twist mask $mask does not match the number of indices $N")) + return mask +end +function _twistmask(::Val{N}, inds) where {N} + all(i -> 1 <= i <= N, inds) || + throw(ArgumentError(lazy"Can't twist indices $inds of an object with only $N indices.")) + return ntuple(i -> i in inds, N) +end + """ twist(src::Union{FusionTreePair, FusionTreeBlock}, inds; inv::Bool = false) -> (src, θ) Apply a twist to the uncoupled legs `inds` of the fusion-splitting tree pair or block `src`, -where `inds` is either a collection of leg indices or an `NTuple{N, Bool}` mask over all legs. +where `inds` is either a collection of leg indices or an `NTuple{N, Bool}` mask over all `N` legs. The twist is diagonal in the fusion tree basis, so this returns `src` itself together with the scalar factor `θ`, which is shared by all trees in a block. If `inv = true`, use the inverse twist. """ function twist(src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, inds; inv::Bool = false) where {I} uncoupled₁, uncoupled₂ = src isa FusionTreeBlock ? src.uncoupled : (src[1].uncoupled, src[2].uncoupled) uncoupled = (uncoupled₁..., uncoupled₂...) - N = length(uncoupled) - mask = inds isa NTuple{N, Bool} ? inds : ntuple(i -> i in inds, N) + mask = _twistmask(Val(length(uncoupled)), inds) θ = prod(map((m, a) -> m ? twist(a) : one(twist(a)), mask, uncoupled); init = one(sectorscalartype(I))) return src, inv ? θ' : θ end diff --git a/src/pullbacks/indexmanipulations.jl b/src/pullbacks/indexmanipulations.jl index 0cfe57c37..2281687c6 100644 --- a/src/pullbacks/indexmanipulations.jl +++ b/src/pullbacks/indexmanipulations.jl @@ -1,3 +1,8 @@ +# the optional positional `backend` and `allocator` as keywords for the out-of-place methods +backend_kwargs() = (;) +backend_kwargs(backend) = (; backend) +backend_kwargs(backend, allocator) = (; backend, allocator) + for transform in (:permute, :transpose) transform! = Symbol(transform, :!) transform_pb = Symbol(transform, :_pullback_dA) diff --git a/src/tensors/indexmanipulations.jl b/src/tensors/indexmanipulations.jl index 1b768de52..39e8dff5e 100644 --- a/src/tensors/indexmanipulations.jl +++ b/src/tensors/indexmanipulations.jl @@ -31,10 +31,13 @@ end # --------- # twist(!) # --------- -function has_shared_twist(t, inds) +_twistmask(t::AbstractTensorMap, inds) = _twistmask(Val(numind(t)), inds) + +function has_shared_twist(t, mask::Tuple{Vararg{Bool}}) I = sectortype(t) if BraidingStyle(I) == NoBraiding() - for i in inds + for i in 1:length(mask) + mask[i] || continue cs = sectors(space(t, i)) all(isunit, cs) || throw(SectorMismatch(lazy"Cannot twist sectors $cs")) end @@ -42,7 +45,8 @@ function has_shared_twist(t, inds) elseif BraidingStyle(I) == Bosonic() return true else - for i in inds + for i in 1:length(mask) + mask[i] || continue cs = sectors(space(t, i)) all(isone ∘ twist, cs) || return false end @@ -55,6 +59,7 @@ end twist!(t::AbstractTensorMap, inds; inv::Bool = false) -> t Apply a twist to the `i`th index of `t`, or all indices in `inds`, storing the result in `t`. +Here, `inds` is either a collection of indices or an `NTuple{numind(t), Bool}` mask over all indices. If `inv=true`, use the inverse twist. twist!(tdst, tsrc, inds, α = 1, β = 0, [backend], [allocator]; inv::Bool = false) -> tdst @@ -65,12 +70,12 @@ Optionally specify a `backend` and `allocator` for the underlying array operatio See [`twist`](@ref) for creating a new tensor. """ function twist!(t::AbstractTensorMap, inds; inv::Bool = false) - spacecheck_transform(twist, space(t), space(t), inds) + mask = _twistmask(t, inds) (scalartype(t) <: Real && !(sectorscalartype(sectortype(t)) <: Real)) && throw(ArgumentError("Can't in-place twist a real tensor with complex sector type")) - has_shared_twist(t, inds) && return t + has_shared_twist(t, mask) && return t # returning `t` rather than the result of `twist!` avoids an Enzyme crash on Julia 1.10 - @inbounds twist!(t, t, inds, One(), Zero(); inv) + @inbounds twist!(t, t, mask, One(), Zero(); inv) return t end @propagate_inbounds function twist!( @@ -79,9 +84,17 @@ end backend::AbstractBackend = TO.DefaultBackend(), allocator = TO.DefaultAllocator(); inv::Bool = false ) - @boundscheck spacecheck_transform(twist, space(tdst), space(tsrc), inds) + return twist!(tdst, tsrc, _twistmask(tsrc, inds), α, β, backend, allocator; inv) +end +@propagate_inbounds function twist!( + tdst::AbstractTensorMap, tsrc::AbstractTensorMap, mask::Tuple{Vararg{Bool}}, + α::Number = One(), β::Number = Zero(), + backend::AbstractBackend = TO.DefaultBackend(), allocator = TO.DefaultAllocator(); + inv::Bool = false + ) + twistmask = _twistmask(tsrc, mask) # checks the length, and maps an empty `inds` onto a mask + @boundscheck spacecheck_transform(twist, space(tdst), space(tsrc), twistmask) @timeit_debug GLOBAL_TIMER "twist!" begin - twistmask = ntuple(i -> i in inds, numind(tsrc)) p = (codomainind(tsrc), domainind(tsrc)) tdst′, tsrc′, p′, twistmask′, conjsrc′, α′, β′ = unwrap_adjoints(tdst, tsrc, p, twistmask, false, α, β) # like `α`, the twist is conjugated by an adjoint destination @@ -98,6 +111,7 @@ end ) -> tdst Apply a twist to the `i`th index of `tsrc`, or all indices in `inds`, and return the result as a new tensor. +Here, `inds` is either a collection of indices or an `NTuple{numind(tsrc), Bool}` mask over all indices. If `inv = true`, use the inverse twist. If `copy = false`, `tdst` might share data with `tsrc` whenever possible. Otherwise, a copy is always made. Optionally specify a `backend` and `allocator` for the underlying array operation. @@ -108,11 +122,12 @@ function twist( t::AbstractTensorMap, inds; inv::Bool = false, copy::Bool = false, backend::AbstractBackend = TO.DefaultBackend(), allocator = TO.DefaultAllocator() ) - has_shared_twist(t, inds) && return copy ? Base.copy(t) : t + mask = _twistmask(t, inds) + has_shared_twist(t, mask) && return copy ? Base.copy(t) : t # general case tdst = similar(t, promote_twist(t)) - return @inbounds twist!(tdst, t, inds, One(), Zero(), backend, allocator; inv) + return @inbounds twist!(tdst, t, mask, One(), Zero(), backend, allocator; inv) end # ========================= @@ -545,15 +560,17 @@ end Vsrc′, p′ = conjsrc ? (Vsrc', adjointtensorindices(Vsrc, p)) : (Vsrc, p) return spacecheck_transform(f, Vdst, Vsrc′, p′) end -@noinline function spacecheck_transform(::typeof(twist), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, inds) +@noinline function spacecheck_transform( + ::typeof(twist), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, mask::Tuple{Vararg{Bool}} + ) check_spacetype(Vdst, Vsrc) - all(in(allind(Vsrc)), inds) || - throw(ArgumentError(lazy"Can't twist indices $inds of a tensor with only $(numind(Vsrc)) indices.")) + length(mask) == numind(Vsrc) || + throw(ArgumentError(lazy"twist mask $mask does not match the number of indices $(numind(Vsrc))")) Vdst == Vsrc || throw( SpaceMismatch( lazy""" - incompatible spaces for `twist(Vsrc, $inds) -> Vdst` + incompatible spaces for `twist(Vsrc, $mask) -> Vdst` Vsrc = $Vsrc Vdst = $Vdst """ @@ -561,9 +578,6 @@ end ) return nothing end -# disambiguation with the generic method -spacecheck_transform(f::typeof(twist), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, inds::Index2Tuple) = - invoke(spacecheck_transform, Tuple{typeof(twist), TensorMapSpace, TensorMapSpace, Any}, f, Vdst, Vsrc, inds) @noinline function spacecheck_transform(::typeof(braid), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, levels::IndexTuple) check_spacetype(Vdst, Vsrc) braid(Vsrc, p, levels) == Vdst || From 11ba909607c2cb2970b9b11e01be1fe1c74d6d0c Mon Sep 17 00:00:00 2001 From: lkdvos Date: Mon, 9 Nov 2026 10:35:59 -0500 Subject: [PATCH 06/11] Fix formatting Co-Authored-By: Claude Opus 5.5 --- src/tensors/indexmanipulations.jl | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/tensors/indexmanipulations.jl b/src/tensors/indexmanipulations.jl index 39e8dff5e..f2b68d2ac 100644 --- a/src/tensors/indexmanipulations.jl +++ b/src/tensors/indexmanipulations.jl @@ -560,9 +560,7 @@ end Vsrc′, p′ = conjsrc ? (Vsrc', adjointtensorindices(Vsrc, p)) : (Vsrc, p) return spacecheck_transform(f, Vdst, Vsrc′, p′) end -@noinline function spacecheck_transform( - ::typeof(twist), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, mask::Tuple{Vararg{Bool}} - ) +@noinline function spacecheck_transform(::typeof(twist), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, mask::Tuple{Vararg{Bool}}) check_spacetype(Vdst, Vsrc) length(mask) == numind(Vsrc) || throw(ArgumentError(lazy"twist mask $mask does not match the number of indices $(numind(Vsrc))")) From b62e91076334cefc293b2578a2e1108e668a39cd Mon Sep 17 00:00:00 2001 From: lkdvos Date: Mon, 9 Nov 2026 11:55:35 -0500 Subject: [PATCH 07/11] Keep the twist spacecheck message line unchanged for git-runic Co-Authored-By: Claude Opus 5.5 --- src/tensors/indexmanipulations.jl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/tensors/indexmanipulations.jl b/src/tensors/indexmanipulations.jl index f2b68d2ac..a7b9e331e 100644 --- a/src/tensors/indexmanipulations.jl +++ b/src/tensors/indexmanipulations.jl @@ -560,15 +560,15 @@ end Vsrc′, p′ = conjsrc ? (Vsrc', adjointtensorindices(Vsrc, p)) : (Vsrc, p) return spacecheck_transform(f, Vdst, Vsrc′, p′) end -@noinline function spacecheck_transform(::typeof(twist), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, mask::Tuple{Vararg{Bool}}) +@noinline function spacecheck_transform(::typeof(twist), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, inds::Tuple{Vararg{Bool}}) check_spacetype(Vdst, Vsrc) - length(mask) == numind(Vsrc) || - throw(ArgumentError(lazy"twist mask $mask does not match the number of indices $(numind(Vsrc))")) + length(inds) == numind(Vsrc) || + throw(ArgumentError(lazy"twist mask $inds does not match the number of indices $(numind(Vsrc))")) Vdst == Vsrc || throw( SpaceMismatch( lazy""" - incompatible spaces for `twist(Vsrc, $mask) -> Vdst` + incompatible spaces for `twist(Vsrc, $inds) -> Vdst` Vsrc = $Vsrc Vdst = $Vdst """ From 350321b033c1c686689c04d112faea6b09feb749 Mon Sep 17 00:00:00 2001 From: lkdvos Date: Mon, 9 Nov 2026 12:11:24 -0500 Subject: [PATCH 08/11] Write out backend/allocator keywords in the AD rules instead of a helper Co-Authored-By: Claude Opus 5.5 --- ext/TensorKitEnzymeExt/indexmanipulations.jl | 15 +++++++++------ ext/TensorKitMooncakeExt/indexmanipulations.jl | 12 +++++++++--- src/pullbacks/indexmanipulations.jl | 5 ----- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/ext/TensorKitEnzymeExt/indexmanipulations.jl b/ext/TensorKitEnzymeExt/indexmanipulations.jl index 17bb6b783..bdcb91031 100644 --- a/ext/TensorKitEnzymeExt/indexmanipulations.jl +++ b/ext/TensorKitEnzymeExt/indexmanipulations.jl @@ -21,8 +21,9 @@ for transform in (:permute, :transpose) # without copy=true, this may just alias A if # the permutation is an identity or the space # is Trivial and has_shared_permute is true - bavs = map(a -> a.val, ba) - Ap = $transform(A.val, p.val; copy = true, TK.backend_kwargs(bavs...)...) + backend = get(ba, 1, Const(TO.DefaultBackend())).val + allocator = get(ba, 2, Const(TO.DefaultAllocator())).val + Ap = $transform(A.val, p.val; copy = true, backend, allocator) add!(C.val, Ap, α.val, β.val) Ap else @@ -114,8 +115,9 @@ function EnzymeRules.augmented_primal( # and store that instead of repeating the permutation in the pullback each time. # effectively, we replace `add_permute` by `add ∘ permute`. Ap = if !isa(α, Const) - bavs = map(a -> a.val, ba) - Ap = braid(A.val, p.val, levels.val; copy = true, TK.backend_kwargs(bavs...)...) + backend = get(ba, 1, Const(TO.DefaultBackend())).val + allocator = get(ba, 2, Const(TO.DefaultAllocator())).val + Ap = braid(A.val, p.val, levels.val; copy = true, backend, allocator) add!(C.val, Ap, α.val, β.val) Ap else @@ -206,8 +208,9 @@ function EnzymeRules.augmented_primal( # and store that instead of repeating the twist in the pullback each time. # effectively, we replace `twist!` by `add ∘ twist`. Ap = if !isa(α, Const) - bavs = map(a -> a.val, ba) - Ap = twist(A.val, inds.val; inv, copy = true, TK.backend_kwargs(bavs...)...) + backend = get(ba, 1, Const(TO.DefaultBackend())).val + allocator = get(ba, 2, Const(TO.DefaultAllocator())).val + Ap = twist(A.val, inds.val; inv, copy = true, backend, allocator) add!(C.val, Ap, α.val, β.val) Ap else diff --git a/ext/TensorKitMooncakeExt/indexmanipulations.jl b/ext/TensorKitMooncakeExt/indexmanipulations.jl index 56e968035..d57109e20 100644 --- a/ext/TensorKitMooncakeExt/indexmanipulations.jl +++ b/ext/TensorKitMooncakeExt/indexmanipulations.jl @@ -33,7 +33,9 @@ for transform in (:permute, :transpose) # and store that instead of repeating the permutation in the pullback each time. # effectively, we replace `permute!/transpose!` by `add ∘ permute/transpose`. Ap = if _needs_tangent(α) - Ap = $transform(A, p; copy = true, TK.backend_kwargs(ba...)...) + backend = get(ba, 1, TO.DefaultBackend()) + allocator = get(ba, 2, TO.DefaultAllocator()) + Ap = $transform(A, p; copy = true, backend, allocator) add!(C, Ap, α, β) Ap else @@ -91,7 +93,9 @@ function Mooncake.rrule!!( # and store that instead of repeating the permutation in the pullback each time. # effectively, we replace `braid!` by `add ∘ braid`. Ap = if _needs_tangent(α) - Ap = braid(A, p, levels; copy = true, TK.backend_kwargs(ba...)...) + backend = get(ba, 1, TO.DefaultBackend()) + allocator = get(ba, 2, TO.DefaultAllocator()) + Ap = braid(A, p, levels; copy = true, backend, allocator) add!(C, Ap, α, β) Ap else @@ -222,7 +226,9 @@ function twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, inv, args_Δargs) # and store that instead of repeating the twist in the pullback each time. # effectively, we replace `twist!` by `add ∘ twist`. Ap = if _needs_tangent(α) - Ap = twist(A, inds; inv, copy = true, TK.backend_kwargs(ba...)...) + backend = get(ba, 1, TO.DefaultBackend()) + allocator = get(ba, 2, TO.DefaultAllocator()) + Ap = twist(A, inds; inv, copy = true, backend, allocator) add!(C, Ap, α, β) Ap else diff --git a/src/pullbacks/indexmanipulations.jl b/src/pullbacks/indexmanipulations.jl index 2281687c6..0cfe57c37 100644 --- a/src/pullbacks/indexmanipulations.jl +++ b/src/pullbacks/indexmanipulations.jl @@ -1,8 +1,3 @@ -# the optional positional `backend` and `allocator` as keywords for the out-of-place methods -backend_kwargs() = (;) -backend_kwargs(backend) = (; backend) -backend_kwargs(backend, allocator) = (; backend, allocator) - for transform in (:permute, :transpose) transform! = Symbol(transform, :!) transform_pb = Symbol(transform, :_pullback_dA) From 940b97ab7fa9b59deb541bbb4a83c02a5290663d Mon Sep 17 00:00:00 2001 From: lkdvos Date: Mon, 9 Nov 2026 13:00:16 -0500 Subject: [PATCH 09/11] Take explicit backend and allocator arguments in the Enzyme index manipulation rules Co-Authored-By: Claude Opus 5.5 --- ext/TensorKitEnzymeExt/indexmanipulations.jl | 75 ++++++++------------ 1 file changed, 30 insertions(+), 45 deletions(-) diff --git a/ext/TensorKitEnzymeExt/indexmanipulations.jl b/ext/TensorKitEnzymeExt/indexmanipulations.jl index bdcb91031..a589a5644 100644 --- a/ext/TensorKitEnzymeExt/indexmanipulations.jl +++ b/ext/TensorKitEnzymeExt/indexmanipulations.jl @@ -10,7 +10,7 @@ for transform in (:permute, :transpose) p::Const{<:Index2Tuple}, α::Annotation{<:Number}, β::Annotation{<:Number}, - ba::Const... + backend::Const, allocator::Const ) where {RT} C_cache = !isa(β, Const) ? copy(C.val) : nothing A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing @@ -21,14 +21,11 @@ for transform in (:permute, :transpose) # without copy=true, this may just alias A if # the permutation is an identity or the space # is Trivial and has_shared_permute is true - backend = get(ba, 1, Const(TO.DefaultBackend())).val - allocator = get(ba, 2, Const(TO.DefaultAllocator())).val - Ap = $transform(A.val, p.val; copy = true, backend, allocator) + Ap = $transform(A.val, p.val; copy = true, backend = backend.val, allocator = allocator.val) add!(C.val, Ap, α.val, β.val) Ap else - bavs = map(a -> a.val, ba) - TK.$transform!(C.val, A.val, p.val, α.val, β.val, bavs...) + TK.$transform!(C.val, A.val, p.val, α.val, β.val, backend.val, allocator.val) nothing end cache = (C_cache, A_cache, Ap) @@ -46,20 +43,19 @@ for transform in (:permute, :transpose) p::Const{<:Index2Tuple}, α::Annotation{<:Number}, β::Annotation{<:Number}, - ba::Const... + backend::Const, allocator::Const ) where {RT} C_cache, A_cache, Ap = cache Cval = something(C_cache, C.val) - bavs = map(a -> a.val, ba) # ΔA if !isa(A, Const) && !isa(C, Const) Aval = something(A_cache, A.val) - TK.$transform_pb(A.dval, Aval, C.dval, C.val, p.val, α.val, bavs...) + TK.$transform_pb(A.dval, Aval, C.dval, C.val, p.val, α.val, backend.val, allocator.val) end Δα = pullback_dα(α, C, Ap) Δβ = pullback_dβ(β, C, Cval) !isa(C, Const) && pullback_dC!(C.dval, β.val) - return nothing, nothing, nothing, Δα, Δβ, map(Returns(nothing), ba)... + return nothing, nothing, nothing, Δα, Δβ, nothing, nothing end @eval function EnzymeRules.forward( config::EnzymeRules.FwdConfigWidth{1}, @@ -70,19 +66,18 @@ for transform in (:permute, :transpose) p::Annotation{<:Index2Tuple}, α::Annotation{<:Number}, β::Annotation{<:Number}, - ba::Const... + backend::Const, allocator::Const ) where {RT} - bavs = map(a -> a.val, ba) if !isa(C, Const) if isa(β, Const) scale!(C.dval, β.val) else add!(C.dval, C.val, β.dval, β.val) end - !isa(α, Const) && TK.$transform!(C.dval, A.val, p.val, α.dval, One(), bavs...) - !isa(A, Const) && TK.$transform!(C.dval, A.dval, p.val, α.val, One(), bavs...) + !isa(α, Const) && TK.$transform!(C.dval, A.val, p.val, α.dval, One(), backend.val, allocator.val) + !isa(A, Const) && TK.$transform!(C.dval, A.dval, p.val, α.val, One(), backend.val, allocator.val) end - TK.$transform!(C.val, A.val, p.val, α.val, β.val, bavs...) + TK.$transform!(C.val, A.val, p.val, α.val, β.val, backend.val, allocator.val) if EnzymeRules.needs_primal(config) && EnzymeRules.needs_shadow(config) return C elseif EnzymeRules.needs_primal(config) @@ -107,7 +102,7 @@ function EnzymeRules.augmented_primal( levels::Const{<:IndexTuple}, α::Annotation{<:Number}, β::Annotation{<:Number}, - ba::Const... + backend::Const, allocator::Const ) where {RT} C_cache = !isa(β, Const) ? copy(C.val) : nothing A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing @@ -115,14 +110,11 @@ function EnzymeRules.augmented_primal( # and store that instead of repeating the permutation in the pullback each time. # effectively, we replace `add_permute` by `add ∘ permute`. Ap = if !isa(α, Const) - backend = get(ba, 1, Const(TO.DefaultBackend())).val - allocator = get(ba, 2, Const(TO.DefaultAllocator())).val - Ap = braid(A.val, p.val, levels.val; copy = true, backend, allocator) + Ap = braid(A.val, p.val, levels.val; copy = true, backend = backend.val, allocator = allocator.val) add!(C.val, Ap, α.val, β.val) Ap else - bavs = map(a -> a.val, ba) - TK.braid!(C.val, A.val, p.val, levels.val, α.val, β.val, bavs...) + TK.braid!(C.val, A.val, p.val, levels.val, α.val, β.val, backend.val, allocator.val) nothing end cache = (C_cache, A_cache, Ap) @@ -141,20 +133,19 @@ function EnzymeRules.reverse( levels::Const{<:IndexTuple}, α::Annotation{<:Number}, β::Annotation{<:Number}, - ba::Const... + backend::Const, allocator::Const ) where {RT} C_cache, A_cache, Ap = cache Cval = something(C_cache, C.val) Aval = something(A_cache, A.val) - bavs = map(a -> a.val, ba) # ΔA if !isa(A, Const) && !isa(C, Const) - TK.braid_pb(A.dval, Aval, C.dval, C.val, p.val, levels.val, α.val, bavs...) + TK.braid_pb(A.dval, Aval, C.dval, C.val, p.val, levels.val, α.val, backend.val, allocator.val) end Δαr = pullback_dα(α, C, Ap) Δβr = pullback_dβ(β, C, Cval) !isa(C, Const) && pullback_dC!(C.dval, β.val) - return nothing, nothing, nothing, nothing, Δαr, Δβr, map(Returns(nothing), ba)... + return nothing, nothing, nothing, nothing, Δαr, Δβr, nothing, nothing end function EnzymeRules.forward( config::EnzymeRules.FwdConfigWidth{1}, @@ -166,19 +157,18 @@ function EnzymeRules.forward( levels::Annotation{<:IndexTuple}, α::Annotation{<:Number}, β::Annotation{<:Number}, - ba::Const... + backend::Const, allocator::Const ) where {RT} - bavs = map(a -> a.val, ba) if !isa(C, Const) if isa(β, Const) scale!(C.dval, β.val) else add!(C.dval, C.val, β.dval, β.val) end - !isa(α, Const) && TK.braid!(C.dval, A.val, p.val, levels.val, α.dval, One(), bavs...) - !isa(A, Const) && TK.braid!(C.dval, A.dval, p.val, levels.val, α.val, One(), bavs...) + !isa(α, Const) && TK.braid!(C.dval, A.val, p.val, levels.val, α.dval, One(), backend.val, allocator.val) + !isa(A, Const) && TK.braid!(C.dval, A.dval, p.val, levels.val, α.val, One(), backend.val, allocator.val) end - TK.braid!(C.val, A.val, p.val, levels.val, α.val, β.val, bavs...) + TK.braid!(C.val, A.val, p.val, levels.val, α.val, β.val, backend.val, allocator.val) if EnzymeRules.needs_primal(config) && EnzymeRules.needs_shadow(config) return C elseif EnzymeRules.needs_primal(config) @@ -199,7 +189,7 @@ function EnzymeRules.augmented_primal( inds::Const, α::Annotation{<:Number}, β::Annotation{<:Number}, - ba::Const...; + backend::Const, allocator::Const; inv::Bool = false ) where {RT} C_cache = !isa(β, Const) ? copy(C.val) : nothing @@ -208,14 +198,11 @@ function EnzymeRules.augmented_primal( # and store that instead of repeating the twist in the pullback each time. # effectively, we replace `twist!` by `add ∘ twist`. Ap = if !isa(α, Const) - backend = get(ba, 1, Const(TO.DefaultBackend())).val - allocator = get(ba, 2, Const(TO.DefaultAllocator())).val - Ap = twist(A.val, inds.val; inv, copy = true, backend, allocator) + Ap = twist(A.val, inds.val; inv, copy = true, backend = backend.val, allocator = allocator.val) add!(C.val, Ap, α.val, β.val) Ap else - bavs = map(a -> a.val, ba) - TK.twist!(C.val, A.val, inds.val, α.val, β.val, bavs...; inv) + TK.twist!(C.val, A.val, inds.val, α.val, β.val, backend.val, allocator.val; inv) nothing end cache = (C_cache, A_cache, Ap) @@ -233,21 +220,20 @@ function EnzymeRules.reverse( inds::Const, α::Annotation{<:Number}, β::Annotation{<:Number}, - ba::Const...; + backend::Const, allocator::Const; inv::Bool = false ) where {RT} C_cache, A_cache, Ap = cache Cval = something(C_cache, C.val) Aval = something(A_cache, A.val) - bavs = map(a -> a.val, ba) # ΔA if !isa(A, Const) && !isa(C, Const) - TK.twist_pb(A.dval, Aval, C.dval, C.val, inds.val, α.val, bavs...; inv) + TK.twist_pb(A.dval, Aval, C.dval, C.val, inds.val, α.val, backend.val, allocator.val; inv) end Δαr = pullback_dα(α, C, Ap) Δβr = pullback_dβ(β, C, Cval) !isa(C, Const) && pullback_dC!(C.dval, β.val) - return nothing, nothing, nothing, Δαr, Δβr, map(Returns(nothing), ba)... + return nothing, nothing, nothing, Δαr, Δβr, nothing, nothing end function EnzymeRules.forward( config::EnzymeRules.FwdConfigWidth{1}, @@ -258,20 +244,19 @@ function EnzymeRules.forward( inds::Annotation, α::Annotation{<:Number}, β::Annotation{<:Number}, - ba::Const...; + backend::Const, allocator::Const; inv::Bool = false ) where {RT} - bavs = map(a -> a.val, ba) if !isa(C, Const) if isa(β, Const) scale!(C.dval, β.val) else add!(C.dval, C.val, β.dval, β.val) end - !isa(α, Const) && TK.twist!(C.dval, A.val, inds.val, α.dval, One(), bavs...; inv) - !isa(A, Const) && TK.twist!(C.dval, A.dval, inds.val, α.val, One(), bavs...; inv) + !isa(α, Const) && TK.twist!(C.dval, A.val, inds.val, α.dval, One(), backend.val, allocator.val; inv) + !isa(A, Const) && TK.twist!(C.dval, A.dval, inds.val, α.val, One(), backend.val, allocator.val; inv) end - TK.twist!(C.val, A.val, inds.val, α.val, β.val, bavs...; inv) + TK.twist!(C.val, A.val, inds.val, α.val, β.val, backend.val, allocator.val; inv) if EnzymeRules.needs_primal(config) && EnzymeRules.needs_shadow(config) return C elseif EnzymeRules.needs_primal(config) From 5a00ce5c63f4dd0bd6ee9310578877c5bd86d35f Mon Sep 17 00:00:00 2001 From: lkdvos Date: Mon, 9 Nov 2026 13:45:18 -0500 Subject: [PATCH 10/11] Take explicit backend and allocator arguments in the Mooncake index manipulation rules `twist!` fills in its default backend and allocator through an explicit call, such that rules for the full signature also apply to keyword calls. Co-Authored-By: Claude Opus 5.5 --- .../indexmanipulations.jl | 63 ++++++++----------- src/tensors/indexmanipulations.jl | 14 +++-- test/enzyme/flip.jl | 4 ++ test/mooncake/indexmanipulations.jl | 35 ++++++----- 4 files changed, 60 insertions(+), 56 deletions(-) diff --git a/ext/TensorKitMooncakeExt/indexmanipulations.jl b/ext/TensorKitMooncakeExt/indexmanipulations.jl index d57109e20..fd050c0d5 100644 --- a/ext/TensorKitMooncakeExt/indexmanipulations.jl +++ b/ext/TensorKitMooncakeExt/indexmanipulations.jl @@ -9,7 +9,7 @@ for transform in (:permute, :transpose) typeof(TK.$transform!), AbstractTensorMap, AbstractTensorMap, Index2Tuple, - Number, Number, Vararg{Any}, + Number, Number, Any, Any, } ) @@ -18,14 +18,14 @@ for transform in (:permute, :transpose) C_ΔC::CoDual{<:AbstractTensorMap}, A_ΔA::CoDual{<:AbstractTensorMap}, p_Δp::CoDual{<:Index2Tuple}, α_Δα::CoDual{<:Number}, β_Δβ::CoDual{<:Number}, - ba_Δba::CoDual... + backend_Δbackend::CoDual, allocator_Δallocator::CoDual ) # prepare arguments C, ΔC = arrayify(C_ΔC) A, ΔA = arrayify(A_ΔA) p = primal(p_Δp) α, β = primal.((α_Δα, β_Δβ)) - ba = primal.(ba_Δba) + backend, allocator = primal.((backend_Δbackend, allocator_Δallocator)) C_cache = copy(C) @@ -33,13 +33,11 @@ for transform in (:permute, :transpose) # and store that instead of repeating the permutation in the pullback each time. # effectively, we replace `permute!/transpose!` by `add ∘ permute/transpose`. Ap = if _needs_tangent(α) - backend = get(ba, 1, TO.DefaultBackend()) - allocator = get(ba, 2, TO.DefaultAllocator()) Ap = $transform(A, p; copy = true, backend, allocator) add!(C, Ap, α, β) Ap else - TK.$transform!(C, A, p, α, β, ba...) + TK.$transform!(C, A, p, α, β, backend, allocator) nothing end @@ -47,14 +45,14 @@ for transform in (:permute, :transpose) copy!(C, C_cache) # ΔA - TK.$transform_pb(ΔA, A, ΔC, C, p, α, ba...) + TK.$transform_pb(ΔA, A, ΔC, C, p, α, backend, allocator) ΔAr = NoRData() Δαr = pullback_dα(α, ΔC, Ap) Δβr = pullback_dβ(β, ΔC, C) ΔCr = pullback_dC!(ΔC, β) # this typically returns NoRData() - return NoRData(), ΔCr, ΔAr, NoRData(), Δαr, Δβr, map(Returns(NoRData()), ba)... + return NoRData(), ΔCr, ΔAr, NoRData(), Δαr, Δβr, NoRData(), NoRData() end return C_ΔC, $transform_pullback @@ -68,7 +66,7 @@ end typeof(TK.braid!), AbstractTensorMap, AbstractTensorMap, Index2Tuple, IndexTuple, - Number, Number, Vararg{Any}, + Number, Number, Any, Any, } ) @@ -77,7 +75,7 @@ function Mooncake.rrule!!( C_ΔC::CoDual{<:AbstractTensorMap}, A_ΔA::CoDual{<:AbstractTensorMap}, p_Δp::CoDual{<:Index2Tuple}, levels_Δlevels::CoDual{<:IndexTuple}, α_Δα::CoDual{<:Number}, β_Δβ::CoDual{<:Number}, - ba_Δba::CoDual... + backend_Δbackend::CoDual, allocator_Δallocator::CoDual ) # prepare arguments C, ΔC = arrayify(C_ΔC) @@ -85,7 +83,7 @@ function Mooncake.rrule!!( p = primal(p_Δp) levels = primal(levels_Δlevels) α, β = primal.((α_Δα, β_Δβ)) - ba = primal.(ba_Δba) + backend, allocator = primal.((backend_Δbackend, allocator_Δallocator)) C_cache = copy(C) @@ -93,27 +91,25 @@ function Mooncake.rrule!!( # and store that instead of repeating the permutation in the pullback each time. # effectively, we replace `braid!` by `add ∘ braid`. Ap = if _needs_tangent(α) - backend = get(ba, 1, TO.DefaultBackend()) - allocator = get(ba, 2, TO.DefaultAllocator()) Ap = braid(A, p, levels; copy = true, backend, allocator) add!(C, Ap, α, β) Ap else - TK.braid!(C, A, p, levels, α, β, ba...) + TK.braid!(C, A, p, levels, α, β, backend, allocator) nothing end function braid!_pullback(::NoRData) copy!(C, C_cache) - TK.braid_pb(ΔA, A, ΔC, C, p, levels, α, ba...) + TK.braid_pb(ΔA, A, ΔC, C, p, levels, α, backend, allocator) ΔAr = NoRData() Δαr = pullback_dα(α, ΔC, Ap) Δβr = pullback_dβ(β, ΔC, C) ΔCr = pullback_dC!(ΔC, β) # this typically returns NoRData() - return NoRData(), ΔCr, ΔAr, NoRData(), NoRData(), Δαr, Δβr, map(Returns(NoRData()), ba)... + return NoRData(), ΔCr, ΔAr, NoRData(), NoRData(), Δαr, Δβr, NoRData(), NoRData() end return C_ΔC, braid!_pullback @@ -172,7 +168,7 @@ end typeof(TK.twist!), AbstractTensorMap, AbstractTensorMap, Any, - Number, Number, Vararg{Any}, + Number, Number, Any, Any, } ) @is_primitive( @@ -182,7 +178,7 @@ end typeof(Core.kwcall), @NamedTuple{inv::Bool}, typeof(TK.twist!), AbstractTensorMap, AbstractTensorMap, Any, - Vararg{Any}, + Number, Number, Any, Any, } ) @@ -191,9 +187,9 @@ function Mooncake.rrule!!( C_ΔC::CoDual{<:AbstractTensorMap}, A_ΔA::CoDual{<:AbstractTensorMap}, inds_Δinds::CoDual, α_Δα::CoDual{<:Number}, β_Δβ::CoDual{<:Number}, - ba_Δba::CoDual... + backend_Δbackend::CoDual, allocator_Δallocator::CoDual ) - C_ΔC, pullback = twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, false, (α_Δα, β_Δβ, ba_Δba...)) + C_ΔC, pullback = twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, α_Δα, β_Δβ, backend_Δbackend, allocator_Δallocator, false) twist!_pullback(Δ::NoRData) = (NoRData(), pullback(Δ)...) return C_ΔC, twist!_pullback end @@ -201,24 +197,22 @@ function Mooncake.rrule!!( ::CoDual{typeof(Core.kwcall)}, kwargs_Δkwargs::CoDual{@NamedTuple{inv::Bool}}, ::CoDual{typeof(TK.twist!)}, C_ΔC::CoDual{<:AbstractTensorMap}, A_ΔA::CoDual{<:AbstractTensorMap}, inds_Δinds::CoDual, - args_Δargs::CoDual... + α_Δα::CoDual{<:Number}, β_Δβ::CoDual{<:Number}, + backend_Δbackend::CoDual, allocator_Δallocator::CoDual ) inv = primal(kwargs_Δkwargs).inv - C_ΔC, pullback = twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, inv, args_Δargs) + C_ΔC, pullback = twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, α_Δα, β_Δβ, backend_Δbackend, allocator_Δallocator, inv) twist!_pullback(Δ::NoRData) = (NoRData(), NoRData(), NoRData(), pullback(Δ)...) return C_ΔC, twist!_pullback end -# `args_Δargs` holds the optional `α`, `β`, backend and allocator, where a missing `α` or `β` is constant -function twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, inv, args_Δargs) +function twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, α_Δα, β_Δβ, backend_Δbackend, allocator_Δallocator, inv) # prepare arguments C, ΔC = arrayify(C_ΔC) A, ΔA = arrayify(A_ΔA) inds = primal(inds_Δinds) - args = primal.(args_Δargs) - α = length(args) >= 1 ? args[1] : One() - β = length(args) >= 2 ? args[2] : Zero() - ba = length(args) >= 3 ? args[3:end] : () + α, β = primal.((α_Δα, β_Δβ)) + backend, allocator = primal.((backend_Δbackend, allocator_Δallocator)) C_cache = copy(C) @@ -226,28 +220,25 @@ function twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, inv, args_Δargs) # and store that instead of repeating the twist in the pullback each time. # effectively, we replace `twist!` by `add ∘ twist`. Ap = if _needs_tangent(α) - backend = get(ba, 1, TO.DefaultBackend()) - allocator = get(ba, 2, TO.DefaultAllocator()) Ap = twist(A, inds; inv, copy = true, backend, allocator) add!(C, Ap, α, β) Ap else - TK.twist!(C, A, inds, α, β, ba...; inv) + TK.twist!(C, A, inds, α, β, backend, allocator; inv) nothing end function pullback(::NoRData) copy!(C, C_cache) - TK.twist_pb(ΔA, A, ΔC, C, inds, α, ba...; inv) + TK.twist_pb(ΔA, A, ΔC, C, inds, α, backend, allocator; inv) ΔAr = NoRData() - Δαr = length(args) >= 1 ? pullback_dα(α, ΔC, Ap) : nothing - Δβr = length(args) >= 2 ? pullback_dβ(β, ΔC, C) : nothing + Δαr = pullback_dα(α, ΔC, Ap) + Δβr = pullback_dβ(β, ΔC, C) ΔCr = pullback_dC!(ΔC, β) # this typically returns NoRData() - Δargsr = (Δαr, Δβr, map(Returns(NoRData()), ba)...)[1:length(args)] - return ΔCr, ΔAr, NoRData(), Δargsr... + return ΔCr, ΔAr, NoRData(), Δαr, Δβr, NoRData(), NoRData() end return C_ΔC, pullback diff --git a/src/tensors/indexmanipulations.jl b/src/tensors/indexmanipulations.jl index a7b9e331e..887825dd0 100644 --- a/src/tensors/indexmanipulations.jl +++ b/src/tensors/indexmanipulations.jl @@ -78,19 +78,23 @@ function twist!(t::AbstractTensorMap, inds; inv::Bool = false) @inbounds twist!(t, t, mask, One(), Zero(); inv) return t end +# fill in the defaults through an explicit call, such that AD rules for the full signature also apply @propagate_inbounds function twist!( tdst::AbstractTensorMap, tsrc::AbstractTensorMap, inds, - α::Number = One(), β::Number = Zero(), - backend::AbstractBackend = TO.DefaultBackend(), allocator = TO.DefaultAllocator(); + α::Number = One(), β::Number = Zero(), backend::AbstractBackend = TO.DefaultBackend(); inv::Bool = false ) + return twist!(tdst, tsrc, inds, α, β, backend, TO.DefaultAllocator(); inv) +end +@propagate_inbounds function twist!( + tdst::AbstractTensorMap, tsrc::AbstractTensorMap, inds, + α::Number, β::Number, backend::AbstractBackend, allocator; inv::Bool = false + ) return twist!(tdst, tsrc, _twistmask(tsrc, inds), α, β, backend, allocator; inv) end @propagate_inbounds function twist!( tdst::AbstractTensorMap, tsrc::AbstractTensorMap, mask::Tuple{Vararg{Bool}}, - α::Number = One(), β::Number = Zero(), - backend::AbstractBackend = TO.DefaultBackend(), allocator = TO.DefaultAllocator(); - inv::Bool = false + α::Number, β::Number, backend::AbstractBackend, allocator; inv::Bool = false ) twistmask = _twistmask(tsrc, mask) # checks the length, and maps an empty `inds` onto a mask @boundscheck spacecheck_transform(twist, space(tdst), space(tsrc), twistmask) diff --git a/test/enzyme/flip.jl b/test/enzyme/flip.jl index 39f3b3756..16b82943d 100644 --- a/test/enzyme/flip.jl +++ b/test/enzyme/flip.jl @@ -1,5 +1,6 @@ using Test, TestExtras using TensorKit +using TensorOperations: TensorOperations using Enzyme, EnzymeTestUtils using Random @@ -34,6 +35,9 @@ is_ci = get(ENV, "CI", "false") == "true" C = randn!(similar(A, TensorKit.promote_twist(A))) EnzymeTestUtils.test_reverse(twist!, TA, (copy(C), TA), (A, TA), ((1, 3), Const), (α, Active), (β, Active); atol, rtol, fkwargs = (inv = true,)) EnzymeTestUtils.test_forward(twist!, TA, (copy(C), TA), (A, TA), ((1, 3), Const), (α, Duplicated), (β, Duplicated); atol, rtol, fkwargs = (inv = false,)) + bac = ((TensorOperations.DefaultBackend(), Const), (TensorOperations.DefaultAllocator(), Const)) + EnzymeTestUtils.test_reverse(twist!, TA, (copy(C), TA), (A, TA), ((true, false, true, false, false), Const), (α, Active), (β, Active), bac...; atol, rtol, fkwargs = (inv = true,)) + EnzymeTestUtils.test_forward(twist!, TA, (copy(C), TA), (A, TA), ((true, false, true, false, false), Const), (α, Duplicated), (β, Duplicated), bac...; atol, rtol) if !is_ci EnzymeTestUtils.test_reverse(twist!, TA, (copy(C), TA), (A, TA), ([2, 4], Const), (α, Const), (β, Const); atol, rtol) EnzymeTestUtils.test_forward(twist!, TA, (copy(C), TA), (A, TA), ([2, 4], Const), (α, Const), (β, Const); atol, rtol) diff --git a/test/mooncake/indexmanipulations.jl b/test/mooncake/indexmanipulations.jl index a7a637dac..38bb73791 100644 --- a/test/mooncake/indexmanipulations.jl +++ b/test/mooncake/indexmanipulations.jl @@ -27,7 +27,8 @@ eltypes = (Float64, ComplexF64) for _ in 1:5 p = randindextuple(numind(A)) C = randn!(permute(A, p)) - Mooncake.TestUtils.test_rule(rng, TensorKit.permute!, C, A, p, α, β; atol, rtol, mode) + Mooncake.TestUtils.test_rule(rng, TensorKit.permute!, C, A, p, α, β; atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, TensorKit.permute!, C, A, p, α, β, TensorOperations.DefaultBackend(), TensorOperations.DefaultAllocator(); atol, rtol, mode) A = C end end @@ -41,12 +42,13 @@ eltypes = (Float64, ComplexF64) for _ in 1:2 p = randcircshift(numout(A), numin(A)) C = randn!(transpose(A, p)) - Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, A, p, One(), Zero(); atol, rtol, mode) - Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, A, p, α, β; atol, rtol, mode) + Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, A, p, One(), Zero(); atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, A, p, α, β; atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, A, p, α, β, TensorOperations.DefaultBackend(), TensorOperations.DefaultAllocator(); atol, rtol, mode) if !(T <: Real) - Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, real(A), p, α, β; atol, rtol, mode) - Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, A, p, real(α), β; atol, rtol, mode) - Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, real(A), p, real(α), β; atol, rtol, mode) + Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, real(A), p, α, β; atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, A, p, real(α), β; atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, TensorKit.transpose!, C, real(A), p, real(α), β; atol, rtol, mode, is_primitive = false) end A = C end @@ -62,11 +64,12 @@ eltypes = (Float64, ComplexF64) p = randcircshift(numout(A), numin(A)) levels = Tuple(randperm(numind(A))) C = randn!(transpose(A, p)) - Mooncake.TestUtils.test_rule(rng, TensorKit.braid!, C, A, p, levels, α, β; atol, rtol, mode) + Mooncake.TestUtils.test_rule(rng, TensorKit.braid!, C, A, p, levels, α, β; atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, TensorKit.braid!, C, A, p, levels, α, β, TensorOperations.DefaultBackend(), TensorOperations.DefaultAllocator(); atol, rtol, mode) if !(T <: Real) - Mooncake.TestUtils.test_rule(rng, TensorKit.braid!, C, real(A), p, levels, α, β; atol, rtol, mode) - Mooncake.TestUtils.test_rule(rng, TensorKit.braid!, C, A, p, levels, real(α), β; atol, rtol, mode) - Mooncake.TestUtils.test_rule(rng, TensorKit.braid!, C, A, p, levels, real(α), real(β); atol, rtol, mode) + Mooncake.TestUtils.test_rule(rng, TensorKit.braid!, C, real(A), p, levels, α, β; atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, TensorKit.braid!, C, A, p, levels, real(α), β; atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, TensorKit.braid!, C, A, p, levels, real(α), real(β); atol, rtol, mode, is_primitive = false) end A = C end @@ -85,12 +88,14 @@ eltypes = (Float64, ComplexF64) α = randn(T) β = randn(T) C = randn!(similar(A, TensorKit.promote_twist(A))) - Mooncake.TestUtils.test_rule(rng, TensorKit.twist!, C, A, (1, 3), α, β; atol, rtol, mode) - Mooncake.TestUtils.test_rule(rng, Core.kwcall, (; inv = true), TensorKit.twist!, C, A, [2, 4], α, β; atol, rtol, mode) - Mooncake.TestUtils.test_rule(rng, Core.kwcall, (; inv = false), TensorKit.twist!, C, A, 1; atol, rtol, mode) + Mooncake.TestUtils.test_rule(rng, TensorKit.twist!, C, A, (1, 3), α, β; atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, Core.kwcall, (; inv = true), TensorKit.twist!, C, A, [2, 4], α, β; atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, Core.kwcall, (; inv = true), TensorKit.twist!, C, A, [2, 4], α, β, TensorOperations.DefaultBackend(), TensorOperations.DefaultAllocator(); atol, rtol, mode) + Mooncake.TestUtils.test_rule(rng, TensorKit.twist!, C, A, (true, false, true, false, false), α, β, TensorOperations.DefaultBackend(), TensorOperations.DefaultAllocator(); atol, rtol, mode) + Mooncake.TestUtils.test_rule(rng, Core.kwcall, (; inv = false), TensorKit.twist!, C, A, 1; atol, rtol, mode, is_primitive = false) if !(T <: Real) - Mooncake.TestUtils.test_rule(rng, TensorKit.twist!, C, real(A), (1, 3), α, β; atol, rtol, mode) - Mooncake.TestUtils.test_rule(rng, TensorKit.twist!, C, A, (1, 3), real(α), real(β); atol, rtol, mode) + Mooncake.TestUtils.test_rule(rng, TensorKit.twist!, C, real(A), (1, 3), α, β; atol, rtol, mode, is_primitive = false) + Mooncake.TestUtils.test_rule(rng, TensorKit.twist!, C, A, (1, 3), real(α), real(β); atol, rtol, mode, is_primitive = false) end Mooncake.TestUtils.test_rule(rng, Core.kwcall, (; inv = true), twist, A, (1, 3); atol, rtol, mode, is_primitive = false) From 982797510882b7170a619f886e8a5af899d9fb67 Mon Sep 17 00:00:00 2001 From: lkdvos Date: Tue, 10 Nov 2026 11:01:15 -0500 Subject: [PATCH 11/11] Pass a mask to has_shared_twist in the CUDA tests, keep extra Enzyme checks out of CI Co-Authored-By: Claude Opus 5.5 --- test/cuda/tensors.jl | 4 ++-- test/enzyme/flip.jl | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/cuda/tensors.jl b/test/cuda/tensors.jl index 79c5ca11a..ec351d09f 100644 --- a/test/cuda/tensors.jl +++ b/test/cuda/tensors.jl @@ -352,8 +352,8 @@ for V in spacelist @test adapt(Array, t2)' ≈ twist(copy(ht'), inds; inv) end @test twist(twist(t, 2), 2; inv = true) ≈ t - if !TensorKit.has_shared_twist(t, (1, 3, 5)) - twistmask = (true, false, true, false, true) + twistmask = (true, false, true, false, true) + if !TensorKit.has_shared_twist(t, twistmask) p = (codomainind(t), domainind(t)) twister = TensorKit.treetwister(storagetype(t), space(t), space(t), p, false, twistmask, false) @test twister isa getglobal(GPUArraysExt, :DeviceUniqueTreeTransformer) diff --git a/test/enzyme/flip.jl b/test/enzyme/flip.jl index 16b82943d..75cc47e0a 100644 --- a/test/enzyme/flip.jl +++ b/test/enzyme/flip.jl @@ -35,12 +35,12 @@ is_ci = get(ENV, "CI", "false") == "true" C = randn!(similar(A, TensorKit.promote_twist(A))) EnzymeTestUtils.test_reverse(twist!, TA, (copy(C), TA), (A, TA), ((1, 3), Const), (α, Active), (β, Active); atol, rtol, fkwargs = (inv = true,)) EnzymeTestUtils.test_forward(twist!, TA, (copy(C), TA), (A, TA), ((1, 3), Const), (α, Duplicated), (β, Duplicated); atol, rtol, fkwargs = (inv = false,)) - bac = ((TensorOperations.DefaultBackend(), Const), (TensorOperations.DefaultAllocator(), Const)) - EnzymeTestUtils.test_reverse(twist!, TA, (copy(C), TA), (A, TA), ((true, false, true, false, false), Const), (α, Active), (β, Active), bac...; atol, rtol, fkwargs = (inv = true,)) - EnzymeTestUtils.test_forward(twist!, TA, (copy(C), TA), (A, TA), ((true, false, true, false, false), Const), (α, Duplicated), (β, Duplicated), bac...; atol, rtol) if !is_ci EnzymeTestUtils.test_reverse(twist!, TA, (copy(C), TA), (A, TA), ([2, 4], Const), (α, Const), (β, Const); atol, rtol) EnzymeTestUtils.test_forward(twist!, TA, (copy(C), TA), (A, TA), ([2, 4], Const), (α, Const), (β, Const); atol, rtol) + bac = ((TensorOperations.DefaultBackend(), Const), (TensorOperations.DefaultAllocator(), Const)) + EnzymeTestUtils.test_reverse(twist!, TA, (copy(C), TA), (A, TA), ((true, false, true, false, false), Const), (α, Active), (β, Active), bac...; atol, rtol, fkwargs = (inv = true,)) + EnzymeTestUtils.test_forward(twist!, TA, (copy(C), TA), (A, TA), ((true, false, true, false, false), Const), (α, Duplicated), (β, Duplicated), bac...; atol, rtol) end EnzymeTestUtils.test_reverse(flip, TA, (A, TA), (1, Const); atol, rtol, fkwargs = (inv = false,)) EnzymeTestUtils.test_reverse(flip, TA, (A, TA), ([1, 3], Const); atol, rtol, fkwargs = (inv = true,))