Skip to content

Keep persistent, concretely typed workspaces for sparsity tracer types - #198

Merged
ChrisRackauckas merged 3 commits into
SciML:masterfrom
SebastianM-C:smc/sct-typed-buffers
Aug 12, 2026
Merged

ChrisRackauckas merged 3 commits into
SciML:masterfrom
SebastianM-C:smc/sct-typed-buffers

Conversation

@SebastianM-C

Copy link
Copy Markdown
Member

Problem

For sparsity tracer element types, get_tmp allocated a fresh similar(dc.du, T) on every call. That breaks the invariant every other get_tmp path upholds: repeated fetches from the same DiffCache return 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: UndefRefError for reference-carrying tracers, or a segfault in BitSet union for the inline-stored duals during sparsity detection (see #197 for the MWE).

The obvious fix — reusing the any_du fallback storage — restores persistence but degrades the eltype to Vector{Any}, which test/sparse_connectivity_tracer.jl deliberately guards against (one(eltype(c))-style caller code needs a concrete eltype). Both contracts are real; this PR satisfies both.

Design

Following the LazyBufferCache pattern: DiffCache gets a typed_du::Dict{DataType, Any} field holding one lazily allocated, persistent buffer per element type that can reuse neither du nor dual_du. The SCT extension's get_tmp becomes a get! into that table, type-asserted the same way LazyBufferCache.get_tmp asserts its untyped-dict lookup (via a Base.@assume_effects :removable type 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 if du was resized behind the cache's back.
  • A backward-compatible 4-positional-arg DiffCache constructor is kept, so Base.zero/Base.copy and any external positional construction keep working unchanged.

Tests

  • New regression testset for get_tmp allocates fresh storage per call for sparsity tracer types, breaking the shared-storage contract #197: the write-through-one-fetch/read-through-another pattern under TracerSparsityDetector and TracerLocalSparsityDetector (must yield the all-ones pattern), a Base.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 across resize!.
  • The pre-existing concrete-eltype guards (one(eltype(c)) under @inferred) still pass.
  • Full test suite is green locally.

Fixes #197

🤖 Generated with Claude Code

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 MethodError

so 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.)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
Comment thread src/PreallocationTools.jl Outdated
Comment on lines +820 to +822
# 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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread test/sparse_connectivity_tracer.jl Outdated
Comment on lines +115 to +118
# 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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@SebastianM-C
SebastianM-C force-pushed the smc/sct-typed-buffers branch from 34c7701 to 21ae435 Compare August 11, 2026 07:49
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review August 12, 2026 21:30
@ChrisRackauckas
ChrisRackauckas merged commit a032da6 into SciML:master Aug 12, 2026
16 of 17 checks passed
@SebastianM-C
SebastianM-C deleted the smc/sct-typed-buffers branch August 13, 2026 08:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

get_tmp allocates fresh storage per call for sparsity tracer types, breaking the shared-storage contract

2 participants