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