Skip to content

Prepare differentiation for the type the caches use - #173

Merged
pkofod merged 2 commits into
masterfrom
pkm/prepare-with-cache-type
Aug 17, 2026
Merged

pkofod merged 2 commits into
masterfrom
pkm/prepare-with-cache-type

Conversation

@pkofod

@pkofod pkofod commented Aug 15, 2026

Copy link
Copy Markdown
Member

Fixes #172.

What was wrong

Differentiation is prepared once, at construction, and then reused for every evaluation. Preparation was seeded with the array the caller passed in, but evaluation uses the x caches, and those are built with similar, which does not always keep the caller's container: a ReinterpretArray comes back as an Array.

DI 0.6 defaulted strict = Val(false) and let the inconsistency through. DI 0.7 flipped the default, and since the compat range here is "0.6.43, 0.7", an ordinary upgrade turned a silent mismatch into a hard error. Nothing in this package changed.

x0 = reinterpret(Float64, [1.0+1.0im])
df = OnceDifferentiable(f!, x0, copy(x0), AutoFiniteDiff())
typeof(x0)        # ReinterpretArray{Float64, 1, ComplexF64, Vector{ComplexF64}, false}
typeof(df.x_f)    # Vector{Float64}
value_jacobian!!(df, copy(df.x_f))   # PreparationMismatchError

The fix

Seed preparation from x_of_values(x_seed), a new sibling of x_of_nans that returns an array with the cache's type carrying the caller's values.

The values are not incidental. DI evaluates the objective while preparing (prepare_gradient_nokwarg runs y = f(x, ...)), so preparing at the NaN-filled cache would call the user's function at NaN during construction, which breaks tape-recording backends, local sparsity detection, and any objective with a domain guard.

Nine sites: gradient and jacobian in OnceDifferentiable, and hessian, hvp and gradient across the three TwiceDifferentiable constructors. The hvp tangent tuple gets it too, since the tangent type is part of the signature DI compares.

Deliberately not addressed

  • The constraint constructors (constraints.jl:141, :176, :188) prepare at a freshly built zeros(T, n) and have no cache to refer to, so they are the mirror image of this bug rather than the same one.
  • The jacobian y slot prepares with F2 = similar(F) while fj! is handed obj.F = copy(F). Same types for ordinary arrays, latent otherwise.

Both are latent and neither has a reproducer, so they are left for a separate change.

One behaviour change worth recording

similar is the whole mechanism, and it only bites for immutable static arrays:

  • an MArray seed gives an MArray cache, so the preparation point is unchanged and behaviour is identical. This is the static-array path Optim supports.
  • an SArray seed gives an MArray cache (asserted at test/utils.jl:13), so preparation moves to MArray while a caller would still pass SArray. SArray plus an autodiff backend would now throw.

Nothing constructs an objective from an SArray in the test suite, and Optim's state needs mutable arrays, so this is theoretical rather than live. Flagging it rather than burying it.

Testing

Full suite green on Julia 1.10 and 1.12: 1632 passing, including Aqua, JET and ExplicitImports.

New regression testset in test/abstractarrays.jl, named after this issue and run against both AutoFiniteDiff(; fdtype = Val(:central)) and AutoForwardDiff(), covering the jacobian, gradient and hessian paths. It uses reinterpret, so it needs no new test dependency. That file was the right home: it is already the array-container file and already asserts on x_f, but all three of its existing testsets supply explicit derivatives, so no exotic container ever reached DI.

test/complex.jl existed but was missing from the include list in runtests.jl, so it had never run. It is wired in here and passes.

Cross-checked downstream against JuliaNLSolvers/NLsolve.jl#299, which carries six @test_broken markers waiting on this. With this branch developed in, all six report Unexpected Pass, which is the signal to convert them back to @test.


This pull request was written with the assistance of generative AI.

🤖 Generated with Claude Code

Differentiation is prepared once, at construction, and reused for every
evaluation. Preparation was seeded with the array the caller passed in,
while evaluation uses the x caches, which are built with `similar` and so
do not always have the caller's container type: a ReinterpretArray comes
back as an Array. DI 0.6 defaulted `strict = Val(false)` and let the
inconsistency pass; 0.7 flipped the default, so every evaluation of such
an objective now throws PreparationMismatchError.

Seed preparation from `x_of_values(x_seed)` instead: an array with the
cache's type carrying the caller's values. The values matter, because
preparation evaluates the objective, so the NaN-filled cache is not a
safe point to prepare at.

Nine sites: gradient and jacobian in OnceDifferentiable, and hessian,
hvp and gradient across the three TwiceDifferentiable constructors. The
hvp tangent tuple needs it too, since the tangent type is part of the
signature DI checks.

Not addressed here: the constraint constructors prepare at a freshly
built `zeros(T, n)` and have no cache to refer to, and the jacobian `y`
slot prepares with `similar(F)` while `fj!` is handed `copy(F)`. Both
are latent and neither has a reproducer.

Fixes #172.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@codecov

codecov Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.47%. Comparing base (29a0327) to head (afc8f26).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #173      +/-   ##
==========================================
+ Coverage   88.41%   88.47%   +0.05%     
==========================================
  Files           9        9              
  Lines         872      876       +4     
==========================================
+ Hits          771      775       +4     
  Misses        101      101              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@devmotion devmotion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks mostly good to me.

The Claude summary was a bit confusing, I'm not sure if I understood it correctly: Are there other instances of this issues? If that's actually the case, then I'd fix them as well right away.

Comment thread src/NLSolversBase.jl Outdated
# of the array the caller handed us: the caches come from `similar`, which can change the container (a
# ReinterpretArray becomes an Array). The caller's values are carried over because preparation evaluates the
# objective, so a cache full of NaNs is not a safe point to prepare at.
x_of_values(x::AbstractArray, ::Type{Tf}=float(eltype(x))) where {Tf} = copyto!(x_of_nans(x, Tf), x)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Seems the second argument is never used anywhere, so it's a bit useless. I think it would be simpler to just remove it.

No call site passes it, and unlike x_of_nans (which alloc_DF calls with
an explicit promote_type) nothing needs the override.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@pkofod
pkofod merged commit 69d0ad2 into master Aug 17, 2026
11 checks passed
@pkofod
pkofod deleted the pkm/prepare-with-cache-type branch August 17, 2026 12:02
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.

OnceDifferentiable prepares DI with x_seed but evaluates with x_of_nans(x_seed), breaking wrapper arrays

2 participants