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