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