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