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 # torch.backends.cuda.matmul.allow_tf23
9 # torch.autocast(torch.bfloat16)
11 import math, sys, argparse, time, tqdm, itertools, os
13 import torch, torchvision
15 from torch.nn import functional as F
17 import mygpt, tensorstack
19 ######################################################################
21 if torch.cuda.is_available():
22 device = torch.device("cuda")
23 torch.backends.cuda.matmul.allow_tf32 = True
25 device = torch.device("cpu")
27 ######################################################################
29 parser = argparse.ArgumentParser(
30 description="An implementation of GPT with cache to solve a toy geometric reasoning task."
33 parser.add_argument("--task", type=str, default="picoclvr")
35 parser.add_argument("--log_filename", type=str, default="train.log")
37 parser.add_argument("--result_dir", type=str, default="results_default")
39 parser.add_argument("--seed", type=int, default=0)
41 parser.add_argument("--nb_epochs", type=int, default=25)
43 parser.add_argument("--batch_size", type=int, default=25)
45 parser.add_argument("--nb_train_samples", type=int, default=250000)
47 parser.add_argument("--nb_test_samples", type=int, default=10000)
49 parser.add_argument("--optim", type=str, default="adam")
51 parser.add_argument("--learning_rate", type=float, default=1e-4)
53 parser.add_argument("--learning_rate_schedule", type=str, default="10: 2e-5,30: 4e-6")
55 parser.add_argument("--dim_model", type=int, default=512)
57 parser.add_argument("--dim_keys", type=int, default=64)
59 parser.add_argument("--dim_hidden", type=int, default=2048)
61 parser.add_argument("--nb_heads", type=int, default=8)
63 parser.add_argument("--nb_blocks", type=int, default=12)
65 parser.add_argument("--dropout", type=float, default=0.1)
67 parser.add_argument("--deterministic_synthesis", action="store_true", default=False)
69 parser.add_argument("--no_checkpoint", action="store_true", default=False)
71 parser.add_argument("--overwrite_results", action="store_true", default=False)
73 parser.add_argument("--checkpoint_name", type=str, default="checkpoint.pth")
75 ##############################
78 parser.add_argument("--picoclvr_nb_colors", type=int, default=5)
80 parser.add_argument("--picoclvr_height", type=int, default=12)
82 parser.add_argument("--picoclvr_width", type=int, default=16)
84 parser.add_argument("--picocvlr_prune_properties", type=str, default="none")
86 ##############################
89 parser.add_argument("--maze_height", type=int, default=13)
91 parser.add_argument("--maze_width", type=int, default=21)
93 parser.add_argument("--maze_nb_walls", type=int, default=15)
95 ##############################
98 parser.add_argument("--snake_height", type=int, default=6)
100 parser.add_argument("--snake_width", type=int, default=8)
102 parser.add_argument("--snake_nb_colors", type=int, default=3)
104 parser.add_argument("--snake_length", type=int, default=100)
106 ######################################################################
108 args = parser.parse_args()
110 assert args.picocvlr_prune_properties in {"none", "train+eval", "eval"}
113 os.mkdir(args.result_dir)
114 except FileExistsError:
115 if not args.overwrite_results:
116 print(f"result directory {args.result_dir} already exists")
119 log_file = open(os.path.join(args.result_dir, args.log_filename), "a")
122 # torch.backends.cudnn.deterministic = True
123 # torch.backends.cudnn.benchmark = False
124 # torch.use_deterministic_algorithms(True)
125 torch.manual_seed(args.seed)
126 if torch.cuda.is_available():
127 torch.cuda.manual_seed_all(args.seed)
129 ######################################################################
133 t = time.strftime("%Y%m%d-%H:%M:%S ", time.localtime())
135 if log_file is not None:
136 log_file.write(t + s + "\n")
144 log_string(f"args.{n} {getattr(args, n)}")
146 ######################################################################
149 def masked_inplace_autoregression(
150 model, batch_size, input, ar_mask, forbidden_tokens=None, device=torch.device("cpu")
152 for input, ar_mask in zip(input.split(batch_size), ar_mask.split(batch_size)):
153 i = (ar_mask.sum(0) > 0).nonzero()
156 mygpt.BracketedSequence(input, 0, i.min())
157 ) # Needed to initialize the model's cache
158 for s in range(i.min(), i.max() + 1):
159 output = model(mygpt.BracketedSequence(input, s, 1)).x
160 logits = output[:, s]
161 if forbidden_tokens is not None:
162 logits = logits.masked_fill(forbidden_tokens, float("-inf"))
163 if args.deterministic_synthesis:
164 t_next = logits.argmax(1)
166 dist = torch.distributions.categorical.Categorical(logits=logits)
167 t_next = dist.sample()
168 input[:, s] = ar_mask[:, s] * t_next + (1 - ar_mask[:, s]) * input[:, s]
171 ######################################################################
175 def batches(self, split="train"):
178 def vocabulary_size(self):
181 def produce_results(self, n_epoch, model):
185 ######################################################################
190 class TaskPicoCLVR(Task):
191 # Make a tensor from a list of strings
192 def tensorize(self, descr):
193 token_descr = [s.strip().split(" ") for s in descr]
194 l = max([len(s) for s in token_descr])
195 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
196 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
197 return torch.tensor(id_descr, device=self.device)
199 # Make a list of strings from a tensor
200 def detensorize(self, x):
201 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
203 # trim all the tensors in the tuple z to remove as much token from
204 # left and right in the first tensor. If z is a tuple, all its
205 # elements are trimed according to the triming for the first
206 def trim(self, z, token="<nul>"):
207 n = self.token2id[token]
210 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
211 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
212 return tuple([t[:, a:b] for t in z])
214 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
215 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
218 ######################
219 # Not the cleanest part of the code
221 # Extract the last image of each sequence, from the last <img>
222 # included, and set to <nul> all the tokens from the beginning of
223 # that image to the end
224 def excise_last_image(self, input):
225 t_img, t_nul = self.token2id["<img>"], self.token2id["<nul>"]
226 nb_img_tokens = self.height * self.width + 1
228 input = input.clone()
229 t = (input == t_img).long()
230 tail_masks = (t.cumsum(dim=1) == t.sum(dim=1, keepdim=True)).long()
231 i = (t * tail_masks).nonzero(as_tuple=True)
234 i[1][:, None] + torch.arange(nb_img_tokens, device=input.device)[None, :],
236 images = self.trim(input[j])
238 loss_masks = 1 - tail_masks
239 input, loss_masks = self.trim((input, loss_masks))
240 return input, loss_masks, images
242 def add_true_image(self, input, images, loss_masks):
243 t_nul = self.token2id["<nul>"]
244 nb_img_tokens = self.height * self.width + 1
245 input = F.pad(input, (0, nb_img_tokens), value=t_nul)
246 loss_masks = F.pad(loss_masks, (0, nb_img_tokens), value=0)
247 t = (input == t_nul).long()
248 i = (t.cumsum(dim=1) == 1).nonzero(as_tuple=True)
251 i[1][:, None] + torch.arange(nb_img_tokens, device=input.device)[None, :],
255 input, loss_masks = self.trim((input, loss_masks))
256 return input, loss_masks
258 def add_generated_image(self, input, loss_masks, model):
259 t_img, t_nul = self.token2id["<img>"], self.token2id["<nul>"]
260 nb_img_tokens = self.height * self.width + 1
262 input = F.pad(input, (0, nb_img_tokens), value=t_nul)
263 loss_masks = F.pad(loss_masks, (0, nb_img_tokens), value=0)
264 t = (input == t_nul).long()
265 i = (t.cumsum(dim=1) == 1).nonzero(as_tuple=True)
272 + torch.arange(nb_img_tokens - 1, device=input.device)[None, :],
274 ar_masks = input.new_zeros(input.size(), dtype=torch.int64)
277 torch.arange(self.vocabulary_size(), device=input.device) == t_nul
279 with torch.autograd.no_grad():
282 masked_inplace_autoregression(
292 input, loss_masks = self.trim((input, loss_masks))
294 return input, loss_masks
296 ######################
306 device=torch.device("cpu"),
310 def generate_descr(nb, cache_suffix, pruner):
311 return picoclvr.generate(
321 self.batch_size = batch_size
323 self.pruner_train = pruner_train
324 self.pruner_eval = pruner_eval
327 "nb_train_samples": nb_train_samples,
328 "nb_test_samples": nb_test_samples,
331 "nb_colors": nb_colors,
332 "batch_size": batch_size,
333 "rng_state": list(torch.get_rng_state()),
337 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
339 self.train_descr = generate_descr(
340 nb_train_samples, "train", pruner=self.pruner_train
342 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
344 # Build the tokenizer
345 tokens = {"<nul>", "<img>"}
346 for d in [self.train_descr, self.test_descr]:
348 for t in s.strip().split(" "):
350 # make this set a sorted list to get the same tensors given
352 tokens = list(tokens)
354 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
355 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
357 # Tokenize the train and test sets
358 self.train_input = self.tensorize(self.train_descr)
359 self.test_input = self.tensorize(self.test_descr)
361 def batches(self, split="train"):
362 assert split in {"train", "test"}
363 input = self.train_input if split == "train" else self.test_input
364 for batch in tqdm.tqdm(
365 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
367 yield self.trim(batch)
369 def vocabulary_size(self):
370 return len(self.token2id)
372 def compute_missing_properties(self, n_epoch, model, pruner=None):
373 acc_nb_requested_properties = []
374 acc_nb_missing_properties = []
377 for input in tqdm.tqdm(
378 self.test_input.split(self.batch_size),
380 desc=f"test-properties",
382 tape, loss_masks, _ = self.excise_last_image(input)
383 tape, loss_masks = self.add_generated_image(tape, loss_masks, model)
384 result_descr = self.detensorize(tape)
385 np = picoclvr.nb_properties(
391 nb_requested_properties, _, nb_missing_properties = zip(*np)
392 acc_nb_requested_properties += nb_requested_properties
393 acc_nb_missing_properties += nb_missing_properties
394 acc_nb_results += len(result_descr)
396 nb_requested_properties = sum(acc_nb_requested_properties)
397 nb_missing_properties = sum(acc_nb_missing_properties)
399 prefix = "" if pruner is None else "pruned_"
400 log_string(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
402 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
405 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
408 ######################################################################
410 def produce_results(self, n_epoch, model):
411 self.compute_missing_properties(n_epoch, model)
413 if self.pruner_eval is not None:
414 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
416 nb_tokens_to_generate = self.height * self.width + 3
421 for primer_descr in [
422 "red above green <sep> green top <sep> blue right of red",
423 "there is red <sep> there is yellow <sep> there is blue",
424 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
425 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
427 primer += [primer_descr] * nb_per_primer
429 tape = self.tensorize(primer)
430 loss_masks = 1 - (tape == self.token2id["<nul>"]).long()
431 tape, loss_masks = self.add_generated_image(tape, loss_masks, model)
432 result_descr = self.detensorize(tape)
434 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
436 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
437 acc_nb_results = len(result_descr)
439 nb_requested_properties = sum(acc_nb_requested_properties)
440 nb_missing_properties = sum(acc_nb_missing_properties)
443 log_string(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
445 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
448 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
451 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
455 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
459 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
465 image_name = os.path.join(args.result_dir, f"picoclvr_result_{n_epoch:04d}.png")
466 torchvision.utils.save_image(
467 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=1.0
469 log_string(f"wrote {image_name}")
472 ######################################################################
475 class TaskMNIST(Task):
476 def __init__(self, batch_size, device=torch.device("cpu")):
478 self.batch_size = batch_size
480 def batches(self, split="train"):
481 assert split in {"train", "test"}
482 data_set = torchvision.datasets.MNIST(
483 root="./data", train=(split == "train"), download=True
485 data_input = data_set.data.view(-1, 28 * 28).long()
486 if args.nb_train_samples is not None:
487 data_input = data_input[: args.nb_train_samples]
488 for batch in tqdm.tqdm(
489 data_input.split(self.batch_size), desc=f"epoch-{split}"
493 def vocabulary_size(self):
496 def produce_results(self, n_epoch, model):
497 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
498 ar_mask = torch.full_like(results, 1)
499 masked_inplace_autoregression(
500 model, self.batch_size, results, ar_mask, device=self.device
502 image_name = os.path.join(args.result_dir, f"result_mnist_{n_epoch:04d}.png")
503 torchvision.utils.save_image(
504 1 - results.reshape(-1, 1, 28, 28) / 255.0,
509 log_string(f"wrote {image_name}")
512 ######################################################################
517 class TaskMaze(Task):
518 def map2seq(self, *m):
519 return torch.cat([x.flatten(1) for x in m], 1)
521 def seq2map(self, s):
522 s = s.reshape(s.size(0), -1, self.height, self.width)
523 return (s[:, k] for k in range(s.size(1)))
533 device=torch.device("cpu"),
535 self.batch_size = batch_size
540 train_mazes, train_paths, _ = maze.create_maze_data(
545 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
547 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
549 test_mazes, test_paths, _ = maze.create_maze_data(
554 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
556 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
558 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
560 def batches(self, split="train", nb_to_use=-1, desc=None):
561 assert split in {"train", "test"}
562 input = self.train_input if split == "train" else self.test_input
564 input = input[:nb_to_use]
566 desc = f"epoch-{split}"
567 for batch in tqdm.tqdm(
568 input.split(self.batch_size), dynamic_ncols=True, desc=desc
572 def vocabulary_size(self):
575 def compute_error(self, model, split="train", nb_to_use=-1):
576 nb_total, nb_correct = 0, 0
577 for input in task.batches(split, nb_to_use):
578 result = input.clone()
579 ar_mask = result.new_zeros(result.size())
580 ar_mask[:, self.height * self.width :] = 1
581 result *= 1 - ar_mask
582 masked_inplace_autoregression(
583 model, self.batch_size, result, ar_mask, device=self.device
585 mazes, paths = self.seq2map(result)
586 nb_correct += maze.path_correctness(mazes, paths).long().sum()
587 nb_total += mazes.size(0)
589 return nb_total, nb_correct
591 def produce_results(self, n_epoch, model):
592 with torch.autograd.no_grad():
596 train_nb_total, train_nb_correct = self.compute_error(
597 model, "train", nb_to_use=1000
600 f"accuracy_train nb_total {train_nb_total} nb_correct {train_nb_correct} accuracy {(100.0*train_nb_correct)/train_nb_total:.02f}%"
603 test_nb_total, test_nb_correct = self.compute_error(
604 model, "test", nb_to_use=1000
607 f"accuracy_test nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
610 input = self.test_input[:48]
611 result = input.clone()
612 ar_mask = result.new_zeros(result.size())
613 ar_mask[:, self.height * self.width :] = 1
614 result *= 1 - ar_mask
615 masked_inplace_autoregression(
616 model, self.batch_size, result, ar_mask, device=self.device
619 mazes, paths = self.seq2map(input)
620 _, predicted_paths = self.seq2map(result)
622 filename = os.path.join(args.result_dir, f"result_{n_epoch:04d}.png")
627 predicted_paths=predicted_paths,
628 path_correct=maze.path_correctness(mazes, predicted_paths),
630 log_string(f"wrote {filename}")
635 ######################################################################
638 def generate_snake_sequences(
639 nb, height, width, nb_colors, length, device=torch.device("cpu")
641 worlds = torch.randint(nb_colors, (nb, height, width), device=device)
643 snake_position = torch.cat(
645 torch.randint(height, (nb, 1), device=device),
646 torch.randint(width, (nb, 1), device=device),
650 snake_direction = torch.randint(4, (nb,), device=device)
651 sequences = torch.empty(nb, 2 * length, device=device, dtype=torch.int64)
652 count = torch.arange(nb, device=device) # [:,None]
654 for l in range(length):
656 snake_next_direction = torch.cat(
658 (snake_direction[:, None] - 1) % 4,
659 snake_direction[:, None],
660 (snake_direction[:, None] + 1) % 4,
666 vh = (snake_next_direction + 1) % 2 * (snake_next_direction - 1)
667 vw = snake_next_direction % 2 * (snake_next_direction - 2)
670 snake_next_speed = torch.cat((vh[:, :, None], vw[:, :, None]), 2)
671 snake_next_position = snake_position[:, None, :] + snake_next_speed
674 val = torch.logical_and(
676 snake_next_position[:, :, 0] >= 0, snake_next_position[:, :, 0] < height
679 snake_next_position[:, :, 1] >= 0, snake_next_position[:, :, 1] < width
683 torch.rand_like(val) * val * torch.tensor([[1.0, 4.0, 1.0]], device=device)
687 i = torch.arange(val.size(0), device=device)
689 snake_direction = snake_next_direction[i, j]
691 sequences[:, 2 * l] = worlds[count, snake_position[:, 0], snake_position[:, 1]]
692 sequences[:, 2 * l + 1] = snake_direction
695 snake_position = snake_next_position[i, j]
697 return sequences, worlds
699 # print(snake_position)
702 # generate_snake_sequences(nb=1, height=4, width=6, nb_colors=3, length=20)
706 class TaskSnake(Task):
716 device=torch.device("cpu"),
718 self.batch_size = batch_size
723 self.train_input, self.train_worlds = generate_snake_sequences(
724 nb_train_samples, height, width, nb_colors, length, self.device
726 self.test_input, self.test_worlds = generate_snake_sequences(
727 nb_test_samples, height, width, nb_colors, length, self.device
730 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
732 def batches(self, split="train", nb_to_use=-1, desc=None):
733 assert split in {"train", "test"}
734 input = self.train_input if split == "train" else self.test_input
736 input = input[:nb_to_use]
738 desc = f"epoch-{split}"
739 for batch in tqdm.tqdm(
740 input.split(self.batch_size), dynamic_ncols=True, desc=desc
744 def vocabulary_size(self):
748 ######################################################################
751 def picoclvr_pruner_horizontal_green(p):
752 return not ("green" in p and ("left" in p or "right" in p))
755 picoclvr_pruner_train = (
756 picoclvr_pruner_horizontal_green
757 if args.picocvlr_prune_properties in {"train+eval"}
761 picoclvr_pruner_eval = (
762 (lambda p: not picoclvr_pruner_horizontal_green(p))
763 if args.picocvlr_prune_properties in {"train+eval", "eval"}
767 ######################################################################
769 if args.task == "picoclvr":
771 nb_train_samples=args.nb_train_samples,
772 nb_test_samples=args.nb_test_samples,
773 batch_size=args.batch_size,
774 height=args.picoclvr_height,
775 width=args.picoclvr_width,
776 nb_colors=args.picoclvr_nb_colors,
778 pruner_train=picoclvr_pruner_train,
779 pruner_eval=picoclvr_pruner_eval,
782 elif args.task == "mnist":
784 batch_size=args.batch_size,
788 elif args.task == "maze":
790 nb_train_samples=args.nb_train_samples,
791 nb_test_samples=args.nb_test_samples,
792 batch_size=args.batch_size,
793 height=args.maze_height,
794 width=args.maze_width,
795 nb_walls=args.maze_nb_walls,
799 elif args.task == "snake":
801 nb_train_samples=args.nb_train_samples,
802 nb_test_samples=args.nb_test_samples,
803 batch_size=args.batch_size,
804 height=args.snake_height,
805 width=args.snake_width,
806 nb_colors=args.snake_nb_colors,
807 length=args.snake_length,
812 raise ValueError(f"Unknown task {args.task}")
814 ######################################################################
816 log_string(f"device {device}")
818 vocabulary_size = task.vocabulary_size()
820 log_string(f"vocabulary_size {vocabulary_size}")
822 ##############################
825 vocabulary_size=vocabulary_size,
826 dim_model=args.dim_model,
827 dim_keys=args.dim_keys,
828 dim_hidden=args.dim_hidden,
829 nb_heads=args.nb_heads,
830 nb_blocks=args.nb_blocks,
832 dropout=args.dropout,
837 nb_parameters = sum(p.numel() for p in model.parameters())
838 log_string(f"nb_parameters {nb_parameters} ({int(nb_parameters/1e6)}M)")
840 ######################################################################
842 nb_epochs_finished = 0
844 if args.no_checkpoint:
845 log_string(f"not trying to load checkpoint.")
849 checkpoint_name = os.path.join(args.result_dir, args.checkpoint_name)
850 checkpoint = torch.load(checkpoint_name)
851 nb_epochs_finished = checkpoint["nb_epochs_finished"]
852 model.load_state_dict(checkpoint["model_state"])
853 torch.set_rng_state(checkpoint["rng_state"])
854 if torch.cuda.is_available():
855 torch.cuda.set_rng_state(checkpoint["cuda_rng_state"])
857 log_string(f"checkpoint loaded with {nb_epochs_finished} epochs finished.")
859 except FileNotFoundError:
860 log_string("starting from scratch.")
863 log_string("error when loading the checkpoint.")
866 ######################################################################
868 nb_epochs = args.nb_epochs if args.nb_epochs > 0 else nb_epochs_default
871 for input in task.batches(split="train"):
872 token_count += F.one_hot(input, num_classes=task.vocabulary_size()).sum((0, 1))
873 token_probas = token_count / token_count.sum()
874 entropy = -torch.xlogy(token_probas, token_probas).sum()
875 train_set_perplexity = math.exp(entropy)
877 ##############################
879 if args.learning_rate_schedule == "cos":
880 learning_rate_schedule = {}
881 for n_epoch in range(args.nb_epochs):
882 u = n_epoch / args.nb_epochs * math.pi
883 learning_rate_schedule[n_epoch] = args.learning_rate * 0.5 * (1 + math.cos(u))
888 tuple(x.split(":")) for x in args.learning_rate_schedule.split(",")
892 learning_rate_schedule = {}
893 learning_rate = args.learning_rate
894 for n_epoch in range(args.nb_epochs):
896 learning_rate = u[n_epoch]
897 learning_rate_schedule[n_epoch] = learning_rate
899 log_string(f"learning_rate_schedule {learning_rate_schedule}")
901 ##############################
905 if nb_epochs_finished >= nb_epochs:
906 task.produce_results(nb_epochs_finished, model)
908 for n_epoch in range(nb_epochs_finished, nb_epochs):
909 learning_rate = learning_rate_schedule[n_epoch]
911 log_string(f"learning_rate {learning_rate}")
913 if args.optim == "sgd":
914 optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
915 elif args.optim == "adam":
916 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
917 elif args.optim == "adamw":
918 optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
920 raise ValueError(f"Unknown optimizer {args.optim}.")
924 nb_train_samples, acc_train_loss = 0, 0.0
926 for input in task.batches(split="train"):
927 input = input.to(device)
928 output = model(mygpt.BracketedSequence(input)).x
929 loss = F.cross_entropy(output.transpose(1, 2), input)
930 acc_train_loss += loss.item() * input.size(0)
931 nb_train_samples += input.size(0)
932 nb_samples_seen += input.size(0)
934 optimizer.zero_grad()
938 with torch.autograd.no_grad():
941 nb_test_samples, acc_test_loss = 0, 0.0
943 for input in task.batches(split="test"):
944 input = input.to(device)
946 # input, loss_masks, true_images = task.excise_last_image(input)
947 # input, loss_masks = task.add_true_image(input, true_images, loss_masks)
949 output = model(mygpt.BracketedSequence(input)).x
950 loss = F.cross_entropy(output.transpose(1, 2), input)
951 acc_test_loss += loss.item() * input.size(0)
952 nb_test_samples += input.size(0)
954 train_perplexity = math.exp(min(100, acc_train_loss / nb_train_samples))
955 test_perplexity = math.exp(min(100, acc_test_loss / nb_test_samples))
958 f"perplexity {n_epoch} train_set {train_set_perplexity} train_prediction {train_perplexity} test_prediction {test_perplexity}"
961 task.produce_results(n_epoch, model)
964 "nb_epochs_finished": n_epoch + 1,
965 "model_state": model.state_dict(),
966 "rng_state": torch.get_rng_state(),
969 if torch.cuda.is_available():
970 checkpoint["cuda_rng_state"] = torch.cuda.get_rng_state()
972 checkpoint_name = os.path.join(args.result_dir, args.checkpoint_name)
973 torch.save(checkpoint, checkpoint_name)
974 log_string(f"saved checkpoint {checkpoint_name}")
976 ######################################################################