Skip to content

hessian!(::ImmutableDiffResult, f, ::StaticArray) errors when f does not depend on its argument #846

Description

@devmotion

hessian!(::ImmutableDiffResult, f, ::StaticArray) errors outright whenever f returns no Dual of its own tag.

using ForwardDiff, StaticArrays, DiffResults
sx = SVector(1.0, 2.0, 3.0)

# (a) constant `f`
ForwardDiff.hessian!(DiffResults.HessianResult(sx), z -> 2.0, sx)
# ERROR: DimensionMismatch: No precise constructor for SMatrix{3, 3, Float64, 9} found.
#        Size of input was (0, 3).

# (b) `f` constant in `z` but carrying an enclosing tag
ForwardDiff.derivative(1.0) do a
    r = ForwardDiff.hessian!(DiffResults.HessianResult(sx), z -> a * 2.0, sx)
    DiffResults.value(r)
end
# ERROR: MethodError: no method matching extract_jacobian(::Type{Tag{…}}, ::Dual{…}, ::SVector{3, Float64})

Every other path handles both fine — hessian(f, sx), hessian!(::Matrix, f, sx) and hessian(f, ::Vector) all return a 3×3 zero Hessian, and the nested forms of those return 0.0.

Cause

The method extracts with extract_jacobian(T, partials(T, fd2), x), and extract_jacobian(::Type{T}, ydual::Union{StaticArray,Partials}, x) assumes partials(T, fd2) has one entry per input. It does not when f returns no Dual{T}:

  • a constant gives Partials{0}, so the result is built at size (0, N) and the SMatrix constructor rejects it;
  • a Dual{S} with S ≺ T gives zero(d), a bare Dual, which matches no method at all.

Suggested fix

Dispatch on the result rather than on its partials, returning a zero length(x) × length(x) Hessian when there is no differentiated layer to read — a constant f, an empty x, and a result that carries only an enclosing tag all fall under the same rule.

Version: ForwardDiff master (v1.4.5), Julia 1.12.7, StaticArrays 1.9.19.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions