@@ -9,6 +9,7 @@ using Strided: StridedViews
99using MatrixAlgebraKit, Adapt
1010using TensorKit
1111using TensorKit. TensorOperations: linearize, DefaultAllocator
12+ const TO = TensorKit. TensorOperations
1213using TensorKit. Factorizations
1314using TensorKit. Factorizations: AbstractAlgorithm
1415using TensorKit: SectorDict, tensormaptype, scalar, similarstoragetype, AdjointTensorMap, scalartype, project_symmetric_and_check
@@ -272,11 +273,17 @@ function DeviceGenericTreeTransformer(
272273 )
273274end
274275
276+ # Planar traces run in two stages. The first computes partial traces of every source subblock:
277+ # each thread sums a chunk of at most `chunksize` traced entries for a single remaining entry,
278+ # such that large traces (e.g. full reductions) are still spread over many threads. The second
279+ # recouples these partials with one thread per destination element, as for the generic transformers,
280+ # such that the traced entries of a source are summed only once, rather than once per destination tree.
281+
275282"""
276283 TraceTransformerBlock{N}
277284
278285Descriptor for a destination block of a `TraceTransformer`, indexing into the flat
279- `coeffs`/`structs_dst`/`structs_src ` vectors of a `DeviceTraceTransformer`.
286+ `coeffs`/`structs_dst`/`sources ` vectors of a `DeviceTraceTransformer`.
280287"""
281288struct TraceTransformerBlock{N}
282289 sz:: NTuple{N, Int}
@@ -288,35 +295,60 @@ struct TraceTransformerBlock{N}
288295 src_offset:: Int
289296end
290297
291- # (permuted strides of the remaining legs, sizes, dense strides and summed strides of the traced
292- # pairs, offset): the traced entries of a source subblock are found through a single stride per pair
293- const TraceSourceStructure{N, M} = Tuple{NTuple{N, Int}, NTuple{M, Int}, NTuple{M, Int}, NTuple{M, Int}, Int}
298+ """
299+ TraceSourceBlock{N, M}
294300
295- struct DeviceTraceTransformer{VB <: AbstractVector{<:TraceTransformerBlock} , VO <: AbstractVector{Int} , VC <: AbstractVector{<:Number} , VD <: AbstractVector {<: Tuple{<:Tuple{Vararg{Int}}, Int} }, VS <: AbstractVector{<:TraceSourceStructure} }
301+ Descriptor for the partial traces of a source subblock of a `TraceTransformer`, with `N` remaining
302+ legs (permuted to the destination order) and `M` traced pairs, whose entries are found through a
303+ single stride per pair. The partials are stored chunk-major, as `nchunks` dense arrays of shape `sz`.
304+ """
305+ struct TraceSourceBlock{N, M}
306+ sz:: NTuple{N, Int}
307+ dense_strides:: NTuple{N, Int}
308+ permuted_strides:: NTuple{N, Int}
309+ offset:: Int
310+ sz_traced:: NTuple{M, Int}
311+ dense_strides_traced:: NTuple{M, Int}
312+ strides_traced:: NTuple{M, Int} # strides[q₁] .+ strides[q₂]
313+ nremaining:: Int
314+ ntraced:: Int
315+ chunksize:: Int
316+ nchunks:: Int
317+ end
318+
319+ struct DeviceTraceTransformer{VB <: AbstractVector{<:TraceTransformerBlock} , VO <: AbstractVector{Int} , VC <: AbstractVector{<:Number} , VD <: AbstractVector {<: Tuple{<:Tuple{Vararg{Int}}, Int} }, VS <: AbstractVector{<:TraceSourceBlock} }
296320 blocks:: VB
297321 work_offsets:: VO
298322 nwork:: Int
299323 coeffs:: VC # every `U`, concatenated in column-major order
300324 structs_dst:: VD
301- structs_src:: VS
325+ sources:: VS
326+ partial_offsets:: VO # also the work offsets of the first stage
327+ npartials:: Int
302328end
303329
330+ # traces with fewer entries are not split, larger ones are split into at most `√ntraced` chunks,
331+ # such that no thread in either stage sums more than `max(256, √ntraced)` entries
332+ const MIN_TRACE_CHUNKSIZE = 256
333+ _trace_chunksize (ntraced:: Int ) = max (MIN_TRACE_CHUNKSIZE, isqrt (ntraced))
334+
304335function DeviceTraceTransformer (transformer:: TraceTransformer{T, N₁, N₂} , p, (q₁, q₂)) where {T, N₁, N₂}
305336 lp = linearize (p)
306337 M = length (q₁)
307338 blocks = TraceTransformerBlock{N₁}[]
308339 coeffs = T[]
309340 structs_dst = TreeStructure{N₁}[]
310- structs_src = TraceSourceStructure {N₁, M}[]
341+ sources = TraceSourceBlock {N₁, M}[]
311342
312343 (; structure_dst, structure_src) = transformer
313344 for (U, inds_dst, inds_src) in transformer. data
314345 # all destination trees in a block share the same subblock size
315346 size_dst = first (structure_dst[first (inds_dst)])
347+ dense_strides_dst = _dense_strides (size_dst)
316348 push! (
317349 blocks, TraceTransformerBlock {N₁} (
318- size_dst, _dense_strides (size_dst) , size (U, 1 ), size (U, 2 ),
319- length (coeffs), length (structs_dst), length (structs_src )
350+ size_dst, dense_strides_dst , size (U, 1 ), size (U, 2 ),
351+ length (coeffs), length (structs_dst), length (sources )
320352 )
321353 )
322354 append! (coeffs, U)
@@ -328,17 +360,23 @@ function DeviceTraceTransformer(transformer::TraceTransformer{T, N₁, N₂}, p,
328360 size_src, strides_src, offset_src = structure_src[isrc]
329361 size_traced = TupleTools. getindices (size_src, q₁)
330362 strides_traced = TupleTools. getindices (strides_src, q₁) .+ TupleTools. getindices (strides_src, q₂)
363+ ntraced = prod (size_traced)
364+ chunksize = _trace_chunksize (ntraced)
331365 push! (
332- structs_src, (
333- TupleTools. getindices (strides_src, lp), size_traced,
334- _dense_strides (size_traced), strides_traced, offset_src,
366+ sources, TraceSourceBlock {N₁, M} (
367+ size_dst, dense_strides_dst, TupleTools. getindices (strides_src, lp), offset_src,
368+ size_traced, _dense_strides (size_traced), strides_traced,
369+ prod (size_dst), ntraced, chunksize, cld (ntraced, chunksize)
335370 )
336371 )
337372 end
338373 end
339374
340375 work_offsets, nwork = _work_offsets (blk. rows * prod (blk. sz) for blk in blocks)
341- return DeviceTraceTransformer (blocks, work_offsets, nwork, coeffs, structs_dst, structs_src)
376+ partial_offsets, npartials = _work_offsets (src. nchunks * src. nremaining for src in sources)
377+ return DeviceTraceTransformer (
378+ blocks, work_offsets, nwork, coeffs, structs_dst, sources, partial_offsets, npartials
379+ )
342380end
343381
344382# Cache the device transformer directly, constructing the cached host version only on a miss.
@@ -418,7 +456,8 @@ function device_transformer(A, transformer::TraceTransformer, p, q)
418456 upload (x) = copy! (similar (proto, eltype (x), size (x)), x)
419457 DeviceTraceTransformer (
420458 upload (packed. blocks), upload (packed. work_offsets), packed. nwork,
421- upload (packed. coeffs), upload (packed. structs_dst), upload (packed. structs_src)
459+ upload (packed. coeffs), upload (packed. structs_dst), upload (packed. sources),
460+ upload (packed. partial_offsets), packed. npartials
422461 )
423462 end
424463end
@@ -523,34 +562,57 @@ end
523562end
524563
525564# COV_EXCL_START
526- # One thread per destination element, as for the generic transformers, where every source
527- # additionally contributes the sum over its traced entries.
528- @kernel function batched_trace_kernel! (
529- data_dst, data_src, blocks, work_offsets, coeffs, structs_dst, structs_src, α, β, nwork
530- )
565+ # First stage: one thread per (chunk, remaining entry) of every source subblock, writing its
566+ # partial trace to `partials[w + 1]`. Consecutive threads handle consecutive remaining entries.
567+ @kernel function partial_trace_kernel! (partials, data_src, sources, partial_offsets, npartials)
531568 # w = @index(Global, Linear) - 1 does not work due to JLArrays bug
532569 w = @index (Global, Linear)
533570 w -= 1
571+ if w < npartials
572+ j = _searchblock (partial_offsets, w)
573+ src = @inbounds sources[j]
574+ k, e = divrem (w - (@inbounds partial_offsets[j]), src. nremaining)
575+ coords = _coordinates (e, src. sz, src. dense_strides)
576+ i_src = _linear_index (coords, src. permuted_strides, src. offset)
577+
578+ acc = zero (eltype (partials))
579+ start = k * src. chunksize
580+ @inbounds for t in start: (min (start + src. chunksize, src. ntraced) - 1 )
581+ coords_traced = _coordinates (t, src. sz_traced, src. dense_strides_traced)
582+ acc += data_src[i_src + _linear_index (coords_traced, src. strides_traced, - 1 )]
583+ end
584+ @inbounds partials[w + 1 ] = acc
585+ end
586+ end
587+
588+ # Second stage: one thread per destination element, as for the generic transformers, where
589+ # every source contributes the sum of its partial traces.
590+ @kernel function trace_recouple_kernel! (
591+ data_dst, partials, blocks, work_offsets, coeffs, structs_dst, sources, partial_offsets,
592+ α, β, nwork
593+ )
594+ w = @index (Global, Linear)
595+ w -= 1
534596 if w < nwork
535597 b = _searchblock (work_offsets, w)
536598 blk = @inbounds blocks[b]
537599 local_w = w - (@inbounds work_offsets[b])
538600 blocksize = prod (blk. sz)
539- i = local_w ÷ blocksize # 0-based destination tree
540- coords = _coordinates (local_w % blocksize , blk. sz, blk. dense_strides)
601+ i, e = divrem ( local_w, blocksize) # 0-based destination tree and entry
602+ coords = _coordinates (e , blk. sz, blk. dense_strides)
541603
542604 st_dst, offs_dst = @inbounds structs_dst[blk. dst_offset + i + 1 ]
543605 i_dst = _linear_index (coords, st_dst, offs_dst)
544606
545- acc = zero (promote_type (eltype (data_src ), eltype (coeffs)))
607+ acc = zero (promote_type (eltype (partials ), eltype (coeffs)))
546608 @inbounds for j in 1 : blk. cols
547609 coeff = coeffs[blk. u_offset + 1 + i + (j - 1 ) * blk. rows]
548610 iszero (coeff) && continue
549- pst_src, sz_tr, dense_tr, st_tr, offs_src = structs_src[ blk. src_offset + j]
550- i_src = _linear_index (coords, pst_src, offs_src)
551- tr = zero (eltype (data_src ))
552- for t in 0 : (prod (sz_tr) - 1 )
553- tr += data_src[i_src + _linear_index ( _coordinates (t, sz_tr, dense_tr), st_tr, - 1 ) ]
611+ js = blk. src_offset + j
612+ offset = partial_offsets[js] + e + 1
613+ tr = zero (eltype (partials ))
614+ for k in 0 : (sources[js] . nchunks - 1 )
615+ tr += partials[offset + k * blocksize ]
554616 end
555617 acc += coeff * tr
556618 end
@@ -615,10 +677,21 @@ function TensorKit.trace_transform_kernel!(
615677 device:: DeviceTraceTransformer , α, β, backend, allocator, ntasks:: Int
616678 )
617679 device. nwork == 0 && return nothing
618- batched_trace_kernel! (get_backend (dst))(
619- dst, src, device. blocks, device. work_offsets, device. coeffs,
620- device. structs_dst, device. structs_src, α, β, device. nwork; ndrange = device. nwork
680+ kernel_backend = get_backend (dst)
681+ cp = TO. allocator_checkpoint! (allocator)
682+ partials = TO. tensoralloc (similarstoragetype (src), device. npartials, Val (true ), allocator)
683+ if device. npartials > 0
684+ partial_trace_kernel! (kernel_backend)(
685+ partials, src, device. sources, device. partial_offsets, device. npartials;
686+ ndrange = device. npartials
687+ )
688+ end
689+ trace_recouple_kernel! (kernel_backend)(
690+ dst, partials, device. blocks, device. work_offsets, device. coeffs, device. structs_dst,
691+ device. sources, device. partial_offsets, α, β, device. nwork; ndrange = device. nwork
621692 )
693+ TO. tensorfree! (partials, allocator)
694+ TO. allocator_reset! (allocator, cp)
622695 return nothing
623696end
624697
0 commit comments