Repository navigation
Prepare differentiation for the type the caches use - #173
Merged
Merged
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
devmotion
reviewed
Aug 17, 2026
devmotion
left a comment
Contributor
There was a problem hiding this comment.
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.
| # 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) |
Contributor
There was a problem hiding this comment.
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
xcaches, and those are built withsimilar, which does not always keep the caller's container: aReinterpretArraycomes back as anArray.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.The fix
Seed preparation from
x_of_values(x_seed), a new sibling ofx_of_nansthat 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_nokwargrunsy = 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 threeTwiceDifferentiableconstructors. The hvp tangent tuple gets it too, since the tangent type is part of the signature DI compares.Deliberately not addressed
constraints.jl:141,:176,:188) prepare at a freshly builtzeros(T, n)and have no cache to refer to, so they are the mirror image of this bug rather than the same one.yslot prepares withF2 = similar(F)whilefj!is handedobj.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
similaris the whole mechanism, and it only bites for immutable static arrays:MArrayseed gives anMArraycache, so the preparation point is unchanged and behaviour is identical. This is the static-array path Optim supports.SArrayseed gives anMArraycache (asserted attest/utils.jl:13), so preparation moves toMArraywhile a caller would still passSArray.SArrayplus an autodiff backend would now throw.Nothing constructs an objective from an
SArrayin 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 bothAutoFiniteDiff(; fdtype = Val(:central))andAutoForwardDiff(), covering the jacobian, gradient and hessian paths. It usesreinterpret, so it needs no new test dependency. That file was the right home: it is already the array-container file and already asserts onx_f, but all three of its existing testsets supply explicit derivatives, so no exotic container ever reached DI.test/complex.jlexisted but was missing from the include list inruntests.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_brokenmarkers waiting on this. With this branch developed in, all six reportUnexpected 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