@@ -3,11 +3,11 @@ module TensorKitGPUArraysExt
33using GPUArrays
44using GPUArrays: @allowscalar
55using GPUArrays. KernelAbstractions: @kernel , @index , get_backend
6-
6+ using Adapt
77using Strided: StridedViews
88using MatrixAlgebraKit, Adapt
99using TensorKit
10- using TensorKit. TensorOperations: linearize
10+ using TensorKit. TensorOperations: linearize, DefaultAllocator
1111using TensorKit. Factorizations
1212using TensorKit. Factorizations: AbstractAlgorithm
1313using TensorKit: SectorDict, tensormaptype, scalar, similarstoragetype, AdjointTensorMap, scalartype, project_symmetric_and_check
@@ -122,30 +122,346 @@ 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)]
123123end
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+ filter! (kv -> ! isnothing (last (kv)[1 ]. value), DEVICE_TRANSFORMER_CACHE)
315+ entry = (WeakRef (key), Dict {Any, Any} ())
316+ DEVICE_TRANSFORMER_CACHE[objectid (key)] = entry
317+ end
318+ get! (last (entry), (typeof (proto), p)) do
319+ # be careful about the lifetime of these, since they live as long as their
320+ # "parent" on the CPU, so they can persist beyond the call
321+ GPUArrays. @uncached Adapt. adapt (
322+ StorageAdaptor (proto), _device_transformer (transformer, p)
323+ )
324+ end
325+ end
326+ end
327+
328+ _device_transformer (t:: TensorKit.AbelianTreeTransformer , p) = DeviceAbelianTreeTransformer (t, p)
329+ _device_transformer (t:: TensorKit.GenericTreeTransformer , p) = DeviceGenericTreeTransformer (t, p)
330+
125331# COV_EXCL_START
126332# 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]
333+
334+ # largest `i` with `offsets[i] <= w`. This corresponds to the
335+ # block which this kernel thread will work on.
336+ @inline function _searchblock (offsets, w)
337+ lo, hi = 1 , length (offsets)
338+ while lo < hi
339+ mid = (lo + hi + 1 ) >>> 1
340+ if @inbounds offsets[mid] <= w
341+ lo = mid
342+ else
343+ hi = mid - 1
344+ end
345+ end
346+ return lo
347+ end
348+
349+ # Cartesian coordinates of the `w`-th (0-based) entry of a dense subblock of shape `sz`.
350+ # Computed once per thread and then reused for every strided view of that subblock.
351+ # This avoids `StridedView` redoing these divisions on every single element access.
352+ # Integer division on GPU is usually pretty slow.
353+ @inline function _coordinates (w, sz:: NTuple{N, Int} , densestrides:: NTuple{N, Int} ) where {N}
354+ return ntuple (n -> (w ÷ densestrides[n]) % sz[n], Val (N))
355+ end
356+
357+ # finds the overall offset in the output and input arrays corresponding to the **sublock**
358+ # coordinates currently being worked on
359+ @inline function _offset (coords:: NTuple{N, Int} , st:: NTuple{N, Int} , offs) where {N}
360+ return offs + sum (ntuple (n -> coords[n] * st[n], Val (N))) + 1
361+ end
362+
363+ # One thread per destination element in `data_dst`.
364+ @kernel function abelian_batched_permute! (
365+ data_dst, data_src, blocks, work_offsets, α, β, nwork, :: Val{N}
366+ ) where {N}
367+ w = @index (Global, Linear) - 1
368+ if w < nwork
369+ b = _searchblock (work_offsets, w)
370+ blk = @inbounds blocks[b]
371+ coords = _coordinates (w - (@inbounds work_offsets[b]), blk. sz, blk. densestrides)
372+ i_dst = _offset (coords, blk. st_dst, blk. offs_dst)
373+ i_src = _offset (coords, blk. pst_src, blk. offs_src)
374+ @inbounds data_dst[i_dst] = α * blk. coeff * data_src[i_src] + β * data_dst[i_dst]
375+ end
376+ end
377+
378+ # One thread per destination element in `data_dst`. This makes much better use of the
379+ # GPU "massive parallelism" as compared to the one-thread-per-subtransformer approach.
380+ # It also more evenly divides the work among threads so the work profile is less
381+ # jagged. Unlike the CPU implementation, there is no extract → recouple → insert process:
382+ # BLAS is not generally reachable from inside a kernel, and fusing the recoupling into
383+ # the strided gather lets us remove the buffer entirely.
384+ @kernel function generic_batched_permute! (
385+ data_dst, data_src, blocks, work_offsets, coeffs, structs_dst, structs_src,
386+ α, β, nwork, :: Val{N}
387+ ) where {N}
388+ w = @index (Global, Linear) - 1
389+ if w < nwork
390+ # bookkeeping to figure out where to read from and write to
391+ b = _searchblock (work_offsets, w)
392+ blk = @inbounds blocks[b]
393+ local_w = w - (@inbounds work_offsets[b])
394+ blocksize = prod (blk. sz)
395+ i = local_w ÷ blocksize # 0-based destination tree
396+ coords = _coordinates (local_w % blocksize, blk. sz, blk. densestrides)
397+
398+ st_dst, offs_dst = @inbounds structs_dst[blk. dst_offset + i + 1 ]
399+ i_dst = _offset (coords, st_dst, offs_dst)
400+
401+ # dst_i = β * dst_i + α * Σ_j U[i, j] * permute(src_j, p): each output tree is a
402+ # linear combination of the input trees weighted by the recoupling coefficients.
403+ # The permutation of src_j was already done by permuting its strides before the
404+ # kernel launched.
405+ acc = zero (promote_type (eltype (data_src), eltype (coeffs)))
406+ for j in 1 : blk. cols
407+ # TODO is there a more efficient way to do this read?
408+ coeff = @inbounds coeffs[blk. u_offset + (j - 1 ) * blk. rows + i + 1 ]
409+ iszero (coeff) && continue
410+ pst_src, offs_src = @inbounds structs_src[blk. src_offset + j]
411+ acc += coeff * @inbounds data_src[_offset (coords, pst_src, offs_src)]
138412 end
413+ @inbounds data_dst[i_dst] = α * acc + β * data_dst[i_dst]
139414 end
140415end
141416# COV_EXCL_STOP
142417
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
418+ function _launch_abelian! (data_dst, data_src, transformer, α, β, :: Val{N} ) where {N}
419+ nwork = transformer. nwork
420+ nwork == 0 && return nothing
421+ abelian_batched_permute! (get_backend (data_dst))(
422+ data_dst, data_src, transformer. blocks, transformer. work_offsets, α, β, nwork,
423+ Val (N); ndrange = nwork
424+ )
425+ return nothing
426+ end
427+
428+ function _launch_generic! (data_dst, data_src, transformer, α, β, :: Val{N} ) where {N}
429+ nwork = transformer. nwork
430+ nwork == 0 && return nothing
431+ generic_batched_permute! (get_backend (data_dst))(
432+ data_dst, data_src, transformer. blocks, transformer. work_offsets,
433+ transformer. coeffs, transformer. structs_dst, transformer. structs_src, α, β, nwork,
434+ Val (N); ndrange = nwork
435+ )
436+ return nothing
437+ end
438+
439+ function TensorKit. add_transform_kernel! (
440+ data_dst:: A , data_src:: A , p, transformer:: TensorKit.AbelianTreeTransformer{T, N} ,
441+ α, β, backend, allocator, scheduler
442+ ) where {T, N, A <: AnyGPUArray }
443+ # GPU-side object to hold the treetransformer information
444+ device = device_transformer (data_dst, transformer, linearize (p)):: DeviceAbelianTreeTransformer
445+ _launch_abelian! (data_dst, data_src, device, α, β, Val (N))
446+ return nothing
447+ end
448+
449+ function TensorKit. add_transform_kernel! (
450+ data_dst:: A , data_src:: A , p, transformer:: TensorKit.GenericTreeTransformer{T, N} ,
451+ α, β, backend, allocator, scheduler
452+ ) where {T, N, A <: AnyGPUArray }
453+ # GPU-side object to hold the treetransformer information
454+ device = device_transformer (data_dst, transformer, linearize (p)):: DeviceGenericTreeTransformer
455+ # one-tree blocks are a scaled permutation, which the Abelian kernel already handles; the
456+ # two kernels touch disjoint subblocks so the launch order does not matter
457+ _launch_abelian! (data_dst, data_src, device. degenerate, α, β, Val (N))
458+ _launch_generic! (data_dst, data_src, device, α, β, Val (N))
459+ return nothing
460+ end
461+
462+ function TensorKit. TensorOperations. tensorfree! (C:: AnyGPUArray , :: DefaultAllocator )
463+ GPUArrays. unsafe_free! (C)
464+ return nothing
149465end
150466
151467end
0 commit comments