@@ -4,7 +4,6 @@ using GPUArrays
44using GPUArrays: @allowscalar
55using GPUArrays. KernelAbstractions: @kernel , @index , get_backend
66using Adapt
7- using TensorKit. LRUCache: LRU
87using TensorKit. TupleTools
98using Strided: StridedViews
109using MatrixAlgebraKit, Adapt
@@ -13,7 +12,7 @@ using TensorKit.TensorOperations: linearize, DefaultAllocator
1312using TensorKit. Factorizations
1413using TensorKit. Factorizations: AbstractAlgorithm
1514using TensorKit: SectorDict, tensormaptype, scalar, similarstoragetype, AdjointTensorMap, scalartype, project_symmetric_and_check
16- using TensorKit: StridedSubblocks, UniqueTreeTransformer, GenericTreeTransformer
15+ using TensorKit: UniqueTreeTransformer, GenericTreeTransformer, @cached , TensorMapSpace, Index2Tuple, IndexTuple
1716import TensorKit: randisometry, rand, randn, fill_braidingsubblock!, add_transform_kernel!
1817
1918function TensorKit. fill_braidingsubblock! (data:: TD , val) where {T, TD <: Union{<:AnyGPUMatrix{T}, <:StridedViews.StridedView{T, 4, <:AnyGPUArray{T}}} }
@@ -272,70 +271,66 @@ function DeviceGenericTreeTransformer(
272271 )
273272end
274273
275- """
276- StorageAdaptor(proto)
277-
278- `Adapt` adaptor moving arrays onto the same device and array type as `proto`, preserving
279- their element type. For `proto::CuVector{Float64}` and `array::Vector{Int}`,
280- the call `adapt(typeof(proto), array)` would force-convert the element type `Int`
281- to `Float64`, while `adapt(StoreAdaptor(proto), array)` does not.
282- """
283- struct StorageAdaptor{A <: AbstractArray }
284- proto:: A
285- end
286- function Adapt. adapt_storage (a:: StorageAdaptor , x:: AbstractArray )
287- dst = similar (a. proto, eltype (x), size (x))
288- isempty (x) && return dst
289- return copy! (dst, x)
274+ # Cache the device transformer directly, constructing the cached host version only on a miss.
275+ @cached function TensorKit. treebraider (
276+ A:: Type{TA} , Vdst:: TensorMapSpace , Vsrc:: TensorMapSpace , p:: Index2Tuple ,
277+ conjsrc:: Bool , levels:: IndexTuple
278+ ) where {TA <: AnyGPUVector }
279+ host = TensorKit. treebraider (Vector{scalartype (A)}, Vdst, Vsrc, p, conjsrc, levels)
280+ return device_transformer (A, host, linearize (p))
290281end
291282
292- function Adapt. adapt_structure (to, t:: DeviceUniqueTreeTransformer )
293- return DeviceUniqueTreeTransformer (
294- Adapt. adapt (to, t. blocks), Adapt. adapt (to, t. work_offsets), t. nwork
295- )
283+ @cached function TensorKit. treetransposer (
284+ A:: Type{TA} , Vdst:: TensorMapSpace , Vsrc:: TensorMapSpace , p:: Index2Tuple , conjsrc:: Bool
285+ ) where {TA <: AnyGPUVector }
286+ host = TensorKit. treetransposer (Vector{scalartype (A)}, Vdst, Vsrc, p, conjsrc)
287+ return device_transformer (A, host, linearize (p))
296288end
297289
298- function Adapt. adapt_structure (to, t:: DeviceGenericTreeTransformer )
299- return DeviceGenericTreeTransformer (
300- Adapt. adapt (to, t. unique_blocks), Adapt. adapt (to, t. blocks),
301- Adapt. adapt (to, t. work_offsets), t. nwork, Adapt. adapt (to, t. coeffs),
302- Adapt. adapt (to, t. structs_dst), Adapt. adapt (to, t. structs_src)
290+ const DEFAULT_DEVICECACHE_SIZE = 1000
291+
292+ function __init__ ()
293+ # extensions can't modify GLOBAL_CACHES during precompilation, so register explicitly
294+ append! (
295+ TensorKit. GLOBAL_CACHES, (
296+ Symbol (" TensorKitGPUArraysExt.GLOBAL_TREEBRAIDER_CACHE" ) => GLOBAL_TREEBRAIDER_CACHE,
297+ Symbol (" TensorKitGPUArraysExt.GLOBAL_TREETRANSPOSER_CACHE" ) => GLOBAL_TREETRANSPOSER_CACHE,
298+ )
303299 )
304- end
305300
306- # Copying a transformer to GPU is more expensive than running it, so we cache the device
307- # copy in a global LRU cache, registered in `TensorKit.GLOBAL_CACHES` so that
308- # `empty_globalcaches!` also frees the device memory. The key is:
309- # - transformer which is an immutable struct. It's hashed and compared by the identity of
310- # its fields, which avoids walking every recoupling matrix on every lookup.
311- # Holding it in the key also keeps it alive, so its `objectid` cannot be
312- # reused by a different transformer while the entry is cached.
313- # - the storage type
314- # - `p`, which is baked into the permuted source strides.
315- # TODO : should this live in the main package?
316- const DEVICE_TRANSFORMER_CACHE = LRU {Any, Any} (; maxsize = TensorKit. DEFAULT_GLOBALCACHE_SIZE[])
301+ # device-caches should probably have smaller sizes:
302+ resize! (GLOBAL_TREEBRAIDER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
303+ resize! (GLOBAL_TREETRANSPOSER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
317304
318- function __init__ ()
319- push! (TensorKit. GLOBAL_CACHES, :DEVICE_TRANSFORMER_CACHE => DEVICE_TRANSFORMER_CACHE)
320305 return nothing
321306end
322307
323- # We have this complicated setup because a naive `adapt` doesn't work.
324- # Rather we copy everything to GPU-native arrays and have kernels that can work
325- # with that.
326- function device_transformer (proto:: AbstractArray , transformer, p)
327- key = (transformer, typeof (proto), p)
328- return get! (DEVICE_TRANSFORMER_CACHE, key) do
329- # be careful about the lifetime of these, since they live in a global cache and
330- # thus persist beyond the call
331- GPUArrays. @uncached Adapt. adapt (
332- StorageAdaptor (proto), _device_transformer (transformer, p)
333- )
308+ # Allocations must outlive any GPUArrays allocation-cache scope around the operation.
309+ function device_transformer (A, transformer:: UniqueTreeTransformer , p)
310+ packed = DeviceUniqueTreeTransformer (transformer, p)
311+ return GPUArrays. @uncached begin
312+ proto = A (undef, 0 )
313+ # Metadata and coefficients have different element types; preserve each on upload.
314+ upload (x) = copy! (similar (proto, eltype (x), size (x)), x)
315+ DeviceUniqueTreeTransformer (upload (packed. blocks), upload (packed. work_offsets), packed. nwork)
334316 end
335317end
336318
337- _device_transformer (t:: UniqueTreeTransformer , p) = DeviceUniqueTreeTransformer (t, p)
338- _device_transformer (t:: GenericTreeTransformer , p) = DeviceGenericTreeTransformer (t, p)
319+ function device_transformer (A, transformer:: GenericTreeTransformer , p)
320+ packed = DeviceGenericTreeTransformer (transformer, p)
321+ return GPUArrays. @uncached begin
322+ proto = A (undef, 0 )
323+ upload (x) = copy! (similar (proto, eltype (x), size (x)), x)
324+ unique = packed. unique_blocks
325+ device_unique = DeviceUniqueTreeTransformer (
326+ upload (unique. blocks), upload (unique. work_offsets), unique. nwork
327+ )
328+ DeviceGenericTreeTransformer (
329+ device_unique, upload (packed. blocks), upload (packed. work_offsets), packed. nwork,
330+ upload (packed. coeffs), upload (packed. structs_dst), upload (packed. structs_src)
331+ )
332+ end
333+ end
339334
340335# COV_EXCL_START
341336# kernels are not reachable by coverage
373368@kernel function unique_batched_permute_kernel! (
374369 data_dst, data_src, op, blocks, work_offsets, α, β, nwork, :: Val{N}
375370 ) where {N}
376- w = @index (Global, Linear) - 1
371+ # w = @index(Global, Linear) - 1 does not work due to JLArrays bug
372+ w = @index (Global, Linear)
373+ w -= 1
377374 if w < nwork
378375 b = _searchblock (work_offsets, w)
379376 blk = @inbounds blocks[b]
398395 data_dst, data_src, op, blocks, work_offsets, coeffs, structs_dst, structs_src,
399396 α, β, nwork, :: Val{N}
400397 ) where {N}
401- w = @index (Global, Linear) - 1
398+ # w = @index(Global, Linear) - 1 does not work due to JLArrays bug
399+ w = @index (Global, Linear)
400+ w -= 1
402401 if w < nwork
403402 # bookkeeping to figure out where to read from and write to
404403 b = _searchblock (work_offsets, w)
@@ -448,30 +447,32 @@ function _launch_generic!(data_dst, data_src, op, transformer, α, β, ::Val{N})
448447 return nothing
449448end
450449
451- const GPUStridedSubblocks = StridedSubblocks{<: AnyGPUArray }
450+ # we don't want/need the `StridedSubblocks` here because that information is already in the transformer
451+ TensorKit. _transform_subblocks (
452+ tdst:: TensorMap , tsrc:: TensorMap ,
453+ transformer:: Union{DeviceUniqueTreeTransformer, DeviceGenericTreeTransformer}
454+ ) = (tdst. data, tsrc. data)
452455
453456function TensorKit. add_transform_kernel! (
454- dst:: GPUStridedSubblocks , src:: GPUStridedSubblocks , p, conjsrc:: Bool ,
455- transformer:: UniqueTreeTransformer{T, N} , α, β, backend, allocator, ntasks:: Int
456- ) where {T, N}
457- # GPU-side object to hold the treetransformer information
458- device = device_transformer (dst. data, transformer, linearize (p))
457+ dst:: AnyGPUVector , src:: AnyGPUVector , p, conjsrc:: Bool ,
458+ device:: DeviceUniqueTreeTransformer , α, β, backend, allocator, ntasks:: Int
459+ )
460+ N = length (linearize (p))
459461 op = conjsrc ? conj : identity
460- _launch_unique! (dst. data , src. data , op, device, α, β, Val (N))
462+ _launch_unique! (dst, src, op, device, α, β, Val (N))
461463 return nothing
462464end
463465
464466function TensorKit. add_transform_kernel! (
465- dst:: GPUStridedSubblocks , src:: GPUStridedSubblocks , p, conjsrc:: Bool ,
466- transformer:: GenericTreeTransformer{T, N} , α, β, backend, allocator, ntasks:: Int
467- ) where {T, N}
468- # GPU-side object to hold the treetransformer information
469- device = device_transformer (dst. data, transformer, linearize (p))
467+ dst:: AnyGPUVector , src:: AnyGPUVector , p, conjsrc:: Bool ,
468+ device:: DeviceGenericTreeTransformer , α, β, backend, allocator, ntasks:: Int
469+ )
470+ N = length (linearize (p))
470471 op = conjsrc ? conj : identity
471472 # one-tree blocks are a scaled permutation, which the unique kernel already handles; the
472473 # two kernels touch disjoint subblocks so the launch order does not matter
473- _launch_unique! (dst. data , src. data , op, device. unique_blocks, α, β, Val (N))
474- _launch_generic! (dst. data , src. data , op, device, α, β, Val (N))
474+ _launch_unique! (dst, src, op, device. unique_blocks, α, β, Val (N))
475+ _launch_generic! (dst, src, op, device, α, β, Val (N))
475476 return nothing
476477end
477478
0 commit comments