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):
86 device=torch.device("cpu"),
90 self.batch_size = batch_size
92 def generate_sequences(nb_samples):
93 problem_indexes = torch.randint(len(problems), (nb_samples,))
94 nb_samples_per_problem = torch.one_hot(problem_indexes).sum(0)
95 print(f"{nb_samples_per_problem}")
97 self.train_input = generate_sequences(nb_train_samples)
98 self.test_input = generate_sequences(nb_test_samples)
100 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
102 def batches(self, split="train", nb_to_use=-1, desc=None):
103 assert split in {"train", "test"}
104 input = self.train_input if split == "train" else self.test_input
106 input = input[:nb_to_use]
108 desc = f"epoch-{split}"
109 for batch in tqdm.tqdm(
110 input.split(self.batch_size), dynamic_ncols=True, desc=desc
114 def vocabulary_size(self):
118 self, n_epoch, model, result_dir, logger, deterministic_synthesis
121 # 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}%"
126 ######################################################################
131 class PicoCLVR(Task):
132 # Make a tensor from a list of strings
133 def tensorize(self, descr):
134 token_descr = [s.strip().split(" ") for s in descr]
135 l = max([len(s) for s in token_descr])
136 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
137 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
138 return torch.tensor(id_descr, device=self.device)
140 # Make a list of strings from a tensor
141 def detensorize(self, x):
142 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
144 # trim all the tensors in the tuple z to remove as much token from
145 # left and right in the first tensor. If z is a tuple, all its
146 # elements are trimed according to the triming for the first
147 def trim(self, z, token="<nul>"):
148 n = self.token2id[token]
151 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
152 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
153 return tuple([t[:, a:b] for t in z])
155 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
156 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
159 ######################
170 device=torch.device("cpu"),
176 def generate_descr(nb, cache_suffix, pruner):
177 return picoclvr.generate(
187 self.batch_size = batch_size
189 self.pruner_train = pruner_train
190 self.pruner_eval = pruner_eval
192 if logger is not None:
194 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
197 self.train_descr = generate_descr(
198 nb_train_samples, "train", pruner=self.pruner_train
200 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
202 # Build the tokenizer
203 tokens = {"<nul>", "<img>"}
204 for d in [self.train_descr, self.test_descr]:
206 for t in s.strip().split(" "):
208 # make this set a sorted list to get the same tensors given
210 tokens = list(tokens)
212 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
213 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
214 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
216 # Tokenize the train and test sets
217 self.train_input = self.tensorize(self.train_descr)
218 self.test_input = self.tensorize(self.test_descr)
220 def batches(self, split="train"):
221 assert split in {"train", "test"}
222 input = self.train_input if split == "train" else self.test_input
223 for batch in tqdm.tqdm(
224 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
226 yield self.trim(batch)
228 def vocabulary_size(self):
229 return len(self.token2id)
231 def compute_missing_properties(
232 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
234 acc_nb_requested_properties = []
235 acc_nb_missing_properties = []
238 for input in tqdm.tqdm(
239 self.test_input.split(self.batch_size),
241 desc=f"test-properties",
243 result = input.clone()
244 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
245 result = (1 - ar_mask) * result + ar_mask * self.t_nul
246 masked_inplace_autoregression(
251 deterministic_synthesis,
252 progress_bar_desc=None,
256 result_descr = self.detensorize(result)
257 np = picoclvr.nb_properties(
263 nb_requested_properties, _, nb_missing_properties = zip(*np)
264 acc_nb_requested_properties += nb_requested_properties
265 acc_nb_missing_properties += nb_missing_properties
266 acc_nb_results += len(result_descr)
268 nb_requested_properties = sum(acc_nb_requested_properties)
269 nb_missing_properties = sum(acc_nb_missing_properties)
271 prefix = "" if pruner is None else "pruned_"
272 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
274 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
277 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
280 ######################################################################
283 self, n_epoch, model, result_dir, logger, deterministic_synthesis
285 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
287 if self.pruner_eval is not None:
288 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
290 nb_tokens_to_generate = self.height * self.width + 3
295 for primer_descr in [
296 "red above green <sep> green top <sep> blue right of red",
297 "there is red <sep> there is yellow <sep> there is blue",
298 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
299 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
301 primer += [primer_descr + " <img>"] * nb_per_primer
303 result = self.tensorize(primer)
304 fill = result.new_full(
305 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
307 result = torch.cat((result, fill), 1)
308 ar_mask = (result == self.t_nul).long()
309 masked_inplace_autoregression(
314 deterministic_synthesis,
317 result_descr = self.detensorize(result)
319 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
321 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
322 acc_nb_results = len(result_descr)
324 nb_requested_properties = sum(acc_nb_requested_properties)
325 nb_missing_properties = sum(acc_nb_missing_properties)
328 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
330 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
333 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
336 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
340 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
344 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
350 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
351 torchvision.utils.save_image(
352 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
354 logger(f"wrote {image_name}")
357 ######################################################################
362 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
366 self.nb_train_samples = (nb_train_samples,)
367 self.nb_test_samples = (nb_test_samples,)
368 self.batch_size = batch_size
370 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
371 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
372 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
373 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
375 def batches(self, split="train", nb_to_use=-1, desc=None):
376 assert split in {"train", "test"}
377 input = self.train_input if split == "train" else self.test_input
379 input = input[:nb_to_use]
381 desc = f"epoch-{split}"
382 for batch in tqdm.tqdm(
383 input.split(self.batch_size), dynamic_ncols=True, desc=desc
387 def vocabulary_size(self):
391 self, n_epoch, model, result_dir, logger, deterministic_synthesis
393 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
394 ar_mask = torch.full_like(results, 1)
395 masked_inplace_autoregression(
400 deterministic_synthesis,
403 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
404 torchvision.utils.save_image(
405 1 - results.reshape(-1, 1, 28, 28) / 255.0,
410 logger(f"wrote {image_name}")
413 ######################################################################
419 def map2seq(self, *m):
420 return torch.cat([x.flatten(1) for x in m], 1)
422 def seq2map(self, s):
423 s = s.reshape(s.size(0), -1, self.height, self.width)
424 return (s[:, k] for k in range(s.size(1)))
434 device=torch.device("cpu"),
438 self.batch_size = batch_size
443 train_mazes, train_paths, _ = maze.create_maze_data(
448 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
450 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
452 test_mazes, test_paths, _ = maze.create_maze_data(
457 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
459 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
461 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
463 def batches(self, split="train", nb_to_use=-1, desc=None):
464 assert split in {"train", "test"}
465 input = self.train_input if split == "train" else self.test_input
467 input = input[:nb_to_use]
469 desc = f"epoch-{split}"
470 for batch in tqdm.tqdm(
471 input.split(self.batch_size), dynamic_ncols=True, desc=desc
475 def vocabulary_size(self):
479 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
481 nb_total, nb_correct = 0, 0
483 self.width * self.height,
484 self.width * self.height,
489 for input in self.batches(split, nb_to_use):
490 result = input.clone()
491 ar_mask = result.new_zeros(result.size())
492 ar_mask[:, self.height * self.width :] = 1
493 result *= 1 - ar_mask
494 masked_inplace_autoregression(
499 deterministic_synthesis,
500 progress_bar_desc=None,
503 mazes, paths = self.seq2map(result)
504 path_correctness = maze.path_correctness(mazes, paths)
505 nb_correct += path_correctness.long().sum()
506 nb_total += mazes.size(0)
508 optimal_path_lengths = (
509 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
511 predicted_path_lengths = (
512 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
514 optimal_path_lengths = optimal_path_lengths[path_correctness]
515 predicted_path_lengths = predicted_path_lengths[path_correctness]
516 count[optimal_path_lengths, predicted_path_lengths] += 1
522 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
525 return nb_total, nb_correct, count
528 self, n_epoch, model, result_dir, logger, deterministic_synthesis
530 train_nb_total, train_nb_correct, count = self.compute_error(
534 deterministic_synthesis=deterministic_synthesis,
537 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}%"
540 test_nb_total, test_nb_correct, count = self.compute_error(
544 deterministic_synthesis=deterministic_synthesis,
547 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}%"
550 if count is not None:
551 proportion_optimal = count.diagonal().sum().float() / count.sum()
552 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
554 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
556 for i in range(count.size(0)):
557 for j in range(count.size(1)):
558 eol = " " if j < count.size(1) - 1 else "\n"
559 f.write(f"{count[i,j]}{eol}")
561 input = self.test_input[:48]
562 result = input.clone()
563 ar_mask = result.new_zeros(result.size())
564 ar_mask[:, self.height * self.width :] = 1
565 result *= 1 - ar_mask
566 masked_inplace_autoregression(
571 deterministic_synthesis,
575 mazes, paths = self.seq2map(input)
576 _, predicted_paths = self.seq2map(result)
578 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
583 predicted_paths=predicted_paths,
584 path_correct=maze.path_correctness(mazes, predicted_paths),
585 path_optimal=maze.path_optimality(paths, predicted_paths),
587 logger(f"wrote {filename}")
590 ######################################################################
607 device=torch.device("cpu"),
611 self.batch_size = batch_size
615 self.prompt_length = prompt_length
617 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
626 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
636 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
638 def batches(self, split="train", nb_to_use=-1, desc=None):
639 assert split in {"train", "test"}
640 input = self.train_input if split == "train" else self.test_input
642 input = input[:nb_to_use]
644 desc = f"epoch-{split}"
645 for batch in tqdm.tqdm(
646 input.split(self.batch_size), dynamic_ncols=True, desc=desc
650 def vocabulary_size(self):
654 self, n_epoch, model, result_dir, logger, deterministic_synthesis
656 def compute_nb_correct(input, prior_visits):
657 result = input.clone()
658 i = torch.arange(result.size(1), device=result.device)[None, :]
660 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
664 result *= 1 - ar_mask
666 masked_inplace_autoregression(
671 deterministic_synthesis,
675 nb_total = ((prior_visits > 0) * ar_mask).sum()
677 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
679 return nb_total, nb_correct
681 test_nb_total, test_nb_correct = compute_nb_correct(
682 self.test_input[:1000], self.test_prior_visits[:1000]
686 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}%"
690 ######################################################################
706 fraction_values_for_train=None,
707 device=torch.device("cpu"),
711 self.batch_size = batch_size
712 self.nb_steps = nb_steps
713 self.nb_stacks = nb_stacks
714 self.nb_digits = nb_digits
717 if fraction_values_for_train is None:
718 values_for_train = None
719 values_for_test = None
721 all = torch.randperm(10**nb_digits)
722 nb_for_train = int(all.size(0) * fraction_values_for_train)
723 values_for_train = all[:nb_for_train]
724 values_for_test = all[nb_for_train:]
726 self.train_input, self.train_stack_counts = stack.generate_sequences(
735 self.test_input, self.test_stack_counts = stack.generate_sequences(
744 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
745 counts = self.test_stack_counts.flatten()[i.flatten()]
746 counts = F.one_hot(counts).sum(0)
747 logger(f"test_pop_stack_counts {counts}")
749 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
751 def batches(self, split="train", nb_to_use=-1, desc=None):
752 assert split in {"train", "test"}
753 input = self.train_input if split == "train" else self.test_input
755 input = input[:nb_to_use]
757 desc = f"epoch-{split}"
758 for batch in tqdm.tqdm(
759 input.split(self.batch_size), dynamic_ncols=True, desc=desc
763 def vocabulary_size(self):
767 self, n_epoch, model, result_dir, logger, deterministic_synthesis
769 def compute_nb_correct(input):
770 result = input.clone()
771 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
772 ar_mask = (result != input).long()
773 masked_inplace_autoregression(
778 deterministic_synthesis,
782 errors = ((result != input).long() * ar_mask).reshape(
783 -1, 1 + self.nb_digits
785 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
787 nb_total = ar_mask.max(1).values.sum()
788 nb_correct = nb_total - errors.max(1).values.sum()
790 return nb_total, nb_correct
792 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
795 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}%"
798 ##############################################################
799 # Log a few generated sequences
800 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
801 result = input.clone()
802 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
803 ar_mask = (result != input).long()
805 # for n in range(result.size(0)):
807 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
810 masked_inplace_autoregression(
815 deterministic_synthesis,
819 for n in range(result.size(0)):
821 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
823 ##############################################################
826 ######################################################################
833 def tensorize(self, sequences):
834 len_max = max([len(x) for x in sequences])
839 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
856 device=torch.device("cpu"),
860 self.batch_size = batch_size
863 train_sequences = expr.generate_sequences(
865 nb_variables=nb_variables,
866 length=sequence_length,
867 operand_max=operand_max,
868 result_max=result_max,
871 test_sequences = expr.generate_sequences(
873 nb_variables=nb_variables,
874 length=sequence_length,
875 operand_max=operand_max,
876 result_max=result_max,
879 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
882 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
883 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
885 self.filler, self.space = self.char2id["#"], self.char2id[" "]
887 self.train_input = self.tensorize(train_sequences)
888 self.test_input = self.tensorize(test_sequences)
890 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
892 def batches(self, split="train", nb_to_use=-1, desc=None):
893 assert split in {"train", "test"}
894 input = self.train_input if split == "train" else self.test_input
896 input = input[:nb_to_use]
898 desc = f"epoch-{split}"
899 for batch in tqdm.tqdm(
900 input.split(self.batch_size), dynamic_ncols=True, desc=desc
902 last = (batch != self.filler).max(0).values.nonzero().max() + 3
903 batch = batch[:, :last]
906 def vocabulary_size(self):
909 def seq2str(self, s):
910 return "".join([self.id2char[k.item()] for k in s])
918 deterministic_synthesis,
921 def compute_nb_correct(input):
922 result = input.clone()
923 s = (result == self.space).long()
924 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
925 result = (1 - ar_mask) * result + ar_mask * self.filler
926 masked_inplace_autoregression(
931 deterministic_synthesis,
935 nb_total = input.size(0)
936 nb_correct = (input == result).long().min(1).values.sum()
938 #######################################################################
939 # Comput predicted vs. true variable values
941 nb_delta = torch.zeros(5, dtype=torch.int64)
944 values_input = expr.extract_results([self.seq2str(s) for s in input])
945 values_result = expr.extract_results([self.seq2str(s) for s in result])
947 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
949 with open(filename, "w") as f:
950 for i, r in zip(values_input, values_result):
951 for n, vi in i.items():
953 f.write(f"{vi} {-1 if vr is None else vr}\n")
955 if vr is None or vr < 0:
959 if d >= nb_delta.size(0):
964 ######################################################################
966 return nb_total, nb_correct, nb_delta, nb_missed
973 ) = compute_nb_correct(self.test_input[:10000])
976 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}%"
979 nb_total = test_nb_delta.sum() + test_nb_missed
980 for d in range(test_nb_delta.size(0)):
982 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
985 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
988 ##############################################################
989 # Log a few generated sequences
990 if input_file is None:
991 input = self.test_input[:10]
993 with open(input_file, "r") as f:
994 sequences = [e.strip() for e in f.readlines()]
995 sequences = [s + " " + "#" * 50 for s in sequences]
996 input = self.tensorize(sequences)
998 result = input.clone()
999 s = (result == self.space).long()
1000 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1001 result = (1 - ar_mask) * result + ar_mask * self.filler
1003 for n in range(result.size(0)):
1004 logger(f"test_before {self.seq2str(result[n])}")
1006 masked_inplace_autoregression(
1011 deterministic_synthesis,
1015 correct = (1 - ar_mask) * self.space + ar_mask * input
1016 for n in range(result.size(0)):
1017 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1018 logger(f"test_after {self.seq2str(result[n])} {comment}")
1019 logger(f"truth {self.seq2str(correct[n])}")
1020 ##############################################################
1023 ######################################################################
1036 device=torch.device("cpu"),
1037 device_storage=torch.device("cpu"),
1041 self.batch_size = batch_size
1042 self.device = device
1051 ) = world.create_data_and_processors(
1056 nb_epochs=vqae_nb_epochs,
1059 device_storage=device_storage,
1062 print(f"{train_action_seq.size()=}")
1064 train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1065 test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1067 nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1068 nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1070 self.len_frame_seq = train_frame_seq.size(1)
1071 self.len_action_seq = train_action_seq.size(1)
1072 self.nb_codes = nb_frame_codes + nb_action_codes
1074 train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1075 print(f"{train_action_seq.device=} {nb_frame_codes.device=}")
1076 train_action_seq += nb_frame_codes
1077 self.train_input = torch.cat(
1078 (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1081 test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1082 test_action_seq += nb_frame_codes
1083 self.test_input = torch.cat(
1084 (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1087 def batches(self, split="train", nb_to_use=-1, desc=None):
1088 assert split in {"train", "test"}
1089 input = self.train_input if split == "train" else self.test_input
1091 input = input[:nb_to_use]
1093 desc = f"epoch-{split}"
1094 for batch in tqdm.tqdm(
1095 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1097 yield batch.to(self.device)
1099 def vocabulary_size(self):
1100 return self.nb_codes
1102 def produce_results(
1103 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1106 2 * self.len_frame_seq + self.len_action_seq, device=self.device
1109 input = self.test_input[:64].to(self.device)
1110 result = input.clone()
1113 (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1115 result *= 1 - ar_mask
1117 masked_inplace_autoregression(
1122 deterministic_synthesis,
1126 seq_start = input[:, : self.len_frame_seq]
1127 seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1128 seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1131 (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1133 result = result.reshape(-1, result.size(-1))
1134 print(f"{result.size()=}")
1136 frames = self.seq2frame(result)
1137 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1138 torchvision.utils.save_image(
1139 frames.float() / (world.Box.nb_rgb_levels - 1),
1145 logger(f"wrote {image_name}")
1148 ######################################################################