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