Visualizing Gradients
intermediate/visualizing_gradients_tutorial
nn
.
Sigmoid
())
class
Net
(
):
"""Define a network that has num_layers of linear->norm->sigmoid transformations"""
def
__init__
(
self
,
in_size
=
28
*
28
,
hidden_size
=
128
,
out_size
=
10
,
num_layers
=
3
,
batchnorm
=
False
):
super
()
.
__init__
()
if
batchnorm
is
False
:
norm_layer
=
else
:
norm_layer
=
layers
=
[]
layers
.
append
(
fc_layer
(
in_size
,
hidden_size
,
norm_layer
))
for
i
in
range
(
num_layers
-
1
):
layers
.
append
(
fc_layer
(
hidden_size
,
hidden_size
,
norm_layer
))
layers
.
append
(
(
hidden_size
,
out_size
))
self
.
layers
=
(
*
layers
)
def
forward
(
self
,
):
=
(
,
1
)
return
self
.
layers
(
)
model_bn
=
(
batchnorm
=
True
,
num_layers
=
3
)
model_nobn
=
(
batchnorm
=
False
,
num_layers
=
3
)
()
()
=
(
(),
lr
=
0.01
,
momentum
=
0.9
)
=
(
(),
lr
=
0.01
,
momentum
=
0.9
)
hook_backward
(
module_name
,
grads
):
def
hook
(
grad
):
"""Backward pass hook which appends gradients"""
grads
.
append
((
module_name
,
grad
))
return
hook
def
get_all_layers
(
model
,
hook_forward
,
hook_backward
):
"""Register forward pass hook (which registers a backward hook) to model outputs
Returns:
- layers: a dict with keys as layer/module and values as layer/module names
e.g. layers[nn.Conv2d] = layer1.0.conv1
- grads: a list of tuples with module name and tensor output gradient
e.g. grads[0] == (layer1.0.conv1, tensor.Torch(...))
"""
layers
=
dict
()
grads
=
[]
for
name
,
layer
in
model
.
named_modules
():
if
any
(
layer
.
children
())
is
False
:
layers
[
layer
]
=
name
layer
.
register_forward_hook
(
hook_forward
(
name
,
grads
,
hook_backward
))
return
layers
,
grads
layers_bn
,
grads_bn
=
get_all_layers
(
model_bn
,
hook_forward
,
hook_backward
)
layers_nobn
,
grads_nobn
=
get_all_layers
(
model_nobn
,
hook_forward
,
hook_backward
)
()
.
mean
()
avg_grads
.
append
(
avg_grad
)
layer_idx
.
append
(
len
(
grads
)
-
1
-
idx
)
return
layer_idx
,
avg_grads
layer_idx_bn
,
avg_grads_bn
=
get_grads
(
grads_bn
)
layer_idx_nobn
,
avg_grads_nobn
=
get_grads
(
grads_nobn
)
marker
=
"x"
)
ax
.
set_xlabel
(
"Layer depth"
)
ax
.
set_ylabel
(
"Average gradient"
)
ax
.
set_title
(
"Gradient flow"
)
ax
.
grid
(
True
)
ax
.
legend
()
plt
.
show
()