Skip to content

Commit 32a46c9

Browse files
committed
Implement different kernel approach for GPU-side braiding
1 parent 1c63eb4 commit 32a46c9

1 file changed

Lines changed: 327 additions & 18 deletions

File tree

‎ext/TensorKitGPUArraysExt.jl‎

Lines changed: 327 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ module TensorKitGPUArraysExt
33
using GPUArrays
44
using GPUArrays: @allowscalar
55
using GPUArrays.KernelAbstractions: @kernel, @index, get_backend
6-
6+
using Adapt
77
using Strided: StridedViews
88
using MatrixAlgebraKit, Adapt
99
using TensorKit
@@ -122,30 +122,339 @@ function TensorKit.scalar(t::TensorMap{T, S, 0, 0, <:AnyGPUArray}) where {T, S}
122122
return isempty(inds) ? zero(scalartype(t)) : @allowscalar @inbounds t.data[only(inds)]
123123
end
124124

125+
# Device-side tree transformers
126+
# -----------------------------
127+
# `AbelianTransformerData` is `isbits`, but `GenericTransformerData` isn't.
128+
# `Matrix{T}` and two ragged `Vector`s, so we can't just call `adapt` on it.
129+
# But we can work around this but packing all the information on the CPU side
130+
# into dense vectors of numbers, plus some accounting information so we know how
131+
# to unpack in the generic kernel. Also, we can permute the source strides "in
132+
# advance" on the CPU side. We also precompute the strides of the subblock each
133+
# kernel index will work on, so that the GPU thread can recover the Cartesian
134+
# coordinates it will need for input/ouput, and a running `work_offsets` count
135+
# of destination elements, so that a kernel can run one thread per output
136+
# element and recover which subblock that element belongs with.
137+
138+
# Some possible TODO here:
139+
# - Try cuTILE as this is a classic tile programming problem
140+
# - Use shared memory to coalesce the reads
141+
# - Use a 2D grid for the Generic case
142+
143+
const TreeStructure{N} = Tuple{NTuple{N, Int}, Int}
144+
145+
"""
146+
AbelianTransformerBlock{T, N}
147+
148+
Isbits descriptor for a subblock that is a single scaled permutation: either an entry of
149+
an `AbelianTreeTransformer`, or a degenerate (one-tree) block of a
150+
`GenericTreeTransformer`.
151+
"""
152+
struct AbelianTransformerBlock{T, N}
153+
coeff::T
154+
sz::NTuple{N, Int}
155+
densestrides::NTuple{N, Int}
156+
st_dst::NTuple{N, Int}
157+
offs_dst::Int
158+
pst_src::NTuple{N, Int} # source strides, permuted by `p`
159+
offs_src::Int
160+
end
161+
162+
"""
163+
GenericTransformerBlock{N}
164+
165+
Descriptor for a recoupling block of a `GenericTreeTransformer`, indexing into the
166+
flat `coeffs`/`structs_dst`/`structs_src` vectors of a `DeviceGenericTreeTransformer`.
167+
** All offsets are 0-based since it makes the arithmetic easier. **
168+
"""
169+
struct GenericTransformerBlock{N}
170+
sz::NTuple{N, Int}
171+
densestrides::NTuple{N, Int}
172+
rows::Int
173+
cols::Int
174+
u_offset::Int # location in the flattened U vector to find this block's U
175+
dst_offset::Int
176+
src_offset::Int
177+
end
178+
179+
struct DeviceAbelianTreeTransformer{VB <: AbstractVector{<:AbelianTransformerBlock}, VO <: AbstractVector{Int}}
180+
blocks::VB
181+
work_offsets::VO
182+
nwork::Int
183+
end
184+
185+
# force all the type signatures here to make sure doing something wrong fails
186+
# before the kernel launch. Kernel error dumps are awful and hard to interpret.
187+
struct DeviceGenericTreeTransformer{VO <: AbstractVector{Int}, DA <: DeviceAbelianTreeTransformer{<:Any, VO}, VB <: AbstractVector{<:GenericTransformerBlock}, VC <: AbstractVector{<:Number}, VS <: AbstractVector{<:Tuple{<:Tuple{Vararg{Int}}, Int}}}
188+
degenerate::DA # length(U) = 1 blocks, can be handled by Abelian kernel
189+
blocks::VB
190+
work_offsets::VO
191+
nwork::Int
192+
coeffs::VC # every `U`, concatenated in column-major order
193+
structs_dst::VS
194+
structs_src::VS
195+
end
196+
197+
# strides of a dense array of shape `sz`
198+
_densestrides(sz::NTuple{N, Int}) where {N} = ntuple(n -> prod(sz[1:(n - 1)]; init = 1), Val(N))
199+
_permutestrides(st::NTuple{N, Int}, p) where {N} = ntuple(n -> st[p[n]], Val(N))
200+
201+
# `permute(Vsrc, p) == Vdst` is enforced when the transformer is built, so the permuted
202+
# source shape always matches `sz_dst` and the two views share Cartesian inds.
203+
function _abelian_block(
204+
coeff::T, (sz_dst, st_dst, offs_dst), (_, st_src, offs_src), p
205+
) where {T}
206+
return AbelianTransformerBlock{T, length(sz_dst)}(
207+
coeff, sz_dst, _densestrides(sz_dst), st_dst, offs_dst,
208+
_permutestrides(st_src, p), offs_src
209+
)
210+
end
211+
212+
function _work_offsets(work)
213+
offsets = cumsum(work)
214+
pushfirst!(offsets, 0)
215+
total = pop!(offsets)
216+
return offsets, total
217+
end
218+
219+
function DeviceAbelianTreeTransformer(
220+
transformer::TensorKit.AbelianTreeTransformer{T, N}, p
221+
) where {T, N}
222+
blocks = AbelianTransformerBlock{T, N}[_abelian_block(entry..., p) for entry in transformer.data]
223+
work_offsets, nwork = _work_offsets(prod(blk.sz) for blk in blocks)
224+
return DeviceAbelianTreeTransformer(blocks, work_offsets, nwork)
225+
end
226+
227+
function DeviceGenericTreeTransformer(
228+
transformer::TensorKit.GenericTreeTransformer{T, N}, p
229+
) where {T, N}
230+
degenerate = AbelianTransformerBlock{T, N}[]
231+
blocks = GenericTransformerBlock{N}[]
232+
coeffs = T[]
233+
structs_dst = TreeStructure{N}[]
234+
structs_src = TreeStructure{N}[]
235+
236+
for (U, (sz_dst, sts_dst), (sz_src, sts_src)) in transformer.data
237+
if length(U) == 1 # same as the Abelian case
238+
push!(
239+
degenerate, _abelian_block(
240+
only(U), (sz_dst, only(sts_dst)...), (sz_src, only(sts_src)...), p
241+
)
242+
)
243+
else
244+
push!(
245+
blocks, GenericTransformerBlock{N}(
246+
sz_dst, _densestrides(sz_dst), size(U, 1), size(U, 2),
247+
length(coeffs), length(structs_dst), length(structs_src)
248+
)
249+
)
250+
append!(coeffs, U)
251+
append!(structs_dst, sts_dst)
252+
for (st_src, offs_src) in sts_src
253+
push!(structs_src, (_permutestrides(st_src, p), offs_src))
254+
end
255+
end
256+
end
257+
258+
deg_offsets, deg_nwork = _work_offsets(prod(blk.sz) for blk in degenerate)
259+
work_offsets, nwork = _work_offsets(blk.rows * prod(blk.sz) for blk in blocks)
260+
return DeviceGenericTreeTransformer(
261+
DeviceAbelianTreeTransformer(degenerate, deg_offsets, deg_nwork),
262+
blocks, work_offsets, nwork, coeffs, structs_dst, structs_src
263+
)
264+
end
265+
266+
"""
267+
StorageAdaptor(proto)
268+
269+
`Adapt` adaptor moving arrays onto the same device and array type as `proto`, preserving
270+
their element type. `adapt(CuVector{Float64}, ::Vector{Int})` would force-convert the Int
271+
to Float64, while `similar(proto, Int, n)` doesn't.
272+
"""
273+
struct StorageAdaptor{A <: AbstractArray}
274+
proto::A
275+
end
276+
function Adapt.adapt_storage(a::StorageAdaptor, x::AbstractArray)
277+
dst = similar(a.proto, eltype(x), size(x))
278+
isempty(x) && return dst
279+
return copyto!(dst, x)
280+
end
281+
282+
function Adapt.adapt_structure(to, t::DeviceAbelianTreeTransformer)
283+
return DeviceAbelianTreeTransformer(
284+
Adapt.adapt(to, t.blocks), Adapt.adapt(to, t.work_offsets), t.nwork
285+
)
286+
end
287+
function Adapt.adapt_structure(to, t::DeviceGenericTreeTransformer)
288+
return DeviceGenericTreeTransformer(
289+
Adapt.adapt(to, t.degenerate), Adapt.adapt(to, t.blocks),
290+
Adapt.adapt(to, t.work_offsets), t.nwork, Adapt.adapt(to, t.coeffs),
291+
Adapt.adapt(to, t.structs_dst), Adapt.adapt(to, t.structs_src)
292+
)
293+
end
294+
295+
# Copying a transformer to GPU is more expensive than running it, and transformers are
296+
# themselves cached (and thus long-lived) by `treebraider`/`treetransposer`, so we cache the
297+
# device copy for as long as the CPU original is "alive". The key is:
298+
# - `transformer.data`
299+
# - the storage type
300+
# - `p`, which is baked into the permuted source strides.
301+
# Using `objectid` avoids walking every recoupling matrix on every lookup.
302+
# TODO: should this live in the main package?
303+
const DEVICE_TRANSFORMER_CACHE = Dict{UInt, Tuple{WeakRef, Dict{Any, Any}}}()
304+
const DEVICE_TRANSFORMER_LOCK = ReentrantLock()
305+
306+
# We have this complicated setup because a naive `adapt` doesn't work.
307+
# Rather we copy everything to GPU-native arrays and have kernels that can work
308+
# with that.
309+
function device_transformer(proto::AbstractArray, transformer, p)
310+
key = transformer.data
311+
return Base.@lock DEVICE_TRANSFORMER_LOCK begin
312+
entry = get(DEVICE_TRANSFORMER_CACHE, objectid(key), nothing)
313+
if isnothing(entry) || entry[1].value !== key
314+
# misses are rare (once per transformer), so pay for a sweep of the entries
315+
# whose host transformer has been collected and free their device copies
316+
filter!(kv -> !isnothing(last(kv)[1].value), DEVICE_TRANSFORMER_CACHE)
317+
entry = (WeakRef(key), Dict{Any, Any}())
318+
DEVICE_TRANSFORMER_CACHE[objectid(key)] = entry
319+
end
320+
get!(last(entry), (typeof(proto), p)) do
321+
Adapt.adapt(StorageAdaptor(proto), _device_transformer(transformer, p))
322+
end
323+
end
324+
end
325+
326+
_device_transformer(t::TensorKit.AbelianTreeTransformer, p) = DeviceAbelianTreeTransformer(t, p)
327+
_device_transformer(t::TensorKit.GenericTreeTransformer, p) = DeviceGenericTreeTransformer(t, p)
328+
125329
# COV_EXCL_START
126330
# kernels are not reachable by coverage
127-
@kernel function abelian_batched_permute!(data_dst::AbstractArray{T}, data_src, transformer_data, p, α, β, ::Val{N}) where {T, N}
128-
idx = @index(Global, Linear)
129-
if idx <= length(transformer_data)
130-
coeff, struct_dst, struct_src = @inbounds transformer_data[idx]
131-
dst_view = StridedViews.StridedView(data_dst, struct_dst...)
132-
sz_src, st_src, offs_src = struct_src
133-
psz = ntuple(n -> sz_src[p[n]], Val(N))
134-
pst = ntuple(n -> st_src[p[n]], Val(N))
135-
p_src_view = StridedViews.StridedView(data_src, psz, pst, offs_src)
136-
for ix in 1:length(dst_view)
137-
@inbounds dst_view[ix] = α * coeff * p_src_view[ix] + β * dst_view[ix]
331+
332+
# largest `i` with `offsets[i] <= w`. This corresponds to the
333+
# block which this kernel thread will work on.
334+
@inline function _searchblock(offsets, w)
335+
lo, hi = 1, length(offsets)
336+
while lo < hi
337+
mid = (lo + hi + 1) >>> 1
338+
if @inbounds offsets[mid] <= w
339+
lo = mid
340+
else
341+
hi = mid - 1
138342
end
139343
end
344+
return lo
345+
end
346+
347+
# Cartesian coordinates of the `w`-th (0-based) entry of a dense subblock of shape `sz`.
348+
# Computed once per thread and then reused for every strided view of that subblock.
349+
# This avoids `StridedView` redoing these divisions on every single element access.
350+
# Integer division on GPU is usually pretty slow.
351+
@inline function _coordinates(w, sz::NTuple{N, Int}, densestrides::NTuple{N, Int}) where {N}
352+
return ntuple(n -> (w ÷ densestrides[n]) % sz[n], Val(N))
353+
end
354+
355+
# finds the overall offset in the output and input arrays corresponding to the **sublock**
356+
# coordinates currently being worked on
357+
@inline function _offset(coords::NTuple{N, Int}, st::NTuple{N, Int}, offs) where {N}
358+
return offs + sum(ntuple(n -> coords[n] * st[n], Val(N))) + 1
359+
end
360+
361+
# One thread per destination element in `data_dst`.
362+
@kernel function abelian_batched_permute!(
363+
data_dst, data_src, blocks, work_offsets, α, β, nwork, ::Val{N}
364+
) where {N}
365+
w = @index(Global, Linear) - 1
366+
if w < nwork
367+
b = _searchblock(work_offsets, w)
368+
blk = @inbounds blocks[b]
369+
coords = _coordinates(w - (@inbounds work_offsets[b]), blk.sz, blk.densestrides)
370+
i_dst = _offset(coords, blk.st_dst, blk.offs_dst)
371+
i_src = _offset(coords, blk.pst_src, blk.offs_src)
372+
@inbounds data_dst[i_dst] = α * blk.coeff * data_src[i_src] + β * data_dst[i_dst]
373+
end
374+
end
375+
376+
# One thread per destination element in `data_dst`. This makes much better use of the
377+
# GPU "massive parallelism" as compared to the one-thread-per-subtransformer approach.
378+
# It also more evenly divides the work among threads so the work profile is less
379+
# jagged. Unlike the CPU implementation, there is no extract → recouple → insert process:
380+
# BLAS is not generally reachable from inside a kernel, and fusing the recoupling into
381+
# the strided gather lets us remove the buffer entirely.
382+
@kernel function generic_batched_permute!(
383+
data_dst, data_src, blocks, work_offsets, coeffs, structs_dst, structs_src,
384+
α, β, nwork, ::Val{N}
385+
) where {N}
386+
w = @index(Global, Linear) - 1
387+
if w < nwork
388+
# bookkeeping to figure out where to read from and write to
389+
b = _searchblock(work_offsets, w)
390+
blk = @inbounds blocks[b]
391+
local_w = w - (@inbounds work_offsets[b])
392+
blocksize = prod(blk.sz)
393+
i = local_w ÷ blocksize # 0-based destination tree
394+
coords = _coordinates(local_w % blocksize, blk.sz, blk.densestrides)
395+
396+
st_dst, offs_dst = @inbounds structs_dst[blk.dst_offset + i + 1]
397+
i_dst = _offset(coords, st_dst, offs_dst)
398+
399+
# dst_i = β * dst_i + α * Σ_j U[i, j] * permute(src_j, p): each output tree is a
400+
# linear combination of the input trees weighted by the recoupling coefficients.
401+
# The permutation of src_j was already done by permuting its strides before the
402+
# kernel launched.
403+
acc = zero(promote_type(eltype(data_src), eltype(coeffs)))
404+
for j in 1:blk.cols
405+
# TODO is there a more efficient way to do this read?
406+
coeff = @inbounds coeffs[blk.u_offset + (j - 1) * blk.rows + i + 1]
407+
iszero(coeff) && continue
408+
pst_src, offs_src = @inbounds structs_src[blk.src_offset + j]
409+
acc += coeff * @inbounds data_src[_offset(coords, pst_src, offs_src)]
410+
end
411+
@inbounds data_dst[i_dst] = α * acc + β * data_dst[i_dst]
412+
end
140413
end
141414
# COV_EXCL_STOP
142415

