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