@@ -13,8 +13,9 @@ using TensorKit.VectorInterface: One
1313using TensorKit. Factorizations
1414using TensorKit. Factorizations: AbstractAlgorithm
1515using TensorKit: SectorDict, tensormaptype, scalar, similarstoragetype, AdjointTensorMap, scalartype, project_symmetric_and_check
16- using TensorKit: UniqueTreeTransformer, GenericTreeTransformer, @cached , TensorMapSpace, Index2Tuple, IndexTuple
17- import TensorKit: randisometry, rand, randn, fill_braidingsubblock!, add_transform_kernel!
16+ using TensorKit: UniqueTreeTransformer, GenericTreeTransformer, TraceTransformer, @cached , TensorMapSpace, Index2Tuple, IndexTuple
17+ using TensorKit: SubblockIterator
18+ import TensorKit: randisometry, rand, randn, fill_braidingsubblock!, add_transform_kernel!, trace_transform_kernel!
1819
1920function TensorKit. fill_braidingsubblock! (data:: TD , val) where {T, TD <: Union{<:AnyGPUMatrix{T}, <:StridedViews.StridedView{T, 4, <:AnyGPUArray{T}}} }
2021 # COV_EXCL_START
@@ -272,6 +273,75 @@ function DeviceGenericTreeTransformer(
272273 )
273274end
274275
276+ """
277+ TraceTransformerBlock{N}
278+
279+ Descriptor for a destination block of a `TraceTransformer`, indexing into the flat
280+ `coeffs`/`structs_dst`/`structs_src` vectors of a `DeviceTraceTransformer`.
281+ """
282+ struct TraceTransformerBlock{N}
283+ sz:: NTuple{N, Int}
284+ dense_strides:: NTuple{N, Int}
285+ rows:: Int
286+ cols:: Int
287+ u_offset:: Int
288+ dst_offset:: Int
289+ src_offset:: Int
290+ end
291+
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}
295+
296+ struct DeviceTraceTransformer{VB <: AbstractVector{<:TraceTransformerBlock} , VO <: AbstractVector{Int} , VC <: AbstractVector{<:Number} , VD <: AbstractVector {<: Tuple{<:Tuple{Vararg{Int}}, Int} }, VS <: AbstractVector{<:TraceSourceStructure} }
297+ blocks:: VB
298+ work_offsets:: VO
299+ nwork:: Int
300+ coeffs:: VC # every `U`, concatenated in column-major order
301+ structs_dst:: VD
302+ structs_src:: VS
303+ end
304+
305+ function DeviceTraceTransformer (transformer:: TraceTransformer{T, N₁, N₂} , p, (q₁, q₂)) where {T, N₁, N₂}
306+ lp = linearize (p)
307+ M = length (q₁)
308+ blocks = TraceTransformerBlock{N₁}[]
309+ coeffs = T[]
310+ structs_dst = TreeStructure{N₁}[]
311+ structs_src = TraceSourceStructure{N₁, M}[]
312+
313+ (; structure_dst, structure_src) = transformer
314+ for (U, inds_dst, inds_src) in transformer. data
315+ # all destination trees in a block share the same subblock size
316+ size_dst = first (structure_dst[first (inds_dst)])
317+ push! (
318+ 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)
321+ )
322+ )
323+ append! (coeffs, U)
324+ for idst in inds_dst
325+ _, strides_dst, offset_dst = structure_dst[idst]
326+ push! (structs_dst, (strides_dst, offset_dst))
327+ end
328+ for isrc in inds_src
329+ size_src, strides_src, offset_src = structure_src[isrc]
330+ size_traced = TupleTools. getindices (size_src, q₁)
331+ strides_traced = TupleTools. getindices (strides_src, q₁) .+ TupleTools. getindices (strides_src, q₂)
332+ push! (
333+ structs_src, (
334+ TupleTools. getindices (strides_src, lp), size_traced,
335+ _dense_strides (size_traced), strides_traced, offset_src,
336+ )
337+ )
338+ end
339+ end
340+
341+ 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)
343+ end
344+
275345# Cache the device transformer directly, constructing the cached host version only on a miss.
276346@cached function TensorKit. treebraider (
277347 A:: Type{TA} , Vdst:: TensorMapSpace , Vsrc:: TensorMapSpace , p:: Index2Tuple ,
288358 return device_transformer (A, host, linearize (p))
289359end
290360
361+ @cached function TensorKit. treetracer (
362+ A:: Type{TA} , Vdst:: TensorMapSpace , Vsrc:: TensorMapSpace , p:: Index2Tuple , q:: Index2Tuple
363+ ) where {TA <: AnyGPUVector }
364+ host = TensorKit. treetracer (Vector{scalartype (A)}, Vdst, Vsrc, p, q)
365+ return device_transformer (A, host, p, q)
366+ end
367+
291368const DEFAULT_DEVICECACHE_SIZE = 1000
292369
293370function __init__ ()
@@ -298,6 +375,7 @@ function __init__()
298375 Symbol (" TensorKitGPUArraysExt.GLOBAL_TREETRANSPOSER_CACHE" ) => GLOBAL_TREETRANSPOSER_CACHE,
299376 Symbol (" TensorKitGPUArraysExt.GLOBAL_DIAGONAL_TREEBRAIDER_CACHE" ) => GLOBAL_DIAGONAL_TREEBRAIDER_CACHE,
300377 Symbol (" TensorKitGPUArraysExt.GLOBAL_DIAGONAL_TREETRANSPOSER_CACHE" ) => GLOBAL_DIAGONAL_TREETRANSPOSER_CACHE,
378+ Symbol (" TensorKitGPUArraysExt.GLOBAL_TREETRACER_CACHE" ) => GLOBAL_TREETRACER_CACHE,
301379 )
302380 )
303381
@@ -306,6 +384,7 @@ function __init__()
306384 resize! (GLOBAL_TREETRANSPOSER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
307385 resize! (GLOBAL_DIAGONAL_TREEBRAIDER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
308386 resize! (GLOBAL_DIAGONAL_TREETRANSPOSER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
387+ resize! (GLOBAL_TREETRACER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
309388
310389 return nothing
311390end
@@ -339,6 +418,18 @@ function device_transformer(A, transformer::GenericTreeTransformer, p)
339418 end
340419end
341420
421+ function device_transformer (A, transformer:: TraceTransformer , p, q)
422+ packed = DeviceTraceTransformer (transformer, p, q)
423+ return GPUArrays. @uncached begin
424+ proto = A (undef, 0 )
425+ upload (x) = copy! (similar (proto, eltype (x), size (x)), x)
426+ DeviceTraceTransformer (
427+ upload (packed. blocks), upload (packed. work_offsets), packed. nwork,
428+ upload (packed. coeffs), upload (packed. structs_dst), upload (packed. structs_src)
429+ )
430+ end
431+ end
432+
342433# COV_EXCL_START
343434# kernels are not reachable by coverage
344435
367458# finds the overall linear index in the output and input arrays corresponding to the **sublock**
368459# coordinates currently being worked on
369460@inline function _linear_index (coords:: NTuple{N, Int} , strides:: NTuple{N, Int} , offset) where {N}
370- return offset + sum (ntuple (n -> coords[n] * strides[n], Val (N))) + 1
461+ # an explicit loop, since `sum` of an empty tuple (e.g. a full trace) does not compile for GPUs
462+ i = offset + 1
463+ for n in 1 : N
464+ i += coords[n] * strides[n]
465+ end
466+ return i
371467end
372468
373469# One thread per destination element in `data_dst`. `op` is `identity` or `conj`, and is
433529 end
434530end
435531
532+ # 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+ )
538+ # w = @index(Global, Linear) - 1 does not work due to JLArrays bug
539+ w = @index (Global, Linear)
540+ w -= 1
541+ if w < nwork
542+ b = _searchblock (work_offsets, w)
543+ blk = @inbounds blocks[b]
544+ local_w = w - (@inbounds work_offsets[b])
545+ blocksize = prod (blk. sz)
546+ i = local_w ÷ blocksize # 0-based destination tree
547+ coords = _coordinates (local_w % blocksize, blk. sz, blk. dense_strides)
548+
549+ st_dst, offs_dst = @inbounds structs_dst[blk. dst_offset + i + 1 ]
550+ i_dst = _linear_index (coords, st_dst, offs_dst)
551+
552+ acc = zero (promote_type (eltype (data_src), eltype (coeffs)))
553+ @inbounds for j in 1 : blk. cols
554+ coeff = coeffs[blk. u_offset + 1 + i + (j - 1 ) * blk. rows]
555+ 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 )]
561+ end
562+ acc += coeff * tr
563+ end
564+ # destinations without contributions are overwritten for `β == 0`
565+ @inbounds data_dst[i_dst] = iszero (β) ? α * acc : α * acc + β * data_dst[i_dst]
566+ end
567+ end
568+ # COV_EXCL_STOP
569+
436570function _launch_unique! (data_dst, data_src, op, transformer, α, β, :: Val{N} ) where {N}
437571 nwork = transformer. nwork
438572 nwork == 0 && return nothing
457591# we don't want/need the `StridedSubblocks` here because that information is already in the transformer
458592TensorKit. _transform_subblocks (
459593 tdst:: TensorMap , tsrc:: TensorMap ,
460- transformer:: Union{DeviceUniqueTreeTransformer, DeviceGenericTreeTransformer}
594+ transformer:: Union{DeviceUniqueTreeTransformer, DeviceGenericTreeTransformer, DeviceTraceTransformer }
461595) = (tdst. data, tsrc. data)
462596
463597# Diagonal sources
@@ -568,4 +702,29 @@ function TensorKit.add_transform_kernel!(
568702 return nothing
569703end
570704
705+ function TensorKit. trace_transform_kernel! (
706+ dst:: AnyGPUVector , src:: AnyGPUVector , p:: Index2Tuple , q:: Index2Tuple ,
707+ device:: DeviceTraceTransformer , α, β, backend, allocator, ntasks:: Int
708+ )
709+ 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
713+ )
714+ return nothing
715+ end
716+
717+ # other tensor types are first converted to `TensorMap`s: tracing subblock by subblock with
718+ # `tensortrace!` is not an option, since cuTENSOR requires aligned data for the subblock views
719+ function TensorKit. trace_transform_kernel! (
720+ dst:: SubblockIterator , src:: SubblockIterator , p:: Index2Tuple , q:: Index2Tuple ,
721+ device:: DeviceTraceTransformer , α, β, backend, allocator, ntasks:: Int
722+ )
723+ _tensormap (t) = t isa TensorMap ? t : copy! (similar (t, scalartype (t), space (t)), t)
724+ tdst, tsrc = _tensormap (dst. t), _tensormap (src. t)
725+ trace_transform_kernel! (tdst. data, tsrc. data, p, q, device, α, β, backend, allocator, ntasks)
726+ tdst === dst. t || copy! (dst. t, tdst)
727+ return nothing
728+ end
729+
571730end
0 commit comments