Update
[beaver.git] / beaver.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 # torch.backends.cuda.matmul.allow_tf23
9 # torch.autocast(torch.bfloat16)
10
11 import math, sys, argparse, time, tqdm, itertools, os
12
13 import torch, torchvision
14 from torch import nn
15 from torch.nn import functional as F
16
17 import mygpt, tensorstack
18
19 ######################################################################
20
21 if torch.cuda.is_available():
22     device = torch.device("cuda")
23     torch.backends.cuda.matmul.allow_tf32 = True
24 else:
25     device = torch.device("cpu")
26
27 ######################################################################
28
29 parser = argparse.ArgumentParser(description="A maze shortest path solving with a GPT.")
30
31 parser.add_argument("--log_filename", type=str, default="train.log")
32
33 parser.add_argument("--result_dir", type=str, default="results_default")
34
35 parser.add_argument("--seed", type=int, default=0)
36
37 parser.add_argument("--nb_epochs", type=int, default=25)
38
39 parser.add_argument("--nb_train_samples", type=int, default=200000)
40
41 parser.add_argument("--nb_test_samples", type=int, default=50000)
42
43 parser.add_argument("--batch_size", type=int, default=25)
44
45 parser.add_argument("--optim", type=str, default="adam")
46
47 parser.add_argument("--learning_rate", type=float, default=1e-3)
48
49 parser.add_argument(
50     "--learning_rate_schedule", type=str, default="10: 2e-4,20: 4e-5,30: 8e-6"
51 )
52
53 parser.add_argument("--dim_model", type=int, default=512)
54
55 parser.add_argument("--dim_keys", type=int, default=64)
56
57 parser.add_argument("--dim_hidden", type=int, default=2048)
58
59 parser.add_argument("--nb_heads", type=int, default=8)
60
61 parser.add_argument("--nb_blocks", type=int, default=12)
62
63 parser.add_argument("--dropout", type=float, default=0.1)
64
65 parser.add_argument("--deterministic_synthesis", action="store_true", default=False)
66
67 parser.add_argument("--random_regression_order", action="store_true", default=False)
68
69 parser.add_argument("--no_checkpoint", action="store_true", default=False)
70
71 parser.add_argument("--overwrite_results", action="store_true", default=False)
72
73 parser.add_argument("--checkpoint_name", type=str, default="checkpoint.pth")
74
75 ##############################
76 # maze options
77
78 parser.add_argument("--maze_height", type=int, default=13)
79
80 parser.add_argument("--maze_width", type=int, default=21)
81
82 parser.add_argument("--maze_nb_walls", type=int, default=15)
83
84 ##############################
85 # one-shot prediction
86
87 parser.add_argument("--oneshot", action="store_true", default=False)
88
89 parser.add_argument("--oneshot_input", type=str, default="head")
90
91 parser.add_argument("--oneshot_output", type=str, default="trace")
92
93 ######################################################################
94
95 args = parser.parse_args()
96
97 try:
98     os.mkdir(args.result_dir)
99 except FileExistsError:
100     if not args.overwrite_results:
101         print(f"result directory {args.result_dir} already exists")
102         exit(1)
103
104 log_file = open(os.path.join(args.result_dir, args.log_filename), "a")
105
106 if args.seed >= 0:
107     # torch.backends.cudnn.deterministic = True
108     # torch.backends.cudnn.benchmark = False
109     # torch.use_deterministic_algorithms(True)
110     torch.manual_seed(args.seed)
111     if torch.cuda.is_available():
112         torch.cuda.manual_seed_all(args.seed)
113
114 ######################################################################
115
116
117 def log_string(s):
118     t = time.strftime("%Y%m%d-%H:%M:%S ", time.localtime())
119
120     if log_file is not None:
121         log_file.write(t + s + "\n")
122         log_file.flush()
123
124     print(t + s)
125     sys.stdout.flush()
126
127
128 for n in vars(args):
129     log_string(f"args.{n} {getattr(args, n)}")
130
131 ######################################################################
132
133
134 def generation_order(x, fixed_len):
135     if args.random_regression_order:
136         order = torch.rand(x.size(), device=x.device)
137         order[:, :fixed_len] = torch.linspace(-2, -1, fixed_len, device=order.device)
138         order = order.sort(1).indices
139     else:
140         order = (
141             torch.arange(x.size(1), device=x.device).unsqueeze(0).expand(x.size(0), -1)
142         )
143     return order
144
145
146 def reorder(x, order, back=False):  # x is NxTxD1x...xDk, order is NxT'
147     u = x.reshape(x.size()[:2] + (-1,))
148     order = order.unsqueeze(-1).expand(-1, -1, u.size(-1))
149     if back:
150         v = u.new(u.size())
151         v.scatter_(1, order, u)
152     else:
153         v = u.gather(1, order)
154     v = v.reshape(v.size()[:2] + x.size()[2:])
155     return v
156
157
158 def shuffle(x, fixed_len):
159     order = generation_order(x, fixed_len)
160     return reorder(x, order), order
161
162
163 ######################################################################
164
165 # ar_mask is a Boolean matrix of same shape as input, with 1s on the
166 # tokens that should be generated
167
168
169 def masked_inplace_autoregression(model, batch_size, input, ar_mask, order=None):
170     for input, ar_mask in zip(input.split(batch_size), ar_mask.split(batch_size)):
171         i = (ar_mask.sum(0) > 0).nonzero()
172         if i.min() > 0:
173             # Needed to initialize the model's cache
174             model(mygpt.BracketedSequence(input, 0, i.min()), order=order)
175         for s in range(i.min(), i.max() + 1):
176             output = model(mygpt.BracketedSequence(input, s, 1), order=order).x
177             logits = output[:, s]
178             if args.deterministic_synthesis:
179                 t_next = logits.argmax(1)
180             else:
181                 dist = torch.distributions.categorical.Categorical(logits=logits)
182                 t_next = dist.sample()
183             input[:, s] = ar_mask[:, s] * t_next + (1 - ar_mask[:, s]) * input[:, s]
184
185
186 ######################################################################
187
188
189 def compute_perplexity(model, fixed_len, split="train"):
190     with torch.autograd.no_grad():
191         t = model.training
192         model.eval()
193
194         nb_samples, acc_loss = 0, 0.0
195
196         for input in task.batches(split=split):
197             input = input.to(device)
198             x, order = shuffle(input, fixed_len)
199             x = model(mygpt.BracketedSequence(x), order=order).x
200             output = reorder(x, order, back=True)
201             loss = F.cross_entropy(output.transpose(1, 2), input)
202             acc_loss += loss.item() * input.size(0)
203             nb_samples += input.size(0)
204
205         model.train(t)
206
207         return math.exp(min(100, acc_loss / nb_samples))
208
209
210 ######################################################################
211
212
213 def oneshot_policy_loss(mazes, output, policies, height, width):
214     masks = (mazes == maze.v_empty).unsqueeze(-1)
215     targets = policies.permute(0, 2, 1) * masks
216     output = output * masks
217     return -(output.log_softmax(-1) * targets).sum() / masks.sum()
218
219
220 def oneshot_trace_loss(mazes, output, policies, height, width):
221     masks = mazes == maze.v_empty
222     targets = maze.stationary_densities(
223         mazes.view(-1, height, width), policies.view(-1, 4, height, width)
224     ).flatten(-2)
225     targets = targets * masks
226     output = output.squeeze(-1) * masks
227     return (output - targets).abs().sum() / masks.sum()
228
229
230 def oneshot(gpt, task):
231     t = gpt.training
232     gpt.eval()
233
234     if args.oneshot_input == "head":
235         dim_in = args.dim_model
236     elif args.oneshot_input == "deep":
237         dim_in = args.dim_model * args.nb_blocks * 2
238     else:
239         raise ValueError(f"{args.oneshot_input=}")
240
241     if args.oneshot_output == "policy":
242         dim_out = 4
243         compute_loss = oneshot_policy_loss
244     elif args.oneshot_output == "trace":
245         dim_out = 1
246         compute_loss = oneshot_trace_loss
247     else:
248         raise ValueError(f"{args.oneshot_output=}")
249
250     model = nn.Sequential(
251         nn.Linear(dim_in, args.dim_model),
252         nn.ReLU(),
253         nn.Linear(args.dim_model, args.dim_model),
254         nn.ReLU(),
255         nn.Linear(args.dim_model, dim_out),
256     ).to(device)
257
258     for n_epoch in range(args.nb_epochs):
259         learning_rate = learning_rate_schedule[n_epoch]
260         optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
261
262         acc_train_loss, nb_train_samples = 0, 0
263         for mazes, policies in task.policy_batches(split="train"):
264             x, order = shuffle(mazes, task.height * task.width)
265             x = gpt(mygpt.BracketedSequence(x), mode=args.oneshot_input, order=order).x
266             output_gpt = reorder(x, order, back=True)
267             output = model(output_gpt)
268
269             loss = compute_loss(mazes, output, policies, task.height, task.width)
270             acc_train_loss += loss.item() * mazes.size(0)
271             nb_train_samples += mazes.size(0)
272
273             optimizer.zero_grad()
274             loss.backward()
275             optimizer.step()
276
277         acc_test_loss, nb_test_samples = 0, 0
278         for mazes, policies in task.policy_batches(split="test"):
279             x, order = shuffle(mazes, task.height * task.width)
280             x = gpt(mygpt.BracketedSequence(x), mode=args.oneshot_input, order=order).x
281             output_gpt = reorder(x, order, back=True)
282             output = model(output_gpt)
283             loss = compute_loss(mazes, output, policies, task.height, task.width)
284             acc_test_loss += loss.item() * mazes.size(0)
285             nb_test_samples += mazes.size(0)
286
287         log_string(
288             f"diff_ce {n_epoch} train {acc_train_loss/nb_train_samples} test {acc_test_loss/nb_test_samples}"
289         )
290
291         # -------------------
292         mazes = task.test_input[:32, : task.height * task.width]
293         policies = task.test_policies[:32]
294         x, order = shuffle(mazes, task.height * task.width)
295         x = gpt(mygpt.BracketedSequence(x), mode=args.oneshot_input, order=order).x
296         output_gpt = reorder(x, order, back=True)
297         output = model(output_gpt)
298         if args.oneshot_output == "policy":
299             targets = policies.permute(0, 2, 1)
300             scores = (
301                 (F.one_hot(output.argmax(-1), num_classes=4) * targets).sum(-1) == 0
302             ).float()
303         elif args.oneshot_output == "trace":
304             targets = maze.stationary_densities(
305                 mazes.view(-1, task.height, task.width),
306                 policies.view(-1, 4, task.height, task.width),
307             ).flatten(-2)
308             scores = output
309         else:
310             raise ValueError(f"{args.oneshot_output=}")
311
312         scores = scores.reshape(-1, task.height, task.width)
313         mazes = mazes.reshape(-1, task.height, task.width)
314         targets = targets.reshape(-1, task.height, task.width)
315         filename = (
316             f"oneshot_{args.oneshot_input}_{args.oneshot_output}_{n_epoch:04d}.png"
317         )
318         maze.save_image(
319             os.path.join(args.result_dir, filename),
320             mazes=mazes,
321             score_paths=scores,
322             score_truth=targets,
323         )
324         log_string(f"wrote {filename}")
325
326         # -------------------
327
328     gpt.train(t)
329
330
331 ######################################################################
332
333
334 class Task:
335     def batches(self, split="train", nb_to_use=-1, desc=None):
336         pass
337
338     def vocabulary_size(self):
339         pass
340
341     def produce_results(self, n_epoch, model):
342         pass
343
344
345 ######################################################################
346
347 import maze
348
349
350 class TaskMaze(Task):
351     def map2seq(self, *m):
352         return torch.cat([x.flatten(1) for x in m], 1)
353
354     def seq2map(self, s):
355         s = s.reshape(s.size(0), -1, self.height, self.width)
356         return (s[:, k] for k in range(s.size(1)))
357
358     def __init__(
359         self,
360         nb_train_samples,
361         nb_test_samples,
362         batch_size,
363         height,
364         width,
365         nb_walls,
366         device=torch.device("cpu"),
367     ):
368         self.batch_size = batch_size
369         self.height = height
370         self.width = width
371         self.device = device
372
373         train_mazes, train_paths, train_policies = maze.create_maze_data(
374             nb_train_samples,
375             height=height,
376             width=width,
377             nb_walls=nb_walls,
378             progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
379         )
380         self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
381         self.train_policies = train_policies.flatten(-2).to(device)
382
383         test_mazes, test_paths, test_policies = maze.create_maze_data(
384             nb_test_samples,
385             height=height,
386             width=width,
387             nb_walls=nb_walls,
388             progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
389         )
390         self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
391         self.test_policies = test_policies.flatten(-2).to(device)
392
393         self.nb_codes = self.train_input.max() + 1
394
395     def batches(self, split="train", nb_to_use=-1, desc=None):
396         assert split in {"train", "test"}
397         input = self.train_input if split == "train" else self.test_input
398         if nb_to_use > 0:
399             input = input[:nb_to_use]
400         if desc is None:
401             desc = f"epoch-{split}"
402         for batch in tqdm.tqdm(
403             input.split(self.batch_size), dynamic_ncols=True, desc=desc
404         ):
405             yield batch
406
407     def policy_batches(self, split="train", nb_to_use=-1, desc=None):
408         assert split in {"train", "test"}
409         input = self.train_input if split == "train" else self.test_input
410         policies = self.train_policies if split == "train" else self.test_policies
411         input = input[:, : self.height * self.width]
412         policies = policies * (input != maze.v_wall)[:, None]
413
414         if nb_to_use > 0:
415             input = input[:nb_to_use]
416             policies = policies[:nb_to_use]
417
418         if desc is None:
419             desc = f"epoch-{split}"
420         for batch in tqdm.tqdm(
421             zip(input.split(self.batch_size), policies.split(self.batch_size)),
422             dynamic_ncols=True,
423             desc=desc,
424         ):
425             yield batch
426
427     def vocabulary_size(self):
428         return self.nb_codes
429
430     def compute_error(self, model, split="train", nb_to_use=-1):
431         nb_total, nb_correct = 0, 0
432         for input in task.batches(split, nb_to_use):
433             result = input.clone()
434             ar_mask = result.new_zeros(result.size())
435             ar_mask[:, self.height * self.width :] = 1
436             result *= 1 - ar_mask
437             x, order = shuffle(result, self.height * self.width)
438             masked_inplace_autoregression(
439                 model, self.batch_size, x, ar_mask, order=order
440             )
441             result = reorder(x, order, back=True)
442             mazes, paths = self.seq2map(result)
443             nb_correct += maze.path_correctness(mazes, paths).long().sum()
444             nb_total += mazes.size(0)
445
446         return nb_total, nb_correct
447
448     def produce_results(self, n_epoch, model):
449         with torch.autograd.no_grad():
450             t = model.training
451             model.eval()
452
453             train_nb_total, train_nb_correct = self.compute_error(
454                 model, "train", nb_to_use=1000
455             )
456             log_string(
457                 f"accuracy_train nb_total {train_nb_total} nb_correct {train_nb_correct} accuracy {(100.0*train_nb_correct)/train_nb_total:.02f}%"
458             )
459
460             test_nb_total, test_nb_correct = self.compute_error(
461                 model, "test", nb_to_use=1000
462             )
463             log_string(
464                 f"accuracy_test nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
465             )
466
467             input = self.test_input[:32]
468             result = input.clone()
469             ar_mask = result.new_zeros(result.size())
470             ar_mask[:, self.height * self.width :] = 1
471             result *= 1 - ar_mask
472             masked_inplace_autoregression(model, self.batch_size, result, ar_mask)
473
474             mazes, paths = self.seq2map(input)
475             _, predicted_paths = self.seq2map(result)
476             filename = f"result_{n_epoch:04d}.png"
477             maze.save_image(
478                 os.path.join(args.result_dir, filename),
479                 mazes=mazes,
480                 target_paths=paths,
481                 predicted_paths=predicted_paths,
482                 path_correct=maze.path_correctness(mazes, predicted_paths),
483             )
484             log_string(f"wrote {filename}")
485
486             model.train(t)
487
488
489 ######################################################################
490
491 log_string(f"device {device}")
492
493
494 task = TaskMaze(
495     nb_train_samples=args.nb_train_samples,
496     nb_test_samples=args.nb_test_samples,
497     batch_size=args.batch_size,
498     height=args.maze_height,
499     width=args.maze_width,
500     nb_walls=args.maze_nb_walls,
501     device=device,
502 )
503
504
505 vocabulary_size = task.vocabulary_size()
506
507 log_string(f"vocabulary_size {vocabulary_size}")
508
509 ##############################
510
511 model = mygpt.MyGPT(
512     vocabulary_size=vocabulary_size,
513     dim_model=args.dim_model,
514     dim_keys=args.dim_keys,
515     dim_hidden=args.dim_hidden,
516     nb_heads=args.nb_heads,
517     nb_blocks=args.nb_blocks,
518     causal=True,
519     dropout=args.dropout,
520 )
521
522 model.to(device)
523
524 nb_parameters = sum(p.numel() for p in model.parameters())
525 log_string(f"nb_parameters {nb_parameters} ({int(nb_parameters/1e6)}M)")
526
527 ######################################################################
528
529 nb_epochs_finished = 0
530
531 if args.no_checkpoint:
532     log_string(f"not trying to load checkpoint.")
533
534 else:
535     try:
536         checkpoint_name = os.path.join(args.result_dir, args.checkpoint_name)
537         checkpoint = torch.load(checkpoint_name)
538         nb_epochs_finished = checkpoint["nb_epochs_finished"]
539         model.load_state_dict(checkpoint["model_state"])
540         torch.set_rng_state(checkpoint["rng_state"])
541         if torch.cuda.is_available():
542             torch.cuda.set_rng_state(checkpoint["cuda_rng_state"])
543
544         log_string(f"checkpoint loaded with {nb_epochs_finished} epochs finished.")
545
546     except FileNotFoundError:
547         log_string("starting from scratch.")
548
549     except:
550         log_string("error when loading the checkpoint.")
551         exit(1)
552
553 ######################################################################
554
555 token_count = 0
556 for input in task.batches(split="train"):
557     token_count += F.one_hot(input, num_classes=task.vocabulary_size()).sum((0, 1))
558 token_probas = token_count / token_count.sum()
559 entropy = -torch.xlogy(token_probas, token_probas).sum()
560 train_set_perplexity = math.exp(entropy)
561
562 ##############################
563
564 if args.learning_rate_schedule == "cos":
565     learning_rate_schedule = {}
566     for n_epoch in range(args.nb_epochs):
567         u = n_epoch / args.nb_epochs * math.pi
568         learning_rate_schedule[n_epoch] = args.learning_rate * 0.5 * (1 + math.cos(u))
569 else:
570     u = {
571         int(k): float(v)
572         for k, v in [
573             tuple(x.split(":")) for x in args.learning_rate_schedule.split(",")
574         ]
575     }
576
577     learning_rate_schedule = {}
578     learning_rate = args.learning_rate
579     for n_epoch in range(args.nb_epochs):
580         if n_epoch in u:
581             learning_rate = u[n_epoch]
582         learning_rate_schedule[n_epoch] = learning_rate
583
584 log_string(f"learning_rate_schedule {learning_rate_schedule}")
585
586 ##############################
587
588 if nb_epochs_finished >= args.nb_epochs:
589     n_epoch = nb_epochs_finished
590     train_perplexity = compute_perplexity(
591         model, fixed_len=task.height * task.width, split="train"
592     )
593     test_perplexity = compute_perplexity(
594         model, fixed_len=task.height * task.width, split="test"
595     )
596
597     log_string(
598         f"perplexity {n_epoch} train_set {train_set_perplexity} train_prediction {train_perplexity} test_prediction {test_perplexity}"
599     )
600
601     task.produce_results(n_epoch, model)
602
603 ##############################
604
605 for n_epoch in range(nb_epochs_finished, args.nb_epochs):
606     learning_rate = learning_rate_schedule[n_epoch]
607
608     log_string(f"learning_rate {learning_rate}")
609
610     if args.optim == "sgd":
611         optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
612     elif args.optim == "adam":
613         optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
614     elif args.optim == "adamw":
615         optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
616     else:
617         raise ValueError(f"{args.optim=}")
618
619     model.train()
620
621     nb_train_samples, acc_train_loss = 0, 0.0
622
623     for input in task.batches(split="train"):
624         input = input.to(device)
625         x, order = shuffle(input, task.height * task.width)
626         x = model(mygpt.BracketedSequence(x), order=order).x
627         output = reorder(x, order, back=True)
628         loss = F.cross_entropy(output.transpose(1, 2), input)
629         acc_train_loss += loss.item() * input.size(0)
630         nb_train_samples += input.size(0)
631
632         optimizer.zero_grad()
633         loss.backward()
634         optimizer.step()
635
636     train_perplexity = math.exp(min(100, acc_train_loss / nb_train_samples))
637     test_perplexity = compute_perplexity(
638         model, fixed_len=task.height * task.width, split="test"
639     )
640
641     log_string(
642         f"perplexity {n_epoch} train_set {train_set_perplexity} train_prediction {train_perplexity} test_prediction {test_perplexity}"
643     )
644
645     task.produce_results(n_epoch, model)
646
647     checkpoint = {
648         "nb_epochs_finished": n_epoch + 1,
649         "model_state": model.state_dict(),
650         "rng_state": torch.get_rng_state(),
651     }
652
653     if torch.cuda.is_available():
654         checkpoint["cuda_rng_state"] = torch.cuda.get_rng_state()
655
656     checkpoint_name = os.path.join(args.result_dir, args.checkpoint_name)
657     torch.save(checkpoint, checkpoint_name)
658     log_string(f"saved checkpoint {checkpoint_name}")
659
660 ######################################################################
661
662 if args.oneshot:
663     oneshot(model, task)
664
665 ######################################################################