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 ######################################################################
70 def perf(seq, logger):
74 class ProblemByheart(Problem):
76 nb_seq, len_prompt, len_result = 100, 5, 5
77 self.seq = torch.randint(10, (nb_seq, len_prompt + 1 + len_result))
78 self.seq[:,len_prompt]=-1
80 def generate_sequences(self, nb):
81 return self.seq[torch.randint(self.seq.size(0), (nb,))]
90 device=torch.device("cpu"),
94 self.batch_size = batch_size
96 problems = [ ProblemByheart() ]
99 def generate_sequences(nb_samples):
100 problem_indexes = torch.randint(len(problems), (nb_samples,))
101 nb_samples_per_problem = torch.one_hot(problem_indexes).sum(0)
102 print(f"{nb_samples_per_problem}")
104 for nb, p in zip(nb_samples_per_problem,problems):
105 all_seq.append(p.generate_sequences(nb_samples_per_problem[nb]))
108 train_seq = generate_sequences(nb_train_samples)
109 test_seq = generate_sequences(nb_test_samples)
111 for strain, stest in zip(train_seq, test_seq):
112 s = torch.cat((strain,stest),0)
114 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
116 def batches(self, split="train", nb_to_use=-1, desc=None):
117 assert split in {"train", "test"}
118 input = self.train_input if split == "train" else self.test_input
120 input = input[:nb_to_use]
122 desc = f"epoch-{split}"
123 for batch in tqdm.tqdm(
124 input.split(self.batch_size), dynamic_ncols=True, desc=desc
128 def vocabulary_size(self):
132 self, n_epoch, model, result_dir, logger, deterministic_synthesis
135 # 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}%"
140 ######################################################################
145 class PicoCLVR(Task):
146 # Make a tensor from a list of strings
147 def tensorize(self, descr):
148 token_descr = [s.strip().split(" ") for s in descr]
149 l = max([len(s) for s in token_descr])
150 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
151 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
152 return torch.tensor(id_descr, device=self.device)
154 # Make a list of strings from a tensor
155 def detensorize(self, x):
156 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
158 # trim all the tensors in the tuple z to remove as much token from
159 # left and right in the first tensor. If z is a tuple, all its
160 # elements are trimed according to the triming for the first
161 def trim(self, z, token="<nul>"):
162 n = self.token2id[token]
165 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
166 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
167 return tuple([t[:, a:b] for t in z])
169 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
170 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
173 ######################
184 device=torch.device("cpu"),
190 def generate_descr(nb, cache_suffix, pruner):
191 return picoclvr.generate(
201 self.batch_size = batch_size
203 self.pruner_train = pruner_train
204 self.pruner_eval = pruner_eval
206 if logger is not None:
208 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
211 self.train_descr = generate_descr(
212 nb_train_samples, "train", pruner=self.pruner_train
214 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
216 # Build the tokenizer
217 tokens = {"<nul>", "<img>"}
218 for d in [self.train_descr, self.test_descr]:
220 for t in s.strip().split(" "):
222 # make this set a sorted list to get the same tensors given
224 tokens = list(tokens)
226 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
227 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
228 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
230 # Tokenize the train and test sets
231 self.train_input = self.tensorize(self.train_descr)
232 self.test_input = self.tensorize(self.test_descr)
234 def batches(self, split="train"):
235 assert split in {"train", "test"}
236 input = self.train_input if split == "train" else self.test_input
237 for batch in tqdm.tqdm(
238 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
240 yield self.trim(batch)
242 def vocabulary_size(self):
243 return len(self.token2id)
245 def compute_missing_properties(
246 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
248 acc_nb_requested_properties = []
249 acc_nb_missing_properties = []
252 for input in tqdm.tqdm(
253 self.test_input.split(self.batch_size),
255 desc=f"test-properties",
257 result = input.clone()
258 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
259 result = (1 - ar_mask) * result + ar_mask * self.t_nul
260 masked_inplace_autoregression(
265 deterministic_synthesis,
266 progress_bar_desc=None,
270 result_descr = self.detensorize(result)
271 np = picoclvr.nb_properties(
277 nb_requested_properties, _, nb_missing_properties = zip(*np)
278 acc_nb_requested_properties += nb_requested_properties
279 acc_nb_missing_properties += nb_missing_properties
280 acc_nb_results += len(result_descr)
282 nb_requested_properties = sum(acc_nb_requested_properties)
283 nb_missing_properties = sum(acc_nb_missing_properties)
285 prefix = "" if pruner is None else "pruned_"
286 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
288 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
291 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
294 ######################################################################
297 self, n_epoch, model, result_dir, logger, deterministic_synthesis
299 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
301 if self.pruner_eval is not None:
302 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
304 nb_tokens_to_generate = self.height * self.width + 3
309 for primer_descr in [
310 "red above green <sep> green top <sep> blue right of red",
311 "there is red <sep> there is yellow <sep> there is blue",
312 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
313 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
315 primer += [primer_descr + " <img>"] * nb_per_primer
317 result = self.tensorize(primer)
318 fill = result.new_full(
319 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
321 result = torch.cat((result, fill), 1)
322 ar_mask = (result == self.t_nul).long()
323 masked_inplace_autoregression(
328 deterministic_synthesis,
331 result_descr = self.detensorize(result)
333 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
335 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
336 acc_nb_results = len(result_descr)
338 nb_requested_properties = sum(acc_nb_requested_properties)
339 nb_missing_properties = sum(acc_nb_missing_properties)
342 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
344 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
347 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
350 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
354 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
358 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
364 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
365 torchvision.utils.save_image(
366 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
368 logger(f"wrote {image_name}")
371 ######################################################################
376 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
380 self.nb_train_samples = (nb_train_samples,)
381 self.nb_test_samples = (nb_test_samples,)
382 self.batch_size = batch_size
384 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
385 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
386 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
387 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
389 def batches(self, split="train", nb_to_use=-1, desc=None):
390 assert split in {"train", "test"}
391 input = self.train_input if split == "train" else self.test_input
393 input = input[:nb_to_use]
395 desc = f"epoch-{split}"
396 for batch in tqdm.tqdm(
397 input.split(self.batch_size), dynamic_ncols=True, desc=desc
401 def vocabulary_size(self):
405 self, n_epoch, model, result_dir, logger, deterministic_synthesis
407 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
408 ar_mask = torch.full_like(results, 1)
409 masked_inplace_autoregression(
414 deterministic_synthesis,
417 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
418 torchvision.utils.save_image(
419 1 - results.reshape(-1, 1, 28, 28) / 255.0,
424 logger(f"wrote {image_name}")
427 ######################################################################
433 def map2seq(self, *m):
434 return torch.cat([x.flatten(1) for x in m], 1)
436 def seq2map(self, s):
437 s = s.reshape(s.size(0), -1, self.height, self.width)
438 return (s[:, k] for k in range(s.size(1)))
448 device=torch.device("cpu"),
452 self.batch_size = batch_size
457 train_mazes, train_paths, _ = maze.create_maze_data(
462 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
464 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
466 test_mazes, test_paths, _ = maze.create_maze_data(
471 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
473 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
475 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
477 def batches(self, split="train", nb_to_use=-1, desc=None):
478 assert split in {"train", "test"}
479 input = self.train_input if split == "train" else self.test_input
481 input = input[:nb_to_use]
483 desc = f"epoch-{split}"
484 for batch in tqdm.tqdm(
485 input.split(self.batch_size), dynamic_ncols=True, desc=desc
489 def vocabulary_size(self):
493 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
495 nb_total, nb_correct = 0, 0
497 self.width * self.height,
498 self.width * self.height,
503 for input in self.batches(split, nb_to_use):
504 result = input.clone()
505 ar_mask = result.new_zeros(result.size())
506 ar_mask[:, self.height * self.width :] = 1
507 result *= 1 - ar_mask
508 masked_inplace_autoregression(
513 deterministic_synthesis,
514 progress_bar_desc=None,
517 mazes, paths = self.seq2map(result)
518 path_correctness = maze.path_correctness(mazes, paths)
519 nb_correct += path_correctness.long().sum()
520 nb_total += mazes.size(0)
522 optimal_path_lengths = (
523 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
525 predicted_path_lengths = (
526 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
528 optimal_path_lengths = optimal_path_lengths[path_correctness]
529 predicted_path_lengths = predicted_path_lengths[path_correctness]
530 count[optimal_path_lengths, predicted_path_lengths] += 1
536 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
539 return nb_total, nb_correct, count
542 self, n_epoch, model, result_dir, logger, deterministic_synthesis
544 train_nb_total, train_nb_correct, count = self.compute_error(
548 deterministic_synthesis=deterministic_synthesis,
551 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}%"
554 test_nb_total, test_nb_correct, count = self.compute_error(
558 deterministic_synthesis=deterministic_synthesis,
561 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}%"
564 if count is not None:
565 proportion_optimal = count.diagonal().sum().float() / count.sum()
566 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
568 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
570 for i in range(count.size(0)):
571 for j in range(count.size(1)):
572 eol = " " if j < count.size(1) - 1 else "\n"
573 f.write(f"{count[i,j]}{eol}")
575 input = self.test_input[:48]
576 result = input.clone()
577 ar_mask = result.new_zeros(result.size())
578 ar_mask[:, self.height * self.width :] = 1
579 result *= 1 - ar_mask
580 masked_inplace_autoregression(
585 deterministic_synthesis,
589 mazes, paths = self.seq2map(input)
590 _, predicted_paths = self.seq2map(result)
592 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
597 predicted_paths=predicted_paths,
598 path_correct=maze.path_correctness(mazes, predicted_paths),
599 path_optimal=maze.path_optimality(paths, predicted_paths),
601 logger(f"wrote {filename}")
604 ######################################################################
621 device=torch.device("cpu"),
625 self.batch_size = batch_size
629 self.prompt_length = prompt_length
631 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
640 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
650 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
652 def batches(self, split="train", nb_to_use=-1, desc=None):
653 assert split in {"train", "test"}
654 input = self.train_input if split == "train" else self.test_input
656 input = input[:nb_to_use]
658 desc = f"epoch-{split}"
659 for batch in tqdm.tqdm(
660 input.split(self.batch_size), dynamic_ncols=True, desc=desc
664 def vocabulary_size(self):
668 self, n_epoch, model, result_dir, logger, deterministic_synthesis
670 def compute_nb_correct(input, prior_visits):
671 result = input.clone()
672 i = torch.arange(result.size(1), device=result.device)[None, :]
674 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
678 result *= 1 - ar_mask
680 masked_inplace_autoregression(
685 deterministic_synthesis,
689 nb_total = ((prior_visits > 0) * ar_mask).sum()
691 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
693 return nb_total, nb_correct
695 test_nb_total, test_nb_correct = compute_nb_correct(
696 self.test_input[:1000], self.test_prior_visits[:1000]
700 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}%"
704 ######################################################################
720 fraction_values_for_train=None,
721 device=torch.device("cpu"),
725 self.batch_size = batch_size
726 self.nb_steps = nb_steps
727 self.nb_stacks = nb_stacks
728 self.nb_digits = nb_digits
731 if fraction_values_for_train is None:
732 values_for_train = None
733 values_for_test = None
735 all = torch.randperm(10**nb_digits)
736 nb_for_train = int(all.size(0) * fraction_values_for_train)
737 values_for_train = all[:nb_for_train]
738 values_for_test = all[nb_for_train:]
740 self.train_input, self.train_stack_counts = stack.generate_sequences(
749 self.test_input, self.test_stack_counts = stack.generate_sequences(
758 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
759 counts = self.test_stack_counts.flatten()[i.flatten()]
760 counts = F.one_hot(counts).sum(0)
761 logger(f"test_pop_stack_counts {counts}")
763 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
765 def batches(self, split="train", nb_to_use=-1, desc=None):
766 assert split in {"train", "test"}
767 input = self.train_input if split == "train" else self.test_input
769 input = input[:nb_to_use]
771 desc = f"epoch-{split}"
772 for batch in tqdm.tqdm(
773 input.split(self.batch_size), dynamic_ncols=True, desc=desc
777 def vocabulary_size(self):
781 self, n_epoch, model, result_dir, logger, deterministic_synthesis
783 def compute_nb_correct(input):
784 result = input.clone()
785 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
786 ar_mask = (result != input).long()
787 masked_inplace_autoregression(
792 deterministic_synthesis,
796 errors = ((result != input).long() * ar_mask).reshape(
797 -1, 1 + self.nb_digits
799 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
801 nb_total = ar_mask.max(1).values.sum()
802 nb_correct = nb_total - errors.max(1).values.sum()
804 return nb_total, nb_correct
806 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
809 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}%"
812 ##############################################################
813 # Log a few generated sequences
814 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
815 result = input.clone()
816 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
817 ar_mask = (result != input).long()
819 # for n in range(result.size(0)):
821 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
824 masked_inplace_autoregression(
829 deterministic_synthesis,
833 for n in range(result.size(0)):
835 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
837 ##############################################################
840 ######################################################################
847 def tensorize(self, sequences):
848 len_max = max([len(x) for x in sequences])
853 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
870 device=torch.device("cpu"),
874 self.batch_size = batch_size
877 train_sequences = expr.generate_sequences(
879 nb_variables=nb_variables,
880 length=sequence_length,
881 operand_max=operand_max,
882 result_max=result_max,
885 test_sequences = expr.generate_sequences(
887 nb_variables=nb_variables,
888 length=sequence_length,
889 operand_max=operand_max,
890 result_max=result_max,
893 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
896 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
897 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
899 self.filler, self.space = self.char2id["#"], self.char2id[" "]
901 self.train_input = self.tensorize(train_sequences)
902 self.test_input = self.tensorize(test_sequences)
904 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
906 def batches(self, split="train", nb_to_use=-1, desc=None):
907 assert split in {"train", "test"}
908 input = self.train_input if split == "train" else self.test_input
910 input = input[:nb_to_use]
912 desc = f"epoch-{split}"
913 for batch in tqdm.tqdm(
914 input.split(self.batch_size), dynamic_ncols=True, desc=desc
916 last = (batch != self.filler).max(0).values.nonzero().max() + 3
917 batch = batch[:, :last]
920 def vocabulary_size(self):
923 def seq2str(self, s):
924 return "".join([self.id2char[k.item()] for k in s])
932 deterministic_synthesis,
935 def compute_nb_correct(input):
936 result = input.clone()
937 s = (result == self.space).long()
938 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
939 result = (1 - ar_mask) * result + ar_mask * self.filler
940 masked_inplace_autoregression(
945 deterministic_synthesis,
949 nb_total = input.size(0)
950 nb_correct = (input == result).long().min(1).values.sum()
952 #######################################################################
953 # Comput predicted vs. true variable values
955 nb_delta = torch.zeros(5, dtype=torch.int64)
958 values_input = expr.extract_results([self.seq2str(s) for s in input])
959 values_result = expr.extract_results([self.seq2str(s) for s in result])
961 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
963 with open(filename, "w") as f:
964 for i, r in zip(values_input, values_result):
965 for n, vi in i.items():
967 f.write(f"{vi} {-1 if vr is None else vr}\n")
969 if vr is None or vr < 0:
973 if d >= nb_delta.size(0):
978 ######################################################################
980 return nb_total, nb_correct, nb_delta, nb_missed
987 ) = compute_nb_correct(self.test_input[:10000])
990 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}%"
993 nb_total = test_nb_delta.sum() + test_nb_missed
994 for d in range(test_nb_delta.size(0)):
996 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
999 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1002 ##############################################################
1003 # Log a few generated sequences
1004 if input_file is None:
1005 input = self.test_input[:10]
1007 with open(input_file, "r") as f:
1008 sequences = [e.strip() for e in f.readlines()]
1009 sequences = [s + " " + "#" * 50 for s in sequences]
1010 input = self.tensorize(sequences)
1012 result = input.clone()
1013 s = (result == self.space).long()
1014 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1015 result = (1 - ar_mask) * result + ar_mask * self.filler
1017 for n in range(result.size(0)):
1018 logger(f"test_before {self.seq2str(result[n])}")
1020 masked_inplace_autoregression(
1025 deterministic_synthesis,
1029 correct = (1 - ar_mask) * self.space + ar_mask * input
1030 for n in range(result.size(0)):
1031 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1032 logger(f"test_after {self.seq2str(result[n])} {comment}")
1033 logger(f"truth {self.seq2str(correct[n])}")
1034 ##############################################################
1037 ######################################################################
1050 device=torch.device("cpu"),
1051 device_storage=torch.device("cpu"),
1055 self.batch_size = batch_size
1056 self.device = device
1065 ) = world.create_data_and_processors(
1070 nb_epochs=vqae_nb_epochs,
1073 device_storage=device_storage,
1076 print(f"{train_action_seq.size()=}")
1078 train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1079 test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1081 nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1082 nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1084 self.len_frame_seq = train_frame_seq.size(1)
1085 self.len_action_seq = train_action_seq.size(1)
1086 self.nb_codes = nb_frame_codes + nb_action_codes
1088 train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1089 print(f"{train_action_seq.device=} {nb_frame_codes.device=}")
1090 train_action_seq += nb_frame_codes
1091 self.train_input = torch.cat(
1092 (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1095 test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1096 test_action_seq += nb_frame_codes
1097 self.test_input = torch.cat(
1098 (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1101 def batches(self, split="train", nb_to_use=-1, desc=None):
1102 assert split in {"train", "test"}
1103 input = self.train_input if split == "train" else self.test_input
1105 input = input[:nb_to_use]
1107 desc = f"epoch-{split}"
1108 for batch in tqdm.tqdm(
1109 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1111 yield batch.to(self.device)
1113 def vocabulary_size(self):
1114 return self.nb_codes
1116 def produce_results(
1117 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1120 2 * self.len_frame_seq + self.len_action_seq, device=self.device
1123 input = self.test_input[:64].to(self.device)
1124 result = input.clone()
1127 (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1129 result *= 1 - ar_mask
1131 masked_inplace_autoregression(
1136 deterministic_synthesis,
1140 seq_start = input[:, : self.len_frame_seq]
1141 seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1142 seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1145 (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1147 result = result.reshape(-1, result.size(-1))
1148 print(f"{result.size()=}")
1150 frames = self.seq2frame(result)
1151 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1152 torchvision.utils.save_image(
1153 frames.float() / (world.Box.nb_rgb_levels - 1),
1159 logger(f"wrote {image_name}")
1162 ######################################################################