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, itertools, os
10 import torch, torchvision
12 from torch.nn import functional as F
14 import mygpt, tensorstack
16 ######################################################################
18 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20 ######################################################################
22 parser = argparse.ArgumentParser(
23 description="An implementation of GPT with cache to solve a toy geometric reasoning task."
26 parser.add_argument("--log_filename", type=str, default="train.log")
28 parser.add_argument("--result_dir", type=str, default="results_default")
30 parser.add_argument("--seed", type=int, default=0)
32 parser.add_argument("--nb_epochs", type=int, default=25)
34 parser.add_argument("--batch_size", type=int, default=100)
36 parser.add_argument("--data_size", type=int, default=-1)
38 parser.add_argument("--optim", type=str, default="adam")
40 parser.add_argument("--learning_rate", type=float, default=1e-3)
43 "--learning_rate_schedule", type=str, default="10: 2e-4,20: 4e-5,30: 8e-6"
46 parser.add_argument("--dim_model", type=int, default=512)
48 parser.add_argument("--dim_keys", type=int, default=64)
50 parser.add_argument("--dim_hidden", type=int, default=2048)
52 parser.add_argument("--nb_heads", type=int, default=8)
54 parser.add_argument("--nb_blocks", type=int, default=12)
56 parser.add_argument("--dropout", type=float, default=0.1)
58 parser.add_argument("--nb_oneshot_blocks", type=int, default=-1)
60 parser.add_argument("--deterministic_synthesis", action="store_true", default=False)
62 parser.add_argument("--no_checkpoint", action="store_true", default=False)
64 parser.add_argument("--overwrite_results", action="store_true", default=False)
66 parser.add_argument("--checkpoint_name", type=str, default="checkpoint.pth")
68 ##############################
71 parser.add_argument("--nb_colors", type=int, default=5)
73 parser.add_argument("--height", type=int, default=12)
75 parser.add_argument("--width", type=int, default=16)
77 parser.add_argument("--prune_properties", type=str, default="none")
79 ######################################################################
81 args = parser.parse_args()
83 assert args.prune_properties in {"none", "train+eval", "eval"}
86 os.mkdir(args.result_dir)
87 except FileExistsError:
88 if not args.overwrite_results:
89 print(f"result directory {args.result_dir} already exists")
92 log_file = open(os.path.join(args.result_dir, args.log_filename), "w")
95 # torch.backends.cudnn.deterministic = True
96 # torch.backends.cudnn.benchmark = False
97 # torch.use_deterministic_algorithms(True)
98 torch.manual_seed(args.seed)
99 if torch.cuda.is_available():
100 torch.cuda.manual_seed_all(args.seed)
102 ######################################################################
106 t = time.strftime("%Y%m%d-%H:%M:%S ", time.localtime())
108 if log_file is not None:
109 log_file.write(t + s + "\n")
117 log_string(f"args.{n} {getattr(args, n)}")
119 ######################################################################
122 def masked_inplace_autoregression(
123 model, batch_size, input, ar_mask, forbidden_tokens=None, device=torch.device("cpu")
126 for input, ar_mask in zip(input.split(batch_size), ar_mask.split(batch_size)):
127 i = (ar_mask.sum(0) > 0).nonzero()
130 mygpt.BracketedSequence(input, 0, i.min())
131 ) # Needed to initialize the model's cache
132 for s in range(i.min(), i.max() + 1):
133 output = model(mygpt.BracketedSequence(input, s, 1)).x
134 logits = output[:, s]
135 if forbidden_tokens is not None:
136 logits = logits.masked_fill(forbidden_tokens, float("-inf"))
137 if args.deterministic_synthesis:
138 t_next = logits.argmax(1)
140 dist = torch.distributions.categorical.Categorical(logits=logits)
141 t_next = dist.sample()
142 input[:, s] = ar_mask[:, s] * t_next + (1 - ar_mask[:, s]) * input[:, s]
145 ######################################################################
149 def batches(self, split="train"):
152 def vocabulary_size(self):
155 def produce_results(self, n_epoch, model):
159 ######################################################################
164 class TaskPicoCLVR(Task):
166 # Make a tensor from a list of strings
167 def tensorize(self, descr):
168 token_descr = [s.strip().split(" ") for s in descr]
169 l = max([len(s) for s in token_descr])
170 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
171 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
172 return torch.tensor(id_descr, device=self.device)
174 # Make a list of strings from a tensor
175 def detensorize(self, x):
176 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
178 # trim all the tensors in the tuple z to remove as much token from
179 # left and right in the first tensor. If z is a tuple, all its
180 # elements are trimed according to the triming for the first
181 def trim(self, z, token="<nul>"):
182 n = self.token2id[token]
185 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
186 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
187 return tuple([t[:, a:b] for t in z])
189 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
190 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
193 ######################
194 # Not the cleanest part of the code
196 # Extract the last image of each sequence, from the last <img>
197 # included, and set to <nul> all the tokens from the beginning of
198 # that image to the end
199 def excise_last_image(self, input):
200 t_img, t_nul = self.token2id["<img>"], self.token2id["<nul>"]
201 nb_img_tokens = self.height * self.width + 1
203 input = input.clone()
204 t = (input == t_img).long()
205 tail_masks = (t.cumsum(dim=1) == t.sum(dim=1, keepdim=True)).long()
206 i = (t * tail_masks).nonzero(as_tuple=True)
209 i[1][:, None] + torch.arange(nb_img_tokens, device=input.device)[None, :],
211 images = self.trim(input[j])
213 loss_masks = 1 - tail_masks
214 input, loss_masks = self.trim((input, loss_masks))
215 return input, loss_masks, images
217 def add_true_image(self, input, images, loss_masks):
218 t_nul = self.token2id["<nul>"]
219 nb_img_tokens = self.height * self.width + 1
220 input = F.pad(input, (0, nb_img_tokens), value=t_nul)
221 loss_masks = F.pad(loss_masks, (0, nb_img_tokens), value=0)
222 t = (input == t_nul).long()
223 i = (t.cumsum(dim=1) == 1).nonzero(as_tuple=True)
226 i[1][:, None] + torch.arange(nb_img_tokens, device=input.device)[None, :],
230 input, loss_masks = self.trim((input, loss_masks))
231 return input, loss_masks
233 def add_generated_image(self, input, loss_masks, model):
234 t_img, t_nul = self.token2id["<img>"], self.token2id["<nul>"]
235 nb_img_tokens = self.height * self.width + 1
237 input = F.pad(input, (0, nb_img_tokens), value=t_nul)
238 loss_masks = F.pad(loss_masks, (0, nb_img_tokens), value=0)
239 t = (input == t_nul).long()
240 i = (t.cumsum(dim=1) == 1).nonzero(as_tuple=True)
247 + torch.arange(nb_img_tokens - 1, device=input.device)[None, :],
249 ar_masks = input.new_zeros(input.size(), dtype=torch.int64)
252 torch.arange(self.vocabulary_size(), device=input.device) == t_nul
254 with torch.autograd.no_grad():
257 masked_inplace_autoregression(
267 input, loss_masks = self.trim((input, loss_masks))
269 return input, loss_masks
271 ######################
279 device=torch.device("cpu"),
283 def generate_descr(nb, cache_suffix, pruner):
284 return picoclvr.generate(
294 self.batch_size = batch_size
296 nb = args.data_size if args.data_size > 0 else 250000
297 self.pruner_train = pruner_train
298 self.pruner_eval = pruner_eval
304 "nb_colors": nb_colors,
305 "batch_size": batch_size,
306 "rng_state": list(torch.get_rng_state()),
309 log_string(f"generating {nb} samples (can take some time)")
310 self.train_descr = generate_descr(
311 (nb * 4) // 5, "train", pruner=self.pruner_train
313 self.test_descr = generate_descr((nb * 1) // 5, "test", pruner=None)
315 # Build the tokenizer
316 tokens = {"<nul>", "<img>"}
317 for d in [self.train_descr, self.test_descr]:
319 for t in s.strip().split(" "):
321 # make this set a sorted list to get the same tensors given
323 tokens = list(tokens)
325 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
326 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
328 # Tokenize the train and test sets
329 self.train_input = self.tensorize(self.train_descr)
330 self.test_input = self.tensorize(self.test_descr)
332 def batches(self, split="train"):
333 assert split in {"train", "test"}
334 input = self.train_input if split == "train" else self.test_input
335 for batch in tqdm.tqdm(
336 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
338 yield self.trim(batch)
340 def vocabulary_size(self):
341 return len(self.token2id)
343 def compute_missing_properties(self, n_epoch, model, pruner=None):
345 acc_nb_requested_properties = []
346 acc_nb_missing_properties = []
349 for input in tqdm.tqdm(
350 self.test_input.split(self.batch_size),
352 desc=f"test-properties",
354 tape, loss_masks, _ = self.excise_last_image(input)
355 tape, loss_masks = self.add_generated_image(tape, loss_masks, model)
356 result_descr = self.detensorize(tape)
357 np = picoclvr.nb_properties(
363 nb_requested_properties, _, nb_missing_properties = zip(*np)
364 acc_nb_requested_properties += nb_requested_properties
365 acc_nb_missing_properties += nb_missing_properties
366 acc_nb_results += len(result_descr)
368 nb_requested_properties = sum(acc_nb_requested_properties)
369 nb_missing_properties = sum(acc_nb_missing_properties)
371 prefix = "" if pruner is None else "pruned_"
372 log_string(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
374 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
377 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
380 ######################################################################
382 def produce_results(self, n_epoch, model):
384 self.compute_missing_properties(n_epoch, model)
386 if self.pruner_eval is not None:
387 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
389 nb_tokens_to_generate = self.height * self.width + 3
394 for primer_descr in [
395 "red above green <sep> green top <sep> blue right of red",
396 "there is red <sep> there is yellow <sep> there is blue",
397 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
398 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
400 primer += [primer_descr] * nb_per_primer
402 tape = self.tensorize(primer)
403 loss_masks = 1 - (tape == self.token2id["<nul>"]).long()
404 tape, loss_masks = self.add_generated_image(tape, loss_masks, model)
405 result_descr = self.detensorize(tape)
407 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
409 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
410 acc_nb_results = len(result_descr)
412 nb_requested_properties = sum(acc_nb_requested_properties)
413 nb_missing_properties = sum(acc_nb_missing_properties)
416 log_string(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
418 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
421 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
424 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
428 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
432 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
438 image_name = os.path.join(args.result_dir, f"result_{n_epoch:04d}.png")
439 torchvision.utils.save_image(
440 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=1.0
442 log_string(f"wrote {image_name}")
445 ######################################################################
447 log_string(f"device {device}")
450 def pruner_horizontal_green(p):
451 return not ("green" in p and ("left" in p or "right" in p))
455 batch_size=args.batch_size,
458 nb_colors=args.nb_colors,
460 pruner_train=pruner_horizontal_green
461 if args.prune_properties in {"train+eval"}
463 pruner_eval=(lambda p: not pruner_horizontal_green(p))
464 if args.prune_properties in {"train+eval", "eval"}
468 vocabulary_size = task.vocabulary_size()
470 log_string(f"vocabulary_size {vocabulary_size}")
472 ##############################
475 vocabulary_size=vocabulary_size,
476 dim_model=args.dim_model,
477 dim_keys=args.dim_keys,
478 dim_hidden=args.dim_hidden,
479 nb_heads=args.nb_heads,
480 nb_blocks=args.nb_blocks,
482 dropout=args.dropout,
487 nb_parameters = sum(p.numel() for p in model.parameters())
488 log_string(f"nb_parameters {nb_parameters} ({int(nb_parameters/1e6)}M)")
490 ######################################################################
492 nb_epochs_finished = 0
494 if args.no_checkpoint:
495 log_string(f"not trying to load checkpoint.")
499 checkpoint_name = os.path.join(args.result_dir, args.checkpoint_name)
500 checkpoint = torch.load(checkpoint_name)
501 nb_epochs_finished = checkpoint["nb_epochs_finished"]
502 model.load_state_dict(checkpoint["model_state"])
503 torch.set_rng_state(checkpoint["rng_state"])
504 if torch.cuda.is_available():
505 torch.cuda.set_rng_state(checkpoint["cuda_rng_state"])
507 log_string(f"checkpoint loaded with {nb_epochs_finished} epochs finished.")
509 except FileNotFoundError:
510 log_string("starting from scratch.")
513 log_string("error when loading the checkpoint.")
516 ######################################################################
518 nb_epochs = args.nb_epochs if args.nb_epochs > 0 else nb_epochs_default
521 for input in task.batches(split="train"):
522 token_count += F.one_hot(input, num_classes=task.vocabulary_size()).sum((0, 1))
523 token_probas = token_count / token_count.sum()
524 entropy = -torch.xlogy(token_probas, token_probas).sum()
525 train_set_perplexity = math.exp(entropy)
527 ##############################
529 if args.learning_rate_schedule == "cos":
530 learning_rate_schedule = {}
531 for n_epoch in range(args.nb_epochs):
532 u = n_epoch / args.nb_epochs * math.pi
533 learning_rate_schedule[n_epoch] = args.learning_rate * 0.5 * (1 + math.cos(u))
538 tuple(x.split(":")) for x in args.learning_rate_schedule.split(",")
542 learning_rate_schedule = {}
543 learning_rate = args.learning_rate
544 for n_epoch in range(args.nb_epochs):
546 learning_rate = u[n_epoch]
547 learning_rate_schedule[n_epoch] = learning_rate
549 log_string(f"learning_rate_schedule {learning_rate_schedule}")
551 ##############################
555 if nb_epochs_finished >= nb_epochs:
556 task.produce_results(nb_epochs_finished, model)
558 for n_epoch in range(nb_epochs_finished, nb_epochs):
560 learning_rate = learning_rate_schedule[n_epoch]
562 log_string(f"learning_rate {learning_rate}")
564 if args.optim == "sgd":
565 optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
566 elif args.optim == "adam":
567 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
568 elif args.optim == "adamw":
569 optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
571 raise ValueError(f"Unknown optimizer {args.optim}.")
575 nb_train_samples, acc_train_loss = 0, 0.0
577 for input in task.batches(split="train"):
578 input = input.to(device)
579 output = model(mygpt.BracketedSequence(input)).x
580 loss = F.cross_entropy(output.transpose(1, 2), input)
581 acc_train_loss += loss.item() * input.size(0)
582 nb_train_samples += input.size(0)
583 nb_samples_seen += input.size(0)
585 optimizer.zero_grad()
589 with torch.autograd.no_grad():
593 nb_test_samples, acc_test_loss = 0, 0.0
595 for input in task.batches(split="test"):
596 input = input.to(device)
598 # input, loss_masks, true_images = task.excise_last_image(input)
599 # input, loss_masks = task.add_true_image(input, true_images, loss_masks)
601 output = model(mygpt.BracketedSequence(input)).x
602 loss = F.cross_entropy(output.transpose(1, 2), input)
603 acc_test_loss += loss.item() * input.size(0)
604 nb_test_samples += input.size(0)
606 train_perplexity = math.exp(min(100, acc_train_loss / nb_train_samples))
607 test_perplexity = math.exp(min(100, acc_test_loss / nb_test_samples))
610 f"perplexity {n_epoch} train_set {train_set_perplexity} train_prediction {train_perplexity} test_prediction {test_perplexity}"
613 task.produce_results(n_epoch, model)
616 "nb_epochs_finished": n_epoch + 1,
617 "model_state": model.state_dict(),
618 "rng_state": torch.get_rng_state(),
621 if torch.cuda.is_available():
622 checkpoint["cuda_rng_state"] = torch.cuda.get_rng_state()
624 checkpoint_name = os.path.join(args.result_dir, args.checkpoint_name)
625 torch.save(checkpoint, checkpoint_name)
626 log_string(f"saved checkpoint {checkpoint_name}")
628 ######################################################################