-
Notifications
You must be signed in to change notification settings - Fork 259
/
Copy pathtransformer_tutorial.py
373 lines (306 loc) Β· 16.4 KB
/
transformer_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
"""
``nn.Transformer`` μ torchtextλ‘ μνμ€-ν¬-μνμ€(Sequence-to-Sequence) λͺ¨λΈλ§νκΈ°
=====================================================================================
μ΄ νν 리μΌμμλ
`nn.Transformer <https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html>`__ λͺ¨λμ
μ΄μ©νλ μνμ€-ν¬-μνμ€(Sequence-to-Sequence) λͺ¨λΈμ νμ΅νλ λ°©λ²μ λ°°μλ³΄κ² μ΅λλ€.
PyTorch 1.2 λ²μ Όμλ `Attention is All You Need <https://arxiv.org/pdf/1706.03762.pdf>`__ λ
Όλ¬Έμ
κΈ°λ°ν νμ€ νΈλμ€ν¬λ¨Έ(transformer) λͺ¨λμ ν¬ν¨νκ³ μμ΅λλ€.
νΈλμ€ν¬λ¨Έ λͺ¨λΈμ λ€μν μνμ€-ν¬-μνμ€ λ¬Έμ λ€μμ λ λ³λ ¬ν(parallelizable)κ° κ°λ₯νλ©΄μλ
μν μ κ²½λ§(RNN; Recurrent Neural Network)κ³Ό λΉκ΅νμ¬ λ λμ μ±λ₯μ 보μμ΄ μ
μ¦λμμ΅λλ€.
``nn.Transformer`` λͺ¨λμ μ
λ ₯(input) κ³Ό μΆλ ₯(output) μ¬μ΄μ μ μμ μΈ μμ‘΄μ±(global dependencies)
μ λνλ΄κΈ° μνμ¬ (`nn.MultiheadAttention <https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html>`__ μΌλ‘
ꡬνλ) μ΄ν
μ
(attention) λ©μ»€λμ¦μ μ μ μΌλ‘ μμ‘΄ν©λλ€.
νμ¬ ``nn.Transformer`` λͺ¨λμ λͺ¨λνκ° μ λμ΄ μμ΄
λ¨μΌ μ»΄ν¬λνΈ (μ. `nn.TransformerEncoder <https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html>`__ )
λ‘ μ½κ² μ μ© λ° κ΅¬μ±ν μ μμ΅λλ€.
.. image:: ../_static/img/transformer_architecture.jpg
"""
######################################################################
# λͺ¨λΈ μ μνκΈ°
# ----------------
#
######################################################################
# μ΄ νν 리μΌμμ, μ°λ¦¬λ ``nn.TransformerEncoder`` λͺ¨λΈμ μΈμ΄ λͺ¨λΈλ§(language modeling) κ³Όμ μ λν΄μ νμ΅μν¬ κ²μ
λλ€.
# μΈμ΄ λͺ¨λΈλ§ κ³Όμ λ μ£Όμ΄μ§ λ¨μ΄ (λλ λ¨μ΄μ μνμ€) κ° λ€μμ μ΄μ΄μ§λ λ¨μ΄ μνμ€λ₯Ό λ°λ₯Ό κ°λ₯μ±(likelihood)μ λν νλ₯ μ ν λΉνλ κ²μ
λλ€.
# λ¨Όμ , ν ν°(token) λ€μ μνμ€κ° μλ² λ©(embedding) λ μ΄μ΄λ‘ μ λ¬λλ©°, μ΄μ΄μ ν¬μ§μ
λ μΈμ½λ©(positional encoding) λ μ΄μ΄κ° κ° λ¨μ΄μ μμλ₯Ό μ€λͺ
ν©λλ€.
# (λ μμΈν μ€λͺ
μ λ€μ λ¨λ½μ μ°Έκ³ ν΄μ£ΌμΈμ.)
# ``nn.TransformerEncoder`` λ μ¬λ¬ κ°μ
# `nn.TransformerEncoderLayer <https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html>`__
# λ μ΄μ΄λ‘ ꡬμ±λμ΄ μμ΅λλ€.
# ``nn.TransformerEncoder`` λ΄λΆμ μ
ν-μ΄ν
μ
(self-attention) λ μ΄μ΄λ€μ μνμ€ μμμμ μ΄μ ν¬μ§μ
μλ§ μ§μ€νλλ‘ νμ©λκΈ° λλ¬Έμ,
# μ
λ ₯(input) μμμ ν¨κ», μ μ¬κ° ννμ μ΄ν
μ
λ§μ€ν¬(attention mask) κ° νμν©λλ€.
# μΈμ΄ λͺ¨λΈλ§ κ³Όμ λ₯Ό μν΄μ, λ―Έλμ ν¬μ§μ
μ μλ λͺ¨λ ν ν°λ€μ λ§μ€νΉ λμ΄μΌ(κ°λ €μ ΈμΌ) ν©λλ€.
# μ€μ λ¨μ΄λ₯Ό μ»κΈ° μν΄μ, ``nn.TransformerEncoder`` μ μΆλ ₯μ λ‘κ·Έ-μννΈλ§₯μ€(log-Softmax) λ‘ μ΄μ΄μ§λ μ΅μ’
μ ν(Linear) λ μ΄μ΄λ‘ μ λ¬ λ©λλ€.
#
import math
import os
from tempfile import TemporaryDirectory
from typing import Tuple
import torch
from torch import nn, Tensor
import torch.nn.functional as F
from torch.nn import TransformerEncoder, TransformerEncoderLayer
from torch.utils.data import dataset
class TransformerModel(nn.Module):
def __init__(self, ntoken: int, d_model: int, nhead: int, d_hid: int,
nlayers: int, dropout: float = 0.5):
super().__init__()
self.model_type = 'Transformer'
self.pos_encoder = PositionalEncoding(d_model, dropout)
encoder_layers = TransformerEncoderLayer(d_model, nhead, d_hid, dropout)
self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)
self.encoder = nn.Embedding(ntoken, d_model)
self.d_model = d_model
self.decoder = nn.Linear(d_model, ntoken)
self.init_weights()
def init_weights(self) -> None:
initrange = 0.1
self.encoder.weight.data.uniform_(-initrange, initrange)
self.decoder.bias.data.zero_()
self.decoder.weight.data.uniform_(-initrange, initrange)
def forward(self, src: Tensor, src_mask: Tensor) -> Tensor:
"""
Arguments:
src: Tensor, shape ``[seq_len, batch_size]``
src_mask: Tensor, shape ``[seq_len, seq_len]``
Returns:
output Tensor of shape ``[seq_len, batch_size, ntoken]``
"""
src = self.encoder(src) * math.sqrt(self.d_model)
src = self.pos_encoder(src)
output = self.transformer_encoder(src, src_mask)
output = self.decoder(output)
return output
def generate_square_subsequent_mask(sz: int) -> Tensor:
"""Generates an upper-triangular matrix of ``-inf``, with zeros on ``diag``."""
return torch.triu(torch.ones(sz, sz) * float('-inf'), diagonal=1)
######################################################################
# ``PositionalEncoding`` λͺ¨λμ μνμ€ μμμ ν ν°μ μλμ μΈ λλ μ λμ μΈ ν¬μ§μ
μ λν μ΄λ€ μ 보λ₯Ό μ£Όμ
ν©λλ€.
# ν¬μ§μ
λ μΈμ½λ©μ μλ² λ©κ³Ό ν©μΉ μ μλλ‘ λκ°μ μ°¨μμ κ°μ§λλ€.
# μ¬κΈ°μμ, μ°λ¦¬λ λ€λ₯Έ μ£Όνμ(frequency) μ ``sine`` κ³Ό ``cosine`` ν¨μλ₯Ό μ¬μ©ν©λλ€.
#
class PositionalEncoding(nn.Module):
def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000):
super().__init__()
self.dropout = nn.Dropout(p=dropout)
position = torch.arange(max_len).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
pe = torch.zeros(max_len, 1, d_model)
pe[:, 0, 0::2] = torch.sin(position * div_term)
pe[:, 0, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe)
def forward(self, x: Tensor) -> Tensor:
"""
Arguments:
x: Tensor, shape ``[seq_len, batch_size, embedding_dim]``
"""
x = x + self.pe[:x.size(0)]
return self.dropout(x)
######################################################################
# λ°μ΄ν° λ‘λνκ³ λ°°μΉ λ§λ€κΈ°
# -----------------------------
#
######################################################################
# μ΄ νν 리μΌμμλ ``torchtext`` λ₯Ό μ¬μ©νμ¬ Wikitext-2 λ°μ΄ν°μ
μ μμ±ν©λλ€.
# torchtext λ°μ΄ν°μ
μ μ κ·ΌνκΈ° μ μ, https://github.com/pytorch/data μ μ°Έκ³ νμ¬ torchdataλ₯Ό μ€μΉνμκΈ° λ°λλλ€.
# %%
# .. code-block:: bash
#
# %%bash
# pip install torchdata
#
# μ΄ν(vocab) κ°μ²΄λ νλ ¨ λ°μ΄ν°μ
(train dataset) μ μνμ¬ λ§λ€μ΄μ§κ³ , ν ν°(token)μ ν
μ(tensor)λ‘ μμΉννλλ° μ¬μ©λ©λλ€.
# Wikitext-2μμ 보기 λλ¬Έ ν ν°(rare token)μ `<unk>` λ‘ ννλ©λλ€.
#
# μ£Όμ΄μ§ 1D 벑ν°μ μνμ€ λ°μ΄ν°μμ, ``batchify()`` ν¨μλ λ°μ΄ν°λ₯Ό ``batch_size`` 컬λΌλ€λ‘ μ λ ¬ν©λλ€.
# λ§μ½ λ°μ΄ν°κ° ``batch_size`` 컬λΌμΌλ‘ λλμ΄ λ¨μ΄μ§μ§ μμΌλ©΄, λ°μ΄ν°λ₯Ό μλΌλ΄μ λ§μΆ₯λλ€.
# μλ₯Ό λ€μ΄ (μ΄ κΈΈμ΄ 26μ) μνλ²³μ λ°μ΄ν°λ‘ λ³΄κ³ ``batch_size=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}
#
# λ°°μΉ μμ
(batching)μ λ λ§μ λ³λ ¬ μ²λ¦¬λ₯Ό κ°λ₯νκ² νμ§λ§, λͺ¨λΈμ΄ λ
립μ μΌλ‘ κ° μ»¬λΌλ€μ μ·¨κΈν΄μΌ ν¨μ λ»ν©λλ€;
# μλ₯Ό λ€μ΄, μ μμ μμ ``G`` μ ``F`` μ μμ‘΄μ±(dependance)μ νμ΅λμ§ μμ΅λλ€.
#
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: dataset.IterableDataset) -> Tensor:
"""Converts raw text into a flat Tensor."""
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`` was "consumed" by the process of building the vocab,
# so we have to create it again
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' if torch.cuda.is_available() else 'cpu')
def batchify(data: Tensor, bsz: int) -> Tensor:
"""Divides the data into ``bsz`` separate sequences, removing extra elements
that wouldn't cleanly fit.
Arguments:
data: Tensor, shape ``[N]``
bsz: int, batch size
Returns:
Tensor of shape ``[N // bsz, bsz]``
"""
seq_len = data.size(0) // bsz
data = data[:seq_len * bsz]
data = data.view(bsz, seq_len).t().contiguous()
return data.to(device)
batch_size = 20
eval_batch_size = 10
train_data = batchify(train_data, batch_size) # shape [seq_len, batch_size]
val_data = batchify(val_data, eval_batch_size)
test_data = batchify(test_data, eval_batch_size)
######################################################################
# μ
λ ₯(input) κ³Ό νκ²(target) μνμ€λ₯Ό μμ±νκΈ° μν ν¨μλ€
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
######################################################################
# ``get_batch()`` ν¨μλ νΈλμ€ν¬λ¨Έ λͺ¨λΈμ μν μ
λ ₯-νκ² μνμ€ μ(pair)μ μμ±ν©λλ€.
# μ΄ ν¨μλ μμ€ λ°μ΄ν°λ₯Ό ``bptt`` κΈΈμ΄λ₯Ό κ°μ§ λ©μ΄λ¦¬λ‘ μΈλΆν ν©λλ€.
# μΈμ΄ λͺ¨λΈλ§ κ³Όμ λ₯Ό μν΄μ, λͺ¨λΈμ λ€μ λ¨μ΄μΈ ``Target`` μ΄ νμ ν©λλ€.
# μλ₯Ό λ€μ΄, ``bptt`` μ κ°μ΄ 2 λΌλ©΄, μ°λ¦¬λ ``i`` = 0 μΌ λ λ€μμ 2 κ°μ λ³μ(Variable) λ₯Ό μ»μ μ μμ΅λλ€:
#
# .. image:: ../_static/img/transformer_input_target.png
#
# λ³μ λ©μ΄λ¦¬λ νΈλμ€ν¬λ¨Έ λͺ¨λΈμ ``S`` μ°¨μκ³Ό μΌμΉνλ 0 μ°¨μμ ν΄λΉν©λλ€.
# λ°°μΉ μ°¨μ ``N`` μ 1 μ°¨μμ ν΄λΉν©λλ€.
#
bptt = 35
def get_batch(source: Tensor, i: int) -> Tuple[Tensor, Tensor]:
"""
Arguments:
source: Tensor, shape ``[full_seq_len, batch_size]``
i: int
Returns:
tuple ``(data, target)``, where data has shape ``[seq_len, batch_size]`` and
target has shape ``[seq_len * batch_size]``
"""
seq_len = min(bptt, len(source) - 1 - i)
data = source[i:i+seq_len]
target = source[i+1:i+1+seq_len].reshape(-1)
return data, target
######################################################################
# μΈμ€ν΄μ€(instance) μ΄κΈ°ννκΈ°
# --------------------------------
#
######################################################################
# λͺ¨λΈμ νμ΄νΌνλΌλ―Έν°(hyperparameter)λ μλμ κ°μ΄ μ μλ©λλ€.
# μ΄νμ§( ``vocab`` )μ ν¬κΈ°λ λ¨μ΄ μ€λΈμ νΈμ κΈΈμ΄μ μΌμΉ ν©λλ€.
#
ntokens = len(vocab) # λ¨μ΄ μ¬μ (μ΄νμ§)μ ν¬κΈ°
emsize = 200 # μλ² λ© μ°¨μ
d_hid = 200 # ``nn.TransformerEncoder`` μμ νΌλν¬μλ λ€νΈμν¬(feedforward network) λͺ¨λΈμ μ°¨μ
nlayers = 2 # ``nn.TransformerEncoder`` λ΄λΆμ nn.TransformerEncoderLayer κ°μ
nhead = 2 # ``nn.MultiheadAttention`` μ ν€λ κ°μ
dropout = 0.2 # λλμμ(dropout) νλ₯
model = TransformerModel(ntokens, emsize, nhead, d_hid, nlayers, dropout).to(device)
######################################################################
# λͺ¨λΈ μ€ννκΈ°
# ---------------
#
######################################################################
# `CrossEntropyLoss <https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html>`__ λ₯Ό
# `SGD <https://pytorch.org/docs/stable/generated/torch.optim.SGD.html>`__ (νλ₯ μ κ²½μ¬ νκ°λ²) μ΅ν°λ§μ΄μ (optimizer)μ
# ν¨κ» μ¬μ©νμμ΅λλ€. νμ΅λ₯ (learning rate)λ 5.0μΌλ‘ μ΄κΈ°ννμμΌλ©° `StepLR <https://pytorch.org/docs/master/optim.html?highlight=steplr#torch.optim.lr_scheduler.StepLR>`__
# μ€μΌμ₯΄μ λ°λ¦
λλ€. νμ΅νλ λμ, `nn.utils.clip_grad_norm\_ <https://pytorch.org/docs/stable/generated/torch.nn.utils.clip_grad_norm_.html>`__
# μ μ¬μ©νμ¬ κΈ°μΈκΈ°(gradient)κ° νλ°(exploding)νμ§ μλλ‘ ν©λλ€.
#
import copy
import time
criterion = nn.CrossEntropyLoss()
lr = 5.0 # νμ΅λ₯ (learning rate)
optimizer = torch.optim.SGD(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)
def train(model: nn.Module) -> None:
model.train() # νμ΅ λͺ¨λ μμ
total_loss = 0.
log_interval = 200
start_time = time.time()
src_mask = generate_square_subsequent_mask(bptt).to(device)
num_batches = len(train_data) // bptt
for batch, i in enumerate(range(0, train_data.size(0) - 1, bptt)):
data, targets = get_batch(train_data, i)
seq_len = data.size(0)
if seq_len != bptt: # λ§μ§λ§ λ°°μΉμλ§ μ μ©
src_mask = src_mask[:seq_len, :seq_len]
output = model(data, src_mask)
loss = criterion(output.view(-1, ntokens), targets)
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
optimizer.step()
total_loss += loss.item()
if batch % log_interval == 0 and batch > 0:
lr = scheduler.get_last_lr()[0]
ms_per_batch = (time.time() - start_time) * 1000 / log_interval
cur_loss = total_loss / log_interval
ppl = math.exp(cur_loss)
print(f'| epoch {epoch:3d} | {batch:5d}/{num_batches:5d} batches | '
f'lr {lr:02.2f} | ms/batch {ms_per_batch:5.2f} | '
f'loss {cur_loss:5.2f} | ppl {ppl:8.2f}')
total_loss = 0
start_time = time.time()
def evaluate(model: nn.Module, eval_data: Tensor) -> float:
model.eval() # νκ° λͺ¨λ μμ
total_loss = 0.
src_mask = generate_square_subsequent_mask(bptt).to(device)
with torch.no_grad():
for i in range(0, eval_data.size(0) - 1, bptt):
data, targets = get_batch(eval_data, i)
seq_len = data.size(0)
if seq_len != bptt:
src_mask = src_mask[:seq_len, :seq_len]
output = model(data, src_mask)
output_flat = output.view(-1, ntokens)
total_loss += seq_len * criterion(output_flat, targets).item()
return total_loss / (len(eval_data) - 1)
######################################################################
# μν¬ν¬ λ΄μμ λ°λ³΅λ©λλ€. λ§μ½ κ²μ¦ μ€μ°¨(validation loss) κ° μ°λ¦¬κ° μ§κΈκΉμ§ κ΄μ°°ν κ² μ€ μ΅μ μ΄λΌλ©΄ λͺ¨λΈμ μ μ₯ν©λλ€.
# 맀 μν¬ν¬ μ΄νμ νμ΅λ₯ μ μ‘°μ ν©λλ€.
best_val_loss = float('inf')
epochs = 3
with TemporaryDirectory() as tempdir:
best_model_params_path = os.path.join(tempdir, "best_model_params.pt")
for epoch in range(1, epochs + 1):
epoch_start_time = time.time()
train(model)
val_loss = evaluate(model, val_data)
val_ppl = math.exp(val_loss)
elapsed = time.time() - epoch_start_time
print('-' * 89)
print(f'| end of epoch {epoch:3d} | time: {elapsed:5.2f}s | '
f'valid loss {val_loss:5.2f} | valid ppl {val_ppl:8.2f}')
print('-' * 89)
if val_loss < best_val_loss:
best_val_loss = val_loss
torch.save(model.state_dict(), best_model_params_path)
scheduler.step()
model.load_state_dict(torch.load(best_model_params_path)) # load best model states
######################################################################
# νκ° λ°μ΄ν°μ
(test dataset)μΌλ‘ λͺ¨λΈμ νκ°νκΈ°
# -------------------------------------------------
#
test_loss = evaluate(model, test_data)
test_ppl = math.exp(test_loss)
print('=' * 89)
print(f'| End of training | test loss {test_loss:5.2f} | '
f'test ppl {test_ppl:8.2f}')
print('=' * 89)