Upload model_baseline.py
Browse files- model_baseline.py +169 -0
model_baseline.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Standard Transformer baseline for comparison with DTAT
|
3 |
+
Based on NanoGPT architecture with optimizations for enwik8
|
4 |
+
"""
|
5 |
+
|
6 |
+
import math
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
import torch.nn.functional as F
|
10 |
+
|
11 |
+
class CausalSelfAttention(nn.Module):
|
12 |
+
def __init__(self, config):
|
13 |
+
super().__init__()
|
14 |
+
assert config.n_embd % config.n_head == 0
|
15 |
+
|
16 |
+
self.n_head = config.n_head
|
17 |
+
self.n_embd = config.n_embd
|
18 |
+
self.dropout = config.dropout
|
19 |
+
self.block_size = config.block_size
|
20 |
+
|
21 |
+
# Key, Query, Value projections
|
22 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
|
23 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
24 |
+
|
25 |
+
# Regularization
|
26 |
+
self.attn_dropout = nn.Dropout(config.dropout)
|
27 |
+
self.resid_dropout = nn.Dropout(config.dropout)
|
28 |
+
|
29 |
+
# Flash attention style computation
|
30 |
+
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
|
31 |
+
.view(1, 1, config.block_size, config.block_size))
|
32 |
+
|
33 |
+
def forward(self, x):
|
34 |
+
B, T, C = x.size()
|
35 |
+
|
36 |
+
# Calculate query, key, values
|
37 |
+
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
|
38 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
39 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
40 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
41 |
+
|
42 |
+
# Causal self-attention
|
43 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
44 |
+
att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
|
45 |
+
att = F.softmax(att, dim=-1)
|
46 |
+
att = self.attn_dropout(att)
|
47 |
+
y = att @ v
|
48 |
+
|
49 |
+
# Re-assemble all head outputs side by side
|
50 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C)
|
51 |
+
|
52 |
+
# Output projection
|
53 |
+
y = self.resid_dropout(self.c_proj(y))
|
54 |
+
return y
|
55 |
+
|
56 |
+
class Block(nn.Module):
|
57 |
+
def __init__(self, config):
|
58 |
+
super().__init__()
|
59 |
+
self.ln_1 = nn.LayerNorm(config.n_embd)
|
60 |
+
self.attn = CausalSelfAttention(config)
|
61 |
+
self.ln_2 = nn.LayerNorm(config.n_embd)
|
62 |
+
self.mlp = nn.Sequential(
|
63 |
+
nn.Linear(config.n_embd, 4 * config.n_embd),
|
64 |
+
nn.GELU(),
|
65 |
+
nn.Linear(4 * config.n_embd, config.n_embd),
|
66 |
+
nn.Dropout(config.dropout),
|
67 |
+
)
|
68 |
+
|
69 |
+
def forward(self, x):
|
70 |
+
x = x + self.attn(self.ln_1(x))
|
71 |
+
x = x + self.mlp(self.ln_2(x))
|
72 |
+
return x
|
73 |
+
|
74 |
+
class BaselineTransformer(nn.Module):
|
75 |
+
def __init__(self, config):
|
76 |
+
super().__init__()
|
77 |
+
assert config.vocab_size is not None
|
78 |
+
assert config.block_size is not None
|
79 |
+
self.config = config
|
80 |
+
|
81 |
+
self.transformer = nn.ModuleDict(dict(
|
82 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
83 |
+
wpe = nn.Embedding(config.block_size, config.n_embd),
|
84 |
+
drop = nn.Dropout(config.dropout),
|
85 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
86 |
+
ln_f = nn.LayerNorm(config.n_embd)
|
87 |
+
))
|
88 |
+
|
89 |
+
# Language modeling head
|
90 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
91 |
+
|
92 |
+
# Initialize weights
|
93 |
+
self.apply(self._init_weights)
|
94 |
+
# Apply special scaled init to the residual projections, per GPT-2 paper
|
95 |
+
for pn, p in self.named_parameters():
|
96 |
+
if pn.endswith('c_proj.weight'):
|
97 |
+
torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
|
98 |
+
|
99 |
+
# Report number of parameters
|
100 |
+
print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
|
101 |
+
|
102 |
+
def get_num_params(self, non_embedding=True):
|
103 |
+
n_params = sum(p.numel() for p in self.parameters())
|
104 |
+
if non_embedding:
|
105 |
+
n_params -= self.transformer.wpe.weight.numel()
|
106 |
+
return n_params
|
107 |
+
|
108 |
+
def _init_weights(self, module):
|
109 |
+
if isinstance(module, nn.Linear):
|
110 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
111 |
+
if module.bias is not None:
|
112 |
+
torch.nn.init.zeros_(module.bias)
|
113 |
+
elif isinstance(module, nn.Embedding):
|
114 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
115 |
+
|
116 |
+
def forward(self, idx, targets=None):
|
117 |
+
device = idx.device
|
118 |
+
b, t = idx.size()
|
119 |
+
assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
|
120 |
+
pos = torch.arange(0, t, dtype=torch.long, device=device)
|
121 |
+
|
122 |
+
# Forward the GPT model itself
|
123 |
+
tok_emb = self.transformer.wte(idx)
|
124 |
+
pos_emb = self.transformer.wpe(pos)
|
125 |
+
x = self.transformer.drop(tok_emb + pos_emb)
|
126 |
+
|
127 |
+
for block in self.transformer.h:
|
128 |
+
x = block(x)
|
129 |
+
x = self.transformer.ln_f(x)
|
130 |
+
|
131 |
+
# Get logits and compute loss
|
132 |
+
logits = self.lm_head(x)
|
133 |
+
|
134 |
+
loss = None
|
135 |
+
if targets is not None:
|
136 |
+
# Calculate loss directly in BPC
|
137 |
+
B, T, C = logits.shape
|
138 |
+
logits = logits.view(B*T, C)
|
139 |
+
targets = targets.view(B*T)
|
140 |
+
loss = F.cross_entropy(logits, targets) * math.log2(math.e)
|
141 |
+
|
142 |
+
return logits, loss
|
143 |
+
|
144 |
+
@torch.no_grad()
|
145 |
+
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
|
146 |
+
"""
|
147 |
+
Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
|
148 |
+
the sequence max_new_tokens times, feeding the predictions back into the model each time.
|
149 |
+
Most likely you'll want to make sure to be in model.eval() mode of operation for this.
|
150 |
+
"""
|
151 |
+
for _ in range(max_new_tokens):
|
152 |
+
# if the sequence context is growing too long we must crop it at block_size
|
153 |
+
idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
|
154 |
+
# forward the model to get the logits for the index in the sequence
|
155 |
+
logits, _ = self(idx_cond)
|
156 |
+
# pluck the logits at the final step and scale by desired temperature
|
157 |
+
logits = logits[:, -1, :] / temperature
|
158 |
+
# optionally crop the logits to only the top k options
|
159 |
+
if top_k is not None:
|
160 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
161 |
+
logits[logits < v[:, [-1]]] = -float('Inf')
|
162 |
+
# apply softmax to convert logits to (normalized) probabilities
|
163 |
+
probs = F.softmax(logits, dim=-1)
|
164 |
+
# sample from the distribution
|
165 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
166 |
+
# append sampled index to the running sequence
|
167 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
168 |
+
|
169 |
+
return idx
|