5 import torch, torchvision
8 from torch.nn import functional as F
10 ######################################################################
13 def masked_inplace_autoregression(
18 deterministic_synthesis,
19 forbidden_tokens=None,
20 progress_bar_desc="autoregression",
21 device=torch.device("cpu"),
23 batches = zip(input.split(batch_size), ar_mask.split(batch_size))
25 if progress_bar_desc is not None:
29 desc=progress_bar_desc,
30 total=input.size(0) // batch_size,
33 for input, ar_mask in batches:
34 model.masked_inplace_autoregression(
35 input, ar_mask, forbidden_tokens, deterministic_synthesis
40 def batches(self, split="train"):
43 def vocabulary_size(self):
47 self, n_epoch, model, result_dir, logger, deterministic_synthesis
52 ######################################################################
58 # Make a tensor from a list of strings
59 def tensorize(self, descr):
60 token_descr = [s.strip().split(" ") for s in descr]
61 l = max([len(s) for s in token_descr])
62 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
63 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
64 return torch.tensor(id_descr, device=self.device)
66 # Make a list of strings from a tensor
67 def detensorize(self, x):
68 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
70 # trim all the tensors in the tuple z to remove as much token from
71 # left and right in the first tensor. If z is a tuple, all its
72 # elements are trimed according to the triming for the first
73 def trim(self, z, token="<nul>"):
74 n = self.token2id[token]
77 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
78 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
79 return tuple([t[:, a:b] for t in z])
81 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
82 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
85 ######################
96 device=torch.device("cpu"),
100 def generate_descr(nb, cache_suffix, pruner):
101 return picoclvr.generate(
111 self.batch_size = batch_size
113 self.pruner_train = pruner_train
114 self.pruner_eval = pruner_eval
116 if logger is not None:
118 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
121 self.train_descr = generate_descr(
122 nb_train_samples, "train", pruner=self.pruner_train
124 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
126 # Build the tokenizer
127 tokens = {"<nul>", "<img>"}
128 for d in [self.train_descr, self.test_descr]:
130 for t in s.strip().split(" "):
132 # make this set a sorted list to get the same tensors given
134 tokens = list(tokens)
136 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
137 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
138 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
140 # Tokenize the train and test sets
141 self.train_input = self.tensorize(self.train_descr)
142 self.test_input = self.tensorize(self.test_descr)
144 def batches(self, split="train"):
145 assert split in {"train", "test"}
146 input = self.train_input if split == "train" else self.test_input
147 for batch in tqdm.tqdm(
148 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
150 yield self.trim(batch)
152 def vocabulary_size(self):
153 return len(self.token2id)
155 def compute_missing_properties(
156 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
158 acc_nb_requested_properties = []
159 acc_nb_missing_properties = []
162 for input in tqdm.tqdm(
163 self.test_input.split(self.batch_size),
165 desc=f"test-properties",
167 result = input.clone()
168 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
169 result = (1 - ar_mask) * result + ar_mask * self.t_nul
170 masked_inplace_autoregression(
175 deterministic_synthesis,
176 progress_bar_desc=None,
180 result_descr = self.detensorize(result)
181 np = picoclvr.nb_properties(
187 nb_requested_properties, _, nb_missing_properties = zip(*np)
188 acc_nb_requested_properties += nb_requested_properties
189 acc_nb_missing_properties += nb_missing_properties
190 acc_nb_results += len(result_descr)
192 nb_requested_properties = sum(acc_nb_requested_properties)
193 nb_missing_properties = sum(acc_nb_missing_properties)
195 prefix = "" if pruner is None else "pruned_"
196 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
198 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
201 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
204 ######################################################################
207 self, n_epoch, model, result_dir, logger, deterministic_synthesis
209 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
211 if self.pruner_eval is not None:
212 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
214 nb_tokens_to_generate = self.height * self.width + 3
219 for primer_descr in [
220 "red above green <sep> green top <sep> blue right of red",
221 "there is red <sep> there is yellow <sep> there is blue",
222 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
223 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
225 primer += [primer_descr + " <img>"] * nb_per_primer
227 result = self.tensorize(primer)
228 fill = result.new_full(
229 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
231 result = torch.cat((result, fill), 1)
232 ar_mask = (result == self.t_nul).long()
233 masked_inplace_autoregression(
238 deterministic_synthesis,
241 result_descr = self.detensorize(result)
243 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
245 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
246 acc_nb_results = len(result_descr)
248 nb_requested_properties = sum(acc_nb_requested_properties)
249 nb_missing_properties = sum(acc_nb_missing_properties)
252 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
254 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
257 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
260 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
264 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
268 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
274 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
275 torchvision.utils.save_image(
276 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
278 logger(f"wrote {image_name}")
281 ######################################################################
286 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
288 self.nb_train_samples = (nb_train_samples,)
289 self.nb_test_samples = (nb_test_samples,)
290 self.batch_size = batch_size
292 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
293 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
294 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
295 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
297 def batches(self, split="train", nb_to_use=-1, desc=None):
298 assert split in {"train", "test"}
299 input = self.train_input if split == "train" else self.test_input
301 input = input[:nb_to_use]
303 desc = f"epoch-{split}"
304 for batch in tqdm.tqdm(
305 input.split(self.batch_size), dynamic_ncols=True, desc=desc
309 def vocabulary_size(self):
313 self, n_epoch, model, result_dir, logger, deterministic_synthesis
315 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
316 ar_mask = torch.full_like(results, 1)
317 masked_inplace_autoregression(
322 deterministic_synthesis,
325 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
326 torchvision.utils.save_image(
327 1 - results.reshape(-1, 1, 28, 28) / 255.0,
332 logger(f"wrote {image_name}")
335 ######################################################################
341 def map2seq(self, *m):
342 return torch.cat([x.flatten(1) for x in m], 1)
344 def seq2map(self, s):
345 s = s.reshape(s.size(0), -1, self.height, self.width)
346 return (s[:, k] for k in range(s.size(1)))
356 device=torch.device("cpu"),
358 self.batch_size = batch_size
363 train_mazes, train_paths, _ = maze.create_maze_data(
368 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
370 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
372 test_mazes, test_paths, _ = maze.create_maze_data(
377 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
379 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
381 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
383 def batches(self, split="train", nb_to_use=-1, desc=None):
384 assert split in {"train", "test"}
385 input = self.train_input if split == "train" else self.test_input
387 input = input[:nb_to_use]
389 desc = f"epoch-{split}"
390 for batch in tqdm.tqdm(
391 input.split(self.batch_size), dynamic_ncols=True, desc=desc
395 def vocabulary_size(self):
399 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
401 nb_total, nb_correct = 0, 0
403 self.width * self.height,
404 self.width * self.height,
409 for input in self.batches(split, nb_to_use):
410 result = input.clone()
411 ar_mask = result.new_zeros(result.size())
412 ar_mask[:, self.height * self.width :] = 1
413 result *= 1 - ar_mask
414 masked_inplace_autoregression(
419 deterministic_synthesis,
420 progress_bar_desc=None,
423 mazes, paths = self.seq2map(result)
424 path_correctness = maze.path_correctness(mazes, paths)
425 nb_correct += path_correctness.long().sum()
426 nb_total += mazes.size(0)
428 optimal_path_lengths = (
429 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
431 predicted_path_lengths = (
432 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
434 optimal_path_lengths = optimal_path_lengths[path_correctness]
435 predicted_path_lengths = predicted_path_lengths[path_correctness]
436 count[optimal_path_lengths, predicted_path_lengths] += 1
442 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
445 return nb_total, nb_correct, count
448 self, n_epoch, model, result_dir, logger, deterministic_synthesis
450 with torch.autograd.no_grad():
454 train_nb_total, train_nb_correct, count = self.compute_error(
458 deterministic_synthesis=deterministic_synthesis,
461 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}%"
464 test_nb_total, test_nb_correct, count = self.compute_error(
468 deterministic_synthesis=deterministic_synthesis,
471 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}%"
474 if count is not None:
475 proportion_optimal = count.diagonal().sum().float() / count.sum()
476 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
478 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
480 for i in range(count.size(0)):
481 for j in range(count.size(1)):
482 eol = " " if j < count.size(1) - 1 else "\n"
483 f.write(f"{count[i,j]}{eol}")
485 input = self.test_input[:48]
486 result = input.clone()
487 ar_mask = result.new_zeros(result.size())
488 ar_mask[:, self.height * self.width :] = 1
489 result *= 1 - ar_mask
490 masked_inplace_autoregression(
495 deterministic_synthesis,
499 mazes, paths = self.seq2map(input)
500 _, predicted_paths = self.seq2map(result)
502 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
507 predicted_paths=predicted_paths,
508 path_correct=maze.path_correctness(mazes, predicted_paths),
509 path_optimal=maze.path_optimality(paths, predicted_paths),
511 logger(f"wrote {filename}")
516 ######################################################################
533 device=torch.device("cpu"),
535 self.batch_size = batch_size
539 self.prompt_length = prompt_length
541 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
550 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
560 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
562 def batches(self, split="train", nb_to_use=-1, desc=None):
563 assert split in {"train", "test"}
564 input = self.train_input if split == "train" else self.test_input
566 input = input[:nb_to_use]
568 desc = f"epoch-{split}"
569 for batch in tqdm.tqdm(
570 input.split(self.batch_size), dynamic_ncols=True, desc=desc
574 def vocabulary_size(self):
578 self, n_epoch, model, result_dir, logger, deterministic_synthesis
580 with torch.autograd.no_grad():
584 def compute_nb_correct(input, prior_visits):
585 result = input.clone()
586 i = torch.arange(result.size(1), device=result.device)[None, :]
588 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
592 result *= 1 - ar_mask
594 # snake.solver(result,ar_mask)
596 masked_inplace_autoregression(
601 deterministic_synthesis,
605 nb_total = ((prior_visits > 0) * ar_mask).sum()
608 (result == input).long() * (prior_visits > 0) * ar_mask
611 # nb_total = result.size(0)
612 # nb_correct = ((result - input).abs().sum(1) == 0).sum()
614 return nb_total, nb_correct
616 # train_nb_total, train_nb_correct = compute_nb_correct(
617 # self.train_input, self.train_prior_visits
621 # f"accuracy_train nb_total {train_nb_total} nb_correct {train_nb_correct} accuracy {(100.0*train_nb_correct)/train_nb_total:.02f}%"
624 test_nb_total, test_nb_correct = compute_nb_correct(
625 self.test_input[:1000], self.test_prior_visits[:1000]
629 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}%"
635 ######################################################################
651 fraction_values_for_train=None,
652 device=torch.device("cpu"),
654 self.batch_size = batch_size
655 self.nb_steps = nb_steps
656 self.nb_stacks = nb_stacks
657 self.nb_digits = nb_digits
660 if fraction_values_for_train is None:
661 values_for_train = None
662 values_for_test = None
664 all = torch.randperm(10**nb_digits)
665 nb_for_train = int(all.size(0) * fraction_values_for_train)
666 values_for_train = all[:nb_for_train]
667 values_for_test = all[nb_for_train:]
669 self.train_input, self.train_stack_counts = stack.generate_sequences(
678 self.test_input, self.test_stack_counts = stack.generate_sequences(
687 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
688 counts = self.test_stack_counts.flatten()[i.flatten()]
689 counts = F.one_hot(counts).sum(0)
690 logger(f"test_pop_stack_counts {counts}")
692 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
694 def batches(self, split="train", nb_to_use=-1, desc=None):
695 assert split in {"train", "test"}
696 input = self.train_input if split == "train" else self.test_input
698 input = input[:nb_to_use]
700 desc = f"epoch-{split}"
701 for batch in tqdm.tqdm(
702 input.split(self.batch_size), dynamic_ncols=True, desc=desc
706 def vocabulary_size(self):
710 self, n_epoch, model, result_dir, logger, deterministic_synthesis
712 with torch.autograd.no_grad():
716 def compute_nb_correct(input):
717 result = input.clone()
718 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
719 ar_mask = (result != input).long()
720 masked_inplace_autoregression(
725 deterministic_synthesis,
729 errors = ((result != input).long() * ar_mask).reshape(
730 -1, 1 + self.nb_digits
732 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
734 nb_total = ar_mask.max(1).values.sum()
735 nb_correct = nb_total - errors.max(1).values.sum()
737 return nb_total, nb_correct
739 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
742 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}%"
745 ##############################################################
746 # Log a few generated sequences
747 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
748 result = input.clone()
749 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
750 ar_mask = (result != input).long()
752 # for n in range(result.size(0)):
754 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
757 masked_inplace_autoregression(
762 deterministic_synthesis,
766 for n in range(result.size(0)):
768 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
770 ##############################################################
775 ######################################################################
782 def tensorize(self, sequences):
783 len_max = max([len(x) for x in sequences])
788 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
803 device=torch.device("cpu"),
805 self.batch_size = batch_size
808 train_sequences = expr.generate_sequences(
810 nb_variables=nb_variables,
811 length=sequence_length,
812 # length=2 * sequence_length,
813 # randomize_length=True,
815 test_sequences = expr.generate_sequences(
817 nb_variables=nb_variables,
818 length=sequence_length,
821 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
824 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
825 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
827 self.filler, self.space = self.char2id["#"], self.char2id[" "]
829 self.train_input = self.tensorize(train_sequences)
830 self.test_input = self.tensorize(test_sequences)
832 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
834 def batches(self, split="train", nb_to_use=-1, desc=None):
835 assert split in {"train", "test"}
836 input = self.train_input if split == "train" else self.test_input
838 input = input[:nb_to_use]
840 desc = f"epoch-{split}"
841 for batch in tqdm.tqdm(
842 input.split(self.batch_size), dynamic_ncols=True, desc=desc
845 last = (batch != self.filler).max(0).values.nonzero().max() + 3
846 batch = batch[:, :last]
849 def vocabulary_size(self):
852 def seq2str(self, s):
853 return "".join([self.id2char[k.item()] for k in s])
861 deterministic_synthesis,
864 with torch.autograd.no_grad():
868 def compute_nb_correct(input):
869 result = input.clone()
870 ar_mask = (result == self.space).long().cumsum(dim=1).clamp(max=1)
871 result = (1 - ar_mask) * result + ar_mask * self.filler
872 masked_inplace_autoregression(
877 deterministic_synthesis,
881 nb_total = input.size(0)
882 nb_correct = (input == result).long().min(1).values.sum()
884 #######################################################################
885 # Comput predicted vs. true variable values
887 nb_delta = torch.zeros(5, dtype=torch.int64)
890 values_input = expr.extract_results([self.seq2str(s) for s in input])
891 values_result = expr.extract_results([self.seq2str(s) for s in result])
893 for i, r in zip(values_input, values_result):
894 for n, vi in i.items():
896 if vr is None or vr < 0:
900 if d >= nb_delta.size(0):
905 ######################################################################
907 return nb_total, nb_correct, nb_delta, nb_missed
914 ) = compute_nb_correct(self.test_input[:1000])
917 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}%"
920 nb_total = test_nb_delta.sum() + test_nb_missed
921 for d in range(test_nb_delta.size(0)):
923 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
926 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
929 ##############################################################
930 # Log a few generated sequences
931 if input_file is None:
932 input = self.test_input[:10]
934 with open(input_file, "r") as f:
935 sequences = [e.strip() for e in f.readlines()]
936 sequences = [s + " " + "#" * 50 for s in sequences]
937 input = self.tensorize(sequences)
939 result = input.clone()
940 s = (result == self.space).long()
941 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
942 result = (1 - ar_mask) * result + ar_mask * self.filler
944 for n in range(result.size(0)):
945 logger(f"test_before {self.seq2str(result[n])}")
947 masked_inplace_autoregression(
952 deterministic_synthesis,
956 correct = (1 - ar_mask) * self.space + ar_mask * input
957 for n in range(result.size(0)):
958 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
959 logger(f"test_after {self.seq2str(result[n])} {comment}")
960 logger(f"truth {self.seq2str(correct[n])}")
961 ##############################################################
966 ######################################################################