Cached `treetwister` for `twist!` #599
similar to permute and transform, is there any chance this could secretly be aliasing A.val?
Was Enzyme not able to make its own rules for these? Kind of sad if so...
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?
That's what the copy=true is for right?
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>
</details>
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?
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.
Approved these changes.
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}?
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.
Should this twist call have backend and allocator passed on as keyword arguments?
Same comment about ba.
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.
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.
Yes, fixed in #619 (also for the permute!/transpose!/braid! rules, which had the same issue).
Fixed in #619 as well.
kshyatt
lkdvos
Addresses the standalone
twist!part of #595.twist!looped overfusiontrees(t)and calledscale!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 routestwist!/twistthrough 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 topermute/braid, withindsgiven as indices or as anNTuple{N, Bool}mask (indices are converted to a fixed-length mask, so all forms are inferable).twist!(tdst, tsrc, inds, α = 1, β = 0, [backend], [allocator]; inv = false)computingtdst = β tdst + α twist(tsrc, inds; inv), laid out likebraid!: it unwraps adjoints throughunwrap_adjointsand calls a_twist!kernel entry mirroring_braid!.twist!(t, inds)andtwist(t, inds)are thin wrappers around it, andtwistnow also acceptsbackend/allocatorkeywords.treetwister(A, Vdst, Vsrc, p, conjsrc, twistmask, inv), with the same arguments astreebraider(the mask taking the place of the levels): always aUniqueTreeTransformer, 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).twist!(t, inds)runs throughadd_transform!(aliasing is allowed for trivial permutations in TensorOperations), andtwistis a single out-of-place pass instead ofcopy!followed bytwist!.TensorMap/AdjointTensorMapdestinations and sources go through the twister. The twist mask is relabeled like the levels ofbraid!, and an adjoint destination flipsinv(just as it conjugatesα).twist_pbpullback with Mooncake and Enzyme rules for the three-argumenttwist!, plus Enzyme rules for the in-placetwist!(t, inds). The existing ChainRulestwistrrule already forwards keywords and is now also tested withinvandbackend/allocator.add_transform!into_braid!/_transpose!(which also skips the transformer lookup there), soadd_transform!always applies its transformer.treetwister, registered and sized like the other device caches, so a GPUtwist!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
tensors/indexmanipulations.jl,tensors/contractions.jl,chainrules/linalg.jl,mooncake/indexmanipulations.jl,enzyme/flip.jlandcuda/tensors.jl(RTX A6000) pass.test/cuda/tensors.jlcomparingtwist/twist!onCuTensorMaps (and their adjoints) against the host results, and checking that the cached device transformer is used.test/tensors/indexmanipulations.jl, covering adjoint sources, adjoint destinations and in-place twists of adjoints, plus α/β accumulation.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