generated from fkodom/python-repo-template
-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtransformer.py
358 lines (320 loc) · 12.6 KB
/
transformer.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
from math import log
from typing import Callable, Optional, Union
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from torch.nn.modules.transformer import _get_activation_fn
from torchscale.component.xpos_relative_position import XPOS
from grouped_query_attention_pytorch.attention import MultiheadGQA
class GQATransformerEncoderLayer(nn.Module):
# NOTE: Mostly pulled from 'nn.TransformerEncoderLayer', but with changes:
# - use sub-LayerNorm like in MAGNETO. See: https://arxiv.org/abs/2210.06423
# - use MultiheadGQA instead of MultiheadAttention
def __init__(
self,
d_model: int,
nhead: int,
kv_heads: int,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
layer_norm_eps: float = 1e-5,
gamma_init: float = 1.0,
device: Optional[Union[torch.device, str]] = None,
dtype: Optional[torch.dtype] = None,
) -> None:
super().__init__()
# Legacy string support for activation function.
if isinstance(activation, str):
activation = _get_activation_fn(activation)
self.activation = activation
self.gamma_init = gamma_init
self.dropout = nn.Dropout(dropout)
# Self-attention block
self.norm1 = nn.LayerNorm(
d_model, eps=layer_norm_eps, device=device, dtype=dtype
)
self.self_attn = MultiheadGQA( # type: ignore
embed_dim=d_model,
query_heads=nhead,
kv_heads=kv_heads,
dropout=dropout,
layer_norm=True,
layer_norm_eps=layer_norm_eps,
gamma_init=gamma_init,
device=device,
dtype=dtype,
)
# Feedforward block
self.norm2 = nn.LayerNorm(
d_model, eps=layer_norm_eps, device=device, dtype=dtype
)
self.linear1 = nn.Linear(d_model, dim_feedforward, device=device, dtype=dtype)
self.norm3 = nn.LayerNorm(
dim_feedforward, eps=layer_norm_eps, device=device, dtype=dtype
)
self.linear2 = nn.Linear(dim_feedforward, d_model, device=device, dtype=dtype)
self._reset_parameters()
def _reset_parameters(self):
# NOTE: We follow the initialization strategy from MAGNETO. See:
# https://arxiv.org/pdf/2210.06423.pdf, Fig. 2
# The 'MultiheadGQA' module uses ths same initialization,
# so we just need to worry about the 'Linear' modules here.
nn.init.xavier_normal_(self.linear1.weight, gain=self.gamma_init)
nn.init.constant_(self.linear1.bias, 0)
nn.init.xavier_normal_(self.linear2.weight, gain=self.gamma_init)
nn.init.constant_(self.linear2.bias, 0)
def _self_attention_block(self, x: Tensor, is_causal: bool = False) -> Tensor:
x = self.norm1(x)
x, _ = self.self_attn(x, x, x, is_causal=is_causal)
x = self.dropout(x)
return x
def _feedforward_block(self, x: Tensor) -> Tensor:
x = self.norm2(x)
x = self.activation(self.linear1(x))
x = self.dropout(x)
x = self.norm3(x)
x = self.linear2(x)
x = self.dropout(x)
return x
def forward(self, src: Tensor, is_causal: bool = False) -> Tensor:
x = src
x = x + self._self_attention_block(x, is_causal=is_causal)
x = x + self._feedforward_block(x)
return x
class GQATransformerDecoderLayer(nn.Module):
# NOTE: Mostly pulled from 'nn.TransformerDecoderLayer', but with changes:
# - use sub-LayerNorm like in MAGNETO. See: https://arxiv.org/abs/2210.06423
# - use MultiheadGQA instead of MultiheadAttention
def __init__(
self,
d_model: int,
nhead: int,
kv_heads: int,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
layer_norm_eps: float = 1e-5,
gamma_init: float = 1.0,
device: Optional[Union[torch.device, str]] = None,
dtype: Optional[torch.dtype] = None,
) -> None:
super().__init__()
# Legacy string support for activation function.
if isinstance(activation, str):
activation = _get_activation_fn(activation)
self.activation = activation
self.gamma_init = gamma_init
self.dropout = nn.Dropout(dropout)
# Self-attention block
self.norm1 = nn.LayerNorm(
d_model, eps=layer_norm_eps, device=device, dtype=dtype
)
self.self_attn = MultiheadGQA( # type: ignore
embed_dim=d_model,
query_heads=nhead,
kv_heads=kv_heads,
dropout=dropout,
layer_norm=False,
gamma_init=gamma_init,
device=device,
dtype=dtype,
)
# Multi-head attention block
self.norm2 = nn.LayerNorm(
d_model, eps=layer_norm_eps, device=device, dtype=dtype
)
self.multihead_attn = MultiheadGQA( # type: ignore
embed_dim=d_model,
query_heads=nhead,
kv_heads=kv_heads,
dropout=dropout,
layer_norm_eps=layer_norm_eps,
gamma_init=gamma_init,
device=device,
dtype=dtype,
)
# Feedforward block
self.norm3 = nn.LayerNorm(
d_model, eps=layer_norm_eps, device=device, dtype=dtype
)
self.linear1 = nn.Linear(d_model, dim_feedforward, device=device, dtype=dtype)
self.norm4 = nn.LayerNorm(
dim_feedforward, eps=layer_norm_eps, device=device, dtype=dtype
)
self.linear2 = nn.Linear(dim_feedforward, d_model, device=device, dtype=dtype)
self._reset_parameters()
def _reset_parameters(self):
# NOTE: We follow the initialization strategy from MAGNETO. See:
# https://arxiv.org/pdf/2210.06423.pdf, Fig. 2
# The 'MultiheadGQA' module uses ths same initialization,
# so we just need to worry about the 'Linear' modules here.
nn.init.xavier_normal_(self.linear1.weight, gain=self.gamma_init)
nn.init.constant_(self.linear1.bias, 0)
nn.init.xavier_normal_(self.linear2.weight, gain=self.gamma_init)
nn.init.constant_(self.linear2.bias, 0)
def _self_attention_block(self, x: Tensor, is_causal: bool = False) -> Tensor:
x = self.norm1(x)
x, _ = self.self_attn(x, x, x, is_causal=is_causal)
x = self.dropout(x)
return x
def _multihead_attention_block(
self, x: Tensor, memory: Tensor, is_causal: bool = False
) -> Tensor:
x = self.norm2(x)
x, _ = self.multihead_attn(x, memory, memory, is_causal=is_causal)
x = self.dropout(x)
return x
def _feedforward_block(self, x: Tensor) -> Tensor:
x = self.norm3(x)
x = self.activation(self.linear1(x))
x = self.dropout(x)
x = self.norm4(x)
x = self.linear2(x)
x = self.dropout(x)
return x
def forward(
self,
tgt: Tensor,
memory: Tensor,
tgt_is_causal: bool = False,
memory_is_causal: bool = False,
) -> Tensor:
x = tgt
x = x + self._self_attention_block(x, is_causal=tgt_is_causal)
x = x + self._multihead_attention_block(x, memory, is_causal=memory_is_causal)
x = x + self._feedforward_block(x)
return x
class GQATransformer(nn.Module):
def __init__(
self,
d_model: int = 512,
nhead: int = 8,
kv_heads: int = 4,
num_encoder_layers: int = 6,
num_decoder_layers: int = 6,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
layer_norm_eps: float = 1e-5,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
):
super().__init__()
# The 'gamma_init' parameters are different for the encoder and decoder,
# and depend on the number of encoder/decoder layers. See MAGNETO paper:
# https://arxiv.org/pdf/2210.06423.pdf, Figure 2
encoder_gamma_init = (
log(3 * num_decoder_layers) * log(2 * num_encoder_layers) / 3
) ** 0.5
decoder_gamma_init = log(3 * num_decoder_layers) ** 0.5
self.encoder = nn.TransformerEncoder(
encoder_layer=GQATransformerEncoderLayer(
d_model=d_model,
nhead=nhead,
kv_heads=kv_heads,
dim_feedforward=dim_feedforward,
dropout=dropout,
activation=activation,
layer_norm_eps=layer_norm_eps,
gamma_init=encoder_gamma_init,
device=device,
dtype=dtype,
),
num_layers=num_encoder_layers,
mask_check=False,
enable_nested_tensor=False,
)
self.decoder = nn.TransformerDecoder(
decoder_layer=GQATransformerDecoderLayer(
d_model=d_model,
nhead=nhead,
kv_heads=kv_heads,
dim_feedforward=dim_feedforward,
dropout=dropout,
activation=activation,
layer_norm_eps=layer_norm_eps,
gamma_init=decoder_gamma_init,
device=device,
dtype=dtype,
),
num_layers=num_decoder_layers,
)
def forward(self, x: Tensor, is_causal: bool = True) -> Tensor:
"""
Input shape: (batch_size, seq_len, d_model)
Output shape: (batch_size, seq_len, d_model)
NOTE: Assume that 'is_causal' applies to both the encoder and decoder.
This is the case for language modeling, but maybe not for other tasks.
"""
tgt = x
for layer in self.encoder.layers:
x = layer(x, is_causal=is_causal)
if self.encoder.norm is not None:
x = self.encoder.norm(x)
mem = x
for layer in self.decoder.layers:
tgt = layer(tgt, mem, memory_is_causal=is_causal, tgt_is_causal=is_causal)
if self.decoder.norm is not None:
tgt = self.decoder.norm(tgt)
return tgt
class GQATransformerLM(nn.Module):
def __init__(
self,
num_tokens: int, # (required) usually obtained from the tokenizer
d_model: int = 512,
nhead: int = 8,
kv_heads: int = 4,
num_encoder_layers: int = 6,
num_decoder_layers: int = 6,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
layer_norm_eps: float = 1e-5,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
):
super().__init__()
self.token_embedding = nn.Embedding(
num_tokens, d_model, device=device, dtype=dtype
)
# TODO: Add support for other positional encodings? I use XPOS, which is the
# "latest and greatest" at the time of writing. In principle, we could swap
# it out for any other encoding, and remove the 'torchscale' dependency for this
# repo, which is only used for XPOS.
self.pos_embedding = XPOS(d_model).to(device=device, dtype=dtype)
self.transformer = GQATransformer(
d_model=d_model,
nhead=nhead,
kv_heads=kv_heads,
num_encoder_layers=num_encoder_layers,
num_decoder_layers=num_decoder_layers,
dim_feedforward=dim_feedforward,
dropout=dropout,
activation=activation,
layer_norm_eps=layer_norm_eps,
device=device,
dtype=dtype,
)
self.norm = nn.LayerNorm(
d_model, eps=layer_norm_eps, device=device, dtype=dtype
)
self.out = nn.Linear(d_model, num_tokens, device=device, dtype=dtype)
def _reset_parameters(self):
nn.init.kaiming_normal_(self.out.weight)
nn.init.constant_(self.out.bias, 0)
def forward(self, x: Tensor, is_causal: bool = True) -> Tensor:
x = self.token_embedding(x)
x = x + self.pos_embedding(x)
x = self.transformer(x, is_causal=is_causal)
x = self.norm(x)
return self.out(x)
if __name__ == "__main__":
num_tokens = 2048
device = torch.device("cuda")
dtype = torch.float16
x = torch.randint(0, num_tokens - 1, size=(2, 512), device=device)
model = GQATransformerLM(num_tokens=num_tokens, device=device, dtype=dtype)
with torch.no_grad():
out = model(x)
print(out.shape)