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