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,))]
91 device=torch.device("cpu"),
95 self.batch_size = batch_size
97 problems = [ProblemByheart()]
100 def generate_sequences(nb_samples):
101 problem_indexes = torch.randint(len(problems), (nb_samples,))
102 nb_samples_per_problem = torch.one_hot(problem_indexes).sum(0)
103 print(f"{nb_samples_per_problem}")
105 for nb, p in zip(nb_samples_per_problem, problems):
106 all_seq.append(p.generate_sequences(nb_samples_per_problem[nb]))
109 train_seq = generate_sequences(nb_train_samples)
110 test_seq = generate_sequences(nb_test_samples)
112 for strain, stest in zip(train_seq, test_seq):
113 s = torch.cat((strain, stest), 0)
115 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
117 def batches(self, split="train", nb_to_use=-1, desc=None):
118 assert split in {"train", "test"}
119 input = self.train_input if split == "train" else self.test_input
121 input = input[:nb_to_use]
123 desc = f"epoch-{split}"
124 for batch in tqdm.tqdm(
125 input.split(self.batch_size), dynamic_ncols=True, desc=desc
129 def vocabulary_size(self):
133 self, n_epoch, model, result_dir, logger, deterministic_synthesis
136 # 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}%"
141 ######################################################################
146 class PicoCLVR(Task):
147 # Make a tensor from a list of strings
148 def tensorize(self, descr):
149 token_descr = [s.strip().split(" ") for s in descr]
150 l = max([len(s) for s in token_descr])
151 token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
152 id_descr = [[self.token2id[u] for u in s] for s in token_descr]
153 return torch.tensor(id_descr, device=self.device)
155 # Make a list of strings from a tensor
156 def detensorize(self, x):
157 return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
159 # trim all the tensors in the tuple z to remove as much token from
160 # left and right in the first tensor. If z is a tuple, all its
161 # elements are trimed according to the triming for the first
162 def trim(self, z, token="<nul>"):
163 n = self.token2id[token]
166 i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
167 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
168 return tuple([t[:, a:b] for t in z])
170 i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
171 a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
174 ######################
185 device=torch.device("cpu"),
191 def generate_descr(nb, cache_suffix, pruner):
192 return picoclvr.generate(
202 self.batch_size = batch_size
204 self.pruner_train = pruner_train
205 self.pruner_eval = pruner_eval
207 if logger is not None:
209 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
212 self.train_descr = generate_descr(
213 nb_train_samples, "train", pruner=self.pruner_train
215 self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
217 # Build the tokenizer
218 tokens = {"<nul>", "<img>"}
219 for d in [self.train_descr, self.test_descr]:
221 for t in s.strip().split(" "):
223 # make this set a sorted list to get the same tensors given
225 tokens = list(tokens)
227 self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
228 self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
229 self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
231 # Tokenize the train and test sets
232 self.train_input = self.tensorize(self.train_descr)
233 self.test_input = self.tensorize(self.test_descr)
235 def batches(self, split="train"):
236 assert split in {"train", "test"}
237 input = self.train_input if split == "train" else self.test_input
238 for batch in tqdm.tqdm(
239 input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
241 yield self.trim(batch)
243 def vocabulary_size(self):
244 return len(self.token2id)
246 def compute_missing_properties(
247 self, n_epoch, model, logger, deterministic_synthesis, pruner=None
249 acc_nb_requested_properties = []
250 acc_nb_missing_properties = []
253 for input in tqdm.tqdm(
254 self.test_input.split(self.batch_size),
256 desc=f"test-properties",
258 result = input.clone()
259 ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
260 result = (1 - ar_mask) * result + ar_mask * self.t_nul
261 masked_inplace_autoregression(
266 deterministic_synthesis,
267 progress_bar_desc=None,
271 result_descr = self.detensorize(result)
272 np = picoclvr.nb_properties(
278 nb_requested_properties, _, nb_missing_properties = zip(*np)
279 acc_nb_requested_properties += nb_requested_properties
280 acc_nb_missing_properties += nb_missing_properties
281 acc_nb_results += len(result_descr)
283 nb_requested_properties = sum(acc_nb_requested_properties)
284 nb_missing_properties = sum(acc_nb_missing_properties)
286 prefix = "" if pruner is None else "pruned_"
287 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
289 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
292 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
295 ######################################################################
298 self, n_epoch, model, result_dir, logger, deterministic_synthesis
300 self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
302 if self.pruner_eval is not None:
303 self.compute_missing_properties(n_epoch, model, self.pruner_eval)
305 nb_tokens_to_generate = self.height * self.width + 3
310 for primer_descr in [
311 "red above green <sep> green top <sep> blue right of red",
312 "there is red <sep> there is yellow <sep> there is blue",
313 "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
314 "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
316 primer += [primer_descr + " <img>"] * nb_per_primer
318 result = self.tensorize(primer)
319 fill = result.new_full(
320 result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
322 result = torch.cat((result, fill), 1)
323 ar_mask = (result == self.t_nul).long()
324 masked_inplace_autoregression(
329 deterministic_synthesis,
332 result_descr = self.detensorize(result)
334 np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
336 acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
337 acc_nb_results = len(result_descr)
339 nb_requested_properties = sum(acc_nb_requested_properties)
340 nb_missing_properties = sum(acc_nb_missing_properties)
343 logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
345 f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
348 f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
351 img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
355 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
359 torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
365 image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
366 torchvision.utils.save_image(
367 img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
369 logger(f"wrote {image_name}")
372 ######################################################################
377 self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
381 self.nb_train_samples = (nb_train_samples,)
382 self.nb_test_samples = (nb_test_samples,)
383 self.batch_size = batch_size
385 data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
386 self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
387 data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
388 self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
390 def batches(self, split="train", nb_to_use=-1, desc=None):
391 assert split in {"train", "test"}
392 input = self.train_input if split == "train" else self.test_input
394 input = input[:nb_to_use]
396 desc = f"epoch-{split}"
397 for batch in tqdm.tqdm(
398 input.split(self.batch_size), dynamic_ncols=True, desc=desc
402 def vocabulary_size(self):
406 self, n_epoch, model, result_dir, logger, deterministic_synthesis
408 results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
409 ar_mask = torch.full_like(results, 1)
410 masked_inplace_autoregression(
415 deterministic_synthesis,
418 image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
419 torchvision.utils.save_image(
420 1 - results.reshape(-1, 1, 28, 28) / 255.0,
425 logger(f"wrote {image_name}")
428 ######################################################################
434 def map2seq(self, *m):
435 return torch.cat([x.flatten(1) for x in m], 1)
437 def seq2map(self, s):
438 s = s.reshape(s.size(0), -1, self.height, self.width)
439 return (s[:, k] for k in range(s.size(1)))
449 device=torch.device("cpu"),
453 self.batch_size = batch_size
458 train_mazes, train_paths, _ = maze.create_maze_data(
463 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
465 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
467 test_mazes, test_paths, _ = maze.create_maze_data(
472 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
474 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
476 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
478 def batches(self, split="train", nb_to_use=-1, desc=None):
479 assert split in {"train", "test"}
480 input = self.train_input if split == "train" else self.test_input
482 input = input[:nb_to_use]
484 desc = f"epoch-{split}"
485 for batch in tqdm.tqdm(
486 input.split(self.batch_size), dynamic_ncols=True, desc=desc
490 def vocabulary_size(self):
494 self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
496 nb_total, nb_correct = 0, 0
498 self.width * self.height,
499 self.width * self.height,
504 for input in self.batches(split, nb_to_use):
505 result = input.clone()
506 ar_mask = result.new_zeros(result.size())
507 ar_mask[:, self.height * self.width :] = 1
508 result *= 1 - ar_mask
509 masked_inplace_autoregression(
514 deterministic_synthesis,
515 progress_bar_desc=None,
518 mazes, paths = self.seq2map(result)
519 path_correctness = maze.path_correctness(mazes, paths)
520 nb_correct += path_correctness.long().sum()
521 nb_total += mazes.size(0)
523 optimal_path_lengths = (
524 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
526 predicted_path_lengths = (
527 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
529 optimal_path_lengths = optimal_path_lengths[path_correctness]
530 predicted_path_lengths = predicted_path_lengths[path_correctness]
531 count[optimal_path_lengths, predicted_path_lengths] += 1
537 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
540 return nb_total, nb_correct, count
543 self, n_epoch, model, result_dir, logger, deterministic_synthesis
545 train_nb_total, train_nb_correct, count = self.compute_error(
549 deterministic_synthesis=deterministic_synthesis,
552 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}%"
555 test_nb_total, test_nb_correct, count = self.compute_error(
559 deterministic_synthesis=deterministic_synthesis,
562 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}%"
565 if count is not None:
566 proportion_optimal = count.diagonal().sum().float() / count.sum()
567 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
569 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
571 for i in range(count.size(0)):
572 for j in range(count.size(1)):
573 eol = " " if j < count.size(1) - 1 else "\n"
574 f.write(f"{count[i,j]}{eol}")
576 input = self.test_input[:48]
577 result = input.clone()
578 ar_mask = result.new_zeros(result.size())
579 ar_mask[:, self.height * self.width :] = 1
580 result *= 1 - ar_mask
581 masked_inplace_autoregression(
586 deterministic_synthesis,
590 mazes, paths = self.seq2map(input)
591 _, predicted_paths = self.seq2map(result)
593 filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
598 predicted_paths=predicted_paths,
599 path_correct=maze.path_correctness(mazes, predicted_paths),
600 path_optimal=maze.path_optimality(paths, predicted_paths),
602 logger(f"wrote {filename}")
605 ######################################################################
622 device=torch.device("cpu"),
626 self.batch_size = batch_size
630 self.prompt_length = prompt_length
632 self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
641 self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
651 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
653 def batches(self, split="train", nb_to_use=-1, desc=None):
654 assert split in {"train", "test"}
655 input = self.train_input if split == "train" else self.test_input
657 input = input[:nb_to_use]
659 desc = f"epoch-{split}"
660 for batch in tqdm.tqdm(
661 input.split(self.batch_size), dynamic_ncols=True, desc=desc
665 def vocabulary_size(self):
669 self, n_epoch, model, result_dir, logger, deterministic_synthesis
671 def compute_nb_correct(input, prior_visits):
672 result = input.clone()
673 i = torch.arange(result.size(1), device=result.device)[None, :]
675 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
679 result *= 1 - ar_mask
681 masked_inplace_autoregression(
686 deterministic_synthesis,
690 nb_total = ((prior_visits > 0) * ar_mask).sum()
692 nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
694 return nb_total, nb_correct
696 test_nb_total, test_nb_correct = compute_nb_correct(
697 self.test_input[:1000], self.test_prior_visits[:1000]
701 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}%"
705 ######################################################################
721 fraction_values_for_train=None,
722 device=torch.device("cpu"),
726 self.batch_size = batch_size
727 self.nb_steps = nb_steps
728 self.nb_stacks = nb_stacks
729 self.nb_digits = nb_digits
732 if fraction_values_for_train is None:
733 values_for_train = None
734 values_for_test = None
736 all = torch.randperm(10**nb_digits)
737 nb_for_train = int(all.size(0) * fraction_values_for_train)
738 values_for_train = all[:nb_for_train]
739 values_for_test = all[nb_for_train:]
741 self.train_input, self.train_stack_counts = stack.generate_sequences(
750 self.test_input, self.test_stack_counts = stack.generate_sequences(
759 i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
760 counts = self.test_stack_counts.flatten()[i.flatten()]
761 counts = F.one_hot(counts).sum(0)
762 logger(f"test_pop_stack_counts {counts}")
764 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
766 def batches(self, split="train", nb_to_use=-1, desc=None):
767 assert split in {"train", "test"}
768 input = self.train_input if split == "train" else self.test_input
770 input = input[:nb_to_use]
772 desc = f"epoch-{split}"
773 for batch in tqdm.tqdm(
774 input.split(self.batch_size), dynamic_ncols=True, desc=desc
778 def vocabulary_size(self):
782 self, n_epoch, model, result_dir, logger, deterministic_synthesis
784 def compute_nb_correct(input):
785 result = input.clone()
786 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
787 ar_mask = (result != input).long()
788 masked_inplace_autoregression(
793 deterministic_synthesis,
797 errors = ((result != input).long() * ar_mask).reshape(
798 -1, 1 + self.nb_digits
800 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
802 nb_total = ar_mask.max(1).values.sum()
803 nb_correct = nb_total - errors.max(1).values.sum()
805 return nb_total, nb_correct
807 test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
810 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}%"
813 ##############################################################
814 # Log a few generated sequences
815 input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
816 result = input.clone()
817 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
818 ar_mask = (result != input).long()
820 # for n in range(result.size(0)):
822 # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
825 masked_inplace_autoregression(
830 deterministic_synthesis,
834 for n in range(result.size(0)):
836 f"test_after {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
838 ##############################################################
841 ######################################################################
848 def tensorize(self, sequences):
849 len_max = max([len(x) for x in sequences])
854 [self.char2id[c] for c in s + "#" * (len_max - len(s))]
871 device=torch.device("cpu"),
875 self.batch_size = batch_size
878 train_sequences = expr.generate_sequences(
880 nb_variables=nb_variables,
881 length=sequence_length,
882 operand_max=operand_max,
883 result_max=result_max,
886 test_sequences = expr.generate_sequences(
888 nb_variables=nb_variables,
889 length=sequence_length,
890 operand_max=operand_max,
891 result_max=result_max,
894 symbols = list(set("#" + "".join(train_sequences + test_sequences)))
897 self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
898 self.id2char = dict([(n, c) for c, n in self.char2id.items()])
900 self.filler, self.space = self.char2id["#"], self.char2id[" "]
902 self.train_input = self.tensorize(train_sequences)
903 self.test_input = self.tensorize(test_sequences)
905 self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
907 def batches(self, split="train", nb_to_use=-1, desc=None):
908 assert split in {"train", "test"}
909 input = self.train_input if split == "train" else self.test_input
911 input = input[:nb_to_use]
913 desc = f"epoch-{split}"
914 for batch in tqdm.tqdm(
915 input.split(self.batch_size), dynamic_ncols=True, desc=desc
917 last = (batch != self.filler).max(0).values.nonzero().max() + 3
918 batch = batch[:, :last]
921 def vocabulary_size(self):
924 def seq2str(self, s):
925 return "".join([self.id2char[k.item()] for k in s])
933 deterministic_synthesis,
936 def compute_nb_correct(input):
937 result = input.clone()
938 s = (result == self.space).long()
939 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
940 result = (1 - ar_mask) * result + ar_mask * self.filler
941 masked_inplace_autoregression(
946 deterministic_synthesis,
950 nb_total = input.size(0)
951 nb_correct = (input == result).long().min(1).values.sum()
953 #######################################################################
954 # Comput predicted vs. true variable values
956 nb_delta = torch.zeros(5, dtype=torch.int64)
959 values_input = expr.extract_results([self.seq2str(s) for s in input])
960 values_result = expr.extract_results([self.seq2str(s) for s in result])
962 filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
964 with open(filename, "w") as f:
965 for i, r in zip(values_input, values_result):
966 for n, vi in i.items():
968 f.write(f"{vi} {-1 if vr is None else vr}\n")
970 if vr is None or vr < 0:
974 if d >= nb_delta.size(0):
979 ######################################################################
981 return nb_total, nb_correct, nb_delta, nb_missed
988 ) = compute_nb_correct(self.test_input[:10000])
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 nb_total = test_nb_delta.sum() + test_nb_missed
995 for d in range(test_nb_delta.size(0)):
997 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1000 f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1003 ##############################################################
1004 # Log a few generated sequences
1005 if input_file is None:
1006 input = self.test_input[:10]
1008 with open(input_file, "r") as f:
1009 sequences = [e.strip() for e in f.readlines()]
1010 sequences = [s + " " + "#" * 50 for s in sequences]
1011 input = self.tensorize(sequences)
1013 result = input.clone()
1014 s = (result == self.space).long()
1015 ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1016 result = (1 - ar_mask) * result + ar_mask * self.filler
1018 for n in range(result.size(0)):
1019 logger(f"test_before {self.seq2str(result[n])}")
1021 masked_inplace_autoregression(
1026 deterministic_synthesis,
1030 correct = (1 - ar_mask) * self.space + ar_mask * input
1031 for n in range(result.size(0)):
1032 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1033 logger(f"test_after {self.seq2str(result[n])} {comment}")
1034 logger(f"truth {self.seq2str(correct[n])}")
1035 ##############################################################
1038 ######################################################################
1051 device=torch.device("cpu"),
1052 device_storage=torch.device("cpu"),
1056 self.batch_size = batch_size
1057 self.device = device
1066 ) = world.create_data_and_processors(
1071 nb_epochs=vqae_nb_epochs,
1074 device_storage=device_storage,
1077 print(f"{train_action_seq.size()=}")
1079 train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1080 test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1082 nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1083 nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1085 self.len_frame_seq = train_frame_seq.size(1)
1086 self.len_action_seq = train_action_seq.size(1)
1087 self.nb_codes = nb_frame_codes + nb_action_codes
1089 train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1090 print(f"{train_action_seq.device=} {nb_frame_codes.device=}")
1091 train_action_seq += nb_frame_codes
1092 self.train_input = torch.cat(
1093 (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1096 test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1097 test_action_seq += nb_frame_codes
1098 self.test_input = torch.cat(
1099 (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1102 def batches(self, split="train", nb_to_use=-1, desc=None):
1103 assert split in {"train", "test"}
1104 input = self.train_input if split == "train" else self.test_input
1106 input = input[:nb_to_use]
1108 desc = f"epoch-{split}"
1109 for batch in tqdm.tqdm(
1110 input.split(self.batch_size), dynamic_ncols=True, desc=desc
1112 yield batch.to(self.device)
1114 def vocabulary_size(self):
1115 return self.nb_codes
1117 def produce_results(
1118 self, n_epoch, model, result_dir, logger, deterministic_synthesis
1121 2 * self.len_frame_seq + self.len_action_seq, device=self.device
1124 input = self.test_input[:64].to(self.device)
1125 result = input.clone()
1128 (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1130 result *= 1 - ar_mask
1132 masked_inplace_autoregression(
1137 deterministic_synthesis,
1141 seq_start = input[:, : self.len_frame_seq]
1142 seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1143 seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1146 (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1148 result = result.reshape(-1, result.size(-1))
1149 print(f"{result.size()=}")
1151 frames = self.seq2frame(result)
1152 image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1153 torchvision.utils.save_image(
1154 frames.float() / (world.Box.nb_rgb_levels - 1),
1160 logger(f"wrote {image_name}")
1163 ######################################################################