← Back to Pull requests

Cached `treetwister` for `twist!` #599

Merged
lkdvos merged 18 files (535 lines) on Nov 04, 2026 19:28 UTC
View on GitHub
lkdvos lkdvos commented on Oct 28, 2026 13:41 UTC
Author

Addresses the standalone twist! part of #595.

twist! looped over fusiontrees(t) and called scale! on every subblock, so its cost grew with the number of subblocks rather than with the data size, and a twist of a GPU tensor launched one kernel per subblock. This PR routes twist!/twist through the existing index manipulation kernel with a cached tree transformer.

Changes

  • twist(src::Union{FusionTreePair, FusionTreeBlock}, inds; inv = false) -> (src, θ): fusion-tree level twist, next to permute/braid, with inds given as indices or as an NTuple{N, Bool} mask (indices are converted to a fixed-length mask, so all forms are inferable).

  • A public twist!(tdst, tsrc, inds, α = 1, β = 0, [backend], [allocator]; inv = false) computing tdst = β tdst + α twist(tsrc, inds; inv), laid out like braid!: it unwraps adjoints through unwrap_adjoints and calls a _twist! kernel entry mirroring _braid!. twist!(t, inds) and twist(t, inds) are thin wrappers around it, and twist now also accepts backend/allocator keywords.

  • Cached treetwister(A, Vdst, Vsrc, p, conjsrc, twistmask, inv), with the same arguments as treebraider (the mask taking the place of the levels): always a UniqueTreeTransformer, also for non-abelian sectors, since a twist maps every tree pair onto itself with a scalar factor (no recoupling matrices / pack-matmul-unpack needed).

  • The in-place twist!(t, inds) runs through add_transform! (aliasing is allowed for trivial permutations in TensorOperations), and twist is a single out-of-place pass instead of copy! followed by twist!.

  • All combinations of TensorMap/AdjointTensorMap destinations and sources go through the twister. The twist mask is relabeled like the levels of braid!, and an adjoint destination flips inv (just as it conjugates α).

  • AD: a twist_pb pullback with Mooncake and Enzyme rules for the three-argument twist!, plus Enzyme rules for the in-place twist!(t, inds). The existing ChainRules twist rrule already forwards keywords and is now also tested with inv and backend/allocator.

  • The shortcut for trivial permutations moved from add_transform! into _braid!/_transpose! (which also skips the transformer lookup there), so add_transform! always applies its transformer.

  • GPUArrays extension: cached device treetwister, registered and sized like the other device caches, so a GPU twist! is a single batched kernel launch.
  • Benchmarks (CPU, single thread)

    fℤ₂ × U(1) tensors Vχ ⊗ VD ⊗ VD' ← Vχ ⊗ VD ⊗ VD', twisted on indices (2, 3, 5, 6), minimum of 20 runs:

    | subblocks | entries | twist! before | twist! after | speedup | copy |
    |---:|---:|---:|---:|---:|---:|
    | 134,688 | 538,752 | 344 ms | 39.5 ms | 8.7× | 1.1 ms |
    | 214,688 | 13,740,032 | 686 ms | 86 ms | 8.0× | 77 ms |
    | 1,058,848 | 1,058,848 | 3157 ms | 91 ms | 35× | 3.3 ms |

    Building the twister on a cache miss costs ~3× a cached call in the smallest case. There is still a per-subblock cost from the individual tensoradd! calls on the CPU, which is left for a follow-up. GPU timings were not measured.

    Testing

  • Locally: tensors/indexmanipulations.jl, tensors/contractions.jl, chainrules/linalg.jl, mooncake/indexmanipulations.jl, enzyme/flip.jl and cuda/tensors.jl (RTX A6000) pass.

  • New "Twists: test via CPU" testset in test/cuda/tensors.jl comparing twist/twist! on CuTensorMaps (and their adjoints) against the host results, and checking that the cached device transformer is used.

  • New "Twists: adjoint operands" testset in test/tensors/indexmanipulations.jl, covering adjoint sources, adjoint destinations and in-place twists of adjoints, plus α/β accumulation.

  • AMD tests were not run locally.
  • Follow-up

    Folding the twist into the permutations that precede a contraction (the second part of #595) will be done on top of this, through a cached contraction plan holding the transformers.

    🤖 Generated with Claude Code

    Diff: 535 lines (+503 / -32) across 18 files Reviewer: kshyatt Review duration: 10426m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.69) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.69 · 535 lines diff across 18 files
    0.69
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.86 · 5 substantive comment(s)
    0.86
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.376
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    17 items
    kshyatt kshyatt commented on code on Oct 28, 2026 18:49 UTC
    Code Review
    ext/TensorKitEnzymeExt/indexmanipulations.jl:1
    @@ -183,6 +183,144 @@ function EnzymeRules.forward(
         end
     end
     
    +function EnzymeRules.augmented_primal(
    +        config::EnzymeRules.RevConfigWidth{1},
    +        func::Const{typeof(TK.twist!)},
    +        ::Type{RT},
    +        C::Annotation{<:AbstractTensorMap},
    +        A::Annotation{<:AbstractTensorMap},
    +        inds::Const,
    +        α::Annotation{<:Number},
    +        β::Annotation{<:Number},
    +        ba::Const...;
    +        inv::Bool = false
    +    ) where {RT}
    +    C_cache = !isa(β, Const) ? copy(C.val) : nothing
    +    A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing
    +    # if we need to compute Δa, it is faster to allocate an intermediate twisted A
    +    # 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)

    similar to permute and transform, is there any chance this could secretly be aliasing A.val?

    kshyatt kshyatt commented on code on Oct 28, 2026 18:51 UTC
    Code Review
    ext/TensorKitEnzymeExt/indexmanipulations.jl:1
    @@ -183,6 +183,144 @@ function EnzymeRules.forward(
         end
     end
     
    +function EnzymeRules.augmented_primal(
    +        config::EnzymeRules.RevConfigWidth{1},
    +        func::Const{typeof(TK.twist!)},
    +        ::Type{RT},
    +        C::Annotation{<:AbstractTensorMap},
    +        A::Annotation{<:AbstractTensorMap},
    +        inds::Const,
    +        α::Annotation{<:Number},
    +        β::Annotation{<:Number},
    +        ba::Const...;
    +        inv::Bool = false
    +    ) where {RT}
    +    C_cache = !isa(β, Const) ? copy(C.val) : nothing
    +    A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing
    +    # if we need to compute Δa, it is faster to allocate an intermediate twisted A
    +    # 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)
    +        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)
    +        nothing
    +    end
    +    cache = (C_cache, A_cache, Ap)
    +    primal = EnzymeRules.needs_primal(config) ? C.val : nothing
    +    shadow = EnzymeRules.needs_shadow(config) ? C.dval : nothing
    +    return EnzymeRules.AugmentedReturn(primal, shadow, cache)
    +end
    +function EnzymeRules.reverse(

    Was Enzyme not able to make its own rules for these? Kind of sad if so...

    lkdvos lkdvos commented on code on Oct 28, 2026 21:05 UTC
    Code Review
    ext/TensorKitEnzymeExt/indexmanipulations.jl:1
    @@ -183,6 +183,144 @@ function EnzymeRules.forward(
         end
     end
     
    +function EnzymeRules.augmented_primal(
    +        config::EnzymeRules.RevConfigWidth{1},
    +        func::Const{typeof(TK.twist!)},
    +        ::Type{RT},
    +        C::Annotation{<:AbstractTensorMap},
    +        A::Annotation{<:AbstractTensorMap},
    +        inds::Const,
    +        α::Annotation{<:Number},
    +        β::Annotation{<:Number},
    +        ba::Const...;
    +        inv::Bool = false
    +    ) where {RT}
    +    C_cache = !isa(β, Const) ? copy(C.val) : nothing
    +    A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing
    +    # if we need to compute Δa, it is faster to allocate an intermediate twisted A
    +    # 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)
    +        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)
    +        nothing
    +    end
    +    cache = (C_cache, A_cache, Ap)
    +    primal = EnzymeRules.needs_primal(config) ? C.val : nothing
    +    shadow = EnzymeRules.needs_shadow(config) ? C.dval : nothing
    +    return EnzymeRules.AugmentedReturn(primal, shadow, cache)
    +end
    +function EnzymeRules.reverse(

    These changes make twist go through the same path as permute and transpose etc, so even if it was able to do this I think this path is way more friendly on both compile time and possibly runtime?

    lkdvos lkdvos commented on code on Oct 28, 2026 21:05 UTC
    Code Review
    ext/TensorKitEnzymeExt/indexmanipulations.jl:1
    @@ -183,6 +183,144 @@ function EnzymeRules.forward(
         end
     end
     
    +function EnzymeRules.augmented_primal(
    +        config::EnzymeRules.RevConfigWidth{1},
    +        func::Const{typeof(TK.twist!)},
    +        ::Type{RT},
    +        C::Annotation{<:AbstractTensorMap},
    +        A::Annotation{<:AbstractTensorMap},
    +        inds::Const,
    +        α::Annotation{<:Number},
    +        β::Annotation{<:Number},
    +        ba::Const...;
    +        inv::Bool = false
    +    ) where {RT}
    +    C_cache = !isa(β, Const) ? copy(C.val) : nothing
    +    A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing
    +    # if we need to compute Δa, it is faster to allocate an intermediate twisted A
    +    # 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)

    That's what the copy=true is for right?

    codecov[bot] codecov[bot] commented on Oct 29, 2026 20:32 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 59.86842% with 61 lines in your changes missing coverage. Please review.

    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | ext/TensorKitEnzymeExt/indexmanipulations.jl | 0.00% | 59 Missing :warning: |
    | ext/TensorKitEnzymeExt/utility.jl | 0.00% | 1 Missing :warning: |
    | src/tensors/indexmanipulations.jl | 96.96% | 1 Missing :warning: |

    | Files with missing lines | Coverage Δ | |
    |---|---|---|
    | ext/TensorKitGPUArraysExt.jl | 95.80% <100.00%> (+0.10%) | :arrow_up: |
    | ext/TensorKitMooncakeExt/indexmanipulations.jl | 96.48% <100.00%> (+0.72%) | :arrow_up: |
    | src/auxiliary/caches.jl | 89.52% <100.00%> (ø) | |
    | src/fusiontrees/braiding\_manipulations.jl | 95.73% <100.00%> (+0.11%) | :arrow_up: |
    | src/pullbacks/indexmanipulations.jl | 100.00% <100.00%> (ø) | |
    | src/tensors/treetransformers.jl | 98.79% <100.00%> (+0.07%) | :arrow_up: |
    | ext/TensorKitEnzymeExt/utility.jl | 0.00% <0.00%> (-33.34%) | :arrow_down: |
    | src/tensors/indexmanipulations.jl | 91.50% <96.96%> (+0.41%) | :arrow_up: |
    | ext/TensorKitEnzymeExt/indexmanipulations.jl | 0.00% <0.00%> (-82.25%) | :arrow_down: |

    ... and 13 files with indirect coverage changes
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • </details>

    Jutho Jutho commented on Nov 02, 2026 21:16 UTC
    Contributor

    Before I start reviewing, since twist only depends on the uncoupled indices of the trees, it is just a constant scalar factor (or thus a UniformScaling) for every FusionBlock. Id that being used here?

    lkdvos lkdvos commented on Nov 02, 2026 21:47 UTC
    Author

    It is, but it's slightly subtle: the code uses UniqueTreeTransformer everywhere, i.e. I'm just reusing that code even for generic fusion because that already encodes the single subblock -> single subblock recoupling.

    kshyatt kshyatt approved these changes on Nov 04, 2026 14:45 UTC
    Approved Reviewer

    Approved these changes.

    Jutho Jutho commented on code on Nov 06, 2026 22:55 UTC
    Code Review
    src/tensors/indexmanipulations.jl:1
    @@ -526,6 +545,25 @@ 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)
    +    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."))
    +    Vdst == Vsrc ||
    +        throw(
    +        SpaceMismatch(
    +            lazy"""
    +            incompatible spaces for `twist(Vsrc, $inds) -> Vdst`
    +            Vsrc = $Vsrc
    +            Vdst = $Vdst
    +            """
    +        )
    +    )
    +    return nothing
    +end
    +# disambiguation with the generic method

    Is the method below only there to avoid ambiguities because of the unspecialized inds argument in the method above. Is it ever called? We do not accept a twist(!) call with inds::Index2Tuple right? And the lowering that is proposed by the invoke call doesn't work I would think, since an inds::Index2Tuple would not work in the method above?

    Couldn't we just specialize the method above to the inds that we do accept/support, namely Union{Int,IndexTuple}?

    Jutho Jutho commented on code on Nov 06, 2026 23:00 UTC
    Code Review
    src/fusiontrees/braiding_manipulations.jl:1
    @@ -367,6 +367,23 @@ function permute(src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple)
         return braid(src, p, (levels1, levels2))
     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.
    +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}

    I see why you want to accept an inds as a mask, i.e. of type NTulpe{N, Bool}, because of how twist is implemented at the tensor level, namely by reusing some of the functionality of the levels argument of braid. But it is somewhat asymmetric that we accept a mask argument for inds in the fusiontree method, but not in the associated tensor method.

    Jutho Jutho commented on code on Nov 06, 2026 23:09 UTC
    Code Review
    ext/TensorKitEnzymeExt/indexmanipulations.jl:1
    @@ -186,6 +186,144 @@ function EnzymeRules.forward(
         end
     end
     
    +function EnzymeRules.augmented_primal(
    +        config::EnzymeRules.RevConfigWidth{1},
    +        func::Const{typeof(TK.twist!)},
    +        ::Type{RT},
    +        C::Annotation{<:AbstractTensorMap},
    +        A::Annotation{<:AbstractTensorMap},
    +        inds::Const,
    +        α::Annotation{<:Number},
    +        β::Annotation{<:Number},
    +        ba::Const...;
    +        inv::Bool = false
    +    ) where {RT}
    +    C_cache = !isa(β, Const) ? copy(C.val) : nothing
    +    A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing
    +    # if we need to compute Δa, it is faster to allocate an intermediate twisted A
    +    # 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)

    Should this twist call have backend and allocator passed on as keyword arguments?

    Jutho Jutho commented on code on Nov 06, 2026 23:19 UTC
    Code Review
    ext/TensorKitMooncakeExt/indexmanipulations.jl:1
    @@ -160,6 +160,93 @@ function Mooncake.rrule!!(
         return t_Δt, twist_pullback
     end
     
    +# both are needed for correctly capturing every dispatch
    +@is_primitive(
    +    DefaultCtx,
    +    ReverseMode,
    +    Tuple{
    +        typeof(TK.twist!),
    +        AbstractTensorMap,
    +        AbstractTensorMap, Any,
    +        Number, Number, Vararg{Any},
    +    }
    +)
    +@is_primitive(
    +    DefaultCtx,
    +    ReverseMode,
    +    Tuple{
    +        typeof(Core.kwcall), @NamedTuple{inv::Bool}, typeof(TK.twist!),
    +        AbstractTensorMap,
    +        AbstractTensorMap, Any,
    +        Vararg{Any},
    +    }
    +)
    +
    +function Mooncake.rrule!!(
    +        ::CoDual{typeof(TK.twist!)},
    +        C_ΔC::CoDual{<:AbstractTensorMap},
    +        A_ΔA::CoDual{<:AbstractTensorMap}, inds_Δinds::CoDual,
    +        α_Δα::CoDual{<:Number}, β_Δβ::CoDual{<:Number},
    +        ba_Δba::CoDual...
    +    )
    +    C_ΔC, pullback = twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, false, (α_Δα, β_Δβ, ba_Δba...))
    +    twist!_pullback(Δ::NoRData) = (NoRData(), pullback(Δ)...)
    +    return C_ΔC, twist!_pullback
    +end
    +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...
    +    )
    +    inv = primal(kwargs_Δkwargs).inv
    +    C_ΔC, pullback = twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, inv, args_Δargs)
    +    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)
    +    # 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] : ()
    +
    +    C_cache = copy(C)
    +
    +    # if we need to compute Δa, it is faster to allocate an intermediate twisted A
    +    # 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)

    Same comment about ba.

    lkdvos lkdvos commented on code on Nov 09, 2026 15:20 UTC
    Code Review
    src/tensors/indexmanipulations.jl:1
    @@ -526,6 +545,25 @@ 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)
    +    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."))
    +    Vdst == Vsrc ||
    +        throw(
    +        SpaceMismatch(
    +            lazy"""
    +            incompatible spaces for `twist(Vsrc, $inds) -> Vdst`
    +            Vsrc = $Vsrc
    +            Vdst = $Vdst
    +            """
    +        )
    +    )
    +    return nothing
    +end
    +# disambiguation with the generic method

    Good catch, it was only there for the ambiguity. Addressed in #619: inds is now converted to a Bool mask on entry (so iterables are still accepted), and the spacecheck takes that mask, which removes the ambiguity and the invoke method.

    lkdvos lkdvos commented on code on Nov 09, 2026 15:20 UTC
    Code Review
    src/fusiontrees/braiding_manipulations.jl:1
    @@ -367,6 +367,23 @@ function permute(src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple)
         return braid(src, p, (levels1, levels2))
     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.
    +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}

    Agreed, addressed in #619: the tensor twist/twist! now also accept an NTuple{numind, Bool} mask, and indices are converted to such a mask internally.

    lkdvos lkdvos commented on code on Nov 09, 2026 15:20 UTC
    Code Review
    ext/TensorKitEnzymeExt/indexmanipulations.jl:1
    @@ -186,6 +186,144 @@ function EnzymeRules.forward(
         end
     end
     
    +function EnzymeRules.augmented_primal(
    +        config::EnzymeRules.RevConfigWidth{1},
    +        func::Const{typeof(TK.twist!)},
    +        ::Type{RT},
    +        C::Annotation{<:AbstractTensorMap},
    +        A::Annotation{<:AbstractTensorMap},
    +        inds::Const,
    +        α::Annotation{<:Number},
    +        β::Annotation{<:Number},
    +        ba::Const...;
    +        inv::Bool = false
    +    ) where {RT}
    +    C_cache = !isa(β, Const) ? copy(C.val) : nothing
    +    A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing
    +    # if we need to compute Δa, it is faster to allocate an intermediate twisted A
    +    # 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)

    Yes, fixed in #619 (also for the permute!/transpose!/braid! rules, which had the same issue).

    lkdvos lkdvos commented on code on Nov 09, 2026 15:20 UTC
    Code Review
    ext/TensorKitMooncakeExt/indexmanipulations.jl:1
    @@ -160,6 +160,93 @@ function Mooncake.rrule!!(
         return t_Δt, twist_pullback
     end
     
    +# both are needed for correctly capturing every dispatch
    +@is_primitive(
    +    DefaultCtx,
    +    ReverseMode,
    +    Tuple{
    +        typeof(TK.twist!),
    +        AbstractTensorMap,
    +        AbstractTensorMap, Any,
    +        Number, Number, Vararg{Any},
    +    }
    +)
    +@is_primitive(
    +    DefaultCtx,
    +    ReverseMode,
    +    Tuple{
    +        typeof(Core.kwcall), @NamedTuple{inv::Bool}, typeof(TK.twist!),
    +        AbstractTensorMap,
    +        AbstractTensorMap, Any,
    +        Vararg{Any},
    +    }
    +)
    +
    +function Mooncake.rrule!!(
    +        ::CoDual{typeof(TK.twist!)},
    +        C_ΔC::CoDual{<:AbstractTensorMap},
    +        A_ΔA::CoDual{<:AbstractTensorMap}, inds_Δinds::CoDual,
    +        α_Δα::CoDual{<:Number}, β_Δβ::CoDual{<:Number},
    +        ba_Δba::CoDual...
    +    )
    +    C_ΔC, pullback = twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, false, (α_Δα, β_Δβ, ba_Δba...))
    +    twist!_pullback(Δ::NoRData) = (NoRData(), pullback(Δ)...)
    +    return C_ΔC, twist!_pullback
    +end
    +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...
    +    )
    +    inv = primal(kwargs_Δkwargs).inv
    +    C_ΔC, pullback = twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, inv, args_Δargs)
    +    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)
    +    # 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] : ()
    +
    +    C_cache = copy(C)
    +
    +    # if we need to compute Δa, it is faster to allocate an intermediate twisted A
    +    # 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)

    Fixed in #619 as well.

    Reviewers
    Assignees
    lkdvos lkdvos
    Labels
    risk: low confidence: 89.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 69.1% (HIGH) · Higher = larger blast radius
    69.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.1% · Lower = rushed or shallow review
    89.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.5% · Safe to merge
    7.5%