Skip to content

Commit 5ece9d1

Browse files
lkdvosclaude
andcommitted
Refactor index manipulation kernels around position-indexed subblocks
Index manipulations now run through a single kernel that operates on subblocks addressed by position: `StridedSubblocks` (sector-independent views into the flat data of a `TensorMap`) or `TreeSubblocks` (any `AbstractTensorMap`, through `subblock`), both carrying an optional lazy conjugation. `TreeTransformer`s store only the mapping between subblock positions and recoupling coefficients, alongside the subblock structures, and are cached for every tensor type. Adjoint sources and destinations, as well as `conj` in `tensoradd!`, are folded into a conjugation flag, relabeled permutation and levels, and conjugated scalars, so that `AdjointTensorMap` wrappers no longer force the uncached generic path (fixes #516, supersedes #519 and #520). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent d95e413 commit 5ece9d1

12 files changed

Lines changed: 446 additions & 301 deletions

File tree

‎benchmark/TensorKitBenchmarks/indexmanipulations/IndexManipulationBenchmarks.jl‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ const all_parameters = TOML.parsefile(joinpath(@__DIR__, "benchparams.toml"))
1212

1313
# permute!
1414
# --------
15-
function init_permute_tensors(T, W, p)
15+
function init_permute_tensors(T, W, p, adjoint::Bool)
1616
C = randn(T, permute(W, p))
17-
A = randn(T, W)
17+
A = adjoint ? randn(T, W')' : randn(T, W)
1818
return C, A
1919
end
2020
function benchmark_permute!(benchgroup, params::Dict)
@@ -25,7 +25,9 @@ function benchmark_permute!(benchgroup, params::Dict)
2525
end
2626
return nothing
2727
end
28-
function benchmark_permute!(bench; sigmas = nothing, T = "Float64", I = "Trivial", dims, p)
28+
function benchmark_permute!(
29+
bench; sigmas = nothing, T = "Float64", I = "Trivial", dims, p, adjoint = false
30+
)
2931
T_ = parse_type(T)
3032
I_ = parse_type(I)
3133

@@ -34,9 +36,10 @@ function benchmark_permute!(bench; sigmas = nothing, T = "Float64", I = "Trivial
3436

3537
codomain = mapreduce(Base.Fix1(getindex, Vs), ⊗, p_[1]; init = one(eltype(Vs)))
3638
domain = mapreduce(Base.Fix1(getindex, Vs), ⊗, p_[2]; init = one(eltype(Vs)))
37-
init() = init_permute_tensors(T_, codomain ← domain, p_)
39+
init() = init_permute_tensors(T_, codomain ← domain, p_, adjoint)
3840

39-
bench[T, I, dims, sigmas, p] = @benchmarkable permute!(C, A, $p_) setup = ((C, A) = $init())
41+
key = adjoint ? (T, I, dims, sigmas, p, "adjoint") : (T, I, dims, sigmas, p)
42+
bench[key...] = @benchmarkable permute!(C, A, $p_) setup = ((C, A) = $init())
4043
return nothing
4144
end
4245

‎benchmark/TensorKitBenchmarks/indexmanipulations/benchparams.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ I = "Z2Irrep"
1010
p = [[[2, 1], []]]
1111
dims = [[7264, 7264], [43408, 1216]]
1212
sigmas = [[0.5, 0.5]]
13+
adjoint = [false, true]
1314

1415
[[permute]]
1516
T = ["Float64"]
@@ -24,3 +25,4 @@ I = "SU2Irrep"
2425
p = [[[1, 3], [2, 4]], [[4, 2, 3], [1]]]
2526
dims = [[48, 48, 48, 48]]
2627
sigmas = [[1.0, 1.0, 1.0, 1.0]]
28+
adjoint = [false, true]

‎docs/src/Changelog.md‎

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

2525
### Changed
2626

27+
- Index manipulations use a single kernel operating on subblocks addressed by position: `StridedSubblocks` (sector-independent views into the flat data of a `TensorMap`) or `TreeSubblocks` (any `AbstractTensorMap`, through `subblock`), both able to carry a lazy conjugation. The `TreeTransformer`s store the mapping between subblock positions and recoupling coefficients and are cached for every tensor type; conjugated and adjoint operands are handled through this mechanism instead of through `AdjointTensorMap` wrappers (internal) ([#516](https://github.com/QuantumKitHub/TensorKit.jl/issues/516))
28+
2729
### Deprecated
2830

2931
### Removed
3032

3133
### Fixed
3234

35+
- `braid!`, `permute!` and `transpose!` with a `BraidingTensor` source now use the cached fusion tree transformers ([#516](https://github.com/QuantumKitHub/TensorKit.jl/issues/516))
36+
3337
### Performance
3438

39+
- In-place `permute!`, `braid!` and `transpose!` with `AdjointTensorMap` sources or destinations, as well as `@tensor` expressions with `conj`, now use the same cached and sector-independent kernel as plain `TensorMap`s; other tensor types (e.g. `DiagonalTensorMap`) also use the cached fusion tree transformers, and `subblocks(::TensorMap)` iterates without hashing fusion trees ([#516](https://github.com/QuantumKitHub/TensorKit.jl/issues/516), [#519](https://github.com/QuantumKitHub/TensorKit.jl/pull/519), [#520](https://github.com/QuantumKitHub/TensorKit.jl/pull/520))
40+
3541
## [0.17.1](https://github.com/QuantumKitHub/TensorKit.jl/compare/v0.17.0...v0.17.1) - 2026-07-13
3642

3743
### Added

‎ext/TensorKitEnzymeExt/utility.jl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ pullback_dC!(ΔC, β::Number) = scale!(ΔC, conj(β))
2424
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.FusionTreeDict}) = true
2525
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.FusionTreeBlock}) = true
2626
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.GenericTreeTransformer}) = true
27+
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.AbelianTreeTransformer}) = true
2728
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.VectorSpace}) = true
2829
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.LRU}) = true
2930

‎src/spaces/homspace.jl‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,20 @@ See also [`degeneracystructure`](@ref), [`blockstructure`](@ref).
169169
"""
170170
subblockstructure(W::HomSpace) = Dictionary(fusiontrees(W), degeneracystructure(W).subblockstructure)
171171

172+
"""
173+
fusiontreeindices(W::HomSpace) -> Dictionary
174+
175+
Return a `Dictionary` mapping each fusion tree pair `(f₁, f₂)` to its position in
176+
[`fusiontrees`](@ref)`(W)`, which coincides with its position in
177+
[`subblockstructure`](@ref)`(W)` and in the subblocks of a `TensorMap` on `W`.
178+
179+
See also [`fusiontrees`](@ref), [`subblockstructure`](@ref).
180+
"""
181+
function fusiontreeindices(W::HomSpace)
182+
trees = fusiontrees(W)
183+
return Dictionary(trees, 1:length(trees))
184+
end
185+
172186
"""
173187
fusionblocks(W::HomSpace)
174188

‎src/tensors/blockiterator.jl‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,73 @@ function Base.show(io::IO, mime::MIME"text/plain", iter::SubblockIterator)
171171
show_subblocks(io, mime, iter)
172172
return nothing
173173
end
174+
175+
"""
176+
struct StridedSubblocks{A <: DenseVector, N, F}
177+
StridedSubblocks(t::TensorMap, [op = identity])
178+
179+
Sector-independent, integer-indexable collection of the subblocks of a `TensorMap`, as
180+
`StridedView`s into its flat data vector. Subblock `i` corresponds to the `i`th fusion tree pair
181+
in the canonical order of `fusiontrees(space(t))`, see also [`fusiontreeindices`](@ref).
182+
The operation `op` (`identity` or `conj`) is applied lazily to every view, which allows
183+
representing the subblocks of a conjugated tensor without materializing it.
184+
185+
This is the data structure consumed by the index manipulation kernels, whose type does not
186+
depend on the sectortype of `t`.
187+
"""
188+
const SubblockOp = Union{typeof(identity), typeof(conj)}
189+
struct StridedSubblocks{A <: DenseVector, N, F <: SubblockOp}
190+
data::A
191+
structure::Vector{StridedStructure{N}}
192+
op::F
193+
end
194+
Base.length(s::StridedSubblocks) = length(s.structure)
195+
Base.firstindex(s::StridedSubblocks) = 1
196+
Base.lastindex(s::StridedSubblocks) = length(s)
197+
Base.eltype(::Type{S}) where {S <: StridedSubblocks} = Core.Compiler.return_type(getindex, Tuple{S, Int})
198+
199+
Base.@propagate_inbounds function Base.getindex(s::StridedSubblocks, i::Int)
200+
sz, str, offset = s.structure[i]
201+
return StridedView(s.data, sz, str, offset, s.op)
202+
end
203+
204+
function Base.iterate(s::StridedSubblocks, i::Int = 1)
205+
i > length(s) && return nothing
206+
return @inbounds(s[i]), i + 1
207+
end
208+
209+
storagetype(::Type{StridedSubblocks{A, N, F}}) where {A, N, F} = A
210+
211+
"""
212+
struct TreeSubblocks{TT <: AbstractTensorMap, I, F}
213+
TreeSubblocks(t::AbstractTensorMap, [op = identity])
214+
215+
Integer-indexable collection of the subblocks of an arbitrary tensor `t`, where position `i`
216+
refers to the `i`th fusion tree pair of `fusiontrees(space(t))` and the data is retrieved through
217+
[`subblock`](@ref), with `op` (`identity` or `conj`) applied. This is the generic counterpart of
218+
[`StridedSubblocks`](@ref) for tensor types that do not store their data in a flat vector.
219+
"""
220+
struct TreeSubblocks{TT <: AbstractTensorMap, I, F <: SubblockOp}
221+
t::TT
222+
trees::I
223+
op::F
224+
end
225+
function TreeSubblocks(t::AbstractTensorMap, op::SubblockOp = identity)
226+
return TreeSubblocks(t, fusiontrees(t), scalartype(t) <: Real ? identity : op)
227+
end
228+
229+
storagetype(::Type{TreeSubblocks{TT, I, F}}) where {TT, I, F} = storagetype(TT)
230+
231+
Base.length(s::TreeSubblocks) = length(s.trees)
232+
Base.firstindex(s::TreeSubblocks) = 1
233+
Base.lastindex(s::TreeSubblocks) = length(s)
234+
Base.eltype(::Type{S}) where {S <: TreeSubblocks} = Core.Compiler.return_type(getindex, Tuple{S, Int})
235+
236+
Base.@propagate_inbounds function Base.getindex(s::TreeSubblocks, i::Int)
237+
return s.op(subblock(s.t, gettokenvalue(s.trees, i)))
238+
end
239+
240+
function Base.iterate(s::TreeSubblocks, i::Int = 1)
241+
i > length(s) && return nothing
242+
return @inbounds(s[i]), i + 1
243+
end

‎src/tensors/braidingtensor.jl‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -195,16 +195,8 @@ end
195195
# Index manipulations
196196
# -------------------
197197
has_shared_permute(t::BraidingTensor, ::Index2Tuple) = false
198-
function add_transform!(
199-
tdst::AbstractTensorMap,
200-
tsrc::BraidingTensor, (p₁, p₂)::Index2Tuple,
201-
fusiontreetransform,
202-
α::Number, β::Number, backend::AbstractBackend...
203-
)
204-
return add_transform!(
205-
tdst, TensorMap(tsrc), (p₁, p₂), fusiontreetransform, α, β,
206-
backend...
207-
)
198+
function unwrap_adjoints(tdst, tsrc::BraidingTensor, p::Index2Tuple, levels, conjsrc::Bool, α, β)
199+
return unwrap_adjoints(tdst, TensorMap(tsrc), p, levels, conjsrc, α, β)
208200
end
209201

210202
function planarcontract!(

0 commit comments

Comments
 (0)