-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsample.py
247 lines (196 loc) · 9.81 KB
/
sample.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
# Sam Greydanus | 2024
########## IMPORTS AND A FEW GLOBAL VARIABLES ##########
import os, sys, time, getpass, textwrap, copy
import numpy as np
import matplotlib.pyplot as plt
from dataclasses import dataclass
import wandb
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.data import Dataset
from torch.utils.data.dataloader import DataLoader
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from model import Transformer, get_checkpoint, get_all_args
from data import create_datasets, offsets_to_strokes
def plot_strokes(stroke, title, fig=None, ax=None, figsize=(12, 2), dpi=150):
"""Plot a single stroke"""
if fig is None or ax is None:
fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
# Separate strokes based on pen lifts
strokes = []
current_stroke = []
for point in stroke:
if point[2] == 1: # Pen is down
current_stroke.append(point)
else: # Pen is up
if current_stroke:
strokes.append(current_stroke)
current_stroke = []
if current_stroke:
strokes.append(current_stroke)
# Plot each stroke
for stroke in strokes:
x, y = zip(*[(p[0], 1 - p[1]) for p in stroke]) # Invert y-axis
ax.plot(x, y, 'b-', linewidth=1.3)
ax.set_aspect('equal') ; ax.set_title(title)
if fig is None: plt.show()
return fig, ax
@torch.no_grad()
def generate(model, idx, context, max_new_tokens, temperature=1.0, do_sample=False, top_k=None):
"""
Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
the sequence max_new_tokens times, feeding the predictions back into the model each time.
Most likely you'll want to make sure to be in model.eval() mode of operation for this.
"""
block_size = model.get_block_size()
steps = max(0, max_new_tokens-idx.size(1))
for i in range(steps):
# if the sequence context is growing too long we must crop it at block_size
idx_cond = idx if idx.size(1) <= block_size else idx[:, -block_size:]
# forward the model to get the logits for the index in the sequence
logits, _ = model(idx_cond, context)
# pluck the logits at the final step and scale by desired temperature
logits = logits[:, -1, :] / temperature
# optionally crop the logits to only the top k options
if top_k is not None:
v, _ = torch.topk(logits, top_k)
logits[logits < v[:, [-1]]] = -float('Inf')
# apply softmax to convert logits to (normalized) probabilities
probs = F.softmax(logits, dim=-1)
# either sample from the distribution or take the most likely element
if do_sample:
idx_next = torch.multinomial(probs, num_samples=1)
else:
_, idx_next = torch.topk(probs, k=1, dim=-1)
# append sampled index to the running sequence and continue
idx = torch.cat((idx, idx_next), dim=1)
return idx
def save_samples(model, dataset, num=2, model_device='cpu', warmup_steps=50, do_sample=False, log_wandb=True):
""" samples from the model and plots the decoded strokes """
model_device = next(model.parameters()).device
stroke_seq, context = [], []
for i in range(num):
x, c, y = dataset[i]
stroke_seq.append(x) ; context.append(c)
X_init = torch.stack(stroke_seq).to(model_device)[:,:warmup_steps]
context = torch.stack(context).long().to(model_device)
top_k = None
steps = dataset.get_stroke_seq_length() - 1 # -1 because we already start with the first token
X_samp = generate(model, X_init, context, steps, top_k=top_k, do_sample=do_sample).to('cpu')
for i in range(X_samp.size(0)):
# get the i'th row of sampled integers, as python list
row = X_samp[i].detach().cpu().numpy()
offset_samp = dataset.decode_stroke(row)
point_samp = word_offsets_to_points(offset_samp)
decoded_ascii = dataset.decode_text(context[i])
# Plot the stroke
fig, ax = plot_strokes(point_samp, f'Sample {i+1}: "{decoded_ascii}"') #plt.axis('off')
tag = 'sample' if do_sample else 'topk'
fig.savefig(f"{dataset.name}_{tag}_{i+1}.png")
if log_wandb:
wandb.log({f"{dataset.name}_{tag}_{i+1}": wandb.Image(f"{dataset.name}_{tag}_{i+1}.png")})
plt.close(fig)
print(f"Saved {dataset.name}_{tag}_{i+1}.png")
print('-'*80)
def generate_helper_fn(model, dataset, word_list, num_steps=1250, do_sample=False,
top_k=None, temperature=1.0, n_words=4, seed_ix=0, verbose=False):
'''Assumes we're using tokenization of git commit afc2425f5bf92c14a9db62da44e8cf2995e7bf8d'''
seed_ix = 0
SEED_TOKENS = [torch.tensor(
[411, 0, 396, 12, 393, 20, 384, 42, 384, 14, 378, 21, 376,
17, 376, 18, 367, 11, 354, 12, 494, 14, 481, 16, 483, 11,
486, 18, 486, 18, 481, 16, 477, 11, 477, 16, 458, 13, 417,
13, 396, 12, 385, 18, 372, 16, 367, 5, 411, 9, 396, 18,
421, 9, 477, 16, 484, 12, 471, 15, 400, 16, 383, 20, 388,
12, 379, 7, 477, 16, 471, 15, 421, 9, 396, 18, 380, 19,
372, 16, 403, 11, 411, 14, 453, 11, 482, 16, 477, 11, 411,
14, 391, 18, 380, 19, 374, 11, 481, 16, 477, 16, 441, 13,
411, 9, 391, 18, 380, 19, 381, 23, 378, 15, 376, 17, 376,
18, 372, 16, 367, 11, 333, 16, 481, 16, 477, 11, 477, 16,
477, 21, 477, 18, 482, 31, 481, 16, 383, 10, 374, 11, 383,
20, 391, 18, 419, 11, 469, 10, 477, 16, 461, 20, 388, 20,
411, 151, 524], dtype=torch.int64),
torch.tensor(
[411, 0, 499, 12, 494, 39, 485, 11, 490, 21, 478, 15, 478,
10, 473, 14, 449, 13, 423, 14, 404, 11, 385, 20, 374, 16,
350, 9, 313, 14, 515, 16, 499, 16, 411, 151, 524],
dtype=torch.int64)][seed_ix]
SEED_CHARS = ["bwuh", "6"][seed_ix]
model_device = next(model.parameters()).device
warmup_steps = len(SEED_TOKENS)
def trunc_or_pad_words(word_list):
n = len(word_list)
if n > n_words:
if verbose: print(f"Expected {n_words} words, got {n}; truncating")
return word_list[:n_words-1]
elif n < n_words:
if verbose: print(f"Expected {n_words} words, got {n}; padding with 'hello'")
return word_list + ['Hkggcvr!', 'TOLAPYPI', '9074', '0.', 'efhgb.'][:max(0, n_words-n-1)]
return word_list
word_list = trunc_or_pad_words(word_list)
text = ' '.join(word_list)
ascii_context = f'{SEED_CHARS} {text}' #print(ascii_context)
context = dataset.encode_text(ascii_context).unsqueeze(0)
context = context.to(model_device)
X_init = SEED_TOKENS.unsqueeze(0).to(model_device)
steps = num_steps - X_init.size(1)
X_samp = generate(model, X_init, context, steps, temperature=temperature,
top_k=top_k, do_sample=do_sample).to('cpu')
stroke_seq = X_samp[0].detach().cpu().numpy()[len(SEED_TOKENS):]
offset_samp = dataset.decode_stroke(stroke_seq)
return offset_samp
def generate_paragraph(model, dataset, text, n_at_a_time=3, **kwargs):
word_list = text.strip(' ').split(' ')
word_list_offsets = []
print('Generating...')
for i in range(0, len(word_list), n_at_a_time):
word_list_subset = word_list[i:i+n_at_a_time]
offset_sample = generate_helper_fn(model, dataset, word_list_subset, **kwargs)
word_list_offsets += offset_sample[:len(word_list_subset)]
print(' ', ' '.join(word_list_subset))
return word_list_offsets
def word_offsets_to_points(word_offsets, word_list=None, space_width=0.14, line_width=10.0, line_height=0.40,
letter_height=0.35): # Add bounds parameters
word_points = []
last_point = None
current_x = current_y = 0
starts_at_bottom = "enaitoshrdx.vpukbgfcymzwlqjS,GJ"
starts_at_top = "8049637OTA5N)EHR\"\'(BCQLMWYUF!DXVKP" # starts_elsewhere = "1I2Z?"
sentence_points = []
for i, offsets in enumerate(word_offsets):
points = offsets_to_strokes(copy.deepcopy(offsets))
if word_list:
word = word_list[i]
if word[0] in starts_at_bottom:
points[:,1] -= points[0,1] # # print('Was at the bottom')
elif word[0] in starts_at_top:
points[:,1] -= points[0,1] + 0.18 #pass #
if current_x > line_width:
current_x = 0
current_y += line_height
if points is not None and points.shape[0] > 0:
points[:,0] = points[:,0] + current_x
points[:,1] = np.clip(points[:,1], -letter_height, letter_height) + current_y
current_x = points[-1, 0] + space_width
sentence_points.append(points)
return np.vstack(sentence_points)
def plot_paragraph(word_list_offsets, text, figsize=(12, 4*2), dpi=200, **kwargs):
point_samp = word_offsets_to_points(word_list_offsets, **kwargs)
fig, ax = plot_strokes(point_samp, '', figsize=figsize, dpi=dpi)
ax.set_title('\n'.join(textwrap.wrap(text, width=83)), loc='left', fontsize=13)
########## ARGS, LOGGING, AND TRAIN LOOP ##########
if __name__ == '__main__':
args = get_all_args()
torch.manual_seed(args.seed) # system inits
torch.cuda.manual_seed_all(args.seed)
train_dataset, test_dataset = create_datasets(args) # init datasets
args.block_size = train_dataset.get_stroke_seq_length()
args.context_block_size = train_dataset.get_text_seq_length()
args.vocab_size = train_dataset.get_vocab_size()
args.context_vocab_size = train_dataset.get_char_vocab_size()
print(f"Dataset determined that: {args.vocab_size=}, {args.block_size=}")
model, optimizer, scheduler, step, best_loss = get_checkpoint(args, sample_only=True)
save_samples(model, test_dataset, num=6, do_sample=True, log_wandb=False)
save_samples(model, test_dataset, num=6, do_sample=False, log_wandb=False)
sys.exit()