Skip to content

Twist indices as a mask, and forward backend/allocator in AD rules - #619

Merged
lkdvos merged 11 commits into
mainfrom
twist-mask-followup
Nov 22, 2026
Merged

lkdvos merged 11 commits into
mainfrom
twist-mask-followup

Conversation

@lkdvos

@lkdvos lkdvos commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Follow-up to the post-merge review comments on #599.

Changes

  • Twist indices as a mask. twist(t, inds), twist!(t, inds) and twist!(tdst, tsrc, inds, ...) convert inds to an NTuple{numind(t), Bool} mask on entry (_twistmask), and the three-argument twist! has a dedicated method for a mask. Any collection of indices (tuples, vectors, ranges, an Int) is still accepted, but everything after the conversion only depends on the number of indices, so it is compiled once per numind.
    • Tensors now accept a Bool mask, just like the fusion tree twist.
    • spacecheck_transform(twist, ...) and has_shared_twist take the mask, so the disambiguation method with the invoke call is gone.
    • Out-of-range indices throw an ArgumentError during the conversion; a Bool mask of the wrong length now throws (also for fusion trees) instead of being interpreted as indices 0/1.
  • AD rules forward backend/allocator. The Enzyme and Mooncake rules of permute!, transpose!, braid! and twist! pass the optional backend and allocator on to the intermediate out-of-place call. That call now also always uses copy = true, since the intermediate is stored for the Δα pullback and should not alias A (this was already the case for the Enzyme permute!/twist! rules).

Testing

  • Locally: tensors/indexmanipulations, tensors/contractions, tensors/diagonal, symmetries/doubletree, other/aqua, mooncake/indexmanipulations, enzyme/{permute,transpose,braid,flip} and chainrules/linalg pass. The final version of the branch was run against tensors/indexmanipulations, symmetries/doubletree, other/aqua, mooncake/indexmanipulations, enzyme/flip and chainrules/linalg (121810 tests); the remaining files were run on an earlier revision whose only differences are the _twistmask rename and the mask dispatch.
  • Extra checks for vectors/ranges/masks/empty inds, a tensor without indices, error cases, inferability, and the absence of method ambiguities.

🤖 Generated with Claude Code

Comment thread src/pullbacks/indexmanipulations.jl Resolved
@lkdvos
lkdvos force-pushed the twist-mask-followup branch 2 times, most recently from d35b3dd to 817ebd5 Compare November 10, 2026 17:26
Comment on lines 82 to +98
@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
)
@boundscheck spacecheck_transform(twist, space(tdst), space(tsrc), inds)
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, β::Number, backend::AbstractBackend, allocator; inv::Bool = false
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think I fully understand why we need 3 different method definitions for this. I would understand if you want to be able to specialize on the one having inds::Tuple{Vararg{Bool}}, but in the end that method still calls _twistmask on its inds/mask argument, so I am confused.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the main reason for calling _twistmask again is to detect if the length of the mask is correct, and meanwhile I think Tuple{} matches this signature, so that still needs to be converted to a tuple of falses.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so the logic is: first fill in all default arguments, then convert to mask, then implement, hence the 3 definitions

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But I don't understand why all the default arguments cannot be filled in a single method definition, i.e. why not

@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
    )
    
    twistmask = _twistmask(tsrc, inds)
    @boundscheck spacecheck_transform(twist, space(tdst), space(tsrc), twistmask)
    @timeit_debug GLOBAL_TIMER "twist!" begin
        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
        inv′ = inv ⊻ (tdst isa AdjointTensorMap)
        @inbounds _twist!(tdst′, tsrc′, p′, conjsrc′, twistmask′, inv′, α′, β′, backend, allocator)
    end
    return tdst
end

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh that's a good point. I think I was playing around with a bunch of different options and wanted to avoid having to recompile the implementation itself for multiple argument types, but that also doesn't seem to be the case for your implementation, so probably your suggestion is just better

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I see correctly, it got merged with the three different method signatures after all. I guess my suggestion didn't work then?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I'm sorry, I somehow read the PR approval and thought you had already pushed this change, that's my bad

@Jutho Jutho left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't checked the tests, but otherwise looks ok aside from the one question I left.

lkdvos and others added 11 commits November 22, 2026 10:12
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 <noreply@anthropic.com>
…epermuter`

`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 <noreply@anthropic.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
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 <noreply@anthropic.com>
…ules

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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ipulation rules

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…anipulation 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 <noreply@anthropic.com>
…checks out of CI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lkdvos
lkdvos force-pushed the twist-mask-followup branch from 817ebd5 to 9827975 Compare November 22, 2026 18:51
@lkdvos
lkdvos changed the base branch from main to contract-fuse November 22, 2026 18:51
Base automatically changed from contract-fuse to main November 22, 2026 18:56
@lkdvos
lkdvos requested a review from Jutho November 22, 2026 18:57
@codecov

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.75758% with 24 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
ext/TensorKitEnzymeExt/indexmanipulations.jl 0.00% 21 Missing ⚠️
src/tensors/indexmanipulations.jl 92.00% 2 Missing ⚠️
ext/TensorKitMooncakeExt/indexmanipulations.jl 95.23% 1 Missing ⚠️
Files with missing lines Coverage Δ
ext/TensorKitGPUArraysExt.jl 96.96% <100.00%> (ø)
src/fusiontrees/braiding_manipulations.jl 95.95% <100.00%> (+0.07%) ⬆️
src/tensors/tensoroperations.jl 97.35% <100.00%> (+0.01%) ⬆️
src/tensors/treetransformers.jl 96.85% <100.00%> (+0.14%) ⬆️
ext/TensorKitMooncakeExt/indexmanipulations.jl 96.42% <95.23%> (-0.06%) ⬇️
src/tensors/indexmanipulations.jl 91.76% <92.00%> (+0.25%) ⬆️
ext/TensorKitEnzymeExt/indexmanipulations.jl 0.00% <0.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lkdvos
lkdvos merged commit d03b3ba into main Nov 22, 2026
18 of 22 checks passed
@lkdvos
lkdvos deleted the twist-mask-followup branch November 22, 2026 23:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants