-
Notifications
You must be signed in to change notification settings - Fork 258
/
Copy pathpipeline_tutorial.py
412 lines (339 loc) ยท 17.7 KB
/
pipeline_tutorial.py
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
"""
ํ์ดํ๋ผ์ธ ๋ณ๋ ฌํ๋ก ํธ๋์คํฌ๋จธ ๋ชจ๋ธ ํ์ต์ํค๊ธฐ
==============================================
**Author**: `Pritam Damania <https://github.com/pritamdamania87>`_
**๋ฒ์ญ**: `๋ฐฑ์ ํฌ <https://github.com/spongebob03>`_
์ด ํํ ๋ฆฌ์ผ์ ํ์ดํ๋ผ์ธ(pipeline) ๋ณ๋ ฌํ(parallelism)๋ฅผ ์ฌ์ฉํ์ฌ ์ฌ๋ฌ GPU์ ๊ฑธ์น ๊ฑฐ๋ํ ํธ๋์คํฌ๋จธ(transformer)
๋ชจ๋ธ์ ์ด๋ป๊ฒ ํ์ต์ํค๋์ง ๋ณด์ฌ์ค๋๋ค. `NN.TRANSFORMER ์ TORCHTEXT ๋ก ์ํ์ค-ํฌ-์ํ์ค(SEQUENCE-TO-SEQUENCE) ๋ชจ๋ธ๋งํ๊ธฐ <https://tutorials.pytorch.kr/beginner/transformer_tutorial.html>`__ ํํ ๋ฆฌ์ผ์
ํ์ฅํ์ด๋ฉฐ ํ์ดํ๋ผ์ธ ๋ณ๋ ฌํ๊ฐ ์ด๋ป๊ฒ ํธ๋์คํฌ๋จธ ๋ชจ๋ธ ํ์ต์ ์ฐ์ด๋์ง ์ฆ๋ช
ํ๊ธฐ ์ํด ์ด์ ํํ ๋ฆฌ์ผ์์์
๋ชจ๋ธ ๊ท๋ชจ๋ฅผ ์ฆ๊ฐ์์ผฐ์ต๋๋ค.
์ ์๊ณผ๋ชฉ(Prerequisites):
* `Pipeline Parallelism <https://pytorch.org/docs/stable/pipeline.html>`__
* `NN.TRANSFORMER ์ TORCHTEXT ๋ก ์ํ์ค-ํฌ-์ํ์ค(SEQUENCE-TO-SEQUENCE) ๋ชจ๋ธ๋งํ๊ธฐ <https://tutorials.pytorch.kr/beginner/transformer_tutorial.html>`__
"""
######################################################################
# ๋ชจ๋ธ ์ ์ํ๊ธฐ
# -------------
#
######################################################################
# ์ด๋ฒ ํํ ๋ฆฌ์ผ์์๋, ํธ๋์คํฌ๋จธ ๋ชจ๋ธ์ ๋ ๊ฐ์ GPU์ ๊ฑธ์ณ์ ๋๋๊ณ ํ์ดํ๋ผ์ธ ๋ณ๋ ฌํ๋ก ํ์ต์์ผ ๋ณด๊ฒ ์ต๋๋ค.
# ๋ชจ๋ธ์ ๋ฐ๋ก `NN.TRANSFORMER ์ TORCHTEXT ๋ก ์ํ์ค-ํฌ-์ํ์ค(SEQUENCE-TO-SEQUENCE) ๋ชจ๋ธ๋งํ๊ธฐ
# <https://tutorials.pytorch.kr/beginner/transformer_tutorial.html>`__ ํํ ๋ฆฌ์ผ๊ณผ
# ๋๊ฐ์ ๋ชจ๋ธ์ด์ง๋ง ๋ ๋จ๊ณ๋ก ๋๋ฉ๋๋ค. ๋๋ถ๋ถ ํ๋ผ๋ฏธํฐ(parameter)๋ค์
# `nn.TransformerEncoder <https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html>`__ ๊ณ์ธต(layer)์ ํฌํจ๋ฉ๋๋ค.
# `nn.TransformerEncoder <https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html>`__ ๋
# `nn.TransformerEncoderLayer <https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html>`__ ์ ``nlayers`` ๋ก ๊ตฌ์ฑ๋์ด ์์ต๋๋ค.
# ๊ฒฐ๊ณผ์ ์ผ๋ก, ์ฐ๋ฆฌ๋ ``nn.TransformerEncoder`` ์ ์ค์ ์ ๋๊ณ ์์ผ๋ฉฐ,
# ``nn.TransformerEncoderLayer`` ์ ์ ๋ฐ์ ํ GPU์ ๋๊ณ
# ๋๋จธ์ง ์ ๋ฐ์ ๋ค๋ฅธ GPU์ ์๋๋ก ๋ชจ๋ธ์ ๋ถํ ํฉ๋๋ค. ์ด๋ฅผ ์ํด์ ``Encoder`` ์
# ``Decoder`` ์น์
์ ๋ถ๋ฆฌ๋ ๋ชจ๋๋ก ๋นผ๋ธ ๋ค์, ์๋ณธ ํธ๋์คํฌ๋จธ ๋ชจ๋์
# ๋ํ๋ด๋ nn.Sequential์ ๋น๋ ํฉ๋๋ค.
import sys
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import tempfile
from torch.nn import TransformerEncoder, TransformerEncoderLayer
if sys.platform == 'win32':
print('Windows platform is not supported for pipeline parallelism')
sys.exit(0)
if torch.cuda.device_count() < 2:
print('Need at least two GPU devices for this tutorial')
sys.exit(0)
class Encoder(nn.Module):
def __init__(self, ntoken, ninp, dropout=0.5):
super(Encoder, self).__init__()
self.pos_encoder = PositionalEncoding(ninp, dropout)
self.encoder = nn.Embedding(ntoken, ninp)
self.ninp = ninp
self.init_weights()
def init_weights(self):
initrange = 0.1
self.encoder.weight.data.uniform_(-initrange, initrange)
def forward(self, src):
# ์ธ์ฝ๋๋ก (S, N) ํฌ๋งท์ด ํ์ํฉ๋๋ค.
src = src.t()
src = self.encoder(src) * math.sqrt(self.ninp)
return self.pos_encoder(src)
class Decoder(nn.Module):
def __init__(self, ntoken, ninp):
super(Decoder, self).__init__()
self.decoder = nn.Linear(ninp, ntoken)
self.init_weights()
def init_weights(self):
initrange = 0.1
self.decoder.bias.data.zero_()
self.decoder.weight.data.uniform_(-initrange, initrange)
def forward(self, inp):
# ํ์ดํ๋ผ์ธ ๊ฒฐ๊ณผ๋ฌผ์ ์ํด ๋จผ์ ๋ฐฐ์น ์ฐจ์ ํ์ํฉ๋๋ค.
return self.decoder(inp).permute(1, 0, 2)
######################################################################
# ``PositionalEncoding``ย ๋ชจ๋์ ์ํ์ค ์์์ ํ ํฐ์ ์๋์ ์ธ ๋๋ ์ ๋์ ์ธ ํฌ์ง์
์ ๋ํ ์ ๋ณด๋ฅผ ์ฃผ์
ํฉ๋๋ค.
# ํฌ์ง์
๋ ์ธ์ฝ๋ฉ์ ์๋ฒ ๋ฉ๊ณผ ํฉ์น ์ ์๋๋ก ๋๊ฐ์ ์ฐจ์์ ๊ฐ์ง๋๋ค. ์ฌ๊ธฐ์
# ๋ค๋ฅธ ์ฃผ๊ธฐ(frequency)์ย ``sine``ย ๊ณผย ``cosine``ย ํจ์๋ฅผ ์ฌ์ฉํฉ๋๋ค.
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
self.register_buffer('pe', pe)
def forward(self, x):
x = x + self.pe[:x.size(0), :]
return self.dropout(x)
######################################################################
# ๋ฐ์ดํฐ ๋ก๋ํ๊ณ ๋ฐฐ์น ๋ง๋ค๊ธฐ
# ---------------------------
#
######################################################################
# ํ์ต ํ๋ก์ธ์ค๋ ``torchtext`` ์ Wikitext-2 ๋ฐ์ดํฐ์
์ ์ฌ์ฉํฉ๋๋ค.
# torchtext ๋ฐ์ดํฐ์
์ ์ ๊ทผํ๊ธฐ ์ ์, https://github.com/pytorch/data ์ ์ฐธ๊ณ ํ์ฌ torchdata๋ฅผ ์ค์นํ์๊ธฐ ๋ฐ๋๋๋ค.
#
# ๋จ์ด ์ค๋ธ์ ํธ๋ ํ๋ จ ๋ฐ์ดํฐ์
์ผ๋ก ๋ง๋ค์ด์ง๊ณ , ํ ํฐ์ ํ
์(tensor)๋ก ์์นํํ๋๋ฐ ์ฌ์ฉ๋ฉ๋๋ค.
# ์ํ์ค ๋ฐ์ดํฐ๋ก๋ถํฐ ์์ํ์ฌ, ``batchify()`` ํจ์๋ ๋ฐ์ดํฐ์
์ ์ด(column)๋ค๋ก ์ ๋ฆฌํ๊ณ ,
# ``batch_size`` ์ฌ์ด์ฆ์ ๋ฐฐ์น๋ค๋ก ๋๋ ํ์ ๋จ์ ๋ชจ๋ ํ ํฐ์ ๋ฒ๋ฆฝ๋๋ค.
# ์๋ฅผ ๋ค์ด, ์ํ๋ฒณ์ ์ํ์ค(์ด ๊ธธ์ด 26)๋ก ์๊ฐํ๊ณ ๋ฐฐ์น ์ฌ์ด์ฆ๋ฅผ 4๋ผ๊ณ ํ๋ค๋ฉด,
# ์ํ๋ฒณ์ ๊ธธ์ด๊ฐ 6์ธ 4๊ฐ์ ์ํ์ค๋ก ๋๋ ์ ์์ต๋๋ค:
#
# .. math::
#
# \begin{bmatrix}
# \text{A} & \text{B} & \text{C} & \ldots & \text{X} & \text{Y} & \text{Z}
# \end{bmatrix}
# \Rightarrow
# \begin{bmatrix}
# \begin{bmatrix}\text{A} \\ \text{B} \\ \text{C} \\ \text{D} \\ \text{E} \\ \text{F}\end{bmatrix} &
# \begin{bmatrix}\text{G} \\ \text{H} \\ \text{I} \\ \text{J} \\ \text{K} \\ \text{L}\end{bmatrix} &
# \begin{bmatrix}\text{M} \\ \text{N} \\ \text{O} \\ \text{P} \\ \text{Q} \\ \text{R}\end{bmatrix} &
# \begin{bmatrix}\text{S} \\ \text{T} \\ \text{U} \\ \text{V} \\ \text{W} \\ \text{X}\end{bmatrix}
# \end{bmatrix}
#
# ์ด ์ด๋ค์ ๋ชจ๋ธ์ ์ํด์ ๋
๋ฆฝ์ ์ผ๋ก ์ทจ๊ธ๋๋ฉฐ, ์ด๋
# ``G``ย ์ย ``F``ย ์ ์์กด์ฑ์ด ํ์ต๋ ์ ์๋ค๋ ๊ฒ์ ์๋ฏธํ์ง๋ง, ๋ ํจ์จ์ ์ธ
# ๋ฐฐ์น ํ๋ก์ธ์ฑ(batch processing)์ ํ์ฉํฉ๋๋ค.
#
import torch
from torchtext.datasets import WikiText2
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
train_iter = WikiText2(split='train')
tokenizer = get_tokenizer('basic_english')
vocab = build_vocab_from_iterator(map(tokenizer, train_iter), specials=["<unk>"])
vocab.set_default_index(vocab["<unk>"])
def data_process(raw_text_iter):
data = [torch.tensor(vocab(tokenizer(item)), dtype=torch.long) for item in raw_text_iter]
return torch.cat(tuple(filter(lambda t: t.numel() > 0, data)))
train_iter, val_iter, test_iter = WikiText2()
train_data = data_process(train_iter)
val_data = data_process(val_iter)
test_data = data_process(test_iter)
device = torch.device("cuda")
def batchify(data, bsz):
# ๋ฐ์ดํฐ์
์ ``bsz`` ํํธ๋ค๋ก ๋๋๋๋ค.
nbatch = data.size(0) // bsz
# ๊น๋ํ๊ฒ ๋๋์ด ๋จ์ด์ง์ง ์๋ ์ถ๊ฐ์ ์ธ ๋ถ๋ถ(๋๋จธ์ง)์ ์๋ผ๋
๋๋ค.
data = data.narrow(0, 0, nbatch * bsz)
# ๋ฐ์ดํฐ๋ฅผ ``bsz`` ๋ฐฐ์น๋ค๋ก ๋์ผํ๊ฒ ๋๋๋๋ค.
data = data.view(bsz, -1).t().contiguous()
return data.to(device)
batch_size = 20
eval_batch_size = 10
train_data = batchify(train_data, batch_size)
val_data = batchify(val_data, eval_batch_size)
test_data = batchify(test_data, eval_batch_size)
######################################################################
# ์
๋ ฅ๊ณผ ํ๊ฒ ์ํ์ค๋ฅผ ์์ฑํ๊ธฐ ์ํ ํจ์๋ค
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
######################################################################
# ``get_batch()`` ํจ์๋ ํธ๋์คํฌ๋จธ ๋ชจ๋ธ์ ์ํ ์
๋ ฅ๊ณผ ํ๊ฒ ์ํ์ค๋ฅผ
# ์์ฑํฉ๋๋ค. ์ด ํจ์๋ ์์ค ๋ฐ์ดํฐ๋ฅผ ``bptt`` ๊ธธ์ด๋ฅผ ๊ฐ์ง ๋ฉ์ด๋ฆฌ๋ก ์ธ๋ถํํฉ๋๋ค.
# ์ธ์ด ๋ชจ๋ธ๋ง ๊ณผ์ ๋ฅผ ์ํด์, ๋ชจ๋ธ์ ๋ค์ ๋จ์ด์ธ ``Target`` ์ด ํ์ํฉ๋๋ค. ์๋ฅผ ๋ค์ด ``bptt`` ์ ๊ฐ์ด 2๋ผ๋ฉด,
# ``i`` = 0 ์ผ ๋ ๋ค์์ 2 ๊ฐ ๋ณ์(Variable)๋ฅผ ์ป์ ์ ์์ต๋๋ค:
#
# .. image:: ../_static/img/transformer_input_target.png
#
# ๋ณ์ ๋ฉ์ด๋ฆฌ๋ ํธ๋์คํฌ๋จธ ๋ชจ๋ธ์ย ``S``ย ์ฐจ์๊ณผ ์ผ์นํ๋ 0 ์ฐจ์์ ํด๋นํฉ๋๋ค.
# ๋ฐฐ์น ์ฐจ์ย ``N``ย ์ 1 ์ฐจ์์ ํด๋นํฉ๋๋ค.
#
bptt = 25
def get_batch(source, i):
seq_len = min(bptt, len(source) - 1 - i)
data = source[i:i+seq_len]
target = source[i+1:i+1+seq_len].view(-1)
# ํ์ดํ๋ผ์ธ ๋ณ๋ ฌํ๋ฅผ ์ํด ๋จผ์ ๋ฐฐ์น ์ฐจ์์ด ํ์ํฉ๋๋ค.
return data.t(), target
######################################################################
# ๋ชจ๋ธ ๊ท๋ชจ์ ํ์ดํ ์ด๊ธฐํ
# -------------------------
#
######################################################################
# ํ์ดํ๋ผ์ธ ๋ณ๋ ฌํ๋ฅผ ํ์ฉํ ๋ํ ํธ๋์คํฌ๋จธ ๋ชจ๋ธ ํ์ต์ ์ฆ๋ช
ํ๊ธฐ ์ํด์
# ํธ๋์คํฌ๋จธ ๊ณ์ธต ๊ท๋ชจ๋ฅผ ์ ์ ํ ํ์ฅ์ํต๋๋ค. 4096์ฐจ์์ ์๋ฒ ๋ฉ ๋ฒกํฐ, 4096์ ์๋ ์ฌ์ด์ฆ,
# 16๊ฐ์ ์ดํ
์
ํค๋(attention head)์ ์ด 12 ๊ฐ์ ํธ๋์คํฌ๋จธ ๊ณ์ธต
# (``nn.TransformerEncoderLayer``)๋ฅผ ์ฌ์ฉํฉ๋๋ค. ์ด๋ ์ต๋
# **1.4์ต** ๊ฐ์ ํ๋ผ๋ฏธํฐ๋ฅผ ๊ฐ๋ ๋ชจ๋ธ์ ์์ฑํฉ๋๋ค.
#
# Pipe๋ `RRef <https://pytorch.org/docs/stable/rpc.html#rref>`__ ๋ฅผ ํตํด
# `RPC ํ๋ ์์ํฌ <https://pytorch.org/docs/stable/rpc.html>`__ ์ ์์กดํ๋๋ฐ
# ์ด๋ ํฅํ ํธ์คํธ ํ์ดํ๋ผ์ธ์ ๊ต์ฐจ ํ์ฅํ ์ ์๋๋ก ํ๊ธฐ ๋๋ฌธ์
# RPC ํ๋ ์์ํฌ๋ฅผ ์ด๊ธฐํํด์ผ ํฉ๋๋ค. ์ด๋ RPC ํ๋ ์์ํฌ๋ ์ค์ง ํ๋์ ํ๋์ worker๋ก ์ด๊ธฐํ๋ฅผ ํด์ผ ํ๋๋ฐ,
# ์ฌ๋ฌ GPU๋ฅผ ๋ค๋ฃจ๊ธฐ ์ํด ํ๋ก์ธ์ค ํ๋๋ง ์ฌ์ฉํ๊ณ ์๊ธฐ ๋๋ฌธ์
๋๋ค.
#
# ๊ทธ๋ฐ ๋ค์ ํ์ดํ๋ผ์ธ์ ํ GPU์ 8๊ฐ์ ํธ๋์คํฌ๋จธ์
# ๋ค๋ฅธ GPU์ 8๊ฐ์ ํธ๋์คํฌ๋จธ ๋ ์ด์ด๋ก ์ด๊ธฐํ๋ฉ๋๋ค.
#
# .. note::
# ํจ์จ์ฑ์ ์ํด ``Pipe`` ์ ์ ๋ฌ๋ ``nn.Sequential`` ์ด
# ์ค์ง ๋ ๊ฐ์ ์์(2๊ฐ์ GPU)๋ก๋ง ๊ตฌ์ฑ๋๋๋ก ํฉ๋๋ค. ์ด๋ ๊ฒ ํ๋ฉด
# Pipe๊ฐ ๋ ๊ฐ์ ํํฐ์
์์๋ง ์๋ํ๊ณ
# ํํฐ์
๊ฐ ์ค๋ฒํค๋๋ฅผ ํผํ ์ ์์ต๋๋ค.
ntokens = len(vocab) # ๋จ์ด ์ฌ์ (์ดํ์ง)์ ํฌ๊ธฐ
emsize = 4096 # ์๋ฒ ๋ฉ ์ฐจ์
nhid = 4096 # ``nn.TransformerEncoder`` ์์ ์์ ํ(feedforward) ์ ๊ฒฝ๋ง ๋ชจ๋ธ์ ์ฐจ์
nlayers = 12 # ``nn.TransformerEncoder`` ๋ด๋ถ์ ``nn.TransformerEncoderLayer`` ๊ฐ์
nhead = 16 # Multihead Attention ๋ชจ๋ธ์ ํค๋ ๊ฐ์
dropout = 0.2 # dropout ๊ฐ
from torch.distributed import rpc
tmpfile = tempfile.NamedTemporaryFile()
rpc.init_rpc(
name="worker",
rank=0,
world_size=1,
rpc_backend_options=rpc.TensorPipeRpcBackendOptions(
init_method="file://{}".format(tmpfile.name),
# _transports์ _channels๋ฅผ ์ง์ ํ๋ ๊ฒ์ด ํด๊ฒฐ ๋ฐฉ๋ฒ์ด๋ฉฐ
# PyTorch ๋ฒ์ >= 1.8.1 ์์๋ _transports์ _channels๋ฅผ
# ์ง์ ํ์ง ์์๋ ๋ฉ๋๋ค.
_transports=["ibv", "uv"],
_channels=["cuda_ipc", "cuda_basic"],
)
)
num_gpus = 2
partition_len = ((nlayers - 1) // num_gpus) + 1
# ์ฒ์์ ์ธ์ฝ๋๋ฅผ ์ถ๊ฐํฉ๋๋ค.
tmp_list = [Encoder(ntokens, emsize, dropout).cuda(0)]
module_list = []
# ํ์ํ ๋ชจ๋ ํธ๋์คํฌ๋จธ ๋ธ๋ก๋ค์ ์ถ๊ฐํฉ๋๋ค.
for i in range(nlayers):
transformer_block = TransformerEncoderLayer(emsize, nhead, nhid, dropout)
if i != 0 and i % (partition_len) == 0:
module_list.append(nn.Sequential(*tmp_list))
tmp_list = []
device = i // (partition_len)
tmp_list.append(transformer_block.to(device))
# ๋ง์ง๋ง์ ๋์ฝ๋๋ฅผ ์ถ๊ฐํฉ๋๋ค.
tmp_list.append(Decoder(ntokens, emsize).cuda(num_gpus - 1))
module_list.append(nn.Sequential(*tmp_list))
from torch.distributed.pipeline.sync import Pipe
# ํ์ดํ๋ผ์ธ์ ๋น๋ํฉ๋๋ค.
chunks = 8
model = Pipe(torch.nn.Sequential(*module_list), chunks = chunks)
def get_total_params(module: torch.nn.Module):
total_params = 0
for param in module.parameters():
total_params += param.numel()
return total_params
print ('Total parameters in model: {:,}'.format(get_total_params(model)))
######################################################################
# ๋ชจ๋ธ ์คํํ๊ธฐ
# ---------------
#
######################################################################
# ์์ค(loss)์ ์ถ์ ํ๊ธฐ ์ํด `CrossEntropyLoss <https://pytorch.org/docs/master/nn.html?highlight=crossentropyloss#torch.nn.CrossEntropyLoss>`__ ๊ฐ
# ์ ์ฉ๋๋ฉฐ, ์ตํฐ๋ง์ด์ (optimizer)๋ก์ `SGD <https://pytorch.org/docs/master/optim.html?highlight=sgd#torch.optim.SGD>`__
# ๋ ํ๋ฅ ์ ๊ฒฝ์ฌํ๊ฐ๋ฒ(stochastic gradient descent method)์ ๊ตฌํํฉ๋๋ค. ์ด๊ธฐ
# ํ์ต๋ฅ (learning rate)์ 5.0๋ก ์ค์ ๋ฉ๋๋ค. `StepLR <https://pytorch.org/docs/master/optim.html?highlight=steplr#torch.optim.lr_scheduler.StepLR>`__ ๋
# ์ํญ(epoch)์ ๋ฐ๋ผ์ ํ์ต๋ฅ ์ ์กฐ์ ํ๋ ๋ฐ ์ฌ์ฉ๋ฉ๋๋ค. ํ์ตํ๋ ๋์,
# ๊ธฐ์ธ๊ธฐ ํญ๋ฐ(gradient exploding)์ ๋ฐฉ์งํ๊ธฐ ์ํด ๋ชจ๋ ๊ธฐ์ธ๊ธฐ๋ฅผ ํจ๊ป ์กฐ์ (scale)ํ๋ ํจ์
# `nn.utils.clip_grad_norm\_ <https://pytorch.org/docs/master/nn.html?highlight=nn%20utils%20clip_grad_norm#torch.nn.utils.clip_grad_norm_>`__
# ์ ์ด์ฉํฉ๋๋ค.
#
criterion = nn.CrossEntropyLoss()
lr = 5.0 # ํ์ต๋ฅ
optimizer = torch.optim.SGD(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)
import time
def train():
model.train() # ํ๋ จ ๋ชจ๋๋ก ์ ํ
total_loss = 0.
start_time = time.time()
ntokens = len(vocab)
# ์คํฌ๋ฆฝํธ ์คํ ์๊ฐ์ ์งง๊ฒ ์ ์งํ๊ธฐ ์ํด์ 50 ๋ฐฐ์น๋ง ํ์ตํฉ๋๋ค.
nbatches = min(50 * bptt, train_data.size(0) - 1)
for batch, i in enumerate(range(0, nbatches, bptt)):
data, targets = get_batch(train_data, i)
optimizer.zero_grad()
# Pipe๋ ๋จ์ผ ํธ์คํธ ๋ด์ ์๊ณ
# forward ๋ฉ์๋๋ก ๋ฐํ๋ ``RRef`` ํ๋ก์ธ์ค๋ ์ด ๋
ธ๋์ ๊ตญํ๋์ด ์๊ธฐ ๋๋ฌธ์
# ``RRef.local_value()`` ๋ฅผ ํตํด ๊ฐ๋จํ ์ฐพ์ ์ ์์ต๋๋ค.
output = model(data).local_value()
# ํ๊ฒ์ ํ์ดํ๋ผ์ธ ์ถ๋ ฅ์ด ์๋
# ์ฅ์น๋ก ์ฎ๊ฒจ์ผํฉ๋๋ค.
loss = criterion(output.view(-1, ntokens), targets.cuda(1))
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
optimizer.step()
total_loss += loss.item()
log_interval = 10
if batch % log_interval == 0 and batch > 0:
cur_loss = total_loss / log_interval
elapsed = time.time() - start_time
print('| epoch {:3d} | {:5d}/{:5d} batches | '
'lr {:02.2f} | ms/batch {:5.2f} | '
'loss {:5.2f} | ppl {:8.2f}'.format(
epoch, batch, nbatches // bptt, scheduler.get_lr()[0],
elapsed * 1000 / log_interval,
cur_loss, math.exp(cur_loss)))
total_loss = 0
start_time = time.time()
def evaluate(eval_model, data_source):
eval_model.eval() # ํ๊ฐ ๋ชจ๋๋ก ์ ํ
total_loss = 0.
ntokens = len(vocab)
# ์คํฌ๋ฆฝํธ ์คํ ์๊ฐ์ ์งง๊ฒ ์ ์งํ๊ธฐ ์ํด 50 ๋ฐฐ์น๋ง ํ๊ฐํฉ๋๋ค.
nbatches = min(50 * bptt, data_source.size(0) - 1)
with torch.no_grad():
for i in range(0, nbatches, bptt):
data, targets = get_batch(data_source, i)
output = eval_model(data).local_value()
output_flat = output.view(-1, ntokens)
# ํ๊ฒ์ ํ์ดํ๋ผ์ธ ์ถ๋ ฅ์ด ์๋
# ์ฅ์น๋ก ์ฎ๊ฒจ์ผํฉ๋๋ค.
total_loss += len(data) * criterion(output_flat, targets.cuda(1)).item()
return total_loss / (len(data_source) - 1)
######################################################################
# ์ํญ์ ๋ฐ๋ณตํฉ๋๋ค. ๋ง์ฝ ๊ฒ์ฆ ์ค์ฐจ(validation loss)๊ฐ ์ง๊ธ๊น์ง ๊ด์ฐฐํ ๊ฒ ์ค ์ต์ ์ด๋ผ๋ฉด
# ๋ชจ๋ธ์ ์ ์ฅํฉ๋๋ค. ๊ฐ ์ํญ ์ดํ์ ํ์ต๋ฅ ์ ์กฐ์ ํฉ๋๋ค.
best_val_loss = float("inf")
epochs = 3 # ์ํญ ์
best_model = None
for epoch in range(1, epochs + 1):
epoch_start_time = time.time()
train()
val_loss = evaluate(model, val_data)
print('-' * 89)
print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '
'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),
val_loss, math.exp(val_loss)))
print('-' * 89)
if val_loss < best_val_loss:
best_val_loss = val_loss
best_model = model
scheduler.step()
######################################################################
# ํ๊ฐ ๋ฐ์ดํฐ์
์ผ๋ก ๋ชจ๋ธ ํ๊ฐํ๊ธฐ
# ---------------------------------
#
######################################################################
# ํ๊ฐ ๋ฐ์ดํฐ์
์์์ ๊ฒฐ๊ณผ๋ฅผ ํ์ธํ๊ธฐ ์ํด ์ต๊ณ ์ ๋ชจ๋ธ์ ์ ์ฉํฉ๋๋ค.
test_loss = evaluate(best_model, test_data)
print('=' * 89)
print('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(
test_loss, math.exp(test_loss)))
print('=' * 89)