Skip to content

Commit dc3cd36

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 8d5d02f commit dc3cd36

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
@@ -30,7 +30,7 @@ When releasing a new version, move the "Unreleased" changes to a new version sec
3030
- Require TensorKitSectors v0.3.10
3131
- `@cached` can be used from other modules, such as package extensions, which then own the cache of the methods they add; these caches are shown with their module in `global_cache_info` after registration in `__init__` (internal)
3232
- The `TreeTransformer`s used in index manipulations are now constructed and cached per storagetype of the destination tensor, which is also a dispatch point for storage-specific transformers with their own cache (internal)
33-
- `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)
33+
- `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)
3434

3535
### Deprecated
3636

‎ext/TensorKitGPUArraysExt.jl‎

Lines changed: 163 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@ using TensorKit.TensorOperations: linearize, DefaultAllocator
1212
using TensorKit.Factorizations
1313
using TensorKit.Factorizations: AbstractAlgorithm
1414
using TensorKit: SectorDict, tensormaptype, scalar, similarstoragetype, AdjointTensorMap, scalartype, project_symmetric_and_check
15-
using TensorKit: UniqueTreeTransformer, GenericTreeTransformer, @cached, TensorMapSpace, Index2Tuple, IndexTuple
16-
import TensorKit: randisometry, rand, randn, fill_braidingsubblock!, add_transform_kernel!
15+
using TensorKit: UniqueTreeTransformer, GenericTreeTransformer, TraceTransformer, @cached, TensorMapSpace, Index2Tuple, IndexTuple
16+
using TensorKit: SubblockIterator
17+
import TensorKit: randisometry, rand, randn, fill_braidingsubblock!, add_transform_kernel!, trace_transform_kernel!
1718

1819
function TensorKit.fill_braidingsubblock!(data::TD, val) where {T, TD <: Union{<:AnyGPUMatrix{T}, <:StridedViews.StridedView{T, 4, <:AnyGPUArray{T}}}}
1920
# COV_EXCL_START
@@ -271,6 +272,75 @@ function DeviceGenericTreeTransformer(
271272
)
272273
end
273274

275+
"""
276+
TraceTransformerBlock{N}
277+
278+
Descriptor for a destination block of a `TraceTransformer`, indexing into the flat
279+
`coeffs`/`structs_dst`/`structs_src` vectors of a `DeviceTraceTransformer`.
280+
"""
281+
struct TraceTransformerBlock{N}
282+
sz::NTuple{N, Int}
283+
dense_strides::NTuple{N, Int}
284+
rows::Int
285+
cols::Int
286+
u_offset::Int
287+
dst_offset::Int
288+
src_offset::Int
289+
end
290+
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}
294+
295+
struct DeviceTraceTransformer{VB <: AbstractVector{<:TraceTransformerBlock}, VO <: AbstractVector{Int}, VC <: AbstractVector{<:Number}, VD <: AbstractVector{<:Tuple{<:Tuple{Vararg{Int}}, Int}}, VS <: AbstractVector{<:TraceSourceStructure}}
296+
blocks::VB
297+
work_offsets::VO
298+
nwork::Int
299+
coeffs::VC # every `U`, concatenated in column-major order
300+
structs_dst::VD
301+
structs_src::VS
302+
end
303+
304+
function DeviceTraceTransformer(transformer::TraceTransformer{T, N₁, N₂}, p, (q₁, q₂)) where {T, N₁, N₂}
305+
lp = linearize(p)
306+
M = length(q₁)
307+
blocks = TraceTransformerBlock{N₁}[]
308+
coeffs = T[]
309+
structs_dst = TreeStructure{N₁}[]
310+
structs_src = TraceSourceStructure{N₁, M}[]
311+
312+
(; structure_dst, structure_src) = transformer
313+
for (U, inds_dst, inds_src) in transformer.data
314+
# all destination trees in a block share the same subblock size
315+
size_dst = first(structure_dst[first(inds_dst)])
316+
push!(
317+
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)
320+
)
321+
)
322+
append!(coeffs, U)
323+
for idst in inds_dst
324+
_, strides_dst, offset_dst = structure_dst[idst]
325+
push!(structs_dst, (strides_dst, offset_dst))
326+
end
327+
for isrc in inds_src
328+
size_src, strides_src, offset_src = structure_src[isrc]
329+
size_traced = TupleTools.getindices(size_src, q₁)
330+
strides_traced = TupleTools.getindices(strides_src, q₁) .+ TupleTools.getindices(strides_src, q₂)
331+
push!(
332+
structs_src, (
333+
TupleTools.getindices(strides_src, lp), size_traced,
334+
_dense_strides(size_traced), strides_traced, offset_src,
335+
)
336+
)
337+
end
338+
end
339+
340+
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)
342+
end
343+
274344
# Cache the device transformer directly, constructing the cached host version only on a miss.
275345
@cached function TensorKit.treebraider(
276346
A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple,
@@ -287,6 +357,13 @@ end
287357
return device_transformer(A, host, linearize(p))
288358
end
289359

360+
@cached function TensorKit.treetracer(
361+
A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, q::Index2Tuple
362+
) where {TA <: AnyGPUVector}
363+
host = TensorKit.treetracer(Vector{scalartype(A)}, Vdst, Vsrc, p, q)
364+
return device_transformer(A, host, p, q)
365+
end
366+
290367
const DEFAULT_DEVICECACHE_SIZE = 1000
291368

292369
function __init__()
@@ -295,12 +372,14 @@ function __init__()
295372
TensorKit.GLOBAL_CACHES, (
296373
Symbol("TensorKitGPUArraysExt.GLOBAL_TREEBRAIDER_CACHE") => GLOBAL_TREEBRAIDER_CACHE,
297374
Symbol("TensorKitGPUArraysExt.GLOBAL_TREETRANSPOSER_CACHE") => GLOBAL_TREETRANSPOSER_CACHE,
375+
Symbol("TensorKitGPUArraysExt.GLOBAL_TREETRACER_CACHE") => GLOBAL_TREETRACER_CACHE,
298376
)
299377
)
300378

