e14ceb76e18ba38283acb99a5f214d42b92cc1b1
[picoclvr.git] / tasks.py
1 #!/usr/bin/env python
2
3 import math, os, tqdm
4
5 import torch, torchvision
6
7 from torch import nn
8 from torch.nn import functional as F
9
10 ######################################################################
11
12
13 def masked_inplace_autoregression(
14     model,
15     batch_size,
16     input,
17     ar_mask,
18     deterministic_synthesis,
19     forbidden_tokens=None,
20     progress_bar_desc="autoregression",
21     device=torch.device("cpu"),
22 ):
23     assert input.size() == ar_mask.size()
24
25     batches = zip(input.split(batch_size), ar_mask.split(batch_size))
26
27     if progress_bar_desc is not None:
28         batches = tqdm.tqdm(
29             batches,
30             dynamic_ncols=True,
31             desc=progress_bar_desc,
32             # total=input.size(0) // batch_size,
33         )
34
35     with torch.autograd.no_grad():
36         t = model.training
37         model.eval()
38
39         for input, ar_mask in batches:
40             model.masked_inplace_autoregression(
41                 input, ar_mask, forbidden_tokens, deterministic_synthesis
42             )
43
44         model.train(t)
45
46
47 ######################################################################
48
49
50 class Task:
51     def batches(self, split="train"):
52         pass
53
54     def vocabulary_size(self):
55         pass
56
57     def produce_results(
58         self, n_epoch, model, result_dir, logger, deterministic_synthesis
59     ):
60         pass
61
62
63 ######################################################################
64
65
66 class Problem:
67     def generate_sequences(self, nb):
68         pass
69
70     def seq2str(self, seq):
71         return "[NOT IMPLEMENTED]"
72
73
74 ####################
75
76
77 class ProblemLevel0(Problem):
78     def __init__(self, nb_sentences=100, len_prompt=5, len_result=5):
79         self.seq = torch.randint(10, (nb_sentences, len_prompt + 1 + len_result))
80         self.seq[:, len_prompt] = 10
81
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
87
88
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,
97         )
98
99     def generate_sequences(self, nb):
100         nb_operators = torch.randint(self.operators.size(0), (nb,))
101         operators = self.operators[nb_operators]
102         nb_operators = (
103             nb_operators[:, None]
104             // 10 ** torch.arange(self.len_nb_operator - 1, -1, -1)
105         ) % 10
106         marker1 = torch.full((nb, 1), 10)
107         # source = torch.randint(10, (nb, self.len_source))
108         source = torch.rand(nb, 10).sort(dim=1).indices[:, : self.len_source]
109         marker2 = torch.full((nb, 1), 11)
110         result = operators.bmm(source[:, :, None]).squeeze(-1)
111         print(f"{nb_operators.dtype=} {marker1.dtype=}")
112         sequences = torch.cat((nb_operators, marker1, source, marker2, result), 1)
113         print(f"{sequences.size()=}")
114         ar_mask = (sequences == 11).long()
115         ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
116         return sequences, ar_mask
117
118     def seq2str(self, seq):
119         return "".join("0123456789|>"[x.item()] for x in seq)
120
121
122 class ProblemLevel2(Problem):
123     def __init__(self, len_source=5, len_result=8):
124         self.len_source = len_source
125         self.len_result = len_result
126
127     def generate_sequences(self, nb):
128         operators = F.one_hot(
129             torch.rand(nb, self.len_result, self.len_source).argmax(-1),
130             num_classes=self.len_source,
131         )
132         source1 = torch.rand(nb, 10).sort(dim=1).indices[:, : self.len_source]
133         # source1 = torch.randint(10, (nb, self.len_source))
134         marker1 = torch.full((nb, 1), 10)
135         result1 = operators.bmm(source1[:, :, None]).squeeze(-1)
136         marker2 = torch.full((nb, 1), 11)
137         source2 = torch.randint(10, (nb, self.len_source))
138         marker3 = torch.full((nb, 1), 12)
139         result2 = operators.bmm(source2[:, :, None]).squeeze(-1)
140
141         sequences = torch.cat(
142             (source1, marker1, result1, marker2, source2, marker3, result2), 1
143         )
144         ar_mask = (sequences == 12).long()
145         ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
146         return sequences, ar_mask
147
148     def seq2str(self, seq):
149         return "".join("0123456789>|~"[x.item()] for x in seq)
150
151
152 ####################
153
154
155 class ProblemAddition(Problem):
156     def __init__(self, nb_digits=10, zero_padded=False, inverted_result=False):
157         self.nb_digits = nb_digits
158         self.zero_padded = zero_padded
159         self.inverted_result = inverted_result
160         self.char2id = dict([(c, n) for n, c in enumerate("0123456789+=$")])
161         self.id2char = dict([(n, c) for c, n in self.char2id.items()])
162
163     def tensorize(self, strings):
164         len_max = max([len(x) for x in strings])
165         return torch.cat(
166             [
167                 torch.tensor(
168                     [
169                         [self.char2id[c] for c in s + "$" * (len_max - len(s))]
170                         for s in strings
171                     ]
172                 )
173             ],
174             0,
175         )
176
177     def generate_sequences(self, nb):
178         sequences = []
179         for k in range(nb):
180             a, b = torch.randint(10**self.nb_digits, (2,))
181             c = a + b
182             a, b, c = str(a.item()), str(b.item()), str(c.item())
183             if self.zero_padded:
184                 a = "0" * (self.nb_digits - len(a)) + a
185                 b = "0" * (self.nb_digits - len(b)) + b
186                 c = "0" * (self.nb_digits + 1 - len(c)) + c
187             if self.inverted_result:
188                 c = c[::-1]
189             sequences.append(f"{a}+{b}={c}$")
190
191         sequences = self.tensorize(sequences)
192         ar_mask = (sequences == self.char2id["="]).long()
193         ar_mask = (ar_mask.cumsum(1) - ar_mask).clamp(max=1)
194         return sequences, ar_mask
195
196     def seq2str(self, seq):
197         return "".join(self.id2char[x.item()] for x in seq)
198
199
200 # class ProblemUnion(Problem):
201 # problems = [ProblemByheart()]
202 # nb_common_codes = 100
203
204 # def generate_sequences(nb_samples):
205 # problem_indexes = torch.randint(len(problems), (nb_samples,))
206 # nb_samples_per_problem = torch.one_hot(problem_indexes).sum(0)
207 # print(f"{nb_samples_per_problem}")
208 # all_seq = []
209 # for nb, p in zip(nb_samples_per_problem, problems):
210 # all_seq.append(p.generate_sequences(nb_samples_per_problem[nb]))
211 # return all_seq
212
213 # for strain, stest in zip(train_seq, test_seq):
214 # s = torch.cat((strain, stest), 0)
215
216 ####################
217
218
219 class SandBox(Task):
220     def __init__(
221         self,
222         problem,
223         nb_train_samples,
224         nb_test_samples,
225         batch_size,
226         logger=None,
227         device=torch.device("cpu"),
228         max_nb_codes=1024,
229     ):
230         super().__init__()
231
232         self.batch_size = batch_size
233         self.device = device
234         self.problem = problem
235
236         self.train_input, self.train_ar_mask = self.problem.generate_sequences(
237             nb_train_samples
238         )
239         self.test_input, self.test_ar_mask = self.problem.generate_sequences(
240             nb_test_samples
241         )
242
243         self.train_input, self.train_ar_mask = self.train_input.to(
244             device
245         ), self.train_ar_mask.to(device)
246         self.test_input, self.test_ar_mask = self.test_input.to(
247             device
248         ), self.test_ar_mask.to(device)
249
250         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
251
252         # A bit of paranoia never hurts
253         assert (
254             self.nb_codes <= max_nb_codes
255             and self.train_input.min() >= 0
256             and self.test_input.min() >= 0
257             and tuple(self.train_ar_mask.unique()) == (0, 1)
258             and tuple(self.test_ar_mask.unique()) == (0, 1)
259         )
260
261     def batches(self, split="train", nb_to_use=-1, desc=None):
262         assert split in {"train", "test"}
263         input = self.train_input if split == "train" else self.test_input
264         if nb_to_use > 0:
265             input = input[:nb_to_use]
266         if desc is None:
267             desc = f"epoch-{split}"
268         for batch in tqdm.tqdm(
269             input.split(self.batch_size), dynamic_ncols=True, desc=desc
270         ):
271             yield batch
272
273     def vocabulary_size(self):
274         return self.nb_codes
275
276     def produce_results(
277         self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
278     ):
279         def compute_accuracy(input, ar_mask, logger=None):
280             input, ar_mask = input[:nmax], ar_mask[:nmax]
281             result = input.clone() * (1 - ar_mask)
282
283             masked_inplace_autoregression(
284                 model,
285                 self.batch_size,
286                 result,
287                 ar_mask,
288                 deterministic_synthesis,
289                 progress_bar_desc=None,
290                 device=self.device,
291             )
292
293             if logger is not None:
294                 for sp, st in zip(result[:10], input[:10]):
295                     logger(
296                         f"test_sequences {n_epoch} prediction   {self.problem.seq2str(sp)}"
297                     )
298                     logger(
299                         f"               {n_epoch} ground truth {self.problem.seq2str(st)}"
300                     )
301
302             nb_total = ar_mask.sum().item()
303             nb_correct = ((result == input).long() * ar_mask).sum().item()
304
305             return nb_total, nb_correct
306
307         train_nb_total, train_nb_correct = compute_accuracy(
308             self.train_input, self.train_ar_mask
309         )
310
311         logger(
312             f"accuracy_train {n_epoch} nb_total {train_nb_total} nb_correct {train_nb_correct} accuracy {(100.0*train_nb_correct)/train_nb_total:.02f}%"
313         )
314
315         test_nb_total, test_nb_correct = compute_accuracy(
316             self.test_input, self.test_ar_mask, logger
317         )
318
319         logger(
320             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}%"
321         )
322
323
324 ######################################################################
325
326 import picoclvr
327
328
329 class PicoCLVR(Task):
330     # Make a tensor from a list of strings
331     def tensorize(self, descr):
332         token_descr = [s.strip().split(" ") for s in descr]
333         l = max([len(s) for s in token_descr])
334         token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
335         id_descr = [[self.token2id[u] for u in s] for s in token_descr]
336         return torch.tensor(id_descr, device=self.device)
337
338     # Make a list of strings from a tensor
339     def detensorize(self, x):
340         return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
341
342     # trim all the tensors in the tuple z to remove as much token from
343     # left and right in the first tensor. If z is a tuple, all its
344     # elements are trimed according to the triming for the first
345     def trim(self, z, token="<nul>"):
346         n = self.token2id[token]
347         if type(z) == tuple:
348             x = z[0]
349             i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
350             a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
351             return tuple([t[:, a:b] for t in z])
352         else:
353             i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
354             a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
355             return z[:, a:b]
356
357     ######################
358
359     def __init__(
360         self,
361         nb_train_samples,
362         nb_test_samples,
363         batch_size,
364         height,
365         width,
366         nb_colors=5,
367         logger=None,
368         device=torch.device("cpu"),
369         pruner_train=None,
370         pruner_eval=None,
371     ):
372         super().__init__()
373
374         def generate_descr(nb, cache_suffix, pruner):
375             return picoclvr.generate(
376                 nb,
377                 height=self.height,
378                 width=self.width,
379                 nb_colors=nb_colors,
380                 pruner=pruner,
381             )
382
383         self.height = height
384         self.width = width
385         self.batch_size = batch_size
386         self.device = device
387         self.pruner_train = pruner_train
388         self.pruner_eval = pruner_eval
389
390         if logger is not None:
391             logger(
392                 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
393             )
394
395         self.train_descr = generate_descr(
396             nb_train_samples, "train", pruner=self.pruner_train
397         )
398         self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
399
400         # Build the tokenizer
401         tokens = {"<nul>", "<img>"}
402         for d in [self.train_descr, self.test_descr]:
403             for s in d:
404                 for t in s.strip().split(" "):
405                     tokens.add(t)
406         # make this set a sorted list to get the same tensors given
407         # the same descr
408         tokens = list(tokens)
409         tokens.sort()
410         self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
411         self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
412         self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
413
414         # Tokenize the train and test sets
415         self.train_input = self.tensorize(self.train_descr)
416         self.test_input = self.tensorize(self.test_descr)
417
418     def batches(self, split="train"):
419         assert split in {"train", "test"}
420         input = self.train_input if split == "train" else self.test_input
421         for batch in tqdm.tqdm(
422             input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
423         ):
424             yield self.trim(batch)
425
426     def vocabulary_size(self):
427         return len(self.token2id)
428
429     def compute_missing_properties(
430         self, n_epoch, model, logger, deterministic_synthesis, pruner=None
431     ):
432         acc_nb_requested_properties = []
433         acc_nb_missing_properties = []
434         acc_nb_results = 0
435
436         for input in tqdm.tqdm(
437             self.test_input.split(self.batch_size),
438             dynamic_ncols=True,
439             desc=f"test-properties",
440         ):
441             result = input.clone()
442             ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
443             result = (1 - ar_mask) * result + ar_mask * self.t_nul
444             masked_inplace_autoregression(
445                 model,
446                 self.batch_size,
447                 result,
448                 ar_mask,
449                 deterministic_synthesis,
450                 progress_bar_desc=None,
451                 device=self.device,
452             )
453
454             result_descr = self.detensorize(result)
455             np = picoclvr.nb_properties(
456                 result_descr,
457                 height=self.height,
458                 width=self.width,
459                 pruner=pruner,
460             )
461             nb_requested_properties, _, nb_missing_properties = zip(*np)
462             acc_nb_requested_properties += nb_requested_properties
463             acc_nb_missing_properties += nb_missing_properties
464             acc_nb_results += len(result_descr)
465
466         nb_requested_properties = sum(acc_nb_requested_properties)
467         nb_missing_properties = sum(acc_nb_missing_properties)
468
469         prefix = "" if pruner is None else "pruned_"
470         logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
471         logger(
472             f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
473         )
474         logger(
475             f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
476         )
477
478     ######################################################################
479
480     def produce_results(
481         self, n_epoch, model, result_dir, logger, deterministic_synthesis
482     ):
483         self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
484
485         if self.pruner_eval is not None:
486             self.compute_missing_properties(n_epoch, model, self.pruner_eval)
487
488         nb_tokens_to_generate = self.height * self.width + 3
489         result_descr = []
490         nb_per_primer = 8
491         primer = []
492
493         for primer_descr in [
494             "red above green <sep> green top <sep> blue right of red",
495             "there is red <sep> there is yellow <sep> there is blue",
496             "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
497             "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
498         ]:
499             primer += [primer_descr + " <img>"] * nb_per_primer
500
501         result = self.tensorize(primer)
502         fill = result.new_full(
503             result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
504         )
505         result = torch.cat((result, fill), 1)
506         ar_mask = (result == self.t_nul).long()
507         masked_inplace_autoregression(
508             model,
509             self.batch_size,
510             result,
511             ar_mask,
512             deterministic_synthesis,
513             device=self.device,
514         )
515         result_descr = self.detensorize(result)
516
517         np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
518
519         acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
520         acc_nb_results = len(result_descr)
521
522         nb_requested_properties = sum(acc_nb_requested_properties)
523         nb_missing_properties = sum(acc_nb_missing_properties)
524
525         prefix = "demo_"
526         logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
527         logger(
528             f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
529         )
530         logger(
531             f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
532         )
533
534         img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
535
536         if img.dim() == 5:
537             if img.size(1) == 1:
538                 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
539             else:
540                 img = torch.cat(
541                     [
542                         torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
543                         for x in img
544                     ],
545                     0,
546                 )
547
548         image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
549         torchvision.utils.save_image(
550             img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
551         )
552         logger(f"wrote {image_name}")
553
554
555 ######################################################################
556
557
558 class MNIST(Task):
559     def __init__(
560         self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
561     ):
562         super().__init__()
563
564         self.nb_train_samples = (nb_train_samples,)
565         self.nb_test_samples = (nb_test_samples,)
566         self.batch_size = batch_size
567         self.device = device
568         data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
569         self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
570         data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
571         self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
572
573     def batches(self, split="train", nb_to_use=-1, desc=None):
574         assert split in {"train", "test"}
575         input = self.train_input if split == "train" else self.test_input
576         if nb_to_use > 0:
577             input = input[:nb_to_use]
578         if desc is None:
579             desc = f"epoch-{split}"
580         for batch in tqdm.tqdm(
581             input.split(self.batch_size), dynamic_ncols=True, desc=desc
582         ):
583             yield batch
584
585     def vocabulary_size(self):
586         return 256
587
588     def produce_results(
589         self, n_epoch, model, result_dir, logger, deterministic_synthesis
590     ):
591         results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
592         ar_mask = torch.full_like(results, 1)
593         masked_inplace_autoregression(
594             model,
595             self.batch_size,
596             results,
597             ar_mask,
598             deterministic_synthesis,
599             device=self.device,
600         )
601         image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
602         torchvision.utils.save_image(
603             1 - results.reshape(-1, 1, 28, 28) / 255.0,
604             image_name,
605             nrow=16,
606             pad_value=0.8,
607         )
608         logger(f"wrote {image_name}")
609
610
611 ######################################################################
612
613 import maze
614
615
616 class Maze(Task):
617     def map2seq(self, *m):
618         return torch.cat([x.flatten(1) for x in m], 1)
619
620     def seq2map(self, s):
621         s = s.reshape(s.size(0), -1, self.height, self.width)
622         return (s[:, k] for k in range(s.size(1)))
623
624     def __init__(
625         self,
626         nb_train_samples,
627         nb_test_samples,
628         batch_size,
629         height,
630         width,
631         nb_walls,
632         device=torch.device("cpu"),
633     ):
634         super().__init__()
635
636         self.batch_size = batch_size
637         self.height = height
638         self.width = width
639         self.device = device
640
641         train_mazes, train_paths, _ = maze.create_maze_data(
642             nb_train_samples,
643             height=height,
644             width=width,
645             nb_walls=nb_walls,
646             progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
647         )
648         self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
649
650         test_mazes, test_paths, _ = maze.create_maze_data(
651             nb_test_samples,
652             height=height,
653             width=width,
654             nb_walls=nb_walls,
655             progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
656         )
657         self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
658
659         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
660
661     def batches(self, split="train", nb_to_use=-1, desc=None):
662         assert split in {"train", "test"}
663         input = self.train_input if split == "train" else self.test_input
664         if nb_to_use > 0:
665             input = input[:nb_to_use]
666         if desc is None:
667             desc = f"epoch-{split}"
668         for batch in tqdm.tqdm(
669             input.split(self.batch_size), dynamic_ncols=True, desc=desc
670         ):
671             yield batch
672
673     def vocabulary_size(self):
674         return self.nb_codes
675
676     def compute_error(
677         self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
678     ):
679         nb_total, nb_correct = 0, 0
680         count = torch.zeros(
681             self.width * self.height,
682             self.width * self.height,
683             device=self.device,
684             dtype=torch.int64,
685         )
686
687         for input in self.batches(split, nb_to_use):
688             result = input.clone()
689             ar_mask = result.new_zeros(result.size())
690             ar_mask[:, self.height * self.width :] = 1
691             result *= 1 - ar_mask
692             masked_inplace_autoregression(
693                 model,
694                 self.batch_size,
695                 result,
696                 ar_mask,
697                 deterministic_synthesis,
698                 progress_bar_desc=None,
699                 device=self.device,
700             )
701             mazes, paths = self.seq2map(result)
702             path_correctness = maze.path_correctness(mazes, paths)
703             nb_correct += path_correctness.long().sum()
704             nb_total += mazes.size(0)
705
706             optimal_path_lengths = (
707                 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
708             )
709             predicted_path_lengths = (
710                 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
711             )
712             optimal_path_lengths = optimal_path_lengths[path_correctness]
713             predicted_path_lengths = predicted_path_lengths[path_correctness]
714             count[optimal_path_lengths, predicted_path_lengths] += 1
715
716         if count.max() == 0:
717             count = None
718         else:
719             count = count[
720                 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
721             ]
722
723         return nb_total, nb_correct, count
724
725     def produce_results(
726         self, n_epoch, model, result_dir, logger, deterministic_synthesis
727     ):
728         train_nb_total, train_nb_correct, count = self.compute_error(
729             model,
730             "train",
731             nb_to_use=1000,
732             deterministic_synthesis=deterministic_synthesis,
733         )
734         logger(
735             f"accuracy_train {n_epoch} nb_total {train_nb_total} nb_correct {train_nb_correct} accuracy {(100.0*train_nb_correct)/train_nb_total:.02f}%"
736         )
737
738         test_nb_total, test_nb_correct, count = self.compute_error(
739             model,
740             "test",
741             nb_to_use=1000,
742             deterministic_synthesis=deterministic_synthesis,
743         )
744         logger(
745             f"accuracy_test {n_epoch} nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
746         )
747
748         if count is not None:
749             proportion_optimal = count.diagonal().sum().float() / count.sum()
750             logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
751             with open(
752                 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
753             ) as f:
754                 for i in range(count.size(0)):
755                     for j in range(count.size(1)):
756                         eol = " " if j < count.size(1) - 1 else "\n"
757                         f.write(f"{count[i,j]}{eol}")
758
759         input = self.test_input[:48]
760         result = input.clone()
761         ar_mask = result.new_zeros(result.size())
762         ar_mask[:, self.height * self.width :] = 1
763         result *= 1 - ar_mask
764         masked_inplace_autoregression(
765             model,
766             self.batch_size,
767             result,
768             ar_mask,
769             deterministic_synthesis,
770             device=self.device,
771         )
772
773         mazes, paths = self.seq2map(input)
774         _, predicted_paths = self.seq2map(result)
775
776         filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
777         maze.save_image(
778             filename,
779             mazes=mazes,
780             target_paths=paths,
781             predicted_paths=predicted_paths,
782             path_correct=maze.path_correctness(mazes, predicted_paths),
783             path_optimal=maze.path_optimality(paths, predicted_paths),
784         )
785         logger(f"wrote {filename}")
786
787
788 ######################################################################
789
790
791 import snake
792
793
794 class Snake(Task):
795     def __init__(
796         self,
797         nb_train_samples,
798         nb_test_samples,
799         batch_size,
800         height,
801         width,
802         nb_colors,
803         length,
804         prompt_length,
805         device=torch.device("cpu"),
806     ):
807         super().__init__()
808
809         self.batch_size = batch_size
810         self.height = height
811         self.width = width
812         self.device = device
813         self.prompt_length = prompt_length
814
815         self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
816             nb_train_samples,
817             height,
818             width,
819             nb_colors,
820             length,
821             prompt_length,
822             self.device,
823         )
824         self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
825             nb_test_samples,
826             height,
827             width,
828             nb_colors,
829             length,
830             prompt_length,
831             self.device,
832         )
833
834         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
835
836     def batches(self, split="train", nb_to_use=-1, desc=None):
837         assert split in {"train", "test"}
838         input = self.train_input if split == "train" else self.test_input
839         if nb_to_use > 0:
840             input = input[:nb_to_use]
841         if desc is None:
842             desc = f"epoch-{split}"
843         for batch in tqdm.tqdm(
844             input.split(self.batch_size), dynamic_ncols=True, desc=desc
845         ):
846             yield batch
847
848     def vocabulary_size(self):
849         return self.nb_codes
850
851     def produce_results(
852         self, n_epoch, model, result_dir, logger, deterministic_synthesis
853     ):
854         def compute_nb_correct(input, prior_visits):
855             result = input.clone()
856             i = torch.arange(result.size(1), device=result.device)[None, :]
857             ar_mask = (
858                 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
859                 .long()
860                 .expand_as(result)
861             )
862             result *= 1 - ar_mask
863
864             masked_inplace_autoregression(
865                 model,
866                 self.batch_size,
867                 result,
868                 ar_mask,
869                 deterministic_synthesis,
870                 device=self.device,
871             )
872
873             nb_total = ((prior_visits > 0) * ar_mask).sum()
874
875             nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
876
877             return nb_total, nb_correct
878
879         test_nb_total, test_nb_correct = compute_nb_correct(
880             self.test_input[:1000], self.test_prior_visits[:1000]
881         )
882
883         logger(
884             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}%"
885         )
886
887
888 ######################################################################
889
890
891 import stack
892
893
894 class Stack(Task):
895     def __init__(
896         self,
897         nb_train_samples,
898         nb_test_samples,
899         batch_size,
900         logger,
901         nb_steps,
902         nb_stacks,
903         nb_digits,
904         fraction_values_for_train=None,
905         device=torch.device("cpu"),
906     ):
907         super().__init__()
908
909         self.batch_size = batch_size
910         self.nb_steps = nb_steps
911         self.nb_stacks = nb_stacks
912         self.nb_digits = nb_digits
913         self.device = device
914
915         if fraction_values_for_train is None:
916             values_for_train = None
917             values_for_test = None
918         else:
919             all = torch.randperm(10**nb_digits)
920             nb_for_train = int(all.size(0) * fraction_values_for_train)
921             values_for_train = all[:nb_for_train]
922             values_for_test = all[nb_for_train:]
923
924         self.train_input, self.train_stack_counts = stack.generate_sequences(
925             nb_train_samples,
926             nb_steps,
927             nb_stacks,
928             nb_digits,
929             values_for_train,
930             self.device,
931         )
932
933         self.test_input, self.test_stack_counts = stack.generate_sequences(
934             nb_test_samples,
935             nb_steps,
936             nb_stacks,
937             nb_digits,
938             values_for_test,
939             self.device,
940         )
941
942         i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
943         counts = self.test_stack_counts.flatten()[i.flatten()]
944         counts = F.one_hot(counts).sum(0)
945         logger(f"test_pop_stack_counts {counts}")
946
947         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
948
949     def batches(self, split="train", nb_to_use=-1, desc=None):
950         assert split in {"train", "test"}
951         input = self.train_input if split == "train" else self.test_input
952         if nb_to_use > 0:
953             input = input[:nb_to_use]
954         if desc is None:
955             desc = f"epoch-{split}"
956         for batch in tqdm.tqdm(
957             input.split(self.batch_size), dynamic_ncols=True, desc=desc
958         ):
959             yield batch
960
961     def vocabulary_size(self):
962         return self.nb_codes
963
964     def produce_results(
965         self, n_epoch, model, result_dir, logger, deterministic_synthesis
966     ):
967         def compute_nb_correct(input):
968             result = input.clone()
969             stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
970             ar_mask = (result != input).long()
971             masked_inplace_autoregression(
972                 model,
973                 self.batch_size,
974                 result,
975                 ar_mask,
976                 deterministic_synthesis,
977                 device=self.device,
978             )
979
980             errors = ((result != input).long() * ar_mask).reshape(
981                 -1, 1 + self.nb_digits
982             )
983             ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
984
985             nb_total = ar_mask.max(1).values.sum()
986             nb_correct = nb_total - errors.max(1).values.sum()
987
988             return nb_total, nb_correct
989
990         test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
991
992         logger(
993             f"accuracy_test {n_epoch} nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
994         )
995
996         ##############################################################
997         # Log a few generated sequences
998         input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
999         result = input.clone()
1000         stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
1001         ar_mask = (result != input).long()
1002
1003         # for n in range(result.size(0)):
1004         # logger(
1005         # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1006         # )
1007
1008         masked_inplace_autoregression(
1009             model,
1010             self.batch_size,
1011             result,
1012             ar_mask,
1013             deterministic_synthesis,
1014             device=self.device,
1015         )
1016
1017         for n in range(result.size(0)):
1018             logger(
1019                 f"test_after  {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
1020             )
1021         ##############################################################
1022
1023
1024 ######################################################################
1025
1026 import rpl
1027
1028
1029 class RPL(Task):
1030     def tensorize(self, sequences):
1031         len_max = max([len(x) for x in sequences])
1032         return torch.cat(
1033             [
1034                 torch.tensor(
1035                     [
1036                         [
1037                             self.token2id[str(c)]
1038                             for c in s + ["<nul>"] * (len_max - len(s))
1039                         ]
1040                         for s in sequences
1041                     ]
1042                 )
1043             ],
1044             0,
1045         ).to(self.device)
1046
1047     def seq2str(self, seq):
1048         return " ".join([self.id2token[i] for i in seq])
1049
1050     def __init__(
1051         self,
1052         nb_train_samples,
1053         nb_test_samples,
1054         batch_size,
1055         nb_starting_values=3,
1056         max_input=9,
1057         prog_len=6,
1058         nb_runs=5,
1059         device=torch.device("cpu"),
1060     ):
1061         super().__init__()
1062
1063         self.batch_size = batch_size
1064         self.device = device
1065
1066         train_sequences = [
1067             rpl.generate(
1068                 nb_starting_values=nb_starting_values,
1069                 max_input=max_input,
1070                 prog_len=prog_len,
1071                 nb_runs=nb_runs,
1072             )
1073             for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
1074         ]
1075
1076         test_sequences = [
1077             rpl.generate(
1078                 nb_starting_values=nb_starting_values,
1079                 max_input=max_input,
1080                 prog_len=prog_len,
1081                 nb_runs=nb_runs,
1082             )
1083             for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
1084         ]
1085
1086         symbols = list(
1087             set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
1088         )
1089         val_max = max([x if type(x) is int else 0 for x in symbols])
1090         symbols = list(filter(lambda x: type(x) is str, symbols))
1091         symbols.sort()
1092         symbols += [str(n) for n in range(val_max + 1)]
1093         print(f"{val_max=}")
1094         self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
1095         self.id2token = dict([(n, c) for c, n in self.token2id.items()])
1096
1097         self.t_nul, self.t_prog = self.token2id["<nul>"], self.token2id["<prog>"]
1098
1099         self.train_input = self.tensorize(train_sequences)
1100         self.test_input = self.tensorize(test_sequences)
1101
1102         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1103
1104     def batches(self, split="train", nb_to_use=-1, desc=None):
1105         assert split in {"train", "test"}
1106         input = self.train_input if split == "train" else self.test_input
1107         if nb_to_use > 0:
1108             input = input[:nb_to_use]
1109         if desc is None:
1110             desc = f"epoch-{split}"
1111         for batch in tqdm.tqdm(
1112             input.split(self.batch_size), dynamic_ncols=True, desc=desc
1113         ):
1114             last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1115             batch = batch[:, :last]
1116             yield batch
1117
1118     def vocabulary_size(self):
1119         return self.nb_codes
1120
1121     def produce_results(
1122         self, n_epoch, model, result_dir, logger, deterministic_synthesis
1123     ):
1124         def compute_nb_errors(input, nb_to_log=0):
1125             result = input.clone()
1126             s = (result == self.t_prog).long()
1127             ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1128             result = (1 - ar_mask) * result + ar_mask * self.t_nul
1129
1130             masked_inplace_autoregression(
1131                 model,
1132                 self.batch_size,
1133                 result,
1134                 ar_mask,
1135                 deterministic_synthesis,
1136                 device=self.device,
1137             )
1138
1139             sum_nb_total, sum_nb_errors = 0, 0
1140             for x, y in zip(input, result):
1141                 seq = [self.id2token[i.item()] for i in y]
1142                 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1143                 sum_nb_total += 1
1144                 sum_nb_errors += 0 if nb_errors == 0 else 1
1145                 if nb_to_log > 0:
1146                     gt_seq = [self.id2token[i.item()] for i in x]
1147                     _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1148                     gt_prog = " ".join([str(x) for x in gt_prog])
1149                     prog = " ".join([str(x) for x in prog])
1150                     logger(f"PROG [{gt_prog}] PREDICTED [{prog}]")
1151                     for start_stack, target_stack, result_stack, correct in stacks:
1152                         comment = " CORRECT" if correct else ""
1153                         start_stack = " ".join([str(x) for x in start_stack])
1154                         target_stack = " ".join([str(x) for x in target_stack])
1155                         result_stack = " ".join([str(x) for x in result_stack])
1156                         logger(
1157                             f"  [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]{comment}"
1158                         )
1159                     nb_to_log -= 1
1160
1161             return sum_nb_total, sum_nb_errors
1162
1163         test_nb_total, test_nb_errors = compute_nb_errors(
1164             self.test_input[:1000], nb_to_log=10
1165         )
1166
1167         logger(
1168             f"accuracy_test {n_epoch} nb_total {test_nb_total} nb_errors {test_nb_errors} accuracy {100.0*(1-test_nb_errors/test_nb_total):.02f}%"
1169         )
1170
1171
1172 ######################################################################
1173
1174
1175 import expr
1176
1177
1178 class Expr(Task):
1179     def tensorize(self, sequences):
1180         len_max = max([len(x) for x in sequences])
1181         return torch.cat(
1182             [
1183                 torch.tensor(
1184                     [
1185                         [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1186                         for s in sequences
1187                     ]
1188                 )
1189             ],
1190             0,
1191         ).to(self.device)
1192
1193     def __init__(
1194         self,
1195         nb_train_samples,
1196         nb_test_samples,
1197         nb_variables,
1198         sequence_length,
1199         operand_max,
1200         result_max,
1201         batch_size,
1202         device=torch.device("cpu"),
1203     ):
1204         super().__init__()
1205
1206         self.batch_size = batch_size
1207         self.device = device
1208
1209         train_sequences = expr.generate_sequences(
1210             nb_train_samples,
1211             nb_variables=nb_variables,
1212             length=sequence_length,
1213             operand_max=operand_max,
1214             result_max=result_max,
1215         )
1216
1217         test_sequences = expr.generate_sequences(
1218             nb_test_samples,
1219             nb_variables=nb_variables,
1220             length=sequence_length,
1221             operand_max=operand_max,
1222             result_max=result_max,
1223         )
1224
1225         symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1226         symbols.sort()
1227
1228         self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1229         self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1230
1231         self.filler, self.space = self.char2id["#"], self.char2id[" "]
1232
1233         self.train_input = self.tensorize(train_sequences)
1234         self.test_input = self.tensorize(test_sequences)
1235
1236         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1237
1238     def batches(self, split="train", nb_to_use=-1, desc=None):
1239         assert split in {"train", "test"}
1240         input = self.train_input if split == "train" else self.test_input
1241         if nb_to_use > 0:
1242             input = input[:nb_to_use]
1243         if desc is None:
1244             desc = f"epoch-{split}"
1245         for batch in tqdm.tqdm(
1246             input.split(self.batch_size), dynamic_ncols=True, desc=desc
1247         ):
1248             last = (batch != self.filler).max(0).values.nonzero().max() + 3
1249             batch = batch[:, :last]
1250             yield batch
1251
1252     def vocabulary_size(self):
1253         return self.nb_codes
1254
1255     def seq2str(self, s):
1256         return "".join([self.id2char[k.item()] for k in s])
1257
1258     def produce_results(
1259         self,
1260         n_epoch,
1261         model,
1262         result_dir,
1263         logger,
1264         deterministic_synthesis,
1265         input_file=None,
1266     ):
1267         def compute_nb_correct(input):
1268             result = input.clone()
1269             s = (result == self.space).long()
1270             ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1271             result = (1 - ar_mask) * result + ar_mask * self.filler
1272             masked_inplace_autoregression(
1273                 model,
1274                 self.batch_size,
1275                 result,
1276                 ar_mask,
1277                 deterministic_synthesis,
1278                 device=self.device,
1279             )
1280
1281             nb_total = input.size(0)
1282             nb_correct = (input == result).long().min(1).values.sum()
1283
1284             #######################################################################
1285             # Comput predicted vs. true variable values
1286
1287             nb_delta = torch.zeros(5, dtype=torch.int64)
1288             nb_missed = 0
1289
1290             values_input = expr.extract_results([self.seq2str(s) for s in input])
1291             values_result = expr.extract_results([self.seq2str(s) for s in result])
1292
1293             filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1294
1295             with open(filename, "w") as f:
1296                 for i, r in zip(values_input, values_result):
1297                     for n, vi in i.items():
1298                         vr = r.get(n)
1299                         f.write(f"{vi} {-1 if vr is None else vr}\n")
1300
1301                         if vr is None or vr < 0:
1302                             nb_missed += 1
1303                         else:
1304                             d = abs(vr - vi)
1305                             if d >= nb_delta.size(0):
1306                                 nb_missed += 1
1307                             else:
1308                                 nb_delta[d] += 1
1309
1310             ######################################################################
1311
1312             return nb_total, nb_correct, nb_delta, nb_missed
1313
1314         (
1315             test_nb_total,
1316             test_nb_correct,
1317             test_nb_delta,
1318             test_nb_missed,
1319         ) = compute_nb_correct(self.test_input[:10000])
1320
1321         logger(
1322             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}%"
1323         )
1324
1325         nb_total = test_nb_delta.sum() + test_nb_missed
1326         for d in range(test_nb_delta.size(0)):
1327             logger(
1328                 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1329             )
1330         logger(
1331             f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1332         )
1333
1334         ##############################################################
1335         # Log a few generated sequences
1336         if input_file is None:
1337             input = self.test_input[:10]
1338         else:
1339             with open(input_file, "r") as f:
1340                 sequences = [e.strip() for e in f.readlines()]
1341                 sequences = [s + " " + "#" * 50 for s in sequences]
1342                 input = self.tensorize(sequences)
1343
1344         result = input.clone()
1345         s = (result == self.space).long()
1346         ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1347         result = (1 - ar_mask) * result + ar_mask * self.filler
1348
1349         for n in range(result.size(0)):
1350             logger(f"test_before {self.seq2str(result[n])}")
1351
1352         masked_inplace_autoregression(
1353             model,
1354             self.batch_size,
1355             result,
1356             ar_mask,
1357             deterministic_synthesis,
1358             device=self.device,
1359         )
1360
1361         correct = (1 - ar_mask) * self.space + ar_mask * input
1362         for n in range(result.size(0)):
1363             comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1364             logger(f"test_after  {self.seq2str(result[n])} {comment}")
1365             logger(f"truth       {self.seq2str(correct[n])}")
1366         ##############################################################
1367
1368
1369 ######################################################################
1370
1371 import world
1372
1373
1374 class World(Task):
1375     def __init__(
1376         self,
1377         nb_train_samples,
1378         nb_test_samples,
1379         batch_size,
1380         vqae_nb_epochs,
1381         logger=None,
1382         device=torch.device("cpu"),
1383         device_storage=torch.device("cpu"),
1384     ):
1385         super().__init__()
1386
1387         self.batch_size = batch_size
1388         self.device = device
1389
1390         (
1391             train_frames,
1392             train_action_seq,
1393             test_frames,
1394             test_action_seq,
1395             self.frame2seq,
1396             self.seq2frame,
1397         ) = world.create_data_and_processors(
1398             nb_train_samples,
1399             nb_test_samples,
1400             mode="first_last",
1401             nb_steps=30,
1402             nb_epochs=vqae_nb_epochs,
1403             logger=logger,
1404             device=device,
1405             device_storage=device_storage,
1406         )
1407
1408         train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1409         test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1410
1411         nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1412         nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1413
1414         self.len_frame_seq = train_frame_seq.size(1)
1415         self.len_action_seq = train_action_seq.size(1)
1416         self.nb_codes = nb_frame_codes + nb_action_codes
1417
1418         train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1419
1420         train_action_seq += nb_frame_codes
1421         self.train_input = torch.cat(
1422             (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1423         )
1424
1425         test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1426         test_action_seq += nb_frame_codes
1427         self.test_input = torch.cat(
1428             (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1429         )
1430
1431     def batches(self, split="train", nb_to_use=-1, desc=None):
1432         assert split in {"train", "test"}
1433         input = self.train_input if split == "train" else self.test_input
1434         if nb_to_use > 0:
1435             input = input[:nb_to_use]
1436         if desc is None:
1437             desc = f"epoch-{split}"
1438         for batch in tqdm.tqdm(
1439             input.split(self.batch_size), dynamic_ncols=True, desc=desc
1440         ):
1441             yield batch.to(self.device)
1442
1443     def vocabulary_size(self):
1444         return self.nb_codes
1445
1446     def produce_results(
1447         self, n_epoch, model, result_dir, logger, deterministic_synthesis
1448     ):
1449         k = torch.arange(
1450             2 * self.len_frame_seq + self.len_action_seq, device=self.device
1451         )[None, :]
1452
1453         input = self.test_input[:64].to(self.device)
1454         result = input.clone()
1455
1456         ar_mask = (
1457             (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1458         )
1459         result *= 1 - ar_mask
1460
1461         masked_inplace_autoregression(
1462             model,
1463             self.batch_size,
1464             result,
1465             ar_mask,
1466             deterministic_synthesis,
1467             device=self.device,
1468         )
1469
1470         seq_start = input[:, : self.len_frame_seq]
1471         seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1472         seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1473
1474         result = torch.cat(
1475             (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1476         )
1477         result = result.reshape(-1, result.size(-1))
1478
1479         frames = self.seq2frame(result)
1480         image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1481         torchvision.utils.save_image(
1482             frames.float() / (world.Box.nb_rgb_levels - 1),
1483             image_name,
1484             nrow=12,
1485             padding=1,
1486             pad_value=0.0,
1487         )
1488         logger(f"wrote {image_name}")
1489
1490
1491 ######################################################################