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