From 69180b2c279fe0b7eef77de46f1d6bd68972b54d Mon Sep 17 00:00:00 2001 From: leburgel Date: Wed, 18 Nov 2026 13:33:35 +0100 Subject: [PATCH 1/3] Transform small blocks by a plain loop in the CPU add_transform! On the CPU, `permute`, `braid`, `transpose` and `twist` call `tensoradd!` once per subblock (and `mul!` once per multi-tree block), whose call overhead dominates for tensors with many small subblocks. Blocks of a `TensorMap` with at most 1024 entries to compute are now transformed term by term with a plain loop over the flat data, addressed directly through the cached subblock structure. Nothing is added to the tree transformers. `taskforeach` skips the atomic counter for a single worker. Co-Authored-By: Claude Fable 5.2 --- docs/src/Changelog.md | 1 + src/auxiliary/auxiliary.jl | 2 ++ src/tensors/indexmanipulations.jl | 52 ++++++++++++++++++++++++++++++ test/tensors/indexmanipulations.jl | 15 +++++++++ 4 files changed, 70 insertions(+) diff --git a/docs/src/Changelog.md b/docs/src/Changelog.md index 63d293e9b..c8ae48b8c 100644 --- a/docs/src/Changelog.md +++ b/docs/src/Changelog.md @@ -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 diff --git a/src/auxiliary/auxiliary.jl b/src/auxiliary/auxiliary.jl index b46800a50..df327dc55 100644 --- a/src/auxiliary/auxiliary.jl +++ b/src/auxiliary/auxiliary.jl @@ -102,6 +102,7 @@ Apply `f(item)` (respectively `f(item, resource)`) to all elements of `items`, d The calling thread acts as the first of the workers, so at most `ntasks - 1` tasks are spawned, and none at all for a single worker. """ function taskforeach(f, items, ntasks::Integer) + ntasks == 1 && return foreach(f, items) items′ = items isa AbstractArray ? items : collect(items) n = length(items′) nworkers = min(ntasks, n) @@ -116,6 +117,7 @@ function taskforeach(f, items, ntasks::Integer) return nothing end function taskforeach(f, items, resources) + length(resources) == 1 && return foreach(Base.Fix2(f, only(resources)), items) items′ = items isa AbstractArray ? items : collect(items) n = length(items′) nworkers = min(length(resources), n) diff --git a/src/tensors/indexmanipulations.jl b/src/tensors/indexmanipulations.jl index 78a7d82fe..c2532b312 100644 --- a/src/tensors/indexmanipulations.jl +++ b/src/tensors/indexmanipulations.jl @@ -769,6 +769,58 @@ 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 + 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} + strides_src′ = TupleTools.getindices(strides_src, p) + 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 + +# 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 + # 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) diff --git a/test/tensors/indexmanipulations.jl b/test/tensors/indexmanipulations.jl index c4059e00d..9374ff7d4 100644 --- a/test/tensors/indexmanipulations.jl +++ b/test/tensors/indexmanipulations.jl @@ -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 From d72a753092f72790d816e59e838e54bc72adce8e Mon Sep 17 00:00:00 2001 From: leburgel Date: Wed, 18 Nov 2026 14:26:50 +0100 Subject: [PATCH 2/3] Move the single-worker path of taskforeach to its own PR Co-Authored-By: Claude Fable 5.2 --- src/auxiliary/auxiliary.jl | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/auxiliary/auxiliary.jl b/src/auxiliary/auxiliary.jl index df327dc55..b46800a50 100644 --- a/src/auxiliary/auxiliary.jl +++ b/src/auxiliary/auxiliary.jl @@ -102,7 +102,6 @@ Apply `f(item)` (respectively `f(item, resource)`) to all elements of `items`, d The calling thread acts as the first of the workers, so at most `ntasks - 1` tasks are spawned, and none at all for a single worker. """ function taskforeach(f, items, ntasks::Integer) - ntasks == 1 && return foreach(f, items) items′ = items isa AbstractArray ? items : collect(items) n = length(items′) nworkers = min(ntasks, n) @@ -117,7 +116,6 @@ function taskforeach(f, items, ntasks::Integer) return nothing end function taskforeach(f, items, resources) - length(resources) == 1 && return foreach(Base.Fix2(f, only(resources)), items) items′ = items isa AbstractArray ? items : collect(items) n = length(items′) nworkers = min(length(resources), n) From 5ef0dc78e09288c2440f2d75e71118095ffc82ab Mon Sep 17 00:00:00 2001 From: leburgel Date: Tue, 24 Nov 2026 06:50:48 +0100 Subject: [PATCH 3/3] Loop over size-1 dimensions outermost and fuse contiguous dimensions in _add_strided! Co-Authored-By: Claude Opus 5.5 --- src/tensors/indexmanipulations.jl | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/tensors/indexmanipulations.jl b/src/tensors/indexmanipulations.jl index c2532b312..9c0a3b13e 100644 --- a/src/tensors/indexmanipulations.jl +++ b/src/tensors/indexmanipulations.jl @@ -798,6 +798,11 @@ 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} 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]) @@ -810,6 +815,19 @@ function _add_strided!(a, b, (sz, strides_dst, offset_dst), (_, strides_src, off 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)