-
Notifications
You must be signed in to change notification settings - Fork 10
/
model.py
257 lines (205 loc) · 7.98 KB
/
model.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
"""Training implementation."""
from dataclasses import dataclass
from typing import Optional
import torch
import torch.utils.checkpoint
from torch import nn as nn
from torch.nn import functional as F
@dataclass
class ModelConfig:
d_model: int
n_heads: int
n_layers: int
ff_mult: int
drop_p: float
max_seq_len: int
grad_checkpoint: bool
vocab_size: Optional[int] = None
def set_vocab_size(self, vocab_size: int):
self.vocab_size = vocab_size
class FusedEncoderBlock(nn.Module):
def __init__(self, model_config: ModelConfig):
super().__init__()
self.drop_p = model_config.drop_p
self.n_heads = model_config.n_heads
self.d_head = model_config.d_model // model_config.n_heads
self.max_seq_len = model_config.max_seq_len
# Attention
self.mixed_qkv = nn.Linear(
in_features=model_config.d_model,
out_features=3 * model_config.d_model,
bias=False,
)
self.att_proj_linear = nn.Linear(
in_features=model_config.d_model,
out_features=model_config.d_model,
)
self.resid_dropout = nn.Dropout(model_config.drop_p)
# FF Layer
self.ff_dropout = nn.Dropout(model_config.drop_p)
self.ff_linear_1 = nn.Linear(
in_features=model_config.d_model,
out_features=model_config.d_model * model_config.ff_mult,
)
self.ff_linear_2 = nn.Linear(
in_features=model_config.d_model * model_config.ff_mult,
out_features=model_config.d_model,
)
self.ff_activation = nn.GELU()
# Pre layer norms
self.norm1 = nn.LayerNorm(model_config.d_model)
self.norm2 = nn.LayerNorm(model_config.d_model)
def forward(self, x: torch.Tensor, freqs_cis: torch.Tensor):
x = x + self._att_block(self.norm1(x), freqs_cis)
x = x + self._ff_block(self.norm2(x))
return x
def _att_block(self, x: torch.Tensor, freqs_cis: torch.Tensor):
batch_size, seq_len, _ = x.shape
mixed_qkv = self.mixed_qkv(x)
xq, xk, xv = mixed_qkv.chunk(3, -1)
# Reshape for rotary embeddings
# Need contiguous for q, k since in-place RoPE cannot be applied on a view
xq = xq.reshape(
batch_size, seq_len, self.n_heads, self.d_head
).contiguous()
xk = xk.reshape(
batch_size, seq_len, self.n_heads, self.d_head
).contiguous()
xv = xv.view(batch_size, seq_len, self.n_heads, self.d_head)
# apply_rotary_post_emb expects: (b_sz, s_len, n_head, d_head)
xq = apply_rotary_emb(xq, freqs_cis)
xk = apply_rotary_emb(xk, freqs_cis)
xq, xk, xv = map(lambda t: t.transpose(1, 2), (xq, xk, xv))
# scaled_dot_product_attention expects: (b_sz, n_head, s_len, d_head)
att = F.scaled_dot_product_attention(
query=xq,
key=xk,
value=xv,
is_causal=True,
)
# Reshape for out: (b_sz, s_len, n_head, d_head)
out = att.transpose(1, 2).contiguous()
out = out.view(batch_size, seq_len, self.n_heads * self.d_head)
return self.resid_dropout(self.att_proj_linear(out))
def _ff_block(self, x: torch.Tensor):
x = self.ff_linear_2(self.ff_activation(self.ff_linear_1(x)))
return self.ff_dropout(x)
class Transformer(nn.Module):
"""Transformer decoder with no language model head.
Args:
model_config (ModelConfig): Model config settings.
"""
def __init__(self, model_config: ModelConfig):
super().__init__()
self.model_config = model_config
self.freqs_cis = None
self.tok_embeddings = nn.Embedding(
num_embeddings=model_config.vocab_size,
embedding_dim=model_config.d_model,
)
self.out_layer_norm = nn.LayerNorm(model_config.d_model)
self.encode_layers = nn.ModuleList()
for _ in range(model_config.n_layers):
self.encode_layers.append(FusedEncoderBlock(model_config))
def forward(
self,
src: torch.Tensor,
):
"""Forward pass of Transformer.
Args:
src (torch.tensor): Input to encoder block, of shape (batch_size,
seq_len, d_model).
attn_mask (Optional[torch.tensor]): Attention mask of shape
(batch_size, seq_len). Defaults to None.
past_kv (Optional[list[KVCache]]): a list of kv caches. The list index
corresponds to the layer index.
Returns:
torch.tensor: Model outputs with shape (batch_size, seq_len,
d_model).
"""
hidden_states = self.tok_embeddings(src)
if self.freqs_cis is None:
self.freqs_cis = precompute_freqs_cis(
seq_len=self.model_config.max_seq_len,
n_elem=self.model_config.d_model // self.model_config.n_heads,
base=10000,
dtype=hidden_states.dtype,
).to(src.device)
freqs_cis = self.freqs_cis[: src.shape[1]]
if self.model_config.grad_checkpoint is True:
for layer in self.encode_layers:
def create_custom_forward(module):
def custom_forward(*args):
return module(*args)
return custom_forward
hidden_states = torch.utils.checkpoint.checkpoint(
create_custom_forward(layer),
hidden_states,
freqs_cis,
preserve_rng_state=True,
use_reentrant=True,
)
else:
for layer in self.encode_layers:
hidden_states = layer(hidden_states, freqs_cis=freqs_cis)
return self.out_layer_norm(hidden_states)
class TransformerLM(nn.Module):
"""Transformer decoder with head for language modelling.
Args:
model_config (ModelConfig): Model config settings.
"""
def __init__(self, model_config: ModelConfig):
super().__init__()
self.max_seq_len = model_config.max_seq_len
self.model = Transformer(model_config)
self.lm_head = nn.Linear(
model_config.d_model, model_config.vocab_size, bias=False
)
def forward(
self,
src: torch.Tensor,
):
"""Forward pass of Transformer decoder with LM head.
Args:
src (torch.tensor): Input to encoder block, of shape (batch_size,
seq_len, d_model).
attn_mask (Optional[torch.tensor]): Attention mask of shape
(batch_size, seq_len). Defaults to None.
past_kv (Optional[list[KVCache]]): a list of kv caches. The list index
corresponds to the layer index.
Returns:
torch.tensor: Forward pass of src through Transformer and LM head.
Has shape (batch_size, seq_len, vocab_size).
"""
hidden = self.model(src)
logits = self.lm_head(hidden)
return logits
def precompute_freqs_cis(
seq_len: int,
n_elem: int,
base: int = 10000,
dtype: torch.dtype = torch.bfloat16,
):
freqs = 1.0 / (
base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem)
)
t = torch.arange(seq_len, device=freqs.device)
freqs = torch.outer(t, freqs)
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
return cache.to(dtype=dtype)
@torch.jit.script
def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
"""
In-place RoPE. Credits to Katherine Crowson:
x shape (b_sz, s_len, n_head, d_head).
cos, sin shape (s_len, d_head // 2).
"""
d = x.shape[-1] // 2
cos = freqs_cis[..., 0][None, :, None]
sin = freqs_cis[..., 1][None, :, None]
x1, x2 = x[..., :d], x[..., d : d * 2]
tmp = x1.clone()
x1.mul_(cos).addcmul_(x2, sin, value=-1)
x2.mul_(cos).addcmul_(tmp, sin, value=1)
return x