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