301379
# device-caches should probably have smaller sizes:
302380
resize!(GLOBAL_TREEBRAIDER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
303381
resize!(GLOBAL_TREETRANSPOSER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
382+
resize!(GLOBAL_TREETRACER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
304383

305384
return nothing
306385
end
@@ -332,6 +411,18 @@ function device_transformer(A, transformer::GenericTreeTransformer, p)
332411
end
333412
end
334413

414+
function device_transformer(A, transformer::TraceTransformer, p, q)
415+
packed = DeviceTraceTransformer(transformer, p, q)
416+
return GPUArrays.@uncached begin
417+
proto = A(undef, 0)
418+
upload(x) = copy!(similar(proto, eltype(x), size(x)), x)
419+
DeviceTraceTransformer(
420+
upload(packed.blocks), upload(packed.work_offsets), packed.nwork,
421+
upload(packed.coeffs), upload(packed.structs_dst), upload(packed.structs_src)
422+
)
423+
end
424+
end
425+
335426
# COV_EXCL_START
336427
# kernels are not reachable by coverage
337428

@@ -360,7 +451,12 @@ end
360451
# finds the overall linear index in the output and input arrays corresponding to the **sublock**
361452
# coordinates currently being worked on
362453
@inline function _linear_index(coords::NTuple{N, Int}, strides::NTuple{N, Int}, offset) where {N}
363-
return offset + sum(ntuple(n -> coords[n] * strides[n], Val(N))) + 1
454+
# an explicit loop, since `sum` of an empty tuple (e.g. a full trace) does not compile for GPUs
455+
i = offset + 1
456+
for n in 1:N
457+
i += coords[n] * strides[n]
458+
end
459+
return i
364460
end
365461

366462
# One thread per destination element in `data_dst`. `op` is `identity` or `conj`, and is
@@ -426,6 +522,44 @@ end
426522
end
427523
end
428524

525+
# 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+
)
531+
# w = @index(Global, Linear) - 1 does not work due to JLArrays bug
532+
w = @index(Global, Linear)
533+
w -= 1
534+
if w < nwork
535+
b = _searchblock(work_offsets, w)
536+
blk = @inbounds blocks[b]
537+
local_w = w - (@inbounds work_offsets[b])
538+
blocksize = prod(blk.sz)
539+
i = local_w ÷ blocksize # 0-based destination tree
540+
coords = _coordinates(local_w % blocksize, blk.sz, blk.dense_strides)
541+
542+
st_dst, offs_dst = @inbounds structs_dst[blk.dst_offset + i + 1]
543+
i_dst = _linear_index(coords, st_dst, offs_dst)
544+
545+
acc = zero(promote_type(eltype(data_src), eltype(coeffs)))
546+
@inbounds for j in 1:blk.cols
547+
coeff = coeffs[blk.u_offset + 1 + i + (j - 1) * blk.rows]
548+
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)]
554+
end
555+
acc += coeff * tr
556+
end
557+
# destinations without contributions are overwritten for `β == 0`
558+
@inbounds data_dst[i_dst] = iszero(β) ? α * acc : α * acc + β * data_dst[i_dst]
559+
end
560+
end
561+
# COV_EXCL_STOP
562+
429563
function _launch_unique!(data_dst, data_src, op, transformer, α, β, ::Val{N}) where {N}
430564
nwork = transformer.nwork
431565
nwork == 0 && return nothing
@@ -450,7 +584,7 @@ end
450584
# we don't want/need the `StridedSubblocks` here because that information is already in the transformer
451585
TensorKit._transform_subblocks(
452586
tdst::TensorMap, tsrc::TensorMap,
453-
transformer::Union{DeviceUniqueTreeTransformer, DeviceGenericTreeTransformer}
587+
transformer::Union{DeviceUniqueTreeTransformer, DeviceGenericTreeTransformer, DeviceTraceTransformer}
454588
) = (tdst.data, tsrc.data)
455589

456590
function TensorKit.add_transform_kernel!(
@@ -476,4 +610,29 @@ function TensorKit.add_transform_kernel!(
476610
return nothing
477611
end
478612

613+
function TensorKit.trace_transform_kernel!(
614+
dst::AnyGPUVector, src::AnyGPUVector, p::Index2Tuple, q::Index2Tuple,
615+
device::DeviceTraceTransformer, α, β, backend, allocator, ntasks::Int
616+
)
617+
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
621+
)
622+
return nothing
623+
end
624+
625+
# other tensor types are first converted to `TensorMap`s: tracing subblock by subblock with
626+
# `tensortrace!` is not an option, since cuTENSOR requires aligned data for the subblock views
627+
function TensorKit.trace_transform_kernel!(
628+
dst::SubblockIterator, src::SubblockIterator, p::Index2Tuple, q::Index2Tuple,
629+
device::DeviceTraceTransformer, α, β, backend, allocator, ntasks::Int
630+
)
631+
_tensormap(t) = t isa TensorMap ? t : copy!(similar(t, scalartype(t), space(t)), t)
632+
tdst, tsrc = _tensormap(dst.t), _tensormap(src.t)
633+
trace_transform_kernel!(tdst.data, tsrc.data, p, q, device, α, β, backend, allocator, ntasks)
634+
tdst === dst.t || copy!(dst.t, tdst)
635+
return nothing
636+
end
637+
479638
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)