Skip to content

Commit 5ea4742

Browse files
leburgelclaude
andcommitted
Transform small subblocks in shape groups on the CPU instead of one tensoradd! per subblock
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b58fa66 commit 5ea4742

2 files changed

Lines changed: 151 additions & 7 deletions

File tree

‎src/tensors/indexmanipulations.jl‎

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -655,9 +655,23 @@ function add_transform_kernel!(
655655
dst::TransformSubblocks, src::TransformSubblocks, p, conjsrc::Bool,
656656
transformer::TreeTransformer, α, β, backend, allocator, ntasks::Int
657657
)
658+
return _add_transform_blocks!(dst, src, p, conjsrc, transformer, transformer.data, α, β, backend, allocator, ntasks)
659+
end
660+
# on the CPU, the small subblocks of `TensorMap`s are transformed in groups, the others one by one
661+
function add_transform_kernel!(
662+
dst::StridedSubblocks{<:CPUStorage}, src::StridedSubblocks{<:CPUStorage}, p, conjsrc::Bool,
663+
transformer::TreeTransformer, α, β, backend, allocator, ntasks::Int
664+
)
665+
_add_subblockgroups!(dst.data, src.data, conjsrc, transformer.groups, α, β, ntasks)
666+
large = view(transformer.data, transformer.large)
667+
return _add_transform_blocks!(dst, src, p, conjsrc, transformer, large, α, β, backend, allocator, ntasks)
668+
end
669+
670+
function _add_transform_blocks!(dst, src, p, conjsrc::Bool, transformer, data, α, β, backend, allocator, ntasks::Int)
671+
isempty(data) && return nothing
658672
bufsize = buffersize(transformer)
659673
if bufsize == 0 # no recoupling needed: every block consists of a single tree
660-
taskforeach(transformer.data, ntasks) do (U, inds_dst, inds_src)
674+
taskforeach(data, ntasks) do (U, inds_dst, inds_src)
661675
_add_transform_block!(dst, src, p, conjsrc, U, inds_dst, inds_src, nothing, α, β, backend, allocator)
662676
end
663677
else
@@ -667,9 +681,9 @@ function add_transform_kernel!(
667681
cp = TO.allocator_checkpoint!(allocator)
668682
@timeit_debug GLOBAL_TIMER "alloc: buffers" buffers = [
669683
TO.tensoralloc(storagetype(dst), bufsize, Val(true), allocator)
670-
for _ in 1:min(length(transformer.data), ntasks)
684+
for _ in 1:min(length(data), ntasks)
671685
]
672-
taskforeach(transformer.data, buffers) do (U, inds_dst, inds_src), buffer
686+
taskforeach(data, buffers) do (U, inds_dst, inds_src), buffer
673687
_add_transform_block!(dst, src, p, conjsrc, U, inds_dst, inds_src, buffer, α, β, backend, allocator)
674688
end
675689
foreach(Base.Fix2(TO.tensorfree!, allocator), buffers)
@@ -721,6 +735,49 @@ function _add_transform_block!(
721735
return nothing
722736
end
723737

738+
function _add_subblockgroups!(A, B, conjsrc::Bool, groups, α, β, ntasks::Int)
739+
return conjsrc ? _add_subblockgroups!(A, B, conj, groups, α, β, ntasks) :
740+
_add_subblockgroups!(A, B, identity, groups, α, β, ntasks)
741+
end
742+
function _add_subblockgroups!(A, B, op, groups, α, β, ntasks::Int)
743+
if ntasks == 1
744+
foreach(group -> _add_subblockgroup!(A, B, op, group, eachindex(group.coeff), α, β), groups)
745+
else
746+
# tasks handle disjoint ranges of destination offsets, and thus disjoint subblocks
747+
nchunks = 4 * ntasks
748+
taskforeach(1:nchunks, ntasks) do c
749+
lo, hi = div((c - 1) * length(A), nchunks), div(c * length(A), nchunks)
750+
for group in groups
751+
terms = searchsortedfirst(group.offset_dst, lo):(searchsortedfirst(group.offset_dst, hi) - 1)
752+
_add_subblockgroup!(A, B, op, group, terms, α, β)
753+
end
754+
end
755+
end
756+
return nothing
757+
end
758+
759+
# the metadata of the groups is built together with the transformer, which ensures the indices are inbounds
760+
function _add_subblockgroup!(A, B, op, group::SubblockGroup, terms, α, β)
761+
(; rel_dst, rel_src, offset_dst, offset_src, coeff) = group
762+
@inbounds for n in terms
763+
o₁, o₂, a = offset_dst[n], offset_src[n], α * coeff[n]
764+
if group.accumulate
765+
@simd for k in eachindex(rel_dst)
766+
A[o₁ + rel_dst[k]] += a * op(B[o₂ + rel_src[k]])
767+
end
768+
elseif iszero(β)
769+
@simd for k in eachindex(rel_dst)
770+
A[o₁ + rel_dst[k]] = a * op(B[o₂ + rel_src[k]])
771+
end
772+
else
773+
@simd for k in eachindex(rel_dst)
774+
A[o₁ + rel_dst[k]] = a * op(B[o₂ + rel_src[k]]) + β * A[o₁ + rel_dst[k]]
775+
end
776+
end
777+
end
778+
return nothing
779+
end
780+
724781
# computes `buffer_dst = buffer_src * transpose(U)`, where both are column-major views into `buffer`
725782
_recouple!(buffer, buffer_dst, buffer_src, U) =
726783
(mul!(buffer_dst, buffer_src, transpose(StridedView(U))); nothing)

‎src/tensors/treetransformers.jl‎

Lines changed: 91 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,30 @@ function recoupling_scalartype(::Type{A}, ::Type{Tₛ}) where {A, Tₛ <: Number
3333
return Tₛ <: Real ? real(T) : complex(T)
3434
end
3535

36+
"""
37+
SubblockGroup{T}
38+
39+
Small subblocks of equal size and strides, which are transformed by a single loop over all of them
40+
rather than by one `tensoradd!` call per subblock. Entry `k` of a subblock lies at `rel_dst[k]`
41+
and `rel_src[k]` relative to the offsets of the destination and source subblock, where the source
42+
strides are permuted such that both refer to the same entry. Term `n` then computes
43+
`dst[offset_dst[n] .+ rel_dst] = α * coeff[n] * src[offset_src[n] .+ rel_src] + b * dst[offset_dst[n] .+ rel_dst]`,
44+
with `b = β` for the first term into every destination subblock and `b = 1` for the groups of
45+
further recoupling terms, which have `accumulate` set and are applied after all others.
46+
The terms are sorted by `offset_dst`.
47+
"""
48+
struct SubblockGroup{T}
49+
rel_dst::Vector{Int}
50+
rel_src::Vector{Int}
51+
offset_dst::Vector{Int}
52+
offset_src::Vector{Int}
53+
coeff::Vector{T}
54+
accumulate::Bool
55+
end
56+
57+
# subblocks up to this length are transformed in `SubblockGroup`s
58+
const SUBBLOCKGROUP_MAXLENGTH = 1024
59+
3660
# (coefficient, destination position, source position)
3761
const UniqueTransformerData{T} = Tuple{T, Int, Int}
3862

@@ -42,12 +66,16 @@ const UniqueTransformerData{T} = Tuple{T, Int, Int}
4266
Tree transformation for `UniqueFusion` sectors, where every source subblock maps onto a single
4367
destination subblock with a scalar coefficient, stored as `(coeff, idst, isrc)`. The subblock
4468
structures of the destination and source spaces are kept alongside, such that the
45-
[`StridedSubblocks`](@ref) of both tensors can be created without further lookups.
69+
[`StridedSubblocks`](@ref) of both tensors can be created without further lookups. The small
70+
subblocks are also collected in [`SubblockGroup`](@ref)s, and `large` holds the positions in
71+
`data` of the others.
4672
"""
4773
struct UniqueTreeTransformer{T, N} <: TreeTransformer
4874
data::Vector{UniqueTransformerData{T}}
4975
structure_dst::Vector{StridedStructure{N}}
5076
structure_src::Vector{StridedStructure{N}}
77+
groups::Vector{SubblockGroup{T}}
78+
large::Vector{Int}
5179
end
5280

5381
# (recoupling matrix, destination positions, source positions)
@@ -60,12 +88,16 @@ Tree transformation for sectors with multiple fusion channels, where the subbloc
6088
[`FusionTreeBlock`](@ref) map onto the subblocks of the transformed block through a recoupling
6189
matrix, stored as `(U, inds_dst, inds_src)`, where `U[j, i]` maps source `i` onto destination `j`.
6290
The subblock structures of the destination and source spaces are kept alongside, such that the
63-
[`StridedSubblocks`](@ref) of both tensors can be created without further lookups.
91+
[`StridedSubblocks`](@ref) of both tensors can be created without further lookups. The blocks of
92+
small subblocks are also collected in [`SubblockGroup`](@ref)s, and `large` holds the positions in
93+
`data` of the others.
6494
"""
6595
struct GenericTreeTransformer{T, N} <: TreeTransformer
6696
data::Vector{GenericTransformerData{T}}
6797
structure_dst::Vector{StridedStructure{N}}
6898
structure_src::Vector{StridedStructure{N}}
99+
groups::Vector{SubblockGroup{T}}
100+
large::Vector{Int}
69101
end
70102

71103
function UniqueTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::HomSpace, conjsrc::Bool) where {A}
@@ -85,7 +117,8 @@ function UniqueTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::Ho
85117

86118
structure_dst = degeneracystructure(Vdst).subblockstructure
87119
structure_src = degeneracystructure(Vsrc).subblockstructure
88-
transformer = UniqueTreeTransformer(data, structure_dst, structure_src)
120+
groups, large = subblockgroups(T, data, structure_dst, structure_src, linearize(p))
121+
transformer = UniqueTreeTransformer(data, structure_dst, structure_src, groups, large)
89122

90123
Δt = Base.time() - t₀
91124
@debug(lazy"Treetransformer for $Vsrc to $Vdst via $p", conjsrc, nblocks = length(data), Δt)
@@ -137,7 +170,8 @@ function GenericTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::H
137170

138171
# sort by (approximate) weight to facilitate multi-threading strategies
139172
@timeit_debug GLOBAL_TIMER "bookkeeping: sort" Base.permute!(data, sortperm(weights; rev = true))
140-
transformer = GenericTreeTransformer{T, numind(Vdst)}(data, structure_dst, structure_src)
173+
groups, large = subblockgroups(T, data, structure_dst, structure_src, linearize(p))
174+
transformer = GenericTreeTransformer{T, numind(Vdst)}(data, structure_dst, structure_src, groups, large)
141175

142176
Δt = Base.time() - t₀
143177
@debug(
@@ -151,6 +185,59 @@ function GenericTreeTransformer(::Type{A}, transform, p, Vdst::HomSpace, Vsrc::H
151185
return transformer
152186
end
153187

188+
"""
189+
subblockgroups(T, data, structure_dst, structure_src, p) -> (groups, large)
190+
191+
Collect the terms of the transformer `data` that act on subblocks with at most
192+
`SUBBLOCKGROUP_MAXLENGTH` entries into [`SubblockGroup`](@ref)s by size and strides, with the
193+
accumulating groups last, and return them together with the positions in `data` of the other entries.
194+
"""
195+
function subblockgroups(::Type{T}, data, structure_dst::Vector{StridedStructure{N}}, structure_src, p) where {T, N}
196+
terms = Tuple{T, Int, Int, Bool}[]
197+
large = Int[]
198+
for (n, (U, inds_dst, inds_src)) in enumerate(data)
199+
if prod(first(structure_dst[first(inds_dst)])) > SUBBLOCKGROUP_MAXLENGTH
200+
push!(large, n)
201+
else
202+
_push_terms!(terms, U, inds_dst, inds_src)
203+
end
204+
end
205+
sort!(terms; by = term -> structure_dst[term[2]][3])
206+
207+
# strides of dimensions of size 1 are irrelevant, and set to zero to obtain fewer groups
208+
groups = Dict{Tuple{Bool, NTuple{3, NTuple{N, Int}}}, SubblockGroup{T}}()
209+
for (coeff, idst, isrc, accumulate) in terms
210+
sz, strides_dst, offset_dst = structure_dst[idst]
211+
_, strides_src, offset_src = structure_src[isrc]
212+
strides_dst = map((n, s) -> n == 1 ? 0 : s, sz, strides_dst)
213+
strides_src′ = map((n, s) -> n == 1 ? 0 : s, sz, TupleTools.getindices(strides_src, p))
214+
group = get!(groups, (accumulate, (sz, strides_dst, strides_src′))) do
215+
rel_dst, rel_src = Int[], Int[]
216+
for I in CartesianIndices(sz)
217+
push!(rel_dst, 1 + sum((Tuple(I) .- 1) .* strides_dst; init = 0))
218+
push!(rel_src, 1 + sum((Tuple(I) .- 1) .* strides_src′; init = 0))
219+
end
220+
return SubblockGroup(rel_dst, rel_src, Int[], Int[], T[], accumulate)
221+
end
222+
push!(group.offset_dst, offset_dst)
223+
push!(group.offset_src, offset_src)
224+
push!(group.coeff, coeff)
225+
end
226+
return sort!(collect(values(groups)); by = group -> group.accumulate), large
227+
end
228+
229+
_push_terms!(terms, coeff::Number, idst::Int, isrc::Int) = push!(terms, (coeff, idst, isrc, false))
230+
function _push_terms!(terms, U::AbstractMatrix, inds_dst, inds_src)
231+
for (i, idst) in enumerate(inds_dst)
232+
js = findall(!iszero, view(U, i, :))
233+
isempty(js) && push!(js, 1) # such that β is still applied
234+
for j in js
235+
push!(terms, (U[i, j], idst, inds_src[j], j != first(js)))
236+
end
237+
end
238+
return terms
239+
end
240+
154241
"""
155242
buffersize(transformer::TreeTransformer) -> Int
156243

0 commit comments

Comments
 (0)