Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map and broadcast on LSTM layers give different gradients #1324

Closed
maetshju opened this issue Aug 30, 2020 · 1 comment
Closed

Map and broadcast on LSTM layers give different gradients #1324

maetshju opened this issue Aug 30, 2020 · 1 comment

Comments

@maetshju
Copy link
Contributor

While I was working on creating some samples for #1287, I noticed that the gradients coming back to LSTM layers are different when the LSTM layer is broadcast vs. the map function is used. I suspect that it is the gradients from broadcasting that are incorrect because the nets I'm working on struggle to optimize the loss when broadcasting and seem to optimize the loss fine when using map.

This is a minimal working example comparing the gradients from using map with the gradients from dot broadcasting:

using Flux
using Flux: mse
using Zygote: gradient
using Statistics
using Random

Random.seed!(20)

x = [rand(4) for x in 1:3]
y = [rand(4) for x in 1:3]

forward = LSTM(4, 4)

m1(x) = forward.(x)
m2(x) = map(forward, x) |> collect

loss1(x, y) = begin Flux.reset!(forward); sum(mse.(m1(x), y)) end
loss2(x, y) = begin Flux.reset!(forward); sum(mse.(m2(x), y)) end

ps = params(forward)

g1 = gradient(ps) do
  loss1(x, y)
end

g2 = gradient(ps) do 
  loss2(x, y)
end

for (i, p) in enumerate(ps)
  diff = g1[p] .- g2[p]
  abs_diff = abs.(diff)

  max_vals = maximum.(zip(g1[p], g2[p]))
  rel_diff = abs.(diff ./ max_vals)

  println("param $i mean abs diff: ", mean(abs_diff))
  println("param $i mean rel diff: ", mean(rel_diff))
  println()
end

which gives me the results

param 1 mean abs diff: 0.008737461794316823
param 1 mean rel diff: 0.41276081573440826

param 2 mean abs diff: 0.0010637529608087419
param 2 mean rel diff: 0.4532311729338062

param 3 mean abs diff: 0.01340231641668706
param 3 mean rel diff: 0.27217502820508244

param 4 mean abs diff: 0.024221922410463972
param 4 mean rel diff: 1.2236773487876056

param 5 mean abs diff: 0.07576487501903266
param 5 mean rel diff: 6.1682256880252115

This is with Julia 1.4.1, Flux 0.11.0, and Zygote 0.5.4. I get the same results with Julia 1.5.1, Flux 0.11.1, and Zygote 0.5.5.

@maetshju
Copy link
Contributor Author

Okay, it looks like this may be related to #1209. I missed it when I was first looking through the issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant