Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/src/Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec

- `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))
- `foreachblock` with several tensors is type stable, which removes the dynamic dispatch on every call to it and to the factorizations that go through it
- `permute`, `braid`, `transpose` and `twist` on a `TensorMap` transform blocks of at most 1024 entries by a plain loop over the data instead of through `tensoradd!` and `mul!`, whose call overhead dominated for tensors with many small subblocks

## [0.17.3](https://github.com/QuantumKitHub/TensorKit.jl/compare/v0.17.2...v0.17.3) - 2026-10-30

Expand Down
70 changes: 70 additions & 0 deletions src/tensors/indexmanipulations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,76 @@ function _add_transform_block!(
return nothing
end

# blocks with at most this many entries to compute are transformed by plain loops
const SMALL_BLOCK_LENGTH = 1024

# On the CPU, the call overhead of `tensoradd!` and `mul!` dominates for small blocks of a `TensorMap`,
# which are therefore transformed by a plain loop over the flat data for every term of `U`.
function _add_transform_block!(
dst::StridedSubblocks{<:CPUStorage}, src::StridedSubblocks{<:CPUStorage}, p, conjsrc::Bool,
U, inds_dst, inds_src, buffer, α, β, backend, allocator
)
if length(U) * prod(first(@inbounds src.structure[first(inds_src)])) > SMALL_BLOCK_LENGTH

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.

This is actually quite a good point, and somewhat independent of the strided kernel:
I think currently the recoupling step that uses the buffer only ever checks the size of U being 1x1, while arguably things like 2x2 still don't benefit from the BLAS call: every input has to be copied twice anyways, so the gain from the BLAS intermediate accessing memory more efficiently is completely not there. Ultimately, I think to get optimal performance it would be nice to get a custom kernel for the recoupling as a whole, which does something like QuasiStrided.jl but then for "lists of inputs" rather than just regular strided inputs. If someone has some tokens to burn and/or compute to do this it might still speed up things by quite a lot, also for the larger cases, but 🤷

return @invoke _add_transform_block!(
dst::TransformSubblocks, src::TransformSubblocks, p, conjsrc, U, inds_dst, inds_src, buffer,
α, β, backend, allocator
)
end
op = conjsrc ? conj : identity
@inbounds for (i, idst) in enumerate(inds_dst), (j, isrc) in enumerate(inds_src)
j == 1 || !iszero(U[i, j]) || continue # the first term also applies `β`
_add_strided!(
dst.data, src.data, dst.structure[idst], src.structure[isrc], linearize(p),
op, α * U[i, j], j == 1 ? β : One()
)
end
return nothing
end

# computes `A = β * A + α * permutedims(op.(B), p)` for the strided arrays `A` and `B` within `a` and `b`
function _add_strided!(a, b, (sz, strides_dst, offset_dst), (_, strides_src, offset_src), p, op::F, α, β) where {F}

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.

How does this compare to actually forming the StridedView and doing a broadcasting expression on that?
It might actually make sense to fix this "higher up", ie just make Strided.jl bypass all its optimizations/blocking/... when the number of entries is below 1024. The main question is a bit which part of the tensoradd! stack actually adds all the overhead, and whether or not we can get rid of it.

This is mostly what I was trying to do before, but definitely did not go into a lot of detail on that. (As a side comment, can you double-check you are comparing to the latest versions of Strided-TensorOperations, since some of the improvements did actually make it in)

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.

I checked, and this was all tested using the latest versions of everything at the time: Strided 2.6.7 (so with #87–#92 and #97), StridedViews 0.5.5, TensorOperations 5.8.4. StridedViews had a new release since, but that shouldn't affect the timings here.

For a 4-entry, 6-index ComplexF64 block, one tensoradd! call costs about 220 ns on my workstation, against about 20 ns for the loop. Forming the StridedView is ~1 ns, and broadcasting on it costs the same as tensoradd!, so it is not the TensorOperations wrapper (under 10% of the profile). About 60% of the samples are in _mapreduce_order! → order_and_fuse_dims (_fusedims, indexorder, the cost computation), and ~11% in the kernel itself.

I also tried out QuantumKitHub/Strided.jl#99, cherry-picked onto main, plus stridedtensoradd! calling the new permutedims!, so that TensorKit main picks it up unchanged. On top of that I added a plain loop nest for at most 32 elements that skips the sorting and fusing. permute! in ms on a shared, loaded machine (not the workstation, so only the ratios mean something; minimum over 8 interleaved runs):

subblocks / largest main main + Strided#99 main + Strided#99 + loop this PR
9632 / 16 (fℤ₂ ⊠ U1) 5.65 3.48 1.62 0.92
40736 / 4 (fℤ₂ ⊠ U1) 26.9 18.7 12.0 7.15
301 / 256 (U1) 0.32 0.21 0.23 0.14
977 / 4 (fℤ₂ ⊠ SU2) 1.14 0.65 0.59 0.18
977 / 256 (fℤ₂ ⊠ SU2) 2.49 2.25 2.35 2.69
301 / 16384 (U1) 17.5 17.2 18.1 17.4

So for Abelian symmetries with tiny blocks a Strided-side fix recovers most of it (75–85% of the time this PR saves), and it helps everything else that calls tensoradd! on small arrays. It doesn't cover the non-Abelian case, where the remaining time is the per-block recoupling and not the permutation.

One way forward would be to keep this PR for the small blocks, get the small path into Strided, and then lower the 1024 cutoff here to whatever the Strided path does not already handle well. Above ~256 entries the Strided kernel is already as fast as the loop, and faster for β ≠ 0 on complex data, so the cutoff here can probably come down quite a bit.

strides_src′ = TupleTools.getindices(strides_src, p)
# loop over dimensions of size 1 outermost, so that the innermost loop is a nontrivial one
sz, strides_dst, strides_src′ = _permutedims3(_singletons_last(sz), sz, strides_dst, strides_src′)
# fuse dimensions along which both arrays are contiguous, and move the size-1 dimensions this leaves outward
sz = _fusedims(sz, strides_dst, strides_src′)
sz, strides_dst, strides_src′ = _permutedims3(_singletons_last(sz), sz, strides_dst, strides_src′)
if iszero(β)
_stridedloop(sz, strides_dst, strides_src′, offset_dst + 1, offset_src + 1) do i, j
@inbounds a[i] = α * op(b[j])
end
else
_stridedloop(sz, strides_dst, strides_src′, offset_dst + 1, offset_src + 1) do i, j
@inbounds a[i] = α * op(b[j]) + β * a[i]
end
end
return nothing
end

_permutedims3(q, ts...) = map(t -> TupleTools.getindices(t, q), ts)
_singletons_last(sz::Dims{N}) where {N} = TupleTools.sortperm(ntuple(k -> k + N * (sz[k] == 1), Val(N)))

# merges dimension `k + 1` into `k` wherever both arrays are contiguous across them, leaving size 1 at `k + 1`
function _fusedims(sz::Dims{N}, s₁::Dims{N}, s₂::Dims{N}) where {N}
for k in (N - 1):-1:1
if s₁[k + 1] == sz[k] * s₁[k] && s₂[k + 1] == sz[k] * s₂[k]
sz = Base.setindex(Base.setindex(sz, sz[k] * sz[k + 1], k), 1, k + 1)
end
end
return sz
end

# calls `f(i, j)` for the positions of all corresponding entries of two strided arrays of size `sz`
@inline _stridedloop(f, ::Tuple{}, ::Tuple{}, ::Tuple{}, i::Int, j::Int) = f(i, j)
@inline function _stridedloop(f, sz::Tuple, strides₁::Tuple, strides₂::Tuple, i::Int, j::Int)
for _ in 1:last(sz)
_stridedloop(f, Base.front(sz), Base.front(strides₁), Base.front(strides₂), i, j)
i += last(strides₁)
j += last(strides₂)
end
return nothing
end
Comment on lines +831 to +840

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.

This is actually quite a cool code pattern, I wonder if it could be used to replace some of the @generated functions in the Strided kernels. In particular, something I always wondered about is whether this could be used to reduce the compilation time a bit, for example by only inlining the first N layers and then actually using a function call. (This is definitely something Claude can play around with rather quickly/efficiently 😉)

Ultimately, I do think it reads a lot nicer than the actual generated functions so that would also be a bonus.

@Jutho tagging you here explicitly, since this might be of interest to you 😄

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.

Yes this looks very cool indeed.
As an aside, I hope to finally have a proper chunk of time for PR reviews the next few days.


# computes `buffer_dst = buffer_src * transpose(U)`, where both are column-major views into `buffer`
_recouple!(buffer, buffer_dst, buffer_src, U) =
(mul!(buffer_dst, buffer_src, transpose(StridedView(U))); nothing)
Expand Down
15 changes: 15 additions & 0 deletions test/tensors/indexmanipulations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,18 @@ for V in spacelist
end
TensorKit.empty_globalcaches!()
end

@timedtestset "Permutations with small and large blocks" begin
# blocks up to `SMALL_BLOCK_LENGTH` entries are transformed by plain loops, larger ones through `tensoradd!`
V = Vect[SU2Irrep](0 => 6, 1 // 2 => 6, 1 => 1)
t = rand(ComplexF64, V ⊗ V ⊗ V ← V)
@test minimum(length ∘ last, subblocks(t)) < TensorKit.SMALL_BLOCK_LENGTH < maximum(length ∘ last, subblocks(t))
a = convert(Array, t)
for p in (((1, 4), (2, 3)), ((3, 1, 4), (2,)))
a′ = permutedims(a, (p[1]..., p[2]...))
@test convert(Array, permute(t, p)) ≈ a′
tdst = rand(ComplexF64, permute(space(t), p))
@test convert(Array, permute!(copy(tdst), t, p, 0.7im, 0.3)) ≈ 0.7im * a′ + 0.3 * convert(Array, tdst)
end
@test convert(Array, permute(t', ((3, 1), (4, 2)))) ≈ permutedims(convert(Array, t'), (3, 1, 4, 2))
end