3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
6 # Written by Francois Fleuret <francois@fleuret.org>
8 import math, sys, argparse, time, tqdm, os, datetime, warnings
10 import torch, torchvision
12 from torch.nn import functional as F
15 import mygpt, tasks, problems
17 ######################################################################
19 if torch.cuda.is_available():
20 device = torch.device("cuda")
21 torch.backends.cuda.matmul.allow_tf32 = True
23 device = torch.device("cpu")
25 ######################################################################
27 parser = argparse.ArgumentParser(
28 description="An implementation of GPT with cache.",
29 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
36 help="file, byheart, learnop, guessop, mixing, memory, twotargets, addition, picoclvr, mnist, maze, snake, stack, expr, rpl, grid, qmlp, greed",
39 parser.add_argument("--log_filename", type=str, default="train.log", help=" ")
41 parser.add_argument("--result_dir", type=str, default=None)
43 parser.add_argument("--seed", type=int, default=0)
45 parser.add_argument("--max_percents_of_test_in_train", type=int, default=1)
47 ########################################
49 parser.add_argument("--nb_epochs", type=int, default=100)
51 parser.add_argument("--batch_size", type=int, default=None)
53 parser.add_argument("--physical_batch_size", type=int, default=None)
55 parser.add_argument("--nb_train_samples", type=int, default=None)
57 parser.add_argument("--nb_test_samples", type=int, default=None)
59 parser.add_argument("--optim", type=str, default="adam")
61 parser.add_argument("--learning_rate", type=float, default=1e-4)
63 parser.add_argument("--learning_rate_schedule", type=str, default=None)
65 ########################################
67 parser.add_argument("--model", type=str, default=None)
69 parser.add_argument("--dim_model", type=int, default=None)
71 parser.add_argument("--dim_keys", type=int, default=None)
73 parser.add_argument("--dim_hidden", type=int, default=None)
75 parser.add_argument("--nb_heads", type=int, default=None)
77 parser.add_argument("--nb_blocks", type=int, default=None)
79 parser.add_argument("--dropout", type=float, default=0.1)
81 ########################################
83 parser.add_argument("--deterministic_synthesis", action="store_true", default=False)
85 ##############################
88 parser.add_argument("--filetask_train_file", type=str, default=None)
90 parser.add_argument("--filetask_test_file", type=str, default=None)
92 ##############################
95 parser.add_argument("--rpl_nb_starting_values", type=int, default=3)
97 parser.add_argument("--rpl_max_input", type=int, default=9)
99 parser.add_argument("--rpl_prog_len", type=int, default=8)
101 parser.add_argument("--rpl_nb_runs", type=int, default=5)
103 parser.add_argument("--rpl_no_prog", action="store_true", default=False)
105 ##############################
108 parser.add_argument("--grid_size", type=int, default=6)
110 parser.add_argument("--grid_fraction_play", type=float, default=0)
112 ##############################
115 parser.add_argument("--picoclvr_nb_colors", type=int, default=5)
117 parser.add_argument("--picoclvr_height", type=int, default=12)
119 parser.add_argument("--picoclvr_width", type=int, default=16)
121 parser.add_argument("--picocvlr_prune_properties", type=str, default="none")
123 ##############################
126 parser.add_argument("--maze_height", type=int, default=13)
128 parser.add_argument("--maze_width", type=int, default=21)
130 parser.add_argument("--maze_nb_walls", type=int, default=15)
132 ##############################
135 parser.add_argument("--snake_height", type=int, default=9)
137 parser.add_argument("--snake_width", type=int, default=12)
139 parser.add_argument("--snake_nb_colors", type=int, default=5)
141 parser.add_argument("--snake_length", type=int, default=200)
143 ##############################
146 parser.add_argument("--byheart_separation", type=int, default=1)
148 ##############################
151 parser.add_argument("--stack_nb_steps", type=int, default=100)
153 parser.add_argument("--stack_nb_stacks", type=int, default=3)
155 parser.add_argument("--stack_nb_digits", type=int, default=3)
157 parser.add_argument("--stack_fraction_values_for_train", type=float, default=None)
159 ##############################
162 parser.add_argument("--expr_nb_variables", type=int, default=5)
164 parser.add_argument("--expr_sequence_length", type=int, default=40)
166 parser.add_argument("--expr_operand_max", type=int, default=9)
168 parser.add_argument("--expr_result_max", type=int, default=99)
170 parser.add_argument("--expr_input_file", type=str, default=None)
172 ##############################
175 parser.add_argument("--mixing_hard", action="store_true", default=False)
177 parser.add_argument("--mixing_deterministic_start", action="store_true", default=False)
179 ##############################
182 parser.add_argument("--greed_height", type=int, default=5)
184 parser.add_argument("--greed_width", type=int, default=7)
186 parser.add_argument("--greed_T", type=int, default=25)
188 parser.add_argument("--greed_nb_walls", type=int, default=5)
190 parser.add_argument("--greed_nb_coins", type=int, default=2)
192 ######################################################################
194 args = parser.parse_args()
196 assert args.picocvlr_prune_properties in {"none", "train+eval", "eval"}
198 if args.result_dir is None:
199 args.result_dir = f"results_{args.task}"
201 ######################################################################
203 default_task_args = {
207 "nb_train_samples": 250000,
208 "nb_test_samples": 10000,
213 "nb_train_samples": 250000,
214 "nb_test_samples": 10000,
219 "nb_train_samples": 250000,
220 "nb_test_samples": 10000,
225 "nb_train_samples": 50000,
226 "nb_test_samples": 10000,
231 "nb_train_samples": 2500000,
232 "nb_test_samples": 10000,
237 "nb_train_samples": 250000,
238 "nb_test_samples": 10000,
243 "nb_train_samples": 100000,
244 "nb_test_samples": 1000,
249 "nb_train_samples": 1000000,
250 "nb_test_samples": 10000,
255 "nb_train_samples": 50000,
256 "nb_test_samples": 10000,
261 "nb_train_samples": 100000,
262 "nb_test_samples": 10000,
267 "nb_train_samples": 250000,
268 "nb_test_samples": 10000,
273 "nb_train_samples": 2500000,
274 "nb_test_samples": 10000,
279 "nb_train_samples": 250000,
280 "nb_test_samples": 10000,
285 "nb_train_samples": 100000,
286 "nb_test_samples": 1000,
291 "nb_train_samples": 50000,
292 "nb_test_samples": 10000,
297 "nb_train_samples": 25000,
298 "nb_test_samples": 1000,
303 "nb_train_samples": 250000,
304 "nb_test_samples": 10000,
309 "nb_train_samples": 60000,
310 "nb_test_samples": 10000,
315 "nb_train_samples": 25000,
316 "nb_test_samples": 10000,
320 if args.task in default_task_args:
321 for k, v in default_task_args[args.task].items():
322 if getattr(args, k) is None:
325 ######################################################################
327 default_model_args = {
365 if args.model in default_model_args:
366 for k, v in default_model_args[args.model].items():
367 if getattr(args, k) is None:
370 raise ValueError(f"Unknown model {args.model}")
372 ######################################################################
375 os.mkdir(args.result_dir)
376 except FileExistsError:
377 print(f"result directory {args.result_dir} already exists")
380 log_file = open(os.path.join(args.result_dir, args.log_filename), "a")
383 # torch.backends.cudnn.deterministic = True
384 # torch.backends.cudnn.benchmark = False
385 # torch.use_deterministic_algorithms(True)
386 torch.manual_seed(args.seed)
387 if torch.cuda.is_available():
388 torch.cuda.manual_seed_all(args.seed)
390 ######################################################################
394 t = time.strftime("%Y%m%d-%H:%M:%S ", time.localtime())
396 if log_file is not None:
397 log_file.write(t + s + "\n")
404 log_string(f"argv {' '.join(sys.argv)}")
407 log_string(f"args.{n} {getattr(args, n)}")
410 ######################################################################
413 def picoclvr_pruner_horizontal_green(p):
414 return not ("green" in p and ("left" in p or "right" in p))
417 picoclvr_pruner_train = (
418 picoclvr_pruner_horizontal_green
419 if args.picocvlr_prune_properties in {"train+eval"}
423 picoclvr_pruner_eval = (
424 (lambda p: not picoclvr_pruner_horizontal_green(p))
425 if args.picocvlr_prune_properties in {"train+eval", "eval"}
429 ######################################################################
431 if args.physical_batch_size is None:
432 args.physical_batch_size = args.batch_size
434 assert args.batch_size % args.physical_batch_size == 0
436 assert args.nb_train_samples % args.batch_size == 0
437 assert args.nb_test_samples % args.batch_size == 0
439 if args.task == "file":
441 args.filetask_train_file is not None and args.filetask_test_file is not None
442 ), "You have to specify the task train and test files"
443 task = tasks.TaskFromFile(
444 args.filetask_train_file,
445 args.filetask_test_file,
446 nb_train_samples=args.nb_train_samples,
447 nb_test_samples=args.nb_test_samples,
448 batch_size=args.physical_batch_size,
452 args.max_percents_of_test_in_train = 0
454 elif args.task == "byheart":
455 task = tasks.SandBox(
456 problem=problems.ProblemByHeart(separation=args.byheart_separation),
457 nb_train_samples=args.nb_train_samples,
458 nb_test_samples=args.nb_test_samples,
459 batch_size=args.physical_batch_size,
463 args.max_percents_of_test_in_train = -1
465 elif args.task == "world":
467 nb_train_samples=args.nb_train_samples,
468 nb_test_samples=args.nb_test_samples,
469 batch_size=args.physical_batch_size,
470 result_dir=args.result_dir,
474 args.max_percents_of_test_in_train = -1
476 elif args.task == "learnop":
477 task = tasks.SandBox(
478 problem=problems.ProblemLearnOperator(),
479 nb_train_samples=args.nb_train_samples,
480 nb_test_samples=args.nb_test_samples,
481 batch_size=args.physical_batch_size,
487 elif args.task == "guessop":
488 task = tasks.SandBox(
489 problem=problems.ProblemGuessOperator(),
490 nb_train_samples=args.nb_train_samples,
491 nb_test_samples=args.nb_test_samples,
492 batch_size=args.physical_batch_size,
498 elif args.task == "twotargets":
499 task = tasks.SandBox(
500 problem=problems.ProblemTwoTargets(),
501 nb_train_samples=args.nb_train_samples,
502 nb_test_samples=args.nb_test_samples,
503 batch_size=args.physical_batch_size,
508 elif args.task == "memory":
509 task = tasks.SandBox(
510 problem=problems.ProblemMemory(),
511 nb_train_samples=args.nb_train_samples,
512 nb_test_samples=args.nb_test_samples,
513 batch_size=args.physical_batch_size,
518 elif args.task == "mixing":
519 task = tasks.SandBox(
520 problem=problems.ProblemMixing(
521 hard=args.mixing_hard, random_start=not args.mixing_deterministic_start
523 nb_train_samples=args.nb_train_samples,
524 nb_test_samples=args.nb_test_samples,
525 batch_size=args.physical_batch_size,
530 elif args.task == "addition":
531 task = tasks.SandBox(
532 problem=problems.ProblemAddition(),
533 nb_train_samples=args.nb_train_samples,
534 nb_test_samples=args.nb_test_samples,
535 batch_size=args.physical_batch_size,
540 elif args.task == "picoclvr":
541 task = tasks.PicoCLVR(
542 nb_train_samples=args.nb_train_samples,
543 nb_test_samples=args.nb_test_samples,
544 batch_size=args.physical_batch_size,
545 height=args.picoclvr_height,
546 width=args.picoclvr_width,
547 nb_colors=args.picoclvr_nb_colors,
550 pruner_train=picoclvr_pruner_train,
551 pruner_eval=picoclvr_pruner_eval,
554 elif args.task == "mnist":
556 nb_train_samples=args.nb_train_samples,
557 nb_test_samples=args.nb_test_samples,
558 batch_size=args.physical_batch_size,
562 elif args.task == "maze":
564 nb_train_samples=args.nb_train_samples,
565 nb_test_samples=args.nb_test_samples,
566 batch_size=args.physical_batch_size,
567 height=args.maze_height,
568 width=args.maze_width,
569 nb_walls=args.maze_nb_walls,
573 elif args.task == "snake":
575 nb_train_samples=args.nb_train_samples,
576 nb_test_samples=args.nb_test_samples,
577 batch_size=args.physical_batch_size,
578 height=args.snake_height,
579 width=args.snake_width,
580 nb_colors=args.snake_nb_colors,
581 length=args.snake_length,
582 prompt_length=args.snake_length // 2,
586 elif args.task == "stack":
588 nb_train_samples=args.nb_train_samples,
589 nb_test_samples=args.nb_test_samples,
590 batch_size=args.physical_batch_size,
592 nb_steps=args.stack_nb_steps,
593 nb_stacks=args.stack_nb_stacks,
594 nb_digits=args.stack_nb_digits,
595 fraction_values_for_train=args.stack_fraction_values_for_train,
599 elif args.task == "expr":
601 nb_train_samples=args.nb_train_samples,
602 nb_test_samples=args.nb_test_samples,
603 nb_variables=args.expr_nb_variables,
604 sequence_length=args.expr_sequence_length,
605 operand_max=args.expr_operand_max,
606 result_max=args.expr_result_max,
607 batch_size=args.physical_batch_size,
611 elif args.task == "rpl":
613 nb_train_samples=args.nb_train_samples,
614 nb_test_samples=args.nb_test_samples,
615 batch_size=args.physical_batch_size,
616 nb_starting_values=args.rpl_nb_starting_values,
617 max_input=args.rpl_max_input,
618 prog_len=args.rpl_prog_len,
619 nb_runs=args.rpl_nb_runs,
620 no_prog=args.rpl_no_prog,
625 elif args.task == "grid":
627 nb_train_samples=args.nb_train_samples,
628 nb_test_samples=args.nb_test_samples,
629 batch_size=args.physical_batch_size,
631 fraction_play=args.grid_fraction_play,
636 elif args.task == "qmlp":
638 nb_train_samples=args.nb_train_samples,
639 nb_test_samples=args.nb_test_samples,
640 batch_size=args.physical_batch_size,
641 result_dir=args.result_dir,
646 elif args.task == "greed":
648 nb_train_samples=args.nb_train_samples,
649 nb_test_samples=args.nb_test_samples,
650 batch_size=args.physical_batch_size,
651 height=args.greed_height,
652 width=args.greed_width,
654 nb_walls=args.greed_nb_walls,
655 nb_coins=args.greed_nb_coins,
661 raise ValueError(f"Unknown task {args.task}")
663 ######################################################################
665 log_string(f"device {device}")
667 vocabulary_size = task.vocabulary_size()
669 log_string(f"vocabulary_size {vocabulary_size}")
671 ######################################################################
673 # Compute the entropy of the training tokens
676 for input in task.batches(split="train", desc="train-entropy"):
677 token_count += F.one_hot(input, num_classes=task.vocabulary_size()).sum((0, 1))
678 token_probas = token_count / token_count.sum()
679 entropy = -torch.xlogy(token_probas, token_probas).sum()
680 train_set_perplexity = math.exp(entropy)
682 ######################################################################
683 # A bit of paranoia never hurts
685 if args.max_percents_of_test_in_train >= 0:
687 def subsets_as_tuples(batches, cs):
689 for batch in batches:
691 s.add(tuple([v.item() for v in x]))
697 nb_test, nb_in_train = 0, 0
698 for test_subset in subsets_as_tuples(
699 task.batches(split="test", desc="test-check"), 25000
702 for train_subset in subsets_as_tuples(
703 task.batches(split="train", desc="train-check"), 25000
705 in_train.update(test_subset.intersection(train_subset))
706 nb_in_train += len(in_train)
707 nb_test += len(test_subset)
710 f"data_check {nb_in_train*100/nb_test:.02f}% ({nb_in_train}/{nb_test}) of test samples are in the train set"
714 nb_in_train <= args.max_percents_of_test_in_train * nb_test / 100
715 ), f"More than {args.max_percents_of_test_in_train}% of test samples are in the train set"
717 ##############################
719 if args.learning_rate_schedule == "cos":
720 learning_rate_schedule = {}
721 for n_epoch in range(args.nb_epochs):
722 u = n_epoch / args.nb_epochs * math.pi
723 learning_rate_schedule[n_epoch] = args.learning_rate * 0.5 * (1 + math.cos(u))
725 if args.learning_rate_schedule is not None:
729 tuple(x.split(":")) for x in args.learning_rate_schedule.split(",")
735 learning_rate_schedule = {}
736 learning_rate = args.learning_rate
737 for n_epoch in range(args.nb_epochs):
739 learning_rate = u[n_epoch]
740 learning_rate_schedule[n_epoch] = learning_rate
742 log_string(f"learning_rate_schedule {learning_rate_schedule}")
744 ######################################################################
747 def one_epoch(model, task):
748 if args.optim == "sgd":
749 optimizer = torch.optim.SGD(model.parameters(), lr=args.learning_rate)
750 elif args.optim == "adam":
751 optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)
752 elif args.optim == "adamw":
753 optimizer = torch.optim.AdamW(model.parameters(), lr=args.learning_rate)
755 raise ValueError(f"Unknown optimizer {args.optim}.")
759 nb_train_samples, acc_train_loss = 0, 0.0
761 for input in task.batches(split="train"):
762 input = input.to(device)
764 if nb_train_samples % args.batch_size == 0:
765 optimizer.zero_grad()
767 output = model(mygpt.BracketedSequence(input)).x
768 loss = F.cross_entropy(output.transpose(1, 2), input)
769 acc_train_loss += loss.item() * input.size(0)
771 nb_train_samples += input.size(0)
775 if nb_train_samples % args.batch_size == 0:
778 train_perplexity = math.exp(min(100, acc_train_loss / nb_train_samples))
780 log_string(f"train_perplexity {n_epoch} {train_perplexity}")
783 ######################################################################
786 def run_tests(model, task, deterministic_synthesis):
787 with torch.autograd.no_grad():
790 nb_test_samples, acc_test_loss = 0, 0.0
791 nb_samples_accumulated = 0
793 for input in task.batches(split="test"):
794 input = input.to(device)
796 bs = model(mygpt.BracketedSequence(input))
799 loss = F.cross_entropy(output.transpose(1, 2), input)
801 acc_test_loss += loss.item() * input.size(0)
803 nb_test_samples += input.size(0)
805 main_test_accuracy = task.produce_results(
808 result_dir=args.result_dir,
810 deterministic_synthesis=deterministic_synthesis,
813 test_perplexity = math.exp(min(100, acc_test_loss / nb_test_samples))
815 log_string(f"test_perplexity {n_epoch} {test_perplexity}")
817 model.main_test_accuracy = main_test_accuracy
820 ######################################################################
832 while sum([x.size(0) for x in kept]) < nb_for_train + nb_for_test:
833 new_quizzes, nb_correct = task.create_new_quizzes(
835 result_dir=args.result_dir,
837 nb=4 * (nb_for_train + nb_for_test),
839 other_models=other_models,
842 to_keep = new_quizzes[nb_correct == len(other_models) - 1]
843 log_string(f"keep {to_keep.size(0)} quizzes")
846 new_quizzes = torch.cat(kept, dim=0)[: nb_for_train + nb_for_test]
848 task.store_new_quizzes(new_quizzes[:nb_for_train], for_train=True)
849 task.store_new_quizzes(new_quizzes[nb_for_train:], for_train=False)
854 f"world_new_{n_epoch:04d}.png",
859 ######################################################################
865 vocabulary_size=vocabulary_size,
866 dim_model=args.dim_model,
867 dim_keys=args.dim_keys,
868 dim_hidden=args.dim_hidden,
869 nb_heads=args.nb_heads,
870 nb_blocks=args.nb_blocks,
872 dropout=args.dropout,
875 model.main_test_accuracy = 0.0
881 nb_parameters = sum(p.numel() for p in models[0].parameters())
882 log_string(f"nb_parameters {nb_parameters} ({int(nb_parameters/1e6)}M)")
884 ######################################################################
886 accuracy_to_make_quizzes = 0.975
888 for n_epoch in range(args.nb_epochs):
889 models.sort(key=lambda model: model.main_test_accuracy)
894 f"training model {model.id} main_test_accuracy {model.main_test_accuracy}"
897 one_epoch(model, task)
900 f"train_set_composition world {task.nb_batch_samples_world} quizzes {task.nb_batch_samples_quizzes}"
903 run_tests(model, task, deterministic_synthesis=False)
905 if model.main_test_accuracy >= accuracy_to_make_quizzes:
906 other_models = models.copy()
907 other_models.remove(model)
918 ######################################################################