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,
101 def generate_sequences(self, nb):
102 nb_operators = torch.randint(self.operators.size(0), (nb,))
103 operators = self.operators[nb_operators]
104 nb_operators = (nb_operators[:, None] // 10 ** torch.arange(self.len_nb_operator-1,-1,-1)) % 10
105 marker1 = torch.full((nb,1),10)
106 source = torch.randint(10, (nb, self.len_source))
107 marker2 = torch.full((nb,1),11)
108 result = operators.bmm(source[:, :, None]).squeeze(-1)
109 print(f"{nb_operators.dtype=} {marker1.dtype=}")
110 sequences = torch.cat((nb_operators, marker1, source,marker2,result),1)
111 print(f"{sequences.size()=}")
112 ar_mask = (sequences == 11).long()
113 ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
114 return sequences, ar_mask
116 def seq2str(self, seq):
117 return "".join("0123456789|>"[x.item()] for x in seq)
123 class ProblemAddition(Problem):
124 def __init__(self, nb_digits=10, zero_padded=False, inverted_result=False):
125 self.nb_digits = nb_digits
126 self.zero_padded = zero_padded
127 self.inverted_result = inverted_result
128 self.char2id = dict([(c, n) for n, c in enumerate("0123456789+=$")])
129 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
131 def tensorize(self, strings):
132 len_max = max([len(x) for x in strings])
137 [self.char2id[c] for c in s + "$" * (len_max - len(s))]
145 def generate_sequences(self, nb):
148 a, b = torch.randint(10**self.nb_digits, (2,))
150 a, b, c = str(a.item()), str(b.item()), str(c.item())
152 a = "0" * (self.nb_digits - len(a)) + a
153 b = "0" * (self.nb_digits - len(b)) + b
154 c = "0" * (self.nb_digits + 1 - len(c)) + c
155 if self.inverted_result:
157 sequences.append(f"{a}+{b}={c}$")
159 sequences = self.tensorize(sequences)
160 ar_mask = (sequences == self.char2id["="]).long()
161 ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
162 return sequences, ar_mask
164 def seq2str(self, seq):
165 return "".join(self.id2char[x.item()] for x in seq)
168 # class ProblemUnion(Problem):
169 # problems = [ProblemByheart()]
170 # nb_common_codes = 100
172 # def generate_sequences(nb_samples):
173 # problem_indexes = torch.randint(len(problems), (nb_samples,))
174 # nb_samples_per_problem = torch.one_hot(problem_indexes).sum(0)
175 # print(f"{nb_samples_per_problem}")
177 # for nb, p in zip(nb_samples_per_problem, problems):
178 # all_seq.append(p.generate_sequences(nb_samples_per_problem[nb]))
181 # for strain, stest in zip(train_seq, test_seq):
182 # s = torch.cat((strain, stest), 0)
195 device=torch.device("cpu"),
200 self.batch_size = batch_size
202 self.problem = problem
204 self.train_input, self.train_ar_mask = self.problem.generate_sequences(
207 self.test_input, self.test_ar_mask = self.problem.generate_sequences(
211 self.train_input, self.train_ar_mask = self.train_input.to(
213 ), self.train_ar_mask.to(device)
214 self.test_input, self.test_ar_mask = self.test_input.to(
216 ), self.test_ar_mask.to(device)
218 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
220 # A bit of paranoia never hurts
222 self.nb_codes <= max_nb_codes
223 and self.train_input.min() >= 0
224 and self.test_input.min() >= 0
225 and tuple(self.train_ar_mask.unique()) == (0, 1)
226 and tuple(self.test_ar_mask.unique()) == (0, 1)
229 def batches(self, split="train", nb_to_use=-1, desc=None):
230 assert split in {"train", "test"}
231 input = self.train_input if split == "train" else self.test_input
233 input = input[:nb_to_use]
235 desc = f"epoch-{split}"
236 for batch in tqdm.tqdm(
237 input.split(self.batch_size), dynamic_ncols=True, desc=desc
241 def vocabulary_size(self):
245 self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
247 def compute_accuracy(input, ar_mask, logger=None):
248 input, ar_mask = input[:nmax], ar_mask[:nmax]
249 result = input.clone() * (1 - ar_mask)
251 masked_inplace_autoregression(
256 deterministic_synthesis,
257 progress_bar_desc=None,
261 if logger is not None:
262 for sp, st in zip(result[:10], input[:10]):
264 f"test_sequences {n_epoch} prediction {self.problem.seq2str(sp)}"
267 f" {n_epoch} ground truth {self.problem.seq2str(st)}"
270 nb_total = ar_mask.sum().item()
271 nb_correct = ((result == input).long() * ar_mask).sum().item()
273 return nb_total, nb_correct
275 train_nb_total, train_nb_correct = compute_accuracy(
276 self.train_input, self.train_ar_mask
280 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}%"
283 test_nb_total, test_nb_correct = compute_accuracy(
284 self.test_input, self.test_ar_mask, logger
288 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}%"
292 ######################################################################
297 class PicoCLVR(Task):
298 # Make a tensor from a list of strings
299 def tensorize(self, descr):
300 token_descr = [s.strip().split(" ") for s in descr]
301 l = max([len(s) for s in token_descr])
302 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
303 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
304 return torch.tensor(id_descr, device=self.device)
306 # Make a list of strings from a tensor
307 def detensorize(self, x):
308 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
310 # trim all the tensors in the tuple z to remove as much token from
311 # left and right in the first tensor. If z is a tuple, all its
312 # elements are trimed according to the triming for the first
313 def trim(self, z, token="<nul>"):
314 n = self.token2id[token]
317 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
318 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
319 return tuple([t[:, a:b] for t in z])
321 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
322 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
325 ######################
336 device=torch.device("cpu"),
342 def generate_descr(nb, cache_suffix, pruner):
343 return picoclvr.generate(
353 self.batch_size = batch_size
355 self.pruner_train = pruner_train
356 self.pruner_eval = pruner_eval
358 if logger is not None:
360 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
363 self.train_descr = generate_descr(
364 nb_train_samples, "train", pruner=self.pruner_train
366 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
368 # Build the tokenizer
369 tokens = {"<nul>", "<img>"}
370 for d in [self.train_descr, self.test_descr]:
372 for t in s.strip().split(" "):
374 # make this set a sorted list to get the same tensors given
376 tokens = list(tokens)
378 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
379 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
380 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
382 # Tokenize the train and test sets
383 self.train_input = self.tensorize(self.train_descr)
384 self.test_input = self.tensorize(self.test_descr)
386 def batches(self, split="train"):
387 assert split in {"train", "test"}
388 input = self.train_input if split == "train" else self.test_input
389 for batch in tqdm.tqdm(
390 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
392 yield self.trim(batch)
394 def vocabulary_size(self):
395 return len(self.token2id)
397 def compute_missing_properties(
398 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
400 acc_nb_requested_properties = []
401 acc_nb_missing_properties = []
404 for input in tqdm.tqdm(
405 self.test_input.split(self.batch_size),
407 desc=f"test-properties",
409 result = input.clone()
410 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
411 result = (1 - ar_mask) * result + ar_mask * self.t_nul
412 masked_inplace_autoregression(
417 deterministic_synthesis,
418 progress_bar_desc=None,
422 result_descr = self.detensorize(result)
423 np = picoclvr.nb_properties(
429 nb_requested_properties, _, nb_missing_properties = zip(*np)
430 acc_nb_requested_properties += nb_requested_properties
431 acc_nb_missing_properties += nb_missing_properties
432 acc_nb_results += len(result_descr)
434 nb_requested_properties = sum(acc_nb_requested_properties)
435 nb_missing_properties = sum(acc_nb_missing_properties)
437 prefix = "" if pruner is None else "pruned_"
438 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
440 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
443 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
446 ######################################################################
449 self, n_epoch, model, result_dir, logger, deterministic_synthesis
451 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
453 if self.pruner_eval is not None:
454 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
456 nb_tokens_to_generate = self.height * self.width + 3
461 for primer_descr in [
462 "red above green <sep> green top <sep> blue right of red",
463 "there is red <sep> there is yellow <sep> there is blue",
464 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
465 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
467 primer += [primer_descr + " <img>"] * nb_per_primer
469 result = self.tensorize(primer)
470 fill = result.new_full(
471 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
473 result = torch.cat((result, fill), 1)
474 ar_mask = (result == self.t_nul).long()
475 masked_inplace_autoregression(
480 deterministic_synthesis,
483 result_descr = self.detensorize(result)
485 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
487 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
488 acc_nb_results = len(result_descr)
490 nb_requested_properties = sum(acc_nb_requested_properties)
491 nb_missing_properties = sum(acc_nb_missing_properties)
494 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
496 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
499 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
502 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
506 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
510 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
516 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
517 torchvision.utils.save_image(
518 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
520 logger(f"wrote {image_name}")
523 ######################################################################
528 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
532 self.nb_train_samples = (nb_train_samples,)
533 self.nb_test_samples = (nb_test_samples,)
534 self.batch_size = batch_size
536 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
537 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
538 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
539 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
541 def batches(self, split="train", nb_to_use=-1, desc=None):
542 assert split in {"train", "test"}
543 input = self.train_input if split == "train" else self.test_input
545 input = input[:nb_to_use]
547 desc = f"epoch-{split}"
548 for batch in tqdm.tqdm(
549 input.split(self.batch_size), dynamic_ncols=True, desc=desc
553 def vocabulary_size(self):
557 self, n_epoch, model, result_dir, logger, deterministic_synthesis
559 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
560 ar_mask = torch.full_like(results, 1)
561 masked_inplace_autoregression(
566 deterministic_synthesis,
569 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
570 torchvision.utils.save_image(
571 1 - results.reshape(-1, 1, 28, 28) / 255.0,
576 logger(f"wrote {image_name}")
579 ######################################################################
585 def map2seq(self, *m):
586 return torch.cat([x.flatten(1) for x in m], 1)
588 def seq2map(self, s):
589 s = s.reshape(s.size(0), -1, self.height, self.width)
590 return (s[:, k] for k in range(s.size(1)))
600 device=torch.device("cpu"),
604 self.batch_size = batch_size
609 train_mazes, train_paths, _ = maze.create_maze_data(
614 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
616 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
618 test_mazes, test_paths, _ = maze.create_maze_data(
623 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
625 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
627 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
629 def batches(self, split="train", nb_to_use=-1, desc=None):
630 assert split in {"train", "test"}
631 input = self.train_input if split == "train" else self.test_input
633 input = input[:nb_to_use]
635 desc = f"epoch-{split}"
636 for batch in tqdm.tqdm(
637 input.split(self.batch_size), dynamic_ncols=True, desc=desc
641 def vocabulary_size(self):
645 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
647 nb_total, nb_correct = 0, 0
649 self.width * self.height,
650 self.width * self.height,
655 for input in self.batches(split, nb_to_use):
656 result = input.clone()
657 ar_mask = result.new_zeros(result.size())
658 ar_mask[:, self.height * self.width :] = 1
659 result *= 1 - ar_mask
660 masked_inplace_autoregression(
665 deterministic_synthesis,
666 progress_bar_desc=None,
669 mazes, paths = self.seq2map(result)
670 path_correctness = maze.path_correctness(mazes, paths)
671 nb_correct += path_correctness.long().sum()
672 nb_total += mazes.size(0)
674 optimal_path_lengths = (
675 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
677 predicted_path_lengths = (
678 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
680 optimal_path_lengths = optimal_path_lengths[path_correctness]
681 predicted_path_lengths = predicted_path_lengths[path_correctness]
682 count[optimal_path_lengths, predicted_path_lengths] += 1
688 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
691 return nb_total, nb_correct, count
694 self, n_epoch, model, result_dir, logger, deterministic_synthesis
696 train_nb_total, train_nb_correct, count = self.compute_error(
700 deterministic_synthesis=deterministic_synthesis,
703 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}%"
706 test_nb_total, test_nb_correct, count = self.compute_error(
710 deterministic_synthesis=deterministic_synthesis,
713 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}%"
716 if count is not None:
717 proportion_optimal = count.diagonal().sum().float() / count.sum()
718 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
720 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
722 for i in range(count.size(0)):
723 for j in range(count.size(1)):
724 eol = " " if j < count.size(1) - 1 else "\n"
725 f.write(f"{count[i,j]}{eol}")
727 input = self.test_input[:48]
728 result = input.clone()
729 ar_mask = result.new_zeros(result.size())
730 ar_mask[:, self.height * self.width :] = 1
731 result *= 1 - ar_mask
732 masked_inplace_autoregression(
737 deterministic_synthesis,
741 mazes, paths = self.seq2map(input)
742 _, predicted_paths = self.seq2map(result)
744 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
749 predicted_paths=predicted_paths,
750 path_correct=maze.path_correctness(mazes, predicted_paths),
751 path_optimal=maze.path_optimality(paths, predicted_paths),
753 logger(f"wrote {filename}")
756 ######################################################################
773 device=torch.device("cpu"),
777 self.batch_size = batch_size
781 self.prompt_length = prompt_length
783 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
792 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
802 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
804 def batches(self, split="train", nb_to_use=-1, desc=None):
805 assert split in {"train", "test"}
806 input = self.train_input if split == "train" else self.test_input
808 input = input[:nb_to_use]
810 desc = f"epoch-{split}"
811 for batch in tqdm.tqdm(
812 input.split(self.batch_size), dynamic_ncols=True, desc=desc
816 def vocabulary_size(self):
820 self, n_epoch, model, result_dir, logger, deterministic_synthesis
822 def compute_nb_correct(input, prior_visits):
823 result = input.clone()
824 i = torch.arange(result.size(1), device=result.device)[None, :]
826 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
830 result *= 1 - ar_mask
832 masked_inplace_autoregression(
837 deterministic_synthesis,
841 nb_total = ((prior_visits > 0) * ar_mask).sum()
843 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
845 return nb_total, nb_correct
847 test_nb_total, test_nb_correct = compute_nb_correct(
848 self.test_input[:1000], self.test_prior_visits[:1000]
852 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}%"
856 ######################################################################
872 fraction_values_for_train=None,
873 device=torch.device("cpu"),
877 self.batch_size = batch_size
878 self.nb_steps = nb_steps
879 self.nb_stacks = nb_stacks
880 self.nb_digits = nb_digits
883 if fraction_values_for_train is None:
884 values_for_train = None
885 values_for_test = None
887 all = torch.randperm(10**nb_digits)
888 nb_for_train = int(all.size(0) * fraction_values_for_train)
889 values_for_train = all[:nb_for_train]
890 values_for_test = all[nb_for_train:]
892 self.train_input, self.train_stack_counts = stack.generate_sequences(
901 self.test_input, self.test_stack_counts = stack.generate_sequences(
910 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
911 counts = self.test_stack_counts.flatten()[i.flatten()]
912 counts = F.one_hot(counts).sum(0)
913 logger(f"test_pop_stack_counts {counts}")
915 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
917 def batches(self, split="train", nb_to_use=-1, desc=None):
918 assert split in {"train", "test"}
919 input = self.train_input if split == "train" else self.test_input
921 input = input[:nb_to_use]
923 desc = f"epoch-{split}"
924 for batch in tqdm.tqdm(
925 input.split(self.batch_size), dynamic_ncols=True, desc=desc
929 def vocabulary_size(self):
933 self, n_epoch, model, result_dir, logger, deterministic_synthesis
935 def compute_nb_correct(input):
936 result = input.clone()
937 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
938 ar_mask = (result != input).long()
939 masked_inplace_autoregression(
944 deterministic_synthesis,
948 errors = ((result != input).long() * ar_mask).reshape(
949 -1, 1 + self.nb_digits
951 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
953 nb_total = ar_mask.max(1).values.sum()
954 nb_correct = nb_total - errors.max(1).values.sum()
956 return nb_total, nb_correct
958 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
961 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}%"
964 ##############################################################
965 # Log a few generated sequences
966 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
967 result = input.clone()
968 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
969 ar_mask = (result != input).long()
971 # for n in range(result.size(0)):
973 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
976 masked_inplace_autoregression(
981 deterministic_synthesis,
985 for n in range(result.size(0)):
987 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
989 ##############################################################
992 ######################################################################
999 def tensorize(self, sequences):
1000 len_max = max([len(x) for x in sequences])
1005 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1022 device=torch.device("cpu"),
1026 self.batch_size = batch_size
1027 self.device = device
1029 train_sequences = expr.generate_sequences(
1031 nb_variables=nb_variables,
1032 length=sequence_length,
1033 operand_max=operand_max,
1034 result_max=result_max,
1037 test_sequences = expr.generate_sequences(
1039 nb_variables=nb_variables,
1040 length=sequence_length,
1041 operand_max=operand_max,
1042 result_max=result_max,
1045 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1048 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1049 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1051 self.filler, self.space = self.char2id["#"], self.char2id[" "]
1053 self.train_input = self.tensorize(train_sequences)
1054 self.test_input = self.tensorize(test_sequences)
1056 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1058 def batches(self, split="train", nb_to_use=-1, desc=None):
1059 assert split in {"train", "test"}
1060 input = self.train_input if split == "train" else self.test_input
1062 input = input[:nb_to_use]
1064 desc = f"epoch-{split}"
1065 for batch in tqdm.tqdm(
1066 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1068 last = (batch != self.filler).max(0).values.nonzero().max() + 3
1069 batch = batch[:, :last]
1072 def vocabulary_size(self):
1073 return self.nb_codes
1075 def seq2str(self, s):
1076 return "".join([self.id2char[k.item()] for k in s])
1078 def produce_results(
1084 deterministic_synthesis,
1087 def compute_nb_correct(input):
1088 result = input.clone()
1089 s = (result == self.space).long()
1090 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1091 result = (1 - ar_mask) * result + ar_mask * self.filler
1092 masked_inplace_autoregression(
1097 deterministic_synthesis,
1101 nb_total = input.size(0)
1102 nb_correct = (input == result).long().min(1).values.sum()
1104 #######################################################################
1105 # Comput predicted vs. true variable values
1107 nb_delta = torch.zeros(5, dtype=torch.int64)
1110 values_input = expr.extract_results([self.seq2str(s) for s in input])
1111 values_result = expr.extract_results([self.seq2str(s) for s in result])
1113 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1115 with open(filename, "w") as f:
1116 for i, r in zip(values_input, values_result):
1117 for n, vi in i.items():
1119 f.write(f"{vi} {-1 if vr is None else vr}\n")
1121 if vr is None or vr < 0:
1125 if d >= nb_delta.size(0):
1130 ######################################################################
1132 return nb_total, nb_correct, nb_delta, nb_missed
1139 ) = compute_nb_correct(self.test_input[:10000])
1142 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}%"
1145 nb_total = test_nb_delta.sum() + test_nb_missed
1146 for d in range(test_nb_delta.size(0)):
1148 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1151 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1154 ##############################################################
1155 # Log a few generated sequences
1156 if input_file is None:
1157 input = self.test_input[:10]
1159 with open(input_file, "r") as f:
1160 sequences = [e.strip() for e in f.readlines()]
1161 sequences = [s + " " + "#" * 50 for s in sequences]
1162 input = self.tensorize(sequences)
1164 result = input.clone()
1165 s = (result == self.space).long()
1166 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1167 result = (1 - ar_mask) * result + ar_mask * self.filler
1169 for n in range(result.size(0)):
1170 logger(f"test_before {self.seq2str(result[n])}")
1172 masked_inplace_autoregression(
1177 deterministic_synthesis,
1181 correct = (1 - ar_mask) * self.space + ar_mask * input
1182 for n in range(result.size(0)):
1183 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1184 logger(f"test_after {self.seq2str(result[n])} {comment}")
1185 logger(f"truth {self.seq2str(correct[n])}")
1186 ##############################################################
1189 ######################################################################
1202 device=torch.device("cpu"),
1203 device_storage=torch.device("cpu"),
1207 self.batch_size = batch_size
1208 self.device = device
1217 ) = world.create_data_and_processors(
1222 nb_epochs=vqae_nb_epochs,
1225 device_storage=device_storage,
1228 train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1229 test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1231 nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1232 nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1234 self.len_frame_seq = train_frame_seq.size(1)
1235 self.len_action_seq = train_action_seq.size(1)
1236 self.nb_codes = nb_frame_codes + nb_action_codes
1238 train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1240 train_action_seq += nb_frame_codes
1241 self.train_input = torch.cat(
1242 (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1245 test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1246 test_action_seq += nb_frame_codes
1247 self.test_input = torch.cat(
1248 (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1251 def batches(self, split="train", nb_to_use=-1, desc=None):
1252 assert split in {"train", "test"}
1253 input = self.train_input if split == "train" else self.test_input
1255 input = input[:nb_to_use]
1257 desc = f"epoch-{split}"
1258 for batch in tqdm.tqdm(
1259 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1261 yield batch.to(self.device)
1263 def vocabulary_size(self):
1264 return self.nb_codes
1266 def produce_results(
1267 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1270 2 * self.len_frame_seq + self.len_action_seq, device=self.device
1273 input = self.test_input[:64].to(self.device)
1274 result = input.clone()
1277 (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1279 result *= 1 - ar_mask
1281 masked_inplace_autoregression(
1286 deterministic_synthesis,
1290 seq_start = input[:, : self.len_frame_seq]
1291 seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1292 seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1295 (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1297 result = result.reshape(-1, result.size(-1))
1299 frames = self.seq2frame(result)
1300 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1301 torchvision.utils.save_image(
1302 frames.float() / (world.Box.nb_rgb_levels - 1),
1308 logger(f"wrote {image_name}")
1311 ######################################################################