Hello,
i was wondering, whether it is possible to code some kind of cache pool, where i can request cache arrays of various types. Each type of cache array should be only created once. I’ve tried
# cache arbitrary arrays of dim N
struct CachePool{N}
caches::Dict{Tuple{DataType, NTuple{N, Int}}, AbstractArray}
CachePool(N) = new{N}(Dict{Tuple{DataType, NTuple{N,Int}}, AbstractArray}())
end
# request a cache of specific type and size
# allocate new cache if there is none yet
function getcache(c::CachePool, T, size...)::T
key = (T, size)
if haskey(c.caches, key)
cache = c.caches[key]::T
else
cache = T(undef, size...)
c.caches[key] = cache
end
return cache
end
pool = CachePool(2)
@code_warntype getcache(pool, Matrix{Int}, 3, 1_000)
but (kinda as expected) the c.caches[key]
is not typestable.
For some context here is the problem i’m trying to solve (maybe there is a much better solution?).
I have a function for differential equations which needs a cache.
struct ODEFun{T}
_cache::T
end
function (ode::ODEFun)(du, u, p, t)
f!(ode._cache, u, ...) # update cache with expensive calculations
g!(du, ode._cache, ...) # update du with cache
end
This works fine for explicit solvers. However for implicit solvers the types of du
and u
change to some AD types. I’d love to have a generic version
struct ODEFun{T}
_cachepool::T
end
function (ode::ODEFun)(du::T, u::T, p, t) where {T}
cache = getcache(ode._cachepool, T)
f!(cache, u, ...) # update cache with expensive calculations
g!(du, cache, ...) # update du with cache
end
which would work for different AD types as well as CuArrays for example.
Any ideas?