Repository navigation
Expand file tree
/
Copy pathtrain.py
More file actions
503 lines (375 loc) · 12.5 KB
/
Copy pathtrain.py
File metadata and controls
503 lines (375 loc) · 12.5 KB
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
"""
TinyGPT training
Trains TinyGPT on the training sentences and saves it to model.npz.
- Saves to model.npz after every epoch (survives a reboot)
- Ctrl+C saves the weights up to the current step
- Re-running resumes from the epoch after the saved one
- Retrains from scratch if the sentences or architecture change
Usage:
python train.py
python train.py --epochs 500 # continue the saved model up to 500 epochs
python train.py --retrain # start over from scratch
Sentence generation (inference): generate.py
"""
import argparse
import signal
from pathlib import Path
import numpy as np
from tinygpt import (
TinyGPT,
Adam,
build_dataset,
save_state,
load_state
)
# ====================================================================
# Training
# ====================================================================
def train(
model,
data,
epochs=1000,
lr=2e-3,
print_every=100,
checkpoint_dir=None,
checkpoint_every=1,
optimizer=None,
start_epoch=1,
state_path=None,
sentences=None
):
# ---------------------------------------------------------------
# If state_path is given, the training state is saved after every epoch.
#
# Ctrl+C finishes the current step, saves, and stops.
# (Press it again to force quit; the last epoch's state is still kept.)
#
# Returns True if training finished, False if it was interrupted.
# ---------------------------------------------------------------
# Save the model parameters every checkpoint_every epochs when a
# checkpoint directory is provided. Each .npz file contains every
# array in model.p, using the parameter names as keys.
if checkpoint_dir is not None:
checkpoint_dir = Path(
checkpoint_dir
)
checkpoint_dir.mkdir(
parents=True,
exist_ok=True
)
if optimizer is None:
optimizer = Adam(
model.p,
lr=lr
)
# ---------------------------------------------------------------
# Ctrl+C handler
# ---------------------------------------------------------------
stop = {"requested": False}
def request_stop(signum, frame):
if stop["requested"]:
raise KeyboardInterrupt
stop["requested"] = True
print(
"\nStop requested: finishing the current step and saving. "
"(Force quit: press Ctrl+C again)"
)
previous_handler = signal.signal(
signal.SIGINT,
request_stop
)
try:
for epoch in range(
start_epoch,
epochs + 1
):
# Random sentence order
order = np.random.permutation(
len(data)
)
total_loss = 0.0
for idx in order:
sequence = data[idx]
# ----------------------------------------------------
# Example:
#
# [BOS, i, like, cats, EOS]
#
# input:
#
# [BOS, i, like, cats]
#
# target:
#
# [i, like, cats, EOS]
# ----------------------------------------------------
input_ids = sequence[:-1]
target_ids = sequence[1:]
# ----------------------------------------------------
# Forward + backward
# ----------------------------------------------------
loss, grads = (
model.loss_and_backward(
input_ids,
target_ids
)
)
# ----------------------------------------------------
# Parameter update
# ----------------------------------------------------
optimizer.step(
model.p,
grads,
clip_norm=1.0
)
total_loss += loss
if stop["requested"]:
break
# --------------------------------------------------------
# Interrupted in the middle of this epoch
#
# Save the weights including the last step,
# but record only the previous epoch as completed.
# (the next run resumes from this epoch)
# --------------------------------------------------------
if stop["requested"]:
if state_path is not None:
save_state(
state_path,
model,
optimizer,
epoch - 1,
sentences
)
print(
f"Interrupted during epoch {epoch} -> "
f"saved to {Path(state_path).name}."
)
return False
# --------------------------------------------------------
# Training state (every epoch)
# --------------------------------------------------------
if state_path is not None:
save_state(
state_path,
model,
optimizer,
epoch,
sentences
)
# --------------------------------------------------------
# Epoch checkpoint
# --------------------------------------------------------
if (
checkpoint_dir is not None
and
epoch % checkpoint_every == 0
):
checkpoint_path = (
checkpoint_dir
/ f"epoch_{epoch:04d}.npz"
)
np.savez_compressed(
checkpoint_path,
**model.p
)
# --------------------------------------------------------
# Print loss
# --------------------------------------------------------
if (
epoch == start_epoch
or
epoch % print_every == 0
):
average_loss = (
total_loss
/
len(data)
)
print(
f"epoch {epoch:4d} "
f"| loss {average_loss:.4f}"
)
finally:
signal.signal(
signal.SIGINT,
previous_handler
)
return True
# ====================================================================
# Main
# ====================================================================
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="TinyGPT training"
)
parser.add_argument(
"--epochs",
type=int,
default=700,
help="target number of epochs (continues if the saved model has fewer)"
)
parser.add_argument(
"--retrain",
action="store_true",
help="ignore the saved model and train from scratch"
)
args = parser.parse_args()
# ================================================================
# 1. Training corpus
# ================================================================
sentences = [
"the cat sleeps on the warm sofa every afternoon",
"the cat chases a small mouse in the kitchen",
"our cat likes to sit by the window",
"the dog runs in the park with a red ball",
"the dog barks loudly when the mailman comes",
"my brother plays soccer with his friends after school",
"my sister reads a book in her room at night",
"my mother makes bread in the kitchen every saturday",
"my father reads the newspaper after breakfast",
"i drink a cup of coffee every morning",
"i walk to school with my best friend",
"i like to read books on a rainy day",
"we eat dinner together at seven every evening",
"we go to the beach in the summer",
"we like to watch the stars at night",
"she cooks pasta for her family on sunday",
"she listens to music while she studies",
"he rides his bike to work every day",
"he watches a movie with his wife on friday",
"they visit their grandparents every winter",
"they play board games at home when it rains",
"the children play in the garden after lunch",
"the children sing a song in the classroom",
"the students study hard for the final exam",
"the students eat lunch in the school cafeteria",
"the teacher writes a long sentence on the board",
"the teacher gives us homework every weekend",
"the little girl draws a picture of her dog",
"the old man walks slowly along the river",
"the baby sleeps quietly in a small bed",
"the farmer grows rice and vegetables in his field",
"the doctor helps sick people at the hospital",
"the sun rises early in the summer morning",
"the rain falls softly on the old roof",
"the birds sing in the tall trees at dawn",
"the train leaves the station at eight in the morning",
]
# ================================================================
# 2. Tokenization
# ================================================================
(
token_to_id,
id_to_token,
data
) = build_dataset(
sentences
)
# Maximum sequence length
max_context = max(
len(sequence) - 1
for sequence in data
)
print(
"vocab size:",
len(token_to_id)
)
print(
"max context:",
max_context
)
# ================================================================
# 3. Create GPT
# ================================================================
model = TinyGPT(
vocab_size=len(
token_to_id
),
max_context=max_context,
d_model=64,
n_heads=4,
d_ff=128,
n_layers=2,
seed=42
)
parameter_count = sum(
parameter.size
for parameter in model.p.values()
)
print(
"parameters:",
parameter_count
)
optimizer = Adam(
model.p,
lr=2e-3
)
# ================================================================
# 4. Load saved state
#
# Load model.npz if it exists and matches the sentences / architecture.
# ================================================================
state_path = Path(__file__).with_name(
"model.npz"
)
done_epoch = 0
if not args.retrain:
loaded = load_state(
state_path,
model,
optimizer,
sentences
)
if loaded is not None:
done_epoch = loaded
print(
f"Loaded saved model: {state_path.name} "
f"({done_epoch} epochs trained)"
)
elif state_path.exists():
print(
"Training sentences or architecture changed; training from scratch."
)
# ================================================================
# 5. Train (from scratch or resume)
# ================================================================
if done_epoch >= args.epochs:
print(
f"Already trained for {done_epoch} epochs. "
"To train more, raise --epochs; "
"to start over, add --retrain."
)
else:
print(
f"Training: epoch {done_epoch + 1} -> {args.epochs} "
"(weights are saved even if you press Ctrl+C)"
)
completed = train(
model,
data,
epochs=args.epochs,
print_every=50,
checkpoint_dir=(
Path(__file__).with_name(
"checkpoints_v2"
)
),
checkpoint_every=100,
optimizer=optimizer,
start_epoch=done_epoch + 1,
state_path=state_path,
sentences=sentences
)
if not completed:
print(
"Training was interrupted. "
"Run again to resume."
)
print()
print(
f"Saved to: {state_path}"
)
print(
"Generate sentences: python generate.py"
)