143-
function TensorKit.add_transform_kernel!(data_dst::A, data_src::A, p, transformer::TensorKit.AbelianTreeTransformer{T, N}, α, β, backend, allocator, scheduler) where {T, N, A <: AnyGPUArray}
144-
new_typ = similar(data_dst, Tuple{T, TensorKit.StridedStructure{N}, TensorKit.StridedStructure{N}}, 0)
145-
device_data = adapt(typeof(new_typ), transformer.data)
146-
p_ = linearize(p)
147-
abelian_batched_permute!(get_backend(data_dst))(data_dst, data_src, device_data, p_, α, β, Val(N); ndrange = length(device_data))
148-
return
416+
function _launch_abelian!(data_dst, data_src, transformer, α, β, ::Val{N}) where {N}
417+
nwork = transformer.nwork
418+
nwork == 0 && return nothing
419+
abelian_batched_permute!(get_backend(data_dst))(
420+
data_dst, data_src, transformer.blocks, transformer.work_offsets, α, β, nwork,
421+
Val(N); ndrange = nwork
422+
)
423+
return nothing
424+
end
425+
426+
function _launch_generic!(data_dst, data_src, transformer, α, β, ::Val{N}) where {N}
427+
nwork = transformer.nwork
428+
nwork == 0 && return nothing
429+
generic_batched_permute!(get_backend(data_dst))(
430+
data_dst, data_src, transformer.blocks, transformer.work_offsets,
431+
transformer.coeffs, transformer.structs_dst, transformer.structs_src, α, β, nwork,
432+
Val(N); ndrange = nwork
433+
)
434+
return nothing
435+
end
436+
437+
function TensorKit.add_transform_kernel!(
438+
data_dst::A, data_src::A, p, transformer::TensorKit.AbelianTreeTransformer{T, N},
439+
α, β, backend, allocator, scheduler
440+
) where {T, N, A <: AnyGPUArray}
441+
# GPU-side object to hold the treetransformer information
442+
device = device_transformer(data_dst, transformer, linearize(p))::DeviceAbelianTreeTransformer
443+
_launch_abelian!(data_dst, data_src, device, α, β, Val(N))
444+
return nothing
445+
end
446+
447+
function TensorKit.add_transform_kernel!(
448+
data_dst::A, data_src::A, p, transformer::TensorKit.GenericTreeTransformer{T, N},
449+
α, β, backend, allocator, scheduler
450+
) where {T, N, A <: AnyGPUArray}
451+
# GPU-side object to hold the treetransformer information
452+
device = device_transformer(data_dst, transformer, linearize(p))::DeviceGenericTreeTransformer
453+
# one-tree blocks are a scaled permutation, which the Abelian kernel already handles; the
454+
# two kernels touch disjoint subblocks so the launch order does not matter
455+
_launch_abelian!(data_dst, data_src, device.degenerate, α, β, Val(N))
456+
_launch_generic!(data_dst, data_src, device, α, β, Val(N))
457+
return nothing
149458
end
150459

151460
end

0 commit comments

Comments
 (0)