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}%"
185 ######################################################################
190 class PicoCLVR(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 ######################
229 device=torch.device("cpu"),
235 def generate_descr(nb, cache_suffix, pruner):
236 return picoclvr.generate(
246 self.batch_size = batch_size
248 self.pruner_train = pruner_train
249 self.pruner_eval = pruner_eval
251 if logger is not None:
253 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
256 self.train_descr = generate_descr(
257 nb_train_samples, "train", pruner=self.pruner_train
259 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
261 # Build the tokenizer
262 tokens = {"<nul>", "<img>"}
263 for d in [self.train_descr, self.test_descr]:
265 for t in s.strip().split(" "):
267 # make this set a sorted list to get the same tensors given
269 tokens = list(tokens)
271 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
272 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
273 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
275 # Tokenize the train and test sets
276 self.train_input = self.tensorize(self.train_descr)
277 self.test_input = self.tensorize(self.test_descr)
279 def batches(self, split="train"):
280 assert split in {"train", "test"}
281 input = self.train_input if split == "train" else self.test_input
282 for batch in tqdm.tqdm(
283 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
285 yield self.trim(batch)
287 def vocabulary_size(self):
288 return len(self.token2id)
290 def compute_missing_properties(
291 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
293 acc_nb_requested_properties = []
294 acc_nb_missing_properties = []
297 for input in tqdm.tqdm(
298 self.test_input.split(self.batch_size),
300 desc=f"test-properties",
302 result = input.clone()
303 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
304 result = (1 - ar_mask) * result + ar_mask * self.t_nul
305 masked_inplace_autoregression(
310 deterministic_synthesis,
311 progress_bar_desc=None,
315 result_descr = self.detensorize(result)
316 np = picoclvr.nb_properties(
322 nb_requested_properties, _, nb_missing_properties = zip(*np)
323 acc_nb_requested_properties += nb_requested_properties
324 acc_nb_missing_properties += nb_missing_properties
325 acc_nb_results += len(result_descr)
327 nb_requested_properties = sum(acc_nb_requested_properties)
328 nb_missing_properties = sum(acc_nb_missing_properties)
330 prefix = "" if pruner is None else "pruned_"
331 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
333 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
336 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
339 ######################################################################
342 self, n_epoch, model, result_dir, logger, deterministic_synthesis
344 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
346 if self.pruner_eval is not None:
347 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
349 nb_tokens_to_generate = self.height * self.width + 3
354 for primer_descr in [
355 "red above green <sep> green top <sep> blue right of red",
356 "there is red <sep> there is yellow <sep> there is blue",
357 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
358 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
360 primer += [primer_descr + " <img>"] * nb_per_primer
362 result = self.tensorize(primer)
363 fill = result.new_full(
364 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
366 result = torch.cat((result, fill), 1)
367 ar_mask = (result == self.t_nul).long()
368 masked_inplace_autoregression(
373 deterministic_synthesis,
376 result_descr = self.detensorize(result)
378 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
380 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
381 acc_nb_results = len(result_descr)
383 nb_requested_properties = sum(acc_nb_requested_properties)
384 nb_missing_properties = sum(acc_nb_missing_properties)
387 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
389 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
392 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
395 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
399 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
403 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
409 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
410 torchvision.utils.save_image(
411 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
413 logger(f"wrote {image_name}")
416 ######################################################################
421 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
425 self.nb_train_samples = (nb_train_samples,)
426 self.nb_test_samples = (nb_test_samples,)
427 self.batch_size = batch_size
429 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
430 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
431 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
432 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
434 def batches(self, split="train", nb_to_use=-1, desc=None):
435 assert split in {"train", "test"}
436 input = self.train_input if split == "train" else self.test_input
438 input = input[:nb_to_use]
440 desc = f"epoch-{split}"
441 for batch in tqdm.tqdm(
442 input.split(self.batch_size), dynamic_ncols=True, desc=desc
446 def vocabulary_size(self):
450 self, n_epoch, model, result_dir, logger, deterministic_synthesis
452 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
453 ar_mask = torch.full_like(results, 1)
454 masked_inplace_autoregression(
459 deterministic_synthesis,
462 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
463 torchvision.utils.save_image(
464 1 - results.reshape(-1, 1, 28, 28) / 255.0,
469 logger(f"wrote {image_name}")
472 ######################################################################
478 def map2seq(self, *m):
479 return torch.cat([x.flatten(1) for x in m], 1)
481 def seq2map(self, s):
482 s = s.reshape(s.size(0), -1, self.height, self.width)
483 return (s[:, k] for k in range(s.size(1)))
493 device=torch.device("cpu"),
497 self.batch_size = batch_size
502 train_mazes, train_paths, _ = maze.create_maze_data(
507 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
509 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
511 test_mazes, test_paths, _ = maze.create_maze_data(
516 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
518 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
520 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
522 def batches(self, split="train", nb_to_use=-1, desc=None):
523 assert split in {"train", "test"}
524 input = self.train_input if split == "train" else self.test_input
526 input = input[:nb_to_use]
528 desc = f"epoch-{split}"
529 for batch in tqdm.tqdm(
530 input.split(self.batch_size), dynamic_ncols=True, desc=desc
534 def vocabulary_size(self):
538 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
540 nb_total, nb_correct = 0, 0
542 self.width * self.height,
543 self.width * self.height,
548 for input in self.batches(split, nb_to_use):
549 result = input.clone()
550 ar_mask = result.new_zeros(result.size())
551 ar_mask[:, self.height * self.width :] = 1
552 result *= 1 - ar_mask
553 masked_inplace_autoregression(
558 deterministic_synthesis,
559 progress_bar_desc=None,
562 mazes, paths = self.seq2map(result)
563 path_correctness = maze.path_correctness(mazes, paths)
564 nb_correct += path_correctness.long().sum()
565 nb_total += mazes.size(0)
567 optimal_path_lengths = (
568 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
570 predicted_path_lengths = (
571 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
573 optimal_path_lengths = optimal_path_lengths[path_correctness]
574 predicted_path_lengths = predicted_path_lengths[path_correctness]
575 count[optimal_path_lengths, predicted_path_lengths] += 1
581 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
584 return nb_total, nb_correct, count
587 self, n_epoch, model, result_dir, logger, deterministic_synthesis
589 train_nb_total, train_nb_correct, count = self.compute_error(
593 deterministic_synthesis=deterministic_synthesis,
596 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}%"
599 test_nb_total, test_nb_correct, count = self.compute_error(
603 deterministic_synthesis=deterministic_synthesis,
606 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}%"
609 if count is not None:
610 proportion_optimal = count.diagonal().sum().float() / count.sum()
611 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
613 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
615 for i in range(count.size(0)):
616 for j in range(count.size(1)):
617 eol = " " if j < count.size(1) - 1 else "\n"
618 f.write(f"{count[i,j]}{eol}")
620 input = self.test_input[:48]
621 result = input.clone()
622 ar_mask = result.new_zeros(result.size())
623 ar_mask[:, self.height * self.width :] = 1
624 result *= 1 - ar_mask
625 masked_inplace_autoregression(
630 deterministic_synthesis,
634 mazes, paths = self.seq2map(input)
635 _, predicted_paths = self.seq2map(result)
637 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
642 predicted_paths=predicted_paths,
643 path_correct=maze.path_correctness(mazes, predicted_paths),
644 path_optimal=maze.path_optimality(paths, predicted_paths),
646 logger(f"wrote {filename}")
649 ######################################################################
666 device=torch.device("cpu"),
670 self.batch_size = batch_size
674 self.prompt_length = prompt_length
676 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
685 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
695 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
697 def batches(self, split="train", nb_to_use=-1, desc=None):
698 assert split in {"train", "test"}
699 input = self.train_input if split == "train" else self.test_input
701 input = input[:nb_to_use]
703 desc = f"epoch-{split}"
704 for batch in tqdm.tqdm(
705 input.split(self.batch_size), dynamic_ncols=True, desc=desc
709 def vocabulary_size(self):
713 self, n_epoch, model, result_dir, logger, deterministic_synthesis
715 def compute_nb_correct(input, prior_visits):
716 result = input.clone()
717 i = torch.arange(result.size(1), device=result.device)[None, :]
719 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
723 result *= 1 - ar_mask
725 masked_inplace_autoregression(
730 deterministic_synthesis,
734 nb_total = ((prior_visits > 0) * ar_mask).sum()
736 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
738 return nb_total, nb_correct
740 test_nb_total, test_nb_correct = compute_nb_correct(
741 self.test_input[:1000], self.test_prior_visits[:1000]
745 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}%"
749 ######################################################################
765 fraction_values_for_train=None,
766 device=torch.device("cpu"),
770 self.batch_size = batch_size
771 self.nb_steps = nb_steps
772 self.nb_stacks = nb_stacks
773 self.nb_digits = nb_digits
776 if fraction_values_for_train is None:
777 values_for_train = None
778 values_for_test = None
780 all = torch.randperm(10**nb_digits)
781 nb_for_train = int(all.size(0) * fraction_values_for_train)
782 values_for_train = all[:nb_for_train]
783 values_for_test = all[nb_for_train:]
785 self.train_input, self.train_stack_counts = stack.generate_sequences(
794 self.test_input, self.test_stack_counts = stack.generate_sequences(
803 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
804 counts = self.test_stack_counts.flatten()[i.flatten()]
805 counts = F.one_hot(counts).sum(0)
806 logger(f"test_pop_stack_counts {counts}")
808 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
810 def batches(self, split="train", nb_to_use=-1, desc=None):
811 assert split in {"train", "test"}
812 input = self.train_input if split == "train" else self.test_input
814 input = input[:nb_to_use]
816 desc = f"epoch-{split}"
817 for batch in tqdm.tqdm(
818 input.split(self.batch_size), dynamic_ncols=True, desc=desc
822 def vocabulary_size(self):
826 self, n_epoch, model, result_dir, logger, deterministic_synthesis
828 def compute_nb_correct(input):
829 result = input.clone()
830 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
831 ar_mask = (result != input).long()
832 masked_inplace_autoregression(
837 deterministic_synthesis,
841 errors = ((result != input).long() * ar_mask).reshape(
842 -1, 1 + self.nb_digits
844 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
846 nb_total = ar_mask.max(1).values.sum()
847 nb_correct = nb_total - errors.max(1).values.sum()
849 return nb_total, nb_correct
851 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
854 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}%"
857 ##############################################################
858 # Log a few generated sequences
859 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
860 result = input.clone()
861 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
862 ar_mask = (result != input).long()
864 # for n in range(result.size(0)):
866 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
869 masked_inplace_autoregression(
874 deterministic_synthesis,
878 for n in range(result.size(0)):
880 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
882 ##############################################################
885 ######################################################################
891 def tensorize(self, sequences):
892 len_max = max([len(x) for x in sequences])
898 self.token2id[str(c)]
899 for c in s + ["<nul>"] * (len_max - len(s))
908 def seq2str(self, seq):
909 return " ".join([self.id2token[i] for i in seq])
916 nb_starting_values=3,
922 device=torch.device("cpu"),
926 self.batch_size = batch_size
928 self.no_prog = no_prog
932 nb_starting_values=nb_starting_values,
933 nb_result_values_max=4 * nb_starting_values,
938 for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
943 nb_starting_values=nb_starting_values,
944 nb_result_values_max=4 * nb_starting_values,
949 for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
953 set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
955 val_max = max([x if type(x) is int else 0 for x in symbols])
956 symbols = list(filter(lambda x: type(x) is str, symbols))
958 symbols += [str(n) for n in range(val_max + 1)]
959 self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
960 self.id2token = dict([(n, c) for c, n in self.token2id.items()])
962 self.t_nul = self.token2id["<nul>"]
963 self.t_input = self.token2id["<in>"]
964 self.t_output = self.token2id["<out>"]
965 self.t_prog = self.token2id["<prg>"]
966 self.t_end = self.token2id["<end>"]
968 self.train_input = self.tensorize(train_sequences)
969 self.test_input = self.tensorize(test_sequences)
972 # Excise the program from every train and test example
973 k = torch.arange(self.train_input.size(1), device=self.train_input.device)[
977 ((self.train_input == self.t_prog).long() * k)
978 .max(1, keepdim=True)
982 self.train_input * (k <= p).long()
983 + self.t_end * (k == p + 1).long()
984 + self.t_nul * (k > p + 1).long()
986 k = torch.arange(self.test_input.size(1), device=self.test_input.device)[
990 ((self.test_input == self.t_prog).long() * k)
991 .max(1, keepdim=True)
995 self.test_input * (k <= p).long()
996 + self.t_end * (k == p + 1).long()
997 + self.t_nul * (k > p + 1).long()
1000 if logger is not None:
1001 logger(f"value_max {val_max}")
1002 for x in self.train_input[:25]:
1003 end = (x != self.t_nul).nonzero().max().item() + 1
1004 seq = [self.id2token[i.item()] for i in x[:end]]
1006 logger(f"example_seq {s}")
1008 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1010 def batches(self, split="train", nb_to_use=-1, desc=None):
1011 assert split in {"train", "test"}
1012 input = self.train_input if split == "train" else self.test_input
1014 input = input[:nb_to_use]
1016 desc = f"epoch-{split}"
1017 for batch in tqdm.tqdm(
1018 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1020 last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1021 batch = batch[:, :last].to(self.device)
1024 def vocabulary_size(self):
1025 return self.nb_codes
1027 def produce_results(
1028 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1030 # --------------------------------------------------------------------
1031 def compute_nb_errors_prog(input, nb_to_log=0):
1032 result = input.clone()
1033 s = (result == self.t_prog).long()
1034 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1035 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1037 masked_inplace_autoregression(
1042 deterministic_synthesis,
1046 sum_nb_total, sum_nb_errors = 0, 0
1047 for one_input, one_result in zip(input, result):
1048 seq = [self.id2token[i.item()] for i in one_result]
1049 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1051 sum_nb_errors += 0 if nb_errors == 0 else 1
1053 gt_seq = [self.id2token[i.item()] for i in one_input]
1054 _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1055 gt_prog = " ".join([str(x) for x in gt_prog])
1056 prog = " ".join([str(x) for x in prog])
1057 comment = "*" if nb_errors == 0 else "-"
1058 logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1059 for start_stack, target_stack, result_stack, correct in stacks:
1060 comment = "*" if correct else "-"
1061 start_stack = " ".join([str(x) for x in start_stack])
1062 target_stack = " ".join([str(x) for x in target_stack])
1063 result_stack = " ".join([str(x) for x in result_stack])
1065 f" {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1069 return sum_nb_total, sum_nb_errors
1071 # --------------------------------------------------------------------
1072 def compute_nb_errors_output(input, nb_to_log=0):
1073 result = input.clone()
1074 k = torch.arange(result.size(1), device=result.device)[None, :]
1076 ((result == self.t_output) * k).max(dim=1, keepdim=True).values
1079 ((result == self.t_prog) * k).max(dim=1, keepdim=True).values
1081 ar_mask = (k > last_output_idx).long() * (k < first_prog_idx).long()
1082 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1084 masked_inplace_autoregression(
1089 deterministic_synthesis,
1093 sum_nb_total, sum_nb_errors = 0, 0
1094 for one_input, one_result, i, j in zip(
1095 input, result, last_output_idx, first_prog_idx
1097 seq = [self.id2token[i.item()] for i in one_result]
1099 correct = (one_input - one_result).abs().max() == 0
1100 sum_nb_errors += 0 if correct else 1
1103 self.id2token[i.item()] for i in one_result[i : j + 1]
1106 self.id2token[i.item()] for i in one_input[i : j + 1]
1108 comment = "*" if correct else "-"
1109 result_stack = " ".join([str(x) for x in result_stack])
1110 target_stack = " ".join([str(x) for x in target_stack])
1112 f"output_test {comment} [{target_stack}] PREDICTED [{result_stack}]"
1116 return sum_nb_total, sum_nb_errors
1118 # --------------------------------------------------------------------
1120 if not self.no_prog:
1121 test_nb_total, test_nb_errors = compute_nb_errors_prog(
1122 self.test_input[:1000].to(self.device), nb_to_log=10
1126 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}%"
1129 test_nb_total, test_nb_errors = compute_nb_errors_output(
1130 self.test_input[:1000].to(self.device), nb_to_log=10
1134 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}%"
1137 if save_attention_image is not None:
1138 ns = torch.randint(self.test_input.size(0), (1,)).item()
1139 input = self.test_input[ns : ns + 1].clone()
1140 last = (input != self.t_nul).max(0).values.nonzero().max() + 3
1141 input = input[:, :last].to(self.device)
1143 with torch.autograd.no_grad():
1146 model.record_attention(True)
1147 model(BracketedSequence(input))
1149 ram = model.retrieve_attention()
1150 model.record_attention(False)
1152 tokens_output = [self.id2token[i.item()] for i in input[0]]
1153 tokens_input = ["n/a"] + tokens_output[:-1]
1154 for n_head in range(ram[0].size(1)):
1155 filename = os.path.join(
1156 result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
1158 attention_matrices = [m[0, n_head] for m in ram]
1159 save_attention_image(
1165 # min_total_attention=0.9,
1169 logger(f"wrote {filename}")
1172 ######################################################################
1179 def tensorize(self, sequences):
1180 len_max = max([len(x) for x in sequences])
1185 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1202 device=torch.device("cpu"),
1206 self.batch_size = batch_size
1207 self.device = device
1209 train_sequences = expr.generate_sequences(
1211 nb_variables=nb_variables,
1212 length=sequence_length,
1213 operand_max=operand_max,
1214 result_max=result_max,
1217 test_sequences = expr.generate_sequences(
1219 nb_variables=nb_variables,
1220 length=sequence_length,
1221 operand_max=operand_max,
1222 result_max=result_max,
1225 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1228 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1229 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1231 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1233 self.train_input = self.tensorize(train_sequences)
1234 self.test_input = self.tensorize(test_sequences)
1236 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1238 def batches(self, split="train", nb_to_use=-1, desc=None):
1239 assert split in {"train", "test"}
1240 input = self.train_input if split == "train" else self.test_input
1242 input = input[:nb_to_use]
1244 desc = f"epoch-{split}"
1245 for batch in tqdm.tqdm(
1246 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1248 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1249 batch = batch[:, :last]
1252 def vocabulary_size(self):
1253 return self.nb_codes
1255 def seq2str(self, s):
1256 return "".join([self.id2char[k.item()] for k in s])
1258 def produce_results(
1264 deterministic_synthesis,
1267 def compute_nb_correct(input):
1268 result = input.clone()
1269 s = (result == self.space).long()
1270 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1271 result = (1 - ar_mask) * result + ar_mask * self.filler
1272 masked_inplace_autoregression(
1277 deterministic_synthesis,
1281 nb_total = input.size(0)
1282 nb_correct = (input == result).long().min(1).values.sum()
1284 #######################################################################
1285 # Comput predicted vs. true variable values
1287 nb_delta = torch.zeros(5, dtype=torch.int64)
1290 values_input = expr.extract_results([self.seq2str(s) for s in input])
1291 values_result = expr.extract_results([self.seq2str(s) for s in result])
1293 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1295 with open(filename, "w") as f:
1296 for i, r in zip(values_input, values_result):
1297 for n, vi in i.items():
1299 f.write(f"{vi} {-1 if vr is None else vr}\n")
1301 if vr is None or vr < 0:
1305 if d >= nb_delta.size(0):
1310 ######################################################################
1312 return nb_total, nb_correct, nb_delta, nb_missed
1319 ) = compute_nb_correct(self.test_input[:10000])
1322 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}%"
1325 nb_total = test_nb_delta.sum() + test_nb_missed
1326 for d in range(test_nb_delta.size(0)):
1328 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1331 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1334 ##############################################################
1335 # Log a few generated sequences
1336 if input_file is None:
1337 input = self.test_input[:10]
1339 with open(input_file, "r") as f:
1340 sequences = [e.strip() for e in f.readlines()]
1341 sequences = [s + " " + "#" * 50 for s in sequences]
1342 input = self.tensorize(sequences)
1344 result = input.clone()
1345 s = (result == self.space).long()
1346 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1347 result = (1 - ar_mask) * result + ar_mask * self.filler
1349 for n in range(result.size(0)):
1350 logger(f"test_before {self.seq2str(result[n])}")
1352 masked_inplace_autoregression(
1357 deterministic_synthesis,
1361 correct = (1 - ar_mask) * self.space + ar_mask * input
1362 for n in range(result.size(0)):
1363 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1364 logger(f"test_after {self.seq2str(result[n])} {comment}")
1365 logger(f"truth {self.seq2str(correct[n])}")
1366 ##############################################################
1369 ######################################################################
1382 device=torch.device("cpu"),
1383 device_storage=torch.device("cpu"),
1387 self.batch_size = batch_size
1388 self.device = device
1397 ) = world.create_data_and_processors(
1402 nb_epochs=vqae_nb_epochs,
1405 device_storage=device_storage,
1408 train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1409 test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1411 nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1412 nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1414 self.len_frame_seq = train_frame_seq.size(1)
1415 self.len_action_seq = train_action_seq.size(1)
1416 self.nb_codes = nb_frame_codes + nb_action_codes
1418 train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1420 train_action_seq += nb_frame_codes
1421 self.train_input = torch.cat(
1422 (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1425 test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1426 test_action_seq += nb_frame_codes
1427 self.test_input = torch.cat(
1428 (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1431 def batches(self, split="train", nb_to_use=-1, desc=None):
1432 assert split in {"train", "test"}
1433 input = self.train_input if split == "train" else self.test_input
1435 input = input[:nb_to_use]
1437 desc = f"epoch-{split}"
1438 for batch in tqdm.tqdm(
1439 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1441 yield batch.to(self.device)
1443 def vocabulary_size(self):
1444 return self.nb_codes
1446 def produce_results(
1447 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1450 2 * self.len_frame_seq + self.len_action_seq, device=self.device
1453 input = self.test_input[:64].to(self.device)
1454 result = input.clone()
1457 (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1459 result *= 1 - ar_mask
1461 masked_inplace_autoregression(
1466 deterministic_synthesis,
1470 seq_start = input[:, : self.len_frame_seq]
1471 seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1472 seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1475 (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1477 result = result.reshape(-1, result.size(-1))
1479 frames = self.seq2frame(result)
1480 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1481 torchvision.utils.save_image(
1482 frames.float() / (world.Box.nb_rgb_levels - 1),
1488 logger(f"wrote {image_name}")
1491 ######################################################################