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"):
64 def vocabulary_size(self):
68 self, n_epoch, model, result_dir, logger, deterministic_synthesis
73 class TaskFromFile(Task):
74 def tensorize(self, pairs):
75 len_max = max([len(x[0]) for x in pairs])
81 [self.char2id[c] for c in s[0] + "#" * (len_max - len(s[0]))]
89 pred_mask = torch.cat(
93 [int(c) for c in s[1] + "0" * (len_max - len(s[1]))]
101 return input, pred_mask
103 # trim all the tensors in the tuple z to remove as much token from
104 # left and right in the first tensor. If z is a tuple, all its
105 # elements are trimed according to the triming for the first
106 def trim(self, z, token="#"):
107 n = self.char2id[token]
110 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
111 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
112 return tuple([t[:, a:b] for t in z])
114 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
115 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
124 device=torch.device("cpu"),
126 self.batch_size = batch_size
130 with open(filename, "r") as f:
131 for _ in range(nb_train_samples + nb_test_samples):
132 sequence = f.readline().strip()
133 pred_mask = f.readline().strip()
134 assert len(sequence) == len(pred_mask)
135 assert set(pred_mask) == {"0", "1", "2"}, f"{set(pred_mask)}"
136 pairs.append((sequence, pred_mask))
138 symbols = ["#"] + list(set("".join([x[0] for x in pairs])) - set(["#"]))
139 print("SANITY", symbols)
140 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
141 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
145 self.train_input, self.train_pred_masks = self.tensorize(
146 pairs[:nb_train_samples]
148 self.test_input, self.test_pred_masks = self.tensorize(pairs[nb_train_samples:])
150 def batches(self, split="train", nb_to_use=-1, desc=None):
151 assert split in {"train", "test"}
152 input = self.train_input if split == "train" else self.test_input
154 input = input[:nb_to_use]
156 desc = f"epoch-{split}"
157 for batch in tqdm.tqdm(
158 input.split(self.batch_size), dynamic_ncols=True, desc=desc
160 yield self.trim(batch).to(self.device)
162 def vocabulary_size(self):
163 return len(self.char2id)
165 def tensor2str(self, t):
167 return ["".join([self.id2char[x.item()] for x in s]) for s in t]
170 self, n_epoch, model, result_dir, logger, deterministic_synthesis
172 correct = self.trim(self.test_input[:1000]).to(self.device)
173 result = correct.clone()
174 pred_mask = self.test_pred_masks[:1000, : result.size(1)].to(self.device)
175 ar_mask = (pred_mask > 0).long()
176 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
178 logger(f"----------------------------------------------------------")
180 for e in self.tensor2str(result[:10]):
181 logger(f"test_before {e}")
183 masked_inplace_autoregression(
188 deterministic_synthesis,
192 logger(f"----------------------------------------------------------")
194 for e, c in zip(self.tensor2str(result[:10]), self.tensor2str(correct[:10])):
195 logger(f"test_after {e}")
196 logger(f"correct {c}")
198 logger(f"----------------------------------------------------------")
200 err_mask = (pred_mask == 2).long()
201 nb_total = err_mask.sum().item()
202 nb_correct = ((correct == result).long() * err_mask).sum().item()
204 logger(f"test_performance {n_epoch} {nb_total=} {nb_correct=}")
205 logger(f"main_test_accuracy {n_epoch} {nb_correct / nb_total}")
221 device=torch.device("cpu"),
226 self.batch_size = batch_size
228 self.problem = problem
230 self.train_input, self.train_ar_mask = self.problem.generate_sequences(
233 self.test_input, self.test_ar_mask = self.problem.generate_sequences(
237 self.train_input, self.train_ar_mask = self.train_input.to(
239 ), self.train_ar_mask.to(device)
240 self.test_input, self.test_ar_mask = self.test_input.to(
242 ), self.test_ar_mask.to(device)
244 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
246 # A bit of paranoia never hurts
247 assert self.nb_codes <= max_nb_codes
248 assert self.train_input.min() >= 0
249 assert self.test_input.min() >= 0
250 assert tuple(x.item() for x in self.train_ar_mask.unique()) in {
255 assert tuple(x.item() for x in self.test_ar_mask.unique()) in {
261 if logger is not None:
262 for s, a in zip(self.train_input[:100], self.train_ar_mask[:100]):
263 logger(f"train_sequences {self.problem.seq2str(s)}")
264 a = "".join(["01"[x.item()] for x in a])
267 def batches(self, split="train", nb_to_use=-1, desc=None):
268 assert split in {"train", "test"}
269 input = self.train_input if split == "train" else self.test_input
271 input = input[:nb_to_use]
273 desc = f"epoch-{split}"
274 for batch in tqdm.tqdm(
275 input.split(self.batch_size), dynamic_ncols=True, desc=desc
279 def vocabulary_size(self):
283 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
285 def compute_accuracy(input, ar_mask, logger=None):
286 input, ar_mask = input[:nmax], ar_mask[:nmax]
287 result = input.clone() * (1 - ar_mask)
289 masked_inplace_autoregression(
294 deterministic_synthesis,
295 progress_bar_desc=None,
299 log_ground_truth = ar_mask.min() == 0
301 if logger is not None:
302 for sp, st in zip(result[:10], input[:10]):
304 f"test_sequences {n_epoch} prediction {self.problem.seq2str(sp)}"
308 f" {n_epoch} ground truth {self.problem.seq2str(st)}"
311 nb_total, nb_correct = self.problem.compute_nb_correct(
312 input, ar_mask, result
315 # nb_total = ar_mask.sum().item()
316 # nb_correct = ((result == input).long() * ar_mask).sum().item()
318 return nb_total, nb_correct
320 train_nb_total, train_nb_correct = compute_accuracy(
321 self.train_input, self.train_ar_mask
325 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}%"
328 test_nb_total, test_nb_correct = compute_accuracy(
329 self.test_input, self.test_ar_mask, logger
333 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}%"
336 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
338 if save_attention_image is not None:
340 ns = torch.randint(self.test_input.size(0), (1,)).item()
341 input = self.test_input[ns : ns + 1].clone()
343 with torch.autograd.no_grad():
346 # model.record_attention(True)
347 model(BracketedSequence(input))
349 # ram = model.retrieve_attention()
350 # model.record_attention(False)
352 # tokens_output = [c for c in self.problem.seq2str(input[0])]
353 # tokens_input = ["n/a"] + tokens_output[:-1]
354 # for n_head in range(ram[0].size(1)):
355 # filename = os.path.join(
356 # result_dir, f"sandbox_attention_{k}_h{n_head}.pdf"
358 # attention_matrices = [m[0, n_head] for m in ram]
359 # save_attention_image(
363 # attention_matrices,
365 ##min_total_attention=0.9,
369 # logger(f"wrote {filename}")
372 ######################################################################
377 class PicoCLVR(Task):
378 # Make a tensor from a list of strings
379 def tensorize(self, descr):
380 token_descr = [s.strip().split(" ") for s in descr]
381 l = max([len(s) for s in token_descr])
382 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
383 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
384 return torch.tensor(id_descr, device=self.device)
386 # Make a list of strings from a tensor
387 def detensorize(self, x):
388 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
390 # trim all the tensors in the tuple z to remove as much token from
391 # left and right in the first tensor. If z is a tuple, all its
392 # elements are trimed according to the triming for the first
393 def trim(self, z, token="<nul>"):
394 n = self.token2id[token]
397 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
398 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
399 return tuple([t[:, a:b] for t in z])
401 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
402 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
405 ######################
416 device=torch.device("cpu"),
422 def generate_descr(nb, cache_suffix, pruner):
423 return picoclvr.generate(
433 self.batch_size = batch_size
435 self.pruner_train = pruner_train
436 self.pruner_eval = pruner_eval
438 if logger is not None:
440 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
443 self.train_descr = generate_descr(
444 nb_train_samples, "train", pruner=self.pruner_train
446 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
448 # Build the tokenizer
449 tokens = {"<nul>", "<img>"}
450 for d in [self.train_descr, self.test_descr]:
452 for t in s.strip().split(" "):
454 # make this set a sorted list to get the same tensors given
456 tokens = list(tokens)
458 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
459 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
460 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
462 # Tokenize the train and test sets
463 self.train_input = self.tensorize(self.train_descr)
464 self.test_input = self.tensorize(self.test_descr)
466 def batches(self, split="train"):
467 assert split in {"train", "test"}
468 input = self.train_input if split == "train" else self.test_input
469 for batch in tqdm.tqdm(
470 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
472 yield self.trim(batch)
474 def vocabulary_size(self):
475 return len(self.token2id)
477 def compute_missing_properties(
478 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
480 acc_nb_requested_properties = []
481 acc_nb_missing_properties = []
484 for input in tqdm.tqdm(
485 self.test_input.split(self.batch_size),
487 desc=f"test-properties",
489 result = input.clone()
490 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
491 result = (1 - ar_mask) * result + ar_mask * self.t_nul
492 masked_inplace_autoregression(
497 deterministic_synthesis,
498 progress_bar_desc=None,
502 result_descr = self.detensorize(result)
503 np = picoclvr.nb_properties(
509 nb_requested_properties, _, nb_missing_properties = zip(*np)
510 acc_nb_requested_properties += nb_requested_properties
511 acc_nb_missing_properties += nb_missing_properties
512 acc_nb_results += len(result_descr)
514 nb_requested_properties = sum(acc_nb_requested_properties)
515 nb_missing_properties = sum(acc_nb_missing_properties)
517 prefix = "" if pruner is None else "pruned_"
518 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
520 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
523 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
527 f"main_test_accuracy {n_epoch} {1-nb_missing_properties/nb_requested_properties}"
530 ######################################################################
533 self, n_epoch, model, result_dir, logger, deterministic_synthesis
535 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
537 if self.pruner_eval is not None:
538 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
540 nb_tokens_to_generate = self.height * self.width + 3
545 for primer_descr in [
546 "red above green <sep> green top <sep> blue right of red",
547 "there is red <sep> there is yellow <sep> there is blue",
548 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
549 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
551 primer += [primer_descr + " <img>"] * nb_per_primer
553 result = self.tensorize(primer)
554 fill = result.new_full(
555 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
557 result = torch.cat((result, fill), 1)
558 ar_mask = (result == self.t_nul).long()
559 masked_inplace_autoregression(
564 deterministic_synthesis,
567 result_descr = self.detensorize(result)
569 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
571 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
572 acc_nb_results = len(result_descr)
574 nb_requested_properties = sum(acc_nb_requested_properties)
575 nb_missing_properties = sum(acc_nb_missing_properties)
578 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
580 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
583 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
586 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
590 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
594 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
600 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
601 torchvision.utils.save_image(
602 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
604 logger(f"wrote {image_name}")
607 ######################################################################
612 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
616 self.nb_train_samples = (nb_train_samples,)
617 self.nb_test_samples = (nb_test_samples,)
618 self.batch_size = batch_size
620 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
621 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
622 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
623 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
625 def batches(self, split="train", nb_to_use=-1, desc=None):
626 assert split in {"train", "test"}
627 input = self.train_input if split == "train" else self.test_input
629 input = input[:nb_to_use]
631 desc = f"epoch-{split}"
632 for batch in tqdm.tqdm(
633 input.split(self.batch_size), dynamic_ncols=True, desc=desc
637 def vocabulary_size(self):
641 self, n_epoch, model, result_dir, logger, deterministic_synthesis
643 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
644 ar_mask = torch.full_like(results, 1)
645 masked_inplace_autoregression(
650 deterministic_synthesis,
653 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
654 torchvision.utils.save_image(
655 1 - results.reshape(-1, 1, 28, 28) / 255.0,
660 logger(f"wrote {image_name}")
663 ######################################################################
669 def map2seq(self, *m):
670 return torch.cat([x.flatten(1) for x in m], 1)
672 def seq2map(self, s):
673 s = s.reshape(s.size(0), -1, self.height, self.width)
674 return (s[:, k] for k in range(s.size(1)))
684 device=torch.device("cpu"),
688 self.batch_size = batch_size
693 train_mazes, train_paths, _ = maze.create_maze_data(
698 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
700 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
702 test_mazes, test_paths, _ = maze.create_maze_data(
707 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
709 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
711 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
713 def batches(self, split="train", nb_to_use=-1, desc=None):
714 assert split in {"train", "test"}
715 input = self.train_input if split == "train" else self.test_input
717 input = input[:nb_to_use]
719 desc = f"epoch-{split}"
720 for batch in tqdm.tqdm(
721 input.split(self.batch_size), dynamic_ncols=True, desc=desc
725 def vocabulary_size(self):
729 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
731 nb_total, nb_correct = 0, 0
733 self.width * self.height,
734 self.width * self.height,
739 for input in self.batches(split, nb_to_use):
740 result = input.clone()
741 ar_mask = result.new_zeros(result.size())
742 ar_mask[:, self.height * self.width :] = 1
743 result *= 1 - ar_mask
744 masked_inplace_autoregression(
749 deterministic_synthesis,
750 progress_bar_desc=None,
753 mazes, paths = self.seq2map(result)
754 path_correctness = maze.path_correctness(mazes, paths)
755 nb_correct += path_correctness.long().sum()
756 nb_total += mazes.size(0)
758 optimal_path_lengths = (
759 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
761 predicted_path_lengths = (
762 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
764 optimal_path_lengths = optimal_path_lengths[path_correctness]
765 predicted_path_lengths = predicted_path_lengths[path_correctness]
766 count[optimal_path_lengths, predicted_path_lengths] += 1
772 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
775 return nb_total, nb_correct, count
778 self, n_epoch, model, result_dir, logger, deterministic_synthesis
780 train_nb_total, train_nb_correct, count = self.compute_error(
784 deterministic_synthesis=deterministic_synthesis,
787 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}%"
790 test_nb_total, test_nb_correct, count = self.compute_error(
794 deterministic_synthesis=deterministic_synthesis,
797 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}%"
800 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
802 if count is not None:
803 proportion_optimal = count.diagonal().sum().float() / count.sum()
804 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
806 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
808 for i in range(count.size(0)):
809 for j in range(count.size(1)):
810 eol = " " if j < count.size(1) - 1 else "\n"
811 f.write(f"{count[i,j]}{eol}")
813 input = self.test_input[:48]
814 result = input.clone()
815 ar_mask = result.new_zeros(result.size())
816 ar_mask[:, self.height * self.width :] = 1
817 result *= 1 - ar_mask
818 masked_inplace_autoregression(
823 deterministic_synthesis,
827 mazes, paths = self.seq2map(input)
828 _, predicted_paths = self.seq2map(result)
830 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
835 predicted_paths=predicted_paths,
836 path_correct=maze.path_correctness(mazes, predicted_paths),
837 path_optimal=maze.path_optimality(paths, predicted_paths),
839 logger(f"wrote {filename}")
842 ######################################################################
859 device=torch.device("cpu"),
863 self.batch_size = batch_size
867 self.prompt_length = prompt_length
869 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
878 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
888 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
890 def batches(self, split="train", nb_to_use=-1, desc=None):
891 assert split in {"train", "test"}
892 input = self.train_input if split == "train" else self.test_input
894 input = input[:nb_to_use]
896 desc = f"epoch-{split}"
897 for batch in tqdm.tqdm(
898 input.split(self.batch_size), dynamic_ncols=True, desc=desc
902 def vocabulary_size(self):
906 self, n_epoch, model, result_dir, logger, deterministic_synthesis
908 def compute_nb_correct(input, prior_visits):
909 result = input.clone()
910 i = torch.arange(result.size(1), device=result.device)[None, :]
912 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
916 result *= 1 - ar_mask
918 masked_inplace_autoregression(
923 deterministic_synthesis,
927 nb_total = ((prior_visits > 0) * ar_mask).sum()
929 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
931 return nb_total, nb_correct
933 test_nb_total, test_nb_correct = compute_nb_correct(
934 self.test_input[:1000], self.test_prior_visits[:1000]
938 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}%"
941 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
944 ######################################################################
960 fraction_values_for_train=None,
961 device=torch.device("cpu"),
965 self.batch_size = batch_size
966 self.nb_steps = nb_steps
967 self.nb_stacks = nb_stacks
968 self.nb_digits = nb_digits
971 if fraction_values_for_train is None:
972 values_for_train = None
973 values_for_test = None
975 all = torch.randperm(10**nb_digits)
976 nb_for_train = int(all.size(0) * fraction_values_for_train)
977 values_for_train = all[:nb_for_train]
978 values_for_test = all[nb_for_train:]
980 self.train_input, self.train_stack_counts = stack.generate_sequences(
989 self.test_input, self.test_stack_counts = stack.generate_sequences(
998 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
999 counts = self.test_stack_counts.flatten()[i.flatten()]
1000 counts = F.one_hot(counts).sum(0)
1001 logger(f"test_pop_stack_counts {counts}")
1003 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1005 def batches(self, split="train", nb_to_use=-1, desc=None):
1006 assert split in {"train", "test"}
1007 input = self.train_input if split == "train" else self.test_input
1009 input = input[:nb_to_use]
1011 desc = f"epoch-{split}"
1012 for batch in tqdm.tqdm(
1013 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1017 def vocabulary_size(self):
1018 return self.nb_codes
1020 def produce_results(
1021 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1023 def compute_nb_correct(input):
1024 result = input.clone()
1025 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
1026 ar_mask = (result != input).long()
1027 masked_inplace_autoregression(
1032 deterministic_synthesis,
1036 errors = ((result != input).long() * ar_mask).reshape(
1037 -1, 1 + self.nb_digits
1039 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
1041 nb_total = ar_mask.max(1).values.sum()
1042 nb_correct = nb_total - errors.max(1).values.sum()
1044 return nb_total, nb_correct
1046 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
1049 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}%"
1052 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
1054 ##############################################################
1055 # Log a few generated sequences
1056 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
1057 result = input.clone()
1058 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
1059 ar_mask = (result != input).long()
1061 # for n in range(result.size(0)):
1063 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1066 masked_inplace_autoregression(
1071 deterministic_synthesis,
1075 for n in range(result.size(0)):
1077 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1079 ##############################################################
1082 ######################################################################
1088 def tensorize(self, sequences):
1089 len_max = max([len(x) for x in sequences])
1095 self.token2id[str(c)]
1096 for c in s + ["<nul>"] * (len_max - len(s))
1105 def seq2str(self, seq):
1106 return " ".join([self.id2token[i] for i in seq])
1113 nb_starting_values=3,
1119 device=torch.device("cpu"),
1123 self.batch_size = batch_size
1124 self.device = device
1125 self.no_prog = no_prog
1129 nb_starting_values=nb_starting_values,
1130 nb_result_values_max=4 * nb_starting_values,
1131 max_input=max_input,
1135 for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
1140 nb_starting_values=nb_starting_values,
1141 nb_result_values_max=4 * nb_starting_values,
1142 max_input=max_input,
1146 for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
1150 set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
1152 val_max = max([x if type(x) is int else 0 for x in symbols])
1153 symbols = list(filter(lambda x: type(x) is str, symbols))
1155 symbols += [str(n) for n in range(val_max + 1)]
1156 self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
1157 self.id2token = dict([(n, c) for c, n in self.token2id.items()])
1159 self.t_nul = self.token2id["<nul>"]
1160 self.t_input = self.token2id["<in>"]
1161 self.t_output = self.token2id["<out>"]
1162 self.t_prog = self.token2id["<prg>"]
1163 self.t_end = self.token2id["<end>"]
1165 self.train_input = self.tensorize(train_sequences)
1166 self.test_input = self.tensorize(test_sequences)
1169 # Excise the program from every train and test example
1170 k = torch.arange(self.train_input.size(1), device=self.train_input.device)[
1174 ((self.train_input == self.t_prog).long() * k)
1175 .max(1, keepdim=True)
1178 self.train_input = (
1179 self.train_input * (k <= p).long()
1180 + self.t_end * (k == p + 1).long()
1181 + self.t_nul * (k > p + 1).long()
1183 k = torch.arange(self.test_input.size(1), device=self.test_input.device)[
1187 ((self.test_input == self.t_prog).long() * k)
1188 .max(1, keepdim=True)
1192 self.test_input * (k <= p).long()
1193 + self.t_end * (k == p + 1).long()
1194 + self.t_nul * (k > p + 1).long()
1197 if logger is not None:
1198 logger(f"value_max {val_max}")
1199 for x in self.train_input[:25]:
1200 end = (x != self.t_nul).nonzero().max().item() + 1
1201 seq = [self.id2token[i.item()] for i in x[:end]]
1203 logger(f"example_seq {s}")
1205 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1207 def batches(self, split="train", nb_to_use=-1, desc=None):
1208 assert split in {"train", "test"}
1209 input = self.train_input if split == "train" else self.test_input
1211 input = input[:nb_to_use]
1213 desc = f"epoch-{split}"
1214 for batch in tqdm.tqdm(
1215 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1217 last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1218 batch = batch[:, :last].to(self.device)
1221 def vocabulary_size(self):
1222 return self.nb_codes
1224 def produce_results(
1225 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1227 # --------------------------------------------------------------------
1228 def compute_nb_errors_prog(input, nb_to_log=0):
1229 result = input.clone()
1230 s = (result == self.t_prog).long()
1231 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1232 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1234 masked_inplace_autoregression(
1239 deterministic_synthesis,
1243 sum_nb_total, sum_nb_errors = 0, 0
1244 for one_input, one_result in zip(input, result):
1245 seq = [self.id2token[i.item()] for i in one_result]
1246 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1248 sum_nb_errors += 0 if nb_errors == 0 else 1
1250 gt_seq = [self.id2token[i.item()] for i in one_input]
1251 _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1252 gt_prog = " ".join([str(x) for x in gt_prog])
1253 prog = " ".join([str(x) for x in prog])
1254 comment = "*" if nb_errors == 0 else "-"
1255 logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1256 for start_stack, target_stack, result_stack, correct in stacks:
1257 comment = "*" if correct else "-"
1258 start_stack = " ".join([str(x) for x in start_stack])
1259 target_stack = " ".join([str(x) for x in target_stack])
1260 result_stack = " ".join([str(x) for x in result_stack])
1262 f" {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1266 return sum_nb_total, sum_nb_errors
1268 # --------------------------------------------------------------------
1269 def compute_nb_errors_output(input, nb_to_log=0):
1270 result = input.clone()
1271 k = torch.arange(result.size(1), device=result.device)[None, :]
1273 ((result == self.t_output) * k).max(dim=1, keepdim=True).values
1276 ((result == self.t_prog) * k).max(dim=1, keepdim=True).values
1278 ar_mask = (k > last_output_idx).long() * (k < first_prog_idx).long()
1279 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1281 masked_inplace_autoregression(
1286 deterministic_synthesis,
1290 sum_nb_total, sum_nb_errors = 0, 0
1291 for one_input, one_result, i, j in zip(
1292 input, result, last_output_idx, first_prog_idx
1294 seq = [self.id2token[i.item()] for i in one_result]
1296 correct = (one_input - one_result).abs().max() == 0
1297 sum_nb_errors += 0 if correct else 1
1300 self.id2token[i.item()] for i in one_result[i : j + 1]
1303 self.id2token[i.item()] for i in one_input[i : j + 1]
1305 comment = "*" if correct else "-"
1306 result_stack = " ".join([str(x) for x in result_stack])
1307 target_stack = " ".join([str(x) for x in target_stack])
1309 f"output_test {comment} [{target_stack}] PREDICTED [{result_stack}]"
1313 return sum_nb_total, sum_nb_errors
1315 # --------------------------------------------------------------------
1317 if not self.no_prog:
1318 test_nb_total, test_nb_errors = compute_nb_errors_prog(
1319 self.test_input[:1000].to(self.device), nb_to_log=10
1323 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}%"
1326 logger(f"main_test_accuracy {n_epoch} {1-test_nb_errors/test_nb_total}")
1328 test_nb_total, test_nb_errors = compute_nb_errors_output(
1329 self.test_input[:1000].to(self.device), nb_to_log=10
1333 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}%"
1336 if save_attention_image is None:
1337 logger("no save_attention_image (is pycairo installed?)")
1339 ns = torch.randint(self.test_input.size(0), (1,)).item()
1340 input = self.test_input[ns : ns + 1].clone()
1341 last = (input != self.t_nul).max(0).values.nonzero().max() + 3
1342 input = input[:, :last].to(self.device)
1344 with torch.autograd.no_grad():
1347 model.record_attention(True)
1348 model(BracketedSequence(input))
1350 ram = model.retrieve_attention()
1351 model.record_attention(False)
1353 tokens_output = [self.id2token[i.item()] for i in input[0]]
1354 tokens_input = ["n/a"] + tokens_output[:-1]
1355 for n_head in range(ram[0].size(1)):
1356 filename = os.path.join(
1357 result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
1359 attention_matrices = [m[0, n_head] for m in ram]
1360 save_attention_image(
1366 # min_total_attention=0.9,
1370 logger(f"wrote {filename}")
1373 ######################################################################
1380 def tensorize(self, sequences):
1381 len_max = max([len(x) for x in sequences])
1386 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1403 device=torch.device("cpu"),
1407 self.batch_size = batch_size
1408 self.device = device
1410 train_sequences = expr.generate_sequences(
1412 nb_variables=nb_variables,
1413 length=sequence_length,
1414 operand_max=operand_max,
1415 result_max=result_max,
1418 test_sequences = expr.generate_sequences(
1420 nb_variables=nb_variables,
1421 length=sequence_length,
1422 operand_max=operand_max,
1423 result_max=result_max,
1426 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1429 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1430 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1432 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1434 self.train_input = self.tensorize(train_sequences)
1435 self.test_input = self.tensorize(test_sequences)
1437 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1439 def batches(self, split="train", nb_to_use=-1, desc=None):
1440 assert split in {"train", "test"}
1441 input = self.train_input if split == "train" else self.test_input
1443 input = input[:nb_to_use]
1445 desc = f"epoch-{split}"
1446 for batch in tqdm.tqdm(
1447 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1449 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1450 batch = batch[:, :last]
1453 def vocabulary_size(self):
1454 return self.nb_codes
1456 def seq2str(self, s):
1457 return "".join([self.id2char[k.item()] for k in s])
1459 def produce_results(
1465 deterministic_synthesis,
1468 def compute_nb_correct(input):
1469 result = input.clone()
1470 s = (result == self.space).long()
1471 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1472 result = (1 - ar_mask) * result + ar_mask * self.filler
1473 masked_inplace_autoregression(
1478 deterministic_synthesis,
1482 nb_total = input.size(0)
1483 nb_correct = (input == result).long().min(1).values.sum()
1485 #######################################################################
1486 # Comput predicted vs. true variable values
1488 nb_delta = torch.zeros(5, dtype=torch.int64)
1491 values_input = expr.extract_results([self.seq2str(s) for s in input])
1492 values_result = expr.extract_results([self.seq2str(s) for s in result])
1494 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1496 with open(filename, "w") as f:
1497 for i, r in zip(values_input, values_result):
1498 for n, vi in i.items():
1500 f.write(f"{vi} {-1 if vr is None else vr}\n")
1502 if vr is None or vr < 0:
1506 if d >= nb_delta.size(0):
1511 ######################################################################
1513 return nb_total, nb_correct, nb_delta, nb_missed
1520 ) = compute_nb_correct(self.test_input[:10000])
1523 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}%"
1526 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
1528 nb_total = test_nb_delta.sum() + test_nb_missed
1529 for d in range(test_nb_delta.size(0)):
1531 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1534 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1537 ##############################################################
1538 # Log a few generated sequences
1539 if input_file is None:
1540 input = self.test_input[:10]
1542 with open(input_file, "r") as f:
1543 sequences = [e.strip() for e in f.readlines()]
1544 sequences = [s + " " + "#" * 50 for s in sequences]
1545 input = self.tensorize(sequences)
1547 result = input.clone()
1548 s = (result == self.space).long()
1549 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1550 result = (1 - ar_mask) * result + ar_mask * self.filler
1552 for n in range(result.size(0)):
1553 logger(f"test_before {self.seq2str(result[n])}")
1555 masked_inplace_autoregression(
1560 deterministic_synthesis,
1564 correct = (1 - ar_mask) * self.space + ar_mask * input
1565 for n in range(result.size(0)):
1566 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1567 logger(f"test_after {self.seq2str(result[n])} {comment}")
1568 logger(f"truth {self.seq2str(correct[n])}")
1569 ##############################################################
1572 ######################################################################
1578 # Make a tensor from a list of strings
1579 def str2tensor(self, descr):
1580 token_descr = [s.strip().split(" ") for s in descr]
1581 l = max([len(s) for s in token_descr])
1582 token_descr = [s + ["#"] * (l - len(s)) for s in token_descr]
1583 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
1584 return torch.tensor(id_descr, device=self.device)
1586 # Make a list of strings from a tensor
1587 def tensor2str(self, x):
1588 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
1590 # trim all the tensors in the tuple z to remove as much token from
1591 # left and right in the first tensor. If z is a tuple, all its
1592 # elements are trimed according to the triming for the first
1593 def trim(self, z, token="#"):
1594 n = self.token2id[token]
1595 if type(z) == tuple:
1597 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
1598 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
1599 return tuple([t[:, a:b] for t in z])
1601 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
1602 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
1605 ######################
1615 device=torch.device("cpu"),
1619 self.device = device
1620 self.batch_size = batch_size
1621 self.grid_factory = grid.GridFactory(size=size)
1622 self.fraction_play = fraction_play
1624 if logger is not None:
1626 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
1629 self.train_descr = self.grid_factory.generate_samples(
1630 nb=nb_train_samples,
1631 fraction_play=fraction_play,
1632 progress_bar=lambda r: tqdm.tqdm(r),
1635 self.test_descr = self.grid_factory.generate_samples(
1636 nb=nb_test_samples, fraction_play=0.0, progress_bar=lambda r: tqdm.tqdm(r)
1639 if fraction_play > 0:
1640 self.play_descr = self.grid_factory.generate_samples(
1641 nb=25, fraction_play=1.0, progress_bar=lambda r: tqdm.tqdm(r)
1644 self.play_descr = []
1646 # Build the tokenizer
1648 for d in [self.train_descr, self.test_descr, self.play_descr]:
1650 for t in s.strip().split(" "):
1652 # make this set a sorted list to get the same tensors given
1654 tokens = list(tokens)
1656 tokens = ["#"] + tokens
1657 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
1658 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
1659 self.t_nul = self.token2id["#"]
1660 self.t_true = self.token2id["true"]
1661 self.t_false = self.token2id["false"]
1662 self.t_pipe = self.token2id["|"]
1664 # Tokenize the train and test sets
1665 self.train_input = self.str2tensor(self.train_descr)
1666 self.test_input = self.str2tensor(self.test_descr)
1668 None if len(self.play_descr) == 0 else self.str2tensor(self.play_descr)
1671 def batches(self, split="train"):
1672 assert split in {"train", "test"}
1673 input = self.train_input if split == "train" else self.test_input
1674 for batch in tqdm.tqdm(
1675 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
1677 yield self.trim(batch)
1679 def vocabulary_size(self):
1680 return len(self.token2id)
1682 def produce_results(
1683 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1685 correct = self.test_input[:1000]
1686 result = correct.clone()
1687 ar_mask = torch.logical_or(result == self.t_true, result == self.t_false).long()
1688 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
1690 logger(f"----------------------------------------------------------")
1692 for e in self.tensor2str(result[:10]):
1693 logger(f"test_before {e}")
1695 masked_inplace_autoregression(
1700 deterministic_synthesis,
1704 logger(f"----------------------------------------------------------")
1706 for e in self.tensor2str(result[:10]):
1707 logger(f"test_after {e}")
1709 logger(f"----------------------------------------------------------")
1711 nb_total = ar_mask.sum().item()
1712 nb_correct = ((correct == result).long() * ar_mask).sum().item()
1714 logger(f"test_performance {n_epoch} {nb_total=} {nb_correct=}")
1715 logger(f"main_test_accuracy {n_epoch} {nb_correct / nb_total}")
1717 if self.play_input is not None:
1718 result = self.play_input.clone()
1719 ar_mask = (result == self.t_pipe).long().cumsum(dim=1).clamp(max=1)
1720 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
1722 logger(f"----------------------------------------------------------")
1724 for e in self.tensor2str(result[:10]):
1725 logger(f"play_before {e}")
1727 masked_inplace_autoregression(
1732 deterministic_synthesis,
1736 logger(f"----------------------------------------------------------")
1738 for e in self.tensor2str(result[:10]):
1739 logger(f"play_after {e}")
1741 logger(f"----------------------------------------------------------")
1744 ######################################################################
1750 ######################
1759 device=torch.device("cpu"),
1763 self.device = device
1764 self.batch_size = batch_size
1765 self.nb_samples_per_mlp = 256
1767 if logger is not None:
1769 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
1772 seq, q_test_set, test_error = qmlp.generate_sequence_and_test_set(
1773 nb_mlps=nb_train_samples + nb_test_samples,
1774 nb_samples=self.nb_samples_per_mlp,
1778 nb_mlps_per_batch=1024,
1781 self.train_input = seq[:nb_train_samples]
1782 self.train_q_test_set = q_test_set[:nb_train_samples]
1783 self.train_ref_test_errors = test_error[:nb_train_samples]
1784 self.test_input = seq[nb_train_samples:]
1785 self.test_q_test_set = q_test_set[nb_train_samples:]
1786 self.test_ref_test_errors = test_error[nb_train_samples:]
1788 filename = os.path.join(result_dir, f"train_errors_ref.dat")
1789 with open(filename, "w") as f:
1790 for e in self.train_ref_test_errors:
1793 filename = os.path.join(result_dir, f"test_errors_ref.dat")
1794 with open(filename, "w") as f:
1795 for e in self.test_ref_test_errors:
1798 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1800 def batches(self, split="train"):
1801 assert split in {"train", "test"}
1802 input = self.train_input if split == "train" else self.test_input
1803 for batch in tqdm.tqdm(
1804 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
1808 def vocabulary_size(self):
1809 return self.nb_codes
1811 def produce_results(
1812 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1814 correct = self.test_input[:1000]
1815 result = correct.clone()
1817 torch.arange(result.size(1), device=result.device)
1818 > self.nb_samples_per_mlp * 3 + 1
1820 ar_mask = ar_mask.expand_as(result)
1821 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
1823 masked_inplace_autoregression(
1828 deterministic_synthesis,
1832 q_train_set = result[:, : self.nb_samples_per_mlp * 3]
1833 q_params = result[:, self.nb_samples_per_mlp * 3 + 1 :]
1834 error_test = qmlp.evaluate_q_params(q_params, self.test_q_test_set)
1836 filename = os.path.join(result_dir, f"test_errors_{n_epoch:04d}.dat")
1837 with open(filename, "w") as f:
1838 for e in error_test:
1842 ######################################################################