Skip to content

Commit 46980a6

Browse files
lkdvosclaude
andcommitted
Replace TensorKit cache machinery with Cached.jl
Track Cached.jl main through Pkg sources and delegate cache storage, container selection, and module-wide inspection and clearing to Cached. Preserve the registry for the existing GPU transformer cache and use Cached.LRU for its container. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a2496d4 commit 46980a6

10 files changed

Lines changed: 30 additions & 193 deletions

File tree

‎Project.toml‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ projects = ["test", "docs"]
88

99
[deps]
1010
Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
11+
Cached = "1b238080-9255-4fe9-b224-89eb24efe93b"
1112
Dictionaries = "85a47980-9c8c-11e8-2b9f-f7ca1fa99fb4"
12-
LRUCache = "8ac3fa9e-de4c-5943-b1dc-09c6b5f20637"
1313
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
1414
MatrixAlgebraKit = "6c742aac-3347-4629-af66-fc926824e5e4"
1515
OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5"
@@ -45,17 +45,20 @@ TensorKitFiniteDifferencesExt = "FiniteDifferences"
4545
TensorKitGPUArraysExt = "GPUArrays"
4646
TensorKitMooncakeExt = "Mooncake"
4747

48+
[sources]
49+
Cached = {url = "https://github.com/lkdvos/Cached.jl.git", rev = "main"}
50+
4851
[compat]
4952
AMDGPU = "2"
5053
Adapt = "4"
54+
Cached = "0.1"
5155
CUDA = "6"
5256
ChainRulesCore = "1"
5357
Dictionaries = "0.4"
5458
Enzyme = "0.13.207"
5559
EnzymeTestUtils = "0.2.8"
5660
FiniteDifferences = "0.12"
5761
GPUArrays = "11.4.1"
58-
LRUCache = "1.6"
5962
LinearAlgebra = "1"
6063
MatrixAlgebraKit = "0.6.9"
6164
Mooncake = "0.5.27"

‎docs/src/man/fusiontrees.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ This is simply given by
260260

261261
The `braid` and `permute` routines for double fusion trees will be the main access point for corresponding manipulations on tensors.
262262
As a consequence, results from these routines are memoized via a `@cached` mechanism.
263-
The caching strategy is controlled by `CacheStyle`: for `FusionStyle(I) isa UniqueFusion` no caching is used (`NoCache()`), since the result is a single cheap scalar coefficient; for `MultipleFusion` or `GenericFusion` sectors, a global LRU cache (`GlobalLRUCache()`) is used, as computing the transformation matrix can be expensive and results are reused frequently.
263+
The caching strategy is controlled by `Cached.CacheStyle`: for `FusionStyle(I) isa UniqueFusion` no caching is used (`NoCache()`), since the result is a single cheap scalar coefficient; for `MultipleFusion` or `GenericFusion` sectors, `GlobalCache()` uses Cached.jl's configured container (ClockCache by default), as computing the transformation matrix can be expensive and results are reused frequently.
264264

265265
This caching implies that potential inefficiencies in the fusion tree manipulations (which we nonetheless try to avoid) will not seriously affect performance of tensor manipulations.
266266

‎ext/TensorKitEnzymeExt/utility.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ pullback_dC!(ΔC, β::Number) = scale!(ΔC, conj(β))
2626
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.GenericTreeTransformer}) = true
2727
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.UniqueTreeTransformer}) = true
2828
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.VectorSpace}) = true
29-
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.LRU}) = true
29+
@inline EnzymeRules.inactive_type(::Type{<:TensorKit.Cached.AbstractCache}) = true
3030

