Update.
[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
80 class SandBox(Task):
81     def __init__(
82         self,
83         problem,
84         nb_train_samples,
85         nb_test_samples,
86         batch_size,
87         logger=None,
88         device=torch.device("cpu"),
89         max_nb_codes=1024,
90     ):
91         super().__init__()
92
93         self.batch_size = batch_size
94         self.device = device
95         self.problem = problem
96
97         self.train_input, self.train_ar_mask = self.problem.generate_sequences(
98             nb_train_samples
99         )
100         self.test_input, self.test_ar_mask = self.problem.generate_sequences(
101             nb_test_samples
102         )
103
104         self.train_input, self.train_ar_mask = self.train_input.to(
105             device
106         ), self.train_ar_mask.to(device)
107         self.test_input, self.test_ar_mask = self.test_input.to(
108             device
109         ), self.test_ar_mask.to(device)
110
111         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
112
113         # A bit of paranoia never hurts
114         assert (
115             self.nb_codes <= max_nb_codes
116             and self.train_input.min() >= 0
117             and self.test_input.min() >= 0
118             and tuple(self.train_ar_mask.unique()) == (0, 1)
119             and tuple(self.test_ar_mask.unique()) == (0, 1)
120         )
121
122     def batches(self, split="train", nb_to_use=-1, desc=None):
123         assert split in {"train", "test"}
124         input = self.train_input if split == "train" else self.test_input
125         if nb_to_use > 0:
126             input = input[:nb_to_use]
127         if desc is None:
128             desc = f"epoch-{split}"
129         for batch in tqdm.tqdm(
130             input.split(self.batch_size), dynamic_ncols=True, desc=desc
131         ):
132             yield batch
133
134     def vocabulary_size(self):
135         return self.nb_codes
136
137     def produce_results(
138         self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
139     ):
140         def compute_accuracy(input, ar_mask, logger=None):
141             input, ar_mask = input[:nmax], ar_mask[:nmax]
142             result = input.clone() * (1 - ar_mask)
143
144             masked_inplace_autoregression(
145                 model,
146                 self.batch_size,
147                 result,
148                 ar_mask,
149                 deterministic_synthesis,
150                 progress_bar_desc=None,
151                 device=self.device,
152             )
153
154             if logger is not None:
155                 for sp, st in zip(result[:10], input[:10]):
156                     logger(
157                         f"test_sequences {n_epoch} prediction   {self.problem.seq2str(sp)}"
158                     )
159                     logger(
160                         f"               {n_epoch} ground truth {self.problem.seq2str(st)}"
161                     )
162
163             nb_total = ar_mask.sum().item()
164             nb_correct = ((result == input).long() * ar_mask).sum().item()
165
166             return nb_total, nb_correct
167
168         train_nb_total, train_nb_correct = compute_accuracy(
169             self.train_input, self.train_ar_mask
170         )
171
172         logger(
173             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}%"
174         )
175
176         test_nb_total, test_nb_correct = compute_accuracy(
177             self.test_input, self.test_ar_mask, logger
178         )
179
180         logger(
181             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}%"
182         )
183
184
185 ######################################################################
186
187 import picoclvr
188
189
190 class PicoCLVR(Task):
191     # Make a tensor from a list of strings
192     def tensorize(self, descr):
193         token_descr = [s.strip().split(" ") for s in descr]
194         l = max([len(s) for s in token_descr])
195         token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
196         id_descr = [[self.token2id[u] for u in s] for s in token_descr]
197         return torch.tensor(id_descr, device=self.device)
198
199     # Make a list of strings from a tensor
200     def detensorize(self, x):
201         return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
202
203     # trim all the tensors in the tuple z to remove as much token from
204     # left and right in the first tensor. If z is a tuple, all its
205     # elements are trimed according to the triming for the first
206     def trim(self, z, token="<nul>"):
207         n = self.token2id[token]
208         if type(z) == tuple:
209             x = z[0]
210             i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
211             a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
212             return tuple([t[:, a:b] for t in z])
213         else:
214             i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
215             a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
216             return z[:, a:b]
217
218     ######################
219
220     def __init__(
221         self,
222         nb_train_samples,
223         nb_test_samples,
224         batch_size,
225         height,
226         width,
227         nb_colors=5,
228         logger=None,
229         device=torch.device("cpu"),
230         pruner_train=None,
231         pruner_eval=None,
232     ):
233         super().__init__()
234
235         def generate_descr(nb, cache_suffix, pruner):
236             return picoclvr.generate(
237                 nb,
238                 height=self.height,
239                 width=self.width,
240                 nb_colors=nb_colors,
241                 pruner=pruner,
242             )
243
244         self.height = height
245         self.width = width
246         self.batch_size = batch_size
247         self.device = device
248         self.pruner_train = pruner_train
249         self.pruner_eval = pruner_eval
250
251         if logger is not None:
252             logger(
253                 f"generating {nb_train_samples+nb_test_samples} samples (can take some time)"
254             )
255
256         self.train_descr = generate_descr(
257             nb_train_samples, "train", pruner=self.pruner_train
258         )
259         self.test_descr = generate_descr(nb_test_samples, "test", pruner=None)
260
261         # Build the tokenizer
262         tokens = {"<nul>", "<img>"}
263         for d in [self.train_descr, self.test_descr]:
264             for s in d:
265                 for t in s.strip().split(" "):
266                     tokens.add(t)
267         # make this set a sorted list to get the same tensors given
268         # the same descr
269         tokens = list(tokens)
270         tokens.sort()
271         self.token2id = dict([(t, n) for n, t in enumerate(tokens)])
272         self.id2token = dict([(n, t) for n, t in enumerate(tokens)])
273         self.t_img, self.t_nul = self.token2id["<img>"], self.token2id["<nul>"]
274
275         # Tokenize the train and test sets
276         self.train_input = self.tensorize(self.train_descr)
277         self.test_input = self.tensorize(self.test_descr)
278
279     def batches(self, split="train"):
280         assert split in {"train", "test"}
281         input = self.train_input if split == "train" else self.test_input
282         for batch in tqdm.tqdm(
283             input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
284         ):
285             yield self.trim(batch)
286
287     def vocabulary_size(self):
288         return len(self.token2id)
289
290     def compute_missing_properties(
291         self, n_epoch, model, logger, deterministic_synthesis, pruner=None
292     ):
293         acc_nb_requested_properties = []
294         acc_nb_missing_properties = []
295         acc_nb_results = 0
296
297         for input in tqdm.tqdm(
298             self.test_input.split(self.batch_size),
299             dynamic_ncols=True,
300             desc=f"test-properties",
301         ):
302             result = input.clone()
303             ar_mask = (result == self.t_img).long().cumsum(dim=1).clamp(max=1)
304             result = (1 - ar_mask) * result + ar_mask * self.t_nul
305             masked_inplace_autoregression(
306                 model,
307                 self.batch_size,
308                 result,
309                 ar_mask,
310                 deterministic_synthesis,
311                 progress_bar_desc=None,
312                 device=self.device,
313             )
314
315             result_descr = self.detensorize(result)
316             np = picoclvr.nb_properties(
317                 result_descr,
318                 height=self.height,
319                 width=self.width,
320                 pruner=pruner,
321             )
322             nb_requested_properties, _, nb_missing_properties = zip(*np)
323             acc_nb_requested_properties += nb_requested_properties
324             acc_nb_missing_properties += nb_missing_properties
325             acc_nb_results += len(result_descr)
326
327         nb_requested_properties = sum(acc_nb_requested_properties)
328         nb_missing_properties = sum(acc_nb_missing_properties)
329
330         prefix = "" if pruner is None else "pruned_"
331         logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
332         logger(
333             f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
334         )
335         logger(
336             f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
337         )
338
339     ######################################################################
340
341     def produce_results(
342         self, n_epoch, model, result_dir, logger, deterministic_synthesis
343     ):
344         self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
345
346         if self.pruner_eval is not None:
347             self.compute_missing_properties(n_epoch, model, self.pruner_eval)
348
349         nb_tokens_to_generate = self.height * self.width + 3
350         result_descr = []
351         nb_per_primer = 8
352         primer = []
353
354         for primer_descr in [
355             "red above green <sep> green top <sep> blue right of red",
356             "there is red <sep> there is yellow <sep> there is blue",
357             "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
358             "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
359         ]:
360             primer += [primer_descr + " <img>"] * nb_per_primer
361
362         result = self.tensorize(primer)
363         fill = result.new_full(
364             result.size()[:-1] + (self.height * self.width + 1,), self.t_nul
365         )
366         result = torch.cat((result, fill), 1)
367         ar_mask = (result == self.t_nul).long()
368         masked_inplace_autoregression(
369             model,
370             self.batch_size,
371             result,
372             ar_mask,
373             deterministic_synthesis,
374             device=self.device,
375         )
376         result_descr = self.detensorize(result)
377
378         np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
379
380         acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
381         acc_nb_results = len(result_descr)
382
383         nb_requested_properties = sum(acc_nb_requested_properties)
384         nb_missing_properties = sum(acc_nb_missing_properties)
385
386         prefix = "demo_"
387         logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
388         logger(
389             f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
390         )
391         logger(
392             f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
393         )
394
395         img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
396
397         if img.dim() == 5:
398             if img.size(1) == 1:
399                 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
400             else:
401                 img = torch.cat(
402                     [
403                         torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
404                         for x in img
405                     ],
406                     0,
407                 )
408
409         image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
410         torchvision.utils.save_image(
411             img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
412         )
413         logger(f"wrote {image_name}")
414
415
416 ######################################################################
417
418
419 class MNIST(Task):
420     def __init__(
421         self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
422     ):
423         super().__init__()
424
425         self.nb_train_samples = (nb_train_samples,)
426         self.nb_test_samples = (nb_test_samples,)
427         self.batch_size = batch_size
428         self.device = device
429         data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
430         self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
431         data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
432         self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
433
434     def batches(self, split="train", nb_to_use=-1, desc=None):
435         assert split in {"train", "test"}
436         input = self.train_input if split == "train" else self.test_input
437         if nb_to_use > 0:
438             input = input[:nb_to_use]
439         if desc is None:
440             desc = f"epoch-{split}"
441         for batch in tqdm.tqdm(
442             input.split(self.batch_size), dynamic_ncols=True, desc=desc
443         ):
444             yield batch
445
446     def vocabulary_size(self):
447         return 256
448
449     def produce_results(
450         self, n_epoch, model, result_dir, logger, deterministic_synthesis
451     ):
452         results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
453         ar_mask = torch.full_like(results, 1)
454         masked_inplace_autoregression(
455             model,
456             self.batch_size,
457             results,
458             ar_mask,
459             deterministic_synthesis,
460             device=self.device,
461         )
462         image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
463         torchvision.utils.save_image(
464             1 - results.reshape(-1, 1, 28, 28) / 255.0,
465             image_name,
466             nrow=16,
467             pad_value=0.8,
468         )
469         logger(f"wrote {image_name}")
470
471
472 ######################################################################
473
474 import maze
475
476
477 class Maze(Task):
478     def map2seq(self, *m):
479         return torch.cat([x.flatten(1) for x in m], 1)
480
481     def seq2map(self, s):
482         s = s.reshape(s.size(0), -1, self.height, self.width)
483         return (s[:, k] for k in range(s.size(1)))
484
485     def __init__(
486         self,
487         nb_train_samples,
488         nb_test_samples,
489         batch_size,
490         height,
491         width,
492         nb_walls,
493         device=torch.device("cpu"),
494     ):
495         super().__init__()
496
497         self.batch_size = batch_size
498         self.height = height
499         self.width = width
500         self.device = device
501
502         train_mazes, train_paths, _ = maze.create_maze_data(
503             nb_train_samples,
504             height=height,
505             width=width,
506             nb_walls=nb_walls,
507             progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
508         )
509         self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
510
511         test_mazes, test_paths, _ = maze.create_maze_data(
512             nb_test_samples,
513             height=height,
514             width=width,
515             nb_walls=nb_walls,
516             progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
517         )
518         self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
519
520         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
521
522     def batches(self, split="train", nb_to_use=-1, desc=None):
523         assert split in {"train", "test"}
524         input = self.train_input if split == "train" else self.test_input
525         if nb_to_use > 0:
526             input = input[:nb_to_use]
527         if desc is None:
528             desc = f"epoch-{split}"
529         for batch in tqdm.tqdm(
530             input.split(self.batch_size), dynamic_ncols=True, desc=desc
531         ):
532             yield batch
533
534     def vocabulary_size(self):
535         return self.nb_codes
536
537     def compute_error(
538         self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
539     ):
540         nb_total, nb_correct = 0, 0
541         count = torch.zeros(
542             self.width * self.height,
543             self.width * self.height,
544             device=self.device,
545             dtype=torch.int64,
546         )
547
548         for input in self.batches(split, nb_to_use):
549             result = input.clone()
550             ar_mask = result.new_zeros(result.size())
551             ar_mask[:, self.height * self.width :] = 1
552             result *= 1 - ar_mask
553             masked_inplace_autoregression(
554                 model,
555                 self.batch_size,
556                 result,
557                 ar_mask,
558                 deterministic_synthesis,
559                 progress_bar_desc=None,
560                 device=self.device,
561             )
562             mazes, paths = self.seq2map(result)
563             path_correctness = maze.path_correctness(mazes, paths)
564             nb_correct += path_correctness.long().sum()
565             nb_total += mazes.size(0)
566
567             optimal_path_lengths = (
568                 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
569             )
570             predicted_path_lengths = (
571                 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
572             )
573             optimal_path_lengths = optimal_path_lengths[path_correctness]
574             predicted_path_lengths = predicted_path_lengths[path_correctness]
575             count[optimal_path_lengths, predicted_path_lengths] += 1
576
577         if count.max() == 0:
578             count = None
579         else:
580             count = count[
581                 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
582             ]
583
584         return nb_total, nb_correct, count
585
586     def produce_results(
587         self, n_epoch, model, result_dir, logger, deterministic_synthesis
588     ):
589         train_nb_total, train_nb_correct, count = self.compute_error(
590             model,
591             "train",
592             nb_to_use=1000,
593             deterministic_synthesis=deterministic_synthesis,
594         )
595         logger(
596             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}%"
597         )
598
599         test_nb_total, test_nb_correct, count = self.compute_error(
600             model,
601             "test",
602             nb_to_use=1000,
603             deterministic_synthesis=deterministic_synthesis,
604         )
605         logger(
606             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}%"
607         )
608
609         if count is not None:
610             proportion_optimal = count.diagonal().sum().float() / count.sum()
611             logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
612             with open(
613                 os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
614             ) as f:
615                 for i in range(count.size(0)):
616                     for j in range(count.size(1)):
617                         eol = " " if j < count.size(1) - 1 else "\n"
618                         f.write(f"{count[i,j]}{eol}")
619
620         input = self.test_input[:48]
621         result = input.clone()
622         ar_mask = result.new_zeros(result.size())
623         ar_mask[:, self.height * self.width :] = 1
624         result *= 1 - ar_mask
625         masked_inplace_autoregression(
626             model,
627             self.batch_size,
628             result,
629             ar_mask,
630             deterministic_synthesis,
631             device=self.device,
632         )
633
634         mazes, paths = self.seq2map(input)
635         _, predicted_paths = self.seq2map(result)
636
637         filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
638         maze.save_image(
639             filename,
640             mazes=mazes,
641             target_paths=paths,
642             predicted_paths=predicted_paths,
643             path_correct=maze.path_correctness(mazes, predicted_paths),
644             path_optimal=maze.path_optimality(paths, predicted_paths),
645         )
646         logger(f"wrote {filename}")
647
648
649 ######################################################################
650
651
652 import snake
653
654
655 class Snake(Task):
656     def __init__(
657         self,
658         nb_train_samples,
659         nb_test_samples,
660         batch_size,
661         height,
662         width,
663         nb_colors,
664         length,
665         prompt_length,
666         device=torch.device("cpu"),
667     ):
668         super().__init__()
669
670         self.batch_size = batch_size
671         self.height = height
672         self.width = width
673         self.device = device
674         self.prompt_length = prompt_length
675
676         self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
677             nb_train_samples,
678             height,
679             width,
680             nb_colors,
681             length,
682             prompt_length,
683             self.device,
684         )
685         self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
686             nb_test_samples,
687             height,
688             width,
689             nb_colors,
690             length,
691             prompt_length,
692             self.device,
693         )
694
695         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
696
697     def batches(self, split="train", nb_to_use=-1, desc=None):
698         assert split in {"train", "test"}
699         input = self.train_input if split == "train" else self.test_input
700         if nb_to_use > 0:
701             input = input[:nb_to_use]
702         if desc is None:
703             desc = f"epoch-{split}"
704         for batch in tqdm.tqdm(
705             input.split(self.batch_size), dynamic_ncols=True, desc=desc
706         ):
707             yield batch
708
709     def vocabulary_size(self):
710         return self.nb_codes
711
712     def produce_results(
713         self, n_epoch, model, result_dir, logger, deterministic_synthesis
714     ):
715         def compute_nb_correct(input, prior_visits):
716             result = input.clone()
717             i = torch.arange(result.size(1), device=result.device)[None, :]
718             ar_mask = (
719                 torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
720                 .long()
721                 .expand_as(result)
722             )
723             result *= 1 - ar_mask
724
725             masked_inplace_autoregression(
726                 model,
727                 self.batch_size,
728                 result,
729                 ar_mask,
730                 deterministic_synthesis,
731                 device=self.device,
732             )
733
734             nb_total = ((prior_visits > 0) * ar_mask).sum()
735
736             nb_correct = ((result == input).long() * (prior_visits > 0) * ar_mask).sum()
737
738             return nb_total, nb_correct
739
740         test_nb_total, test_nb_correct = compute_nb_correct(
741             self.test_input[:1000], self.test_prior_visits[:1000]
742         )
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
749 ######################################################################
750
751
752 import stack
753
754
755 class Stack(Task):
756     def __init__(
757         self,
758         nb_train_samples,
759         nb_test_samples,
760         batch_size,
761         logger,
762         nb_steps,
763         nb_stacks,
764         nb_digits,
765         fraction_values_for_train=None,
766         device=torch.device("cpu"),
767     ):
768         super().__init__()
769
770         self.batch_size = batch_size
771         self.nb_steps = nb_steps
772         self.nb_stacks = nb_stacks
773         self.nb_digits = nb_digits
774         self.device = device
775
776         if fraction_values_for_train is None:
777             values_for_train = None
778             values_for_test = None
779         else:
780             all = torch.randperm(10**nb_digits)
781             nb_for_train = int(all.size(0) * fraction_values_for_train)
782             values_for_train = all[:nb_for_train]
783             values_for_test = all[nb_for_train:]
784
785         self.train_input, self.train_stack_counts = stack.generate_sequences(
786             nb_train_samples,
787             nb_steps,
788             nb_stacks,
789             nb_digits,
790             values_for_train,
791             self.device,
792         )
793
794         self.test_input, self.test_stack_counts = stack.generate_sequences(
795             nb_test_samples,
796             nb_steps,
797             nb_stacks,
798             nb_digits,
799             values_for_test,
800             self.device,
801         )
802
803         i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks)
804         counts = self.test_stack_counts.flatten()[i.flatten()]
805         counts = F.one_hot(counts).sum(0)
806         logger(f"test_pop_stack_counts {counts}")
807
808         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
809
810     def batches(self, split="train", nb_to_use=-1, desc=None):
811         assert split in {"train", "test"}
812         input = self.train_input if split == "train" else self.test_input
813         if nb_to_use > 0:
814             input = input[:nb_to_use]
815         if desc is None:
816             desc = f"epoch-{split}"
817         for batch in tqdm.tqdm(
818             input.split(self.batch_size), dynamic_ncols=True, desc=desc
819         ):
820             yield batch
821
822     def vocabulary_size(self):
823         return self.nb_codes
824
825     def produce_results(
826         self, n_epoch, model, result_dir, logger, deterministic_synthesis
827     ):
828         def compute_nb_correct(input):
829             result = input.clone()
830             stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
831             ar_mask = (result != input).long()
832             masked_inplace_autoregression(
833                 model,
834                 self.batch_size,
835                 result,
836                 ar_mask,
837                 deterministic_synthesis,
838                 device=self.device,
839             )
840
841             errors = ((result != input).long() * ar_mask).reshape(
842                 -1, 1 + self.nb_digits
843             )
844             ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
845
846             nb_total = ar_mask.max(1).values.sum()
847             nb_correct = nb_total - errors.max(1).values.sum()
848
849             return nb_total, nb_correct
850
851         test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
852
853         logger(
854             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}%"
855         )
856
857         ##############################################################
858         # Log a few generated sequences
859         input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
860         result = input.clone()
861         stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
862         ar_mask = (result != input).long()
863
864         # for n in range(result.size(0)):
865         # logger(
866         # f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
867         # )
868
869         masked_inplace_autoregression(
870             model,
871             self.batch_size,
872             result,
873             ar_mask,
874             deterministic_synthesis,
875             device=self.device,
876         )
877
878         for n in range(result.size(0)):
879             logger(
880                 f"test_after  {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
881             )
882         ##############################################################
883
884
885 ######################################################################
886
887 import rpl
888
889
890 class RPL(Task):
891     def tensorize(self, sequences):
892         len_max = max([len(x) for x in sequences])
893         return torch.cat(
894             [
895                 torch.tensor(
896                     [
897                         [
898                             self.token2id[str(c)]
899                             for c in s + ["<nul>"] * (len_max - len(s))
900                         ]
901                         for s in sequences
902                     ]
903                 )
904             ],
905             0,
906         )
907
908     def seq2str(self, seq):
909         return " ".join([self.id2token[i] for i in seq])
910
911     def __init__(
912         self,
913         nb_train_samples,
914         nb_test_samples,
915         batch_size,
916         nb_starting_values=3,
917         max_input=9,
918         prog_len=6,
919         nb_runs=5,
920         no_prog=False,
921         logger=None,
922         device=torch.device("cpu"),
923     ):
924         super().__init__()
925
926         self.batch_size = batch_size
927         self.device = device
928         self.no_prog = no_prog
929
930         train_sequences = [
931             rpl.generate(
932                 nb_starting_values=nb_starting_values,
933                 nb_result_values_max=4 * nb_starting_values,
934                 max_input=max_input,
935                 prog_len=prog_len,
936                 nb_runs=nb_runs,
937             )
938             for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
939         ]
940
941         test_sequences = [
942             rpl.generate(
943                 nb_starting_values=nb_starting_values,
944                 nb_result_values_max=4 * nb_starting_values,
945                 max_input=max_input,
946                 prog_len=prog_len,
947                 nb_runs=nb_runs,
948             )
949             for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
950         ]
951
952         symbols = list(
953             set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
954         )
955         val_max = max([x if type(x) is int else 0 for x in symbols])
956         symbols = list(filter(lambda x: type(x) is str, symbols))
957         symbols.sort()
958         symbols += [str(n) for n in range(val_max + 1)]
959         self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
960         self.id2token = dict([(n, c) for c, n in self.token2id.items()])
961
962         self.t_nul = self.token2id["<nul>"]
963         self.t_input = self.token2id["<in>"]
964         self.t_output = self.token2id["<out>"]
965         self.t_prog = self.token2id["<prg>"]
966         self.t_end = self.token2id["<end>"]
967
968         self.train_input = self.tensorize(train_sequences)
969         self.test_input = self.tensorize(test_sequences)
970
971         if no_prog:
972             # Excise the program from every train and test example
973             k = torch.arange(self.train_input.size(1), device=self.train_input.device)[
974                 None, :
975             ]
976             p = (
977                 ((self.train_input == self.t_prog).long() * k)
978                 .max(1, keepdim=True)
979                 .values
980             )
981             self.train_input = (
982                 self.train_input * (k <= p).long()
983                 + self.t_end * (k == p + 1).long()
984                 + self.t_nul * (k > p + 1).long()
985             )
986             k = torch.arange(self.test_input.size(1), device=self.test_input.device)[
987                 None, :
988             ]
989             p = (
990                 ((self.test_input == self.t_prog).long() * k)
991                 .max(1, keepdim=True)
992                 .values
993             )
994             self.test_input = (
995                 self.test_input * (k <= p).long()
996                 + self.t_end * (k == p + 1).long()
997                 + self.t_nul * (k > p + 1).long()
998             )
999
1000         if logger is not None:
1001             logger(f"value_max {val_max}")
1002             for x in self.train_input[:25]:
1003                 end = (x != self.t_nul).nonzero().max().item() + 1
1004                 seq = [self.id2token[i.item()] for i in x[:end]]
1005                 s = " ".join(seq)
1006                 logger(f"example_seq {s}")
1007
1008         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1009
1010     def batches(self, split="train", nb_to_use=-1, desc=None):
1011         assert split in {"train", "test"}
1012         input = self.train_input if split == "train" else self.test_input
1013         if nb_to_use > 0:
1014             input = input[:nb_to_use]
1015         if desc is None:
1016             desc = f"epoch-{split}"
1017         for batch in tqdm.tqdm(
1018             input.split(self.batch_size), dynamic_ncols=True, desc=desc
1019         ):
1020             last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1021             batch = batch[:, :last].to(self.device)
1022             yield batch
1023
1024     def vocabulary_size(self):
1025         return self.nb_codes
1026
1027     def produce_results(
1028         self, n_epoch, model, result_dir, logger, deterministic_synthesis
1029     ):
1030         # --------------------------------------------------------------------
1031         def compute_nb_errors_prog(input, nb_to_log=0):
1032             result = input.clone()
1033             s = (result == self.t_prog).long()
1034             ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1035             result = (1 - ar_mask) * result + ar_mask * self.t_nul
1036
1037             masked_inplace_autoregression(
1038                 model,
1039                 self.batch_size,
1040                 result,
1041                 ar_mask,
1042                 deterministic_synthesis,
1043                 device=self.device,
1044             )
1045
1046             sum_nb_total, sum_nb_errors = 0, 0
1047             for one_input, one_result in zip(input, result):
1048                 seq = [self.id2token[i.item()] for i in one_result]
1049                 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1050                 sum_nb_total += 1
1051                 sum_nb_errors += 0 if nb_errors == 0 else 1
1052                 if nb_to_log > 0:
1053                     gt_seq = [self.id2token[i.item()] for i in one_input]
1054                     _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1055                     gt_prog = " ".join([str(x) for x in gt_prog])
1056                     prog = " ".join([str(x) for x in prog])
1057                     comment = "*" if nb_errors == 0 else "-"
1058                     logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1059                     for start_stack, target_stack, result_stack, correct in stacks:
1060                         comment = "*" if correct else "-"
1061                         start_stack = " ".join([str(x) for x in start_stack])
1062                         target_stack = " ".join([str(x) for x in target_stack])
1063                         result_stack = " ".join([str(x) for x in result_stack])
1064                         logger(
1065                             f"  {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1066                         )
1067                     nb_to_log -= 1
1068
1069             return sum_nb_total, sum_nb_errors
1070
1071         # --------------------------------------------------------------------
1072         def compute_nb_errors_output(input, nb_to_log=0):
1073             result = input.clone()
1074             k = torch.arange(result.size(1), device=result.device)[None, :]
1075             last_output_idx = (
1076                 ((result == self.t_output) * k).max(dim=1, keepdim=True).values
1077             )
1078             first_prog_idx = (
1079                 ((result == self.t_prog) * k).max(dim=1, keepdim=True).values
1080             )
1081             ar_mask = (k > last_output_idx).long() * (k < first_prog_idx).long()
1082             result = (1 - ar_mask) * result + ar_mask * self.t_nul
1083
1084             masked_inplace_autoregression(
1085                 model,
1086                 self.batch_size,
1087                 result,
1088                 ar_mask,
1089                 deterministic_synthesis,
1090                 device=self.device,
1091             )
1092
1093             sum_nb_total, sum_nb_errors = 0, 0
1094             for one_input, one_result, i, j in zip(
1095                 input, result, last_output_idx, first_prog_idx
1096             ):
1097                 seq = [self.id2token[i.item()] for i in one_result]
1098                 sum_nb_total += 1
1099                 correct = (one_input - one_result).abs().max() == 0
1100                 sum_nb_errors += 0 if correct else 1
1101                 if nb_to_log > 0:
1102                     result_stack = [
1103                         self.id2token[i.item()] for i in one_result[i : j + 1]
1104                     ]
1105                     target_stack = [
1106                         self.id2token[i.item()] for i in one_input[i : j + 1]
1107                     ]
1108                     comment = "*" if correct else "-"
1109                     result_stack = " ".join([str(x) for x in result_stack])
1110                     target_stack = " ".join([str(x) for x in target_stack])
1111                     logger(
1112                         f"output_test {comment} [{target_stack}] PREDICTED [{result_stack}]"
1113                     )
1114                     nb_to_log -= 1
1115
1116             return sum_nb_total, sum_nb_errors
1117
1118         # --------------------------------------------------------------------
1119
1120         if not self.no_prog:
1121             test_nb_total, test_nb_errors = compute_nb_errors_prog(
1122                 self.test_input[:1000].to(self.device), nb_to_log=10
1123             )
1124
1125             logger(
1126                 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}%"
1127             )
1128
1129         test_nb_total, test_nb_errors = compute_nb_errors_output(
1130             self.test_input[:1000].to(self.device), nb_to_log=10
1131         )
1132
1133         logger(
1134             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}%"
1135         )
1136
1137         if save_attention_image is not None:
1138             ns = torch.randint(self.test_input.size(0), (1,)).item()
1139             input = self.test_input[ns : ns + 1].clone()
1140             last = (input != self.t_nul).max(0).values.nonzero().max() + 3
1141             input = input[:, :last].to(self.device)
1142
1143             with torch.autograd.no_grad():
1144                 t = model.training
1145                 model.eval()
1146                 model.record_attention(True)
1147                 model(BracketedSequence(input))
1148                 model.train(t)
1149                 ram = model.retrieve_attention()
1150                 model.record_attention(False)
1151
1152             tokens_output = [self.id2token[i.item()] for i in input[0]]
1153             tokens_input = ["n/a"] + tokens_output[:-1]
1154             for n_head in range(ram[0].size(1)):
1155                 filename = os.path.join(
1156                     result_dir, f"rpl_attention_{n_epoch}_h{n_head}.pdf"
1157                 )
1158                 attention_matrices = [m[0, n_head] for m in ram]
1159                 save_attention_image(
1160                     filename,
1161                     tokens_input,
1162                     tokens_output,
1163                     attention_matrices,
1164                     k_top=10,
1165                     # min_total_attention=0.9,
1166                     token_gap=12,
1167                     layer_gap=50,
1168                 )
1169                 logger(f"wrote {filename}")
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 ######################################################################