Hi everyone
I am new to automatic differentiation. I decided to use Enzyme since I need to handle mutating objects (even if I am not differentiating with respect to these objects).
I try to write a minimal, self-consistent, example:
using Enzyme
mutable struct my_struct
p1::Vector{Float64}
p2::Float64
end
function edit_str!(str::my_struct, x, i)
str.p2 = str.p2 + 2x^2
return nothing
end
function foo(x, str)
edit_str!(str, x, 1)
return str.p2
end
str = my_struct([2.0, 3.0], 1.0)
foo(1.0, str), autodiff(Reverse, foo, Active, Active(1.0), str)
Here I try to differentiate the function foo
in x = 1.0
. Note that the function edit_str!
inside foo
changes the object str
. Yet, I do not need to differentiate with respect to str
.
I found out that, depending on the mutations on str
, the code may or may not work. In the above example it gives the right result 4.0
, but if I change it slightly
function edit_str!(str::my_struct, x, i)
str.p1 = str.p1 .+ 1.0
str.p2 = str.p2 + 2x^2
return nothing
end
it does not work anymore and it gives 0.0
. Note that str.p1
is not needed anywhere. Perhaps even weirder, this works
function edit_str!(str::my_struct, x, i)
str.p1 = 2.0 * str.p1
str.p2 = str.p2 + 2x^2
return nothing
end
I guess it depends on the kind of mutation on the mutable struct
, but I would like to know if there is a robust way of dealing with this.
Thanks a lot.