5 import torch, torchvision
8 from torch.nn import functional as F
10 ######################################################################
13 def masked_inplace_autoregression(
18 deterministic_synthesis,
19 forbidden_tokens=None,
20 progress_bar_desc="autoregression",
21 device=torch.device("cpu"),
23 assert input.size() == ar_mask.size()
25 batches = zip(input.split(batch_size), ar_mask.split(batch_size))
27 if progress_bar_desc is not None:
31 desc=progress_bar_desc,
32 # total=input.size(0) // batch_size,
35 with torch.autograd.no_grad():
39 for input, ar_mask in batches:
40 model.masked_inplace_autoregression(
41 input, ar_mask, forbidden_tokens, deterministic_synthesis
47 ######################################################################
51 def batches(self, split="train"):
54 def vocabulary_size(self):
58 self, n_epoch, model, result_dir, logger, deterministic_synthesis
63 ######################################################################
67 def generate_sequences(self, nb):
70 def seq2str(self, seq):
71 return "[NOT IMPLEMENTED]"
77 class ProblemLevel0(Problem):
78 def __init__(self, nb_sentences=100, len_prompt=5, len_result=5):
79 self.seq = torch.randint(10, (nb_seq, len_prompt + 1 + len_result))
80 self.seq[:, len_prompt] = 10
82 def generate_sequences(self, nb):
83 sequences = self.seq[torch.randint(self.seq.size(0), (nb,))]
84 ar_mask = (sequences == 10).long()
85 ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
86 return sequences, ar_mask
89 class ProblemLevel1(Problem):
90 def __init__(self, nb_operators=100, len_source=5, len_result=8):
91 self.len_source = len_source
92 self.len_result = len_result
93 self.len_nb_operator = int(math.log(nb_operators) / math.log(10)) + 1
94 self.operators = F.one_hot(
95 torch.rand(nb_operators, len_result, len_source).argmax(-1),
96 num_classes=len_source,
99 def generate_sequences(self, nb):
100 nb_operators = torch.randint(self.operators.size(0), (nb,))
101 operators = self.operators[nb_operators]
103 nb_operators[:, None]
104 // 10 ** torch.arange(self.len_nb_operator - 1, -1, -1)
106 marker1 = torch.full((nb, 1), 10)
107 source = torch.randint(10, (nb, self.len_source))
108 marker2 = torch.full((nb, 1), 11)
109 result = operators.bmm(source[:, :, None]).squeeze(-1)
110 print(f"{nb_operators.dtype=} {marker1.dtype=}")
111 sequences = torch.cat((nb_operators, marker1, source, marker2, result), 1)
112 print(f"{sequences.size()=}")
113 ar_mask = (sequences == 11).long()
114 ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
115 return sequences, ar_mask
117 def seq2str(self, seq):
118 return "".join("0123456789|>"[x.item()] for x in seq)
121 class ProblemLevel2(Problem):
122 def __init__(self, len_source=5, len_result=8):
123 self.len_source = len_source
124 self.len_result = len_result
126 def generate_sequences(self, nb):
127 operators = F.one_hot(
128 torch.rand(nb, self.len_result, self.len_source).argmax(-1),
129 num_classes=self.len_source,
131 source1 = torch.randint(10, (nb, self.len_source))
132 marker1 = torch.full((nb, 1), 10)
133 result1 = operators.bmm(source1[:, :, None]).squeeze(-1)
134 marker2 = torch.full((nb, 1), 11)
135 source2 = torch.randint(10, (nb, self.len_source))
136 marker3 = torch.full((nb, 1), 12)
137 result2 = operators.bmm(source2[:, :, None]).squeeze(-1)
139 sequences = torch.cat(
140 (source1, marker1, result1, marker2, source2, marker3, result2), 1
142 ar_mask = (sequences == 12).long()
143 ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
144 return sequences, ar_mask
146 def seq2str(self, seq):
147 return "".join("0123456789>|~"[x.item()] for x in seq)
153 class ProblemAddition(Problem):
154 def __init__(self, nb_digits=10, zero_padded=False, inverted_result=False):
155 self.nb_digits = nb_digits
156 self.zero_padded = zero_padded
157 self.inverted_result = inverted_result
158 self.char2id = dict([(c, n) for n, c in enumerate("0123456789+=$")])
159 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
161 def tensorize(self, strings):
162 len_max = max([len(x) for x in strings])
167 [self.char2id[c] for c in s + "$" * (len_max - len(s))]
175 def generate_sequences(self, nb):
178 a, b = torch.randint(10**self.nb_digits, (2,))
180 a, b, c = str(a.item()), str(b.item()), str(c.item())
182 a = "0" * (self.nb_digits - len(a)) + a
183 b = "0" * (self.nb_digits - len(b)) + b
184 c = "0" * (self.nb_digits + 1 - len(c)) + c
185 if self.inverted_result:
187 sequences.append(f"{a}+{b}={c}$")
189 sequences = self.tensorize(sequences)
190 ar_mask = (sequences == self.char2id["="]).long()
191 ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
192 return sequences, ar_mask
194 def seq2str(self, seq):
195 return "".join(self.id2char[x.item()] for x in seq)
198 # class ProblemUnion(Problem):
199 # problems = [ProblemByheart()]
200 # nb_common_codes = 100
202 # def generate_sequences(nb_samples):
203 # problem_indexes = torch.randint(len(problems), (nb_samples,))
204 # nb_samples_per_problem = torch.one_hot(problem_indexes).sum(0)
205 # print(f"{nb_samples_per_problem}")
207 # for nb, p in zip(nb_samples_per_problem, problems):
208 # all_seq.append(p.generate_sequences(nb_samples_per_problem[nb]))
211 # for strain, stest in zip(train_seq, test_seq):
212 # s = torch.cat((strain, stest), 0)
225 device=torch.device("cpu"),
230 self.batch_size = batch_size
232 self.problem = problem
234 self.train_input, self.train_ar_mask = self.problem.generate_sequences(
237 self.test_input, self.test_ar_mask = self.problem.generate_sequences(
241 self.train_input, self.train_ar_mask = self.train_input.to(
243 ), self.train_ar_mask.to(device)
244 self.test_input, self.test_ar_mask = self.test_input.to(
246 ), self.test_ar_mask.to(device)
248 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
250 # A bit of paranoia never hurts
252 self.nb_codes <= max_nb_codes
253 and self.train_input.min() >= 0
254 and self.test_input.min() >= 0
255 and tuple(self.train_ar_mask.unique()) == (0, 1)
256 and tuple(self.test_ar_mask.unique()) == (0, 1)
259 def batches(self, split="train", nb_to_use=-1, desc=None):
260 assert split in {"train", "test"}
261 input = self.train_input if split == "train" else self.test_input
263 input = input[:nb_to_use]
265 desc = f"epoch-{split}"
266 for batch in tqdm.tqdm(
267 input.split(self.batch_size), dynamic_ncols=True, desc=desc
271 def vocabulary_size(self):
275 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
277 def compute_accuracy(input, ar_mask, logger=None):
278 input, ar_mask = input[:nmax], ar_mask[:nmax]
279 result = input.clone() * (1 - ar_mask)
281 masked_inplace_autoregression(
286 deterministic_synthesis,
287 progress_bar_desc=None,
291 if logger is not None:
292 for sp, st in zip(result[:10], input[:10]):
294 f"test_sequences {n_epoch} prediction {self.problem.seq2str(sp)}"
297 f" {n_epoch} ground truth {self.problem.seq2str(st)}"
300 nb_total = ar_mask.sum().item()
301 nb_correct = ((result == input).long() * ar_mask).sum().item()
303 return nb_total, nb_correct
305 train_nb_total, train_nb_correct = compute_accuracy(
306 self.train_input, self.train_ar_mask
310 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}%"
313 test_nb_total, test_nb_correct = compute_accuracy(
314 self.test_input, self.test_ar_mask, logger
318 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}%"
322 ######################################################################
327 class PicoCLVR(Task):
328 # Make a tensor from a list of strings
329 def tensorize(self, descr):
330 token_descr = [s.strip().split(" ") for s in descr]
331 l = max([len(s) for s in token_descr])
332 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
333 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
334 return torch.tensor(id_descr, device=self.device)
336 # Make a list of strings from a tensor
337 def detensorize(self, x):
338 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
340 # trim all the tensors in the tuple z to remove as much token from
341 # left and right in the first tensor. If z is a tuple, all its
342 # elements are trimed according to the triming for the first
343 def trim(self, z, token="<nul>"):
344 n = self.token2id[token]
347 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
348 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
349 return tuple([t[:, a:b] for t in z])
351 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
352 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
355 ######################
366 device=torch.device("cpu"),
372 def generate_descr(nb, cache_suffix, pruner):
373 return picoclvr.generate(
383 self.batch_size = batch_size
385 self.pruner_train = pruner_train
386 self.pruner_eval = pruner_eval
388 if logger is not None:
390 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
393 self.train_descr = generate_descr(
394 nb_train_samples, "train", pruner=self.pruner_train
396 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
398 # Build the tokenizer
399 tokens = {"<nul>", "<img>"}
400 for d in [self.train_descr, self.test_descr]:
402 for t in s.strip().split(" "):
404 # make this set a sorted list to get the same tensors given
406 tokens = list(tokens)
408 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
409 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
410 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
412 # Tokenize the train and test sets
413 self.train_input = self.tensorize(self.train_descr)
414 self.test_input = self.tensorize(self.test_descr)
416 def batches(self, split="train"):
417 assert split in {"train", "test"}
418 input = self.train_input if split == "train" else self.test_input
419 for batch in tqdm.tqdm(
420 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
422 yield self.trim(batch)
424 def vocabulary_size(self):
425 return len(self.token2id)
427 def compute_missing_properties(
428 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
430 acc_nb_requested_properties = []
431 acc_nb_missing_properties = []
434 for input in tqdm.tqdm(
435 self.test_input.split(self.batch_size),
437 desc=f"test-properties",
439 result = input.clone()
440 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
441 result = (1 - ar_mask) * result + ar_mask * self.t_nul
442 masked_inplace_autoregression(
447 deterministic_synthesis,
448 progress_bar_desc=None,
452 result_descr = self.detensorize(result)
453 np = picoclvr.nb_properties(
459 nb_requested_properties, _, nb_missing_properties = zip(*np)
460 acc_nb_requested_properties += nb_requested_properties
461 acc_nb_missing_properties += nb_missing_properties
462 acc_nb_results += len(result_descr)
464 nb_requested_properties = sum(acc_nb_requested_properties)
465 nb_missing_properties = sum(acc_nb_missing_properties)
467 prefix = "" if pruner is None else "pruned_"
468 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
470 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
473 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
476 ######################################################################
479 self, n_epoch, model, result_dir, logger, deterministic_synthesis
481 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
483 if self.pruner_eval is not None:
484 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
486 nb_tokens_to_generate = self.height * self.width + 3
491 for primer_descr in [
492 "red above green <sep> green top <sep> blue right of red",
493 "there is red <sep> there is yellow <sep> there is blue",
494 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
495 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
497 primer += [primer_descr + " <img>"] * nb_per_primer
499 result = self.tensorize(primer)
500 fill = result.new_full(
501 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
503 result = torch.cat((result, fill), 1)
504 ar_mask = (result == self.t_nul).long()
505 masked_inplace_autoregression(
510 deterministic_synthesis,
513 result_descr = self.detensorize(result)
515 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
517 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
518 acc_nb_results = len(result_descr)
520 nb_requested_properties = sum(acc_nb_requested_properties)
521 nb_missing_properties = sum(acc_nb_missing_properties)
524 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
526 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
529 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
532 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
536 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
540 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
546 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
547 torchvision.utils.save_image(
548 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
550 logger(f"wrote {image_name}")
553 ######################################################################
558 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
562 self.nb_train_samples = (nb_train_samples,)
563 self.nb_test_samples = (nb_test_samples,)
564 self.batch_size = batch_size
566 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
567 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
568 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
569 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
571 def batches(self, split="train", nb_to_use=-1, desc=None):
572 assert split in {"train", "test"}
573 input = self.train_input if split == "train" else self.test_input
575 input = input[:nb_to_use]
577 desc = f"epoch-{split}"
578 for batch in tqdm.tqdm(
579 input.split(self.batch_size), dynamic_ncols=True, desc=desc
583 def vocabulary_size(self):
587 self, n_epoch, model, result_dir, logger, deterministic_synthesis
589 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
590 ar_mask = torch.full_like(results, 1)
591 masked_inplace_autoregression(
596 deterministic_synthesis,
599 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
600 torchvision.utils.save_image(
601 1 - results.reshape(-1, 1, 28, 28) / 255.0,
606 logger(f"wrote {image_name}")
609 ######################################################################
615 def map2seq(self, *m):
616 return torch.cat([x.flatten(1) for x in m], 1)
618 def seq2map(self, s):
619 s = s.reshape(s.size(0), -1, self.height, self.width)
620 return (s[:, k] for k in range(s.size(1)))
630 device=torch.device("cpu"),
634 self.batch_size = batch_size
639 train_mazes, train_paths, _ = maze.create_maze_data(
644 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
646 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
648 test_mazes, test_paths, _ = maze.create_maze_data(
653 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
655 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
657 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
659 def batches(self, split="train", nb_to_use=-1, desc=None):
660 assert split in {"train", "test"}
661 input = self.train_input if split == "train" else self.test_input
663 input = input[:nb_to_use]
665 desc = f"epoch-{split}"
666 for batch in tqdm.tqdm(
667 input.split(self.batch_size), dynamic_ncols=True, desc=desc
671 def vocabulary_size(self):
675 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
677 nb_total, nb_correct = 0, 0
679 self.width * self.height,
680 self.width * self.height,
685 for input in self.batches(split, nb_to_use):
686 result = input.clone()
687 ar_mask = result.new_zeros(result.size())
688 ar_mask[:, self.height * self.width :] = 1
689 result *= 1 - ar_mask
690 masked_inplace_autoregression(
695 deterministic_synthesis,
696 progress_bar_desc=None,
699 mazes, paths = self.seq2map(result)
700 path_correctness = maze.path_correctness(mazes, paths)
701 nb_correct += path_correctness.long().sum()
702 nb_total += mazes.size(0)
704 optimal_path_lengths = (
705 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
707 predicted_path_lengths = (
708 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
710 optimal_path_lengths = optimal_path_lengths[path_correctness]
711 predicted_path_lengths = predicted_path_lengths[path_correctness]
712 count[optimal_path_lengths, predicted_path_lengths] += 1
718 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
721 return nb_total, nb_correct, count
724 self, n_epoch, model, result_dir, logger, deterministic_synthesis
726 train_nb_total, train_nb_correct, count = self.compute_error(
730 deterministic_synthesis=deterministic_synthesis,
733 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}%"
736 test_nb_total, test_nb_correct, count = self.compute_error(
740 deterministic_synthesis=deterministic_synthesis,
743 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}%"
746 if count is not None:
747 proportion_optimal = count.diagonal().sum().float() / count.sum()
748 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
750 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
752 for i in range(count.size(0)):
753 for j in range(count.size(1)):
754 eol = " " if j < count.size(1) - 1 else "\n"
755 f.write(f"{count[i,j]}{eol}")
757 input = self.test_input[:48]
758 result = input.clone()
759 ar_mask = result.new_zeros(result.size())
760 ar_mask[:, self.height * self.width :] = 1
761 result *= 1 - ar_mask
762 masked_inplace_autoregression(
767 deterministic_synthesis,
771 mazes, paths = self.seq2map(input)
772 _, predicted_paths = self.seq2map(result)
774 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
779 predicted_paths=predicted_paths,
780 path_correct=maze.path_correctness(mazes, predicted_paths),
781 path_optimal=maze.path_optimality(paths, predicted_paths),
783 logger(f"wrote {filename}")
786 ######################################################################
803 device=torch.device("cpu"),
807 self.batch_size = batch_size
811 self.prompt_length = prompt_length
813 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
822 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
832 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
834 def batches(self, split="train", nb_to_use=-1, desc=None):
835 assert split in {"train", "test"}
836 input = self.train_input if split == "train" else self.test_input
838 input = input[:nb_to_use]
840 desc = f"epoch-{split}"
841 for batch in tqdm.tqdm(
842 input.split(self.batch_size), dynamic_ncols=True, desc=desc
846 def vocabulary_size(self):
850 self, n_epoch, model, result_dir, logger, deterministic_synthesis
852 def compute_nb_correct(input, prior_visits):
853 result = input.clone()
854 i = torch.arange(result.size(1), device=result.device)[None, :]
856 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
860 result *= 1 - ar_mask
862 masked_inplace_autoregression(
867 deterministic_synthesis,
871 nb_total = ((prior_visits > 0) * ar_mask).sum()
873 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
875 return nb_total, nb_correct
877 test_nb_total, test_nb_correct = compute_nb_correct(
878 self.test_input[:1000], self.test_prior_visits[:1000]
882 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}%"
886 ######################################################################
902 fraction_values_for_train=None,
903 device=torch.device("cpu"),
907 self.batch_size = batch_size
908 self.nb_steps = nb_steps
909 self.nb_stacks = nb_stacks
910 self.nb_digits = nb_digits
913 if fraction_values_for_train is None:
914 values_for_train = None
915 values_for_test = None
917 all = torch.randperm(10**nb_digits)
918 nb_for_train = int(all.size(0) * fraction_values_for_train)
919 values_for_train = all[:nb_for_train]
920 values_for_test = all[nb_for_train:]
922 self.train_input, self.train_stack_counts = stack.generate_sequences(
931 self.test_input, self.test_stack_counts = stack.generate_sequences(
940 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
941 counts = self.test_stack_counts.flatten()[i.flatten()]
942 counts = F.one_hot(counts).sum(0)
943 logger(f"test_pop_stack_counts {counts}")
945 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
947 def batches(self, split="train", nb_to_use=-1, desc=None):
948 assert split in {"train", "test"}
949 input = self.train_input if split == "train" else self.test_input
951 input = input[:nb_to_use]
953 desc = f"epoch-{split}"
954 for batch in tqdm.tqdm(
955 input.split(self.batch_size), dynamic_ncols=True, desc=desc
959 def vocabulary_size(self):
963 self, n_epoch, model, result_dir, logger, deterministic_synthesis
965 def compute_nb_correct(input):
966 result = input.clone()
967 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
968 ar_mask = (result != input).long()
969 masked_inplace_autoregression(
974 deterministic_synthesis,
978 errors = ((result != input).long() * ar_mask).reshape(
979 -1, 1 + self.nb_digits
981 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
983 nb_total = ar_mask.max(1).values.sum()
984 nb_correct = nb_total - errors.max(1).values.sum()
986 return nb_total, nb_correct
988 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
991 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}%"
994 ##############################################################
995 # Log a few generated sequences
996 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
997 result = input.clone()
998 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
999 ar_mask = (result != input).long()
1001 # for n in range(result.size(0)):
1003 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1006 masked_inplace_autoregression(
1011 deterministic_synthesis,
1015 for n in range(result.size(0)):
1017 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1019 ##############################################################
1022 ######################################################################
1029 def tensorize(self, sequences):
1030 len_max = max([len(x) for x in sequences])
1035 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1052 device=torch.device("cpu"),
1056 self.batch_size = batch_size
1057 self.device = device
1059 train_sequences = expr.generate_sequences(
1061 nb_variables=nb_variables,
1062 length=sequence_length,
1063 operand_max=operand_max,
1064 result_max=result_max,
1067 test_sequences = expr.generate_sequences(
1069 nb_variables=nb_variables,
1070 length=sequence_length,
1071 operand_max=operand_max,
1072 result_max=result_max,
1075 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1078 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1079 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1081 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1083 self.train_input = self.tensorize(train_sequences)
1084 self.test_input = self.tensorize(test_sequences)
1086 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1088 def batches(self, split="train", nb_to_use=-1, desc=None):
1089 assert split in {"train", "test"}
1090 input = self.train_input if split == "train" else self.test_input
1092 input = input[:nb_to_use]
1094 desc = f"epoch-{split}"
1095 for batch in tqdm.tqdm(
1096 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1098 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1099 batch = batch[:, :last]
1102 def vocabulary_size(self):
1103 return self.nb_codes
1105 def seq2str(self, s):
1106 return "".join([self.id2char[k.item()] for k in s])
1108 def produce_results(
1114 deterministic_synthesis,
1117 def compute_nb_correct(input):
1118 result = input.clone()
1119 s = (result == self.space).long()
1120 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1121 result = (1 - ar_mask) * result + ar_mask * self.filler
1122 masked_inplace_autoregression(
1127 deterministic_synthesis,
1131 nb_total = input.size(0)
1132 nb_correct = (input == result).long().min(1).values.sum()
1134 #######################################################################
1135 # Comput predicted vs. true variable values
1137 nb_delta = torch.zeros(5, dtype=torch.int64)
1140 values_input = expr.extract_results([self.seq2str(s) for s in input])
1141 values_result = expr.extract_results([self.seq2str(s) for s in result])
1143 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1145 with open(filename, "w") as f:
1146 for i, r in zip(values_input, values_result):
1147 for n, vi in i.items():
1149 f.write(f"{vi} {-1 if vr is None else vr}\n")
1151 if vr is None or vr < 0:
1155 if d >= nb_delta.size(0):
1160 ######################################################################
1162 return nb_total, nb_correct, nb_delta, nb_missed
1169 ) = compute_nb_correct(self.test_input[:10000])
1172 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}%"
1175 nb_total = test_nb_delta.sum() + test_nb_missed
1176 for d in range(test_nb_delta.size(0)):
1178 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1181 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1184 ##############################################################
1185 # Log a few generated sequences
1186 if input_file is None:
1187 input = self.test_input[:10]
1189 with open(input_file, "r") as f:
1190 sequences = [e.strip() for e in f.readlines()]
1191 sequences = [s + " " + "#" * 50 for s in sequences]
1192 input = self.tensorize(sequences)
1194 result = input.clone()
1195 s = (result == self.space).long()
1196 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1197 result = (1 - ar_mask) * result + ar_mask * self.filler
1199 for n in range(result.size(0)):
1200 logger(f"test_before {self.seq2str(result[n])}")
1202 masked_inplace_autoregression(
1207 deterministic_synthesis,
1211 correct = (1 - ar_mask) * self.space + ar_mask * input
1212 for n in range(result.size(0)):
1213 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1214 logger(f"test_after {self.seq2str(result[n])} {comment}")
1215 logger(f"truth {self.seq2str(correct[n])}")
1216 ##############################################################
1219 ######################################################################
1232 device=torch.device("cpu"),
1233 device_storage=torch.device("cpu"),
1237 self.batch_size = batch_size
1238 self.device = device
1247 ) = world.create_data_and_processors(
1252 nb_epochs=vqae_nb_epochs,
1255 device_storage=device_storage,
1258 train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1259 test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1261 nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1262 nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1264 self.len_frame_seq = train_frame_seq.size(1)
1265 self.len_action_seq = train_action_seq.size(1)
1266 self.nb_codes = nb_frame_codes + nb_action_codes
1268 train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1270 train_action_seq += nb_frame_codes
1271 self.train_input = torch.cat(
1272 (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1275 test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1276 test_action_seq += nb_frame_codes
1277 self.test_input = torch.cat(
1278 (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1281 def batches(self, split="train", nb_to_use=-1, desc=None):
1282 assert split in {"train", "test"}
1283 input = self.train_input if split == "train" else self.test_input
1285 input = input[:nb_to_use]
1287 desc = f"epoch-{split}"
1288 for batch in tqdm.tqdm(
1289 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1291 yield batch.to(self.device)
1293 def vocabulary_size(self):
1294 return self.nb_codes
1296 def produce_results(
1297 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1300 2 * self.len_frame_seq + self.len_action_seq, device=self.device
1303 input = self.test_input[:64].to(self.device)
1304 result = input.clone()
1307 (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1309 result *= 1 - ar_mask
1311 masked_inplace_autoregression(
1316 deterministic_synthesis,
1320 seq_start = input[:, : self.len_frame_seq]
1321 seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1322 seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1325 (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1327 result = result.reshape(-1, result.size(-1))
1329 frames = self.seq2frame(result)
1330 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1331 torchvision.utils.save_image(
1332 frames.float() / (world.Box.nb_rgb_levels - 1),
1338 logger(f"wrote {image_name}")
1341 ######################################################################