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