Skip to content

Commit 4f00cba

Browse files
kshyattKatharine Hyatt
authored andcommitted
Implement different kernel approach for GPU-side braiding
1 parent 440722d commit 4f00cba

1 file changed

Lines changed: 149 additions & 5 deletions

File tree

‎ext/TensorKitGPUArraysExt.jl‎

Lines changed: 149 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ using TensorKit.TensorOperations: linearize, DefaultAllocator
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: StridedSubblocks, UniqueTreeTransformer
16+
using TensorKit: StridedSubblocks, UniqueTreeTransformer, GenericTreeTransformer
1717
import TensorKit: randisometry, rand, randn, fill_braidingsubblock!, add_transform_kernel!
1818

1919
function TensorKit.fill_braidingsubblock!(data::TD, val) where {T, TD <: Union{<:AnyGPUMatrix{T}, <:StridedViews.StridedView{T, 4, <:AnyGPUArray{T}}}}
@@ -136,7 +136,6 @@ end
136136
# so that the GPU thread can recover the Cartesian coordinates it will need for input/ouput,
137137
# and a running `work_offsets` count of destination elements, so that a kernel can run one
138138
# thread per output element and recover which input that element belongs with.
139-
140139
# Some possible TODO here:
141140
# - Try cuTILE as this is a classic tile programming problem
142141
# - Use shared memory to coalesce the reads
@@ -148,7 +147,8 @@ const TreeStructure{N} = Tuple{NTuple{N, Int}, Int}
148147
UniqueTransformerBlock{T, N}
149148
150149
`isbits` descriptor for a subblock that is a *single* scaled permutation:
151-
an entry of a `UniqueTreeTransformer`.
150+
an entry of a `UniqueTreeTransformer` or a degenerate (one-tree) block of a
151+
`GenericTreeTransformer`.
152152
"""
153153
struct UniqueTransformerBlock{T, N}
154154
coeff::T
@@ -167,6 +167,35 @@ struct DeviceUniqueTreeTransformer{VB <: AbstractVector{<:UniqueTransformerBlock
167167
nwork::Int
168168
end
169169

170+
"""
171+
GenericTransformerBlock{N}
172+
173+
Descriptor for a recoupling block of a `GenericTreeTransformer`, indexing into the
174+
flat `coeffs`/`structs_dst`/`structs_src` vectors of a `DeviceGenericTreeTransformer`.
175+
** All offsets are 0-based since it makes the arithmetic easier. **
176+
"""
177+
struct GenericTransformerBlock{N}
178+
sz::NTuple{N, Int}
179+
densestrides::NTuple{N, Int}
180+
rows::Int
181+
cols::Int
182+
u_offset::Int # location in the flattened U vector to find this block's U
183+
dst_offset::Int
184+
src_offset::Int
185+
end
186+
187+
# force all the type signatures here to make sure doing something wrong fails
188+
# before the kernel launch. Kernel error dumps are awful and hard to interpret.
189+
struct DeviceGenericTreeTransformer{VO <: AbstractVector{Int}, DA <: DeviceAbelianTreeTransformer{<:Any, VO}, VB <: AbstractVector{<:GenericTransformerBlock}, VC <: AbstractVector{<:Number}, VS <: AbstractVector{<:Tuple{<:Tuple{Vararg{Int}}, Int}}}
190+
degenerate::DA # length(U) = 1 blocks, can be handled by Abelian kernel
191+
blocks::VB
192+
work_offsets::VO
193+
nwork::Int
194+
coeffs::VC # every `U`, concatenated in column-major order
195+
structs_dst::VS
196+
structs_src::VS
197+
end
198+
170199
# strides of a dense array of shape `sz`
171200
_dense_strides(size::Dims) = (1, Base.front(cumprod(size))...)
172201

@@ -178,7 +207,7 @@ function _unique_block(
178207
return UniqueTransformerBlock{T, length(size_dst)}(
179208
coeff, size_dst, _dense_strides(size_dst), strides_dst, offsets_dst,
180209
TupleTools.getindices(strides_src, p), offsets_src
181-
)
210+
)
182211
end
183212

184213
function _work_offsets(work)
@@ -198,11 +227,51 @@ function DeviceUniqueTreeTransformer(transformer::UniqueTreeTransformer{T, N}, p
198227
return DeviceUniqueTreeTransformer(blocks, work_offsets, nwork)
199228
end
200229

230+
function DeviceGenericTreeTransformer(
231+
transformer::GenericTreeTransformer{T, N}, p
232+
) where {T, N}
233+
degenerate = UniqueTransformerBlock{T, N}[]
234+
blocks = GenericTransformerBlock{N}[]
235+
coeffs = T[]
236+
structs_dst = TreeStructure{N}[]
237+
structs_src = TreeStructure{N}[]
238+
239+
for (U, (size_dst, strides_dst), (size_src, strides_src)) in transformer.data
240+
if length(U) == 1 # same as the unique (Abelian) case
241+
push!(
242+
degenerate, _abelian_block(
243+
only(U), (size_dst, only(strides_dst)...), (size_src, only(strides_src)...), p
244+
)
245+
)
246+
else
247+
push!(
248+
blocks, GenericTransformerBlock{N}(
249+
size_dst, _dense_strides(size_dst), size(U, 1), size(U, 2),
250+
length(coeffs), length(structs_dst), length(structs_src)
251+
)
252+
)
253+
append!(coeffs, U)
254+
append!(structs_dst, strides_dst)
255+
for (stride_src, offset_src) in strides_src
256+
push!(structs_src, (_permutestrides(stride_src, p), offset_src))
257+
end
258+
end
259+
end
260+
261+
degenerate_offsets, degenerate_nwork = _work_offsets(prod(blk.sz) for blk in degenerate)
262+
work_offsets, nwork = _work_offsets(blk.rows * prod(blk.sz) for blk in blocks)
263+
return DeviceGenericTreeTransformer(
264+
DeviceUniqueTreeTransformer(degenerate, degenerate_offsets, degenerate_nwork),
265+
blocks, work_offsets, nwork, coeffs, structs_dst, structs_src
266+
)
267+
end
268+
201269
"""
202270
StorageAdaptor(proto)
203271
204272
`Adapt` adaptor moving arrays onto the same device and array type as `proto`, preserving
205-
their element type. For `proto::CuVector{Float64}` and `array::Vector{Int}`, the call `adapt(typeof(proto), array)` would force-convert the element type `Int`
273+
their element type. For `proto::CuVector{Float64}` and `array::Vector{Int}`,
274+
the call `adapt(typeof(proto), array)` would force-convert the element type `Int`
206275
to `Float64`, while `adapt(StoreAdaptor(proto), array)` does not.
207276
"""
208277
struct StorageAdaptor{A <: AbstractArray}
@@ -220,6 +289,14 @@ function Adapt.adapt_structure(to, t::DeviceUniqueTreeTransformer)
220289
)
221290
end
222291

292+
function Adapt.adapt_structure(to, t::DeviceGenericTreeTransformer)
293+
return DeviceGenericTreeTransformer(
294+
Adapt.adapt(to, t.degenerate), Adapt.adapt(to, t.blocks),
295+
Adapt.adapt(to, t.work_offsets), t.nwork, Adapt.adapt(to, t.coeffs),
296+
Adapt.adapt(to, t.structs_dst), Adapt.adapt(to, t.structs_src)
297+
)
298+
end
299+
223300
# Copying a transformer to GPU is more expensive than running it, so we cache the device
224301
# copy in a global LRU cache, registered in `TensorKit.GLOBAL_CACHES` so that
225302
# `empty_globalcaches!` also frees the device memory. The key is:
@@ -252,6 +329,7 @@ function device_transformer(proto::AbstractArray, transformer, p)
252329
end
253330

254331
_device_transformer(t::UniqueTreeTransformer, p) = DeviceUniqueTreeTransformer(t, p)
332+
_device_transformer(t::GenericTreeTransformer, p) = DeviceGenericTreeTransformer(t, p)
255333

256334
# COV_EXCL_START
257335
# kernels are not reachable by coverage
@@ -302,6 +380,47 @@ end
302380

303381
# COV_EXCL_STOP
304382

383+
# One thread per destination element in `data_dst`. This makes much better use of the
384+
# GPU "massive parallelism" as compared to the one-thread-per-subtransformer approach.
385+
# It also more evenly divides the work among threads so the work profile is less
386+
# jagged. Unlike the CPU implementation, there is no extract → recouple → insert process:
387+
# BLAS is not generally reachable from inside a kernel, and fusing the recoupling into
388+
# the strided gather lets us remove the buffer entirely.
389+
# TODO: what about symmetries like SU(3), where the column by column approach is not
390+
# optimal?
391+
@kernel function generic_batched_permute_kernel!(
392+
data_dst, data_src, op, blocks, work_offsets, coeffs, structs_dst, structs_src,
393+
α, β, nwork, ::Val{N}
394+
) where {N}
395+
w = @index(Global, Linear) - 1
396+
if w < nwork
397+
# bookkeeping to figure out where to read from and write to
398+
b = _searchblock(work_offsets, w)
399+
blk = @inbounds blocks[b]
400+
local_w = w - (@inbounds work_offsets[b])
401+
blocksize = prod(blk.sz)
402+
i = local_w ÷ blocksize # 0-based destination tree
403+
coords = _coordinates(local_w % blocksize, blk.sz, blk.densestrides)
404+
405+
st_dst, offs_dst = @inbounds structs_dst[blk.dst_offset + i + 1]
406+
i_dst = _offset(coords, st_dst, offs_dst)
407+
408+
# dst_i = β * dst_i + α * Σ_j U[i, j] * permute(src_j, p): each output tree is a
409+
# linear combination of the input trees weighted by the recoupling coefficients.
410+
# The permutation of src_j was already done by permuting its strides before the
411+
# kernel launched.
412+
acc = zero(promote_type(eltype(data_src), eltype(coeffs)))
413+
for j in 1:blk.cols
414+
# TODO is there a more efficient way to do this read?
415+
coeff = @inbounds coeffs[blk.u_offset + (j - 1) * blk.rows + i + 1]
416+
iszero(coeff) && continue
417+
pst_src, offs_src = @inbounds structs_src[blk.src_offset + j]
418+
acc += coeff * @inbounds op(data_src[_offset(coords, pst_src, offs_src)])
419+
end
420+
@inbounds data_dst[i_dst] = α * acc + β * data_dst[i_dst]
421+
end
422+
end
423+
305424
function _launch_unique!(data_dst, data_src, op, transformer, α, β, ::Val{N}) where {N}
306425
nwork = transformer.nwork
307426
nwork == 0 && return nothing
@@ -312,6 +431,17 @@ function _launch_unique!(data_dst, data_src, op, transformer, α, β, ::Val{N})
312431
return nothing
313432
end
314433

434+
function _launch_generic!(data_dst, data_src, op, transformer, α, β, ::Val{N}) where {N}
435+
nwork = transformer.nwork
436+
nwork == 0 && return nothing
437+
generic_batched_permute_kernel!(get_backend(data_dst))(
438+
data_dst, data_src, op, transformer.blocks, transformer.work_offsets,
439+
transformer.coeffs, transformer.structs_dst, transformer.structs_src, α, β, nwork,
440+
Val(N); ndrange = nwork
441+
)
442+
return nothing
443+
end
444+
315445
const GPUStridedSubblocks = StridedSubblocks{<:AnyGPUArray}
316446

317447
function TensorKit.add_transform_kernel!(
@@ -325,4 +455,18 @@ function TensorKit.add_transform_kernel!(
325455
return nothing
326456
end
327457

458+
function TensorKit.add_transform_kernel!(
459+
data_dst::GPUStridedSubblocks, data_src::GPUStridedSubblocks, p, conjsrc::Bool,
460+
transformer::GenericTreeTransformer{T, N}, α, β, backend, allocator, ntasks::Int
461+
) where {T, N}
462+
# GPU-side object to hold the treetransformer information
463+
device = device_transformer(dst.data, transformer, linearize(p))
464+
op = conjsrc ? conj : identity
465+
# one-tree blocks are a scaled permutation, which the Abelian kernel already handles; the
466+
# two kernels touch disjoint subblocks so the launch order does not matter
467+
_launch_unique!(dst.data, src.data, op, device.degenerate, α, β, Val(N))
468+
_launch_generic!(dst.data, src.data, op, device, α, β, Val(N))
469+
return nothing
470+
end
471+
328472
end

0 commit comments

Comments
 (0)