Skip to content

Commit 96dfa3c

Browse files
lkdvosclaude
andcommitted
Add a GPU kernel for planar traces
GPU tensors pack the `TraceTransformer` into `isbits` descriptors, cached per device storagetype, and trace with one thread per destination element, fusing the sum over the traced entries and the recoupling into a single kernel, analogous to the generic tree transformers. Other tensor types, such as adjoints, are first converted to `TensorMap`s: tracing subblock views with cuTENSOR fails for data offsets that are not aligned (e.g. `Float64` data at odd offsets). `_linear_index` is now written as an explicit loop, since `sum` of an empty tuple, as occurs for a full trace, does not compile for GPUs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a1df9bb commit 96dfa3c

3 files changed

Lines changed: 182 additions & 5 deletions

File tree

‎docs/src/Changelog.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec
2424

2525
### Changed
2626

27-
- `planartrace!` precomputes and caches a `TraceTransformer` with the subblock positions and recoupling coefficients, and executes it with a kernel shared by all sectortypes, analogous to the index manipulations; `planar_trace` is now also defined for `FusionTreeBlock`s (internal)
27+
- `planartrace!` precomputes and caches a `TraceTransformer` with the subblock positions and recoupling coefficients, and executes it with a kernel shared by all sectortypes, analogous to the index manipulations; `planar_trace` is now also defined for `FusionTreeBlock`s, and GPU tensors use a dedicated kernel (internal)
2828

2929
### Deprecated
3030

‎ext/TensorKitGPUArraysExt.jl‎

Lines changed: 163 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,9 @@ using TensorKit.VectorInterface: One
1313
using TensorKit.Factorizations
1414
using TensorKit.Factorizations: AbstractAlgorithm
1515
using 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

1920
function 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
)
273274
end
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,
@@ -288,6 +358,13 @@ end
288358
return device_transformer(A, host, linearize(p))
289359
end
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+
291368
const DEFAULT_DEVICECACHE_SIZE = 1000
292369

293370
function __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
311390
end
@@ -339,6 +418,18 @@ function device_transformer(A, transformer::GenericTreeTransformer, p)
339418
end
340419
end
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

@@ -367,7 +458,12 @@ end
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
371467
end
372468

373469
# One thread per destination element in `data_dst`. `op` is `identity` or `conj`, and is
@@ -433,6 +529,44 @@ end
433529
end
434530
end
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+
436570
function _launch_unique!(data_dst, data_src, op, transformer, α, β, ::Val{N}) where {N}
437571
nwork = transformer.nwork
438572
nwork == 0 && return nothing
@@ -457,7 +591,7 @@ end
457591
# we don't want/need the `StridedSubblocks` here because that information is already in the transformer
458592
TensorKit._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
569703
end
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+
571730
end

‎test/cuda/planar.jl‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,24 @@ for V in spacelist
7474
end
7575
end
7676

77+
for V in spacelist
78+
I = sectortype(first(V))
79+
Istr = type_repr(I)
80+
@timedtestset "planartrace + CUDA with symmetry: $Istr" begin
81+
# (space, p, q) for a trace of neighbouring legs and a nested trace
82+
cases = (
83+
(V[1] ⊗ V[2] ⊗ V[3] ← V[4] ⊗ V[3], ((1, 2), (4,)), ((3,), (5,))),
84+
(V[1] ⊗ V[2] ⊗ V[3] ⊗ V[4] ← V[3] ⊗ V[4], ((1,), (2,)), ((3, 4), (5, 6))),
85+
)
86+
for (W, p, q) in cases, (α, β) in ((0.7, 0.3), (1.0, 0.0))
87+
A = randn(ComplexF64, W)
88+
C = randn(ComplexF64, TensorKit.select(W, p))
89+
Cgpu = planartrace!(adapt(CuArray, C), adapt(CuArray, A), p, q, α, β)
90+
@test adapt(Vector{ComplexF64}, Cgpu) ≈ planartrace!(C, A, p, q, α, β)
91+
end
92+
end
93+
end
94+
7795
@testset "planar methods" verbose = true begin
7896
@testset "planaradd" begin
7997
A = CUDA.randn(ℂ^2 ⊗ ℂ^3 ← ℂ^6 ⊗ ℂ^5 ⊗ ℂ^4)

0 commit comments

Comments
 (0)