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 ##############################
505 input, ar_mask = self.test_input[:64], self.test_ar_mask[:64]
506 result = input.clone() * (1 - ar_mask)
508 masked_inplace_autoregression(
513 deterministic_synthesis,
514 progress_bar_desc=None,
518 img = world.sample2img(result.to("cpu"), self.height, self.width)
520 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
521 torchvision.utils.save_image(img.float() / 255.0, image_name, nrow=8, padding=2)
522 logger(f"wrote {image_name}")
525 ######################################################################
530 class PicoCLVR(Task):
531 # Make a tensor from a list of strings
532 def tensorize(self, descr):
533 token_descr = [s.strip().split(" ") for s in descr]
534 l = max([len(s) for s in token_descr])
535 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
536 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
537 return torch.tensor(id_descr, device=self.device)
539 # Make a list of strings from a tensor
540 def detensorize(self, x):
541 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
543 # trim all the tensors in the tuple z to remove as much token from
544 # left and right in the first tensor. If z is a tuple, all its
545 # elements are trimed according to the triming for the first
546 def trim(self, z, token="<nul>"):
547 n = self.token2id[token]
550 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
551 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
552 return tuple([t[:, a:b] for t in z])
554 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
555 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
558 ######################
569 device=torch.device("cpu"),
575 def generate_descr(nb, cache_suffix, pruner):
576 return picoclvr.generate(
586 self.batch_size = batch_size
588 self.pruner_train = pruner_train
589 self.pruner_eval = pruner_eval
591 if logger is not None:
593 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
596 self.train_descr = generate_descr(
597 nb_train_samples, "train", pruner=self.pruner_train
599 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
601 # Build the tokenizer
602 tokens = {"<nul>", "<img>"}
603 for d in [self.train_descr, self.test_descr]:
605 for t in s.strip().split(" "):
607 # make this set a sorted list to get the same tensors given
609 tokens = list(tokens)
611 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
612 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
613 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
615 # Tokenize the train and test sets
616 self.train_input = self.tensorize(self.train_descr)
617 self.test_input = self.tensorize(self.test_descr)
619 def batches(self, split="train", nb_to_use=-1, desc=None):
620 assert split in {"train", "test"}
621 input = self.train_input if split == "train" else self.test_input
622 for batch in tqdm.tqdm(
623 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
625 yield self.trim(batch)
627 def vocabulary_size(self):
628 return len(self.token2id)
630 def compute_missing_properties(
631 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
633 acc_nb_requested_properties = []
634 acc_nb_missing_properties = []
637 for input in tqdm.tqdm(
638 self.test_input.split(self.batch_size),
640 desc=f"test-properties",
642 result = input.clone()
643 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
644 result = (1 - ar_mask) * result + ar_mask * self.t_nul
645 masked_inplace_autoregression(
650 deterministic_synthesis,
651 progress_bar_desc=None,
655 result_descr = self.detensorize(result)
656 np = picoclvr.nb_properties(
662 nb_requested_properties, _, nb_missing_properties = zip(*np)
663 acc_nb_requested_properties += nb_requested_properties
664 acc_nb_missing_properties += nb_missing_properties
665 acc_nb_results += len(result_descr)
667 nb_requested_properties = sum(acc_nb_requested_properties)
668 nb_missing_properties = sum(acc_nb_missing_properties)
670 prefix = "" if pruner is None else "pruned_"
671 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
673 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
676 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
680 f"main_test_accuracy {n_epoch} {1-nb_missing_properties/nb_requested_properties}"
683 ######################################################################
686 self, n_epoch, model, result_dir, logger, deterministic_synthesis
688 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
690 if self.pruner_eval is not None:
691 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
693 nb_tokens_to_generate = self.height * self.width + 3
698 for primer_descr in [
699 "red above green <sep> green top <sep> blue right of red",
700 "there is red <sep> there is yellow <sep> there is blue",
701 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
702 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
704 primer += [primer_descr + " <img>"] * nb_per_primer
706 result = self.tensorize(primer)
707 fill = result.new_full(
708 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
710 result = torch.cat((result, fill), 1)
711 ar_mask = (result == self.t_nul).long()
712 masked_inplace_autoregression(
717 deterministic_synthesis,
720 result_descr = self.detensorize(result)
722 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
724 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
725 acc_nb_results = len(result_descr)
727 nb_requested_properties = sum(acc_nb_requested_properties)
728 nb_missing_properties = sum(acc_nb_missing_properties)
731 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
733 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
736 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
739 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
743 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
747 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
753 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
754 torchvision.utils.save_image(
755 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
757 logger(f"wrote {image_name}")
760 ######################################################################
765 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
769 self.nb_train_samples = (nb_train_samples,)
770 self.nb_test_samples = (nb_test_samples,)
771 self.batch_size = batch_size
773 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
774 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
775 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
776 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
778 def batches(self, split="train", nb_to_use=-1, desc=None):
779 assert split in {"train", "test"}
780 input = self.train_input if split == "train" else self.test_input
782 input = input[:nb_to_use]
784 desc = f"epoch-{split}"
785 for batch in tqdm.tqdm(
786 input.split(self.batch_size), dynamic_ncols=True, desc=desc
790 def vocabulary_size(self):
794 self, n_epoch, model, result_dir, logger, deterministic_synthesis
796 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
797 ar_mask = torch.full_like(results, 1)
798 masked_inplace_autoregression(
803 deterministic_synthesis,
806 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
807 torchvision.utils.save_image(
808 1 - results.reshape(-1, 1, 28, 28) / 255.0,
813 logger(f"wrote {image_name}")
816 ######################################################################
822 def map2seq(self, *m):
823 return torch.cat([x.flatten(1) for x in m], 1)
825 def seq2map(self, s):
826 s = s.reshape(s.size(0), -1, self.height, self.width)
827 return (s[:, k] for k in range(s.size(1)))
837 device=torch.device("cpu"),
841 self.batch_size = batch_size
846 train_mazes, train_paths, _ = maze.create_maze_data(
851 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
853 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
855 test_mazes, test_paths, _ = maze.create_maze_data(
860 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
862 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
864 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
866 def batches(self, split="train", nb_to_use=-1, desc=None):
867 assert split in {"train", "test"}
868 input = self.train_input if split == "train" else self.test_input
870 input = input[:nb_to_use]
872 desc = f"epoch-{split}"
873 for batch in tqdm.tqdm(
874 input.split(self.batch_size), dynamic_ncols=True, desc=desc
878 def vocabulary_size(self):
882 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
884 model_device = next(model.parameters()).device
885 nb_total, nb_correct = 0, 0
887 self.width * self.height,
888 self.width * self.height,
893 for input in self.batches(split, nb_to_use):
894 input = input.to(model_device)
895 result = input.clone()
896 ar_mask = result.new_zeros(result.size())
897 ar_mask[:, self.height * self.width :] = 1
898 result *= 1 - ar_mask
899 masked_inplace_autoregression(
904 deterministic_synthesis,
905 progress_bar_desc=None,
908 mazes, paths = self.seq2map(result)
909 path_correctness = maze.path_correctness(mazes, paths)
910 nb_correct += path_correctness.long().sum()
911 nb_total += mazes.size(0)
913 optimal_path_lengths = (
914 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
916 predicted_path_lengths = (
917 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
919 optimal_path_lengths = optimal_path_lengths[path_correctness]
920 predicted_path_lengths = predicted_path_lengths[path_correctness]
921 count[optimal_path_lengths, predicted_path_lengths] += 1
927 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
930 return nb_total, nb_correct, count
933 self, n_epoch, model, result_dir, logger, deterministic_synthesis
935 train_nb_total, train_nb_correct, count = self.compute_error(
939 deterministic_synthesis=deterministic_synthesis,
942 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}%"
945 test_nb_total, test_nb_correct, count = self.compute_error(
949 deterministic_synthesis=deterministic_synthesis,
952 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}%"
955 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
957 if count is not None:
958 proportion_optimal = count.diagonal().sum().float() / count.sum()
959 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
961 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
963 for i in range(count.size(0)):
964 for j in range(count.size(1)):
965 eol = " " if j < count.size(1) - 1 else "\n"
966 f.write(f"{count[i,j]}{eol}")
968 input = self.test_input[:48].to(next(model.parameters()).device)
969 result = input.clone()
970 ar_mask = result.new_zeros(result.size())
971 ar_mask[:, self.height * self.width :] = 1
972 result *= 1 - ar_mask
973 masked_inplace_autoregression(
978 deterministic_synthesis,
982 mazes, paths = self.seq2map(input)
983 _, predicted_paths = self.seq2map(result)
985 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
990 predicted_paths=predicted_paths,
991 path_correct=maze.path_correctness(mazes, predicted_paths),
992 path_optimal=maze.path_optimality(paths, predicted_paths),
994 logger(f"wrote {filename}")
997 ######################################################################
1014 device=torch.device("cpu"),
1018 self.batch_size = batch_size
1019 self.height = height
1021 self.device = device
1022 self.prompt_length = prompt_length
1024 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
1033 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
1043 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1045 def batches(self, split="train", nb_to_use=-1, desc=None):
1046 assert split in {"train", "test"}
1047 input = self.train_input if split == "train" else self.test_input
1049 input = input[:nb_to_use]
1051 desc = f"epoch-{split}"
1052 for batch in tqdm.tqdm(
1053 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1057 def vocabulary_size(self):
1058 return self.nb_codes
1060 def produce_results(
1061 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1063 def compute_nb_correct(input, prior_visits):
1064 result = input.clone()
1065 i = torch.arange(result.size(1), device=result.device)[None, :]
1067 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
1071 result *= 1 - ar_mask
1073 masked_inplace_autoregression(
1078 deterministic_synthesis,
1082 nb_total = ((prior_visits > 0) * ar_mask).sum()
1084 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
1086 return nb_total, nb_correct
1088 test_nb_total, test_nb_correct = compute_nb_correct(
1089 self.test_input[:1000], self.test_prior_visits[:1000]
1093 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}%"
1096 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
1099 ######################################################################
1115 fraction_values_for_train=None,
1116 device=torch.device("cpu"),
1120 self.batch_size = batch_size
1121 self.nb_steps = nb_steps
1122 self.nb_stacks = nb_stacks
1123 self.nb_digits = nb_digits
1124 self.device = device
1126 if fraction_values_for_train is None:
1127 values_for_train = None
1128 values_for_test = None
1130 all = torch.randperm(10**nb_digits)
1131 nb_for_train = int(all.size(0) * fraction_values_for_train)
1132 values_for_train = all[:nb_for_train]
1133 values_for_test = all[nb_for_train:]
1135 self.train_input, self.train_stack_counts = stack.generate_sequences(
1144 self.test_input, self.test_stack_counts = stack.generate_sequences(
1153 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
1154 counts = self.test_stack_counts.flatten()[i.flatten()]
1155 counts = F.one_hot(counts).sum(0)
1156 logger(f"test_pop_stack_counts {counts}")
1158 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1160 def batches(self, split="train", nb_to_use=-1, desc=None):
1161 assert split in {"train", "test"}
1162 input = self.train_input if split == "train" else self.test_input
1164 input = input[:nb_to_use]
1166 desc = f"epoch-{split}"
1167 for batch in tqdm.tqdm(
1168 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1172 def vocabulary_size(self):
1173 return self.nb_codes
1175 def produce_results(
1176 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1178 def compute_nb_correct(input):
1179 result = input.clone()
1180 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
1181 ar_mask = (result != input).long()
1182 masked_inplace_autoregression(
1187 deterministic_synthesis,
1191 errors = ((result != input).long() * ar_mask).reshape(
1192 -1, 1 + self.nb_digits
1194 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
1196 nb_total = ar_mask.max(1).values.sum()
1197 nb_correct = nb_total - errors.max(1).values.sum()
1199 return nb_total, nb_correct
1201 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
1204 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}%"
1207 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
1209 ##############################################################
1210 # Log a few generated sequences
1211 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
1212 result = input.clone()
1213 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
1214 ar_mask = (result != input).long()
1216 # for n in range(result.size(0)):
1218 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1221 masked_inplace_autoregression(
1226 deterministic_synthesis,
1230 #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1231 for label, input in [
1232 ("train", self.train_input[:32]),
1233 ("test", self.test_input[:32]),
1235 output = model(BracketedSequence(input)).x
1236 output = output.log_softmax(dim=-1)
1237 filename = os.path.join(
1238 result_dir, f"stack_with_crossentropy_{n_epoch:04d}_{label}.txt"
1240 with open(filename, "w") as f:
1241 for n in range(input.size(0)):
1242 s = stack.seq_to_str(
1243 input[n], nb_stacks=self.nb_stacks, nb_digits=self.nb_digits
1245 for t, k, w in zip(range(input[n].size(0)), input[n], s.split(" ")):
1250 + str(output[n][t][k].exp().item())
1255 logger(f"wrote {filename}")
1256 #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1258 for n in range(result.size(0)):
1260 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1262 ##############################################################
1265 ######################################################################
1271 def tensorize(self, sequences):
1272 len_max = max([len(x) for x in sequences])
1278 self.token2id[str(c)]
1279 for c in s + ["<nul>"] * (len_max - len(s))
1288 def seq2str(self, seq):
1289 return " ".join([self.id2token[i] for i in seq])
1296 nb_starting_values=3,
1302 device=torch.device("cpu"),
1306 self.batch_size = batch_size
1307 self.device = device
1308 self.no_prog = no_prog
1312 nb_starting_values=nb_starting_values,
1313 nb_result_values_max=4 * nb_starting_values,
1314 max_input=max_input,
1318 for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
1323 nb_starting_values=nb_starting_values,
1324 nb_result_values_max=4 * nb_starting_values,
1325 max_input=max_input,
1329 for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
1333 set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
1335 val_max = max([x if type(x) is int else 0 for x in symbols])
1336 symbols = list(filter(lambda x: type(x) is str, symbols))
1338 symbols += [str(n) for n in range(val_max + 1)]
1339 self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
1340 self.id2token = dict([(n, c) for c, n in self.token2id.items()])
1342 self.t_nul = self.token2id["<nul>"]
1343 self.t_input = self.token2id["<in>"]
1344 self.t_output = self.token2id["<out>"]
1345 self.t_prog = self.token2id["<prg>"]
1346 self.t_end = self.token2id["<end>"]
1348 self.train_input = self.tensorize(train_sequences)
1349 self.test_input = self.tensorize(test_sequences)
1352 # Excise the program from every train and test example
1353 k = torch.arange(self.train_input.size(1), device=self.train_input.device)[
1357 ((self.train_input == self.t_prog).long() * k)
1358 .max(1, keepdim=True)
1361 self.train_input = (
1362 self.train_input * (k <= p).long()
1363 + self.t_end * (k == p + 1).long()
1364 + self.t_nul * (k > p + 1).long()
1366 k = torch.arange(self.test_input.size(1), device=self.test_input.device)[
1370 ((self.test_input == self.t_prog).long() * k)
1371 .max(1, keepdim=True)
1375 self.test_input * (k <= p).long()
1376 + self.t_end * (k == p + 1).long()
1377 + self.t_nul * (k > p + 1).long()
1380 if logger is not None:
1381 logger(f"value_max {val_max}")
1382 for x in self.train_input[:25]:
1383 end = (x != self.t_nul).nonzero().max().item() + 1
1384 seq = [self.id2token[i.item()] for i in x[:end]]
1386 logger(f"example_seq {s}")
1388 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1390 def batches(self, split="train", nb_to_use=-1, desc=None):
1391 assert split in {"train", "test"}
1392 input = self.train_input if split == "train" else self.test_input
1394 input = input[:nb_to_use]
1396 desc = f"epoch-{split}"
1397 for batch in tqdm.tqdm(
1398 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1400 last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1401 batch = batch[:, :last].to(self.device)
1404 def vocabulary_size(self):
1405 return self.nb_codes
1407 def produce_results(
1408 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1410 # --------------------------------------------------------------------
1411 def compute_nb_errors_prog(input, nb_to_log=0):
1412 result = input.clone()
1413 s = (result == self.t_prog).long()
1414 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1415 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1417 masked_inplace_autoregression(
1422 deterministic_synthesis,
1426 sum_nb_total, sum_nb_errors = 0, 0
1427 for one_input, one_result in zip(input, result):
1428 seq = [self.id2token[i.item()] for i in one_result]
1429 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1431 sum_nb_errors += 0 if nb_errors == 0 else 1
1433 gt_seq = [self.id2token[i.item()] for i in one_input]
1434 _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1435 gt_prog = " ".join([str(x) for x in gt_prog])
1436 prog = " ".join([str(x) for x in prog])
1437 comment = "*" if nb_errors == 0 else "-"
1438 logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1439 for start_stack, target_stack, result_stack, correct in stacks:
1440 comment = "*" if correct else "-"
1441 start_stack = " ".join([str(x) for x in start_stack])
1442 target_stack = " ".join([str(x) for x in target_stack])
1443 result_stack = " ".join([str(x) for x in result_stack])
1445 f" {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1449 return sum_nb_total, sum_nb_errors
1451 # --------------------------------------------------------------------
1452 def compute_nb_errors_output(input, nb_to_log=0):
1453 result = input.clone()
1454 k = torch.arange(result.size(1), device=result.device)[None, :]
1456 ((result == self.t_output) * k).max(dim=1, keepdim=True).values
1459 ((result == self.t_prog) * k).max(dim=1, keepdim=True).values
1461 ar_mask = (k > last_output_idx).long() * (k < first_prog_idx).long()
1462 result = (1 - ar_mask) * result + ar_mask * self.t_nul
1464 masked_inplace_autoregression(
1469 deterministic_synthesis,
1473 sum_nb_total, sum_nb_errors = 0, 0
1474 for one_input, one_result, i, j in zip(
1475 input, result, last_output_idx, first_prog_idx
1477 seq = [self.id2token[i.item()] for i in one_result]
1479 correct = (one_input - one_result).abs().max() == 0
1480 sum_nb_errors += 0 if correct else 1
1483 self.id2token[i.item()] for i in one_result[i : j + 1]
1486 self.id2token[i.item()] for i in one_input[i : j + 1]
1488 comment = "*" if correct else "-"
1489 result_stack = " ".join([str(x) for x in result_stack])
1490 target_stack = " ".join([str(x) for x in target_stack])
1492 f"output_test {comment} [{target_stack}] PREDICTED [{result_stack}]"
1496 return sum_nb_total, sum_nb_errors
1498 # --------------------------------------------------------------------
1500 if not self.no_prog:
1501 test_nb_total, test_nb_errors = compute_nb_errors_prog(
1502 self.test_input[:1000].to(self.device), nb_to_log=10
1506 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}%"
1509 logger(f"main_test_accuracy {n_epoch} {1-test_nb_errors/test_nb_total}")
1511 test_nb_total, test_nb_errors = compute_nb_errors_output(
1512 self.test_input[:1000].to(self.device), nb_to_log=10
1516 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}%"
1519 if save_attention_image is None:
1520 logger("no save_attention_image (is pycairo installed?)")
1522 ns = torch.randint(self.test_input.size(0), (1,)).item()
1523 input = self.test_input[ns : ns + 1].clone()
1524 last = (input != self.t_nul).max(0).values.nonzero().max() + 3
1525 input = input[:, :last].to(self.device)
1527 with torch.autograd.no_grad():
1530 model.record_attention(True)
1531 model(BracketedSequence(input))
1533 ram = model.retrieve_attention()
1534 model.record_attention(False)
1536 tokens_output = [self.id2token[i.item()] for i in input[0]]
1537 tokens_input = ["n/a"] + tokens_output[:-1]
1538 for n_head in range(ram[0].size(1)):
1539 filename = os.path.join(
1540 result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
1542 attention_matrices = [m[0, n_head] for m in ram]
1543 save_attention_image(
1549 # min_total_attention=0.9,
1553 logger(f"wrote {filename}")
1556 ######################################################################
1563 def tensorize(self, sequences):
1564 len_max = max([len(x) for x in sequences])
1569 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1586 device=torch.device("cpu"),
1590 self.batch_size = batch_size
1591 self.device = device
1593 train_sequences = expr.generate_sequences(
1595 nb_variables=nb_variables,
1596 length=sequence_length,
1597 operand_max=operand_max,
1598 result_max=result_max,
1601 test_sequences = expr.generate_sequences(
1603 nb_variables=nb_variables,
1604 length=sequence_length,
1605 operand_max=operand_max,
1606 result_max=result_max,
1609 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1612 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1613 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1615 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1617 self.train_input = self.tensorize(train_sequences)
1618 self.test_input = self.tensorize(test_sequences)
1620 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1622 def batches(self, split="train", nb_to_use=-1, desc=None):
1623 assert split in {"train", "test"}
1624 input = self.train_input if split == "train" else self.test_input
1626 input = input[:nb_to_use]
1628 desc = f"epoch-{split}"
1629 for batch in tqdm.tqdm(
1630 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1632 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1633 batch = batch[:, :last]
1636 def vocabulary_size(self):
1637 return self.nb_codes
1639 def seq2str(self, s):
1640 return "".join([self.id2char[k.item()] for k in s])
1642 def produce_results(
1648 deterministic_synthesis,
1651 def compute_nb_correct(input):
1652 result = input.clone()
1653 s = (result == self.space).long()
1654 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1655 result = (1 - ar_mask) * result + ar_mask * self.filler
1656 masked_inplace_autoregression(
1661 deterministic_synthesis,
1665 nb_total = input.size(0)
1666 nb_correct = (input == result).long().min(1).values.sum()
1668 #######################################################################
1669 # Comput predicted vs. true variable values
1671 nb_delta = torch.zeros(5, dtype=torch.int64)
1674 values_input = expr.extract_results([self.seq2str(s) for s in input])
1675 values_result = expr.extract_results([self.seq2str(s) for s in result])
1677 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1679 with open(filename, "w") as f:
1680 for i, r in zip(values_input, values_result):
1681 for n, vi in i.items():
1683 f.write(f"{vi} {-1 if vr is None else vr}\n")
1685 if vr is None or vr < 0:
1689 if d >= nb_delta.size(0):
1694 ######################################################################
1696 return nb_total, nb_correct, nb_delta, nb_missed
1703 ) = compute_nb_correct(self.test_input[:10000])
1706 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}%"
1709 logger(f"main_test_accuracy {n_epoch} {test_nb_correct/test_nb_total}")
1711 nb_total = test_nb_delta.sum() + test_nb_missed
1712 for d in range(test_nb_delta.size(0)):
1714 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1717 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1720 ##############################################################
1721 # Log a few generated sequences
1722 if input_file is None:
1723 input = self.test_input[:10]
1725 with open(input_file, "r") as f:
1726 sequences = [e.strip() for e in f.readlines()]
1727 sequences = [s + " " + "#" * 50 for s in sequences]
1728 input = self.tensorize(sequences)
1730 result = input.clone()
1731 s = (result == self.space).long()
1732 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1733 result = (1 - ar_mask) * result + ar_mask * self.filler
1735 for n in range(result.size(0)):
1736 logger(f"test_before {self.seq2str(result[n])}")
1738 masked_inplace_autoregression(
1743 deterministic_synthesis,
1747 correct = (1 - ar_mask) * self.space + ar_mask * input
1748 for n in range(result.size(0)):
1749 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1750 logger(f"test_after {self.seq2str(result[n])} {comment}")
1751 logger(f"truth {self.seq2str(correct[n])}")
1752 ##############################################################
1755 ######################################################################
1761 # Make a tensor from a list of strings
1762 def str2tensor(self, descr):
1763 token_descr = [s.strip().split(" ") for s in descr]
1764 l = max([len(s) for s in token_descr])
1765 token_descr = [s + ["#"] * (l - len(s)) for s in token_descr]
1766 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
1767 return torch.tensor(id_descr, device=self.device)
1769 # Make a list of strings from a tensor
1770 def tensor2str(self, x):
1771 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
1773 # trim all the tensors in the tuple z to remove as much token from
1774 # left and right in the first tensor. If z is a tuple, all its
1775 # elements are trimed according to the triming for the first
1776 def trim(self, z, token="#"):
1777 n = self.token2id[token]
1778 if type(z) == tuple:
1780 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
1781 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
1782 return tuple([t[:, a:b] for t in z])
1784 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
1785 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
1788 ######################
1798 device=torch.device("cpu"),
1802 self.device = device
1803 self.batch_size = batch_size
1804 self.grid_factory = grid.GridFactory(size=size)
1805 self.fraction_play = fraction_play
1807 if logger is not None:
1809 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
1812 self.train_descr = self.grid_factory.generate_samples(
1813 nb=nb_train_samples,
1814 fraction_play=fraction_play,
1815 progress_bar=lambda r: tqdm.tqdm(r),
1818 self.test_descr = self.grid_factory.generate_samples(
1819 nb=nb_test_samples, fraction_play=0.0, progress_bar=lambda r: tqdm.tqdm(r)
1822 if fraction_play > 0:
1823 self.play_descr = self.grid_factory.generate_samples(
1824 nb=25, fraction_play=1.0, progress_bar=lambda r: tqdm.tqdm(r)
1827 self.play_descr = []
1829 # Build the tokenizer
1831 for d in [self.train_descr, self.test_descr, self.play_descr]:
1833 for t in s.strip().split(" "):
1835 # make this set a sorted list to get the same tensors given
1837 tokens = list(tokens)
1839 tokens = ["#"] + tokens
1840 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
1841 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
1842 self.t_nul = self.token2id["#"]
1843 self.t_true = self.token2id["true"]
1844 self.t_false = self.token2id["false"]
1845 # self.t_pipe = self.token2id["|"]
1847 # Tokenize the train and test sets
1848 self.train_input = self.str2tensor(self.train_descr)
1849 self.test_input = self.str2tensor(self.test_descr)
1851 None if len(self.play_descr) == 0 else self.str2tensor(self.play_descr)
1854 def batches(self, split="train", nb_to_use=-1, desc=None):
1855 assert split in {"train", "test"}
1856 input = self.train_input if split == "train" else self.test_input
1857 for batch in tqdm.tqdm(
1858 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
1860 yield self.trim(batch)
1862 def vocabulary_size(self):
1863 return len(self.token2id)
1865 def produce_results(
1866 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1868 correct = self.test_input[:1000]
1869 result = correct.clone()
1870 ar_mask = torch.logical_or(result == self.t_true, result == self.t_false).long()
1871 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
1873 logger(f"----------------------------------------------------------")
1875 for e in self.tensor2str(result[:10]):
1876 logger(f"test_before {e}")
1878 masked_inplace_autoregression(
1883 deterministic_synthesis,
1887 logger(f"----------------------------------------------------------")
1889 for e in self.tensor2str(result[:10]):
1890 logger(f"test_after {e}")
1892 logger(f"----------------------------------------------------------")
1894 nb_total = ar_mask.sum().item()
1895 nb_correct = ((correct == result).long() * ar_mask).sum().item()
1897 logger(f"test_performance {n_epoch} {nb_total=} {nb_correct=}")
1898 logger(f"main_test_accuracy {n_epoch} {nb_correct / nb_total}")
1900 if self.play_input is not None:
1901 result = self.play_input.clone()
1902 ar_mask = (result == self.t_pipe).long().cumsum(dim=1).clamp(max=1)
1903 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
1905 logger(f"----------------------------------------------------------")
1907 for e in self.tensor2str(result[:10]):
1908 logger(f"play_before {e}")
1910 masked_inplace_autoregression(
1915 deterministic_synthesis,
1919 logger(f"----------------------------------------------------------")
1921 for e in self.tensor2str(result[:10]):
1922 logger(f"play_after {e}")
1924 logger(f"----------------------------------------------------------")
1927 ######################################################################
1933 ######################
1942 device=torch.device("cpu"),
1946 self.device = device
1947 self.batch_size = batch_size
1948 self.nb_samples_per_mlp = 256
1950 if logger is not None:
1952 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
1955 seq, q_test_set, test_error = qmlp.generate_sequence_and_test_set(
1956 nb_mlps=nb_train_samples + nb_test_samples,
1957 nb_samples=self.nb_samples_per_mlp,
1961 nb_mlps_per_batch=1024,
1964 self.train_input = seq[:nb_train_samples]
1965 self.train_q_test_set = q_test_set[:nb_train_samples]
1966 self.train_ref_test_errors = test_error[:nb_train_samples]
1967 self.test_input = seq[nb_train_samples:]
1968 self.test_q_test_set = q_test_set[nb_train_samples:]
1969 self.test_ref_test_errors = test_error[nb_train_samples:]
1971 filename = os.path.join(result_dir, f"train_errors_ref.dat")
1972 with open(filename, "w") as f:
1973 for e in self.train_ref_test_errors:
1976 filename = os.path.join(result_dir, f"test_errors_ref.dat")
1977 with open(filename, "w") as f:
1978 for e in self.test_ref_test_errors:
1981 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1983 def batches(self, split="train", nb_to_use=-1, desc=None):
1984 assert split in {"train", "test"}
1985 input = self.train_input if split == "train" else self.test_input
1986 for batch in tqdm.tqdm(
1987 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
1991 def vocabulary_size(self):
1992 return self.nb_codes
1994 def produce_results(
1995 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1997 correct = self.test_input[:1000]
1998 result = correct.clone()
2000 torch.arange(result.size(1), device=result.device)
2001 > self.nb_samples_per_mlp * 3 + 1
2003 ar_mask = ar_mask.expand_as(result)
2004 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
2006 masked_inplace_autoregression(
2011 deterministic_synthesis,
2015 q_train_set = result[:, : self.nb_samples_per_mlp * 3]
2016 q_params = result[:, self.nb_samples_per_mlp * 3 + 1 :]
2017 error_test = qmlp.evaluate_q_params(q_params, self.test_q_test_set)
2019 filename = os.path.join(result_dir, f"test_errors_{n_epoch:04d}.dat")
2020 with open(filename, "w") as f:
2021 for e in error_test:
2025 ######################################################################
2042 device=torch.device("cpu"),
2046 self.batch_size = batch_size
2047 self.device = device
2049 self.world = greed.GreedWorld(height, width, T, nb_walls, nb_coins)
2051 states, actions, rewards = self.world.generate_episodes(
2052 nb_train_samples + nb_test_samples
2054 seq = self.world.episodes2seq(states, actions, rewards)
2055 self.train_input = seq[:nb_train_samples].to(self.device)
2056 self.test_input = seq[nb_train_samples:].to(self.device)
2058 def wipe_lookahead_rewards(self, batch):
2059 t = torch.arange(batch.size(1), device=batch.device)[None, :]
2060 u = torch.randint(batch.size(1), (batch.size(0), 1), device=batch.device)
2061 lr_mask = (t <= u).long() * (
2062 t % self.world.it_len == self.world.index_lookahead_reward
2066 lr_mask * self.world.lookahead_reward2code(greed.REWARD_UNKNOWN)
2067 + (1 - lr_mask) * batch
2070 def batches(self, split="train", nb_to_use=-1, desc=None):
2071 assert split in {"train", "test"}
2072 input = self.train_input if split == "train" else self.test_input
2074 input = input[:nb_to_use]
2076 desc = f"epoch-{split}"
2077 for batch in tqdm.tqdm(
2078 input.split(self.batch_size), dynamic_ncols=True, desc=desc
2080 yield self.wipe_lookahead_rewards(batch)
2082 def vocabulary_size(self):
2083 return self.world.nb_codes
2085 def thinking_autoregression(
2086 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
2090 def ar(result, ar_mask, logit_biases=None):
2091 ar_mask = ar_mask.expand_as(result)
2092 result *= 1 - ar_mask
2093 masked_inplace_autoregression(
2098 deterministic_synthesis=deterministic_synthesis,
2099 logit_biases=logit_biases,
2101 progress_bar_desc=None,
2103 warnings.warn("keeping thinking snapshots", RuntimeWarning)
2104 snapshots.append(result[:100].detach().clone())
2106 # Generate iteration after iteration
2108 result = self.test_input[:250].clone()
2109 # Erase all the content but that of the first iteration
2110 result[:, self.world.it_len :] = -1
2111 # Set the lookahead_reward of the firs to UNKNOWN
2112 result[:, self.world.index_lookahead_reward] = self.world.lookahead_reward2code(
2113 greed.REWARD_UNKNOWN
2116 t = torch.arange(result.size(1), device=result.device)[None, :]
2119 range(0, result.size(1), self.world.it_len),
2122 # Generate the next state but keep the initial one, the
2123 # lookahead_reward of previous iterations are set to
2127 :, u + self.world.index_lookahead_reward
2128 ] = self.world.lookahead_reward2code(greed.REWARD_UNKNOWN)
2129 ar_mask = (t >= u + self.world.index_states).long() * (
2130 t < u + self.world.index_states + self.world.state_len
2134 # Generate the action and reward with lookahead_reward to +1
2136 :, u + self.world.index_lookahead_reward
2137 ] = self.world.lookahead_reward2code(greed.REWARD_PLUS)
2138 ar_mask = (t >= u + self.world.index_reward).long() * (
2139 t <= u + self.world.index_action
2143 # Set the lookahead_reward to UNKNOWN for the next iterations
2145 :, u + self.world.index_lookahead_reward
2146 ] = self.world.lookahead_reward2code(greed.REWARD_UNKNOWN)
2148 filename = os.path.join(result_dir, f"test_thinking_compute_{n_epoch:04d}.txt")
2149 with open(filename, "w") as f:
2150 for n in range(snapshots[0].size(0)):
2152 lr, s, a, r = self.world.seq2episodes(
2155 str = self.world.episodes2str(
2156 lr, s, a, r, unicode=True, ansi_colors=True
2161 # Saving the generated sequences
2163 lr, s, a, r = self.world.seq2episodes(result)
2164 str = self.world.episodes2str(lr, s, a, r, unicode=True, ansi_colors=True)
2166 filename = os.path.join(result_dir, f"test_thinking_seq_{n_epoch:04d}.txt")
2167 with open(filename, "w") as f:
2169 logger(f"wrote {filename}")
2171 def produce_results(
2172 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
2174 result = self.wipe_lookahead_rewards(self.test_input[:250].clone())
2176 # Saving the ground truth
2178 lr, s, a, r = self.world.seq2episodes(
2181 str = self.world.episodes2str(lr, s, a, r, unicode=True, ansi_colors=True)
2183 filename = os.path.join(result_dir, f"test_true_seq_{n_epoch:04d}.txt")
2184 with open(filename, "w") as f:
2186 logger(f"wrote {filename}")
2188 # Re-generating from the first frame
2191 torch.arange(result.size(1), device=result.device) >= self.world.it_len
2193 ar_mask = ar_mask.expand_as(result)
2194 result *= 1 - ar_mask # paraaaaanoiaaaaaaa
2196 masked_inplace_autoregression(
2201 deterministic_synthesis,
2205 # Saving the generated sequences
2207 lr, s, a, r = self.world.seq2episodes(
2210 str = self.world.episodes2str(lr, s, a, r, unicode=True, ansi_colors=True)
2212 filename = os.path.join(result_dir, f"test_seq_{n_epoch:04d}.txt")
2213 with open(filename, "w") as f:
2215 logger(f"wrote {filename}")
2217 self.thinking_autoregression(
2218 n_epoch, model, result_dir, logger, deterministic_synthesis, nmax
2222 ######################################################################