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