3131
function EnzymeRules.augmented_primal(
3232
config::EnzymeRules.RevConfigWidth{1},

‎ext/TensorKitGPUArraysExt.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ using GPUArrays
44
using GPUArrays: @allowscalar
55
using GPUArrays.KernelAbstractions: @kernel, @index, get_backend
66
using Adapt
7-
using TensorKit.LRUCache: LRU
7+
using TensorKit: LRU
88
using TensorKit.TupleTools
99
using Strided: StridedViews
1010
using MatrixAlgebraKit, Adapt

‎src/TensorKit.jl‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,6 @@ const TO = TensorOperations
119119
using MatrixAlgebraKit
120120

121121
using Dictionaries: Dictionaries, Dictionary, Indices, gettoken, gettokenvalue
122-
using LRUCache
123122
using OhMyThreads
124123
using ScopedValues
125124
using TimerOutputs: TimerOutputs, TimerOutput, @timeit_debug

‎src/auxiliary/caches.jl‎

Lines changed: 19 additions & 178 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,25 @@
1+
# Caching of the fusion tree manipulations and tensor structures is provided by Cached.jl.
2+
# `CacheStyle` is imported (not just used) so that the `CacheStyle(::typeof(f), ...)`
3+
# specializations in TensorKit, and those of users, extend `Cached.CacheStyle`.
4+
import Cached: CacheStyle
5+
using Cached: Cached, @cached, NoCache, GlobalCache, LRU
6+
17
"""
28
const GLOBAL_CACHES
39
4-
Registry of the global caches TensorKit maintains, as `name => cache` pairs.
5-
6-
See also [`empty_globalcaches!`](@ref) and [`global_cache_info`](@ref).
10+
Registry of additional global caches, which are not managed by `@cached` (e.g. by
11+
extensions), as `name => cache` pairs. They are emptied by [`empty_globalcaches!`](@ref)
12+
and listed by [`global_cache_info`](@ref), together with the caches of TensorKit's cached
13+
functions.
714
"""
815
const GLOBAL_CACHES = Pair{Symbol, Any}[]
916

17+
const DEFAULT_GLOBALCACHE_SIZE = Ref(10^4)
18+
1019
"""
1120
empty_globalcaches!()
1221
13-
Empty every global cache in [`GLOBAL_CACHES`](@ref).
22+
Empty the global caches of TensorKit.
1423
These mostly contain bookkeeping for various different index manipulations and tensor structures,
1524
so clearing this out can free up some memory whenever you have a workflow that involves a large variety of structures.
1625
For example, you may want to clear the cache when working with different symmetries, or in algorithms that dynamically alter the sizes of tensors.
@@ -19,192 +28,24 @@ Since everything is recomputed on demand, this is purely a memory measure.
1928
See also [`global_cache_info`](@ref) to display the status.
2029
"""
2130
function empty_globalcaches!()
31+
Cached.empty_caches!(TensorKit)
2232
foreach(empty! ∘ last, GLOBAL_CACHES)
2333
return nothing
2434
end
2535

2636
"""
2737
global_cache_info([io::IO = stdout])
2838
29-
Print the hit/miss statistics and current size of every global cache in [`GLOBAL_CACHES`](@ref).
39+
Print the hit/miss statistics and current size of every global cache of TensorKit.
3040
3141
See also [`empty_globalcaches!`](@ref).
3242
"""
3343
function global_cache_info(io::IO = stdout)
44+
for (f, cache) in Cached.cache_info(TensorKit)
45+
println(io, nameof(f), ":\t", cache)
46+
end
3447
for (name, cache) in GLOBAL_CACHES
35-
println(io, name, ":\t", LRUCache.cache_info(cache))
48+
println(io, name, ":\t", cache)
3649
end
3750
return
3851
end
39-
40-
abstract type CacheStyle end
41-
struct NoCache <: CacheStyle end
42-
struct TaskLocalCache{D <: AbstractDict} <: CacheStyle end
43-
struct GlobalLRUCache <: CacheStyle end
44-
45-
const DEFAULT_GLOBALCACHE_SIZE = Ref(10^4)
46-
47-
function CacheStyle(args...)
48-
return GlobalLRUCache()
49-
end
50-
51-
# category of the miss-path (construction) timer section of an `@cached` function
52-
function _cached_category(fname::Symbol)
53-
return fname in (:fsbraid, :fstranspose, :treebraider, :treetransposer) ?
54-
"symmetry" : "bookkeeping"
55-
end
56-
57-
macro cached(ex)
58-
Meta.isexpr(ex, :function) ||
59-
error("cached macro can only be used on function definitions")
60-
fcall = ex.args[1]
61-
if Meta.isexpr(fcall, :where)
62-
hasparams = true
63-
params = fcall.args[2:end]
64-
fcall = fcall.args[1]
65-
else
66-
hasparams = false
67-
end
68-
if Meta.isexpr(fcall, :(::))
69-
typed = true
70-
typeex = fcall.args[2]
71-
fcall = fcall.args[1]
72-
else
73-
typed = false
74-
end
75-
Meta.isexpr(fcall, :call) ||
76-
error("cached macro can only be used on function definitions")
77-
fname = fcall.args[1]
78-
# 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
89-
_fbody = ex.args[2]
90-
91-
# actual implenetation, with underscore name
92-
_fname = Symbol(:_, fname)
93-
_fcall = Expr(:call, _fname, fargs...)
94-
if hasparams
95-
_fcall = Expr(:where, _fcall, params...)
96-
end
97-
_fex = Expr(:function, _fcall, _fbody)
98-
99-
# implementation that chooses the cache style
100-
newfcall = fcall
101-
if hasparams
102-
newfcall = Expr(:where, newfcall, params...)
103-
end
104-
cachestylevar = gensym(:cachestyle)
105-
cachestyleex = Expr(
106-
:(=), cachestylevar, Expr(:call, :CacheStyle, fname, fargnames...)
107-
)
108-
newfbody = Expr(
109-
:block, cachestyleex, Expr(:call, fname, fargnames..., cachestylevar)
110-
)
111-
newfex = Expr(:function, newfcall, newfbody)
112-
113-
# nocache implementation
114-
fnocachecall = Expr(:call, fname, fargs..., :(::NoCache))
115-
if hasparams
116-
fnocachecall = Expr(:where, fnocachecall, params...)
117-
end
118-
fnocachebody = :(@timeit_debug GLOBAL_TIMER $misslabel $(Expr(:call, _fname, fargnames...)))
119-
if typed
120-
T = gensym(:T)
121-
fnocachebody = Expr(:block, Expr(:(=), T, typeex), Expr(:(::), fnocachebody, T))
122-
end
123-
fnocacheex = Expr(:function, fnocachecall, fnocachebody)
124-
125-
# tasklocal cache implementation
126-
Dvar = gensym(:D)
127-
flocalcachecall = Expr(:call, fname, fargs..., :(::TaskLocalCache{$Dvar}))
128-
if hasparams
129-
flocalcachecall = Expr(:where, flocalcachecall, params..., Dvar)
130-
else
131-
flocalcachecall = Expr(:where, flocalcachecall, Dvar)
132-
end
133-
localcachename = Symbol(:_tasklocal_, fname, :_cache)
134-
cachevar = gensym(:cache)
135-
getlocalcacheex = :(
136-
$cachevar::$Dvar = get!(task_local_storage(), $localcachename) do
137-
return $Dvar()
138-
end
139-
)
140-
valvar = gensym(:val)
141-
if length(fargnames) == 1
142-
key = fargnames[1]
143-
else
144-
key = Expr(:tuple, fargnames...)
145-
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-
)
151-
if typed
152-
T = gensym(:T)
153-
flocalcachebody = Expr(
154-
:block,
155-
getlocalcacheex,
156-
Expr(:(=), T, typeex),
157-
Expr(:(=), Expr(:(::), valvar, T), getvalex),
158-
Expr(:return, valvar)
159-
)
160-
else
161-
flocalcachebody = Expr(
162-
:block,
163-
getlocalcacheex,
164-
Expr(:(=), valvar, getvalex),
165-
Expr(:return, valvar)
166-
)
167-
end
168-
flocalcacheex = Expr(:function, flocalcachecall, flocalcachebody)
169-
170-
# # global cache implementation
171-
fglobalcachecall = Expr(:call, fname, fargs..., :(::GlobalLRUCache))
172-
if hasparams
173-
fglobalcachecall = Expr(:where, fglobalcachecall, params...)
174-
end
175-
globalcachename = Symbol(:GLOBAL_, uppercase(string(fname)), :_CACHE)
176-
getglobalcachex = Expr(:(=), cachevar, globalcachename)
177-
if typed
178-
T = gensym(:T)
179-
fglobalcachebody = Expr(
180-
:block,
181-
getglobalcachex,
182-
Expr(:(=), T, typeex),
183-
Expr(:(=), Expr(:(::), valvar, T), getvalex),
184-
Expr(:return, valvar)
185-
)
186-
else
187-
fglobalcachebody = Expr(
188-
:block,
189-
getglobalcachex,
190-
Expr(:(=), valvar, getvalex),
191-
Expr(:return, valvar)
192-
)
193-
end
194-
fglobalcacheex = Expr(:function, fglobalcachecall, fglobalcachebody)
195-
fglobalcachedef = Expr(
196-
:const,
197-
Expr(:(=), globalcachename, :(LRU{Any, Any}(; maxsize = DEFAULT_GLOBALCACHE_SIZE[])))
198-
)
199-
fglobalcacheregister = Expr(
200-
:call, :push!, :GLOBAL_CACHES, :($(QuoteNode(globalcachename)) => $globalcachename)
201-
)
202-
203-
# # total expression
204-
return esc(
205-
Expr(
206-
:block, _fex, newfex, fnocacheex, flocalcacheex,
207-
fglobalcachedef, fglobalcacheregister, fglobalcacheex
208-
)
209-
)
210-
end

