Skip to content

Commit c8135ee

Browse files
authored
storagetype-adapted treetransformers (#556)
1 parent 7f1234e commit c8135ee

5 files changed

Lines changed: 208 additions & 143 deletions

File tree

‎docs/src/Changelog.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ When releasing a new version, move the "Unreleased" changes to a new version sec
2828

2929
- Extend VectorInterface compat to include v0.7
3030
- Require TensorKitSectors v0.3.10
31+
- `@cached` can be used from other modules, such as package extensions, which then own the cache of the methods they add; these caches are shown with their module in `global_cache_info` after registration in `__init__` (internal)
32+
- The `TreeTransformer`s used in index manipulations are now constructed and cached per storagetype of the destination tensor, which is also a dispatch point for storage-specific transformers with their own cache (internal)
3133

3234
### Deprecated
3335

@@ -39,6 +41,8 @@ When releasing a new version, move the "Unreleased" changes to a new version sec
3941

4042
### Performance
4143

44+
- Recoupling matrices are stored such that they can leverage BLAS, also for mixed complex tensor with real recoupling coefficients.
45+
4246
## [0.17.2](https://github.com/QuantumKitHub/TensorKit.jl/compare/v0.17.1...v0.17.2) - 2026-09-20
4347

4448
### Added

‎ext/TensorKitGPUArraysExt.jl‎

Lines changed: 70 additions & 69 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: 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}}}}
@@ -272,70 +271,66 @@ function DeviceGenericTreeTransformer(
272271
)
273272
end
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))
290281
end
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))
296288
end
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
321306
end
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
335317
end
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
@@ -373,7 +368,9 @@ end
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]
@@ -398,7 +395,9 @@ end
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
449448
end
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

453456
function 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
462464
end
463465

464466
function 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
476477
end
477478

‎src/auxiliary/caches.jl‎

Lines changed: 58 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,37 @@ function _cached_category(fname::Symbol)
5454
"symmetry" : "bookkeeping"
5555
end
5656

57+
# timer sections are controlled by the `timeit_debug_enabled` switch of the module using `@cached`
58+
_timeit_expr(label, ex) =
59+
Expr(:macrocall, GlobalRef(TimerOutputs, Symbol("@timeit_debug")), LineNumberNode(@__LINE__, @__FILE__), GlobalRef(@__MODULE__, :GLOBAL_TIMER), label, ex)
60+
5761
macro cached(ex)
58-
Meta.isexpr(ex, :function) ||
59-
error("cached macro can only be used on function definitions")
62+
return _cached(__module__, ex)
63+
end
64+
65+
function _cached_error(msg, ex)
66+
ex isa Expr && (ex = Base.remove_linenums!(copy(ex)))
67+
Meta.isexpr(ex, :kw) && (ex = Expr(:(=), ex.args...)) # prints as `x = 1`
68+
throw(ArgumentError("@cached: $msg, got `$ex`"))
69+
end
70+
71+
# the arguments form the cache key, so they must be positional; unnamed ones get a name
72+
function _cached_canonicalize_arg(arg)
73+
Meta.isexpr(arg, :parameters) && _cached_error("keyword arguments are not supported", arg)
74+
Meta.isexpr(arg, :kw) && _cached_error("default values are not supported", arg)
75+
Meta.isexpr(arg, :...) && _cached_error("varargs are not supported", arg)
76+
arg isa Symbol && return arg
77+
Meta.isexpr(arg, :(::)) || _cached_error("unsupported argument", arg)
78+
length(arg.args) == 1 && return Expr(:(::), gensym(:arg), arg.args[1])
79+
return arg
80+
end
81+
82+
function _cached(mod::Module, ex)
83+
if !Meta.isexpr(ex, :function)
84+
Meta.isexpr(ex, :(=)) && Meta.isexpr(ex.args[1], (:call, :where, :(::))) &&
85+
_cached_error("short-form function definitions are not supported, use `function ... end`", ex.args[1])
86+
_cached_error("expected a function definition", ex)
87+
end
6088
fcall = ex.args[1]
6189
if Meta.isexpr(fcall, :where)
6290
hasparams = true
@@ -72,24 +100,22 @@ macro cached(ex)
72100
else
73101
typed = false
74102
end
75-
Meta.isexpr(fcall, :call) ||
76-
error("cached macro can only be used on function definitions")
103+
Meta.isexpr(fcall, :call) || _cached_error("expected a function signature", fcall)
77104
fname = fcall.args[1]
105+
# qualified names such as `TensorKit.treebraider` add methods to a function of another module
106+
basename = Meta.isexpr(fname, :.) ? fname.args[end].value : fname
107+
basename isa Symbol ||
108+
_cached_error("expected a function name or a qualified name such as `Module.f`", fname)
109+
fargs = map(_cached_canonicalize_arg, fcall.args[2:end])
110+
fcall = Expr(:call, fname, fargs...)
111+
fargnames = map(arg -> arg isa Symbol ? arg : arg.args[1], fargs)
78112
# timer labels for the cache lookup and the miss-path construction
79-
lookuplabel = string("bookkeeping: cache ", fname)
80-
misslabel = string(_cached_category(fname), ": compute ", fname)
81-
fargs = fcall.args[2:end]
82-
fargnames = map(fargs) do arg
83-
if Meta.isexpr(arg, :(::))
84-
return arg.args[1]
85-
else
86-
return arg
87-
end
88-
end
113+
lookuplabel = string("bookkeeping: cache ", basename)
114+
misslabel = string(_cached_category(basename), ": compute ", basename)
89115
_fbody = ex.args[2]
90116

91117
# actual implenetation, with underscore name
92-
_fname = Symbol(:_, fname)
118+
_fname = Symbol(:_, basename)
93119
_fcall = Expr(:call, _fname, fargs...)
94120
if hasparams
95121
_fcall = Expr(:where, _fcall, params...)
@@ -103,19 +129,19 @@ macro cached(ex)
103129
end
104130
cachestylevar = gensym(:cachestyle)
105131
cachestyleex = Expr(
106-
:(=), cachestylevar, Expr(:call, :CacheStyle, fname, fargnames...)
132+
:(=), cachestylevar, Expr(:call, CacheStyle, fname, fargnames...)
107133
)
108134
newfbody = Expr(
109135
:block, cachestyleex, Expr(:call, fname, fargnames..., cachestylevar)
110136
)
111137
newfex = Expr(:function, newfcall, newfbody)
112138

113139
# nocache implementation
114-
fnocachecall = Expr(:call, fname, fargs..., :(::NoCache))
140+
fnocachecall = Expr(:call, fname, fargs..., :(::$NoCache))
115141
if hasparams
116142
fnocachecall = Expr(:where, fnocachecall, params...)
117143
end
118-
fnocachebody = :(@timeit_debug GLOBAL_TIMER $misslabel $(Expr(:call, _fname, fargnames...)))
144+
fnocachebody = _timeit_expr(misslabel, Expr(:call, _fname, fargnames...))
119145
if typed
120146
T = gensym(:T)
121147
fnocachebody = Expr(:block, Expr(:(=), T, typeex), Expr(:(::), fnocachebody, T))
@@ -124,16 +150,17 @@ macro cached(ex)
124150

125151
# tasklocal cache implementation
126152
Dvar = gensym(:D)
127-
flocalcachecall = Expr(:call, fname, fargs..., :(::TaskLocalCache{$Dvar}))
153+
flocalcachecall = Expr(:call, fname, fargs..., :(::$TaskLocalCache{$Dvar}))
128154
if hasparams
129155
flocalcachecall = Expr(:where, flocalcachecall, params..., Dvar)
130156
else
131157
flocalcachecall = Expr(:where, flocalcachecall, Dvar)
132158
end
133-
localcachename = Symbol(:_tasklocal_, fname, :_cache)
159+
globalcachename = Symbol(:GLOBAL_, uppercase(string(basename)), :_CACHE)
160+
localcachename = Symbol(:_tasklocal_, globalcachename)
134161
cachevar = gensym(:cache)
135162
getlocalcacheex = :(
136-
$cachevar::$Dvar = get!(task_local_storage(), $localcachename) do
163+
$cachevar::$Dvar = get!(task_local_storage(), $(QuoteNode(localcachename))) do
137164
return $Dvar()
138165
end
139166
)
@@ -143,11 +170,8 @@ macro cached(ex)
143170
else
144171
key = Expr(:tuple, fargnames...)
145172
end
146-
getvalex = :(
147-
@timeit_debug GLOBAL_TIMER $lookuplabel get!($cachevar, $key) do
148-
return @timeit_debug GLOBAL_TIMER $misslabel $_fname($(fargnames...))
149-
end
150-
)
173+
missex = _timeit_expr(misslabel, Expr(:call, _fname, fargnames...))
174+
getvalex = _timeit_expr(lookuplabel, :(get!(() -> $missex, $cachevar, $key)))
151175
if typed
152176
T = gensym(:T)
153177
flocalcachebody = Expr(
@@ -168,11 +192,10 @@ macro cached(ex)
168192
flocalcacheex = Expr(:function, flocalcachecall, flocalcachebody)
169193

170194
# # global cache implementation
171-
fglobalcachecall = Expr(:call, fname, fargs..., :(::GlobalLRUCache))
195+
fglobalcachecall = Expr(:call, fname, fargs..., :(::$GlobalLRUCache))
172196
if hasparams
173197
fglobalcachecall = Expr(:where, fglobalcachecall, params...)
174198
end
175-
globalcachename = Symbol(:GLOBAL_, uppercase(string(fname)), :_CACHE)
176199
getglobalcachex = Expr(:(=), cachevar, globalcachename)
177200
if typed
178201
T = gensym(:T)
@@ -194,11 +217,14 @@ macro cached(ex)
194217
fglobalcacheex = Expr(:function, fglobalcachecall, fglobalcachebody)
195218
fglobalcachedef = Expr(
196219
:const,
197-
Expr(:(=), globalcachename, :(LRU{Any, Any}(; maxsize = DEFAULT_GLOBALCACHE_SIZE[])))
198-
)
199-
fglobalcacheregister = Expr(
200-
:call, :push!, :GLOBAL_CACHES, :($(QuoteNode(globalcachename)) => $globalcachename)
220+
Expr(:(=), globalcachename, :($LRU{Any, Any}(; maxsize = $DEFAULT_GLOBALCACHE_SIZE[])))
201221
)
222+
# Other modules register their caches explicitly from `__init__`, since
223+
# mutations of this registry during their precompilation do not survive loading.
224+
fglobalcacheregister = mod === (@__MODULE__) ? Expr(
225+
:call, :push!, GlobalRef(@__MODULE__, :GLOBAL_CACHES),
226+
:($(QuoteNode(globalcachename)) => $globalcachename)
227+
) : nothing
202228

203229
# # total expression
204230
return esc(

0 commit comments

Comments
 (0)