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:
186 ns = torch.randint(self.test_input.size(0), (1,)).item()
187 input = self.test_input[ns : ns + 1].clone()
189 with torch.autograd.no_grad():
192 model.record_attention(True)
193 model(BracketedSequence(input))
195 ram = model.retrieve_attention()
196 model.record_attention(False)
198 tokens_output = [c for c in self.problem.seq2str(input[0])]
199 tokens_input = ["n/a"] + tokens_output[:-1]
200 for n_head in range(ram[0].size(1)):
201 filename = os.path.join(
202 result_dir, f"sandbox_attention_{k}_h{n_head}.pdf"
204 attention_matrices = [m[0, n_head] for m in ram]
205 save_attention_image(
211 # min_total_attention=0.9,
215 logger(f"wrote {filename}")
218 ######################################################################
223 class PicoCLVR(Task):
224 # Make a tensor from a list of strings
225 def tensorize(self, descr):
226 token_descr = [s.strip().split(" ") for s in descr]
227 l = max([len(s) for s in token_descr])
228 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
229 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
230 return torch.tensor(id_descr, device=self.device)
232 # Make a list of strings from a tensor
233 def detensorize(self, x):
234 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
236 # trim all the tensors in the tuple z to remove as much token from
237 # left and right in the first tensor. If z is a tuple, all its
238 # elements are trimed according to the triming for the first
239 def trim(self, z, token="<nul>"):
240 n = self.token2id[token]
243 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
244 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
245 return tuple([t[:, a:b] for t in z])
247 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
248 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
251 ######################
262 device=torch.device("cpu"),
268 def generate_descr(nb, cache_suffix, pruner):
269 return picoclvr.generate(
279 self.batch_size = batch_size
281 self.pruner_train = pruner_train
282 self.pruner_eval = pruner_eval
284 if logger is not None:
286 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
289 self.train_descr = generate_descr(
290 nb_train_samples, "train", pruner=self.pruner_train
292 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
294 # Build the tokenizer
295 tokens = {"<nul>", "<img>"}
296 for d in [self.train_descr, self.test_descr]:
298 for t in s.strip().split(" "):
300 # make this set a sorted list to get the same tensors given
302 tokens = list(tokens)
304 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
305 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
306 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
308 # Tokenize the train and test sets
309 self.train_input = self.tensorize(self.train_descr)
310 self.test_input = self.tensorize(self.test_descr)
312 def batches(self, split="train"):
313 assert split in {"train", "test"}
314 input = self.train_input if split == "train" else self.test_input
315 for batch in tqdm.tqdm(
316 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
318 yield self.trim(batch)
320 def vocabulary_size(self):
321 return len(self.token2id)
323 def compute_missing_properties(
324 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
326 acc_nb_requested_properties = []
327 acc_nb_missing_properties = []
330 for input in tqdm.tqdm(
331 self.test_input.split(self.batch_size),
333 desc=f"test-properties",
335 result = input.clone()
336 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
337 result = (1 - ar_mask) * result + ar_mask * self.t_nul
338 masked_inplace_autoregression(
343 deterministic_synthesis,
344 progress_bar_desc=None,
348 result_descr = self.detensorize(result)
349 np = picoclvr.nb_properties(
355 nb_requested_properties, _, nb_missing_properties = zip(*np)
356 acc_nb_requested_properties += nb_requested_properties
357 acc_nb_missing_properties += nb_missing_properties
358 acc_nb_results += len(result_descr)
360 nb_requested_properties = sum(acc_nb_requested_properties)
361 nb_missing_properties = sum(acc_nb_missing_properties)
363 prefix = "" if pruner is None else "pruned_"
364 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
366 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
369 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
372 ######################################################################
375 self, n_epoch, model, result_dir, logger, deterministic_synthesis
377 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
379 if self.pruner_eval is not None:
380 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
382 nb_tokens_to_generate = self.height * self.width + 3
387 for primer_descr in [
388 "red above green <sep> green top <sep> blue right of red",
389 "there is red <sep> there is yellow <sep> there is blue",
390 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
391 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
393 primer += [primer_descr + " <img>"] * nb_per_primer
395 result = self.tensorize(primer)
396 fill = result.new_full(
397 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
399 result = torch.cat((result, fill), 1)
400 ar_mask = (result == self.t_nul).long()
401 masked_inplace_autoregression(
406 deterministic_synthesis,
409 result_descr = self.detensorize(result)
411 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
413 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
414 acc_nb_results = len(result_descr)
416 nb_requested_properties = sum(acc_nb_requested_properties)
417 nb_missing_properties = sum(acc_nb_missing_properties)
420 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
422 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
425 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
428 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
432 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
436 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
442 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
443 torchvision.utils.save_image(
444 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
446 logger(f"wrote {image_name}")
449 ######################################################################
454 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
458 self.nb_train_samples = (nb_train_samples,)
459 self.nb_test_samples = (nb_test_samples,)
460 self.batch_size = batch_size
462 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
463 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
464 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
465 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
467 def batches(self, split="train", nb_to_use=-1, desc=None):
468 assert split in {"train", "test"}
469 input = self.train_input if split == "train" else self.test_input
471 input = input[:nb_to_use]
473 desc = f"epoch-{split}"
474 for batch in tqdm.tqdm(
475 input.split(self.batch_size), dynamic_ncols=True, desc=desc
479 def vocabulary_size(self):
483 self, n_epoch, model, result_dir, logger, deterministic_synthesis
485 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
486 ar_mask = torch.full_like(results, 1)
487 masked_inplace_autoregression(
492 deterministic_synthesis,
495 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
496 torchvision.utils.save_image(
497 1 - results.reshape(-1, 1, 28, 28) / 255.0,
502 logger(f"wrote {image_name}")
505 ######################################################################
511 def map2seq(self, *m):
512 return torch.cat([x.flatten(1) for x in m], 1)
514 def seq2map(self, s):
515 s = s.reshape(s.size(0), -1, self.height, self.width)
516 return (s[:, k] for k in range(s.size(1)))
526 device=torch.device("cpu"),
530 self.batch_size = batch_size
535 train_mazes, train_paths, _ = maze.create_maze_data(
540 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
542 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
544 test_mazes, test_paths, _ = maze.create_maze_data(
549 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
551 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
553 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
555 def batches(self, split="train", nb_to_use=-1, desc=None):
556 assert split in {"train", "test"}
557 input = self.train_input if split == "train" else self.test_input
559 input = input[:nb_to_use]
561 desc = f"epoch-{split}"
562 for batch in tqdm.tqdm(
563 input.split(self.batch_size), dynamic_ncols=True, desc=desc
567 def vocabulary_size(self):
571 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
573 nb_total, nb_correct = 0, 0
575 self.width * self.height,
576 self.width * self.height,
581 for input in self.batches(split, nb_to_use):
582 result = input.clone()
583 ar_mask = result.new_zeros(result.size())
584 ar_mask[:, self.height * self.width :] = 1
585 result *= 1 - ar_mask
586 masked_inplace_autoregression(
591 deterministic_synthesis,
592 progress_bar_desc=None,
595 mazes, paths = self.seq2map(result)
596 path_correctness = maze.path_correctness(mazes, paths)
597 nb_correct += path_correctness.long().sum()
598 nb_total += mazes.size(0)
600 optimal_path_lengths = (
601 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
603 predicted_path_lengths = (
604 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
606 optimal_path_lengths = optimal_path_lengths[path_correctness]
607 predicted_path_lengths = predicted_path_lengths[path_correctness]
608 count[optimal_path_lengths, predicted_path_lengths] += 1
614 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
617 return nb_total, nb_correct, count
620 self, n_epoch, model, result_dir, logger, deterministic_synthesis
622 train_nb_total, train_nb_correct, count = self.compute_error(
626 deterministic_synthesis=deterministic_synthesis,
629 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}%"
632 test_nb_total, test_nb_correct, count = self.compute_error(
636 deterministic_synthesis=deterministic_synthesis,
639 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}%"
642 if count is not None:
643 proportion_optimal = count.diagonal().sum().float() / count.sum()
644 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
646 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
648 for i in range(count.size(0)):
649 for j in range(count.size(1)):
650 eol = " " if j < count.size(1) - 1 else "\n"
651 f.write(f"{count[i,j]}{eol}")
653 input = self.test_input[:48]
654 result = input.clone()
655 ar_mask = result.new_zeros(result.size())
656 ar_mask[:, self.height * self.width :] = 1
657 result *= 1 - ar_mask
658 masked_inplace_autoregression(
663 deterministic_synthesis,
667 mazes, paths = self.seq2map(input)
668 _, predicted_paths = self.seq2map(result)
670 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
675 predicted_paths=predicted_paths,
676 path_correct=maze.path_correctness(mazes, predicted_paths),
677 path_optimal=maze.path_optimality(paths, predicted_paths),
679 logger(f"wrote {filename}")
682 ######################################################################
699 device=torch.device("cpu"),
703 self.batch_size = batch_size
707 self.prompt_length = prompt_length
709 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
718 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
728 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
730 def batches(self, split="train", nb_to_use=-1, desc=None):
731 assert split in {"train", "test"}
732 input = self.train_input if split == "train" else self.test_input
734 input = input[:nb_to_use]
736 desc = f"epoch-{split}"
737 for batch in tqdm.tqdm(
738 input.split(self.batch_size), dynamic_ncols=True, desc=desc
742 def vocabulary_size(self):
746 self, n_epoch, model, result_dir, logger, deterministic_synthesis
748 def compute_nb_correct(input, prior_visits):
749 result = input.clone()
750 i = torch.arange(result.size(1), device=result.device)[None, :]
752 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
756 result *= 1 - ar_mask
758 masked_inplace_autoregression(
763 deterministic_synthesis,
767 nb_total = ((prior_visits > 0) * ar_mask).sum()
769 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
771 return nb_total, nb_correct
773 test_nb_total, test_nb_correct = compute_nb_correct(
774 self.test_input[:1000], self.test_prior_visits[:1000]
778 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}%"
782 ######################################################################
798 fraction_values_for_train=None,
799 device=torch.device("cpu"),
803 self.batch_size = batch_size
804 self.nb_steps = nb_steps
805 self.nb_stacks = nb_stacks
806 self.nb_digits = nb_digits
809 if fraction_values_for_train is None:
810 values_for_train = None
811 values_for_test = None
813 all = torch.randperm(10**nb_digits)
814 nb_for_train = int(all.size(0) * fraction_values_for_train)
815 values_for_train = all[:nb_for_train]
816 values_for_test = all[nb_for_train:]
818 self.train_input, self.train_stack_counts = stack.generate_sequences(
827 self.test_input, self.test_stack_counts = stack.generate_sequences(
836 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
837 counts = self.test_stack_counts.flatten()[i.flatten()]
838 counts = F.one_hot(counts).sum(0)
839 logger(f"test_pop_stack_counts {counts}")
841 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
843 def batches(self, split="train", nb_to_use=-1, desc=None):
844 assert split in {"train", "test"}
845 input = self.train_input if split == "train" else self.test_input
847 input = input[:nb_to_use]
849 desc = f"epoch-{split}"
850 for batch in tqdm.tqdm(
851 input.split(self.batch_size), dynamic_ncols=True, desc=desc
855 def vocabulary_size(self):
859 self, n_epoch, model, result_dir, logger, deterministic_synthesis
861 def compute_nb_correct(input):
862 result = input.clone()
863 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
864 ar_mask = (result != input).long()
865 masked_inplace_autoregression(
870 deterministic_synthesis,
874 errors = ((result != input).long() * ar_mask).reshape(
875 -1, 1 + self.nb_digits
877 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
879 nb_total = ar_mask.max(1).values.sum()
880 nb_correct = nb_total - errors.max(1).values.sum()
882 return nb_total, nb_correct
884 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
887 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}%"
890 ##############################################################
891 # Log a few generated sequences
892 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
893 result = input.clone()
894 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
895 ar_mask = (result != input).long()
897 # for n in range(result.size(0)):
899 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
902 masked_inplace_autoregression(
907 deterministic_synthesis,
911 for n in range(result.size(0)):
913 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
915 ##############################################################
918 ######################################################################
924 def tensorize(self, sequences):
925 len_max = max([len(x) for x in sequences])
931 self.token2id[str(c)]
932 for c in s + ["<nul>"] * (len_max - len(s))
941 def seq2str(self, seq):
942 return " ".join([self.id2token[i] for i in seq])
949 nb_starting_values=3,
955 device=torch.device("cpu"),
959 self.batch_size = batch_size
961 self.no_prog = no_prog
965 nb_starting_values=nb_starting_values,
966 nb_result_values_max=4 * nb_starting_values,
971 for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
976 nb_starting_values=nb_starting_values,
977 nb_result_values_max=4 * nb_starting_values,
982 for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
986 set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
988 val_max = max([x if type(x) is int else 0 for x in symbols])
989 symbols = list(filter(lambda x: type(x) is str, symbols))
991 symbols += [str(n) for n in range(val_max + 1)]
992 self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
993 self.id2token = dict([(n, c) for c, n in self.token2id.items()])
995 self.t_nul = self.token2id["<nul>"]
996 self.t_input = self.token2id["<in>"]
997 self.t_output = self.token2id["<out>"]
998 self.t_prog = self.token2id["<prg>"]
999 self.t_end = self.token2id["<end>"]
1001 self.train_input = self.tensorize(train_sequences)
1002 self.test_input = self.tensorize(test_sequences)
1005 # Excise the program from every train and test example
1006 k = torch.arange(self.train_input.size(1), device=self.train_input.device)[
1010 ((self.train_input == self.t_prog).long() * k)
1011 .max(1, keepdim=True)
1014 self.train_input = (
1015 self.train_input * (k <= p).long()
1016 + self.t_end * (k == p + 1).long()
1017 + self.t_nul * (k > p + 1).long()
1019 k = torch.arange(self.test_input.size(1), device=self.test_input.device)[
1023 ((self.test_input == self.t_prog).long() * k)
1024 .max(1, keepdim=True)
1028 self.test_input * (k <= p).long()
1029 + self.t_end * (k == p + 1).long()
1030 + self.t_nul * (k > p + 1).long()
1033 if logger is not None:
1034 logger(f"value_max {val_max}")
1035 for x in self.train_input[:25]:
1036 end = (x != self.t_nul).nonzero().max().item() + 1
1037 seq = [self.id2token[i.item()] for i in x[:end]]
1039 logger(f"example_seq {s}")
1041 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1043 def batches(self, split="train", nb_to_use=-1, desc=None):
1044 assert split in {"train", "test"}
1045 input = self.train_input if split == "train" else self.test_input
1047 input = input[:nb_to_use]
1049 desc = f"epoch-{split}"
1050 for batch in tqdm.tqdm(
1051 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1053 last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1054 batch = batch[:, :last].to(self.device)
1057 def vocabulary_size(self):
1058 return self.nb_codes
1060 def produce_results(
1061 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1063 # --------------------------------------------------------------------
1064 def compute_nb_errors_prog(input, nb_to_log=0):
1065 result = input.clone()
1066 s = (result == self.t_prog).long()
1067 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1068 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1070 masked_inplace_autoregression(
1075 deterministic_synthesis,
1079 sum_nb_total, sum_nb_errors = 0, 0
1080 for one_input, one_result in zip(input, result):
1081 seq = [self.id2token[i.item()] for i in one_result]
1082 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1084 sum_nb_errors += 0 if nb_errors == 0 else 1
1086 gt_seq = [self.id2token[i.item()] for i in one_input]
1087 _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1088 gt_prog = " ".join([str(x) for x in gt_prog])
1089 prog = " ".join([str(x) for x in prog])
1090 comment = "*" if nb_errors == 0 else "-"
1091 logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1092 for start_stack, target_stack, result_stack, correct in stacks:
1093 comment = "*" if correct else "-"
1094 start_stack = " ".join([str(x) for x in start_stack])
1095 target_stack = " ".join([str(x) for x in target_stack])
1096 result_stack = " ".join([str(x) for x in result_stack])
1098 f" {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1102 return sum_nb_total, sum_nb_errors
1104 # --------------------------------------------------------------------
1105 def compute_nb_errors_output(input, nb_to_log=0):
1106 result = input.clone()
1107 k = torch.arange(result.size(1), device=result.device)[None, :]
1109 ((result == self.t_output) * k).max(dim=1, keepdim=True).values
1112 ((result == self.t_prog) * k).max(dim=1, keepdim=True).values
1114 ar_mask = (k > last_output_idx).long() * (k < first_prog_idx).long()
1115 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1117 masked_inplace_autoregression(
1122 deterministic_synthesis,
1126 sum_nb_total, sum_nb_errors = 0, 0
1127 for one_input, one_result, i, j in zip(
1128 input, result, last_output_idx, first_prog_idx
1130 seq = [self.id2token[i.item()] for i in one_result]
1132 correct = (one_input - one_result).abs().max() == 0
1133 sum_nb_errors += 0 if correct else 1
1136 self.id2token[i.item()] for i in one_result[i : j + 1]
1139 self.id2token[i.item()] for i in one_input[i : j + 1]
1141 comment = "*" if correct else "-"
1142 result_stack = " ".join([str(x) for x in result_stack])
1143 target_stack = " ".join([str(x) for x in target_stack])
1145 f"output_test {comment} [{target_stack}] PREDICTED [{result_stack}]"
1149 return sum_nb_total, sum_nb_errors
1151 # --------------------------------------------------------------------
1153 if not self.no_prog:
1154 test_nb_total, test_nb_errors = compute_nb_errors_prog(
1155 self.test_input[:1000].to(self.device), nb_to_log=10
1159 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}%"
1162 test_nb_total, test_nb_errors = compute_nb_errors_output(
1163 self.test_input[:1000].to(self.device), nb_to_log=10
1167 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}%"
1170 if save_attention_image is not None:
1171 ns = torch.randint(self.test_input.size(0), (1,)).item()
1172 input = self.test_input[ns : ns + 1].clone()
1173 last = (input != self.t_nul).max(0).values.nonzero().max() + 3
1174 input = input[:, :last].to(self.device)
1176 with torch.autograd.no_grad():
1179 model.record_attention(True)
1180 model(BracketedSequence(input))
1182 ram = model.retrieve_attention()
1183 model.record_attention(False)
1185 tokens_output = [self.id2token[i.item()] for i in input[0]]
1186 tokens_input = ["n/a"] + tokens_output[:-1]
1187 for n_head in range(ram[0].size(1)):
1188 filename = os.path.join(
1189 result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
1191 attention_matrices = [m[0, n_head] for m in ram]
1192 save_attention_image(
1198 # min_total_attention=0.9,
1202 logger(f"wrote {filename}")
1205 ######################################################################
1212 def tensorize(self, sequences):
1213 len_max = max([len(x) for x in sequences])
1218 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1235 device=torch.device("cpu"),
1239 self.batch_size = batch_size
1240 self.device = device
1242 train_sequences = expr.generate_sequences(
1244 nb_variables=nb_variables,
1245 length=sequence_length,
1246 operand_max=operand_max,
1247 result_max=result_max,
1250 test_sequences = expr.generate_sequences(
1252 nb_variables=nb_variables,
1253 length=sequence_length,
1254 operand_max=operand_max,
1255 result_max=result_max,
1258 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1261 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1262 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1264 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1266 self.train_input = self.tensorize(train_sequences)
1267 self.test_input = self.tensorize(test_sequences)
1269 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1271 def batches(self, split="train", nb_to_use=-1, desc=None):
1272 assert split in {"train", "test"}
1273 input = self.train_input if split == "train" else self.test_input
1275 input = input[:nb_to_use]
1277 desc = f"epoch-{split}"
1278 for batch in tqdm.tqdm(
1279 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1281 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1282 batch = batch[:, :last]
1285 def vocabulary_size(self):
1286 return self.nb_codes
1288 def seq2str(self, s):
1289 return "".join([self.id2char[k.item()] for k in s])
1291 def produce_results(
1297 deterministic_synthesis,
1300 def compute_nb_correct(input):
1301 result = input.clone()
1302 s = (result == self.space).long()
1303 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1304 result = (1 - ar_mask) * result + ar_mask * self.filler
1305 masked_inplace_autoregression(
1310 deterministic_synthesis,
1314 nb_total = input.size(0)
1315 nb_correct = (input == result).long().min(1).values.sum()
1317 #######################################################################
1318 # Comput predicted vs. true variable values
1320 nb_delta = torch.zeros(5, dtype=torch.int64)
1323 values_input = expr.extract_results([self.seq2str(s) for s in input])
1324 values_result = expr.extract_results([self.seq2str(s) for s in result])
1326 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1328 with open(filename, "w") as f:
1329 for i, r in zip(values_input, values_result):
1330 for n, vi in i.items():
1332 f.write(f"{vi} {-1 if vr is None else vr}\n")
1334 if vr is None or vr < 0:
1338 if d >= nb_delta.size(0):
1343 ######################################################################
1345 return nb_total, nb_correct, nb_delta, nb_missed
1352 ) = compute_nb_correct(self.test_input[:10000])
1355 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}%"
1358 nb_total = test_nb_delta.sum() + test_nb_missed
1359 for d in range(test_nb_delta.size(0)):
1361 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1364 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1367 ##############################################################
1368 # Log a few generated sequences
1369 if input_file is None:
1370 input = self.test_input[:10]
1372 with open(input_file, "r") as f:
1373 sequences = [e.strip() for e in f.readlines()]
1374 sequences = [s + " " + "#" * 50 for s in sequences]
1375 input = self.tensorize(sequences)
1377 result = input.clone()
1378 s = (result == self.space).long()
1379 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1380 result = (1 - ar_mask) * result + ar_mask * self.filler
1382 for n in range(result.size(0)):
1383 logger(f"test_before {self.seq2str(result[n])}")
1385 masked_inplace_autoregression(
1390 deterministic_synthesis,
1394 correct = (1 - ar_mask) * self.space + ar_mask * input
1395 for n in range(result.size(0)):
1396 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1397 logger(f"test_after {self.seq2str(result[n])} {comment}")
1398 logger(f"truth {self.seq2str(correct[n])}")
1399 ##############################################################
1402 ######################################################################
1415 device=torch.device("cpu"),
1416 device_storage=torch.device("cpu"),
1420 self.batch_size = batch_size
1421 self.device = device
1430 ) = world.create_data_and_processors(
1435 nb_epochs=vqae_nb_epochs,
1438 device_storage=device_storage,
1441 train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1442 test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1444 nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1445 nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1447 self.len_frame_seq = train_frame_seq.size(1)
1448 self.len_action_seq = train_action_seq.size(1)
1449 self.nb_codes = nb_frame_codes + nb_action_codes
1451 train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1453 train_action_seq += nb_frame_codes
1454 self.train_input = torch.cat(
1455 (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1458 test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1459 test_action_seq += nb_frame_codes
1460 self.test_input = torch.cat(
1461 (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1464 def batches(self, split="train", nb_to_use=-1, desc=None):
1465 assert split in {"train", "test"}
1466 input = self.train_input if split == "train" else self.test_input
1468 input = input[:nb_to_use]
1470 desc = f"epoch-{split}"
1471 for batch in tqdm.tqdm(
1472 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1474 yield batch.to(self.device)
1476 def vocabulary_size(self):
1477 return self.nb_codes
1479 def produce_results(
1480 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1483 2 * self.len_frame_seq + self.len_action_seq, device=self.device
1486 input = self.test_input[:64].to(self.device)
1487 result = input.clone()
1490 (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1492 result *= 1 - ar_mask
1494 masked_inplace_autoregression(
1499 deterministic_synthesis,
1503 seq_start = input[:, : self.len_frame_seq]
1504 seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1505 seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1508 (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1510 result = result.reshape(-1, result.size(-1))
1512 frames = self.seq2frame(result)
1513 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1514 torchvision.utils.save_image(
1515 frames.float() / (world.Box.nb_rgb_levels - 1),
1521 logger(f"wrote {image_name}")
1524 ######################################################################