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>
10 import torch, torchvision
13 from torch.nn import functional as F
15 from mygpt import BracketedSequence
18 from graph import save_attention_image
20 save_attention_image = None
22 ######################################################################
25 def masked_inplace_autoregression(
30 deterministic_synthesis,
31 forbidden_tokens=None,
32 progress_bar_desc="autoregression",
33 device=torch.device("cpu"),
35 assert input.size() == ar_mask.size()
37 batches = zip(input.split(batch_size), ar_mask.split(batch_size))
39 if progress_bar_desc is not None:
43 desc=progress_bar_desc,
44 total=(input.size(0) + batch_size - 1) // batch_size,
47 with torch.autograd.no_grad():
51 for input, ar_mask in batches:
52 model.masked_inplace_autoregression(
53 input, ar_mask, forbidden_tokens, deterministic_synthesis
59 ######################################################################
63 def batches(self, split="train"):
66 def vocabulary_size(self):
70 self, n_epoch, model, result_dir, logger, deterministic_synthesis
88 device=torch.device("cpu"),
93 self.batch_size = batch_size
95 self.problem = problem
97 self.train_input, self.train_ar_mask = self.problem.generate_sequences(
100 self.test_input, self.test_ar_mask = self.problem.generate_sequences(
104 self.train_input, self.train_ar_mask = self.train_input.to(
106 ), self.train_ar_mask.to(device)
107 self.test_input, self.test_ar_mask = self.test_input.to(
109 ), self.test_ar_mask.to(device)
111 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
113 # A bit of paranoia never hurts
115 self.nb_codes <= max_nb_codes
116 and self.train_input.min() >= 0
117 and self.test_input.min() >= 0
118 and tuple(self.train_ar_mask.unique()) == (0, 1)
119 and tuple(self.test_ar_mask.unique()) == (0, 1)
122 def batches(self, split="train", nb_to_use=-1, desc=None):
123 assert split in {"train", "test"}
124 input = self.train_input if split == "train" else self.test_input
126 input = input[:nb_to_use]
128 desc = f"epoch-{split}"
129 for batch in tqdm.tqdm(
130 input.split(self.batch_size), dynamic_ncols=True, desc=desc
134 def vocabulary_size(self):
138 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
140 def compute_accuracy(input, ar_mask, logger=None):
141 input, ar_mask = input[:nmax], ar_mask[:nmax]
142 result = input.clone() * (1 - ar_mask)
144 masked_inplace_autoregression(
149 deterministic_synthesis,
150 progress_bar_desc=None,
154 if logger is not None:
155 for sp, st in zip(result[:10], input[:10]):
157 f"test_sequences {n_epoch} prediction {self.problem.seq2str(sp)}"
160 f" {n_epoch} ground truth {self.problem.seq2str(st)}"
163 nb_total = ar_mask.sum().item()
164 nb_correct = ((result == input).long() * ar_mask).sum().item()
166 return nb_total, nb_correct
168 train_nb_total, train_nb_correct = compute_accuracy(
169 self.train_input, self.train_ar_mask
173 f"accuracy_train {n_epoch} nb_total {train_nb_total} nb_correct {train_nb_correct} accuracy {(100.0*train_nb_correct)/train_nb_total:.02f}%"
176 test_nb_total, test_nb_correct = compute_accuracy(
177 self.test_input, self.test_ar_mask, logger
181 f"accuracy_test {n_epoch} nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
184 if save_attention_image is not None:
185 ns = torch.randint(self.test_input.size(0), (1,)).item()
186 input = self.test_input[ns : ns + 1].clone()
188 with torch.autograd.no_grad():
191 model.record_attention(True)
192 model(BracketedSequence(input))
194 ram = model.retrieve_attention()
195 model.record_attention(False)
197 tokens_output = [c for c in self.problem.seq2str(input[0])]
198 tokens_input = ["n/a"] + tokens_output[:-1]
199 for n_head in range(ram[0].size(1)):
200 filename = os.path.join(
201 result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
203 attention_matrices = [m[0, n_head] for m in ram]
204 save_attention_image(
210 # min_total_attention=0.9,
214 logger(f"wrote {filename}")
217 ######################################################################
222 class PicoCLVR(Task):
223 # Make a tensor from a list of strings
224 def tensorize(self, descr):
225 token_descr = [s.strip().split(" ") for s in descr]
226 l = max([len(s) for s in token_descr])
227 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
228 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
229 return torch.tensor(id_descr, device=self.device)
231 # Make a list of strings from a tensor
232 def detensorize(self, x):
233 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
235 # trim all the tensors in the tuple z to remove as much token from
236 # left and right in the first tensor. If z is a tuple, all its
237 # elements are trimed according to the triming for the first
238 def trim(self, z, token="<nul>"):
239 n = self.token2id[token]
242 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
243 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
244 return tuple([t[:, a:b] for t in z])
246 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
247 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
250 ######################
261 device=torch.device("cpu"),
267 def generate_descr(nb, cache_suffix, pruner):
268 return picoclvr.generate(
278 self.batch_size = batch_size
280 self.pruner_train = pruner_train
281 self.pruner_eval = pruner_eval
283 if logger is not None:
285 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
288 self.train_descr = generate_descr(
289 nb_train_samples, "train", pruner=self.pruner_train
291 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
293 # Build the tokenizer
294 tokens = {"<nul>", "<img>"}
295 for d in [self.train_descr, self.test_descr]:
297 for t in s.strip().split(" "):
299 # make this set a sorted list to get the same tensors given
301 tokens = list(tokens)
303 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
304 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
305 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
307 # Tokenize the train and test sets
308 self.train_input = self.tensorize(self.train_descr)
309 self.test_input = self.tensorize(self.test_descr)
311 def batches(self, split="train"):
312 assert split in {"train", "test"}
313 input = self.train_input if split == "train" else self.test_input
314 for batch in tqdm.tqdm(
315 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
317 yield self.trim(batch)
319 def vocabulary_size(self):
320 return len(self.token2id)
322 def compute_missing_properties(
323 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
325 acc_nb_requested_properties = []
326 acc_nb_missing_properties = []
329 for input in tqdm.tqdm(
330 self.test_input.split(self.batch_size),
332 desc=f"test-properties",
334 result = input.clone()
335 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
336 result = (1 - ar_mask) * result + ar_mask * self.t_nul
337 masked_inplace_autoregression(
342 deterministic_synthesis,
343 progress_bar_desc=None,
347 result_descr = self.detensorize(result)
348 np = picoclvr.nb_properties(
354 nb_requested_properties, _, nb_missing_properties = zip(*np)
355 acc_nb_requested_properties += nb_requested_properties
356 acc_nb_missing_properties += nb_missing_properties
357 acc_nb_results += len(result_descr)
359 nb_requested_properties = sum(acc_nb_requested_properties)
360 nb_missing_properties = sum(acc_nb_missing_properties)
362 prefix = "" if pruner is None else "pruned_"
363 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
365 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
368 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
371 ######################################################################
374 self, n_epoch, model, result_dir, logger, deterministic_synthesis
376 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
378 if self.pruner_eval is not None:
379 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
381 nb_tokens_to_generate = self.height * self.width + 3
386 for primer_descr in [
387 "red above green <sep> green top <sep> blue right of red",
388 "there is red <sep> there is yellow <sep> there is blue",
389 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
390 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
392 primer += [primer_descr + " <img>"] * nb_per_primer
394 result = self.tensorize(primer)
395 fill = result.new_full(
396 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
398 result = torch.cat((result, fill), 1)
399 ar_mask = (result == self.t_nul).long()
400 masked_inplace_autoregression(
405 deterministic_synthesis,
408 result_descr = self.detensorize(result)
410 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
412 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
413 acc_nb_results = len(result_descr)
415 nb_requested_properties = sum(acc_nb_requested_properties)
416 nb_missing_properties = sum(acc_nb_missing_properties)
419 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
421 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
424 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
427 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
431 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
435 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
441 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
442 torchvision.utils.save_image(
443 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
445 logger(f"wrote {image_name}")
448 ######################################################################
453 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
457 self.nb_train_samples = (nb_train_samples,)
458 self.nb_test_samples = (nb_test_samples,)
459 self.batch_size = batch_size
461 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
462 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
463 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
464 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
466 def batches(self, split="train", nb_to_use=-1, desc=None):
467 assert split in {"train", "test"}
468 input = self.train_input if split == "train" else self.test_input
470 input = input[:nb_to_use]
472 desc = f"epoch-{split}"
473 for batch in tqdm.tqdm(
474 input.split(self.batch_size), dynamic_ncols=True, desc=desc
478 def vocabulary_size(self):
482 self, n_epoch, model, result_dir, logger, deterministic_synthesis
484 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
485 ar_mask = torch.full_like(results, 1)
486 masked_inplace_autoregression(
491 deterministic_synthesis,
494 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
495 torchvision.utils.save_image(
496 1 - results.reshape(-1, 1, 28, 28) / 255.0,
501 logger(f"wrote {image_name}")
504 ######################################################################
510 def map2seq(self, *m):
511 return torch.cat([x.flatten(1) for x in m], 1)
513 def seq2map(self, s):
514 s = s.reshape(s.size(0), -1, self.height, self.width)
515 return (s[:, k] for k in range(s.size(1)))
525 device=torch.device("cpu"),
529 self.batch_size = batch_size
534 train_mazes, train_paths, _ = maze.create_maze_data(
539 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
541 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
543 test_mazes, test_paths, _ = maze.create_maze_data(
548 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
550 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
552 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
554 def batches(self, split="train", nb_to_use=-1, desc=None):
555 assert split in {"train", "test"}
556 input = self.train_input if split == "train" else self.test_input
558 input = input[:nb_to_use]
560 desc = f"epoch-{split}"
561 for batch in tqdm.tqdm(
562 input.split(self.batch_size), dynamic_ncols=True, desc=desc
566 def vocabulary_size(self):
570 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
572 nb_total, nb_correct = 0, 0
574 self.width * self.height,
575 self.width * self.height,
580 for input in self.batches(split, nb_to_use):
581 result = input.clone()
582 ar_mask = result.new_zeros(result.size())
583 ar_mask[:, self.height * self.width :] = 1
584 result *= 1 - ar_mask
585 masked_inplace_autoregression(
590 deterministic_synthesis,
591 progress_bar_desc=None,
594 mazes, paths = self.seq2map(result)
595 path_correctness = maze.path_correctness(mazes, paths)
596 nb_correct += path_correctness.long().sum()
597 nb_total += mazes.size(0)
599 optimal_path_lengths = (
600 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
602 predicted_path_lengths = (
603 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
605 optimal_path_lengths = optimal_path_lengths[path_correctness]
606 predicted_path_lengths = predicted_path_lengths[path_correctness]
607 count[optimal_path_lengths, predicted_path_lengths] += 1
613 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
616 return nb_total, nb_correct, count
619 self, n_epoch, model, result_dir, logger, deterministic_synthesis
621 train_nb_total, train_nb_correct, count = self.compute_error(
625 deterministic_synthesis=deterministic_synthesis,
628 f"accuracy_train {n_epoch} nb_total {train_nb_total} nb_correct {train_nb_correct} accuracy {(100.0*train_nb_correct)/train_nb_total:.02f}%"
631 test_nb_total, test_nb_correct, count = self.compute_error(
635 deterministic_synthesis=deterministic_synthesis,
638 f"accuracy_test {n_epoch} nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
641 if count is not None:
642 proportion_optimal = count.diagonal().sum().float() / count.sum()
643 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
645 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
647 for i in range(count.size(0)):
648 for j in range(count.size(1)):
649 eol = " " if j < count.size(1) - 1 else "\n"
650 f.write(f"{count[i,j]}{eol}")
652 input = self.test_input[:48]
653 result = input.clone()
654 ar_mask = result.new_zeros(result.size())
655 ar_mask[:, self.height * self.width :] = 1
656 result *= 1 - ar_mask
657 masked_inplace_autoregression(
662 deterministic_synthesis,
666 mazes, paths = self.seq2map(input)
667 _, predicted_paths = self.seq2map(result)
669 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
674 predicted_paths=predicted_paths,
675 path_correct=maze.path_correctness(mazes, predicted_paths),
676 path_optimal=maze.path_optimality(paths, predicted_paths),
678 logger(f"wrote {filename}")
681 ######################################################################
698 device=torch.device("cpu"),
702 self.batch_size = batch_size
706 self.prompt_length = prompt_length
708 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
717 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
727 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
729 def batches(self, split="train", nb_to_use=-1, desc=None):
730 assert split in {"train", "test"}
731 input = self.train_input if split == "train" else self.test_input
733 input = input[:nb_to_use]
735 desc = f"epoch-{split}"
736 for batch in tqdm.tqdm(
737 input.split(self.batch_size), dynamic_ncols=True, desc=desc
741 def vocabulary_size(self):
745 self, n_epoch, model, result_dir, logger, deterministic_synthesis
747 def compute_nb_correct(input, prior_visits):
748 result = input.clone()
749 i = torch.arange(result.size(1), device=result.device)[None, :]
751 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
755 result *= 1 - ar_mask
757 masked_inplace_autoregression(
762 deterministic_synthesis,
766 nb_total = ((prior_visits > 0) * ar_mask).sum()
768 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
770 return nb_total, nb_correct
772 test_nb_total, test_nb_correct = compute_nb_correct(
773 self.test_input[:1000], self.test_prior_visits[:1000]
777 f"accuracy_test {n_epoch} nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
781 ######################################################################
797 fraction_values_for_train=None,
798 device=torch.device("cpu"),
802 self.batch_size = batch_size
803 self.nb_steps = nb_steps
804 self.nb_stacks = nb_stacks
805 self.nb_digits = nb_digits
808 if fraction_values_for_train is None:
809 values_for_train = None
810 values_for_test = None
812 all = torch.randperm(10**nb_digits)
813 nb_for_train = int(all.size(0) * fraction_values_for_train)
814 values_for_train = all[:nb_for_train]
815 values_for_test = all[nb_for_train:]
817 self.train_input, self.train_stack_counts = stack.generate_sequences(
826 self.test_input, self.test_stack_counts = stack.generate_sequences(
835 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
836 counts = self.test_stack_counts.flatten()[i.flatten()]
837 counts = F.one_hot(counts).sum(0)
838 logger(f"test_pop_stack_counts {counts}")
840 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
842 def batches(self, split="train", nb_to_use=-1, desc=None):
843 assert split in {"train", "test"}
844 input = self.train_input if split == "train" else self.test_input
846 input = input[:nb_to_use]
848 desc = f"epoch-{split}"
849 for batch in tqdm.tqdm(
850 input.split(self.batch_size), dynamic_ncols=True, desc=desc
854 def vocabulary_size(self):
858 self, n_epoch, model, result_dir, logger, deterministic_synthesis
860 def compute_nb_correct(input):
861 result = input.clone()
862 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
863 ar_mask = (result != input).long()
864 masked_inplace_autoregression(
869 deterministic_synthesis,
873 errors = ((result != input).long() * ar_mask).reshape(
874 -1, 1 + self.nb_digits
876 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
878 nb_total = ar_mask.max(1).values.sum()
879 nb_correct = nb_total - errors.max(1).values.sum()
881 return nb_total, nb_correct
883 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
886 f"accuracy_test {n_epoch} nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
889 ##############################################################
890 # Log a few generated sequences
891 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
892 result = input.clone()
893 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
894 ar_mask = (result != input).long()
896 # for n in range(result.size(0)):
898 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
901 masked_inplace_autoregression(
906 deterministic_synthesis,
910 for n in range(result.size(0)):
912 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
914 ##############################################################
917 ######################################################################
923 def tensorize(self, sequences):
924 len_max = max([len(x) for x in sequences])
930 self.token2id[str(c)]
931 for c in s + ["<nul>"] * (len_max - len(s))
940 def seq2str(self, seq):
941 return " ".join([self.id2token[i] for i in seq])
948 nb_starting_values=3,
954 device=torch.device("cpu"),
958 self.batch_size = batch_size
960 self.no_prog = no_prog
964 nb_starting_values=nb_starting_values,
965 nb_result_values_max=4 * nb_starting_values,
970 for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
975 nb_starting_values=nb_starting_values,
976 nb_result_values_max=4 * nb_starting_values,
981 for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
985 set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
987 val_max = max([x if type(x) is int else 0 for x in symbols])
988 symbols = list(filter(lambda x: type(x) is str, symbols))
990 symbols += [str(n) for n in range(val_max + 1)]
991 self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
992 self.id2token = dict([(n, c) for c, n in self.token2id.items()])
994 self.t_nul = self.token2id["<nul>"]
995 self.t_input = self.token2id["<in>"]
996 self.t_output = self.token2id["<out>"]
997 self.t_prog = self.token2id["<prg>"]
998 self.t_end = self.token2id["<end>"]
1000 self.train_input = self.tensorize(train_sequences)
1001 self.test_input = self.tensorize(test_sequences)
1004 # Excise the program from every train and test example
1005 k = torch.arange(self.train_input.size(1), device=self.train_input.device)[
1009 ((self.train_input == self.t_prog).long() * k)
1010 .max(1, keepdim=True)
1013 self.train_input = (
1014 self.train_input * (k <= p).long()
1015 + self.t_end * (k == p + 1).long()
1016 + self.t_nul * (k > p + 1).long()
1018 k = torch.arange(self.test_input.size(1), device=self.test_input.device)[
1022 ((self.test_input == self.t_prog).long() * k)
1023 .max(1, keepdim=True)
1027 self.test_input * (k <= p).long()
1028 + self.t_end * (k == p + 1).long()
1029 + self.t_nul * (k > p + 1).long()
1032 if logger is not None:
1033 logger(f"value_max {val_max}")
1034 for x in self.train_input[:25]:
1035 end = (x != self.t_nul).nonzero().max().item() + 1
1036 seq = [self.id2token[i.item()] for i in x[:end]]
1038 logger(f"example_seq {s}")
1040 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1042 def batches(self, split="train", nb_to_use=-1, desc=None):
1043 assert split in {"train", "test"}
1044 input = self.train_input if split == "train" else self.test_input
1046 input = input[:nb_to_use]
1048 desc = f"epoch-{split}"
1049 for batch in tqdm.tqdm(
1050 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1052 last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1053 batch = batch[:, :last].to(self.device)
1056 def vocabulary_size(self):
1057 return self.nb_codes
1059 def produce_results(
1060 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1062 # --------------------------------------------------------------------
1063 def compute_nb_errors_prog(input, nb_to_log=0):
1064 result = input.clone()
1065 s = (result == self.t_prog).long()
1066 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1067 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1069 masked_inplace_autoregression(
1074 deterministic_synthesis,
1078 sum_nb_total, sum_nb_errors = 0, 0
1079 for one_input, one_result in zip(input, result):
1080 seq = [self.id2token[i.item()] for i in one_result]
1081 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1083 sum_nb_errors += 0 if nb_errors == 0 else 1
1085 gt_seq = [self.id2token[i.item()] for i in one_input]
1086 _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1087 gt_prog = " ".join([str(x) for x in gt_prog])
1088 prog = " ".join([str(x) for x in prog])
1089 comment = "*" if nb_errors == 0 else "-"
1090 logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1091 for start_stack, target_stack, result_stack, correct in stacks:
1092 comment = "*" if correct else "-"
1093 start_stack = " ".join([str(x) for x in start_stack])
1094 target_stack = " ".join([str(x) for x in target_stack])
1095 result_stack = " ".join([str(x) for x in result_stack])
1097 f" {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1101 return sum_nb_total, sum_nb_errors
1103 # --------------------------------------------------------------------
1104 def compute_nb_errors_output(input, nb_to_log=0):
1105 result = input.clone()
1106 k = torch.arange(result.size(1), device=result.device)[None, :]
1108 ((result == self.t_output) * k).max(dim=1, keepdim=True).values
1111 ((result == self.t_prog) * k).max(dim=1, keepdim=True).values
1113 ar_mask = (k > last_output_idx).long() * (k < first_prog_idx).long()
1114 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1116 masked_inplace_autoregression(
1121 deterministic_synthesis,
1125 sum_nb_total, sum_nb_errors = 0, 0
1126 for one_input, one_result, i, j in zip(
1127 input, result, last_output_idx, first_prog_idx
1129 seq = [self.id2token[i.item()] for i in one_result]
1131 correct = (one_input - one_result).abs().max() == 0
1132 sum_nb_errors += 0 if correct else 1
1135 self.id2token[i.item()] for i in one_result[i : j + 1]
1138 self.id2token[i.item()] for i in one_input[i : j + 1]
1140 comment = "*" if correct else "-"
1141 result_stack = " ".join([str(x) for x in result_stack])
1142 target_stack = " ".join([str(x) for x in target_stack])
1144 f"output_test {comment} [{target_stack}] PREDICTED [{result_stack}]"
1148 return sum_nb_total, sum_nb_errors
1150 # --------------------------------------------------------------------
1152 if not self.no_prog:
1153 test_nb_total, test_nb_errors = compute_nb_errors_prog(
1154 self.test_input[:1000].to(self.device), nb_to_log=10
1158 f"accuracy_prog_test {n_epoch} nb_total {test_nb_total} nb_errors {test_nb_errors} accuracy {100.0*(1-test_nb_errors/test_nb_total):.02f}%"
1161 test_nb_total, test_nb_errors = compute_nb_errors_output(
1162 self.test_input[:1000].to(self.device), nb_to_log=10
1166 f"accuracy_output_test {n_epoch} nb_total {test_nb_total} nb_errors {test_nb_errors} accuracy {100.0*(1-test_nb_errors/test_nb_total):.02f}%"
1169 if save_attention_image is not None:
1170 ns = torch.randint(self.test_input.size(0), (1,)).item()
1171 input = self.test_input[ns : ns + 1].clone()
1172 last = (input != self.t_nul).max(0).values.nonzero().max() + 3
1173 input = input[:, :last].to(self.device)
1175 with torch.autograd.no_grad():
1178 model.record_attention(True)
1179 model(BracketedSequence(input))
1181 ram = model.retrieve_attention()
1182 model.record_attention(False)
1184 tokens_output = [self.id2token[i.item()] for i in input[0]]
1185 tokens_input = ["n/a"] + tokens_output[:-1]
1186 for n_head in range(ram[0].size(1)):
1187 filename = os.path.join(
1188 result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
1190 attention_matrices = [m[0, n_head] for m in ram]
1191 save_attention_image(
1197 # min_total_attention=0.9,
1201 logger(f"wrote {filename}")
1204 ######################################################################
1211 def tensorize(self, sequences):
1212 len_max = max([len(x) for x in sequences])
1217 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1234 device=torch.device("cpu"),
1238 self.batch_size = batch_size
1239 self.device = device
1241 train_sequences = expr.generate_sequences(
1243 nb_variables=nb_variables,
1244 length=sequence_length,
1245 operand_max=operand_max,
1246 result_max=result_max,
1249 test_sequences = expr.generate_sequences(
1251 nb_variables=nb_variables,
1252 length=sequence_length,
1253 operand_max=operand_max,
1254 result_max=result_max,
1257 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1260 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1261 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1263 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1265 self.train_input = self.tensorize(train_sequences)
1266 self.test_input = self.tensorize(test_sequences)
1268 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1270 def batches(self, split="train", nb_to_use=-1, desc=None):
1271 assert split in {"train", "test"}
1272 input = self.train_input if split == "train" else self.test_input
1274 input = input[:nb_to_use]
1276 desc = f"epoch-{split}"
1277 for batch in tqdm.tqdm(
1278 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1280 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1281 batch = batch[:, :last]
1284 def vocabulary_size(self):
1285 return self.nb_codes
1287 def seq2str(self, s):
1288 return "".join([self.id2char[k.item()] for k in s])
1290 def produce_results(
1296 deterministic_synthesis,
1299 def compute_nb_correct(input):
1300 result = input.clone()
1301 s = (result == self.space).long()
1302 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1303 result = (1 - ar_mask) * result + ar_mask * self.filler
1304 masked_inplace_autoregression(
1309 deterministic_synthesis,
1313 nb_total = input.size(0)
1314 nb_correct = (input == result).long().min(1).values.sum()
1316 #######################################################################
1317 # Comput predicted vs. true variable values
1319 nb_delta = torch.zeros(5, dtype=torch.int64)
1322 values_input = expr.extract_results([self.seq2str(s) for s in input])
1323 values_result = expr.extract_results([self.seq2str(s) for s in result])
1325 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1327 with open(filename, "w") as f:
1328 for i, r in zip(values_input, values_result):
1329 for n, vi in i.items():
1331 f.write(f"{vi} {-1 if vr is None else vr}\n")
1333 if vr is None or vr < 0:
1337 if d >= nb_delta.size(0):
1342 ######################################################################
1344 return nb_total, nb_correct, nb_delta, nb_missed
1351 ) = compute_nb_correct(self.test_input[:10000])
1354 f"accuracy_test {n_epoch} nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
1357 nb_total = test_nb_delta.sum() + test_nb_missed
1358 for d in range(test_nb_delta.size(0)):
1360 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1363 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1366 ##############################################################
1367 # Log a few generated sequences
1368 if input_file is None:
1369 input = self.test_input[:10]
1371 with open(input_file, "r") as f:
1372 sequences = [e.strip() for e in f.readlines()]
1373 sequences = [s + " " + "#" * 50 for s in sequences]
1374 input = self.tensorize(sequences)
1376 result = input.clone()
1377 s = (result == self.space).long()
1378 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1379 result = (1 - ar_mask) * result + ar_mask * self.filler
1381 for n in range(result.size(0)):
1382 logger(f"test_before {self.seq2str(result[n])}")
1384 masked_inplace_autoregression(
1389 deterministic_synthesis,
1393 correct = (1 - ar_mask) * self.space + ar_mask * input
1394 for n in range(result.size(0)):
1395 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1396 logger(f"test_after {self.seq2str(result[n])} {comment}")
1397 logger(f"truth {self.seq2str(correct[n])}")
1398 ##############################################################
1401 ######################################################################
1414 device=torch.device("cpu"),
1415 device_storage=torch.device("cpu"),
1419 self.batch_size = batch_size
1420 self.device = device
1429 ) = world.create_data_and_processors(
1434 nb_epochs=vqae_nb_epochs,
1437 device_storage=device_storage,
1440 train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1441 test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1443 nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1444 nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1446 self.len_frame_seq = train_frame_seq.size(1)
1447 self.len_action_seq = train_action_seq.size(1)
1448 self.nb_codes = nb_frame_codes + nb_action_codes
1450 train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1452 train_action_seq += nb_frame_codes
1453 self.train_input = torch.cat(
1454 (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1457 test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1458 test_action_seq += nb_frame_codes
1459 self.test_input = torch.cat(
1460 (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1463 def batches(self, split="train", nb_to_use=-1, desc=None):
1464 assert split in {"train", "test"}
1465 input = self.train_input if split == "train" else self.test_input
1467 input = input[:nb_to_use]
1469 desc = f"epoch-{split}"
1470 for batch in tqdm.tqdm(
1471 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1473 yield batch.to(self.device)
1475 def vocabulary_size(self):
1476 return self.nb_codes
1478 def produce_results(
1479 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1482 2 * self.len_frame_seq + self.len_action_seq, device=self.device
1485 input = self.test_input[:64].to(self.device)
1486 result = input.clone()
1489 (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1491 result *= 1 - ar_mask
1493 masked_inplace_autoregression(
1498 deterministic_synthesis,
1502 seq_start = input[:, : self.len_frame_seq]
1503 seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1504 seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1507 (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1509 result = result.reshape(-1, result.size(-1))
1511 frames = self.seq2frame(result)
1512 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1513 torchvision.utils.save_image(
1514 frames.float() / (world.Box.nb_rgb_levels - 1),
1520 logger(f"wrote {image_name}")
1523 ######################################################################