@@ -10,6 +10,7 @@ using MatrixAlgebraKit, Adapt
1010using TensorKit
1111using TensorKit. TensorOperations: linearize, DefaultAllocator
1212using TensorKit. VectorInterface: One
13+ const TO = TensorKit. TensorOperations
1314using TensorKit. Factorizations
1415using TensorKit. Factorizations: AbstractAlgorithm
1516using TensorKit: SectorDict, tensormaptype, scalar, similarstoragetype, AdjointTensorMap, scalartype, project_symmetric_and_check
@@ -273,11 +274,17 @@ function DeviceGenericTreeTransformer(
273274 )
274275end
275276
277+ # Planar traces run in two stages. The first computes partial traces of every source subblock:
278+ # each thread sums a chunk of at most `chunksize` traced entries for a single remaining entry,
279+ # such that large traces (e.g. full reductions) are still spread over many threads. The second
280+ # recouples these partials with one thread per destination element, as for the generic transformers,
281+ # such that the traced entries of a source are summed only once, rather than once per destination tree.
282+
276283"""
277284 TraceTransformerBlock{N}
278285
279286Descriptor for a destination block of a `TraceTransformer`, indexing into the flat
280- `coeffs`/`structs_dst`/`structs_src ` vectors of a `DeviceTraceTransformer`.
287+ `coeffs`/`structs_dst`/`sources ` vectors of a `DeviceTraceTransformer`.
281288"""
282289struct TraceTransformerBlock{N}
283290 sz:: NTuple{N, Int}
@@ -289,35 +296,60 @@ struct TraceTransformerBlock{N}
289296 src_offset:: Int
290297end
291298
292- # (permuted strides of the remaining legs, sizes, dense strides and summed strides of the traced
293- # pairs, offset): the traced entries of a source subblock are found through a single stride per pair
294- const TraceSourceStructure{N, M} = Tuple{NTuple{N, Int}, NTuple{M, Int}, NTuple{M, Int}, NTuple{M, Int}, Int}
299+ """
300+ TraceSourceBlock{N, M}
295301
296- struct DeviceTraceTransformer{VB <: AbstractVector{<:TraceTransformerBlock} , VO <: AbstractVector{Int} , VC <: AbstractVector{<:Number} , VD <: AbstractVector {<: Tuple{<:Tuple{Vararg{Int}}, Int} }, VS <: AbstractVector{<:TraceSourceStructure} }
302+ Descriptor for the partial traces of a source subblock of a `TraceTransformer`, with `N` remaining
303+ legs (permuted to the destination order) and `M` traced pairs, whose entries are found through a
304+ single stride per pair. The partials are stored chunk-major, as `nchunks` dense arrays of shape `sz`.
305+ """
306+ struct TraceSourceBlock{N, M}
307+ sz:: NTuple{N, Int}
308+ dense_strides:: NTuple{N, Int}
309+ permuted_strides:: NTuple{N, Int}
310+ offset:: Int
311+ sz_traced:: NTuple{M, Int}
312+ dense_strides_traced:: NTuple{M, Int}
313+ strides_traced:: NTuple{M, Int} # strides[q₁] .+ strides[q₂]
314+ nremaining:: Int
315+ ntraced:: Int
316+ chunksize:: Int
317+ nchunks:: Int
318+ end
319+
320+ struct DeviceTraceTransformer{VB <: AbstractVector{<:TraceTransformerBlock} , VO <: AbstractVector{Int} , VC <: AbstractVector{<:Number} , VD <: AbstractVector {<: Tuple{<:Tuple{Vararg{Int}}, Int} }, VS <: AbstractVector{<:TraceSourceBlock} }
297321 blocks:: VB
298322 work_offsets:: VO
299323 nwork:: Int
300324 coeffs:: VC # every `U`, concatenated in column-major order
301325 structs_dst:: VD
302- structs_src:: VS
326+ sources:: VS
327+ partial_offsets:: VO # also the work offsets of the first stage
328+ npartials:: Int
303329end
304330
331+ # traces with fewer entries are not split, larger ones are split into at most `√ntraced` chunks,
332+ # such that no thread in either stage sums more than `max(256, √ntraced)` entries
333+ const MIN_TRACE_CHUNKSIZE = 256
334+ _trace_chunksize (ntraced:: Int ) = max (MIN_TRACE_CHUNKSIZE, isqrt (ntraced))
335+
305336function DeviceTraceTransformer (transformer:: TraceTransformer{T, N₁, N₂} , p, (q₁, q₂)) where {T, N₁, N₂}
306337 lp = linearize (p)
307338 M = length (q₁)
308339 blocks = TraceTransformerBlock{N₁}[]
309340 coeffs = T[]
310341 structs_dst = TreeStructure{N₁}[]
311- structs_src = TraceSourceStructure {N₁, M}[]
342+ sources = TraceSourceBlock {N₁, M}[]
312343
313344 (; structure_dst, structure_src) = transformer
314345 for (U, inds_dst, inds_src) in transformer. data
315346 # all destination trees in a block share the same subblock size
316347 size_dst = first (structure_dst[first (inds_dst)])
348+ dense_strides_dst = _dense_strides (size_dst)
317349 push! (
318350 blocks, TraceTransformerBlock {N₁} (
319- size_dst, _dense_strides (size_dst) , size (U, 1 ), size (U, 2 ),
320- length (coeffs), length (structs_dst), length (structs_src )
351+ size_dst, dense_strides_dst , size (U, 1 ), size (U, 2 ),
352+ length (coeffs), length (structs_dst), length (sources )
321353 )
322354 )
323355 append! (coeffs, U)
@@ -329,17 +361,23 @@ function DeviceTraceTransformer(transformer::TraceTransformer{T, N₁, N₂}, p,
329361 size_src, strides_src, offset_src = structure_src[isrc]
330362 size_traced = TupleTools. getindices (size_src, q₁)
331363 strides_traced = TupleTools. getindices (strides_src, q₁) .+ TupleTools. getindices (strides_src, q₂)
364+ ntraced = prod (size_traced)
365+ chunksize = _trace_chunksize (ntraced)
332366 push! (
333- structs_src, (
334- TupleTools. getindices (strides_src, lp), size_traced,
335- _dense_strides (size_traced), strides_traced, offset_src,
367+ sources, TraceSourceBlock {N₁, M} (
368+ size_dst, dense_strides_dst, TupleTools. getindices (strides_src, lp), offset_src,
369+ size_traced, _dense_strides (size_traced), strides_traced,
370+ prod (size_dst), ntraced, chunksize, cld (ntraced, chunksize)
336371 )
337372 )
338373 end
339374 end
340375
341376 work_offsets, nwork = _work_offsets (blk. rows * prod (blk. sz) for blk in blocks)
342- return DeviceTraceTransformer (blocks, work_offsets, nwork, coeffs, structs_dst, structs_src)
377+ partial_offsets, npartials = _work_offsets (src. nchunks * src. nremaining for src in sources)
378+ return DeviceTraceTransformer (
379+ blocks, work_offsets, nwork, coeffs, structs_dst, sources, partial_offsets, npartials
380+ )
343381end
344382
345383# Cache the device transformer directly, constructing the cached host version only on a miss.
@@ -425,7 +463,8 @@ function device_transformer(A, transformer::TraceTransformer, p, q)
425463 upload (x) = copy! (similar (proto, eltype (x), size (x)), x)
426464 DeviceTraceTransformer (
427465 upload (packed. blocks), upload (packed. work_offsets), packed. nwork,
428- upload (packed. coeffs), upload (packed. structs_dst), upload (packed. structs_src)
466+ upload (packed. coeffs), upload (packed. structs_dst), upload (packed. sources),
467+ upload (packed. partial_offsets), packed. npartials
429468 )
430469 end
431470end
@@ -530,34 +569,57 @@ end
530569end
531570
532571# COV_EXCL_START
533- # One thread per destination element, as for the generic transformers, where every source
534- # additionally contributes the sum over its traced entries.
535- @kernel function batched_trace_kernel! (
536- data_dst, data_src, blocks, work_offsets, coeffs, structs_dst, structs_src, α, β, nwork
537- )
572+ # First stage: one thread per (chunk, remaining entry) of every source subblock, writing its
573+ # partial trace to `partials[w + 1]`. Consecutive threads handle consecutive remaining entries.
574+ @kernel function partial_trace_kernel! (partials, data_src, sources, partial_offsets, npartials)
538575 # w = @index(Global, Linear) - 1 does not work due to JLArrays bug
539576 w = @index (Global, Linear)
540577 w -= 1
578+ if w < npartials
579+ j = _searchblock (partial_offsets, w)
580+ src = @inbounds sources[j]
581+ k, e = divrem (w - (@inbounds partial_offsets[j]), src. nremaining)
582+ coords = _coordinates (e, src. sz, src. dense_strides)
583+ i_src = _linear_index (coords, src. permuted_strides, src. offset)
584+
585+ acc = zero (eltype (partials))
586+ start = k * src. chunksize
587+ @inbounds for t in start: (min (start + src. chunksize, src. ntraced) - 1 )
588+ coords_traced = _coordinates (t, src. sz_traced, src. dense_strides_traced)
589+ acc += data_src[i_src + _linear_index (coords_traced, src. strides_traced, - 1 )]
590+ end
591+ @inbounds partials[w + 1 ] = acc
592+ end
593+ end
594+
595+ # Second stage: one thread per destination element, as for the generic transformers, where
596+ # every source contributes the sum of its partial traces.
597+ @kernel function trace_recouple_kernel! (
598+ data_dst, partials, blocks, work_offsets, coeffs, structs_dst, sources, partial_offsets,
599+ α, β, nwork
600+ )
601+ w = @index (Global, Linear)
602+ w -= 1
541603 if w < nwork
542604 b = _searchblock (work_offsets, w)
543605 blk = @inbounds blocks[b]
544606 local_w = w - (@inbounds work_offsets[b])
545607 blocksize = prod (blk. sz)
546- i = local_w ÷ blocksize # 0-based destination tree
547- coords = _coordinates (local_w % blocksize , blk. sz, blk. dense_strides)
608+ i, e = divrem ( local_w, blocksize) # 0-based destination tree and entry
609+ coords = _coordinates (e , blk. sz, blk. dense_strides)
548610
549611 st_dst, offs_dst = @inbounds structs_dst[blk. dst_offset + i + 1 ]
550612 i_dst = _linear_index (coords, st_dst, offs_dst)
551613
552- acc = zero (promote_type (eltype (data_src ), eltype (coeffs)))
614+ acc = zero (promote_type (eltype (partials ), eltype (coeffs)))
553615 @inbounds for j in 1 : blk. cols
554616 coeff = coeffs[blk. u_offset + 1 + i + (j - 1 ) * blk. rows]
555617 iszero (coeff) && continue
556- pst_src, sz_tr, dense_tr, st_tr, offs_src = structs_src[ blk. src_offset + j]
557- i_src = _linear_index (coords, pst_src, offs_src)
558- tr = zero (eltype (data_src ))
559- for t in 0 : (prod (sz_tr) - 1 )
560- tr += data_src[i_src + _linear_index ( _coordinates (t, sz_tr, dense_tr), st_tr, - 1 ) ]
618+ js = blk. src_offset + j
619+ offset = partial_offsets[js] + e + 1
620+ tr = zero (eltype (partials ))
621+ for k in 0 : (sources[js] . nchunks - 1 )
622+ tr += partials[offset + k * blocksize ]
561623 end
562624 acc += coeff * tr
563625 end
@@ -707,10 +769,21 @@ function TensorKit.trace_transform_kernel!(
707769 device:: DeviceTraceTransformer , α, β, backend, allocator, ntasks:: Int
708770 )
709771 device. nwork == 0 && return nothing
710- batched_trace_kernel! (get_backend (dst))(
711- dst, src, device. blocks, device. work_offsets, device. coeffs,
712- device. structs_dst, device. structs_src, α, β, device. nwork; ndrange = device. nwork
772+ kernel_backend = get_backend (dst)
773+ cp = TO. allocator_checkpoint! (allocator)
774+ partials = TO. tensoralloc (similarstoragetype (src), device. npartials, Val (true ), allocator)
775+ if device. npartials > 0
776+ partial_trace_kernel! (kernel_backend)(
777+ partials, src, device. sources, device. partial_offsets, device. npartials;
778+ ndrange = device. npartials
779+ )
780+ end
781+ trace_recouple_kernel! (kernel_backend)(
782+ dst, partials, device. blocks, device. work_offsets, device. coeffs, device. structs_dst,
783+ device. sources, device. partial_offsets, α, β, device. nwork; ndrange = device. nwork
713784 )
785+ TO. tensorfree! (partials, allocator)
786+ TO. allocator_reset! (allocator, cp)
714787 return nothing
715788end
716789
0 commit comments