@@ -3,14 +3,18 @@ module TensorKitGPUArraysExt
33using GPUArrays
44using GPUArrays: @allowscalar
55using GPUArrays. KernelAbstractions: @kernel , @index , get_backend
6-
6+ using Adapt
7+ using TensorKit. LRUCache: LRU
8+ using TensorKit. TupleTools
79using Strided: StridedViews
810using MatrixAlgebraKit, Adapt
911using TensorKit
12+ using TensorKit. TensorOperations: linearize, DefaultAllocator
1013using TensorKit. Factorizations
1114using TensorKit. Factorizations: AbstractAlgorithm
1215using TensorKit: SectorDict, tensormaptype, scalar, similarstoragetype, AdjointTensorMap, scalartype, project_symmetric_and_check
13- import TensorKit: randisometry, rand, randn, fill_braidingsubblock!
16+ using TensorKit: StridedSubblocks, UniqueTreeTransformer
17+ import TensorKit: randisometry, rand, randn, fill_braidingsubblock!, add_transform_kernel!
1418
1519function TensorKit. fill_braidingsubblock! (data:: TD , val) where {T, TD <: Union{<:AnyGPUMatrix{T}, <:StridedViews.StridedView{T, 4, <:AnyGPUArray{T}}} }
1620 # COV_EXCL_START
@@ -121,5 +125,204 @@ function TensorKit.scalar(t::TensorMap{T, S, 0, 0, <:AnyGPUArray}) where {T, S}
121125 return isempty (inds) ? zero (scalartype (t)) : @allowscalar @inbounds t. data[only (inds)]
122126end
123127
128+ # Device-side tree transformers
129+ # -----------------------------
130+ # A `TreeTransformer` stores the mapping between subblock positions (plus recoupling
131+ # coefficients) and the `StridedStructure`s of the source and destination spaces.
132+ # We resolve the positions into sizes/strides/offsets and pack all the information on the
133+ # CPU side into dense vectors of numbers, plus some accounting information so we know how
134+ # to unpack in the kernel. Also, we can permute the source strides "in advance" on the CPU side.
135+ # We also precompute the strides of the subblock each kernel index will work on,
136+ # so that the GPU thread can recover the Cartesian coordinates it will need for input/ouput,
137+ # and a running `work_offsets` count of destination elements, so that a kernel can run one
138+ # thread per output element and recover which input that element belongs with.
139+
140+ # Some possible TODO here:
141+ # - Try cuTILE as this is a classic tile programming problem
142+ # - Use shared memory to coalesce the reads
143+ # - Use a 2D grid for the Generic case
144+
145+ const TreeStructure{N} = Tuple{NTuple{N, Int}, Int}
146+
147+ """
148+ UniqueTransformerBlock{T, N}
149+
150+ `isbits` descriptor for a subblock that is a *single* scaled permutation:
151+ an entry of a `UniqueTreeTransformer`.
152+ """
153+ struct UniqueTransformerBlock{T, N}
154+ coeff:: T
155+ sz:: NTuple{N, Int}
156+ dense_strides:: NTuple{N, Int}
157+ strides_dst:: NTuple{N, Int}
158+ offsets_dst:: Int
159+ permuted_strides_src:: NTuple{N, Int} # source strides, permuted by `p`
160+ offsets_src:: Int
161+ end
162+
163+ # device-side simple struct that GPU kernels can use
164+ struct DeviceUniqueTreeTransformer{VB <: AbstractVector{<:UniqueTransformerBlock} , VO <: AbstractVector{Int} }
165+ blocks:: VB
166+ work_offsets:: VO
167+ nwork:: Int
168+ end
169+
170+ # strides of a dense array of shape `sz`
171+ _dense_strides (size:: Dims ) = (1 , Base. front (cumprod (size))... )
172+
173+ # `permute(Vsrc, p) == Vdst` is enforced when the transformer is built, so the permuted
174+ # source shape always matches `sz_dst` and the two views share Cartesian inds.
175+ function _unique_block (
176+ coeff:: T , (size_dst, strides_dst, offsets_dst), (_, strides_src, offsets_src), p
177+ ) where {T}
178+ return UniqueTransformerBlock {T, length(size_dst)} (
179+ coeff, size_dst, _dense_strides (size_dst), strides_dst, offsets_dst,
180+ TupleTools. getindices (strides_src, p), offsets_src
181+ )
182+ end
183+
184+ function _work_offsets (work)
185+ offsets = cumsum (work)
186+ pushfirst! (offsets, 0 )
187+ total = pop! (offsets)
188+ return offsets, total
189+ end
190+
191+ function DeviceUniqueTreeTransformer (transformer:: UniqueTreeTransformer{T, N} , p) where {T, N}
192+ (; structure_dst, structure_src) = transformer
193+ blocks = UniqueTransformerBlock{T, N}[
194+ _unique_block (coeff, structure_dst[idst], structure_src[isrc], p)
195+ for (coeff, idst, isrc) in transformer. data
196+ ]
197+ work_offsets, nwork = _work_offsets (prod (blk. sz) for blk in blocks)
198+ return DeviceUniqueTreeTransformer (blocks, work_offsets, nwork)
199+ end
200+
201+ """
202+ StorageAdaptor(proto)
203+
204+ `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`
206+ to `Float64`, while `adapt(StoreAdaptor(proto), array)` does not.
207+ """
208+ struct StorageAdaptor{A <: AbstractArray }
209+ proto:: A
210+ end
211+ function Adapt. adapt_storage (a:: StorageAdaptor , x:: AbstractArray )
212+ dst = similar (a. proto, eltype (x), size (x))
213+ isempty (x) && return dst
214+ return copy! (dst, x)
215+ end
216+
217+ function Adapt. adapt_structure (to, t:: DeviceUniqueTreeTransformer )
218+ return DeviceUniqueTreeTransformer (
219+ Adapt. adapt (to, t. blocks), Adapt. adapt (to, t. work_offsets), t. nwork
220+ )
221+ end
222+
223+ # Copying a transformer to GPU is more expensive than running it, so we cache the device
224+ # copy in a global LRU cache, registered in `TensorKit.GLOBAL_CACHES` so that
225+ # `empty_globalcaches!` also frees the device memory. The key is:
226+ # - transformer which is an immutable struct. It's hashed and compared by the identity of
227+ # its fields, which avoids walking every recoupling matrix on every lookup.
228+ # Holding it in the key also keeps it alive, so its `objectid` cannot be
229+ # reused by a different transformer while the entry is cached.
230+ # - the storage type
231+ # - `p`, which is baked into the permuted source strides.
232+ # TODO : should this live in the main package?
233+ const DEVICE_TRANSFORMER_CACHE = LRU {Any, Any} (; maxsize = TensorKit. DEFAULT_GLOBALCACHE_SIZE[])
234+
235+ function __init__ ()
236+ push! (TensorKit. GLOBAL_CACHES, :DEVICE_TRANSFORMER_CACHE => DEVICE_TRANSFORMER_CACHE)
237+ return nothing
238+ end
239+
240+ # We have this complicated setup because a naive `adapt` doesn't work.
241+ # Rather we copy everything to GPU-native arrays and have kernels that can work
242+ # with that.
243+ function device_transformer (proto:: AbstractArray , transformer, p)
244+ key = (transformer, typeof (proto), p)
245+ return get! (DEVICE_TRANSFORMER_CACHE, key) do
246+ # be careful about the lifetime of these, since they live in a global cache and
247+ # thus persist beyond the call
248+ GPUArrays. @uncached Adapt. adapt (
249+ StorageAdaptor (proto), _device_transformer (transformer, p)
250+ )
251+ end
252+ end
253+
254+ _device_transformer (t:: UniqueTreeTransformer , p) = DeviceUniqueTreeTransformer (t, p)
255+
256+ # COV_EXCL_START
257+ # kernels are not reachable by coverage
258+
259+ # largest `i` with `offsets[i] <= w`. This corresponds to the
260+ # block which this kernel thread will work on. Since this is
261+ # used inside a GPU kernel, searchsortedlast/searchsortedfirst
262+ # won't work.
263+ @inline function _searchblock (offsets, w)
264+ lo, hi = 1 , length (offsets)
265+ while lo < hi
266+ mid = (lo + hi + 1 ) >>> 1
267+ if @inbounds offsets[mid] <= w
268+ lo = mid
269+ else
270+ hi = mid - 1
271+ end
272+ end
273+ return lo
274+ end
275+
276+ # Cartesian coordinates of the `w`-th (0-based) entry of a dense subblock of shape `sz`.
277+ @inline function _coordinates (w, size:: NTuple{N, Int} , dense_strides:: NTuple{N, Int} ) where {N}
278+ return ntuple (n -> (w ÷ dense_strides[n]) % size[n], Val (N))
279+ end
280+
281+ # finds the overall linear index in the output and input arrays corresponding to the **sublock**
282+ # coordinates currently being worked on
283+ @inline function _linear_index (coords:: NTuple{N, Int} , strides:: NTuple{N, Int} , offset) where {N}
284+ return offset + sum (ntuple (n -> coords[n] * strides[n], Val (N))) + 1
285+ end
286+
287+ # One thread per destination element in `data_dst`. `op` is `identity` or `conj`, and is
288+ # applied to the source data only (not to the coefficients).
289+ @kernel function unique_batched_permute_kernel! (
290+ data_dst, data_src, op, blocks, work_offsets, α, β, nwork, :: Val{N}
291+ ) where {N}
292+ w = @index (Global, Linear) - 1
293+ if w < nwork
294+ b = _searchblock (work_offsets, w)
295+ blk = @inbounds blocks[b]
296+ coords = _coordinates (w - (@inbounds work_offsets[b]), blk. sz, blk. dense_strides)
297+ i_dst = _linear_index (coords, blk. strides_dst, blk. offsets_dst)
298+ i_src = _linear_index (coords, blk. permuted_strides_src, blk. offsets_src)
299+ @inbounds data_dst[i_dst] = α * blk. coeff * op (data_src[i_src]) + β * data_dst[i_dst]
300+ end
301+ end
302+
303+ # COV_EXCL_STOP
304+
305+ function _launch_unique! (data_dst, data_src, op, transformer, α, β, :: Val{N} ) where {N}
306+ nwork = transformer. nwork
307+ nwork == 0 && return nothing
308+ unique_batched_permute_kernel! (get_backend (data_dst))(
309+ data_dst, data_src, op, transformer. blocks, transformer. work_offsets, α, β, nwork,
310+ Val (N); ndrange = nwork
311+ )
312+ return nothing
313+ end
314+
315+ const GPUStridedSubblocks = StridedSubblocks{<: AnyGPUArray }
316+
317+ function TensorKit. add_transform_kernel! (
318+ dst:: GPUStridedSubblocks , src:: GPUStridedSubblocks , p, conjsrc:: Bool ,
319+ transformer:: UniqueTreeTransformer{T, N} , α, β, backend, allocator, ntasks:: Int
320+ ) where {T, N}
321+ # GPU-side object to hold the treetransformer information
322+ device = device_transformer (dst. data, transformer, linearize (p))
323+ op = conjsrc ? conj : identity
324+ _launch_unique! (dst. data, src. data, op, device, α, β, Val (N))
325+ return nothing
326+ end
124327
125328end
0 commit comments