ForwardDiff.jl icon indicating copy to clipboard operation
ForwardDiff.jl copied to clipboard

StackOverflowError with complex `sqrt`

Open fmeirinhos opened this issue 6 years ago • 7 comments

When differentiating over a complex sqrt

x0 = 5 ForwardDiff.derivative(x -> sqrt(1im * x), x0)

a StackOverflowError is encountered.

StackOverflowError: Stacktrace: [1] sqrt(::Complex{ForwardDiff.Dual{ForwardDiff.Tag{##20#21,Int64},Float16,1}}) at ./complex.jl:416 (repeats 80000 times)

The stacktrace points to the following declaration sqrt(z::Complex) = sqrt(float(z))

I have found similar issues #111 #196 #239, but I don't see how I can fix this problem.

fmeirinhos avatar Jun 11 '18 08:06 fmeirinhos

This is basically https://github.com/JuliaLang/julia/issues/26552 I believe.

tkoolen avatar Jul 03 '18 13:07 tkoolen

I'm running into the same issue when trying to get a derivative over a complex sqrt operation. Here I was able to reproduce the error in a simplified way:

> x = ForwardDiff.Dual{Nothing}(1,0.0,0.0,0.0)*im
> sqrt(x)
StackOverflowError:

Stacktrace:
 [1] Type at ./complex.jl:12 [inlined] (repeats 2 times)
 [2] float at ./complex.jl:967 [inlined]
 [3] sqrt(::Complex{ForwardDiff.Dual{Nothing,Float64,3}}) at ./complex.jl:461 (repeats 80000 times)

Has anyone found a solution for this?

EdoAlvarezR avatar Jan 20 '19 02:01 EdoAlvarezR

I too am running into this

chriscoey avatar Apr 19 '19 02:04 chriscoey

This is a problem for me as well. Any ideas about how to deal with this?

adam-coogan avatar Jun 28 '19 12:06 adam-coogan

I run into same error with a just updated Turing/ForwardDiff.

jfmoulin avatar Nov 12 '19 13:11 jfmoulin

See the discussion in https://github.com/JuliaDiff/ForwardDiff.jl/issues/157

andreasnoack avatar Nov 12 '19 13:11 andreasnoack

I am trying this out in julia v1.6 and it's sometimes working okay now. sqrt(::Complex) contains a call to ssqs which has a branch that sometimes fails on Dual: the problematic function is Base.exponent which is not defined for Dual

 function Base.ssqs(x::T, y::T) where T <: ForwardDiff.Dual
           k::Int = 0
           ρ = x*x + y*y
           @show x
           if !isfinite(ρ) && (isinf(x) || isinf(y))
               ρ = convert(T, Inf)
           elseif isinf(ρ) || (ρ==0 && (x!=0 || y!=0)) || ρ<nextfloat(zero(T))/(2*eps(T)^2)
               m::T = max(abs(x), abs(y))
               @show m
               k = m==0 ? m : Base.exponent(m)
               xk, yk = Base.ldexp(x,-k), Base.ldexp(y,-k)
               ρ = xk*xk + yk*yk
           end
           ρ, k
       end

baggepinnen avatar Oct 28 '20 13:10 baggepinnen