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