Repository navigation
Keep persistent, concretely typed workspaces for sparsity tracer types - #198
Conversation
get_tmp allocated a fresh similar(dc.du, T) on every call for tracer types, breaking the contract that repeated fetches from one DiffCache share storage: callers that write through one fetch and read through another (e.g. the collocation loops in BoundaryValueDiffEq) observed unwritten memory, which errored or segfaulted during sparsity detection. Reusing the any_du fallback storage would restore persistence but degrade the eltype to Any, which the extension deliberately avoids (one(eltype(c))-style caller code requires a concrete eltype, and the testsuite guards this). Instead, give DiffCache a typed_du table of lazily allocated persistent buffers keyed by element type, mirroring how LazyBufferCache keeps one persistent buffer per (type, size). The buffers track resize!(cache, n) like the other workspaces. Fixes SciML#197 Co-Authored-By: Claude Fable 5 <[email protected]>
| # to save memory in the long run since we do not need to store an additional | ||
| # cache for the sparsity detection that would be used only once but carried | ||
| # around forever. | ||
| return similar(dc.du, T) |
There was a problem hiding this comment.
Is there a reason to not just make this dc.any_du? Are these other types bitstypes? I can see a reason to have a dictionary for alternative bitstypes, but most tracers I can think of are non-bitstypes, or at least they used to not be.
There was a problem hiding this comment.
Right — the tracers are indeed non-bitstypes (GradientTracer carries a BitSet-backed index set, and SCT's Dual wraps primal + tracer), so the dict isn't there for storage-layout reasons. Routing them to any_du would fix the persistence bug in #197 just as well.
The problem is eltype: any_du is Vector{Any}, so eltype(get_tmp(cache, u)) === Any. Keeping a concrete eltype during tracing is the reason this extension exists in the first place — test/sparse_connectivity_tracer.jl guards exactly this:
c = get_tmp(cache, u)
T = eltype(c) # must not be Any
@. c = u^2 + one(T) # one(Any) throws MethodErrorso switching to any_du trades the #197 segfault for a regression on that contract (any caller doing one(eltype(c))/zero(eltype(c)) on the workspace during sparsity detection breaks, and every element op goes through boxing/dynamic dispatch while tracing).
The dict is the cheapest way I found to satisfy both contracts: it's lazily populated only when sparsity detection actually runs (empty otherwise), and in practice holds 1–3 entries (global tracer, local Dual, hessian variant), each allocated once and reused across the whole detection.
(Answer written with help from Claude Code.)
There was a problem hiding this comment.
Dict{DataType, Any} won't infer the output either though, it just won't be inferred at the array level. So c won't be inferred, but you function barrier in the broadcast to get most of the performance back. However, it seems like, if we want to go this direction, we should treat this as basically a LazyBufferCache kind of thing. If we're doing that, it probably needs to ::T strictly define the return type, like what LazyBufferCache does. But also, at that point we should probably just remove any_du and just put all "extra" forms through this fallback.
There was a problem hiding this comment.
I would be fine with doing the change of removing any_du and ::T on the returns here: it's a strictly better inference solution that is more general than just sparsity tracing. Then we would remove the sparsity tracing then and make any non-dual extension type head down this general path.
Per review: rather than keeping typed_du as a sparsity-tracing special
case beside the Vector{Any} fallback, remove any_du entirely and route
every element type that can reuse neither du nor dual_du through one
lazily allocated, concretely typed, persistent flat buffer per element
type. The get! lookup is type-asserted like LazyBufferCache.get_tmp, so
the returned array keeps its concrete eltype without the caller needing
a function barrier for eltype-dependent code.
With tracers now covered by the generic path, the
SparseConnectivityTracer extension has nothing left to do and is
removed, along with its weakdep (the package stays as a test
dependency). reshape shares the typed workspaces like it shared any_du;
resize!, fill!, zero and copy handle the table analogously to before.
Co-Authored-By: Claude Fable 5 <[email protected]>
| # Typed workspaces are scratch for other element types, which `val` may not | ||
| # convert to; drop them so they are lazily recreated. | ||
| empty!(dc.typed_du) |
There was a problem hiding this comment.
I don't think this is correct. It should probably fill based on matching the eltype/datatype to val. Create a test of this with the sparse connectivity tracer and make sure this choice is right.
| # fill! converts through the workspace eltype: for a tracer, a constant is the | ||
| # empty tracer, so the buffer keeps its concrete eltype and drops all recorded | ||
| # dependencies rather than being invalidated or left stale. | ||
| fill!(cache, 0.0) |
There was a problem hiding this comment.
That's not the test, it should test using fill! inside of the function being differentiated.
Per review: rather than dropping the typed workspaces, fill! converts
val through each workspace eltype — for a sparsity tracer, a constant
is the empty tracer, so the buffer keeps its concrete eltype and drops
all recorded dependencies. Incompatible eltypes throw, matching the
fill!(::AbstractArray{T}, val) contract. Tested against
SparseConnectivityTracer as requested.
Co-Authored-By: Claude Fable 5 <[email protected]>
34c7701 to
21ae435
Compare
Problem
For sparsity tracer element types,
get_tmpallocated a freshsimilar(dc.du, T)on every call. That breaks the invariant every otherget_tmppath upholds: repeated fetches from the sameDiffCachereturn the same storage. Callers routinely write through one fetch and read through another — BoundaryValueDiffEq's collocation does exactly this — so with per-call allocation the reads observe unwritten memory:UndefRefErrorfor reference-carrying tracers, or a segfault inBitSetunion for the inline-stored duals during sparsity detection (see #197 for the MWE).The obvious fix — reusing the
any_dufallback storage — restores persistence but degrades the eltype toVector{Any}, whichtest/sparse_connectivity_tracer.jldeliberately guards against (one(eltype(c))-style caller code needs a concrete eltype). Both contracts are real; this PR satisfies both.Design
Following the
LazyBufferCachepattern:DiffCachegets atyped_du::Dict{DataType, Any}field holding one lazily allocated, persistent buffer per element type that can reuse neitherdunordual_du. The SCT extension'sget_tmpbecomes aget!into that table, type-asserted the same wayLazyBufferCache.get_tmpasserts its untyped-dict lookup (via aBase.@assume_effects :removabletype helper), so the returned array keeps its concrete tracer eltype.resize!(cache, n)resizes the typed workspaces along with the other storage; the extension also self-heals ifduwas resized behind the cache's back.DiffCacheconstructor is kept, soBase.zero/Base.copyand any external positional construction keep working unchanged.Tests
TracerSparsityDetectorandTracerLocalSparsityDetector(must yield the all-ones pattern), aBase.mightalias(get_tmp(cache, T), get_tmp(cache, T))assertion on the tracer type detection actually uses (fails cleanly instead of segfaulting), a concrete-eltype assertion, and buffer behavior acrossresize!.one(eltype(c))under@inferred) still pass.Fixes #197
🤖 Generated with Claude Code