jacobian(f, x) silently returns zeros if f is complex-valued

未关闭
#830 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
75/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
冷清
技术栈
julia
领域
tooling

调研方向

首先阅读 extract_jacobian!、extract_jacobian_chunk!、extract_derivative 和 valtype,重点关注 Complex{Dual} 值的处理方式。使用 issue 中的复现器测试 vector mode、chunk mode 和 jacobian!。完成的标准是:复值函数生成正确的 ComplexF64 Jacobian,同时实值路径保持不变。

由索引模型根据 Issue 内容生成。

描述

jacobian returns zeros, with Duals leaked into the eltype, instead of the Jacobian or an error:

julia> g(x) = [cis(x[1])*x[2], x[1] + 2im*x[2]];

julia> J = ForwardDiff.jacobian(g, [0.5, 1.0]);

julia> eltype(J)
Complex{ForwardDiff.Dual{ForwardDiff.Tag{typeof(g), Float64}, Float64, 2}}

julia> all(iszero, J)
true

extract_jacobian! extracts with partials(T, ydual, i), which for a Complex{Dual} hits the partials(x, i...) = zero(x) fallback. derivative(f, x) is fine since it goes through extract_derivative, which handles Complex{<:Dual}.

extract_derivative cannot be reused directly because it hardcodes the partial index, while the Jacobian needs index i. But generalising it to an index is enough, and keeps the knowledge of how a complex number carries derivative information in one place:

@inline extract_partial(::Type{T}, y::Real, i) where {T} = zero(y)
@inline extract_partial(::Type{T}, y::Complex, i) where {T} = zero(y)
@inline extract_partial(::Type{T}, y::Dual, i) where {T} = partials(T, y, i)
@inline extract_partial(::Type{T}, y::Complex{<:Dual}, i) where {T} =
    complex(partials(T, real(y), i), partials(T, imag(y), i))

extract_jacobian!/extract_jacobian_chunk! then use extract_partial(T, ·, i) instead of partials(T, ·, i), and the scalar extract_derivative methods become the i = 1 case.

One more piece is needed for the result eltype, since jacobian allocates similar(ydual, valtype(T, eltype(ydual)), ...):

@inline valtype(::Type{T}, ::Type{Complex{D}}) where {T,D} = Complex{valtype(T, D)}

With those, vector mode, chunk mode and jacobian! all give the correct ComplexF64 Jacobian and the real paths are unchanged.

If we would rather not support complex-valued f here, it should at least throw rather than return zeros.

主要语言
Julia
星标
1k
派生
165
平均合并
8 天 22 小时
30 天内合并 PR
3

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

JuliaDiff/ForwardDiff.jl 的其他 Issue

查看 JuliaDiff/ForwardDiff.jl 的全部 Issue

相似的 Issue

更多 Julia Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。