Skip to content

Instantly share code, notes, and snippets.

@HamletWantToCode
Created December 19, 2019 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HamletWantToCode/46d9a3d6588121a9db9d2404b44cde5e to your computer and use it in GitHub Desktop.
Save HamletWantToCode/46d9a3d6588121a9db9d2404b44cde5e to your computer and use it in GitHub Desktop.
Nested AD #Zygote #ForwardDiff
using Zygote
using Flux
x0 = rand(2)
dz0 = rand(2) # test data
model = Chain(Dense(2, 5, relu), Dense(5, 1)) |> f64
f(x) = model(x)
df(x) = gradient(z->f(z)[1], x)[1]
df(x0) # works :)
## or use forward_jacobian
# df(x) = Zygote.forward_jacobian(f, x)[2]
# df(x0) # works :)
p = params(model)
loss(x,y) = sum(df(x) .- y) # some loss function
loss(x0, dz0)
gradient(()->loss(x0, dz0), p) # ERROR: Mutating arrays is not supported :( I don't know the reason here
# gradient(()->loss(x0, dz0), p) # ERROR: Mutating arrays is not supported :(
# I think this is because forward_jacobian will need to change dtype of x to Dual !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment