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 None:
185 logger("no save_attention_image (is pycairo installed?)")
188 ns = torch.randint(self.test_input.size(0), (1,)).item()
189 input = self.test_input[ns : ns + 1].clone()
191 with torch.autograd.no_grad():
194 model.record_attention(True)
195 model(BracketedSequence(input))
197 ram = model.retrieve_attention()
198 model.record_attention(False)
200 tokens_output = [c for c in self.problem.seq2str(input[0])]
201 tokens_input = ["n/a"] + tokens_output[:-1]
202 for n_head in range(ram[0].size(1)):
203 filename = os.path.join(
204 result_dir, f"sandbox_attention_{k}_h{n_head}.pdf"
206 attention_matrices = [m[0, n_head] for m in ram]
207 save_attention_image(
213 # min_total_attention=0.9,
217 logger(f"wrote {filename}")
220 ######################################################################
225 class PicoCLVR(Task):
226 # Make a tensor from a list of strings
227 def tensorize(self, descr):
228 token_descr = [s.strip().split(" ") for s in descr]
229 l = max([len(s) for s in token_descr])
230 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
231 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
232 return torch.tensor(id_descr, device=self.device)
234 # Make a list of strings from a tensor
235 def detensorize(self, x):
236 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
238 # trim all the tensors in the tuple z to remove as much token from
239 # left and right in the first tensor. If z is a tuple, all its
240 # elements are trimed according to the triming for the first
241 def trim(self, z, token="<nul>"):
242 n = self.token2id[token]
245 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
246 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
247 return tuple([t[:, a:b] for t in z])
249 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
250 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
253 ######################
264 device=torch.device("cpu"),
270 def generate_descr(nb, cache_suffix, pruner):
271 return picoclvr.generate(
281 self.batch_size = batch_size
283 self.pruner_train = pruner_train
284 self.pruner_eval = pruner_eval
286 if logger is not None:
288 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
291 self.train_descr = generate_descr(
292 nb_train_samples, "train", pruner=self.pruner_train
294 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
296 # Build the tokenizer
297 tokens = {"<nul>", "<img>"}
298 for d in [self.train_descr, self.test_descr]:
300 for t in s.strip().split(" "):
302 # make this set a sorted list to get the same tensors given
304 tokens = list(tokens)
306 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
307 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
308 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
310 # Tokenize the train and test sets
311 self.train_input = self.tensorize(self.train_descr)
312 self.test_input = self.tensorize(self.test_descr)
314 def batches(self, split="train"):
315 assert split in {"train", "test"}
316 input = self.train_input if split == "train" else self.test_input
317 for batch in tqdm.tqdm(
318 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
320 yield self.trim(batch)
322 def vocabulary_size(self):
323 return len(self.token2id)
325 def compute_missing_properties(
326 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
328 acc_nb_requested_properties = []
329 acc_nb_missing_properties = []
332 for input in tqdm.tqdm(
333 self.test_input.split(self.batch_size),
335 desc=f"test-properties",
337 result = input.clone()
338 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
339 result = (1 - ar_mask) * result + ar_mask * self.t_nul
340 masked_inplace_autoregression(
345 deterministic_synthesis,
346 progress_bar_desc=None,
350 result_descr = self.detensorize(result)
351 np = picoclvr.nb_properties(
357 nb_requested_properties, _, nb_missing_properties = zip(*np)
358 acc_nb_requested_properties += nb_requested_properties
359 acc_nb_missing_properties += nb_missing_properties
360 acc_nb_results += len(result_descr)
362 nb_requested_properties = sum(acc_nb_requested_properties)
363 nb_missing_properties = sum(acc_nb_missing_properties)
365 prefix = "" if pruner is None else "pruned_"
366 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
368 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
371 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
374 ######################################################################
377 self, n_epoch, model, result_dir, logger, deterministic_synthesis
379 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
381 if self.pruner_eval is not None:
382 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
384 nb_tokens_to_generate = self.height * self.width + 3
389 for primer_descr in [
390 "red above green <sep> green top <sep> blue right of red",
391 "there is red <sep> there is yellow <sep> there is blue",
392 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
393 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
395 primer += [primer_descr + " <img>"] * nb_per_primer
397 result = self.tensorize(primer)
398 fill = result.new_full(
399 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
401 result = torch.cat((result, fill), 1)
402 ar_mask = (result == self.t_nul).long()
403 masked_inplace_autoregression(
408 deterministic_synthesis,
411 result_descr = self.detensorize(result)
413 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
415 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
416 acc_nb_results = len(result_descr)
418 nb_requested_properties = sum(acc_nb_requested_properties)
419 nb_missing_properties = sum(acc_nb_missing_properties)
422 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
424 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
427 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
430 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
434 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
438 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
444 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
445 torchvision.utils.save_image(
446 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
448 logger(f"wrote {image_name}")
451 ######################################################################
456 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
460 self.nb_train_samples = (nb_train_samples,)
461 self.nb_test_samples = (nb_test_samples,)
462 self.batch_size = batch_size
464 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
465 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
466 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
467 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
469 def batches(self, split="train", nb_to_use=-1, desc=None):
470 assert split in {"train", "test"}
471 input = self.train_input if split == "train" else self.test_input
473 input = input[:nb_to_use]
475 desc = f"epoch-{split}"
476 for batch in tqdm.tqdm(
477 input.split(self.batch_size), dynamic_ncols=True, desc=desc
481 def vocabulary_size(self):
485 self, n_epoch, model, result_dir, logger, deterministic_synthesis
487 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
488 ar_mask = torch.full_like(results, 1)
489 masked_inplace_autoregression(
494 deterministic_synthesis,
497 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
498 torchvision.utils.save_image(
499 1 - results.reshape(-1, 1, 28, 28) / 255.0,
504 logger(f"wrote {image_name}")
507 ######################################################################
513 def map2seq(self, *m):
514 return torch.cat([x.flatten(1) for x in m], 1)
516 def seq2map(self, s):
517 s = s.reshape(s.size(0), -1, self.height, self.width)
518 return (s[:, k] for k in range(s.size(1)))
528 device=torch.device("cpu"),
532 self.batch_size = batch_size
537 train_mazes, train_paths, _ = maze.create_maze_data(
542 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
544 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
546 test_mazes, test_paths, _ = maze.create_maze_data(
551 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
553 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
555 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
557 def batches(self, split="train", nb_to_use=-1, desc=None):
558 assert split in {"train", "test"}
559 input = self.train_input if split == "train" else self.test_input
561 input = input[:nb_to_use]
563 desc = f"epoch-{split}"
564 for batch in tqdm.tqdm(
565 input.split(self.batch_size), dynamic_ncols=True, desc=desc
569 def vocabulary_size(self):
573 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
575 nb_total, nb_correct = 0, 0
577 self.width * self.height,
578 self.width * self.height,
583 for input in self.batches(split, nb_to_use):
584 result = input.clone()
585 ar_mask = result.new_zeros(result.size())
586 ar_mask[:, self.height * self.width :] = 1
587 result *= 1 - ar_mask
588 masked_inplace_autoregression(
593 deterministic_synthesis,
594 progress_bar_desc=None,
597 mazes, paths = self.seq2map(result)
598 path_correctness = maze.path_correctness(mazes, paths)
599 nb_correct += path_correctness.long().sum()
600 nb_total += mazes.size(0)
602 optimal_path_lengths = (
603 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
605 predicted_path_lengths = (
606 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
608 optimal_path_lengths = optimal_path_lengths[path_correctness]
609 predicted_path_lengths = predicted_path_lengths[path_correctness]
610 count[optimal_path_lengths, predicted_path_lengths] += 1
616 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
619 return nb_total, nb_correct, count
622 self, n_epoch, model, result_dir, logger, deterministic_synthesis
624 train_nb_total, train_nb_correct, count = self.compute_error(
628 deterministic_synthesis=deterministic_synthesis,
631 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}%"
634 test_nb_total, test_nb_correct, count = self.compute_error(
638 deterministic_synthesis=deterministic_synthesis,
641 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}%"
644 if count is not None:
645 proportion_optimal = count.diagonal().sum().float() / count.sum()
646 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
648 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
650 for i in range(count.size(0)):
651 for j in range(count.size(1)):
652 eol = " " if j < count.size(1) - 1 else "\n"
653 f.write(f"{count[i,j]}{eol}")
655 input = self.test_input[:48]
656 result = input.clone()
657 ar_mask = result.new_zeros(result.size())
658 ar_mask[:, self.height * self.width :] = 1
659 result *= 1 - ar_mask
660 masked_inplace_autoregression(
665 deterministic_synthesis,
669 mazes, paths = self.seq2map(input)
670 _, predicted_paths = self.seq2map(result)
672 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
677 predicted_paths=predicted_paths,
678 path_correct=maze.path_correctness(mazes, predicted_paths),
679 path_optimal=maze.path_optimality(paths, predicted_paths),
681 logger(f"wrote {filename}")
684 ######################################################################
701 device=torch.device("cpu"),
705 self.batch_size = batch_size
709 self.prompt_length = prompt_length
711 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
720 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
730 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
732 def batches(self, split="train", nb_to_use=-1, desc=None):
733 assert split in {"train", "test"}
734 input = self.train_input if split == "train" else self.test_input
736 input = input[:nb_to_use]
738 desc = f"epoch-{split}"
739 for batch in tqdm.tqdm(
740 input.split(self.batch_size), dynamic_ncols=True, desc=desc
744 def vocabulary_size(self):
748 self, n_epoch, model, result_dir, logger, deterministic_synthesis
750 def compute_nb_correct(input, prior_visits):
751 result = input.clone()
752 i = torch.arange(result.size(1), device=result.device)[None, :]
754 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
758 result *= 1 - ar_mask
760 masked_inplace_autoregression(
765 deterministic_synthesis,
769 nb_total = ((prior_visits > 0) * ar_mask).sum()
771 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
773 return nb_total, nb_correct
775 test_nb_total, test_nb_correct = compute_nb_correct(
776 self.test_input[:1000], self.test_prior_visits[:1000]
780 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}%"
784 ######################################################################
800 fraction_values_for_train=None,
801 device=torch.device("cpu"),
805 self.batch_size = batch_size
806 self.nb_steps = nb_steps
807 self.nb_stacks = nb_stacks
808 self.nb_digits = nb_digits
811 if fraction_values_for_train is None:
812 values_for_train = None
813 values_for_test = None
815 all = torch.randperm(10**nb_digits)
816 nb_for_train = int(all.size(0) * fraction_values_for_train)
817 values_for_train = all[:nb_for_train]
818 values_for_test = all[nb_for_train:]
820 self.train_input, self.train_stack_counts = stack.generate_sequences(
829 self.test_input, self.test_stack_counts = stack.generate_sequences(
838 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
839 counts = self.test_stack_counts.flatten()[i.flatten()]
840 counts = F.one_hot(counts).sum(0)
841 logger(f"test_pop_stack_counts {counts}")
843 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
845 def batches(self, split="train", nb_to_use=-1, desc=None):
846 assert split in {"train", "test"}
847 input = self.train_input if split == "train" else self.test_input
849 input = input[:nb_to_use]
851 desc = f"epoch-{split}"
852 for batch in tqdm.tqdm(
853 input.split(self.batch_size), dynamic_ncols=True, desc=desc
857 def vocabulary_size(self):
861 self, n_epoch, model, result_dir, logger, deterministic_synthesis
863 def compute_nb_correct(input):
864 result = input.clone()
865 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
866 ar_mask = (result != input).long()
867 masked_inplace_autoregression(
872 deterministic_synthesis,
876 errors = ((result != input).long() * ar_mask).reshape(
877 -1, 1 + self.nb_digits
879 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
881 nb_total = ar_mask.max(1).values.sum()
882 nb_correct = nb_total - errors.max(1).values.sum()
884 return nb_total, nb_correct
886 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
889 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}%"
892 ##############################################################
893 # Log a few generated sequences
894 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
895 result = input.clone()
896 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
897 ar_mask = (result != input).long()
899 # for n in range(result.size(0)):
901 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
904 masked_inplace_autoregression(
909 deterministic_synthesis,
913 for n in range(result.size(0)):
915 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
917 ##############################################################
920 ######################################################################
926 def tensorize(self, sequences):
927 len_max = max([len(x) for x in sequences])
933 self.token2id[str(c)]
934 for c in s + ["<nul>"] * (len_max - len(s))
943 def seq2str(self, seq):
944 return " ".join([self.id2token[i] for i in seq])
951 nb_starting_values=3,
957 device=torch.device("cpu"),
961 self.batch_size = batch_size
963 self.no_prog = no_prog
967 nb_starting_values=nb_starting_values,
968 nb_result_values_max=4 * nb_starting_values,
973 for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
978 nb_starting_values=nb_starting_values,
979 nb_result_values_max=4 * nb_starting_values,
984 for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
988 set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
990 val_max = max([x if type(x) is int else 0 for x in symbols])
991 symbols = list(filter(lambda x: type(x) is str, symbols))
993 symbols += [str(n) for n in range(val_max + 1)]
994 self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
995 self.id2token = dict([(n, c) for c, n in self.token2id.items()])
997 self.t_nul = self.token2id["<nul>"]
998 self.t_input = self.token2id["<in>"]
999 self.t_output = self.token2id["<out>"]
1000 self.t_prog = self.token2id["<prg>"]
1001 self.t_end = self.token2id["<end>"]
1003 self.train_input = self.tensorize(train_sequences)
1004 self.test_input = self.tensorize(test_sequences)
1007 # Excise the program from every train and test example
1008 k = torch.arange(self.train_input.size(1), device=self.train_input.device)[
1012 ((self.train_input == self.t_prog).long() * k)
1013 .max(1, keepdim=True)
1016 self.train_input = (
1017 self.train_input * (k <= p).long()
1018 + self.t_end * (k == p + 1).long()
1019 + self.t_nul * (k > p + 1).long()
1021 k = torch.arange(self.test_input.size(1), device=self.test_input.device)[
1025 ((self.test_input == self.t_prog).long() * k)
1026 .max(1, keepdim=True)
1030 self.test_input * (k <= p).long()
1031 + self.t_end * (k == p + 1).long()
1032 + self.t_nul * (k > p + 1).long()
1035 if logger is not None:
1036 logger(f"value_max {val_max}")
1037 for x in self.train_input[:25]:
1038 end = (x != self.t_nul).nonzero().max().item() + 1
1039 seq = [self.id2token[i.item()] for i in x[:end]]
1041 logger(f"example_seq {s}")
1043 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1045 def batches(self, split="train", nb_to_use=-1, desc=None):
1046 assert split in {"train", "test"}
1047 input = self.train_input if split == "train" else self.test_input
1049 input = input[:nb_to_use]
1051 desc = f"epoch-{split}"
1052 for batch in tqdm.tqdm(
1053 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1055 last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1056 batch = batch[:, :last].to(self.device)
1059 def vocabulary_size(self):
1060 return self.nb_codes
1062 def produce_results(
1063 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1065 # --------------------------------------------------------------------
1066 def compute_nb_errors_prog(input, nb_to_log=0):
1067 result = input.clone()
1068 s = (result == self.t_prog).long()
1069 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1070 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1072 masked_inplace_autoregression(
1077 deterministic_synthesis,
1081 sum_nb_total, sum_nb_errors = 0, 0
1082 for one_input, one_result in zip(input, result):
1083 seq = [self.id2token[i.item()] for i in one_result]
1084 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1086 sum_nb_errors += 0 if nb_errors == 0 else 1
1088 gt_seq = [self.id2token[i.item()] for i in one_input]
1089 _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1090 gt_prog = " ".join([str(x) for x in gt_prog])
1091 prog = " ".join([str(x) for x in prog])
1092 comment = "*" if nb_errors == 0 else "-"
1093 logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1094 for start_stack, target_stack, result_stack, correct in stacks:
1095 comment = "*" if correct else "-"
1096 start_stack = " ".join([str(x) for x in start_stack])
1097 target_stack = " ".join([str(x) for x in target_stack])
1098 result_stack = " ".join([str(x) for x in result_stack])
1100 f" {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1104 return sum_nb_total, sum_nb_errors
1106 # --------------------------------------------------------------------
1107 def compute_nb_errors_output(input, nb_to_log=0):
1108 result = input.clone()
1109 k = torch.arange(result.size(1), device=result.device)[None, :]
1111 ((result == self.t_output) * k).max(dim=1, keepdim=True).values
1114 ((result == self.t_prog) * k).max(dim=1, keepdim=True).values
1116 ar_mask = (k > last_output_idx).long() * (k < first_prog_idx).long()
1117 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1119 masked_inplace_autoregression(
1124 deterministic_synthesis,
1128 sum_nb_total, sum_nb_errors = 0, 0
1129 for one_input, one_result, i, j in zip(
1130 input, result, last_output_idx, first_prog_idx
1132 seq = [self.id2token[i.item()] for i in one_result]
1134 correct = (one_input - one_result).abs().max() == 0
1135 sum_nb_errors += 0 if correct else 1
1138 self.id2token[i.item()] for i in one_result[i : j + 1]
1141 self.id2token[i.item()] for i in one_input[i : j + 1]
1143 comment = "*" if correct else "-"
1144 result_stack = " ".join([str(x) for x in result_stack])
1145 target_stack = " ".join([str(x) for x in target_stack])
1147 f"output_test {comment} [{target_stack}] PREDICTED [{result_stack}]"
1151 return sum_nb_total, sum_nb_errors
1153 # --------------------------------------------------------------------
1155 if not self.no_prog:
1156 test_nb_total, test_nb_errors = compute_nb_errors_prog(
1157 self.test_input[:1000].to(self.device), nb_to_log=10
1161 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}%"
1164 test_nb_total, test_nb_errors = compute_nb_errors_output(
1165 self.test_input[:1000].to(self.device), nb_to_log=10
1169 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}%"
1172 if save_attention_image is None:
1173 logger("no save_attention_image (is pycairo installed?)")
1175 ns = torch.randint(self.test_input.size(0), (1,)).item()
1176 input = self.test_input[ns : ns + 1].clone()
1177 last = (input != self.t_nul).max(0).values.nonzero().max() + 3
1178 input = input[:, :last].to(self.device)
1180 with torch.autograd.no_grad():
1183 model.record_attention(True)
1184 model(BracketedSequence(input))
1186 ram = model.retrieve_attention()
1187 model.record_attention(False)
1189 tokens_output = [self.id2token[i.item()] for i in input[0]]
1190 tokens_input = ["n/a"] + tokens_output[:-1]
1191 for n_head in range(ram[0].size(1)):
1192 filename = os.path.join(
1193 result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
1195 attention_matrices = [m[0, n_head] for m in ram]
1196 save_attention_image(
1202 # min_total_attention=0.9,
1206 logger(f"wrote {filename}")
1209 ######################################################################
1216 def tensorize(self, sequences):
1217 len_max = max([len(x) for x in sequences])
1222 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1239 device=torch.device("cpu"),
1243 self.batch_size = batch_size
1244 self.device = device
1246 train_sequences = expr.generate_sequences(
1248 nb_variables=nb_variables,
1249 length=sequence_length,
1250 operand_max=operand_max,
1251 result_max=result_max,
1254 test_sequences = expr.generate_sequences(
1256 nb_variables=nb_variables,
1257 length=sequence_length,
1258 operand_max=operand_max,
1259 result_max=result_max,
1262 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1265 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1266 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1268 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1270 self.train_input = self.tensorize(train_sequences)
1271 self.test_input = self.tensorize(test_sequences)
1273 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1275 def batches(self, split="train", nb_to_use=-1, desc=None):
1276 assert split in {"train", "test"}
1277 input = self.train_input if split == "train" else self.test_input
1279 input = input[:nb_to_use]
1281 desc = f"epoch-{split}"
1282 for batch in tqdm.tqdm(
1283 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1285 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1286 batch = batch[:, :last]
1289 def vocabulary_size(self):
1290 return self.nb_codes
1292 def seq2str(self, s):
1293 return "".join([self.id2char[k.item()] for k in s])
1295 def produce_results(
1301 deterministic_synthesis,
1304 def compute_nb_correct(input):
1305 result = input.clone()
1306 s = (result == self.space).long()
1307 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1308 result = (1 - ar_mask) * result + ar_mask * self.filler
1309 masked_inplace_autoregression(
1314 deterministic_synthesis,
1318 nb_total = input.size(0)
1319 nb_correct = (input == result).long().min(1).values.sum()
1321 #######################################################################
1322 # Comput predicted vs. true variable values
1324 nb_delta = torch.zeros(5, dtype=torch.int64)
1327 values_input = expr.extract_results([self.seq2str(s) for s in input])
1328 values_result = expr.extract_results([self.seq2str(s) for s in result])
1330 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1332 with open(filename, "w") as f:
1333 for i, r in zip(values_input, values_result):
1334 for n, vi in i.items():
1336 f.write(f"{vi} {-1 if vr is None else vr}\n")
1338 if vr is None or vr < 0:
1342 if d >= nb_delta.size(0):
1347 ######################################################################
1349 return nb_total, nb_correct, nb_delta, nb_missed
1356 ) = compute_nb_correct(self.test_input[:10000])
1359 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}%"
1362 nb_total = test_nb_delta.sum() + test_nb_missed
1363 for d in range(test_nb_delta.size(0)):
1365 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1368 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1371 ##############################################################
1372 # Log a few generated sequences
1373 if input_file is None:
1374 input = self.test_input[:10]
1376 with open(input_file, "r") as f:
1377 sequences = [e.strip() for e in f.readlines()]
1378 sequences = [s + " " + "#" * 50 for s in sequences]
1379 input = self.tensorize(sequences)
1381 result = input.clone()
1382 s = (result == self.space).long()
1383 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1384 result = (1 - ar_mask) * result + ar_mask * self.filler
1386 for n in range(result.size(0)):
1387 logger(f"test_before {self.seq2str(result[n])}")
1389 masked_inplace_autoregression(
1394 deterministic_synthesis,
1398 correct = (1 - ar_mask) * self.space + ar_mask * input
1399 for n in range(result.size(0)):
1400 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1401 logger(f"test_after {self.seq2str(result[n])} {comment}")
1402 logger(f"truth {self.seq2str(correct[n])}")
1403 ##############################################################
1406 ######################################################################
1419 device=torch.device("cpu"),
1420 device_storage=torch.device("cpu"),
1424 self.batch_size = batch_size
1425 self.device = device
1434 ) = world.create_data_and_processors(
1439 nb_epochs=vqae_nb_epochs,
1442 device_storage=device_storage,
1445 train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1446 test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1448 nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1449 nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1451 self.len_frame_seq = train_frame_seq.size(1)
1452 self.len_action_seq = train_action_seq.size(1)
1453 self.nb_codes = nb_frame_codes + nb_action_codes
1455 train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1457 train_action_seq += nb_frame_codes
1458 self.train_input = torch.cat(
1459 (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1462 test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1463 test_action_seq += nb_frame_codes
1464 self.test_input = torch.cat(
1465 (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1468 def batches(self, split="train", nb_to_use=-1, desc=None):
1469 assert split in {"train", "test"}
1470 input = self.train_input if split == "train" else self.test_input
1472 input = input[:nb_to_use]
1474 desc = f"epoch-{split}"
1475 for batch in tqdm.tqdm(
1476 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1478 yield batch.to(self.device)
1480 def vocabulary_size(self):
1481 return self.nb_codes
1483 def produce_results(
1484 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1487 2 * self.len_frame_seq + self.len_action_seq, device=self.device
1490 input = self.test_input[:64].to(self.device)
1491 result = input.clone()
1494 (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1496 result *= 1 - ar_mask
1498 masked_inplace_autoregression(
1503 deterministic_synthesis,
1507 seq_start = input[:, : self.len_frame_seq]
1508 seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1509 seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1512 (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1514 result = result.reshape(-1, result.size(-1))
1516 frames = self.seq2frame(result)
1517 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1518 torchvision.utils.save_image(
1519 frames.float() / (world.Box.nb_rgb_levels - 1),
1525 logger(f"wrote {image_name}")
1528 ######################################################################