Skip to content

Commit 68c2038

Browse files
committed
make GPU versions use @cached
1 parent f218f28 commit 68c2038

1 file changed

Lines changed: 52 additions & 33 deletions

File tree

‎ext/TensorKitGPUArraysExt.jl‎

Lines changed: 52 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ using GPUArrays
44
using GPUArrays: @allowscalar
55
using GPUArrays.KernelAbstractions: @kernel, @index, get_backend
66
using Adapt
7-
using TensorKit.LRUCache: LRU
87
using TensorKit.TupleTools
98
using Strided: StridedViews
109
using MatrixAlgebraKit, Adapt
@@ -13,7 +12,7 @@ using TensorKit.TensorOperations: linearize, DefaultAllocator
1312
using TensorKit.Factorizations
1413
using TensorKit.Factorizations: AbstractAlgorithm
1514
using TensorKit: SectorDict, tensormaptype, scalar, similarstoragetype, AdjointTensorMap, scalartype, project_symmetric_and_check
16-
using TensorKit: StridedSubblocks, UniqueTreeTransformer, GenericTreeTransformer
15+
using TensorKit: StridedSubblocks, UniqueTreeTransformer, GenericTreeTransformer, @cached, TensorMapSpace, Index2Tuple, IndexTuple
1716
import TensorKit: randisometry, rand, randn, fill_braidingsubblock!, add_transform_kernel!
1817

1918
function TensorKit.fill_braidingsubblock!(data::TD, val) where {T, TD <: Union{<:AnyGPUMatrix{T}, <:StridedViews.StridedView{T, 4, <:AnyGPUArray{T}}}}
@@ -303,35 +302,48 @@ function Adapt.adapt_structure(to, t::DeviceGenericTreeTransformer)
303302
)
304303
end
305304

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[])
305+
# Cache the device transformer directly, constructing the cached host version only on a miss.
306+
@cached function TensorKit.treebraider(
307+
A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple,
308+
conjsrc::Bool, levels::IndexTuple
309+
) where {TA <: AnyGPUVector}
310+
host = TensorKit.treebraider(Vector{scalartype(A)}, Vdst, Vsrc, p, conjsrc, levels)
311+
return device_transformer(A, host, linearize(p))
312+
end
313+
314+
@cached function TensorKit.treetransposer(
315+
A::Type{TA}, Vdst::TensorMapSpace, Vsrc::TensorMapSpace, p::Index2Tuple, conjsrc::Bool
316+
) where {TA <: AnyGPUVector}
317+
host = TensorKit.treetransposer(Vector{scalartype(A)}, Vdst, Vsrc, p, conjsrc)
318+
return device_transformer(A, host, linearize(p))
319+
end
320+
321+
const DEFAULT_DEVICECACHE_SIZE = 1000
317322

318323
function __init__()
319-
push!(TensorKit.GLOBAL_CACHES, :DEVICE_TRANSFORMER_CACHE => DEVICE_TRANSFORMER_CACHE)
324+
# extensions can't modify GLOBAL_CACHES during precompilation, so register explicitly
325+
append!(
326+
TensorKit.GLOBAL_CACHES, (
327+
Symbol("TensorKitGPUArraysExt.GLOBAL_TREEBRAIDER_CACHE") => GLOBAL_TREEBRAIDER_CACHE,
328+
Symbol("TensorKitGPUArraysExt.GLOBAL_TREETRANSPOSER_CACHE") => GLOBAL_TREETRANSPOSER_CACHE,
329+
)
330+
)
331+
332+
# device-caches should probably have smaller sizes:
333+
resize!(GLOBAL_TREEBRAIDER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
334+
resize!(GLOBAL_TREETRANSPOSER_CACHE; maxsize = DEFAULT_DEVICECACHE_SIZE)
335+
320336
return nothing
321337
end
322338

323339
# We have this complicated setup because a naive `adapt` doesn't work.
324340
# Rather we copy everything to GPU-native arrays and have kernels that can work
325341
# 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-
)
334-
end
342+
function device_transformer(A, transformer, p)
343+
# Allocations must outlive any GPUArrays allocation-cache scope around the operation.
344+
return GPUArrays.@uncached Adapt.adapt(
345+
StorageAdaptor(A(undef, 0)), _device_transformer(transformer, p)
346+
)
335347
end
336348

337349
_device_transformer(t::UniqueTreeTransformer, p) = DeviceUniqueTreeTransformer(t, p)
@@ -373,7 +385,9 @@ end
373385
@kernel function unique_batched_permute_kernel!(
374386
data_dst, data_src, op, blocks, work_offsets, α, β, nwork, ::Val{N}
375387
) where {N}
376-
w = @index(Global, Linear) - 1
388+
# w = @index(Global, Linear) - 1 does not work due to JLArrays bug
389+
w = @index(Global, Linear)
390+
w -= 1
377391
if w < nwork
378392
b = _searchblock(work_offsets, w)
379393
blk = @inbounds blocks[b]
@@ -398,7 +412,9 @@ end
398412
data_dst, data_src, op, blocks, work_offsets, coeffs, structs_dst, structs_src,
399413
α, β, nwork, ::Val{N}
400414
) where {N}
401-
w = @index(Global, Linear) - 1
415+
# w = @index(Global, Linear) - 1 does not work due to JLArrays bug
416+
w = @index(Global, Linear)
417+
w -= 1
402418
if w < nwork
403419
# bookkeeping to figure out where to read from and write to
404420
b = _searchblock(work_offsets, w)
@@ -450,23 +466,26 @@ end
450466

451467
const GPUStridedSubblocks = StridedSubblocks{<:AnyGPUArray}
452468

469+
TensorKit._transform_subblocks(
470+
tdst::TensorMap, tsrc::TensorMap,
471+
transformer::Union{DeviceUniqueTreeTransformer, DeviceGenericTreeTransformer}
472+
) = StridedSubblocks(tdst), StridedSubblocks(tsrc)
473+
453474
function TensorKit.add_transform_kernel!(
454475
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))
476+
device::DeviceUniqueTreeTransformer, α, β, backend, allocator, ntasks::Int
477+
)
478+
N = length(linearize(p))
459479
op = conjsrc ? conj : identity
460480
_launch_unique!(dst.data, src.data, op, device, α, β, Val(N))
461481
return nothing
462482
end
463483

464484
function TensorKit.add_transform_kernel!(
465485
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))
486+
device::DeviceGenericTreeTransformer, α, β, backend, allocator, ntasks::Int
487+
)
488+
N = length(linearize(p))
470489
op = conjsrc ? conj : identity
471490
# one-tree blocks are a scaled permutation, which the unique kernel already handles; the
472491
# two kernels touch disjoint subblocks so the launch order does not matter

0 commit comments

Comments
 (0)