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
75 ######################################################################
79 def generate_sequences(self, nb):
82 def seq2str(self, seq):
83 return "[NOT IMPLEMENTED]"
89 class ProblemLevel0(Problem):
90 def __init__(self, nb_sentences=100, len_prompt=5, len_result=5):
91 self.seq = torch.randint(10, (nb_sentences, len_prompt + 1 + len_result))
92 self.seq[:, len_prompt] = 10
94 def generate_sequences(self, nb):
95 sequences = self.seq[torch.randint(self.seq.size(0), (nb,))]
96 ar_mask = (sequences == 10).long()
97 ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
98 return sequences, ar_mask
101 class ProblemLevel1(Problem):
102 def __init__(self, nb_operators=100, len_source=5, len_result=8):
103 self.len_source = len_source
104 self.len_result = len_result
105 self.len_nb_operator = int(math.log(nb_operators) / math.log(10)) + 1
106 self.operators = F.one_hot(
107 torch.rand(nb_operators, len_result, len_source).argmax(-1),
108 num_classes=len_source,
111 def generate_sequences(self, nb):
112 nb_operators = torch.randint(self.operators.size(0), (nb,))
113 operators = self.operators[nb_operators]
115 nb_operators[:, None]
116 // 10 ** torch.arange(self.len_nb_operator - 1, -1, -1)
118 marker1 = torch.full((nb, 1), 10)
119 # source = torch.randint(10, (nb, self.len_source))
120 source = torch.rand(nb, 10).sort(dim=1).indices[:, : self.len_source]
121 marker2 = torch.full((nb, 1), 11)
122 result = operators.bmm(source[:, :, None]).squeeze(-1)
123 sequences = torch.cat((nb_operators, marker1, source, marker2, result), 1)
124 ar_mask = (sequences == 11).long()
125 ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
126 return sequences, ar_mask
128 def seq2str(self, seq):
129 return "".join("0123456789|>"[x.item()] for x in seq)
132 class ProblemLevel2(Problem):
133 def __init__(self, len_source=5, len_result=8):
134 self.len_source = len_source
135 self.len_result = len_result
137 def generate_sequences(self, nb):
138 operators = F.one_hot(
139 torch.rand(nb, self.len_result, self.len_source).argmax(-1),
140 num_classes=self.len_source,
142 source1 = torch.rand(nb, 10).sort(dim=1).indices[:, : self.len_source]
143 marker1 = torch.full((nb, 1), 10)
144 result1 = operators.bmm(source1[:, :, None]).squeeze(-1)
145 marker2 = torch.full((nb, 1), 11)
146 source2 = torch.randint(10, (nb, self.len_source))
147 marker3 = torch.full((nb, 1), 12)
148 result2 = operators.bmm(source2[:, :, None]).squeeze(-1)
150 sequences = torch.cat(
151 (source1, marker1, result1, marker2, source2, marker3, result2), 1
153 ar_mask = (sequences == 12).long()
154 ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
155 return sequences, ar_mask
157 def seq2str(self, seq):
158 return "".join("0123456789>|~"[x.item()] for x in seq)
164 class ProblemAddition(Problem):
165 def __init__(self, nb_digits=10, zero_padded=False, inverted_result=False):
166 self.nb_digits = nb_digits
167 self.zero_padded = zero_padded
168 self.inverted_result = inverted_result
169 self.char2id = dict([(c, n) for n, c in enumerate("0123456789+=$")])
170 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
172 def tensorize(self, strings):
173 len_max = max([len(x) for x in strings])
178 [self.char2id[c] for c in s + "$" * (len_max - len(s))]
186 def generate_sequences(self, nb):
189 a, b = torch.randint(10**self.nb_digits, (2,))
191 a, b, c = str(a.item()), str(b.item()), str(c.item())
193 a = "0" * (self.nb_digits - len(a)) + a
194 b = "0" * (self.nb_digits - len(b)) + b
195 c = "0" * (self.nb_digits + 1 - len(c)) + c
196 if self.inverted_result:
198 sequences.append(f"{a}+{b}={c}$")
200 sequences = self.tensorize(sequences)
201 ar_mask = (sequences == self.char2id["="]).long()
202 ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
203 return sequences, ar_mask
205 def seq2str(self, seq):
206 return "".join(self.id2char[x.item()] for x in seq)
209 # class ProblemUnion(Problem):
210 # problems = [ProblemByheart()]
211 # nb_common_codes = 100
213 # def generate_sequences(nb_samples):
214 # problem_indexes = torch.randint(len(problems), (nb_samples,))
215 # nb_samples_per_problem = torch.one_hot(problem_indexes).sum(0)
216 # print(f"{nb_samples_per_problem}")
218 # for nb, p in zip(nb_samples_per_problem, problems):
219 # all_seq.append(p.generate_sequences(nb_samples_per_problem[nb]))
222 # for strain, stest in zip(train_seq, test_seq):
223 # s = torch.cat((strain, stest), 0)
236 device=torch.device("cpu"),
241 self.batch_size = batch_size
243 self.problem = problem
245 self.train_input, self.train_ar_mask = self.problem.generate_sequences(
248 self.test_input, self.test_ar_mask = self.problem.generate_sequences(
252 self.train_input, self.train_ar_mask = self.train_input.to(
254 ), self.train_ar_mask.to(device)
255 self.test_input, self.test_ar_mask = self.test_input.to(
257 ), self.test_ar_mask.to(device)
259 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
261 # A bit of paranoia never hurts
263 self.nb_codes <= max_nb_codes
264 and self.train_input.min() >= 0
265 and self.test_input.min() >= 0
266 and tuple(self.train_ar_mask.unique()) == (0, 1)
267 and tuple(self.test_ar_mask.unique()) == (0, 1)
270 def batches(self, split="train", nb_to_use=-1, desc=None):
271 assert split in {"train", "test"}
272 input = self.train_input if split == "train" else self.test_input
274 input = input[:nb_to_use]
276 desc = f"epoch-{split}"
277 for batch in tqdm.tqdm(
278 input.split(self.batch_size), dynamic_ncols=True, desc=desc
282 def vocabulary_size(self):
286 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
288 def compute_accuracy(input, ar_mask, logger=None):
289 input, ar_mask = input[:nmax], ar_mask[:nmax]
290 result = input.clone() * (1 - ar_mask)
292 masked_inplace_autoregression(
297 deterministic_synthesis,
298 progress_bar_desc=None,
302 if logger is not None:
303 for sp, st in zip(result[:10], input[:10]):
305 f"test_sequences {n_epoch} prediction {self.problem.seq2str(sp)}"
308 f" {n_epoch} ground truth {self.problem.seq2str(st)}"
311 nb_total = ar_mask.sum().item()
312 nb_correct = ((result == input).long() * ar_mask).sum().item()
314 return nb_total, nb_correct
316 train_nb_total, train_nb_correct = compute_accuracy(
317 self.train_input, self.train_ar_mask
321 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}%"
324 test_nb_total, test_nb_correct = compute_accuracy(
325 self.test_input, self.test_ar_mask, logger
329 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}%"
333 ######################################################################
338 class PicoCLVR(Task):
339 # Make a tensor from a list of strings
340 def tensorize(self, descr):
341 token_descr = [s.strip().split(" ") for s in descr]
342 l = max([len(s) for s in token_descr])
343 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
344 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
345 return torch.tensor(id_descr, device=self.device)
347 # Make a list of strings from a tensor
348 def detensorize(self, x):
349 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
351 # trim all the tensors in the tuple z to remove as much token from
352 # left and right in the first tensor. If z is a tuple, all its
353 # elements are trimed according to the triming for the first
354 def trim(self, z, token="<nul>"):
355 n = self.token2id[token]
358 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
359 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
360 return tuple([t[:, a:b] for t in z])
362 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
363 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
366 ######################
377 device=torch.device("cpu"),
383 def generate_descr(nb, cache_suffix, pruner):
384 return picoclvr.generate(
394 self.batch_size = batch_size
396 self.pruner_train = pruner_train
397 self.pruner_eval = pruner_eval
399 if logger is not None:
401 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
404 self.train_descr = generate_descr(
405 nb_train_samples, "train", pruner=self.pruner_train
407 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
409 # Build the tokenizer
410 tokens = {"<nul>", "<img>"}
411 for d in [self.train_descr, self.test_descr]:
413 for t in s.strip().split(" "):
415 # make this set a sorted list to get the same tensors given
417 tokens = list(tokens)
419 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
420 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
421 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
423 # Tokenize the train and test sets
424 self.train_input = self.tensorize(self.train_descr)
425 self.test_input = self.tensorize(self.test_descr)
427 def batches(self, split="train"):
428 assert split in {"train", "test"}
429 input = self.train_input if split == "train" else self.test_input
430 for batch in tqdm.tqdm(
431 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
433 yield self.trim(batch)
435 def vocabulary_size(self):
436 return len(self.token2id)
438 def compute_missing_properties(
439 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
441 acc_nb_requested_properties = []
442 acc_nb_missing_properties = []
445 for input in tqdm.tqdm(
446 self.test_input.split(self.batch_size),
448 desc=f"test-properties",
450 result = input.clone()
451 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
452 result = (1 - ar_mask) * result + ar_mask * self.t_nul
453 masked_inplace_autoregression(
458 deterministic_synthesis,
459 progress_bar_desc=None,
463 result_descr = self.detensorize(result)
464 np = picoclvr.nb_properties(
470 nb_requested_properties, _, nb_missing_properties = zip(*np)
471 acc_nb_requested_properties += nb_requested_properties
472 acc_nb_missing_properties += nb_missing_properties
473 acc_nb_results += len(result_descr)
475 nb_requested_properties = sum(acc_nb_requested_properties)
476 nb_missing_properties = sum(acc_nb_missing_properties)
478 prefix = "" if pruner is None else "pruned_"
479 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
481 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
484 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
487 ######################################################################
490 self, n_epoch, model, result_dir, logger, deterministic_synthesis
492 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
494 if self.pruner_eval is not None:
495 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
497 nb_tokens_to_generate = self.height * self.width + 3
502 for primer_descr in [
503 "red above green <sep> green top <sep> blue right of red",
504 "there is red <sep> there is yellow <sep> there is blue",
505 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
506 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
508 primer += [primer_descr + " <img>"] * nb_per_primer
510 result = self.tensorize(primer)
511 fill = result.new_full(
512 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
514 result = torch.cat((result, fill), 1)
515 ar_mask = (result == self.t_nul).long()
516 masked_inplace_autoregression(
521 deterministic_synthesis,
524 result_descr = self.detensorize(result)
526 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
528 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
529 acc_nb_results = len(result_descr)
531 nb_requested_properties = sum(acc_nb_requested_properties)
532 nb_missing_properties = sum(acc_nb_missing_properties)
535 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
537 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
540 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
543 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
547 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
551 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
557 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
558 torchvision.utils.save_image(
559 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
561 logger(f"wrote {image_name}")
564 ######################################################################
569 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
573 self.nb_train_samples = (nb_train_samples,)
574 self.nb_test_samples = (nb_test_samples,)
575 self.batch_size = batch_size
577 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
578 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
579 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
580 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
582 def batches(self, split="train", nb_to_use=-1, desc=None):
583 assert split in {"train", "test"}
584 input = self.train_input if split == "train" else self.test_input
586 input = input[:nb_to_use]
588 desc = f"epoch-{split}"
589 for batch in tqdm.tqdm(
590 input.split(self.batch_size), dynamic_ncols=True, desc=desc
594 def vocabulary_size(self):
598 self, n_epoch, model, result_dir, logger, deterministic_synthesis
600 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
601 ar_mask = torch.full_like(results, 1)
602 masked_inplace_autoregression(
607 deterministic_synthesis,
610 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
611 torchvision.utils.save_image(
612 1 - results.reshape(-1, 1, 28, 28) / 255.0,
617 logger(f"wrote {image_name}")
620 ######################################################################
626 def map2seq(self, *m):
627 return torch.cat([x.flatten(1) for x in m], 1)
629 def seq2map(self, s):
630 s = s.reshape(s.size(0), -1, self.height, self.width)
631 return (s[:, k] for k in range(s.size(1)))
641 device=torch.device("cpu"),
645 self.batch_size = batch_size
650 train_mazes, train_paths, _ = maze.create_maze_data(
655 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
657 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
659 test_mazes, test_paths, _ = maze.create_maze_data(
664 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
666 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
668 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
670 def batches(self, split="train", nb_to_use=-1, desc=None):
671 assert split in {"train", "test"}
672 input = self.train_input if split == "train" else self.test_input
674 input = input[:nb_to_use]
676 desc = f"epoch-{split}"
677 for batch in tqdm.tqdm(
678 input.split(self.batch_size), dynamic_ncols=True, desc=desc
682 def vocabulary_size(self):
686 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
688 nb_total, nb_correct = 0, 0
690 self.width * self.height,
691 self.width * self.height,
696 for input in self.batches(split, nb_to_use):
697 result = input.clone()
698 ar_mask = result.new_zeros(result.size())
699 ar_mask[:, self.height * self.width :] = 1
700 result *= 1 - ar_mask
701 masked_inplace_autoregression(
706 deterministic_synthesis,
707 progress_bar_desc=None,
710 mazes, paths = self.seq2map(result)
711 path_correctness = maze.path_correctness(mazes, paths)
712 nb_correct += path_correctness.long().sum()
713 nb_total += mazes.size(0)
715 optimal_path_lengths = (
716 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
718 predicted_path_lengths = (
719 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
721 optimal_path_lengths = optimal_path_lengths[path_correctness]
722 predicted_path_lengths = predicted_path_lengths[path_correctness]
723 count[optimal_path_lengths, predicted_path_lengths] += 1
729 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
732 return nb_total, nb_correct, count
735 self, n_epoch, model, result_dir, logger, deterministic_synthesis
737 train_nb_total, train_nb_correct, count = self.compute_error(
741 deterministic_synthesis=deterministic_synthesis,
744 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}%"
747 test_nb_total, test_nb_correct, count = self.compute_error(
751 deterministic_synthesis=deterministic_synthesis,
754 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}%"
757 if count is not None:
758 proportion_optimal = count.diagonal().sum().float() / count.sum()
759 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
761 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
763 for i in range(count.size(0)):
764 for j in range(count.size(1)):
765 eol = " " if j < count.size(1) - 1 else "\n"
766 f.write(f"{count[i,j]}{eol}")
768 input = self.test_input[:48]
769 result = input.clone()
770 ar_mask = result.new_zeros(result.size())
771 ar_mask[:, self.height * self.width :] = 1
772 result *= 1 - ar_mask
773 masked_inplace_autoregression(
778 deterministic_synthesis,
782 mazes, paths = self.seq2map(input)
783 _, predicted_paths = self.seq2map(result)
785 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
790 predicted_paths=predicted_paths,
791 path_correct=maze.path_correctness(mazes, predicted_paths),
792 path_optimal=maze.path_optimality(paths, predicted_paths),
794 logger(f"wrote {filename}")
797 ######################################################################
814 device=torch.device("cpu"),
818 self.batch_size = batch_size
822 self.prompt_length = prompt_length
824 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
833 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
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, prior_visits):
864 result = input.clone()
865 i = torch.arange(result.size(1), device=result.device)[None, :]
867 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
871 result *= 1 - ar_mask
873 masked_inplace_autoregression(
878 deterministic_synthesis,
882 nb_total = ((prior_visits > 0) * ar_mask).sum()
884 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
886 return nb_total, nb_correct
888 test_nb_total, test_nb_correct = compute_nb_correct(
889 self.test_input[:1000], self.test_prior_visits[:1000]
893 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}%"
897 ######################################################################
913 fraction_values_for_train=None,
914 device=torch.device("cpu"),
918 self.batch_size = batch_size
919 self.nb_steps = nb_steps
920 self.nb_stacks = nb_stacks
921 self.nb_digits = nb_digits
924 if fraction_values_for_train is None:
925 values_for_train = None
926 values_for_test = None
928 all = torch.randperm(10**nb_digits)
929 nb_for_train = int(all.size(0) * fraction_values_for_train)
930 values_for_train = all[:nb_for_train]
931 values_for_test = all[nb_for_train:]
933 self.train_input, self.train_stack_counts = stack.generate_sequences(
942 self.test_input, self.test_stack_counts = stack.generate_sequences(
951 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
952 counts = self.test_stack_counts.flatten()[i.flatten()]
953 counts = F.one_hot(counts).sum(0)
954 logger(f"test_pop_stack_counts {counts}")
956 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
958 def batches(self, split="train", nb_to_use=-1, desc=None):
959 assert split in {"train", "test"}
960 input = self.train_input if split == "train" else self.test_input
962 input = input[:nb_to_use]
964 desc = f"epoch-{split}"
965 for batch in tqdm.tqdm(
966 input.split(self.batch_size), dynamic_ncols=True, desc=desc
970 def vocabulary_size(self):
974 self, n_epoch, model, result_dir, logger, deterministic_synthesis
976 def compute_nb_correct(input):
977 result = input.clone()
978 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
979 ar_mask = (result != input).long()
980 masked_inplace_autoregression(
985 deterministic_synthesis,
989 errors = ((result != input).long() * ar_mask).reshape(
990 -1, 1 + self.nb_digits
992 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
994 nb_total = ar_mask.max(1).values.sum()
995 nb_correct = nb_total - errors.max(1).values.sum()
997 return nb_total, nb_correct
999 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
1002 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}%"
1005 ##############################################################
1006 # Log a few generated sequences
1007 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
1008 result = input.clone()
1009 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
1010 ar_mask = (result != input).long()
1012 # for n in range(result.size(0)):
1014 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1017 masked_inplace_autoregression(
1022 deterministic_synthesis,
1026 for n in range(result.size(0)):
1028 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1030 ##############################################################
1033 ######################################################################
1039 def tensorize(self, sequences):
1040 len_max = max([len(x) for x in sequences])
1046 self.token2id[str(c)]
1047 for c in s + ["<nul>"] * (len_max - len(s))
1056 def seq2str(self, seq):
1057 return " ".join([self.id2token[i] for i in seq])
1064 nb_starting_values=3,
1070 device=torch.device("cpu"),
1074 self.batch_size = batch_size
1075 self.device = device
1076 self.no_prog = no_prog
1080 nb_starting_values=nb_starting_values,
1081 nb_result_values_max=4 * nb_starting_values,
1082 max_input=max_input,
1086 for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
1091 nb_starting_values=nb_starting_values,
1092 nb_result_values_max=4 * nb_starting_values,
1093 max_input=max_input,
1097 for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
1101 set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
1103 val_max = max([x if type(x) is int else 0 for x in symbols])
1104 symbols = list(filter(lambda x: type(x) is str, symbols))
1106 symbols += [str(n) for n in range(val_max + 1)]
1107 self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
1108 self.id2token = dict([(n, c) for c, n in self.token2id.items()])
1110 self.t_nul = self.token2id["<nul>"]
1111 self.t_input = self.token2id["<in>"]
1112 self.t_output = self.token2id["<out>"]
1113 self.t_prog = self.token2id["<prg>"]
1114 self.t_end = self.token2id["<end>"]
1116 self.train_input = self.tensorize(train_sequences)
1117 self.test_input = self.tensorize(test_sequences)
1120 # Excise the program from every train and test example
1121 k = torch.arange(self.train_input.size(1), device=self.train_input.device)[
1125 ((self.train_input == self.t_prog).long() * k)
1126 .max(1, keepdim=True)
1129 self.train_input = (
1130 self.train_input * (k <= p).long()
1131 + self.t_end * (k == p + 1).long()
1132 + self.t_nul * (k > p + 1).long()
1134 k = torch.arange(self.test_input.size(1), device=self.test_input.device)[
1138 ((self.test_input == self.t_prog).long() * k)
1139 .max(1, keepdim=True)
1143 self.test_input * (k <= p).long()
1144 + self.t_end * (k == p + 1).long()
1145 + self.t_nul * (k > p + 1).long()
1148 if logger is not None:
1149 logger(f"value_max {val_max}")
1150 for x in self.train_input[:25]:
1151 end = (x != self.t_nul).nonzero().max().item() + 1
1152 seq = [self.id2token[i.item()] for i in x[:end]]
1154 logger(f"example_seq {s}")
1156 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1158 def batches(self, split="train", nb_to_use=-1, desc=None):
1159 assert split in {"train", "test"}
1160 input = self.train_input if split == "train" else self.test_input
1162 input = input[:nb_to_use]
1164 desc = f"epoch-{split}"
1165 for batch in tqdm.tqdm(
1166 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1168 last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1169 batch = batch[:, :last].to(self.device)
1172 def vocabulary_size(self):
1173 return self.nb_codes
1175 def produce_results(
1176 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1178 # --------------------------------------------------------------------
1179 def compute_nb_errors_prog(input, nb_to_log=0):
1180 result = input.clone()
1181 s = (result == self.t_prog).long()
1182 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1183 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1185 masked_inplace_autoregression(
1190 deterministic_synthesis,
1194 sum_nb_total, sum_nb_errors = 0, 0
1195 for one_input, one_result in zip(input, result):
1196 seq = [self.id2token[i.item()] for i in one_result]
1197 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1199 sum_nb_errors += 0 if nb_errors == 0 else 1
1201 gt_seq = [self.id2token[i.item()] for i in one_input]
1202 _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1203 gt_prog = " ".join([str(x) for x in gt_prog])
1204 prog = " ".join([str(x) for x in prog])
1205 comment = "*" if nb_errors == 0 else "-"
1206 logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1207 for start_stack, target_stack, result_stack, correct in stacks:
1208 comment = "*" if correct else "-"
1209 start_stack = " ".join([str(x) for x in start_stack])
1210 target_stack = " ".join([str(x) for x in target_stack])
1211 result_stack = " ".join([str(x) for x in result_stack])
1213 f" {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1217 return sum_nb_total, sum_nb_errors
1219 # --------------------------------------------------------------------
1220 def compute_nb_errors_output(input, nb_to_log=0):
1221 result = input.clone()
1222 k = torch.arange(result.size(1), device=result.device)[None, :]
1224 ((result == self.t_output) * k).max(dim=1, keepdim=True).values
1227 ((result == self.t_prog) * k).max(dim=1, keepdim=True).values
1229 ar_mask = (k > last_output_idx).long() * (k < first_prog_idx).long()
1230 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1232 masked_inplace_autoregression(
1237 deterministic_synthesis,
1241 sum_nb_total, sum_nb_errors = 0, 0
1242 for one_input, one_result, i, j in zip(
1243 input, result, last_output_idx, first_prog_idx
1245 seq = [self.id2token[i.item()] for i in one_result]
1247 correct = (one_input - one_result).abs().max() == 0
1248 sum_nb_errors += 0 if correct else 1
1251 self.id2token[i.item()] for i in one_result[i : j + 1]
1254 self.id2token[i.item()] for i in one_input[i : j + 1]
1256 comment = "*" if correct else "-"
1257 result_stack = " ".join([str(x) for x in result_stack])
1258 target_stack = " ".join([str(x) for x in target_stack])
1260 f"output_test {comment} [{target_stack}] PREDICTED [{result_stack}]"
1264 return sum_nb_total, sum_nb_errors
1266 # --------------------------------------------------------------------
1268 if not self.no_prog:
1269 test_nb_total, test_nb_errors = compute_nb_errors_prog(
1270 self.test_input[:1000].to(self.device), nb_to_log=10
1274 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}%"
1277 test_nb_total, test_nb_errors = compute_nb_errors_output(
1278 self.test_input[:1000].to(self.device), nb_to_log=10
1282 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}%"
1285 if save_attention_image is not None:
1286 input = self.test_input[:1]
1287 result = input.clone()
1288 s = (result == self.t_prog).long()
1289 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1290 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1292 masked_inplace_autoregression(
1297 deterministic_synthesis,
1301 with torch.autograd.no_grad():
1304 model.record_attention(True)
1305 model(BracketedSequence(result))
1307 ram = model.retrieve_attention()
1308 model.record_attention(False)
1310 tokens_output = [self.id2token[i.item()] for i in result[0]]
1311 tokens_input = ["n/a"] + tokens_output[:-1]
1312 for n_head in range(ram[0].size(1)):
1313 filename = os.path.join(
1314 result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
1316 attention_matrices = [m[0, n_head] for m in ram]
1317 save_attention_image(
1323 # min_total_attention=0.9,
1327 logger(f"wrote {filename}")
1330 ######################################################################
1337 def tensorize(self, sequences):
1338 len_max = max([len(x) for x in sequences])
1343 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1360 device=torch.device("cpu"),
1364 self.batch_size = batch_size
1365 self.device = device
1367 train_sequences = expr.generate_sequences(
1369 nb_variables=nb_variables,
1370 length=sequence_length,
1371 operand_max=operand_max,
1372 result_max=result_max,
1375 test_sequences = expr.generate_sequences(
1377 nb_variables=nb_variables,
1378 length=sequence_length,
1379 operand_max=operand_max,
1380 result_max=result_max,
1383 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1386 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1387 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1389 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1391 self.train_input = self.tensorize(train_sequences)
1392 self.test_input = self.tensorize(test_sequences)
1394 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1396 def batches(self, split="train", nb_to_use=-1, desc=None):
1397 assert split in {"train", "test"}
1398 input = self.train_input if split == "train" else self.test_input
1400 input = input[:nb_to_use]
1402 desc = f"epoch-{split}"
1403 for batch in tqdm.tqdm(
1404 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1406 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1407 batch = batch[:, :last]
1410 def vocabulary_size(self):
1411 return self.nb_codes
1413 def seq2str(self, s):
1414 return "".join([self.id2char[k.item()] for k in s])
1416 def produce_results(
1422 deterministic_synthesis,
1425 def compute_nb_correct(input):
1426 result = input.clone()
1427 s = (result == self.space).long()
1428 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1429 result = (1 - ar_mask) * result + ar_mask * self.filler
1430 masked_inplace_autoregression(
1435 deterministic_synthesis,
1439 nb_total = input.size(0)
1440 nb_correct = (input == result).long().min(1).values.sum()
1442 #######################################################################
1443 # Comput predicted vs. true variable values
1445 nb_delta = torch.zeros(5, dtype=torch.int64)
1448 values_input = expr.extract_results([self.seq2str(s) for s in input])
1449 values_result = expr.extract_results([self.seq2str(s) for s in result])
1451 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1453 with open(filename, "w") as f:
1454 for i, r in zip(values_input, values_result):
1455 for n, vi in i.items():
1457 f.write(f"{vi} {-1 if vr is None else vr}\n")
1459 if vr is None or vr < 0:
1463 if d >= nb_delta.size(0):
1468 ######################################################################
1470 return nb_total, nb_correct, nb_delta, nb_missed
1477 ) = compute_nb_correct(self.test_input[:10000])
1480 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}%"
1483 nb_total = test_nb_delta.sum() + test_nb_missed
1484 for d in range(test_nb_delta.size(0)):
1486 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1489 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1492 ##############################################################
1493 # Log a few generated sequences
1494 if input_file is None:
1495 input = self.test_input[:10]
1497 with open(input_file, "r") as f:
1498 sequences = [e.strip() for e in f.readlines()]
1499 sequences = [s + " " + "#" * 50 for s in sequences]
1500 input = self.tensorize(sequences)
1502 result = input.clone()
1503 s = (result == self.space).long()
1504 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1505 result = (1 - ar_mask) * result + ar_mask * self.filler
1507 for n in range(result.size(0)):
1508 logger(f"test_before {self.seq2str(result[n])}")
1510 masked_inplace_autoregression(
1515 deterministic_synthesis,
1519 correct = (1 - ar_mask) * self.space + ar_mask * input
1520 for n in range(result.size(0)):
1521 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1522 logger(f"test_after {self.seq2str(result[n])} {comment}")
1523 logger(f"truth {self.seq2str(correct[n])}")
1524 ##############################################################
1527 ######################################################################
1540 device=torch.device("cpu"),
1541 device_storage=torch.device("cpu"),
1545 self.batch_size = batch_size
1546 self.device = device
1555 ) = world.create_data_and_processors(
1560 nb_epochs=vqae_nb_epochs,
1563 device_storage=device_storage,
1566 train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1567 test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1569 nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1570 nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1572 self.len_frame_seq = train_frame_seq.size(1)
1573 self.len_action_seq = train_action_seq.size(1)
1574 self.nb_codes = nb_frame_codes + nb_action_codes
1576 train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1578 train_action_seq += nb_frame_codes
1579 self.train_input = torch.cat(
1580 (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1583 test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1584 test_action_seq += nb_frame_codes
1585 self.test_input = torch.cat(
1586 (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1589 def batches(self, split="train", nb_to_use=-1, desc=None):
1590 assert split in {"train", "test"}
1591 input = self.train_input if split == "train" else self.test_input
1593 input = input[:nb_to_use]
1595 desc = f"epoch-{split}"
1596 for batch in tqdm.tqdm(
1597 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1599 yield batch.to(self.device)
1601 def vocabulary_size(self):
1602 return self.nb_codes
1604 def produce_results(
1605 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1608 2 * self.len_frame_seq + self.len_action_seq, device=self.device
1611 input = self.test_input[:64].to(self.device)
1612 result = input.clone()
1615 (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1617 result *= 1 - ar_mask
1619 masked_inplace_autoregression(
1624 deterministic_synthesis,
1628 seq_start = input[:, : self.len_frame_seq]
1629 seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1630 seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1633 (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1635 result = result.reshape(-1, result.size(-1))
1637 frames = self.seq2frame(result)
1638 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1639 torchvision.utils.save_image(
1640 frames.float() / (world.Box.nb_rgb_levels - 1),
1646 logger(f"wrote {image_name}")
1649 ######################################################################