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                 nb_result_values_max=4 * nb_starting_values,
1074                 max_input=max_input,
1075                 prog_len=prog_len,
1076                 nb_runs=nb_runs,
1077             )
1078             for _ in tqdm.tqdm(range(nb_train_samples), desc="train-data")
1079         ]
1080
1081         test_sequences = [
1082             rpl.generate(
1083                 nb_starting_values=nb_starting_values,
1084                 nb_result_values_max=4 * nb_starting_values,
1085                 max_input=max_input,
1086                 prog_len=prog_len,
1087                 nb_runs=nb_runs,
1088             )
1089             for _ in tqdm.tqdm(range(nb_test_samples), desc="test-data")
1090         ]
1091
1092         symbols = list(
1093             set(["<nul>"] + [x for l in train_sequences + test_sequences for x in l])
1094         )
1095         val_max = max([x if type(x) is int else 0 for x in symbols])
1096         symbols = list(filter(lambda x: type(x) is str, symbols))
1097         symbols.sort()
1098         symbols += [str(n) for n in range(val_max + 1)]
1099         self.token2id = dict([(c, n) for n, c in enumerate(symbols)])
1100         self.id2token = dict([(n, c) for c, n in self.token2id.items()])
1101
1102         self.t_nul = self.token2id["<nul>"]
1103         self.t_prog = self.token2id["<prog>"]
1104         self.t_input = self.token2id["<input>"]
1105         self.t_output = self.token2id["<output>"]
1106
1107         self.train_input = self.tensorize(train_sequences)
1108         self.test_input = self.tensorize(test_sequences)
1109
1110         if logger is not None:
1111             logger(f"value_max {val_max}")
1112             for x in self.train_input[:25]:
1113                 end = (x != self.t_nul).nonzero().max().item() + 1
1114                 seq = [self.id2token[i.item()] for i in x[:end]]
1115                 s = " ".join(seq)
1116                 logger(f"example_seq {s}")
1117
1118         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1119
1120     def batches(self, split="train", nb_to_use=-1, desc=None):
1121         assert split in {"train", "test"}
1122         input = self.train_input if split == "train" else self.test_input
1123         if nb_to_use > 0:
1124             input = input[:nb_to_use]
1125         if desc is None:
1126             desc = f"epoch-{split}"
1127         for batch in tqdm.tqdm(
1128             input.split(self.batch_size), dynamic_ncols=True, desc=desc
1129         ):
1130             last = (batch != self.t_nul).max(0).values.nonzero().max() + 3
1131             batch = batch[:, :last].to(self.device)
1132             yield batch
1133
1134     def vocabulary_size(self):
1135         return self.nb_codes
1136
1137     def produce_results(
1138         self, n_epoch, model, result_dir, logger, deterministic_synthesis
1139     ):
1140         # --------------------------------------------------------------------
1141         def compute_nb_errors_prog(input, nb_to_log=0):
1142             result = input.clone()
1143             s = (result == self.t_prog).long()
1144             ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1145             result = (1 - ar_mask) * result + ar_mask * self.t_nul
1146
1147             masked_inplace_autoregression(
1148                 model,
1149                 self.batch_size,
1150                 result,
1151                 ar_mask,
1152                 deterministic_synthesis,
1153                 device=self.device,
1154             )
1155
1156             sum_nb_total, sum_nb_errors = 0, 0
1157             for x, y in zip(input, result):
1158                 seq = [self.id2token[i.item()] for i in y]
1159                 nb_total, nb_errors, prog, stacks = rpl.compute_nb_errors(seq)
1160                 sum_nb_total += 1
1161                 sum_nb_errors += 0 if nb_errors == 0 else 1
1162                 if nb_to_log > 0:
1163                     gt_seq = [self.id2token[i.item()] for i in x]
1164                     _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1165                     gt_prog = " ".join([str(x) for x in gt_prog])
1166                     prog = " ".join([str(x) for x in prog])
1167                     comment = "*" if nb_errors == 0 else "-"
1168                     logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1169                     for start_stack, target_stack, result_stack, correct in stacks:
1170                         comment = "*" if correct else "-"
1171                         start_stack = " ".join([str(x) for x in start_stack])
1172                         target_stack = " ".join([str(x) for x in target_stack])
1173                         result_stack = " ".join([str(x) for x in result_stack])
1174                         logger(
1175                             f"  {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1176                         )
1177                     nb_to_log -= 1
1178
1179             return sum_nb_total, sum_nb_errors
1180
1181         # --------------------------------------------------------------------
1182         def compute_nb_errors_output(input, nb_to_log=0):
1183             result = input.clone()
1184             k = torch.arange(result.size(1), device=result.device)[None, :]
1185             last_output_idx = ((result == self.t_output) * k).max(dim=1, keep_dim=True)
1186             first_prog_idx = ((result == self.t_prog) * k).min(dim=1, keep_dim=True)
1187             ar_mask = (k > last_output_idx).long() * (k < first_prog_idx)
1188             result = (1 - ar_mask) * result + ar_mask * self.t_nul
1189
1190             masked_inplace_autoregression(
1191                 model,
1192                 self.batch_size,
1193                 result,
1194                 ar_mask,
1195                 deterministic_synthesis,
1196                 device=self.device,
1197             )
1198
1199             sum_nb_total, sum_nb_errors = 0, 0
1200             for x, y in zip(input, result):
1201                 seq = [self.id2token[i.item()] for i in y]
1202                 sum_nb_total += 1
1203                 sum_nb_errors += 0 if (x - y).abs().max() == 0 else 1
1204                 if nb_to_log > 0:
1205                     gt_seq = [self.id2token[i.item()] for i in x]
1206                     _, _, gt_prog, _ = rpl.compute_nb_errors(gt_seq)
1207                     gt_prog = " ".join([str(x) for x in gt_prog])
1208                     prog = " ".join([str(x) for x in prog])
1209                     comment = "*" if nb_errors == 0 else "-"
1210                     logger(f"{comment} PROG [{gt_prog}] PREDICTED [{prog}]")
1211                     for start_stack, target_stack, result_stack, correct in stacks:
1212                         comment = "*" if correct else "-"
1213                         start_stack = " ".join([str(x) for x in start_stack])
1214                         target_stack = " ".join([str(x) for x in target_stack])
1215                         result_stack = " ".join([str(x) for x in result_stack])
1216                         logger(
1217                             f"  {comment} [{start_stack}] -> [{target_stack}] PREDICTED [{result_stack}]"
1218                         )
1219                     nb_to_log -= 1
1220
1221             return sum_nb_total, sum_nb_errors
1222
1223         # --------------------------------------------------------------------
1224
1225         test_nb_total, test_nb_errors = compute_nb_errors_prog(
1226             self.test_input[:1000].to(self.device), nb_to_log=10
1227         )
1228
1229         logger(
1230             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}%"
1231         )
1232
1233
1234 ######################################################################
1235
1236
1237 import expr
1238
1239
1240 class Expr(Task):
1241     def tensorize(self, sequences):
1242         len_max = max([len(x) for x in sequences])
1243         return torch.cat(
1244             [
1245                 torch.tensor(
1246                     [
1247                         [self.char2id[c] for c in s + "#" * (len_max - len(s))]
1248                         for s in sequences
1249                     ]
1250                 )
1251             ],
1252             0,
1253         ).to(self.device)
1254
1255     def __init__(
1256         self,
1257         nb_train_samples,
1258         nb_test_samples,
1259         nb_variables,
1260         sequence_length,
1261         operand_max,
1262         result_max,
1263         batch_size,
1264         device=torch.device("cpu"),
1265     ):
1266         super().__init__()
1267
1268         self.batch_size = batch_size
1269         self.device = device
1270
1271         train_sequences = expr.generate_sequences(
1272             nb_train_samples,
1273             nb_variables=nb_variables,
1274             length=sequence_length,
1275             operand_max=operand_max,
1276             result_max=result_max,
1277         )
1278
1279         test_sequences = expr.generate_sequences(
1280             nb_test_samples,
1281             nb_variables=nb_variables,
1282             length=sequence_length,
1283             operand_max=operand_max,
1284             result_max=result_max,
1285         )
1286
1287         symbols = list(set("#" + "".join(train_sequences + test_sequences)))
1288         symbols.sort()
1289
1290         self.char2id = dict([(c, n) for n, c in enumerate(symbols)])
1291         self.id2char = dict([(n, c) for c, n in self.char2id.items()])
1292
1293         self.filler, self.space = self.char2id["#"], self.char2id[" "]
1294
1295         self.train_input = self.tensorize(train_sequences)
1296         self.test_input = self.tensorize(test_sequences)
1297
1298         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
1299
1300     def batches(self, split="train", nb_to_use=-1, desc=None):
1301         assert split in {"train", "test"}
1302         input = self.train_input if split == "train" else self.test_input
1303         if nb_to_use > 0:
1304             input = input[:nb_to_use]
1305         if desc is None:
1306             desc = f"epoch-{split}"
1307         for batch in tqdm.tqdm(
1308             input.split(self.batch_size), dynamic_ncols=True, desc=desc
1309         ):
1310             last = (batch != self.filler).max(0).values.nonzero().max() + 3
1311             batch = batch[:, :last]
1312             yield batch
1313
1314     def vocabulary_size(self):
1315         return self.nb_codes
1316
1317     def seq2str(self, s):
1318         return "".join([self.id2char[k.item()] for k in s])
1319
1320     def produce_results(
1321         self,
1322         n_epoch,
1323         model,
1324         result_dir,
1325         logger,
1326         deterministic_synthesis,
1327         input_file=None,
1328     ):
1329         def compute_nb_correct(input):
1330             result = input.clone()
1331             s = (result == self.space).long()
1332             ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1333             result = (1 - ar_mask) * result + ar_mask * self.filler
1334             masked_inplace_autoregression(
1335                 model,
1336                 self.batch_size,
1337                 result,
1338                 ar_mask,
1339                 deterministic_synthesis,
1340                 device=self.device,
1341             )
1342
1343             nb_total = input.size(0)
1344             nb_correct = (input == result).long().min(1).values.sum()
1345
1346             #######################################################################
1347             # Comput predicted vs. true variable values
1348
1349             nb_delta = torch.zeros(5, dtype=torch.int64)
1350             nb_missed = 0
1351
1352             values_input = expr.extract_results([self.seq2str(s) for s in input])
1353             values_result = expr.extract_results([self.seq2str(s) for s in result])
1354
1355             filename = os.path.join(result_dir, f"expr_result_{n_epoch:04d}.txt")
1356
1357             with open(filename, "w") as f:
1358                 for i, r in zip(values_input, values_result):
1359                     for n, vi in i.items():
1360                         vr = r.get(n)
1361                         f.write(f"{vi} {-1 if vr is None else vr}\n")
1362
1363                         if vr is None or vr < 0:
1364                             nb_missed += 1
1365                         else:
1366                             d = abs(vr - vi)
1367                             if d >= nb_delta.size(0):
1368                                 nb_missed += 1
1369                             else:
1370                                 nb_delta[d] += 1
1371
1372             ######################################################################
1373
1374             return nb_total, nb_correct, nb_delta, nb_missed
1375
1376         (
1377             test_nb_total,
1378             test_nb_correct,
1379             test_nb_delta,
1380             test_nb_missed,
1381         ) = compute_nb_correct(self.test_input[:10000])
1382
1383         logger(
1384             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}%"
1385         )
1386
1387         nb_total = test_nb_delta.sum() + test_nb_missed
1388         for d in range(test_nb_delta.size(0)):
1389             logger(
1390                 f"error_value {n_epoch} delta {d} {test_nb_delta[d]} {test_nb_delta[d]*100/nb_total:.02f}%"
1391             )
1392         logger(
1393             f"error_value {n_epoch} missed {test_nb_missed} {test_nb_missed*100/nb_total:.02f}%"
1394         )
1395
1396         ##############################################################
1397         # Log a few generated sequences
1398         if input_file is None:
1399             input = self.test_input[:10]
1400         else:
1401             with open(input_file, "r") as f:
1402                 sequences = [e.strip() for e in f.readlines()]
1403                 sequences = [s + " " + "#" * 50 for s in sequences]
1404                 input = self.tensorize(sequences)
1405
1406         result = input.clone()
1407         s = (result == self.space).long()
1408         ar_mask = (s.cumsum(dim=1) - s).clamp(min=0, max=1)
1409         result = (1 - ar_mask) * result + ar_mask * self.filler
1410
1411         for n in range(result.size(0)):
1412             logger(f"test_before {self.seq2str(result[n])}")
1413
1414         masked_inplace_autoregression(
1415             model,
1416             self.batch_size,
1417             result,
1418             ar_mask,
1419             deterministic_synthesis,
1420             device=self.device,
1421         )
1422
1423         correct = (1 - ar_mask) * self.space + ar_mask * input
1424         for n in range(result.size(0)):
1425             comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1426             logger(f"test_after  {self.seq2str(result[n])} {comment}")
1427             logger(f"truth       {self.seq2str(correct[n])}")
1428         ##############################################################
1429
1430
1431 ######################################################################
1432
1433 import world
1434
1435
1436 class World(Task):
1437     def __init__(
1438         self,
1439         nb_train_samples,
1440         nb_test_samples,
1441         batch_size,
1442         vqae_nb_epochs,
1443         logger=None,
1444         device=torch.device("cpu"),
1445         device_storage=torch.device("cpu"),
1446     ):
1447         super().__init__()
1448
1449         self.batch_size = batch_size
1450         self.device = device
1451
1452         (
1453             train_frames,
1454             train_action_seq,
1455             test_frames,
1456             test_action_seq,
1457             self.frame2seq,
1458             self.seq2frame,
1459         ) = world.create_data_and_processors(
1460             nb_train_samples,
1461             nb_test_samples,
1462             mode="first_last",
1463             nb_steps=30,
1464             nb_epochs=vqae_nb_epochs,
1465             logger=logger,
1466             device=device,
1467             device_storage=device_storage,
1468         )
1469
1470         train_frame_seq = self.frame2seq(train_frames).to(device_storage)
1471         test_frame_seq = self.frame2seq(test_frames).to(device_storage)
1472
1473         nb_frame_codes = max(train_frame_seq.max(), test_frame_seq.max()) + 1
1474         nb_action_codes = max(train_action_seq.max(), test_action_seq.max()) + 1
1475
1476         self.len_frame_seq = train_frame_seq.size(1)
1477         self.len_action_seq = train_action_seq.size(1)
1478         self.nb_codes = nb_frame_codes + nb_action_codes
1479
1480         train_frame_seq = train_frame_seq.reshape(train_frame_seq.size(0) // 2, 2, -1)
1481
1482         train_action_seq += nb_frame_codes
1483         self.train_input = torch.cat(
1484             (train_frame_seq[:, 0, :], train_action_seq, train_frame_seq[:, 1, :]), 1
1485         )
1486
1487         test_frame_seq = test_frame_seq.reshape(test_frame_seq.size(0) // 2, 2, -1)
1488         test_action_seq += nb_frame_codes
1489         self.test_input = torch.cat(
1490             (test_frame_seq[:, 0, :], test_action_seq, test_frame_seq[:, 1, :]), 1
1491         )
1492
1493     def batches(self, split="train", nb_to_use=-1, desc=None):
1494         assert split in {"train", "test"}
1495         input = self.train_input if split == "train" else self.test_input
1496         if nb_to_use > 0:
1497             input = input[:nb_to_use]
1498         if desc is None:
1499             desc = f"epoch-{split}"
1500         for batch in tqdm.tqdm(
1501             input.split(self.batch_size), dynamic_ncols=True, desc=desc
1502         ):
1503             yield batch.to(self.device)
1504
1505     def vocabulary_size(self):
1506         return self.nb_codes
1507
1508     def produce_results(
1509         self, n_epoch, model, result_dir, logger, deterministic_synthesis
1510     ):
1511         k = torch.arange(
1512             2 * self.len_frame_seq + self.len_action_seq, device=self.device
1513         )[None, :]
1514
1515         input = self.test_input[:64].to(self.device)
1516         result = input.clone()
1517
1518         ar_mask = (
1519             (k >= self.len_frame_seq + self.len_action_seq).long().expand_as(result)
1520         )
1521         result *= 1 - ar_mask
1522
1523         masked_inplace_autoregression(
1524             model,
1525             self.batch_size,
1526             result,
1527             ar_mask,
1528             deterministic_synthesis,
1529             device=self.device,
1530         )
1531
1532         seq_start = input[:, : self.len_frame_seq]
1533         seq_end = input[:, self.len_frame_seq + self.len_action_seq :]
1534         seq_predicted = result[:, self.len_frame_seq + self.len_action_seq :]
1535
1536         result = torch.cat(
1537             (seq_start[:, None, :], seq_end[:, None, :], seq_predicted[:, None, :]), 1
1538         )
1539         result = result.reshape(-1, result.size(-1))
1540
1541         frames = self.seq2frame(result)
1542         image_name = os.path.join(result_dir, f"world_result_{n_epoch:04d}.png")
1543         torchvision.utils.save_image(
1544             frames.float() / (world.Box.nb_rgb_levels - 1),
1545             image_name,
1546             nrow=12,
1547             padding=1,
1548             pad_value=0.0,
1549         )
1550         logger(f"wrote {image_name}")
1551
1552
1553 ######################################################################