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