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>
8 import math, os, tqdm, warnings
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,
31 progress_bar_desc="autoregression",
32 device=torch.device("cpu"),
34 assert input.size() == ar_mask.size()
36 batches = zip(input.split(batch_size), ar_mask.split(batch_size))
38 if progress_bar_desc is not None:
42 desc=progress_bar_desc,
43 total=(input.size(0) + batch_size - 1) // batch_size,
46 with torch.autograd.no_grad():
50 for input, ar_mask in batches:
51 model.masked_inplace_autoregression(
54 deterministic_synthesis,
62 ######################################################################
66 def batches(self, split="train", nb_to_use=-1, desc=None):
69 def vocabulary_size(self):
73 self, n_epoch, model, result_dir, logger, deterministic_synthesis
78 class TaskFromFile(Task):
79 def tensorize(self, pairs, shuffle):
80 len_max = max([len(x[0]) for x in pairs])
86 [self.char2id[c] for c in s[0] + "#" * (len_max - len(s[0]))]
94 pred_mask = torch.cat(
98 [int(c) for c in s[1] + "0" * (len_max - len(s[1]))]
107 i = torch.randperm(input.size(0))
108 input = input[i].contiguous()
109 pred_mask = pred_mask[i].contiguous()
111 return input, pred_mask
113 # trim all the tensors in the tuple z to remove as much token from
114 # left and right in the first tensor. If z is a tuple, all its
115 # elements are trimed according to the triming for the first
116 def trim(self, z, token="#"):
117 n = self.char2id[token]
120 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
121 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
122 return tuple([t[:, a:b] for t in z])
124 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
125 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
136 device=torch.device("cpu"),
138 self.batch_size = batch_size
141 def read_file(filename, nb=-1):
143 with open(filename, "r") as f:
145 sequence = f.readline().strip()
148 pred_mask = f.readline().strip()
149 assert len(sequence) == len(pred_mask)
150 assert set(pred_mask).issubset({"0", "1", "2"}), f"{set(pred_mask)}"
151 pairs.append((sequence, pred_mask))
157 assert len(pairs) == nb
161 train_pairs = read_file(train_filename, nb_train_samples)
162 test_pairs = read_file(test_filename, nb_test_samples)
164 symbols = ["#"] + list(
165 set("".join([x[0] for x in train_pairs + test_pairs])) - set(["#"])
167 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
168 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
170 self.train_input, self.train_pred_masks = self.tensorize(
171 train_pairs, shuffle=shuffle
173 self.test_input, self.test_pred_masks = self.tensorize(
174 test_pairs, shuffle=shuffle
177 def batches(self, split="train", nb_to_use=-1, desc=None):
178 assert split in {"train", "test"}
179 input = self.train_input if split == "train" else self.test_input
181 input = input[:nb_to_use]
183 desc = f"epoch-{split}"
184 for batch in tqdm.tqdm(
185 input.split(self.batch_size), dynamic_ncols=True, desc=desc
187 yield self.trim(batch).to(self.device)
189 def vocabulary_size(self):
190 return len(self.char2id)
192 def tensor2str(self, t):
193 return ["".join([self.id2char[x.item()] for x in s]) for s in t]
196 self, n_epoch, model, result_dir, logger, deterministic_synthesis
198 correct = self.trim(self.test_input[:1000]).to(self.device)
199 result = correct.clone()
200 pred_mask = self.test_pred_masks[:1000, : result.size(1)].to(self.device)
201 ar_mask = (pred_mask > 0).long()
202 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
204 logger(f"----------------------------------------------------------")
206 for e in self.tensor2str(result[:50]):
207 logger(f"test_before {e}")
209 masked_inplace_autoregression(
214 deterministic_synthesis,
218 logger(f"----------------------------------------------------------")
220 for e, c in zip(self.tensor2str(result[:50]), self.tensor2str(correct[:50])):
221 logger(f"test_after {e}")
222 logger(f"correct {c}")
224 logger(f"----------------------------------------------------------")
226 err_mask = (pred_mask == 2).long()
227 nb_total = err_mask.sum().item()
228 nb_correct = ((correct == result).long() * err_mask).sum().item()
230 logger(f"test_performance {n_epoch} {nb_total=} {nb_correct=}")
231 logger(f"main_test_accuracy {n_epoch} {nb_correct / nb_total}")
247 device=torch.device("cpu"),
252 self.batch_size = batch_size
254 self.problem = problem
256 self.train_input, self.train_ar_mask = self.problem.generate_sequences(
259 self.test_input, self.test_ar_mask = self.problem.generate_sequences(
263 self.train_input, self.train_ar_mask = self.train_input.to(
265 ), self.train_ar_mask.to(device)
266 self.test_input, self.test_ar_mask = self.test_input.to(
268 ), self.test_ar_mask.to(device)
270 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
272 # A bit of paranoia never hurts
273 assert self.nb_codes <= max_nb_codes
274 assert self.train_input.min() >= 0
275 assert self.test_input.min() >= 0
276 assert tuple(x.item() for x in self.train_ar_mask.unique()) in {
281 assert tuple(x.item() for x in self.test_ar_mask.unique()) in {
287 if logger is not None:
288 for s, a in zip(self.train_input[:100], self.train_ar_mask[:100]):
289 logger(f"train_sequences {self.problem.seq2str(s)}")
290 a = "".join(["01"[x.item()] for x in a])
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, nmax=1000
311 def compute_accuracy(input, ar_mask, logger=None):
312 input, ar_mask = input[:nmax], ar_mask[:nmax]
313 result = input.clone() * (1 - ar_mask)
315 masked_inplace_autoregression(
320 deterministic_synthesis,
321 progress_bar_desc=None,
325 log_ground_truth = ar_mask.min() == 0
327 if logger is not None:
328 for sp, st in zip(result[:10], input[:10]):
330 f"test_sequences {n_epoch} prediction {self.problem.seq2str(sp)}"
334 f" {n_epoch} ground truth {self.problem.seq2str(st)}"
337 nb_total, nb_correct = self.problem.compute_nb_correct(
338 input, ar_mask, result
341 # nb_total = ar_mask.sum().item()
342 # nb_correct = ((result == input).long() * ar_mask).sum().item()
344 return nb_total, nb_correct
346 train_nb_total, train_nb_correct = compute_accuracy(
347 self.train_input, self.train_ar_mask
351 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}%"
354 test_nb_total, test_nb_correct = compute_accuracy(
355 self.test_input, self.test_ar_mask, logger
359 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}%"
362 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
364 if save_attention_image is not None:
366 ns = torch.randint(self.test_input.size(0), (1,)).item()
367 input = self.test_input[ns : ns + 1].clone()
369 with torch.autograd.no_grad():
372 # model.record_attention(True)
373 model(BracketedSequence(input))
375 # ram = model.retrieve_attention()
376 # model.record_attention(False)
378 # tokens_output = [c for c in self.problem.seq2str(input[0])]
379 # tokens_input = ["n/a"] + tokens_output[:-1]
380 # for n_head in range(ram[0].size(1)):
381 # filename = os.path.join(
382 # result_dir, f"sandbox_attention_{k}_h{n_head}.pdf"
384 # attention_matrices = [m[0, n_head] for m in ram]
385 # save_attention_image(
389 # attention_matrices,
391 ##min_total_attention=0.9,
395 # logger(f"wrote {filename}")
398 ######################################################################
410 device=torch.device("cpu"),
414 self.batch_size = batch_size
419 self.train_input = world.generate(
420 nb_train_samples, height=self.height, width=self.width
422 self.train_ar_mask = (
423 (torch.arange(self.train_input.size(1)) > self.train_input.size(1) // 2)
425 .expand_as(self.train_input)
428 self.test_input = world.generate(
429 nb_test_samples, height=self.height, width=self.width
431 self.test_ar_mask = (
432 (torch.arange(self.test_input.size(1)) > self.test_input.size(1) // 2)
434 .expand_as(self.test_input)
437 self.train_input, self.train_ar_mask = self.train_input.to(
439 ), self.train_ar_mask.to(device)
440 self.test_input, self.test_ar_mask = self.test_input.to(
442 ), self.test_ar_mask.to(device)
444 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
446 def batches(self, split="train", nb_to_use=-1, desc=None):
447 assert split in {"train", "test"}
448 input = self.train_input if split == "train" else self.test_input
450 input = input[:nb_to_use]
452 desc = f"epoch-{split}"
453 for batch in tqdm.tqdm(
454 input.split(self.batch_size), dynamic_ncols=True, desc=desc
458 def vocabulary_size(self):
462 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
464 def compute_accuracy(input, ar_mask, logger=None):
465 input, ar_mask = input[:nmax], ar_mask[:nmax]
466 result = input.clone() * (1 - ar_mask)
468 masked_inplace_autoregression(
473 deterministic_synthesis,
474 progress_bar_desc=None,
478 nb_total, nb_correct = (
480 (input == result).long().min(dim=1).values.sum(),
483 return nb_total, nb_correct
485 train_nb_total, train_nb_correct = compute_accuracy(
486 self.train_input, self.train_ar_mask
490 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}%"
493 test_nb_total, test_nb_correct = compute_accuracy(
494 self.test_input, self.test_ar_mask, logger
498 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}%"
501 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
503 if save_attention_image is not None:
505 ns = torch.randint(self.test_input.size(0), (1,)).item()
506 input = self.test_input[ns : ns + 1].clone()
508 with torch.autograd.no_grad():
511 # model.record_attention(True)
512 model(BracketedSequence(input))
514 # ram = model.retrieve_attention()
515 # model.record_attention(False)
517 # tokens_output = [c for c in self.problem.seq2str(input[0])]
518 # tokens_input = ["n/a"] + tokens_output[:-1]
519 # for n_head in range(ram[0].size(1)):
520 # filename = os.path.join(
521 # result_dir, f"sandbox_attention_{k}_h{n_head}.pdf"
523 # attention_matrices = [m[0, n_head] for m in ram]
524 # save_attention_image(
528 # attention_matrices,
530 ##min_total_attention=0.9,
534 # logger(f"wrote {filename}")
537 ######################################################################
542 class PicoCLVR(Task):
543 # Make a tensor from a list of strings
544 def tensorize(self, descr):
545 token_descr = [s.strip().split(" ") for s in descr]
546 l = max([len(s) for s in token_descr])
547 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
548 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
549 return torch.tensor(id_descr, device=self.device)
551 # Make a list of strings from a tensor
552 def detensorize(self, x):
553 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
555 # trim all the tensors in the tuple z to remove as much token from
556 # left and right in the first tensor. If z is a tuple, all its
557 # elements are trimed according to the triming for the first
558 def trim(self, z, token="<nul>"):
559 n = self.token2id[token]
562 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
563 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
564 return tuple([t[:, a:b] for t in z])
566 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
567 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
570 ######################
581 device=torch.device("cpu"),
587 def generate_descr(nb, cache_suffix, pruner):
588 return picoclvr.generate(
598 self.batch_size = batch_size
600 self.pruner_train = pruner_train
601 self.pruner_eval = pruner_eval
603 if logger is not None:
605 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
608 self.train_descr = generate_descr(
609 nb_train_samples, "train", pruner=self.pruner_train
611 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
613 # Build the tokenizer
614 tokens = {"<nul>", "<img>"}
615 for d in [self.train_descr, self.test_descr]:
617 for t in s.strip().split(" "):
619 # make this set a sorted list to get the same tensors given
621 tokens = list(tokens)
623 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
624 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
625 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
627 # Tokenize the train and test sets
628 self.train_input = self.tensorize(self.train_descr)
629 self.test_input = self.tensorize(self.test_descr)
631 def batches(self, split="train", nb_to_use=-1, desc=None):
632 assert split in {"train", "test"}
633 input = self.train_input if split == "train" else self.test_input
634 for batch in tqdm.tqdm(
635 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
637 yield self.trim(batch)
639 def vocabulary_size(self):
640 return len(self.token2id)
642 def compute_missing_properties(
643 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
645 acc_nb_requested_properties = []
646 acc_nb_missing_properties = []
649 for input in tqdm.tqdm(
650 self.test_input.split(self.batch_size),
652 desc=f"test-properties",
654 result = input.clone()
655 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
656 result = (1 - ar_mask) * result + ar_mask * self.t_nul
657 masked_inplace_autoregression(
662 deterministic_synthesis,
663 progress_bar_desc=None,
667 result_descr = self.detensorize(result)
668 np = picoclvr.nb_properties(
674 nb_requested_properties, _, nb_missing_properties = zip(*np)
675 acc_nb_requested_properties += nb_requested_properties
676 acc_nb_missing_properties += nb_missing_properties
677 acc_nb_results += len(result_descr)
679 nb_requested_properties = sum(acc_nb_requested_properties)
680 nb_missing_properties = sum(acc_nb_missing_properties)
682 prefix = "" if pruner is None else "pruned_"
683 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
685 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
688 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
692 f"main_test_accuracy {n_epoch} {1-nb_missing_properties/nb_requested_properties}"
695 ######################################################################
698 self, n_epoch, model, result_dir, logger, deterministic_synthesis
700 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
702 if self.pruner_eval is not None:
703 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
705 nb_tokens_to_generate = self.height * self.width + 3
710 for primer_descr in [
711 "red above green <sep> green top <sep> blue right of red",
712 "there is red <sep> there is yellow <sep> there is blue",
713 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
714 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
716 primer += [primer_descr + " <img>"] * nb_per_primer
718 result = self.tensorize(primer)
719 fill = result.new_full(
720 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
722 result = torch.cat((result, fill), 1)
723 ar_mask = (result == self.t_nul).long()
724 masked_inplace_autoregression(
729 deterministic_synthesis,
732 result_descr = self.detensorize(result)
734 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
736 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
737 acc_nb_results = len(result_descr)
739 nb_requested_properties = sum(acc_nb_requested_properties)
740 nb_missing_properties = sum(acc_nb_missing_properties)
743 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
745 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
748 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
751 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
755 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
759 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
765 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
766 torchvision.utils.save_image(
767 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
769 logger(f"wrote {image_name}")
772 ######################################################################
777 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
781 self.nb_train_samples = (nb_train_samples,)
782 self.nb_test_samples = (nb_test_samples,)
783 self.batch_size = batch_size
785 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
786 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
787 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
788 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
790 def batches(self, split="train", nb_to_use=-1, desc=None):
791 assert split in {"train", "test"}
792 input = self.train_input if split == "train" else self.test_input
794 input = input[:nb_to_use]
796 desc = f"epoch-{split}"
797 for batch in tqdm.tqdm(
798 input.split(self.batch_size), dynamic_ncols=True, desc=desc
802 def vocabulary_size(self):
806 self, n_epoch, model, result_dir, logger, deterministic_synthesis
808 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
809 ar_mask = torch.full_like(results, 1)
810 masked_inplace_autoregression(
815 deterministic_synthesis,
818 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
819 torchvision.utils.save_image(
820 1 - results.reshape(-1, 1, 28, 28) / 255.0,
825 logger(f"wrote {image_name}")
828 ######################################################################
834 def map2seq(self, *m):
835 return torch.cat([x.flatten(1) for x in m], 1)
837 def seq2map(self, s):
838 s = s.reshape(s.size(0), -1, self.height, self.width)
839 return (s[:, k] for k in range(s.size(1)))
849 device=torch.device("cpu"),
853 self.batch_size = batch_size
858 train_mazes, train_paths, _ = maze.create_maze_data(
863 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
865 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
867 test_mazes, test_paths, _ = maze.create_maze_data(
872 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
874 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
876 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
878 def batches(self, split="train", nb_to_use=-1, desc=None):
879 assert split in {"train", "test"}
880 input = self.train_input if split == "train" else self.test_input
882 input = input[:nb_to_use]
884 desc = f"epoch-{split}"
885 for batch in tqdm.tqdm(
886 input.split(self.batch_size), dynamic_ncols=True, desc=desc
890 def vocabulary_size(self):
894 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
896 model_device = next(model.parameters()).device
897 nb_total, nb_correct = 0, 0
899 self.width * self.height,
900 self.width * self.height,
905 for input in self.batches(split, nb_to_use):
906 input = input.to(model_device)
907 result = input.clone()
908 ar_mask = result.new_zeros(result.size())
909 ar_mask[:, self.height * self.width :] = 1
910 result *= 1 - ar_mask
911 masked_inplace_autoregression(
916 deterministic_synthesis,
917 progress_bar_desc=None,
920 mazes, paths = self.seq2map(result)
921 path_correctness = maze.path_correctness(mazes, paths)
922 nb_correct += path_correctness.long().sum()
923 nb_total += mazes.size(0)
925 optimal_path_lengths = (
926 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
928 predicted_path_lengths = (
929 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
931 optimal_path_lengths = optimal_path_lengths[path_correctness]
932 predicted_path_lengths = predicted_path_lengths[path_correctness]
933 count[optimal_path_lengths, predicted_path_lengths] += 1
939 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
942 return nb_total, nb_correct, count
945 self, n_epoch, model, result_dir, logger, deterministic_synthesis
947 train_nb_total, train_nb_correct, count = self.compute_error(
951 deterministic_synthesis=deterministic_synthesis,
954 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}%"
957 test_nb_total, test_nb_correct, count = self.compute_error(
961 deterministic_synthesis=deterministic_synthesis,
964 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}%"
967 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
969 if count is not None:
970 proportion_optimal = count.diagonal().sum().float() / count.sum()
971 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
973 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
975 for i in range(count.size(0)):
976 for j in range(count.size(1)):
977 eol = " " if j < count.size(1) - 1 else "\n"
978 f.write(f"{count[i,j]}{eol}")
980 input = self.test_input[:48].to(next(model.parameters()).device)
981 result = input.clone()
982 ar_mask = result.new_zeros(result.size())
983 ar_mask[:, self.height * self.width :] = 1
984 result *= 1 - ar_mask
985 masked_inplace_autoregression(
990 deterministic_synthesis,
994 mazes, paths = self.seq2map(input)
995 _, predicted_paths = self.seq2map(result)
997 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
1002 predicted_paths=predicted_paths,
1003 path_correct=maze.path_correctness(mazes, predicted_paths),
1004 path_optimal=maze.path_optimality(paths, predicted_paths),
1006 logger(f"wrote {filename}")
1009 ######################################################################
1026 device=torch.device("cpu"),
1030 self.batch_size = batch_size
1031 self.height = height
1033 self.device = device
1034 self.prompt_length = prompt_length
1036 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
1045 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
1055 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1057 def batches(self, split="train", nb_to_use=-1, desc=None):
1058 assert split in {"train", "test"}
1059 input = self.train_input if split == "train" else self.test_input
1061 input = input[:nb_to_use]
1063 desc = f"epoch-{split}"
1064 for batch in tqdm.tqdm(
1065 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1069 def vocabulary_size(self):
1070 return self.nb_codes
1072 def produce_results(
1073 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1075 def compute_nb_correct(input, prior_visits):
1076 result = input.clone()
1077 i = torch.arange(result.size(1), device=result.device)[None, :]
1079 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
1083 result *= 1 - ar_mask
1085 masked_inplace_autoregression(
1090 deterministic_synthesis,
1094 nb_total = ((prior_visits > 0) * ar_mask).sum()
1096 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
1098 return nb_total, nb_correct
1100 test_nb_total, test_nb_correct = compute_nb_correct(
1101 self.test_input[:1000], self.test_prior_visits[:1000]
1105 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}%"
1108 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
1111 ######################################################################
1127 fraction_values_for_train=None,
1128 device=torch.device("cpu"),
1132 self.batch_size = batch_size
1133 self.nb_steps = nb_steps
1134 self.nb_stacks = nb_stacks
1135 self.nb_digits = nb_digits
1136 self.device = device
1138 if fraction_values_for_train is None:
1139 values_for_train = None
1140 values_for_test = None
1142 all = torch.randperm(10**nb_digits)
1143 nb_for_train = int(all.size(0) * fraction_values_for_train)
1144 values_for_train = all[:nb_for_train]
1145 values_for_test = all[nb_for_train:]
1147 self.train_input, self.train_stack_counts = stack.generate_sequences(
1156 self.test_input, self.test_stack_counts = stack.generate_sequences(
1165 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
1166 counts = self.test_stack_counts.flatten()[i.flatten()]
1167 counts = F.one_hot(counts).sum(0)
1168 logger(f"test_pop_stack_counts {counts}")
1170 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1172 def batches(self, split="train", nb_to_use=-1, desc=None):
1173 assert split in {"train", "test"}
1174 input = self.train_input if split == "train" else self.test_input
1176 input = input[:nb_to_use]
1178 desc = f"epoch-{split}"
1179 for batch in tqdm.tqdm(
1180 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1184 def vocabulary_size(self):
1185 return self.nb_codes
1187 def produce_results(
1188 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1190 def compute_nb_correct(input):
1191 result = input.clone()
1192 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
1193 ar_mask = (result != input).long()
1194 masked_inplace_autoregression(
1199 deterministic_synthesis,
1203 errors = ((result != input).long() * ar_mask).reshape(
1204 -1, 1 + self.nb_digits
1206 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
1208 nb_total = ar_mask.max(1).values.sum()
1209 nb_correct = nb_total - errors.max(1).values.sum()
1211 return nb_total, nb_correct
1213 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
1216 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}%"
1219 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
1221 ##############################################################
1222 # Log a few generated sequences
1223 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
1224 result = input.clone()
1225 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
1226 ar_mask = (result != input).long()
1228 # for n in range(result.size(0)):
1230 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1233 masked_inplace_autoregression(
1238 deterministic_synthesis,
1242 #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1243 for label, input in [
1244 ("train", self.train_input[:32]),
1245 ("test", self.test_input[:32]),
1247 output = model(BracketedSequence(input)).x
1248 output = output.log_softmax(dim=-1)
1249 filename = os.path.join(
1250 result_dir, f"stack_with_crossentropy_{n_epoch:04d}_{label}.txt"
1252 with open(filename, "w") as f:
1253 for n in range(input.size(0)):
1254 s = stack.seq_to_str(
1255 input[n], nb_stacks=self.nb_stacks, nb_digits=self.nb_digits
1257 for t, k, w in zip(range(input[n].size(0)), input[n], s.split(" ")):
1262 + str(output[n][t][k].exp().item())
1267 logger(f"wrote {filename}")
1268 #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1270 for n in range(result.size(0)):
1272 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1274 ##############################################################
1277 ######################################################################
1283 def tensorize(self, sequences):
1284 len_max = max([len(x) for x in sequences])
1290 self.token2id[str(c)]
1291 for c in s + ["<nul>"] * (len_max - len(s))
1300 def seq2str(self, seq):
1301 return " ".join([self.id2token[i] for i in seq])
1308 nb_starting_values=3,
1314 device=torch.device("cpu"),
1318 self.batch_size = batch_size
1319 self.device = device
1320 self.no_prog = no_prog
1324 nb_starting_values=nb_starting_values,
1325 nb_result_values_max=4 * nb_starting_values,
1326 max_input=max_input,
1330 for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
1335 nb_starting_values=nb_starting_values,
1336 nb_result_values_max=4 * nb_starting_values,
1337 max_input=max_input,
1341 for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
1345 set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
1347 val_max = max([x if type(x) is int else 0 for x in symbols])
1348 symbols = list(filter(lambda x: type(x) is str, symbols))
1350 symbols += [str(n) for n in range(val_max + 1)]
1351 self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
1352 self.id2token = dict([(n, c) for c, n in self.token2id.items()])
1354 self.t_nul = self.token2id["<nul>"]
1355 self.t_input = self.token2id["<in>"]
1356 self.t_output = self.token2id["<out>"]
1357 self.t_prog = self.token2id["<prg>"]
1358 self.t_end = self.token2id["<end>"]
1360 self.train_input = self.tensorize(train_sequences)
1361 self.test_input = self.tensorize(test_sequences)
1364 # Excise the program from every train and test example
1365 k = torch.arange(self.train_input.size(1), device=self.train_input.device)[
1369 ((self.train_input == self.t_prog).long() * k)
1370 .max(1, keepdim=True)
1373 self.train_input = (
1374 self.train_input * (k <= p).long()
1375 + self.t_end * (k == p + 1).long()
1376 + self.t_nul * (k > p + 1).long()
1378 k = torch.arange(self.test_input.size(1), device=self.test_input.device)[
1382 ((self.test_input == self.t_prog).long() * k)
1383 .max(1, keepdim=True)
1387 self.test_input * (k <= p).long()
1388 + self.t_end * (k == p + 1).long()
1389 + self.t_nul * (k > p + 1).long()
1392 if logger is not None:
1393 logger(f"value_max {val_max}")
1394 for x in self.train_input[:25]:
1395 end = (x != self.t_nul).nonzero().max().item() + 1
1396 seq = [self.id2token[i.item()] for i in x[:end]]
1398 logger(f"example_seq {s}")
1400 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1402 def batches(self, split="train", nb_to_use=-1, desc=None):
1403 assert split in {"train", "test"}
1404 input = self.train_input if split == "train" else self.test_input
1406 input = input[:nb_to_use]
1408 desc = f"epoch-{split}"
1409 for batch in tqdm.tqdm(
1410 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1412 last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1413 batch = batch[:, :last].to(self.device)
1416 def vocabulary_size(self):
1417 return self.nb_codes
1419 def produce_results(
1420 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1422 # --------------------------------------------------------------------
1423 def compute_nb_errors_prog(input, nb_to_log=0):
1424 result = input.clone()
1425 s = (result == self.t_prog).long()
1426 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1427 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1429 masked_inplace_autoregression(
1434 deterministic_synthesis,
1438 sum_nb_total, sum_nb_errors = 0, 0
1439 for one_input, one_result in zip(input, result):
1440 seq = [self.id2token[i.item()] for i in one_result]
1441 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1443 sum_nb_errors += 0 if nb_errors == 0 else 1
1445 gt_seq = [self.id2token[i.item()] for i in one_input]
1446 _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1447 gt_prog = " ".join([str(x) for x in gt_prog])
1448 prog = " ".join([str(x) for x in prog])
1449 comment = "*" if nb_errors == 0 else "-"
1450 logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1451 for start_stack, target_stack, result_stack, correct in stacks:
1452 comment = "*" if correct else "-"
1453 start_stack = " ".join([str(x) for x in start_stack])
1454 target_stack = " ".join([str(x) for x in target_stack])
1455 result_stack = " ".join([str(x) for x in result_stack])
1457 f" {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1461 return sum_nb_total, sum_nb_errors
1463 # --------------------------------------------------------------------
1464 def compute_nb_errors_output(input, nb_to_log=0):
1465 result = input.clone()
1466 k = torch.arange(result.size(1), device=result.device)[None, :]
1468 ((result == self.t_output) * k).max(dim=1, keepdim=True).values
1471 ((result == self.t_prog) * k).max(dim=1, keepdim=True).values
1473 ar_mask = (k > last_output_idx).long() * (k < first_prog_idx).long()
1474 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1476 masked_inplace_autoregression(
1481 deterministic_synthesis,
1485 sum_nb_total, sum_nb_errors = 0, 0
1486 for one_input, one_result, i, j in zip(
1487 input, result, last_output_idx, first_prog_idx
1489 seq = [self.id2token[i.item()] for i in one_result]
1491 correct = (one_input - one_result).abs().max() == 0
1492 sum_nb_errors += 0 if correct else 1
1495 self.id2token[i.item()] for i in one_result[i : j + 1]
1498 self.id2token[i.item()] for i in one_input[i : j + 1]
1500 comment = "*" if correct else "-"
1501 result_stack = " ".join([str(x) for x in result_stack])
1502 target_stack = " ".join([str(x) for x in target_stack])
1504 f"output_test {comment} [{target_stack}] PREDICTED [{result_stack}]"
1508 return sum_nb_total, sum_nb_errors
1510 # --------------------------------------------------------------------
1512 if not self.no_prog:
1513 test_nb_total, test_nb_errors = compute_nb_errors_prog(
1514 self.test_input[:1000].to(self.device), nb_to_log=10
1518 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}%"
1521 logger(f"main_test_accuracy {n_epoch} {1-test_nb_errors/test_nb_total}")
1523 test_nb_total, test_nb_errors = compute_nb_errors_output(
1524 self.test_input[:1000].to(self.device), nb_to_log=10
1528 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}%"
1531 if save_attention_image is None:
1532 logger("no save_attention_image (is pycairo installed?)")
1534 ns = torch.randint(self.test_input.size(0), (1,)).item()
1535 input = self.test_input[ns : ns + 1].clone()
1536 last = (input != self.t_nul).max(0).values.nonzero().max() + 3
1537 input = input[:, :last].to(self.device)
1539 with torch.autograd.no_grad():
1542 model.record_attention(True)
1543 model(BracketedSequence(input))
1545 ram = model.retrieve_attention()
1546 model.record_attention(False)
1548 tokens_output = [self.id2token[i.item()] for i in input[0]]
1549 tokens_input = ["n/a"] + tokens_output[:-1]
1550 for n_head in range(ram[0].size(1)):
1551 filename = os.path.join(
1552 result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
1554 attention_matrices = [m[0, n_head] for m in ram]
1555 save_attention_image(
1561 # min_total_attention=0.9,
1565 logger(f"wrote {filename}")
1568 ######################################################################
1575 def tensorize(self, sequences):
1576 len_max = max([len(x) for x in sequences])
1581 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1598 device=torch.device("cpu"),
1602 self.batch_size = batch_size
1603 self.device = device
1605 train_sequences = expr.generate_sequences(
1607 nb_variables=nb_variables,
1608 length=sequence_length,
1609 operand_max=operand_max,
1610 result_max=result_max,
1613 test_sequences = expr.generate_sequences(
1615 nb_variables=nb_variables,
1616 length=sequence_length,
1617 operand_max=operand_max,
1618 result_max=result_max,
1621 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1624 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1625 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1627 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1629 self.train_input = self.tensorize(train_sequences)
1630 self.test_input = self.tensorize(test_sequences)
1632 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1634 def batches(self, split="train", nb_to_use=-1, desc=None):
1635 assert split in {"train", "test"}
1636 input = self.train_input if split == "train" else self.test_input
1638 input = input[:nb_to_use]
1640 desc = f"epoch-{split}"
1641 for batch in tqdm.tqdm(
1642 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1644 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1645 batch = batch[:, :last]
1648 def vocabulary_size(self):
1649 return self.nb_codes
1651 def seq2str(self, s):
1652 return "".join([self.id2char[k.item()] for k in s])
1654 def produce_results(
1660 deterministic_synthesis,
1663 def compute_nb_correct(input):
1664 result = input.clone()
1665 s = (result == self.space).long()
1666 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1667 result = (1 - ar_mask) * result + ar_mask * self.filler
1668 masked_inplace_autoregression(
1673 deterministic_synthesis,
1677 nb_total = input.size(0)
1678 nb_correct = (input == result).long().min(1).values.sum()
1680 #######################################################################
1681 # Comput predicted vs. true variable values
1683 nb_delta = torch.zeros(5, dtype=torch.int64)
1686 values_input = expr.extract_results([self.seq2str(s) for s in input])
1687 values_result = expr.extract_results([self.seq2str(s) for s in result])
1689 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1691 with open(filename, "w") as f:
1692 for i, r in zip(values_input, values_result):
1693 for n, vi in i.items():
1695 f.write(f"{vi} {-1 if vr is None else vr}\n")
1697 if vr is None or vr < 0:
1701 if d >= nb_delta.size(0):
1706 ######################################################################
1708 return nb_total, nb_correct, nb_delta, nb_missed
1715 ) = compute_nb_correct(self.test_input[:10000])
1718 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}%"
1721 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
1723 nb_total = test_nb_delta.sum() + test_nb_missed
1724 for d in range(test_nb_delta.size(0)):
1726 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1729 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1732 ##############################################################
1733 # Log a few generated sequences
1734 if input_file is None:
1735 input = self.test_input[:10]
1737 with open(input_file, "r") as f:
1738 sequences = [e.strip() for e in f.readlines()]
1739 sequences = [s + " " + "#" * 50 for s in sequences]
1740 input = self.tensorize(sequences)
1742 result = input.clone()
1743 s = (result == self.space).long()
1744 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1745 result = (1 - ar_mask) * result + ar_mask * self.filler
1747 for n in range(result.size(0)):
1748 logger(f"test_before {self.seq2str(result[n])}")
1750 masked_inplace_autoregression(
1755 deterministic_synthesis,
1759 correct = (1 - ar_mask) * self.space + ar_mask * input
1760 for n in range(result.size(0)):
1761 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1762 logger(f"test_after {self.seq2str(result[n])} {comment}")
1763 logger(f"truth {self.seq2str(correct[n])}")
1764 ##############################################################
1767 ######################################################################
1773 # Make a tensor from a list of strings
1774 def str2tensor(self, descr):
1775 token_descr = [s.strip().split(" ") for s in descr]
1776 l = max([len(s) for s in token_descr])
1777 token_descr = [s + ["#"] * (l - len(s)) for s in token_descr]
1778 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
1779 return torch.tensor(id_descr, device=self.device)
1781 # Make a list of strings from a tensor
1782 def tensor2str(self, x):
1783 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
1785 # trim all the tensors in the tuple z to remove as much token from
1786 # left and right in the first tensor. If z is a tuple, all its
1787 # elements are trimed according to the triming for the first
1788 def trim(self, z, token="#"):
1789 n = self.token2id[token]
1790 if type(z) == tuple:
1792 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
1793 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
1794 return tuple([t[:, a:b] for t in z])
1796 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
1797 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
1800 ######################
1810 device=torch.device("cpu"),
1814 self.device = device
1815 self.batch_size = batch_size
1816 self.grid_factory = grid.GridFactory(size=size)
1817 self.fraction_play = fraction_play
1819 if logger is not None:
1821 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
1824 self.train_descr = self.grid_factory.generate_samples(
1825 nb=nb_train_samples,
1826 fraction_play=fraction_play,
1827 progress_bar=lambda r: tqdm.tqdm(r),
1830 self.test_descr = self.grid_factory.generate_samples(
1831 nb=nb_test_samples, fraction_play=0.0, progress_bar=lambda r: tqdm.tqdm(r)
1834 if fraction_play > 0:
1835 self.play_descr = self.grid_factory.generate_samples(
1836 nb=25, fraction_play=1.0, progress_bar=lambda r: tqdm.tqdm(r)
1839 self.play_descr = []
1841 # Build the tokenizer
1843 for d in [self.train_descr, self.test_descr, self.play_descr]:
1845 for t in s.strip().split(" "):
1847 # make this set a sorted list to get the same tensors given
1849 tokens = list(tokens)
1851 tokens = ["#"] + tokens
1852 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
1853 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
1854 self.t_nul = self.token2id["#"]
1855 self.t_true = self.token2id["true"]
1856 self.t_false = self.token2id["false"]
1857 # self.t_pipe = self.token2id["|"]
1859 # Tokenize the train and test sets
1860 self.train_input = self.str2tensor(self.train_descr)
1861 self.test_input = self.str2tensor(self.test_descr)
1863 None if len(self.play_descr) == 0 else self.str2tensor(self.play_descr)
1866 def batches(self, split="train", nb_to_use=-1, desc=None):
1867 assert split in {"train", "test"}
1868 input = self.train_input if split == "train" else self.test_input
1869 for batch in tqdm.tqdm(
1870 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
1872 yield self.trim(batch)
1874 def vocabulary_size(self):
1875 return len(self.token2id)
1877 def produce_results(
1878 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1880 correct = self.test_input[:1000]
1881 result = correct.clone()
1882 ar_mask = torch.logical_or(result == self.t_true, result == self.t_false).long()
1883 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
1885 logger(f"----------------------------------------------------------")
1887 for e in self.tensor2str(result[:10]):
1888 logger(f"test_before {e}")
1890 masked_inplace_autoregression(
1895 deterministic_synthesis,
1899 logger(f"----------------------------------------------------------")
1901 for e in self.tensor2str(result[:10]):
1902 logger(f"test_after {e}")
1904 logger(f"----------------------------------------------------------")
1906 nb_total = ar_mask.sum().item()
1907 nb_correct = ((correct == result).long() * ar_mask).sum().item()
1909 logger(f"test_performance {n_epoch} {nb_total=} {nb_correct=}")
1910 logger(f"main_test_accuracy {n_epoch} {nb_correct / nb_total}")
1912 if self.play_input is not None:
1913 result = self.play_input.clone()
1914 ar_mask = (result == self.t_pipe).long().cumsum(dim=1).clamp(max=1)
1915 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
1917 logger(f"----------------------------------------------------------")
1919 for e in self.tensor2str(result[:10]):
1920 logger(f"play_before {e}")
1922 masked_inplace_autoregression(
1927 deterministic_synthesis,
1931 logger(f"----------------------------------------------------------")
1933 for e in self.tensor2str(result[:10]):
1934 logger(f"play_after {e}")
1936 logger(f"----------------------------------------------------------")
1939 ######################################################################
1945 ######################
1954 device=torch.device("cpu"),
1958 self.device = device
1959 self.batch_size = batch_size
1960 self.nb_samples_per_mlp = 256
1962 if logger is not None:
1964 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
1967 seq, q_test_set, test_error = qmlp.generate_sequence_and_test_set(
1968 nb_mlps=nb_train_samples + nb_test_samples,
1969 nb_samples=self.nb_samples_per_mlp,
1973 nb_mlps_per_batch=1024,
1976 self.train_input = seq[:nb_train_samples]
1977 self.train_q_test_set = q_test_set[:nb_train_samples]
1978 self.train_ref_test_errors = test_error[:nb_train_samples]
1979 self.test_input = seq[nb_train_samples:]
1980 self.test_q_test_set = q_test_set[nb_train_samples:]
1981 self.test_ref_test_errors = test_error[nb_train_samples:]
1983 filename = os.path.join(result_dir, f"train_errors_ref.dat")
1984 with open(filename, "w") as f:
1985 for e in self.train_ref_test_errors:
1988 filename = os.path.join(result_dir, f"test_errors_ref.dat")
1989 with open(filename, "w") as f:
1990 for e in self.test_ref_test_errors:
1993 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1995 def batches(self, split="train", nb_to_use=-1, desc=None):
1996 assert split in {"train", "test"}
1997 input = self.train_input if split == "train" else self.test_input
1998 for batch in tqdm.tqdm(
1999 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
2003 def vocabulary_size(self):
2004 return self.nb_codes
2006 def produce_results(
2007 self, n_epoch, model, result_dir, logger, deterministic_synthesis
2009 correct = self.test_input[:1000]
2010 result = correct.clone()
2012 torch.arange(result.size(1), device=result.device)
2013 > self.nb_samples_per_mlp * 3 + 1
2015 ar_mask = ar_mask.expand_as(result)
2016 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
2018 masked_inplace_autoregression(
2023 deterministic_synthesis,
2027 q_train_set = result[:, : self.nb_samples_per_mlp * 3]
2028 q_params = result[:, self.nb_samples_per_mlp * 3 + 1 :]
2029 error_test = qmlp.evaluate_q_params(q_params, self.test_q_test_set)
2031 filename = os.path.join(result_dir, f"test_errors_{n_epoch:04d}.dat")
2032 with open(filename, "w") as f:
2033 for e in error_test:
2037 ######################################################################
2054 device=torch.device("cpu"),
2058 self.batch_size = batch_size
2059 self.device = device
2061 self.world = greed.GreedWorld(height, width, T, nb_walls, nb_coins)
2063 states, actions, rewards = self.world.generate_episodes(
2064 nb_train_samples + nb_test_samples
2066 seq = self.world.episodes2seq(states, actions, rewards)
2067 self.train_input = seq[:nb_train_samples].to(self.device)
2068 self.test_input = seq[nb_train_samples:].to(self.device)
2070 def wipe_lookahead_rewards(self, batch):
2071 t = torch.arange(batch.size(1), device=batch.device)[None, :]
2072 u = torch.randint(batch.size(1), (batch.size(0), 1), device=batch.device)
2073 lr_mask = (t <= u).long() * (
2074 t % self.world.it_len == self.world.index_lookahead_reward
2078 lr_mask * self.world.lookahead_reward2code(greed.REWARD_UNKNOWN)
2079 + (1 - lr_mask) * batch
2082 def batches(self, split="train", nb_to_use=-1, desc=None):
2083 assert split in {"train", "test"}
2084 input = self.train_input if split == "train" else self.test_input
2086 input = input[:nb_to_use]
2088 desc = f"epoch-{split}"
2089 for batch in tqdm.tqdm(
2090 input.split(self.batch_size), dynamic_ncols=True, desc=desc
2092 yield self.wipe_lookahead_rewards(batch)
2094 def vocabulary_size(self):
2095 return self.world.nb_codes
2097 def thinking_autoregression(
2098 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
2102 def ar(result, ar_mask, logit_biases=None):
2103 ar_mask = ar_mask.expand_as(result)
2104 result *= 1 - ar_mask
2105 masked_inplace_autoregression(
2110 deterministic_synthesis=deterministic_synthesis,
2111 logit_biases=logit_biases,
2113 progress_bar_desc=None,
2115 warnings.warn("keeping thinking snapshots", RuntimeWarning)
2116 snapshots.append(result[:100].detach().clone())
2118 # Generate iteration after iteration
2120 result = self.test_input[:250].clone()
2121 # Erase all the content but that of the first iteration
2122 result[:, self.world.it_len :] = -1
2123 # Set the lookahead_reward of the firs to UNKNOWN
2124 result[:, self.world.index_lookahead_reward] = self.world.lookahead_reward2code(
2125 greed.REWARD_UNKNOWN
2128 t = torch.arange(result.size(1), device=result.device)[None, :]
2131 range(0, result.size(1), self.world.it_len),
2134 # Generate the next state but keep the initial one, the
2135 # lookahead_reward of previous iterations are set to
2139 :, u + self.world.index_lookahead_reward
2140 ] = self.world.lookahead_reward2code(greed.REWARD_UNKNOWN)
2141 ar_mask = (t >= u + self.world.index_states).long() * (
2142 t < u + self.world.index_states + self.world.state_len
2146 # Generate the action and reward with lookahead_reward to +1
2148 :, u + self.world.index_lookahead_reward
2149 ] = self.world.lookahead_reward2code(greed.REWARD_PLUS)
2150 ar_mask = (t >= u + self.world.index_reward).long() * (
2151 t <= u + self.world.index_action
2155 # Set the lookahead_reward to UNKNOWN for the next iterations
2157 :, u + self.world.index_lookahead_reward
2158 ] = self.world.lookahead_reward2code(greed.REWARD_UNKNOWN)
2160 filename = os.path.join(result_dir, f"test_thinking_compute_{n_epoch:04d}.txt")
2161 with open(filename, "w") as f:
2162 for n in range(snapshots[0].size(0)):
2164 lr, s, a, r = self.world.seq2episodes(
2167 str = self.world.episodes2str(
2168 lr, s, a, r, unicode=True, ansi_colors=True
2173 # Saving the generated sequences
2175 lr, s, a, r = self.world.seq2episodes(result)
2176 str = self.world.episodes2str(lr, s, a, r, unicode=True, ansi_colors=True)
2178 filename = os.path.join(result_dir, f"test_thinking_seq_{n_epoch:04d}.txt")
2179 with open(filename, "w") as f:
2181 logger(f"wrote {filename}")
2183 def produce_results(
2184 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
2186 result = self.wipe_lookahead_rewards(self.test_input[:250].clone())
2188 # Saving the ground truth
2190 lr, s, a, r = self.world.seq2episodes(
2193 str = self.world.episodes2str(lr, s, a, r, unicode=True, ansi_colors=True)
2195 filename = os.path.join(result_dir, f"test_true_seq_{n_epoch:04d}.txt")
2196 with open(filename, "w") as f:
2198 logger(f"wrote {filename}")
2200 # Re-generating from the first frame
2203 torch.arange(result.size(1), device=result.device) >= self.world.it_len
2205 ar_mask = ar_mask.expand_as(result)
2206 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
2208 masked_inplace_autoregression(
2213 deterministic_synthesis,
2217 # Saving the generated sequences
2219 lr, s, a, r = self.world.seq2episodes(
2222 str = self.world.episodes2str(lr, s, a, r, unicode=True, ansi_colors=True)
2224 filename = os.path.join(result_dir, f"test_seq_{n_epoch:04d}.txt")
2225 with open(filename, "w") as f:
2227 logger(f"wrote {filename}")
2229 self.thinking_autoregression(
2230 n_epoch, model, result_dir, logger, deterministic_synthesis, nmax
2234 ######################################################################