-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathvisualizing_gradients_tutorial.py
More file actions
295 lines (237 loc) ยท 11.3 KB
/
visualizing_gradients_tutorial.py
File metadata and controls
295 lines (237 loc) ยท 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""
๋ณํ๋ ์๊ฐํ
=====================
**์ ์:** `Justin Silver <https://github.com/j-silv>`__
์ด ํํ ๋ฆฌ์ผ์ ์ ๊ฒฝ๋ง์ ์ด๋ค ๊ณ์ธต์์๋ ๋ณํ๋๋ฅผ ์ถ์ถํ๊ณ ์๊ฐํํ๋ ๋ฐฉ๋ฒ์ ์ค๋ช
ํฉ๋๋ค.
์ด๋ป๊ฒ ์ ๋ณด๊ฐ ๋คํธ์ํฌ์ ๋์์ ์ฐ๋ฆฌ๊ฐ ์ํ๋ ๋งค๊ฐ๋ณ์๊น์ง ํ๋ฅด๋์ง ์ ๊ฒํจ์ผ๋ก์จ
์ฐ๋ฆฌ๋ ํ์ต ์ค ๋ฐ์ํ๋ `๋ณํ๋ ์์ค ๋๋ ํญ๋ฐ <https://arxiv.org/abs/1211.5063>`__๊ณผ ๊ฐ์
๋ฌธ์ ๋ฅผ ๋๋ฒ๊น
ํ ์ ์์ต๋๋ค.
์์ํ๊ธฐ ์ ์ `tensor์ ๊ทธ๊ฒ๋ค์ ์กฐ์ํ๋ ๋ฐฉ๋ฒ
<https://docs.tutorials.pytorch.kr/beginner/basics/tensorqs_tutorial.html>`__์ ํ์คํ ์ดํดํ์ธ์.
๊ธฐ๋ณธ์ ์ธ `autograd ์๋๋ฒ
<https://docs.tutorials.pytorch.kr/beginner/basics/autogradqs_tutorial.html>`__
์ ์์๋๋ ๊ฒ ๋ํ ์ ์ฉํฉ๋๋ค.
"""
######################################################################
# ์ค์
# -----
#
# ์ฐ์ , `ํ์ดํ ์น๊ฐ ์ค์น๋์๋์ง
# <https://pytorch.org/get-started/locally/>`__ ํ์ธํ๊ณ
# ํ์ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค์ importํ์ธ์.
#
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import matplotlib.pyplot as plt
######################################################################
# ๋ค์์ผ๋ก, '๋ฐฐ์น ์ ๊ทํ ๋
ผ๋ฌธ <https://arxiv.org/abs/1502.03167>'__์์
# ์ค๋ช
๋ ์ํคํ
์ฒ์ ์ ์ฌํ, MNIST ๋ฐ์ดํฐ์
์ ์ ํฉํ ๋คํธ์ํฌ๋ฅผ ๊ตฌ์ถํ ๊ฒ์
๋๋ค.
#
#
# ๋ณํ๋ ์๊ฐํ์ ์ค์์ฑ์ ์ค๋ช
ํ๊ธฐ ์ํด, ์ฐ๋ฆฌ๋ ๋ฐฐ์น ์ ๊ทํ๋ฅผ ์ ์ฉํ
# ๋คํธ์ํฌ ๋ฒ์ (BatchNorm)๊ณผ ์ ์ฉํ์ง ์์ ๋ฒ์ ์ ๊ฐ๊ฐ ํ๋์ฉ ์์ฑํ ๊ฒ์
๋๋ค.
# ์ฐ๋ฆฌ๋ ๋ฐฐ์น ์ ๊ทํ๊ฐ `๋ณํ๋ ์์ค/ํญ๋ฐ <https://arxiv.org/abs/1211.5063>`__์
# ํด๊ฒฐํ๋ ๋ฐ ๋งค์ฐ ํจ๊ณผ์ ์ธ ๊ธฐ์ ์์ ์คํ์ ์ผ๋ก ๊ฒ์ฆํ ๊ฒ์
๋๋ค.
#
#
#
# ์ฐ๋ฆฌ๊ฐ ์ฌ์ฉํ๋ ๋ชจ๋ธ์ ``nn.Linear``, ``norm_layer``, ๊ทธ๋ฆฌ๊ณ ``nn.Sigmoid``๋ฅผ
# ๋ฒ๊ฐ์ ์ฌ์ฉํ๋ ๋ณ๊ฒฝ ๊ฐ๋ฅํ ๊ฐ์์, ๋ฐ๋ณต๋๋ ์์ ์ฐ๊ฒฐ(fully-connected) ๊ณ์ธต์ ๊ฐ์ง๊ณ ์์ต๋๋ค.
# `norm_layer`๋ ๋ฐฐ์น ์ ๊ทํ๊ฐ ํ์ฑํ๋ ๊ฒฝ์ฐ์๋
# `BatchNorm1d <https://docs.pytorch.org/docs/stable/generated/torch.nn.BatchNorm1d.html>`__
# ์ ์ฌ์ฉํ๊ณ ๊ทธ๋ ์ง ์์ ๊ฒฝ์ฐ์๋
# `Identity <https://docs.pytorch.org/docs/stable/generated/torch.nn.Identity.html>`__
# ๋ณํ์ ์ฌ์ฉํ ๊ฒ์
๋๋ค.
#
#
def fc_layer(in_size, out_size, norm_layer):
"""Return a stack of linear->norm->sigmoid layers"""
return nn.Sequential(nn.Linear(in_size, out_size), norm_layer(out_size), nn.Sigmoid())
class Net(nn.Module):
"""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 = nn.Identity
else:
norm_layer = nn.BatchNorm1d
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(nn.Linear(hidden_size, out_size))
self.layers = nn.Sequential(*layers)
def forward(self, x):
x = torch.flatten(x, 1)
return self.layers(x)
######################################################################
# ์ด์ ์ฐ๋ฆฌ๋ ๋๋ฏธ ๋ฐ์ดํฐ(dummy data)๋ฅผ ์ค๋นํ์ฌ ๋ ๋ฒ์ ์ ๋ชจ๋ธ์ ์์ฑํ๊ณ
# ์ตํฐ๋ง์ด์ ๋ฅผ ์ด๊ธฐํํฉ๋๋ค.
#
# ๋๋ฏธ ๋ฐ์ดํฐ(dummy data) ์ค์
x = torch.randn(10, 28, 28)
y = torch.randint(10, (10, ))
# ๋ชจ๋ธ ์ด๊ธฐํ
model_bn = Net(batchnorm=True, num_layers=3)
model_nobn = Net(batchnorm=False, num_layers=3)
model_bn.train()
model_nobn.train()
optimizer_bn = optim.SGD(model_bn.parameters(), lr=0.01, momentum=0.9)
optimizer_nobn = optim.SGD(model_nobn.parameters(), lr=0.01, momentum=0.9)
######################################################################
# ์ฐ๋ฆฌ๋ ๋ด๋ถ ๋ ์ด์ด ์ค ํ๋๋ฅผ ์กฐ์ฌํ์ฌ ๋ฐฐ์น ์ ๊ทํ๊ฐ ํ๋์ ๋ชจ๋ธ์๋ง
# ์ ์ฉ๋๋์ง ํ์ธํ ์ ์์ต๋๋ค.
#
print(model_bn.layers[0])
print(model_nobn.layers[0])
######################################################################
# ํ
๋ฑ๋ก
# -----------------
#
######################################################################
# ์ฐ๋ฆฌ๊ฐ ``nn.Module`` ์์ ์๋ ๋ชจ๋ธ์ ๋
ผ๋ฆฌ(logic)์ ์ํ๋ฅผ ๋ํ(wrap up)ํ๊ธฐ ๋๋ฌธ์,
# ๋ชจ๋ ์ฝ๋๋ฅผ ์ง์ ์์ ํ์ง ์๊ณ ์ค๊ฐ ๋ณํ๋์ ์ ๊ทผํ๊ธฐ ์ํด์๋ ์๋ก์ด ๋ฐฉ๋ฒ์ด ํ์ํฉ๋๋ค.
# ์๋ก์ด ๋ฐฉ๋ฒ์ `ํ
๋ฑ๋กํ๊ธฐ <https://docs.pytorch.org/docs/stable/notes/autograd.html#backward-hooks-execution>`__
# ๋ฅผ ํตํด ์ํํ ์ ์์ต๋๋ค.
#
#
# .. ๊ฒฝ๊ณ ::
#
# tensor ์์ฒด์ ``retain_grad()``๋ฅผ ์ฌ์ฉํ๋ ๊ฒ๋ณด๋ค ์ถ๋ ฅ tensor์ ์ฐ๊ฒฐ๋ ์ญ์ ํ ํ
์ ์ฌ์ฉํ๋ ๊ฒ์ด ๊ถ์ฅ๋ฉ๋๋ค. ``nn.Module`` ์ธ์คํด์ค๊ฐ ์ ์๋ฆฌ ์ฐ์ฐ(in-place operation)์ ์ํํ์ง ์๋๋ค๋ฉด ๋ชจ๋ ํ
์ ์ง์ ์ฐ๊ฒฐํ๋ ๋์(์:``register_full_backward_hook()``)๋ ์์ต๋๋ค. ๋ ์์ธํ ์ ๋ณด๋ `์ด ์ด์ <https://github.com/pytorch/pytorch/issues/61519>`__๋ฅผ ์ฐธ๊ณ ํด ์ฃผ์ธ์.
#
# ๋ค์ ์ฝ๋๋ ํ
์ ์ ์ํ๊ณ ๋คํธ์ํฌ ๊ณ์ธต(network layer)์ ๋ํ ๋ฌ์ฌ ๋ช
์นญ(descriptive name)์ ์์งํฉ๋๋ค.
#
#
# ์ธ์๋ฅผ ์ ๋ฌํ ์ ์๋๋ก ํ์ด์ฌ ํด๋ก์ ๋ฅผ ์ํด ๋ํผ ํจ์๊ฐ ์ฌ์ฉ๋๋ค๋ ์ ์ ์ ์ํ์ธ์.
#
def hook_forward(module_name, grads, hook_backward):
def hook(module, args, output):
"""Forward pass hook which attaches backward pass hooks to intermediate tensors"""
output.register_hook(hook_backward(module_name, grads))
return hook
def 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):
"""๋ชจ๋ธ ์ถ๋ ฅ๊ฐ์ ์์ ํ ํ
์ ๋ฑ๋กํ๊ณ , ์ด ํ
๋ด๋ถ์์ ์ญ์ ํ ํ
๋ ๋ฑ๋กํฉ๋๋ค.
๋ฐํ๊ฐ:
- ๊ณ์ธต: ๊ณ์ธต/๋ชจ๋ ๊ฐ์ฒด์ ์ด๋ฆ์ ๊ฐ๊ฐ key์ value๋ก ๊ฐ์ง๋ ๋์
๋๋ฆฌ
e.g. layers[nn.Conv2d] = layer1.0.conv1
- ๋ณํ๋: ๋ชจ๋ ์ด๋ฆ๊ณผ ์ถ๋ ฅ tensor์ ๋ณํ๋๋ก ์ด๋ฃจ์ด์ง ํํ๋ค์ ๋ชฉ๋ก
e.g. grads[0] == (layer1.0.conv1, tensor.Torch(...))
"""
layers = dict()
grads = []
for name, layer in model.named_modules():
# skip Sequential and/or wrapper 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)
######################################################################
# ํ์ต ๋ฐ ์๊ฐ
# --------------------------
#
# ์ด์ ๋ชจ๋ธ์ ๋ช ์ํญ ๋์ ํ์ต์์ผ ๋ณด๊ฒ ์ต๋๋ค:
#
epochs = 10
for epoch in range(epochs):
# ์์ ํ๋ฅผ ์ํํ ๋๋ง๋ค ์ถ๋ ฅ๊ฐ์ ๋ง๋ถ์ผ ๊ฒ์ด๋ฏ๋ก ๋น์ฐ๋ ๊ฒ(clear)์ด ์ค์ํฉ๋๋ค.
#
grads_bn.clear()
grads_nobn.clear()
optimizer_bn.zero_grad()
optimizer_nobn.zero_grad()
y_pred_bn = model_bn(x)
y_pred_nobn = model_nobn(x)
loss_bn = F.cross_entropy(y_pred_bn, y)
loss_nobn = F.cross_entropy(y_pred_nobn, y)
loss_bn.backward()
loss_nobn.backward()
optimizer_bn.step()
optimizer_nobn.step()
######################################################################
# ์๋ฐฉํฅ ๋ฐ ์ญ๋ฐฉํฅ ํจ์ค๋ฅผ ์คํํ ํ, ๋ชจ๋ ์ค๊ฐ tensor์ ๋ํ ๋ณํ๋๋
# ``grads_bn``๊ณผ ``grads_nobn``์ ์กด์ฌํด์ผ ํฉ๋๋ค.
# ๋ ๋ชจ๋ธ์ ๋น๊ตํ ์ ์๋๋ก ๊ฐ ๊ธฐ์ธ๊ธฐ ํ๋ ฌ์ ํ๊ท ์ ๋๊ฐ์ ๊ณ์ฐํฉ๋๋ค.
#
#
def get_grads(grads):
layer_idx = []
avg_grads = []
for idx, (name, grad) in enumerate(grads):
if grad is not None:
avg_grad = grad.abs().mean()
avg_grads.append(avg_grad)
# idx is backwards since we appended in backward pass
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)
######################################################################
# ์ฐ๋ฆฌ๋ ์ด์ ๊ณ์ฐํ ํ๊ท ๋ณํ๋๋ฅผ ๊ทธ๋ํ๋ก ๋ํ๋ด์ด ๋คํธ์ํฌ ๊น์ด์ ๋ฐ๋ผ
# ๊ฐ์ด ์ด๋ป๊ฒ ๋ณํ๋์ง ํ์ธํ ์ ์์ต๋๋ค.
# ์ฐ๋ฆฌ๊ฐ ๋ฐฐ์น ์ ๊ทํ๋ฅผ ์ ์ฉํ์ง ์์ผ๋ฉด ์ค๊ฐ ๊ธฐ์ธ๊ธฐ์ ๋ณํ๋๊ฐ
# ๊ธ๊ฒฉํ๊ฒ 0์ผ๋ก ๋ฎ์์ง๋ ๊ฒ์ ์ ์ ์์ต๋๋ค.
#
#
fig, ax = plt.subplots()
ax.plot(layer_idx_bn, avg_grads_bn, label="With BatchNorm", marker="o")
ax.plot(layer_idx_nobn, avg_grads_nobn, label="Without BatchNorm", marker="x")
ax.set_xlabel("Layer depth")
ax.set_ylabel("Average gradient")
ax.set_title("Gradient flow")
ax.grid(True)
ax.legend()
plt.show()
######################################################################
# ๊ฒฐ๋ก
# ----------
# ์ด ํํ ๋ฆฌ์ผ์์๋ `nn.Module`ํด๋์ค๋ก ๋ํ๋ ์ ๊ฒฝ๋ง์ ํตํด ๋ณํ๋ ํ๋ฆ์
# ์๊ฐํํ๋ ๋ฐฉ๋ฒ์ ์ค๋ช
ํ์์ต๋๋ค.
# ๋ํ, ๋ฐฐ์น ์ ๊ทํ๊ฐ ์ฌ์ธต ์ ๊ฒฝ๋ง์์ ๋ฐ์ํ๋ ๊ธฐ์ธ๊ธฐ ์์ค ๋ฌธ์ ๋ฅผ ์ํํ๋ ๋ฐ
# ์ด๋ป๊ฒ ๋์์ด ๋๋์ง๋ฅผ ์ ์ฑ์ ์ผ๋ก ๋ณด์ฌ์ฃผ์์ต๋๋ค.
#
#
# ํ์ดํ ์น์ ์๋ ๋ฏธ๋ถ ์์คํ
์๋ํ๋ ๋ฐฉ์์ ์ถ๊ฐ๋ก ํ์ตํ๊ณ ์ถ๋ค๋ฉด
# ์๋ `์ฐธ๊ณ ์๋ฃ <#references>`__๋ฅผ ํ์ธํ์ธ์.
# ์ด ํํ ๋ฆฌ์ผ์ ๋ํ ํผ๋๋ฐฑ(๊ฐ์ ์ฌํญ, ์คํ ์์ ๋ฑ)์ด ์๋ค๋ฉด `ํ์ดํ ์น ํฌ๋ผ<https://discuss.pytorch.org/>`__
# ๊ทธ๋ฆฌ๊ณ /๋๋ `์ด์ ํธ๋์ปค <https://github.com/pytorchkorea/tutorials-kr/issues>`__
# ๋ฅผ ํตํด ์๋ ค์ฃผ์๊ธฐ ๋ฐ๋๋๋ค.
#
#
######################################################################
# (์ ํ ์ฌํญ) ์ถ๊ฐ ์ฐ์ต
# -------------------------------
#
# - ๋ชจ๋ธ์ ๋ ์ด์ด ์(``num_layers``)๋ฅผ ๋๋ ค๋ณด๊ณ
# ์ด๊ฒ์ด ๋ณํ ํ๋ฆ ๊ทธ๋ํ์ ์ด๋ค ์ํฅ์ ๋ฏธ์น๋์ง ํ์ธํด ๋ณด์ธ์.
# - ํ๊ท ๋ณํ๋ ๋์ ํ๊ท ํ์ฑ๊ฐ์ ์๊ฐํํ๋ ค๋ฉด ์ฝ๋๋ฅผ ์ด๋ป๊ฒ ์์ ํด์ผ ํ ๊น์?
# (*ํํธ: hook_forward() ํจ์๊ฐ ์์ tensor ์ถ๋ ฅ์ ์ ๊ทผํ ์ ์์ต๋๋ค*)
#
# - ๋ณํ๋ ์์ค ๋ฐ ํญ์ฃผ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํ ๋ค๋ฅธ ๋ฐฉ๋ฒ์๋ ์ด๋ค ๊ฒ๋ค์ด ์์๊น์?
#
#
######################################################################
# ์ฐธ๊ณ ๋ฌธํ
# ----------
#
# - `A Gentle Introduction to
# torch.autograd <https://docs.tutorials.pytorch.kr/beginner/blitz/autograd_tutorial.html>`__
# - `Automatic Differentiation with
# torch.autograd <https://docs.tutorials.pytorch.kr/beginner/basics/autogradqs_tutorial>`__
# - `Autograd
# mechanics <https://docs.pytorch.org/docs/stable/notes/autograd.html>`__
# - `Batch Normalization: Accelerating Deep Network Training by Reducing
# Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`__
# - `On the difficulty of training Recurrent Neural
# Networks <https://arxiv.org/abs/1211.5063>`__
#