‎src/fusiontrees/braiding_manipulations.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,7 @@ end
340340
end
341341

342342
CacheStyle(::typeof(fsbraid), k::Union{FSPBraidKey{I}, FSBBraidKey{I}}) where {I} =
343-
FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalLRUCache()
343+
FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache()
344344

345345
"""
346346
permute((f₁, f₂)::FusionTreePair, (p1, p2)::Index2Tuple)

‎src/fusiontrees/duality_manipulations.jl‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -568,9 +568,9 @@ end
568568
end
569569

570570
CacheStyle(::typeof(fstranspose), k::FSPTransposeKey{I}) where {I} =
571-
FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalLRUCache()
571+
FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache()
572572
CacheStyle(::typeof(fstranspose), k::FSBTransposeKey{I}) where {I} =
573-
FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalLRUCache()
573+
FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache()
574574

575575
# COMPOSITE DUALITY MANIPULATIONS PART 2: Planar traces
576576
#-------------------------------------------------------------------

‎src/spaces/structure.jl‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,6 @@ sectorstructure(W::HomSpace) = sectorstructure(Hashed(W, sectorhash, sectorequal
7171
return SectorStructure{I, F}(Indices(bs), Indices(trees))
7272
end
7373

74-
CacheStyle(::typeof(sectorstructure), ::Hashed{<:HomSpace}) = GlobalLRUCache()
75-
7674
# DegeneracyStructure: degeneracy-dependent characterization of HomSpaces
7775
# -----------------------------------------------------------------------
7876
"""
@@ -194,5 +192,3 @@ function _subblock_strides(subsz, sz, str)
194192
throw(ArgumentError("unexpected error in computing subblock strides"))
195193
return strides
196194
end
197-
198-
CacheStyle(::typeof(degeneracystructure), ::HomSpace) = GlobalLRUCache()

‎src/tensors/treetransformers.jl‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,8 +189,6 @@ end
189189
return TreeTransformer(fusiontreetransform, p, Vdst, Vsrc, conjsrc)
190190
end
191191

192-
# default cachestyle is GlobalLRUCache
193-
194192
# For CPU arrays the recoupling matrix can be used as is, also when the scalar types
195193
# do not match, since Strided handles mixed-eltype mul! without the copy that
196194
# Adapt.adapt would make (which additionally dispatches dynamically). Other storage

0 commit comments

Comments
 (0)