Skip to content

Commit cef98d8

Browse files
lkdvosclaude
andcommitted
Make twist! mirror braid! with a public twist!(tdst, tsrc, inds, α, β, ...)
`twist!(t, inds)` and `twist(t, inds)` are now thin wrappers around the three-argument form, which goes through `unwrap_adjoints` and a `_twist!` kernel entry like `_braid!`. Adds `twist_pb` with Mooncake and Enzyme rules, and backend/allocator keywords for `twist`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 866ee15 commit cef98d8

12 files changed

Lines changed: 354 additions & 59 deletions

File tree

‎docs/src/Changelog.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec
2424

2525
- Re-export `NamedSector` and `@NamedSector` from TensorKitSectors
2626
- `twist(src, inds; inv = false)` for fusion tree pairs and blocks, returning `src` together with the scalar twist factor of the legs `inds`, which can be given as indices or as a `Bool` mask
27+
- `twist!(tdst, tsrc, inds, α = 1, β = 0, [backend], [allocator]; inv = false)` computing `tdst = β * tdst + α * twist(tsrc, inds; inv)`, in line with `permute!` and `braid!`, together with Mooncake and Enzyme rules; `twist` now also accepts `backend` and `allocator` keywords
2728

2829
### Changed
2930

‎ext/TensorKitEnzymeExt/indexmanipulations.jl‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,144 @@ function EnzymeRules.forward(
186186
end
187187
end
188188

189+
function EnzymeRules.augmented_primal(
190+
config::EnzymeRules.RevConfigWidth{1},
191+
func::Const{typeof(TK.twist!)},
192+
::Type{RT},
193+
C::Annotation{<:AbstractTensorMap},
194+
A::Annotation{<:AbstractTensorMap},
195+
inds::Const,
196+
α::Annotation{<:Number},
197+
β::Annotation{<:Number},
198+
ba::Const...;
199+
inv::Bool = false
200+
) where {RT}
201+
C_cache = !isa(β, Const) ? copy(C.val) : nothing
202+
A_cache = EnzymeRules.overwritten(config)[3] ? copy(A.val) : nothing
203+
# if we need to compute Δa, it is faster to allocate an intermediate twisted A
204+
# and store that instead of repeating the twist in the pullback each time.
205+
# effectively, we replace `twist!` by `add ∘ twist`.
206+
Ap = if !isa(α, Const)
207+
Ap = twist(A.val, inds.val; inv, copy = true)
208+
add!(C.val, Ap, α.val, β.val)
209+
Ap
210+
else
211+
bavs = map(a -> a.val, ba)
212+
TK.twist!(C.val, A.val, inds.val, α.val, β.val, bavs...; inv)
213+
nothing
214+
end
215+
cache = (C_cache, A_cache, Ap)
216+
primal = EnzymeRules.needs_primal(config) ? C.val : nothing
217+
shadow = EnzymeRules.needs_shadow(config) ? C.dval : nothing
218+
return EnzymeRules.AugmentedReturn(primal, shadow, cache)
219+
end
220+
function EnzymeRules.reverse(
221+
config::EnzymeRules.RevConfigWidth{1},
222+
func::Const{typeof(TK.twist!)},
223+
::Type{RT},
224+
cache,
225+
C::Annotation{<:AbstractTensorMap},
226+
A::Annotation{<:AbstractTensorMap},
227+
inds::Const,
228+
α::Annotation{<:Number},
229+
β::Annotation{<:Number},
230+
ba::Const...;
231+
inv::Bool = false
232+
) where {RT}
233+
C_cache, A_cache, Ap = cache
234+
Cval = something(C_cache, C.val)
235+
Aval = something(A_cache, A.val)
236+
bavs = map(a -> a.val, ba)
237+
# ΔA
238+
if !isa(A, Const) && !isa(C, Const)
239+
TK.twist_pb(A.dval, Aval, C.dval, C.val, inds.val, α.val, bavs...; inv)
240+
end
241+
Δαr = pullback_dα(α, C, Ap)
242+
Δβr = pullback_dβ(β, C, Cval)
243+
!isa(C, Const) && pullback_dC!(C.dval, β.val)
244+
return nothing, nothing, nothing, Δαr, Δβr, map(Returns(nothing), ba)...
245+
end
246+
function EnzymeRules.forward(
247+
config::EnzymeRules.FwdConfigWidth{1},
248+
func::Const{typeof(TK.twist!)},
249+
::Type{RT},
250+
C::Annotation{<:AbstractTensorMap},
251+
A::Annotation{<:AbstractTensorMap},
252+
inds::Annotation,
253+
α::Annotation{<:Number},
254+
β::Annotation{<:Number},
255+
ba::Const...;
256+
inv::Bool = false
257+
) where {RT}
258+
bavs = map(a -> a.val, ba)
259+
if !isa(C, Const)
260+
if isa(β, Const)
261+
scale!(C.dval, β.val)
262+
else
263+
add!(C.dval, C.val, β.dval, β.val)
264+
end
265+
!isa(α, Const) && TK.twist!(C.dval, A.val, inds.val, α.dval, One(), bavs...; inv)
266+
!isa(A, Const) && TK.twist!(C.dval, A.dval, inds.val, α.val, One(), bavs...; inv)
267+
end
268+
TK.twist!(C.val, A.val, inds.val, α.val, β.val, bavs...; inv)
269+
if EnzymeRules.needs_primal(config) && EnzymeRules.needs_shadow(config)
270+
return C
271+
elseif EnzymeRules.needs_primal(config)
272+
return C.val
273+
elseif EnzymeRules.needs_shadow(config)
274+
return C.dval
275+
else
276+
return nothing
277+
end
278+
end
279+
280+
# in-place twist: the source and destination are the same tensor
281+
function EnzymeRules.augmented_primal(
282+
config::EnzymeRules.RevConfigWidth{1},
283+
func::Const{typeof(TK.twist!)},
284+
::Type{RT},
285+
t::Annotation{<:AbstractTensorMap},
286+
inds::Const;
287+
inv::Bool = false
288+
) where {RT}
289+
TK.twist!(t.val, inds.val; inv)
290+
primal = EnzymeRules.needs_primal(config) ? t.val : nothing
291+
shadow = EnzymeRules.needs_shadow(config) ? t.dval : nothing
292+
return EnzymeRules.AugmentedReturn(primal, shadow, nothing)
293+
end
294+
function EnzymeRules.reverse(
295+
config::EnzymeRules.RevConfigWidth{1},
296+
func::Const{typeof(TK.twist!)},
297+
::Type{RT},
298+
cache,
299+
t::Annotation{<:AbstractTensorMap},
300+
inds::Const;
301+
inv::Bool = false
302+
) where {RT}
303+
!isa(t, Const) && TK.twist!(t.dval, inds.val; inv = !inv)
304+
return (nothing, nothing)
305+
end
306+
function EnzymeRules.forward(
307+
config::EnzymeRules.FwdConfigWidth{1},
308+
func::Const{typeof(TK.twist!)},
309+
::Type{RT},
310+
t::Annotation{<:AbstractTensorMap},
311+
inds::Annotation;
312+
inv::Bool = false
313+
) where {RT}
314+
TK.twist!(t.val, inds.val; inv)
315+
!isa(t, Const) && TK.twist!(t.dval, inds.val; inv)
316+
if EnzymeRules.needs_primal(config) && EnzymeRules.needs_shadow(config)
317+
return t
318+
elseif EnzymeRules.needs_primal(config)
319+
return t.val
320+
elseif EnzymeRules.needs_shadow(config)
321+
return t.dval
322+
else
323+
return nothing
324+
end
325+
end
326+
189327
function EnzymeRules.augmented_primal(
190328
config::EnzymeRules.RevConfigWidth{1},
191329
func::Const{typeof(flip)},

‎ext/TensorKitGPUArraysExt.jl‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -288,10 +288,10 @@ end
288288
end
289289

290290
@cached function TensorKit.treetwister(
291-
A::Type{TA}, V::TensorMapSpace, conjsrc::Bool, twistmask::NTuple{N, Bool}, inv::Bool
291+
A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple,
292+
conjsrc::Bool, twistmask::NTuple{N, Bool}, inv::Bool
292293
) where {TA <: AnyGPUVector, N}
293-
host = TensorKit.treetwister(Vector{scalartype(A)}, V, conjsrc, twistmask, inv)
294-
_, p = TensorKit.twistpermutation(V, conjsrc)
294+
host = TensorKit.treetwister(Vector{scalartype(A)}, Vdst, Vsrc, p, conjsrc, twistmask, inv)
295295
return device_transformer(A, host, linearize(p))
296296
end
297297

‎ext/TensorKitMooncakeExt/indexmanipulations.jl‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,93 @@ function Mooncake.rrule!!(
160160
return t_Δt, twist_pullback
161161
end
162162

163+
# both are needed for correctly capturing every dispatch
164+
@is_primitive(
165+
DefaultCtx,
166+
ReverseMode,
167+
Tuple{
168+
typeof(TK.twist!),
169+
AbstractTensorMap,
170+
AbstractTensorMap, Any,
171+
Number, Number, Vararg{Any},
172+
}
173+
)
174+
@is_primitive(
175+
DefaultCtx,
176+
ReverseMode,
177+
Tuple{
178+
typeof(Core.kwcall), @NamedTuple{inv::Bool}, typeof(TK.twist!),
179+
AbstractTensorMap,
180+
AbstractTensorMap, Any,
181+
Vararg{Any},
182+
}
183+
)
184+
185+
function Mooncake.rrule!!(
186+
::CoDual{typeof(TK.twist!)},
187+
C_ΔC::CoDual{<:AbstractTensorMap},
188+
A_ΔA::CoDual{<:AbstractTensorMap}, inds_Δinds::CoDual,
189+
α_Δα::CoDual{<:Number}, β_Δβ::CoDual{<:Number},
190+
ba_Δba::CoDual...
191+
)
192+
C_ΔC, pullback = twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, false, (α_Δα, β_Δβ, ba_Δba...))
193+
twist!_pullback(Δ::NoRData) = (NoRData(), pullback(Δ)...)
194+
return C_ΔC, twist!_pullback
195+
end
196+
function Mooncake.rrule!!(
197+
::CoDual{typeof(Core.kwcall)}, kwargs_Δkwargs::CoDual{@NamedTuple{inv::Bool}}, ::CoDual{typeof(TK.twist!)},
198+
C_ΔC::CoDual{<:AbstractTensorMap},
199+
A_ΔA::CoDual{<:AbstractTensorMap}, inds_Δinds::CoDual,
200+
args_Δargs::CoDual...
201+
)
202+
inv = primal(kwargs_Δkwargs).inv
203+
C_ΔC, pullback = twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, inv, args_Δargs)
204+
twist!_pullback(Δ::NoRData) = (NoRData(), NoRData(), NoRData(), pullback(Δ)...)
205+
return C_ΔC, twist!_pullback
206+
end
207+
208+
# `args_Δargs` holds the optional `α`, `β`, backend and allocator, where a missing `α` or `β` is constant
209+
function twist!_rrule(C_ΔC, A_ΔA, inds_Δinds, inv, args_Δargs)
210+
# prepare arguments
211+
C, ΔC = arrayify(C_ΔC)
212+
A, ΔA = arrayify(A_ΔA)
213+
inds = primal(inds_Δinds)
214+
args = primal.(args_Δargs)
215+
α = length(args) >= 1 ? args[1] : One()
216+
β = length(args) >= 2 ? args[2] : Zero()
217+
ba = length(args) >= 3 ? args[3:end] : ()
218+
219+
C_cache = copy(C)
220+
221+
# if we need to compute Δa, it is faster to allocate an intermediate twisted A
222+
# and store that instead of repeating the twist in the pullback each time.
223+
# effectively, we replace `twist!` by `add ∘ twist`.
224+
Ap = if _needs_tangent(α)
225+
Ap = twist(A, inds; inv, copy = true)
226+
add!(C, Ap, α, β)
227+
Ap
228+
else
229+
TK.twist!(C, A, inds, α, β, ba...; inv)
230+
nothing
231+
end
232+
233+
function pullback(::NoRData)
234+
copy!(C, C_cache)
235+
236+
TK.twist_pb(ΔA, A, ΔC, C, inds, α, ba...; inv)
237+
ΔAr = NoRData()
238+
239+
Δαr = length(args) >= 1 ? pullback_dα(α, ΔC, Ap) : nothing
240+
Δβr = length(args) >= 2 ? pullback_dβ(β, ΔC, C) : nothing
241+
ΔCr = pullback_dC!(ΔC, β) # this typically returns NoRData()
242+
243+
Δargsr = (Δαr, Δβr, map(Returns(NoRData()), ba)...)[1:length(args)]
244+
return ΔCr, ΔAr, NoRData(), Δargsr...
245+
end
246+
247+
return C_ΔC, pullback
248+
end
249+
163250
# both are needed for correctly capturing every dispatch
164251
@is_primitive DefaultCtx ReverseMode Tuple{typeof(flip), AbstractTensorMap, Any}
165252
@is_primitive DefaultCtx ReverseMode Tuple{typeof(Core.kwcall), @NamedTuple{inv::Bool}, typeof(flip), AbstractTensorMap, Any}

‎src/pullbacks/indexmanipulations.jl‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,17 @@ for transform in (:permute, :transpose)
1515
return
1616
end
1717
end
18+
function twist_pb(ΔA, A, ΔC, C, inds, α, ba...; inv::Bool = false)
19+
TC = promote_twist(VectorInterface.promote_scale(ΔC, α), sectortype(ΔC))
20+
if scalartype(ΔA) <: Real && !(TC <: Real)
21+
ΔAc = similar(ΔC, TC)
22+
twist!(ΔAc, ΔC, inds, conj(α), Zero(), ba...; inv = !inv)
23+
add!(ΔA, real(ΔAc))
24+
else
25+
twist!(ΔA, ΔC, inds, conj(α), One(), ba...; inv = !inv)
26+
end
27+
return
28+
end
1829
function braid_pb(ΔA, A, ΔC, C, p, levels, α, ba...)
1930
ip = invperm(linearize(p))
2031
pΔA = TO.repartition(ip, numout(A))

0 commit comments

Comments
 (0)