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
17 # from graph import save_attention_image
18 save_attention_image = None
20 ######################################################################
23 def masked_inplace_autoregression(
28 deterministic_synthesis,
29 forbidden_tokens=None,
30 progress_bar_desc="autoregression",
31 device=torch.device("cpu"),
33 assert input.size() == ar_mask.size()
35 batches = zip(input.split(batch_size), ar_mask.split(batch_size))
37 if progress_bar_desc is not None:
41 desc=progress_bar_desc,
42 total=(input.size(0) + batch_size - 1) // batch_size,
45 with torch.autograd.no_grad():
49 for input, ar_mask in batches:
50 model.masked_inplace_autoregression(
51 input, ar_mask, forbidden_tokens, deterministic_synthesis
57 ######################################################################
61 def batches(self, split="train", desc=None):
64 def vocabulary_size(self):
68 self, n_epoch, model, result_dir, logger, deterministic_synthesis
86 device=torch.device("cpu"),
91 self.batch_size = batch_size
93 self.problem = problem
95 self.train_input, self.train_ar_mask = self.problem.generate_sequences(
98 self.test_input, self.test_ar_mask = self.problem.generate_sequences(
102 self.train_input, self.train_ar_mask = self.train_input.to(
104 ), self.train_ar_mask.to(device)
105 self.test_input, self.test_ar_mask = self.test_input.to(
107 ), self.test_ar_mask.to(device)
109 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
111 # A bit of paranoia never hurts
112 assert self.nb_codes <= max_nb_codes
113 assert self.train_input.min() >= 0
114 assert self.test_input.min() >= 0
115 assert tuple(x.item() for x in self.train_ar_mask.unique()) in {
120 assert tuple(x.item() for x in self.test_ar_mask.unique()) in {
126 if logger is not None:
127 for s, a in zip(self.train_input[:100], self.train_ar_mask[:100]):
128 logger(f"train_sequences {self.problem.seq2str(s)}")
129 a = "".join(["01"[x.item()] for x in a])
132 def batches(self, split="train", nb_to_use=-1, desc=None):
133 assert split in {"train", "test"}
134 input = self.train_input if split == "train" else self.test_input
136 input = input[:nb_to_use]
138 desc = f"epoch-{split}"
139 for batch in tqdm.tqdm(
140 input.split(self.batch_size), dynamic_ncols=True, desc=desc
144 def vocabulary_size(self):
148 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
150 def compute_accuracy(input, ar_mask, logger=None):
151 input, ar_mask = input[:nmax], ar_mask[:nmax]
152 result = input.clone() * (1 - ar_mask)
154 masked_inplace_autoregression(
159 deterministic_synthesis,
160 progress_bar_desc=None,
164 log_ground_truth = ar_mask.min() == 0
166 if logger is not None:
167 for sp, st in zip(result[:10], input[:10]):
169 f"test_sequences {n_epoch} prediction {self.problem.seq2str(sp)}"
173 f" {n_epoch} ground truth {self.problem.seq2str(st)}"
176 nb_total, nb_correct = self.problem.compute_nb_correct(
177 input, ar_mask, result
180 # nb_total = ar_mask.sum().item()
181 # nb_correct = ((result == input).long() * ar_mask).sum().item()
183 return nb_total, nb_correct
185 train_nb_total, train_nb_correct = compute_accuracy(
186 self.train_input, self.train_ar_mask
190 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}%"
193 test_nb_total, test_nb_correct = compute_accuracy(
194 self.test_input, self.test_ar_mask, logger
198 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}%"
201 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
203 if save_attention_image is not None:
205 ns = torch.randint(self.test_input.size(0), (1,)).item()
206 input = self.test_input[ns : ns + 1].clone()
208 with torch.autograd.no_grad():
211 # model.record_attention(True)
212 model(BracketedSequence(input))
214 # ram = model.retrieve_attention()
215 # model.record_attention(False)
217 # tokens_output = [c for c in self.problem.seq2str(input[0])]
218 # tokens_input = ["n/a"] + tokens_output[:-1]
219 # for n_head in range(ram[0].size(1)):
220 # filename = os.path.join(
221 # result_dir, f"sandbox_attention_{k}_h{n_head}.pdf"
223 # attention_matrices = [m[0, n_head] for m in ram]
224 # save_attention_image(
228 # attention_matrices,
230 ##min_total_attention=0.9,
234 # logger(f"wrote {filename}")
237 ######################################################################
242 class PicoCLVR(Task):
243 # Make a tensor from a list of strings
244 def tensorize(self, descr):
245 token_descr = [s.strip().split(" ") for s in descr]
246 l = max([len(s) for s in token_descr])
247 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
248 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
249 return torch.tensor(id_descr, device=self.device)
251 # Make a list of strings from a tensor
252 def detensorize(self, x):
253 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
255 # trim all the tensors in the tuple z to remove as much token from
256 # left and right in the first tensor. If z is a tuple, all its
257 # elements are trimed according to the triming for the first
258 def trim(self, z, token="<nul>"):
259 n = self.token2id[token]
262 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
263 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
264 return tuple([t[:, a:b] for t in z])
266 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
267 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
270 ######################
281 device=torch.device("cpu"),
287 def generate_descr(nb, cache_suffix, pruner):
288 return picoclvr.generate(
298 self.batch_size = batch_size
300 self.pruner_train = pruner_train
301 self.pruner_eval = pruner_eval
303 if logger is not None:
305 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
308 self.train_descr = generate_descr(
309 nb_train_samples, "train", pruner=self.pruner_train
311 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
313 # Build the tokenizer
314 tokens = {"<nul>", "<img>"}
315 for d in [self.train_descr, self.test_descr]:
317 for t in s.strip().split(" "):
319 # make this set a sorted list to get the same tensors given
321 tokens = list(tokens)
323 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
324 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
325 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
327 # Tokenize the train and test sets
328 self.train_input = self.tensorize(self.train_descr)
329 self.test_input = self.tensorize(self.test_descr)
331 def batches(self, split="train", desc=None):
332 assert split in {"train", "test"}
333 input = self.train_input if split == "train" else self.test_input
334 for batch in tqdm.tqdm(
335 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
337 yield self.trim(batch)
339 def vocabulary_size(self):
340 return len(self.token2id)
342 def compute_missing_properties(
343 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
345 acc_nb_requested_properties = []
346 acc_nb_missing_properties = []
349 for input in tqdm.tqdm(
350 self.test_input.split(self.batch_size),
352 desc=f"test-properties",
354 result = input.clone()
355 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
356 result = (1 - ar_mask) * result + ar_mask * self.t_nul
357 masked_inplace_autoregression(
362 deterministic_synthesis,
363 progress_bar_desc=None,
367 result_descr = self.detensorize(result)
368 np = picoclvr.nb_properties(
374 nb_requested_properties, _, nb_missing_properties = zip(*np)
375 acc_nb_requested_properties += nb_requested_properties
376 acc_nb_missing_properties += nb_missing_properties
377 acc_nb_results += len(result_descr)
379 nb_requested_properties = sum(acc_nb_requested_properties)
380 nb_missing_properties = sum(acc_nb_missing_properties)
382 prefix = "" if pruner is None else "pruned_"
383 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
385 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
388 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
392 f"main_test_accuracy {n_epoch} {1-nb_missing_properties/nb_requested_properties}"
395 ######################################################################
398 self, n_epoch, model, result_dir, logger, deterministic_synthesis
400 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
402 if self.pruner_eval is not None:
403 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
405 nb_tokens_to_generate = self.height * self.width + 3
410 for primer_descr in [
411 "red above green <sep> green top <sep> blue right of red",
412 "there is red <sep> there is yellow <sep> there is blue",
413 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
414 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
416 primer += [primer_descr + " <img>"] * nb_per_primer
418 result = self.tensorize(primer)
419 fill = result.new_full(
420 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
422 result = torch.cat((result, fill), 1)
423 ar_mask = (result == self.t_nul).long()
424 masked_inplace_autoregression(
429 deterministic_synthesis,
432 result_descr = self.detensorize(result)
434 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
436 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
437 acc_nb_results = len(result_descr)
439 nb_requested_properties = sum(acc_nb_requested_properties)
440 nb_missing_properties = sum(acc_nb_missing_properties)
443 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
445 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
448 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
451 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
455 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
459 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
465 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
466 torchvision.utils.save_image(
467 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
469 logger(f"wrote {image_name}")
472 ######################################################################
477 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
481 self.nb_train_samples = (nb_train_samples,)
482 self.nb_test_samples = (nb_test_samples,)
483 self.batch_size = batch_size
485 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
486 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
487 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
488 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
490 def batches(self, split="train", nb_to_use=-1, desc=None):
491 assert split in {"train", "test"}
492 input = self.train_input if split == "train" else self.test_input
494 input = input[:nb_to_use]
496 desc = f"epoch-{split}"
497 for batch in tqdm.tqdm(
498 input.split(self.batch_size), dynamic_ncols=True, desc=desc
502 def vocabulary_size(self):
506 self, n_epoch, model, result_dir, logger, deterministic_synthesis
508 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
509 ar_mask = torch.full_like(results, 1)
510 masked_inplace_autoregression(
515 deterministic_synthesis,
518 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
519 torchvision.utils.save_image(
520 1 - results.reshape(-1, 1, 28, 28) / 255.0,
525 logger(f"wrote {image_name}")
528 ######################################################################
534 def map2seq(self, *m):
535 return torch.cat([x.flatten(1) for x in m], 1)
537 def seq2map(self, s):
538 s = s.reshape(s.size(0), -1, self.height, self.width)
539 return (s[:, k] for k in range(s.size(1)))
549 device=torch.device("cpu"),
553 self.batch_size = batch_size
558 train_mazes, train_paths, _ = maze.create_maze_data(
563 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
565 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
567 test_mazes, test_paths, _ = maze.create_maze_data(
572 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
574 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
576 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
578 def batches(self, split="train", nb_to_use=-1, desc=None):
579 assert split in {"train", "test"}
580 input = self.train_input if split == "train" else self.test_input
582 input = input[:nb_to_use]
584 desc = f"epoch-{split}"
585 for batch in tqdm.tqdm(
586 input.split(self.batch_size), dynamic_ncols=True, desc=desc
590 def vocabulary_size(self):
594 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
596 nb_total, nb_correct = 0, 0
598 self.width * self.height,
599 self.width * self.height,
604 for input in self.batches(split, nb_to_use):
605 result = input.clone()
606 ar_mask = result.new_zeros(result.size())
607 ar_mask[:, self.height * self.width :] = 1
608 result *= 1 - ar_mask
609 masked_inplace_autoregression(
614 deterministic_synthesis,
615 progress_bar_desc=None,
618 mazes, paths = self.seq2map(result)
619 path_correctness = maze.path_correctness(mazes, paths)
620 nb_correct += path_correctness.long().sum()
621 nb_total += mazes.size(0)
623 optimal_path_lengths = (
624 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
626 predicted_path_lengths = (
627 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
629 optimal_path_lengths = optimal_path_lengths[path_correctness]
630 predicted_path_lengths = predicted_path_lengths[path_correctness]
631 count[optimal_path_lengths, predicted_path_lengths] += 1
637 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
640 return nb_total, nb_correct, count
643 self, n_epoch, model, result_dir, logger, deterministic_synthesis
645 train_nb_total, train_nb_correct, count = self.compute_error(
649 deterministic_synthesis=deterministic_synthesis,
652 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}%"
655 test_nb_total, test_nb_correct, count = self.compute_error(
659 deterministic_synthesis=deterministic_synthesis,
662 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}%"
665 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
667 if count is not None:
668 proportion_optimal = count.diagonal().sum().float() / count.sum()
669 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
671 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
673 for i in range(count.size(0)):
674 for j in range(count.size(1)):
675 eol = " " if j < count.size(1) - 1 else "\n"
676 f.write(f"{count[i,j]}{eol}")
678 input = self.test_input[:48]
679 result = input.clone()
680 ar_mask = result.new_zeros(result.size())
681 ar_mask[:, self.height * self.width :] = 1
682 result *= 1 - ar_mask
683 masked_inplace_autoregression(
688 deterministic_synthesis,
692 mazes, paths = self.seq2map(input)
693 _, predicted_paths = self.seq2map(result)
695 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
700 predicted_paths=predicted_paths,
701 path_correct=maze.path_correctness(mazes, predicted_paths),
702 path_optimal=maze.path_optimality(paths, predicted_paths),
704 logger(f"wrote {filename}")
707 ######################################################################
724 device=torch.device("cpu"),
728 self.batch_size = batch_size
732 self.prompt_length = prompt_length
734 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
743 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
753 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
755 def batches(self, split="train", nb_to_use=-1, desc=None):
756 assert split in {"train", "test"}
757 input = self.train_input if split == "train" else self.test_input
759 input = input[:nb_to_use]
761 desc = f"epoch-{split}"
762 for batch in tqdm.tqdm(
763 input.split(self.batch_size), dynamic_ncols=True, desc=desc
767 def vocabulary_size(self):
771 self, n_epoch, model, result_dir, logger, deterministic_synthesis
773 def compute_nb_correct(input, prior_visits):
774 result = input.clone()
775 i = torch.arange(result.size(1), device=result.device)[None, :]
777 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
781 result *= 1 - ar_mask
783 masked_inplace_autoregression(
788 deterministic_synthesis,
792 nb_total = ((prior_visits > 0) * ar_mask).sum()
794 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
796 return nb_total, nb_correct
798 test_nb_total, test_nb_correct = compute_nb_correct(
799 self.test_input[:1000], self.test_prior_visits[:1000]
803 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}%"
806 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
809 ######################################################################
825 fraction_values_for_train=None,
826 device=torch.device("cpu"),
830 self.batch_size = batch_size
831 self.nb_steps = nb_steps
832 self.nb_stacks = nb_stacks
833 self.nb_digits = nb_digits
836 if fraction_values_for_train is None:
837 values_for_train = None
838 values_for_test = None
840 all = torch.randperm(10**nb_digits)
841 nb_for_train = int(all.size(0) * fraction_values_for_train)
842 values_for_train = all[:nb_for_train]
843 values_for_test = all[nb_for_train:]
845 self.train_input, self.train_stack_counts = stack.generate_sequences(
854 self.test_input, self.test_stack_counts = stack.generate_sequences(
863 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
864 counts = self.test_stack_counts.flatten()[i.flatten()]
865 counts = F.one_hot(counts).sum(0)
866 logger(f"test_pop_stack_counts {counts}")
868 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
870 def batches(self, split="train", nb_to_use=-1, desc=None):
871 assert split in {"train", "test"}
872 input = self.train_input if split == "train" else self.test_input
874 input = input[:nb_to_use]
876 desc = f"epoch-{split}"
877 for batch in tqdm.tqdm(
878 input.split(self.batch_size), dynamic_ncols=True, desc=desc
882 def vocabulary_size(self):
886 self, n_epoch, model, result_dir, logger, deterministic_synthesis
888 def compute_nb_correct(input):
889 result = input.clone()
890 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
891 ar_mask = (result != input).long()
892 masked_inplace_autoregression(
897 deterministic_synthesis,
901 errors = ((result != input).long() * ar_mask).reshape(
902 -1, 1 + self.nb_digits
904 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
906 nb_total = ar_mask.max(1).values.sum()
907 nb_correct = nb_total - errors.max(1).values.sum()
909 return nb_total, nb_correct
911 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
914 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}%"
917 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
919 ##############################################################
920 # Log a few generated sequences
921 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
922 result = input.clone()
923 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
924 ar_mask = (result != input).long()
926 # for n in range(result.size(0)):
928 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
931 masked_inplace_autoregression(
936 deterministic_synthesis,
940 for n in range(result.size(0)):
942 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
944 ##############################################################
947 ######################################################################
953 def tensorize(self, sequences):
954 len_max = max([len(x) for x in sequences])
960 self.token2id[str(c)]
961 for c in s + ["<nul>"] * (len_max - len(s))
970 def seq2str(self, seq):
971 return " ".join([self.id2token[i] for i in seq])
978 nb_starting_values=3,
984 device=torch.device("cpu"),
988 self.batch_size = batch_size
990 self.no_prog = no_prog
994 nb_starting_values=nb_starting_values,
995 nb_result_values_max=4 * nb_starting_values,
1000 for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
1005 nb_starting_values=nb_starting_values,
1006 nb_result_values_max=4 * nb_starting_values,
1007 max_input=max_input,
1011 for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
1015 set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
1017 val_max = max([x if type(x) is int else 0 for x in symbols])
1018 symbols = list(filter(lambda x: type(x) is str, symbols))
1020 symbols += [str(n) for n in range(val_max + 1)]
1021 self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
1022 self.id2token = dict([(n, c) for c, n in self.token2id.items()])
1024 self.t_nul = self.token2id["<nul>"]
1025 self.t_input = self.token2id["<in>"]
1026 self.t_output = self.token2id["<out>"]
1027 self.t_prog = self.token2id["<prg>"]
1028 self.t_end = self.token2id["<end>"]
1030 self.train_input = self.tensorize(train_sequences)
1031 self.test_input = self.tensorize(test_sequences)
1034 # Excise the program from every train and test example
1035 k = torch.arange(self.train_input.size(1), device=self.train_input.device)[
1039 ((self.train_input == self.t_prog).long() * k)
1040 .max(1, keepdim=True)
1043 self.train_input = (
1044 self.train_input * (k <= p).long()
1045 + self.t_end * (k == p + 1).long()
1046 + self.t_nul * (k > p + 1).long()
1048 k = torch.arange(self.test_input.size(1), device=self.test_input.device)[
1052 ((self.test_input == self.t_prog).long() * k)
1053 .max(1, keepdim=True)
1057 self.test_input * (k <= p).long()
1058 + self.t_end * (k == p + 1).long()
1059 + self.t_nul * (k > p + 1).long()
1062 if logger is not None:
1063 logger(f"value_max {val_max}")
1064 for x in self.train_input[:25]:
1065 end = (x != self.t_nul).nonzero().max().item() + 1
1066 seq = [self.id2token[i.item()] for i in x[:end]]
1068 logger(f"example_seq {s}")
1070 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1072 def batches(self, split="train", nb_to_use=-1, desc=None):
1073 assert split in {"train", "test"}
1074 input = self.train_input if split == "train" else self.test_input
1076 input = input[:nb_to_use]
1078 desc = f"epoch-{split}"
1079 for batch in tqdm.tqdm(
1080 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1082 last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1083 batch = batch[:, :last].to(self.device)
1086 def vocabulary_size(self):
1087 return self.nb_codes
1089 def produce_results(
1090 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1092 # --------------------------------------------------------------------
1093 def compute_nb_errors_prog(input, nb_to_log=0):
1094 result = input.clone()
1095 s = (result == self.t_prog).long()
1096 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1097 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1099 masked_inplace_autoregression(
1104 deterministic_synthesis,
1108 sum_nb_total, sum_nb_errors = 0, 0
1109 for one_input, one_result in zip(input, result):
1110 seq = [self.id2token[i.item()] for i in one_result]
1111 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1113 sum_nb_errors += 0 if nb_errors == 0 else 1
1115 gt_seq = [self.id2token[i.item()] for i in one_input]
1116 _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1117 gt_prog = " ".join([str(x) for x in gt_prog])
1118 prog = " ".join([str(x) for x in prog])
1119 comment = "*" if nb_errors == 0 else "-"
1120 logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1121 for start_stack, target_stack, result_stack, correct in stacks:
1122 comment = "*" if correct else "-"
1123 start_stack = " ".join([str(x) for x in start_stack])
1124 target_stack = " ".join([str(x) for x in target_stack])
1125 result_stack = " ".join([str(x) for x in result_stack])
1127 f" {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1131 return sum_nb_total, sum_nb_errors
1133 # --------------------------------------------------------------------
1134 def compute_nb_errors_output(input, nb_to_log=0):
1135 result = input.clone()
1136 k = torch.arange(result.size(1), device=result.device)[None, :]
1138 ((result == self.t_output) * k).max(dim=1, keepdim=True).values
1141 ((result == self.t_prog) * k).max(dim=1, keepdim=True).values
1143 ar_mask = (k > last_output_idx).long() * (k < first_prog_idx).long()
1144 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1146 masked_inplace_autoregression(
1151 deterministic_synthesis,
1155 sum_nb_total, sum_nb_errors = 0, 0
1156 for one_input, one_result, i, j in zip(
1157 input, result, last_output_idx, first_prog_idx
1159 seq = [self.id2token[i.item()] for i in one_result]
1161 correct = (one_input - one_result).abs().max() == 0
1162 sum_nb_errors += 0 if correct else 1
1165 self.id2token[i.item()] for i in one_result[i : j + 1]
1168 self.id2token[i.item()] for i in one_input[i : j + 1]
1170 comment = "*" if correct else "-"
1171 result_stack = " ".join([str(x) for x in result_stack])
1172 target_stack = " ".join([str(x) for x in target_stack])
1174 f"output_test {comment} [{target_stack}] PREDICTED [{result_stack}]"
1178 return sum_nb_total, sum_nb_errors
1180 # --------------------------------------------------------------------
1182 if not self.no_prog:
1183 test_nb_total, test_nb_errors = compute_nb_errors_prog(
1184 self.test_input[:1000].to(self.device), nb_to_log=10
1188 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}%"
1191 logger(f"main_test_accuracy {n_epoch} {1-test_nb_errors/test_nb_total}")
1193 test_nb_total, test_nb_errors = compute_nb_errors_output(
1194 self.test_input[:1000].to(self.device), nb_to_log=10
1198 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}%"
1201 if save_attention_image is not None:
1202 ns = torch.randint(self.test_input.size(0), (1,)).item()
1203 input = self.test_input[ns : ns + 1].clone()
1204 last = (input != self.t_nul).max(0).values.nonzero().max() + 3
1205 input = input[:, :last].to(self.device)
1207 with torch.autograd.no_grad():
1210 model.record_attention(True)
1211 model(BracketedSequence(input))
1213 ram = model.retrieve_attention()
1214 model.record_attention(False)
1216 tokens_output = [self.id2token[i.item()] for i in input[0]]
1217 tokens_input = ["n/a"] + tokens_output[:-1]
1218 for n_head in range(ram[0].size(1)):
1219 filename = os.path.join(
1220 result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
1222 attention_matrices = [m[0, n_head] for m in ram]
1223 save_attention_image(
1229 # min_total_attention=0.9,
1233 logger(f"wrote {filename}")
1236 ######################################################################
1243 def tensorize(self, sequences):
1244 len_max = max([len(x) for x in sequences])
1249 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1266 device=torch.device("cpu"),
1270 self.batch_size = batch_size
1271 self.device = device
1273 train_sequences = expr.generate_sequences(
1275 nb_variables=nb_variables,
1276 length=sequence_length,
1277 operand_max=operand_max,
1278 result_max=result_max,
1281 test_sequences = expr.generate_sequences(
1283 nb_variables=nb_variables,
1284 length=sequence_length,
1285 operand_max=operand_max,
1286 result_max=result_max,
1289 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1292 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1293 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1295 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1297 self.train_input = self.tensorize(train_sequences)
1298 self.test_input = self.tensorize(test_sequences)
1300 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1302 def batches(self, split="train", nb_to_use=-1, desc=None):
1303 assert split in {"train", "test"}
1304 input = self.train_input if split == "train" else self.test_input
1306 input = input[:nb_to_use]
1308 desc = f"epoch-{split}"
1309 for batch in tqdm.tqdm(
1310 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1312 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1313 batch = batch[:, :last]
1316 def vocabulary_size(self):
1317 return self.nb_codes
1319 def seq2str(self, s):
1320 return "".join([self.id2char[k.item()] for k in s])
1322 def produce_results(
1328 deterministic_synthesis,
1331 def compute_nb_correct(input):
1332 result = input.clone()
1333 s = (result == self.space).long()
1334 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1335 result = (1 - ar_mask) * result + ar_mask * self.filler
1336 masked_inplace_autoregression(
1341 deterministic_synthesis,
1345 nb_total = input.size(0)
1346 nb_correct = (input == result).long().min(1).values.sum()
1348 #######################################################################
1349 # Comput predicted vs. true variable values
1351 nb_delta = torch.zeros(5, dtype=torch.int64)
1354 values_input = expr.extract_results([self.seq2str(s) for s in input])
1355 values_result = expr.extract_results([self.seq2str(s) for s in result])
1357 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1359 with open(filename, "w") as f:
1360 for i, r in zip(values_input, values_result):
1361 for n, vi in i.items():
1363 f.write(f"{vi} {-1 if vr is None else vr}\n")
1365 if vr is None or vr < 0:
1369 if d >= nb_delta.size(0):
1374 ######################################################################
1376 return nb_total, nb_correct, nb_delta, nb_missed
1383 ) = compute_nb_correct(self.test_input[:10000])
1386 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}%"
1389 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
1391 nb_total = test_nb_delta.sum() + test_nb_missed
1392 for d in range(test_nb_delta.size(0)):
1394 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1397 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1400 ##############################################################
1401 # Log a few generated sequences
1402 if input_file is None:
1403 input = self.test_input[:10]
1405 with open(input_file, "r") as f:
1406 sequences = [e.strip() for e in f.readlines()]
1407 sequences = [s + " " + "#" * 50 for s in sequences]
1408 input = self.tensorize(sequences)
1410 result = input.clone()
1411 s = (result == self.space).long()
1412 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1413 result = (1 - ar_mask) * result + ar_mask * self.filler
1415 for n in range(result.size(0)):
1416 logger(f"test_before {self.seq2str(result[n])}")
1418 masked_inplace_autoregression(
1423 deterministic_synthesis,
1427 correct = (1 - ar_mask) * self.space + ar_mask * input
1428 for n in range(result.size(0)):
1429 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1430 logger(f"test_after {self.seq2str(result[n])} {comment}")
1431 logger(f"truth {self.seq2str(correct[n])}")
1432 ##############################################################
1435 ######################################################################
1441 # Make a tensor from a list of strings
1442 def str2tensor(self, descr):
1443 token_descr = [s.strip().split(" ") for s in descr]
1444 l = max([len(s) for s in token_descr])
1445 token_descr = [s + ["#"] * (l - len(s)) for s in token_descr]
1446 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
1447 return torch.tensor(id_descr, device=self.device)
1449 # Make a list of strings from a tensor
1450 def tensor2str(self, x):
1451 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
1453 # trim all the tensors in the tuple z to remove as much token from
1454 # left and right in the first tensor. If z is a tuple, all its
1455 # elements are trimed according to the triming for the first
1456 def trim(self, z, token="#"):
1457 n = self.token2id[token]
1458 if type(z) == tuple:
1460 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
1461 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
1462 return tuple([t[:, a:b] for t in z])
1464 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
1465 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
1468 ######################
1479 device=torch.device("cpu"),
1483 self.device = device
1484 self.batch_size = batch_size
1485 self.grid_factory = grid.GridFactory(
1486 size=size, nb_shapes=nb_shapes, nb_colors=nb_colors
1489 if logger is not None:
1491 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
1494 self.train_descr = self.grid_factory.generate_samples(
1495 nb_train_samples, lambda r: tqdm.tqdm(r)
1497 self.test_descr = self.grid_factory.generate_samples(
1498 nb_test_samples, lambda r: tqdm.tqdm(r)
1501 # Build the tokenizer
1503 for d in [self.train_descr, self.test_descr]:
1505 for t in s.strip().split(" "):
1507 # make this set a sorted list to get the same tensors given
1509 tokens = list(tokens)
1511 tokens = ["#"] + tokens
1512 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
1513 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
1514 self.t_nul = self.token2id["#"]
1515 self.t_true = self.token2id["true"]
1516 self.t_false = self.token2id["false"]
1518 # Tokenize the train and test sets
1519 self.train_input = self.str2tensor(self.train_descr)
1520 self.test_input = self.str2tensor(self.test_descr)
1522 def batches(self, split="train", desc=None):
1523 assert split in {"train", "test"}
1524 input = self.train_input if split == "train" else self.test_input
1526 desc = f"epoch-{split}"
1527 for batch in tqdm.tqdm(
1528 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1530 yield self.trim(batch)
1532 def vocabulary_size(self):
1533 return len(self.token2id)
1535 def produce_results(
1536 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1538 correct = self.test_input[:1000]
1539 result = correct.clone()
1540 ar_mask = torch.logical_or(result == self.t_true, result == self.t_false).long()
1541 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
1543 logger(f"----------------------------------------------------------")
1545 for e in self.tensor2str(result[:10]):
1546 logger(f"test_before {e}")
1548 masked_inplace_autoregression(
1553 deterministic_synthesis,
1557 logger(f"----------------------------------------------------------")
1559 for e in self.tensor2str(result[:10]):
1560 logger(f"test_after {e}")
1562 logger(f"----------------------------------------------------------")
1564 nb_total = ar_mask.sum().item()
1565 nb_correct = ((correct == result).long() * ar_mask).sum().item()
1567 logger(f"test_performance {n_epoch} {nb_total=} {nb_correct=}")
1568 logger(f"main_test_accuracy {n_epoch} {nb_correct / nb_total}")
1571 ######################################################################
1577 ######################
1586 device=torch.device("cpu"),
1590 self.device = device
1591 self.batch_size = batch_size
1592 self.nb_samples_per_mlp = 256
1594 if logger is not None:
1596 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
1599 seq, q_test_set, test_error = qmlp.generate_sequence_and_test_set(
1600 nb_mlps=nb_train_samples + nb_test_samples,
1601 nb_samples=self.nb_samples_per_mlp,
1605 nb_mlps_per_batch=1024,
1608 self.train_input = seq[:nb_train_samples]
1609 self.train_q_test_set = q_test_set[:nb_train_samples]
1610 self.train_ref_test_errors = test_error[:nb_train_samples]
1611 self.test_input = seq[nb_train_samples:]
1612 self.test_q_test_set = q_test_set[nb_train_samples:]
1613 self.test_ref_test_errors = test_error[nb_train_samples:]
1615 filename = os.path.join(result_dir, f"train_errors_ref.dat")
1616 with open(filename, "w") as f:
1617 for e in self.train_ref_test_errors:
1620 filename = os.path.join(result_dir, f"test_errors_ref.dat")
1621 with open(filename, "w") as f:
1622 for e in self.test_ref_test_errors:
1625 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1627 def batches(self, split="train", desc=None):
1628 assert split in {"train", "test"}
1629 input = self.train_input if split == "train" else self.test_input
1631 desc = f"epoch-{split}"
1632 for batch in tqdm.tqdm(
1633 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1637 def vocabulary_size(self):
1638 return self.nb_codes
1640 def produce_results(
1641 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1643 correct = self.test_input[:1000]
1644 result = correct.clone()
1646 torch.arange(result.size(1), device=result.device)
1647 > self.nb_samples_per_mlp * 3 + 1
1649 ar_mask = ar_mask.expand_as(result)
1650 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
1652 masked_inplace_autoregression(
1657 deterministic_synthesis,
1661 q_train_set = result[:, : self.nb_samples_per_mlp * 3]
1662 q_params = result[:, self.nb_samples_per_mlp * 3 + 1 :]
1663 error_test = qmlp.evaluate_q_params(q_params, self.test_q_test_set)
1665 filename = os.path.join(result_dir, f"test_errors_{n_epoch:04d}.dat")
1666 with open(filename, "w") as f:
1667 for e in error_test:
1671 ######################################################################