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 ar_mask = (result == self.t_nul).long()
229 masked_inplace_autoregression(
234 deterministic_synthesis,
237 result_descr = self.detensorize(result)
239 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
241 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
242 acc_nb_results = len(result_descr)
244 nb_requested_properties = sum(acc_nb_requested_properties)
245 nb_missing_properties = sum(acc_nb_missing_properties)
248 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
250 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
253 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
256 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
260 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
264 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
270 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
271 torchvision.utils.save_image(
272 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
274 logger(f"wrote {image_name}")
277 ######################################################################
282 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
284 self.nb_train_samples = (nb_train_samples,)
285 self.nb_test_samples = (nb_test_samples,)
286 self.batch_size = batch_size
288 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
289 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
290 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
291 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
293 def batches(self, split="train", nb_to_use=-1, desc=None):
294 assert split in {"train", "test"}
295 input = self.train_input if split == "train" else self.test_input
297 input = input[:nb_to_use]
299 desc = f"epoch-{split}"
300 for batch in tqdm.tqdm(
301 input.split(self.batch_size), dynamic_ncols=True, desc=desc
305 def vocabulary_size(self):
309 self, n_epoch, model, result_dir, logger, deterministic_synthesis
311 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
312 ar_mask = torch.full_like(results, 1)
313 masked_inplace_autoregression(
318 deterministic_synthesis,
321 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
322 torchvision.utils.save_image(
323 1 - results.reshape(-1, 1, 28, 28) / 255.0,
328 logger(f"wrote {image_name}")
331 ######################################################################
337 def map2seq(self, *m):
338 return torch.cat([x.flatten(1) for x in m], 1)
340 def seq2map(self, s):
341 s = s.reshape(s.size(0), -1, self.height, self.width)
342 return (s[:, k] for k in range(s.size(1)))
352 device=torch.device("cpu"),
354 self.batch_size = batch_size
359 train_mazes, train_paths, _ = maze.create_maze_data(
364 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
366 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
368 test_mazes, test_paths, _ = maze.create_maze_data(
373 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
375 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
377 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
379 def batches(self, split="train", nb_to_use=-1, desc=None):
380 assert split in {"train", "test"}
381 input = self.train_input if split == "train" else self.test_input
383 input = input[:nb_to_use]
385 desc = f"epoch-{split}"
386 for batch in tqdm.tqdm(
387 input.split(self.batch_size), dynamic_ncols=True, desc=desc
391 def vocabulary_size(self):
395 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
397 nb_total, nb_correct = 0, 0
399 self.width * self.height,
400 self.width * self.height,
405 for input in self.batches(split, nb_to_use):
406 result = input.clone()
407 ar_mask = result.new_zeros(result.size())
408 ar_mask[:, self.height * self.width :] = 1
409 result *= 1 - ar_mask
410 masked_inplace_autoregression(
415 deterministic_synthesis,
416 progress_bar_desc=None,
419 mazes, paths = self.seq2map(result)
420 path_correctness = maze.path_correctness(mazes, paths)
421 nb_correct += path_correctness.long().sum()
422 nb_total += mazes.size(0)
424 optimal_path_lengths = (
425 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
427 predicted_path_lengths = (
428 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
430 optimal_path_lengths = optimal_path_lengths[path_correctness]
431 predicted_path_lengths = predicted_path_lengths[path_correctness]
432 count[optimal_path_lengths, predicted_path_lengths] += 1
438 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
441 return nb_total, nb_correct, count
444 self, n_epoch, model, result_dir, logger, deterministic_synthesis
446 with torch.autograd.no_grad():
450 train_nb_total, train_nb_correct, count = self.compute_error(
454 deterministic_synthesis=deterministic_synthesis,
457 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}%"
460 test_nb_total, test_nb_correct, count = self.compute_error(
464 deterministic_synthesis=deterministic_synthesis,
467 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}%"
470 if count is not None:
471 proportion_optimal = count.diagonal().sum().float() / count.sum()
472 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
474 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
476 for i in range(count.size(0)):
477 for j in range(count.size(1)):
478 eol = " " if j < count.size(1) - 1 else "\n"
479 f.write(f"{count[i,j]}{eol}")
481 input = self.test_input[:48]
482 result = input.clone()
483 ar_mask = result.new_zeros(result.size())
484 ar_mask[:, self.height * self.width :] = 1
485 result *= 1 - ar_mask
486 masked_inplace_autoregression(
491 deterministic_synthesis,
495 mazes, paths = self.seq2map(input)
496 _, predicted_paths = self.seq2map(result)
498 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
503 predicted_paths=predicted_paths,
504 path_correct=maze.path_correctness(mazes, predicted_paths),
505 path_optimal=maze.path_optimality(paths, predicted_paths),
507 logger(f"wrote {filename}")
512 ######################################################################
529 device=torch.device("cpu"),
531 self.batch_size = batch_size
535 self.prompt_length = prompt_length
537 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
546 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
556 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
558 def batches(self, split="train", nb_to_use=-1, desc=None):
559 assert split in {"train", "test"}
560 input = self.train_input if split == "train" else self.test_input
562 input = input[:nb_to_use]
564 desc = f"epoch-{split}"
565 for batch in tqdm.tqdm(
566 input.split(self.batch_size), dynamic_ncols=True, desc=desc
570 def vocabulary_size(self):
574 self, n_epoch, model, result_dir, logger, deterministic_synthesis
576 with torch.autograd.no_grad():
580 def compute_nb_correct(input, prior_visits):
581 result = input.clone()
582 i = torch.arange(result.size(1), device=result.device)[None, :]
584 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
588 result *= 1 - ar_mask
590 # snake.solver(result,ar_mask)
592 masked_inplace_autoregression(
597 deterministic_synthesis,
601 nb_total = ((prior_visits > 0) * ar_mask).sum()
604 (result == input).long() * (prior_visits > 0) * ar_mask
607 # nb_total = result.size(0)
608 # nb_correct = ((result - input).abs().sum(1) == 0).sum()
610 return nb_total, nb_correct
612 # train_nb_total, train_nb_correct = compute_nb_correct(
613 # self.train_input, self.train_prior_visits
617 # f"accuracy_train nb_total {train_nb_total} nb_correct {train_nb_correct} accuracy {(100.0*train_nb_correct)/train_nb_total:.02f}%"
620 test_nb_total, test_nb_correct = compute_nb_correct(
621 self.test_input[:1000], self.test_prior_visits[:1000]
625 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}%"
631 ######################################################################
647 fraction_values_for_train=None,
648 device=torch.device("cpu"),
650 self.batch_size = batch_size
651 self.nb_steps = nb_steps
652 self.nb_stacks = nb_stacks
653 self.nb_digits = nb_digits
656 if fraction_values_for_train is None:
657 values_for_train = None
658 values_for_test = None
660 all = torch.randperm(10**nb_digits)
661 nb_for_train = int(all.size(0) * fraction_values_for_train)
662 values_for_train = all[:nb_for_train]
663 values_for_test = all[nb_for_train:]
665 self.train_input, self.train_stack_counts = stack.generate_sequences(
674 self.test_input, self.test_stack_counts = stack.generate_sequences(
683 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
684 counts = self.test_stack_counts.flatten()[i.flatten()]
685 counts = F.one_hot(counts).sum(0)
686 logger(f"test_pop_stack_counts {counts}")
688 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
690 def batches(self, split="train", nb_to_use=-1, desc=None):
691 assert split in {"train", "test"}
692 input = self.train_input if split == "train" else self.test_input
694 input = input[:nb_to_use]
696 desc = f"epoch-{split}"
697 for batch in tqdm.tqdm(
698 input.split(self.batch_size), dynamic_ncols=True, desc=desc
702 def vocabulary_size(self):
706 self, n_epoch, model, result_dir, logger, deterministic_synthesis
708 with torch.autograd.no_grad():
712 def compute_nb_correct(input):
713 result = input.clone()
714 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
715 ar_mask = (result != input).long()
716 masked_inplace_autoregression(
721 deterministic_synthesis,
725 errors = ((result != input).long() * ar_mask).reshape(
726 -1, 1 + self.nb_digits
728 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
730 nb_total = ar_mask.max(1).values.sum()
731 nb_correct = nb_total - errors.max(1).values.sum()
733 return nb_total, nb_correct
735 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
738 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}%"
741 ##############################################################
742 # Log a few generated sequences
743 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
744 result = input.clone()
745 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
746 ar_mask = (result != input).long()
747 for n in range(result.size(0)):
749 f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
751 masked_inplace_autoregression(
756 deterministic_synthesis,
759 for n in range(result.size(0)):
761 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
763 ##############################################################
768 ######################################################################
782 device=torch.device("cpu"),
784 self.batch_size = batch_size
787 train_sequences = expr.generate_sequences(
789 nb_variables=nb_variables,
790 length=sequence_length,
791 # length=2 * sequence_length,
792 # randomize_length=True,
794 test_sequences = expr.generate_sequences(
796 nb_variables=nb_variables,
797 length=sequence_length,
802 for n, c in enumerate(
803 set("#" + "".join(train_sequences + test_sequences))
807 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
809 self.filler, self.space = self.char2id["#"], self.char2id[" "]
811 len_max = max([len(x) for x in train_sequences])
812 self.train_input = torch.cat(
816 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
817 for s in train_sequences
824 len_max = max([len(x) for x in test_sequences])
825 self.test_input = torch.cat(
829 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
830 for s in test_sequences
837 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
839 def batches(self, split="train", nb_to_use=-1, desc=None):
840 assert split in {"train", "test"}
841 input = self.train_input if split == "train" else self.test_input
843 input = input[:nb_to_use]
845 desc = f"epoch-{split}"
846 for batch in tqdm.tqdm(
847 input.split(self.batch_size), dynamic_ncols=True, desc=desc
850 last = (batch != self.filler).max(0).values.nonzero().max() + 3
851 batch = batch[:, :last]
854 def vocabulary_size(self):
857 def seq2str(self, s):
858 return "".join([self.id2char[k.item()] for k in s])
861 self, n_epoch, model, result_dir, logger, deterministic_synthesis
863 with torch.autograd.no_grad():
867 def compute_nb_correct(input):
868 result = input.clone()
869 ar_mask = (result == self.space).long().cumsum(dim=1).clamp(max=1)
870 result = (1 - ar_mask) * result + ar_mask * self.filler
871 masked_inplace_autoregression(
876 deterministic_synthesis,
880 nb_total = input.size(0)
881 nb_correct = (input == result).long().min(1).values.sum()
883 #######################################################################
884 # Comput predicted vs. true variable values
886 nb_delta = torch.zeros(5, dtype=torch.int64)
889 values_input = expr.extract_results([self.seq2str(s) for s in input])
890 values_result = expr.extract_results([self.seq2str(s) for s in result])
892 for i, r in zip(values_input, values_result):
893 for n, vi in i.items():
895 if vr is None or vr < 0:
899 if d >= nb_delta.size(0):
904 ######################################################################
906 return nb_total, nb_correct, nb_delta, nb_missed
913 ) = compute_nb_correct(self.test_input[:1000])
916 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}%"
919 nb_total = test_nb_delta.sum() + test_nb_missed
920 for d in range(test_nb_delta.size(0)):
922 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
925 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
928 ##############################################################
929 # Log a few generated sequences
930 input = self.test_input[:10]
931 result = input.clone()
932 ar_mask = (result == self.space).long().cumsum(dim=1).clamp(max=1)
933 result = (1 - ar_mask) * result + ar_mask * self.filler
934 for n in range(result.size(0)):
935 logger(f"test_before {self.seq2str(result[n])}")
936 masked_inplace_autoregression(
941 deterministic_synthesis,
944 correct = (1 - ar_mask) * self.space + ar_mask * input
945 for n in range(result.size(0)):
946 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
947 logger(f"test_after {self.seq2str(result[n])} {comment}")
948 logger(f"correct {self.seq2str(correct[n])}")
949 ##############################################################
954 ######################################################################