Skip to content

Commit d17e80e

Browse files
lkdvosclaude
andcommitted
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 <noreply@anthropic.com>
1 parent 04250d7 commit d17e80e

6 files changed

Lines changed: 64 additions & 26 deletions

File tree

‎docs/src/Changelog.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec
2828

2929
### Changed
3030

31+
- `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
3132
- `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)
3233
- 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
3334

@@ -37,6 +38,9 @@ When releasing a new version, move the "Unreleased" changes to a new version sec
3738

3839
### Fixed
3940

41+
- 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
42+
- `twist` of a fusion tree pair or block throws for a `Bool` mask of the wrong length, instead of interpreting it as indices
43+
4044
### Performance
4145

4246
- `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))

‎ext/TensorKitEnzymeExt/indexmanipulations.jl‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ for transform in (:permute, :transpose)
2121
# without copy=true, this may just alias A if
2222
# the permutation is an identity or the space
2323
# is Trivial and has_shared_permute is true
24-
Ap = $transform(A.val, p.val; copy = true)
24+
bavs = map(a -> a.val, ba)
25+
Ap = $transform(A.val, p.val; copy = true, TK.backend_kwargs(bavs...)...)
2526
add!(C.val, Ap, α.val, β.val)
2627
Ap
2728
else
@@ -113,7 +114,8 @@ function EnzymeRules.augmented_primal(
113114
# and store that instead of repeating the permutation in the pullback each time.
114115
# effectively, we replace `add_permute` by `add ∘ permute`.
115116
Ap = if !isa(α, Const)
116-
Ap = braid(A.val, p.val, levels.val)
117+
bavs = map(a -> a.val, ba)
118+
Ap = braid(A.val, p.val, levels.val; copy = true, TK.backend_kwargs(bavs...)...)
117119
add!(C.val, Ap, α.val, β.val)
118120
Ap
119121
else
@@ -204,7 +206,8 @@ function EnzymeRules.augmented_primal(
204206
# and store that instead of repeating the twist in the pullback each time.
205207
# effectively, we replace `twist!` by `add ∘ twist`.
206208
Ap = if !isa(α, Const)
207-
Ap = twist(A.val, inds.val; inv, copy = true)
209+
bavs = map(a -> a.val, ba)
210+
Ap = twist(A.val, inds.val; inv, copy = true, TK.backend_kwargs(bavs...)...)
208211
add!(C.val, Ap, α.val, β.val)
209212
Ap
210213
else

‎ext/TensorKitMooncakeExt/indexmanipulations.jl‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ for transform in (:permute, :transpose)
3333
# and store that instead of repeating the permutation in the pullback each time.
3434
# effectively, we replace `permute!/transpose!` by `add ∘ permute/transpose`.
3535
Ap = if _needs_tangent(α)
36-
Ap = $transform(A, p)
36+
Ap = $transform(A, p; copy = true, TK.backend_kwargs(ba...)...)
3737
add!(C, Ap, α, β)
3838
Ap
3939
else
@@ -91,7 +91,7 @@ function Mooncake.rrule!!(
9191
# and store that instead of repeating the permutation in the pullback each time.
9292
# effectively, we replace `braid!` by `add ∘ braid`.
9393
Ap = if _needs_tangent(α)
94-
Ap = braid(A, p, levels)
94+
Ap = braid(A, p, levels; copy = true, TK.backend_kwargs(ba...)...)
9595
add!(C, Ap, α, β)
9696
Ap
9797
else
@@ -222,7 +222,7 @@ function twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, inv, args_Δargs)
222222
# and store that instead of repeating the twist in the pullback each time.
223223
# effectively, we replace `twist!` by `add ∘ twist`.
224224
Ap = if _needs_tangent(α)
225-
Ap = twist(A, inds; inv, copy = true)
225+
Ap = twist(A, inds; inv, copy = true, TK.backend_kwargs(ba...)...)
226226
add!(C, Ap, α, β)
227227
Ap
228228
else

‎src/fusiontrees/braiding_manipulations.jl‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -396,19 +396,31 @@ function permute(src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple)
396396
return braid(src, p, (levels1, levels2))
397397
end
398398

399+
# convert the indices to twist into a mask over all `N` indices, such that the code
400+
# after this conversion is compiled only once for every `N`
401+
function _twistmask(::Val{N}, mask::Tuple{Bool, Vararg{Bool}}) where {N}
402+
length(mask) == N ||
403+
throw(ArgumentError(lazy"twist mask $mask does not match the number of indices $N"))
404+
return mask
405+
end
406+
function _twistmask(::Val{N}, inds) where {N}
407+
all(i -> 1 <= i <= N, inds) ||
408+
throw(ArgumentError(lazy"Can't twist indices $inds of an object with only $N indices."))
409+
return ntuple(i -> i in inds, N)
410+
end
411+
399412
"""
400413
twist(src::Union{FusionTreePair, FusionTreeBlock}, inds; inv::Bool = false) -> (src, θ)
401414
402415
Apply a twist to the uncoupled legs `inds` of the fusion-splitting tree pair or block `src`,
403-
where `inds` is either a collection of leg indices or an `NTuple{N, Bool}` mask over all legs.
416+
where `inds` is either a collection of leg indices or an `NTuple{N, Bool}` mask over all `N` legs.
404417
The twist is diagonal in the fusion tree basis, so this returns `src` itself together with the
405418
scalar factor `θ`, which is shared by all trees in a block. If `inv = true`, use the inverse twist.
406419
"""
407420
function twist(src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, inds; inv::Bool = false) where {I}
408421
uncoupled₁, uncoupled₂ = src isa FusionTreeBlock ? src.uncoupled : (src[1].uncoupled, src[2].uncoupled)
409422
uncoupled = (uncoupled₁..., uncoupled₂...)
410-
N = length(uncoupled)
411-
mask = inds isa NTuple{N, Bool} ? inds : ntuple(i -> i in inds, N)
423+
mask = _twistmask(Val(length(uncoupled)), inds)
412424
θ = prod(map((m, a) -> m ? twist(a) : one(twist(a)), mask, uncoupled); init = one(sectorscalartype(I)))
413425
return src, inv ? θ' : θ
414426
end

‎src/pullbacks/indexmanipulations.jl‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
# the optional positional `backend` and `allocator` as keywords for the out-of-place methods
2+
backend_kwargs() = (;)
3+
backend_kwargs(backend) = (; backend)
4+
backend_kwargs(backend, allocator) = (; backend, allocator)
5+
16
for transform in (:permute, :transpose)
27
transform! = Symbol(transform, :!)
38
transform_pb = Symbol(transform, :_pullback_dA)

‎src/tensors/indexmanipulations.jl‎

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,18 +31,22 @@ end
3131
# ---------
3232
# twist(!)
3333
# ---------
34-
function has_shared_twist(t, inds)
34+
_twistmask(t::AbstractTensorMap, inds) = _twistmask(Val(numind(t)), inds)
35+
36+
function has_shared_twist(t, mask::Tuple{Vararg{Bool}})
3537
I = sectortype(t)
3638
if BraidingStyle(I) == NoBraiding()
37-
for i in inds
39+
for i in 1:length(mask)
40+
mask[i] || continue
3841
cs = sectors(space(t, i))
3942
all(isunit, cs) || throw(SectorMismatch(lazy"Cannot twist sectors $cs"))
4043
end
4144
return true
4245
elseif BraidingStyle(I) == Bosonic()
4346
return true
4447
else
45-
for i in inds
48+
for i in 1:length(mask)
49+
mask[i] || continue
4650
cs = sectors(space(t, i))
4751
all(isone ∘ twist, cs) || return false
4852
end
@@ -55,6 +59,7 @@ end
5559
twist!(t::AbstractTensorMap, inds; inv::Bool = false) -> t
5660
5761
Apply a twist to the `i`th index of `t`, or all indices in `inds`, storing the result in `t`.
62+
Here, `inds` is either a collection of indices or an `NTuple{numind(t), Bool}` mask over all indices.
5863
If `inv=true`, use the inverse twist.
5964
6065
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
6570
See [`twist`](@ref) for creating a new tensor.
6671
"""
6772
function twist!(t::AbstractTensorMap, inds; inv::Bool = false)
68-
spacecheck_transform(twist, space(t), space(t), inds)
73+
mask = _twistmask(t, inds)
6974
(scalartype(t) <: Real && !(sectorscalartype(sectortype(t)) <: Real)) &&
7075
throw(ArgumentError("Can't in-place twist a real tensor with complex sector type"))
71-
has_shared_twist(t, inds) && return t
76+
has_shared_twist(t, mask) && return t
7277
# returning `t` rather than the result of `twist!` avoids an Enzyme crash on Julia 1.10
73-
@inbounds twist!(t, t, inds, One(), Zero(); inv)
78+
@inbounds twist!(t, t, mask, One(), Zero(); inv)
7479
return t
7580
end
7681
@propagate_inbounds function twist!(
@@ -79,9 +84,17 @@ end
7984
backend::AbstractBackend = TO.DefaultBackend(), allocator = TO.DefaultAllocator();
8085
inv::Bool = false
8186
)
82-
@boundscheck spacecheck_transform(twist, space(tdst), space(tsrc), inds)
87+
return twist!(tdst, tsrc, _twistmask(tsrc, inds), α, β, backend, allocator; inv)
88+
end
89+
@propagate_inbounds function twist!(
90+
tdst::AbstractTensorMap, tsrc::AbstractTensorMap, mask::Tuple{Vararg{Bool}},
91+
α::Number = One(), β::Number = Zero(),
92+
backend::AbstractBackend = TO.DefaultBackend(), allocator = TO.DefaultAllocator();
93+
inv::Bool = false
94+
)
95+
twistmask = _twistmask(tsrc, mask) # checks the length, and maps an empty `inds` onto a mask
96+
@boundscheck spacecheck_transform(twist, space(tdst), space(tsrc), twistmask)
8397
@timeit_debug GLOBAL_TIMER "twist!" begin
84-
twistmask = ntuple(i -> i in inds, numind(tsrc))
8598
p = (codomainind(tsrc), domainind(tsrc))
8699
tdst′, tsrc′, p′, twistmask′, conjsrc′, α′, β′ = unwrap_adjoints(tdst, tsrc, p, twistmask, false, α, β)
87100
# like `α`, the twist is conjugated by an adjoint destination
@@ -98,6 +111,7 @@ end
98111
) -> tdst
99112
100113
Apply a twist to the `i`th index of `tsrc`, or all indices in `inds`, and return the result as a new tensor.
114+
Here, `inds` is either a collection of indices or an `NTuple{numind(tsrc), Bool}` mask over all indices.
101115
If `inv = true`, use the inverse twist.
102116
If `copy = false`, `tdst` might share data with `tsrc` whenever possible. Otherwise, a copy is always made.
103117
Optionally specify a `backend` and `allocator` for the underlying array operation.
@@ -108,11 +122,12 @@ function twist(
108122
t::AbstractTensorMap, inds; inv::Bool = false,
109123
copy::Bool = false, backend::AbstractBackend = TO.DefaultBackend(), allocator = TO.DefaultAllocator()
110124
)
111-
has_shared_twist(t, inds) && return copy ? Base.copy(t) : t
125+
mask = _twistmask(t, inds)
126+
has_shared_twist(t, mask) && return copy ? Base.copy(t) : t
112127

113128
# general case
114129
tdst = similar(t, promote_twist(t))
115-
return @inbounds twist!(tdst, t, inds, One(), Zero(), backend, allocator; inv)
130+
return @inbounds twist!(tdst, t, mask, One(), Zero(), backend, allocator; inv)
116131
end
117132

118133
# =========================
@@ -545,25 +560,24 @@ end
545560
Vsrc′, p′ = conjsrc ? (Vsrc', adjointtensorindices(Vsrc, p)) : (Vsrc, p)
546561
return spacecheck_transform(f, Vdst, Vsrc′, p′)
547562
end
548-
@noinline function spacecheck_transform(::typeof(twist), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, inds)
563+
@noinline function spacecheck_transform(
564+
::typeof(twist), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, mask::Tuple{Vararg{Bool}}
565+
)
549566
check_spacetype(Vdst, Vsrc)
550-
all(in(allind(Vsrc)), inds) ||
551-
throw(ArgumentError(lazy"Can't twist indices $inds of a tensor with only $(numind(Vsrc)) indices."))
567+
length(mask) == numind(Vsrc) ||
568+
throw(ArgumentError(lazy"twist mask $mask does not match the number of indices $(numind(Vsrc))"))
552569
Vdst == Vsrc ||
553570
throw(
554571
SpaceMismatch(
555572
lazy"""
556-
incompatible spaces for `twist(Vsrc, $inds) -> Vdst`
573+
incompatible spaces for `twist(Vsrc, $mask) -> Vdst`
557574
Vsrc = $Vsrc
558575
Vdst = $Vdst
559576
"""
560577
)
561578
)
562579
return nothing
563580
end
564-
# disambiguation with the generic method
565-
spacecheck_transform(f::typeof(twist), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, inds::Index2Tuple) =
566-
invoke(spacecheck_transform, Tuple{typeof(twist), TensorMapSpace, TensorMapSpace, Any}, f, Vdst, Vsrc, inds)
567581
@noinline function spacecheck_transform(::typeof(braid), Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, levels::IndexTuple)
568582
check_spacetype(Vdst, Vsrc)
569583
braid(Vsrc, p, levels) == Vdst ||

0 commit comments

Comments
 (0)