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     batches = zip(input.split(batch_size), ar_mask.split(batch_size))
24
25     if progress_bar_desc is not None:
26         batches = tqdm.tqdm(
27             batches,
28             dynamic_ncols=True,
29             desc=progress_bar_desc,
30             total=input.size(0) // batch_size,
31         )
32
33     for input, ar_mask in batches:
34         model.masked_inplace_autoregression(
35             input, ar_mask, forbidden_tokens, deterministic_synthesis
36         )
37
38
39 class Task:
40     def batches(self, split="train"):
41         pass
42
43     def vocabulary_size(self):
44         pass
45
46     def produce_results(
47         self, n_epoch, model, result_dir, logger, deterministic_synthesis
48     ):
49         pass
50
51
52 ######################################################################
53
54 import picoclvr
55
56
57 class PicoCLVR(Task):
58     # Make a tensor from a list of strings
59     def tensorize(self, descr):
60         token_descr = [s.strip().split(" ") for s in descr]
61         l = max([len(s) for s in token_descr])
62         token_descr = [s + ["<nul>"] * (l - len(s)) for s in token_descr]
63         id_descr = [[self.token2id[u] for u in s] for s in token_descr]
64         return torch.tensor(id_descr, device=self.device)
65
66     # Make a list of strings from a tensor
67     def detensorize(self, x):
68         return [" ".join([self.id2token[t.item()] for t in r]) for r in x]
69
70     # trim all the tensors in the tuple z to remove as much token from
71     # left and right in the first tensor. If z is a tuple, all its
72     # elements are trimed according to the triming for the first
73     def trim(self, z, token="<nul>"):
74         n = self.token2id[token]
75         if type(z) == tuple:
76             x = z[0]
77             i = (1 - (F.pad(x, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
78             a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
79             return tuple([t[:, a:b] for t in z])
80         else:
81             i = (1 - (F.pad(z, (1, 1), value=n) == n).min(0).values.long()).cumsum(0)
82             a, b = (i == 0).nonzero().max(), (i == i.max()).nonzero().min()
83             return z[:, a:b]
84
85     ######################
86     # Not the cleanest part of the code
87
88     # Extract the last image of each sequence, from the last <img>
89     # included, and set to <nul> all the tokens from the beginning of
90     # that image to the end
91     def excise_last_image(self, input):
92         t_img, t_nul = self.token2id["<img>"], self.token2id["<nul>"]
93         nb_img_tokens = self.height * self.width + 1
94
95         input = input.clone()
96         t = (input == t_img).long()
97         tail_masks = (t.cumsum(dim=1) == t.sum(dim=1, keepdim=True)).long()
98         i = (t * tail_masks).nonzero(as_tuple=True)
99         j = (
100             i[0][:, None],
101             i[1][:, None] + torch.arange(nb_img_tokens, device=input.device)[None, :],
102         )
103         images = self.trim(input[j])
104         input[j] = t_nul
105         loss_masks = 1 - tail_masks
106         input, loss_masks = self.trim((input, loss_masks))
107         return input, loss_masks, images
108
109     def add_true_image(self, input, images, loss_masks):
110         t_nul = self.token2id["<nul>"]
111         nb_img_tokens = self.height * self.width + 1
112         input = F.pad(input, (0, nb_img_tokens), value=t_nul)
113         loss_masks = F.pad(loss_masks, (0, nb_img_tokens), value=0)
114         t = (input == t_nul).long()
115         i = (t.cumsum(dim=1) == 1).nonzero(as_tuple=True)
116         j = (
117             i[0][:, None],
118             i[1][:, None] + torch.arange(nb_img_tokens, device=input.device)[None, :],
119         )
120         input[j] = images
121         loss_masks[j] = 1
122         input, loss_masks = self.trim((input, loss_masks))
123         return input, loss_masks
124
125     def add_generated_image(self, input, loss_masks, model, deterministic_synthesis):
126         t_img, t_nul = self.token2id["<img>"], self.token2id["<nul>"]
127         nb_img_tokens = self.height * self.width + 1
128
129         input = F.pad(input, (0, nb_img_tokens), value=t_nul)
130         loss_masks = F.pad(loss_masks, (0, nb_img_tokens), value=0)
131         t = (input == t_nul).long()
132         i = (t.cumsum(dim=1) == 1).nonzero(as_tuple=True)
133         input[i] = t_img
134
135         j = (
136             i[0][:, None],
137             i[1][:, None]
138             + 1
139             + torch.arange(nb_img_tokens - 1, device=input.device)[None, :],
140         )
141         ar_masks = input.new_zeros(input.size(), dtype=torch.int64)
142         ar_masks[j] = 1
143         forbidden_tokens = (
144             torch.arange(self.vocabulary_size(), device=input.device) == t_nul
145         )
146         with torch.autograd.no_grad():
147             t = model.training
148             model.eval()
149             masked_inplace_autoregression(
150                 model,
151                 self.batch_size,
152                 input,
153                 ar_masks,
154                 deterministic_synthesis,
155                 forbidden_tokens,
156                 progress_bar_desc=None,
157                 device=self.device,
158             )
159             model.train(t)
160
161         input, loss_masks = self.trim((input, loss_masks))
162
163         return input, loss_masks
164
165     ######################
166
167     def __init__(
168         self,
169         nb_train_samples,
170         nb_test_samples,
171         batch_size,
172         height,
173         width,
174         nb_colors=5,
175         logger=None,
176         device=torch.device("cpu"),
177         pruner_train=None,
178         pruner_eval=None,
179     ):
180         def generate_descr(nb, cache_suffix, pruner):
181             return picoclvr.generate(
182                 nb,
183                 height=self.height,
184                 width=self.width,
185                 nb_colors=nb_colors,
186                 pruner=pruner,
187             )
188
189         self.height = height
190         self.width = width
191         self.batch_size = batch_size
192         self.device = device
193         self.pruner_train = pruner_train
194         self.pruner_eval = pruner_eval
195
196         param = {
197             "nb_train_samples": nb_train_samples,
198             "nb_test_samples": nb_test_samples,
199             "height": height,
200             "width": width,
201             "nb_colors": nb_colors,
202             "batch_size": batch_size,
203             "rng_state": list(torch.get_rng_state()),
204         }
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
229         # Tokenize the train and test sets
230         self.train_input = self.tensorize(self.train_descr)
231         self.test_input = self.tensorize(self.test_descr)
232
233     def batches(self, split="train"):
234         assert split in {"train", "test"}
235         input = self.train_input if split == "train" else self.test_input
236         for batch in tqdm.tqdm(
237             input.split(self.batch_size), dynamic_ncols=True, desc=f"epoch-{split}"
238         ):
239             yield self.trim(batch)
240
241     def vocabulary_size(self):
242         return len(self.token2id)
243
244     def compute_missing_properties(
245         self, n_epoch, model, logger, deterministic_synthesis, pruner=None
246     ):
247         acc_nb_requested_properties = []
248         acc_nb_missing_properties = []
249         acc_nb_results = 0
250
251         for input in tqdm.tqdm(
252             self.test_input.split(self.batch_size),
253             dynamic_ncols=True,
254             desc=f"test-properties",
255         ):
256             tape, loss_masks, _ = self.excise_last_image(input)
257             tape, loss_masks = self.add_generated_image(
258                 tape, loss_masks, model, deterministic_synthesis
259             )
260             result_descr = self.detensorize(tape)
261             np = picoclvr.nb_properties(
262                 result_descr,
263                 height=self.height,
264                 width=self.width,
265                 pruner=pruner,
266             )
267             nb_requested_properties, _, nb_missing_properties = zip(*np)
268             acc_nb_requested_properties += nb_requested_properties
269             acc_nb_missing_properties += nb_missing_properties
270             acc_nb_results += len(result_descr)
271
272         nb_requested_properties = sum(acc_nb_requested_properties)
273         nb_missing_properties = sum(acc_nb_missing_properties)
274
275         prefix = "" if pruner is None else "pruned_"
276         logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
277         logger(
278             f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
279         )
280         logger(
281             f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
282         )
283
284     ######################################################################
285
286     def produce_results(
287         self, n_epoch, model, result_dir, logger, deterministic_synthesis
288     ):
289         self.compute_missing_properties(n_epoch, model, logger, deterministic_synthesis)
290
291         if self.pruner_eval is not None:
292             self.compute_missing_properties(n_epoch, model, self.pruner_eval)
293
294         nb_tokens_to_generate = self.height * self.width + 3
295         result_descr = []
296         nb_per_primer = 8
297         primer = []
298
299         for primer_descr in [
300             "red above green <sep> green top <sep> blue right of red",
301             "there is red <sep> there is yellow <sep> there is blue",
302             "red below yellow <sep> yellow below green <sep> green below blue <sep> red right <sep> yellow left <sep> green right <sep> blue left",
303             "green bottom <sep> yellow bottom <sep> green left of blue <sep> yellow right of blue <sep> blue top",
304         ]:
305             primer += [primer_descr] * nb_per_primer
306
307         tape = self.tensorize(primer)
308         loss_masks = 1 - (tape == self.token2id["<nul>"]).long()
309         tape, loss_masks = self.add_generated_image(
310             tape, loss_masks, model, deterministic_synthesis
311         )
312         result_descr = self.detensorize(tape)
313
314         np = picoclvr.nb_properties(result_descr, height=self.height, width=self.width)
315
316         acc_nb_requested_properties, _, acc_nb_missing_properties = zip(*np)
317         acc_nb_results = len(result_descr)
318
319         nb_requested_properties = sum(acc_nb_requested_properties)
320         nb_missing_properties = sum(acc_nb_missing_properties)
321
322         prefix = "demo_"
323         logger(f"nb_{prefix}samples {n_epoch} {acc_nb_results}")
324         logger(
325             f"property_{prefix}nb {n_epoch} requested {sum(acc_nb_requested_properties)} missing {sum(acc_nb_missing_properties)}"
326         )
327         logger(
328             f"property_{prefix}miss {n_epoch} {100*nb_missing_properties/nb_requested_properties:.02f}%"
329         )
330
331         img = picoclvr.descr2img(result_descr, height=self.height, width=self.width)
332
333         if img.dim() == 5:
334             if img.size(1) == 1:
335                 img = F.pad(img.squeeze(1), pad=(1, 1, 1, 1), value=64)
336             else:
337                 img = torch.cat(
338                     [
339                         torchvision.utils.make_grid(x, padding=1, pad_value=64)[None]
340                         for x in img
341                     ],
342                     0,
343                 )
344
345         image_name = os.path.join(result_dir, f"picoclvr_result_{n_epoch:04d}.png")
346         torchvision.utils.save_image(
347             img / 255.0, image_name, nrow=nb_per_primer, padding=1, pad_value=0.0
348         )
349         logger(f"wrote {image_name}")
350
351
352 ######################################################################
353
354
355 class MNIST(Task):
356     def __init__(
357         self, nb_train_samples, nb_test_samples, batch_size, device=torch.device("cpu")
358     ):
359         self.nb_train_samples = (nb_train_samples,)
360         self.nb_test_samples = (nb_test_samples,)
361         self.batch_size = batch_size
362         self.device = device
363         data_set = torchvision.datasets.MNIST(root="./data", train=True, download=True)
364         self.train_input = data_set.data[:nb_train_samples].view(-1, 28 * 28).long()
365         data_set = torchvision.datasets.MNIST(root="./data", train=False, download=True)
366         self.test_input = data_set.data[:nb_test_samples].view(-1, 28 * 28).long()
367
368     def batches(self, split="train", nb_to_use=-1, desc=None):
369         assert split in {"train", "test"}
370         input = self.train_input if split == "train" else self.test_input
371         if nb_to_use > 0:
372             input = input[:nb_to_use]
373         if desc is None:
374             desc = f"epoch-{split}"
375         for batch in tqdm.tqdm(
376             input.split(self.batch_size), dynamic_ncols=True, desc=desc
377         ):
378             yield batch
379
380     def vocabulary_size(self):
381         return 256
382
383     def produce_results(
384         self, n_epoch, model, result_dir, logger, deterministic_synthesis
385     ):
386         results = torch.empty(64, 28 * 28, device=self.device, dtype=torch.int64)
387         ar_mask = torch.full_like(results, 1)
388         masked_inplace_autoregression(
389             model,
390             self.batch_size,
391             results,
392             ar_mask,
393             deterministic_synthesis,
394             device=self.device,
395         )
396         image_name = os.path.join(result_dir, f"mnist_result_{n_epoch:04d}.png")
397         torchvision.utils.save_image(
398             1 - results.reshape(-1, 1, 28, 28) / 255.0,
399             image_name,
400             nrow=16,
401             pad_value=0.8,
402         )
403         logger(f"wrote {image_name}")
404
405
406 ######################################################################
407
408 import maze
409
410
411 class Maze(Task):
412     def map2seq(self, *m):
413         return torch.cat([x.flatten(1) for x in m], 1)
414
415     def seq2map(self, s):
416         s = s.reshape(s.size(0), -1, self.height, self.width)
417         return (s[:, k] for k in range(s.size(1)))
418
419     def __init__(
420         self,
421         nb_train_samples,
422         nb_test_samples,
423         batch_size,
424         height,
425         width,
426         nb_walls,
427         device=torch.device("cpu"),
428     ):
429         self.batch_size = batch_size
430         self.height = height
431         self.width = width
432         self.device = device
433
434         train_mazes, train_paths, _ = maze.create_maze_data(
435             nb_train_samples,
436             height=height,
437             width=width,
438             nb_walls=nb_walls,
439             progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
440         )
441         self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
442
443         test_mazes, test_paths, _ = maze.create_maze_data(
444             nb_test_samples,
445             height=height,
446             width=width,
447             nb_walls=nb_walls,
448             progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
449         )
450         self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
451
452         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
453
454     def batches(self, split="train", nb_to_use=-1, desc=None):
455         assert split in {"train", "test"}
456         input = self.train_input if split == "train" else self.test_input
457         if nb_to_use > 0:
458             input = input[:nb_to_use]
459         if desc is None:
460             desc = f"epoch-{split}"
461         for batch in tqdm.tqdm(
462             input.split(self.batch_size), dynamic_ncols=True, desc=desc
463         ):
464             yield batch
465
466     def vocabulary_size(self):
467         return self.nb_codes
468
469     def compute_error(
470         self, model, split="train", nb_to_use=-1, deterministic_synthesis=False
471     ):
472         nb_total, nb_correct = 0, 0
473         count = torch.zeros(
474             self.width * self.height,
475             self.width * self.height,
476             device=self.device,
477             dtype=torch.int64,
478         )
479
480         for input in self.batches(split, nb_to_use):
481             result = input.clone()
482             ar_mask = result.new_zeros(result.size())
483             ar_mask[:, self.height * self.width :] = 1
484             result *= 1 - ar_mask
485             masked_inplace_autoregression(
486                 model,
487                 self.batch_size,
488                 result,
489                 ar_mask,
490                 deterministic_synthesis,
491                 progress_bar_desc=None,
492                 device=self.device,
493             )
494             mazes, paths = self.seq2map(result)
495             path_correctness = maze.path_correctness(mazes, paths)
496             nb_correct += path_correctness.long().sum()
497             nb_total += mazes.size(0)
498
499             optimal_path_lengths = (
500                 (input[:, self.height * self.width :] == maze.v_path).long().sum(1)
501             )
502             predicted_path_lengths = (
503                 (result[:, self.height * self.width :] == maze.v_path).long().sum(1)
504             )
505             optimal_path_lengths = optimal_path_lengths[path_correctness]
506             predicted_path_lengths = predicted_path_lengths[path_correctness]
507             count[optimal_path_lengths, predicted_path_lengths] += 1
508
509         if count.max() == 0:
510             count = None
511         else:
512             count = count[
513                 : count.sum(1).nonzero().max() + 1, : count.sum(0).nonzero().max() + 1
514             ]
515
516         return nb_total, nb_correct, count
517
518     def produce_results(
519         self, n_epoch, model, result_dir, logger, deterministic_synthesis
520     ):
521         with torch.autograd.no_grad():
522             t = model.training
523             model.eval()
524
525             train_nb_total, train_nb_correct, count = self.compute_error(
526                 model,
527                 "train",
528                 nb_to_use=1000,
529                 deterministic_synthesis=deterministic_synthesis,
530             )
531             logger(
532                 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}%"
533             )
534
535             test_nb_total, test_nb_correct, count = self.compute_error(
536                 model,
537                 "test",
538                 nb_to_use=1000,
539                 deterministic_synthesis=deterministic_synthesis,
540             )
541             logger(
542                 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}%"
543             )
544
545             if count is not None:
546                 proportion_optimal = count.diagonal().sum().float() / count.sum()
547                 logger(f"proportion_optimal_test {proportion_optimal*100:.02f}%")
548                 with open(
549                     os.path.join(result_dir, f"maze_result_{n_epoch:04d}.txt"), "w"
550                 ) as f:
551                     for i in range(count.size(0)):
552                         for j in range(count.size(1)):
553                             eol = " " if j < count.size(1) - 1 else "\n"
554                             f.write(f"{count[i,j]}{eol}")
555
556             input = self.test_input[:48]
557             result = input.clone()
558             ar_mask = result.new_zeros(result.size())
559             ar_mask[:, self.height * self.width :] = 1
560             result *= 1 - ar_mask
561             masked_inplace_autoregression(
562                 model,
563                 self.batch_size,
564                 result,
565                 ar_mask,
566                 deterministic_synthesis,
567                 device=self.device,
568             )
569
570             mazes, paths = self.seq2map(input)
571             _, predicted_paths = self.seq2map(result)
572
573             filename = os.path.join(result_dir, f"maze_result_{n_epoch:04d}.png")
574             maze.save_image(
575                 filename,
576                 mazes=mazes,
577                 target_paths=paths,
578                 predicted_paths=predicted_paths,
579                 path_correct=maze.path_correctness(mazes, predicted_paths),
580                 path_optimal=maze.path_optimality(paths, predicted_paths),
581             )
582             logger(f"wrote {filename}")
583
584             model.train(t)
585
586
587 ######################################################################
588
589
590 import snake
591
592
593 class Snake(Task):
594     def __init__(
595         self,
596         nb_train_samples,
597         nb_test_samples,
598         batch_size,
599         height,
600         width,
601         nb_colors,
602         length,
603         prompt_length,
604         device=torch.device("cpu"),
605     ):
606         self.batch_size = batch_size
607         self.height = height
608         self.width = width
609         self.device = device
610         self.prompt_length = prompt_length
611
612         self.train_input, self.train_prior_visits, _, _ = snake.generate_sequences(
613             nb_train_samples,
614             height,
615             width,
616             nb_colors,
617             length,
618             prompt_length,
619             self.device,
620         )
621         self.test_input, self.test_prior_visits, _, _ = snake.generate_sequences(
622             nb_test_samples,
623             height,
624             width,
625             nb_colors,
626             length,
627             prompt_length,
628             self.device,
629         )
630
631         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
632
633     def batches(self, split="train", nb_to_use=-1, desc=None):
634         assert split in {"train", "test"}
635         input = self.train_input if split == "train" else self.test_input
636         if nb_to_use > 0:
637             input = input[:nb_to_use]
638         if desc is None:
639             desc = f"epoch-{split}"
640         for batch in tqdm.tqdm(
641             input.split(self.batch_size), dynamic_ncols=True, desc=desc
642         ):
643             yield batch
644
645     def vocabulary_size(self):
646         return self.nb_codes
647
648     def produce_results(
649         self, n_epoch, model, result_dir, logger, deterministic_synthesis
650     ):
651         with torch.autograd.no_grad():
652             t = model.training
653             model.eval()
654
655             def compute_nb_correct(input, prior_visits):
656                 result = input.clone()
657                 i = torch.arange(result.size(1), device=result.device)[None, :]
658                 ar_mask = (
659                     torch.logical_and(i >= self.prompt_length * 2, i % 2 == 0)
660                     .long()
661                     .expand_as(result)
662                 )
663                 result *= 1 - ar_mask
664
665                 # snake.solver(result,ar_mask)
666
667                 masked_inplace_autoregression(
668                     model,
669                     self.batch_size,
670                     result,
671                     ar_mask,
672                     deterministic_synthesis,
673                     device=self.device,
674                 )
675
676                 nb_total = ((prior_visits > 0) * ar_mask).sum()
677
678                 nb_correct = (
679                     (result == input).long() * (prior_visits > 0) * ar_mask
680                 ).sum()
681
682                 # nb_total = result.size(0)
683                 # nb_correct = ((result - input).abs().sum(1) == 0).sum()
684
685                 return nb_total, nb_correct
686
687             # train_nb_total, train_nb_correct = compute_nb_correct(
688             # self.train_input, self.train_prior_visits
689             # )
690
691             # logger(
692             # f"accuracy_train nb_total {train_nb_total} nb_correct {train_nb_correct} accuracy {(100.0*train_nb_correct)/train_nb_total:.02f}%"
693             # )
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             model.train(t)
704
705
706 ######################################################################
707
708
709 import stack
710
711
712 class Stack(Task):
713     def __init__(
714         self,
715         nb_train_samples,
716         nb_test_samples,
717         batch_size,
718         logger,
719         nb_steps,
720         nb_stacks,
721         nb_digits,
722         fraction_values_for_train=None,
723         device=torch.device("cpu"),
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         with torch.autograd.no_grad():
784             t = model.training
785             model.eval()
786
787             def compute_nb_correct(input):
788                 result = input.clone()
789                 stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
790                 ar_mask = (result != input).long()
791                 masked_inplace_autoregression(
792                     model,
793                     self.batch_size,
794                     result,
795                     ar_mask,
796                     deterministic_synthesis,
797                     device=self.device,
798                 )
799
800                 errors = ((result != input).long() * ar_mask).reshape(
801                     -1, 1 + self.nb_digits
802                 )
803                 ar_mask = ar_mask.reshape(-1, 1 + self.nb_digits)
804
805                 nb_total = ar_mask.max(1).values.sum()
806                 nb_correct = nb_total - errors.max(1).values.sum()
807
808                 return nb_total, nb_correct
809
810             test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000])
811
812             logger(
813                 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}%"
814             )
815
816             ##############################################################
817             # Log a few generated sequences
818             input = self.test_input[:10, : 12 * (1 + self.nb_digits)]
819             result = input.clone()
820             stack.remove_popped_values(result, self.nb_stacks, self.nb_digits)
821             ar_mask = (result != input).long()
822             for n in range(result.size(0)):
823                 logger(
824                     f"test_before {stack.seq_to_str(result[n],nb_stacks=self.nb_stacks,nb_digits=self.nb_digits)}"
825                 )
826                 masked_inplace_autoregression(
827                     model,
828                     self.batch_size,
829                     result,
830                     ar_mask,
831                     deterministic_synthesis,
832                     device=self.device,
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             model.train(t)
841
842
843 ######################################################################
844
845
846 import expr
847
848
849 class Expr(Task):
850     def __init__(
851         self,
852         nb_train_samples,
853         nb_test_samples,
854         nb_variables,
855         sequence_length,
856         batch_size,
857         device=torch.device("cpu"),
858     ):
859         self.batch_size = batch_size
860         self.device = device
861
862         train_sequences = expr.generate_sequences(
863             nb_train_samples,
864             nb_variables=nb_variables,
865             length=sequence_length,
866             # length=2 * sequence_length,
867             # randomize_length=True,
868         )
869         test_sequences = expr.generate_sequences(
870             nb_test_samples,
871             nb_variables=nb_variables,
872             length=sequence_length,
873         )
874         self.char2id = dict(
875             [
876                 (c, n)
877                 for n, c in enumerate(
878                     set("#" + "".join(train_sequences + test_sequences))
879                 )
880             ]
881         )
882         self.id2char = dict([(n, c) for c, n in self.char2id.items()])
883
884         self.filler, self.space = self.char2id["#"], self.char2id[" "]
885
886         len_max = max([len(x) for x in train_sequences])
887         self.train_input = torch.cat(
888             [
889                 torch.tensor(
890                     [
891                         [self.char2id[c] for c in s + "#" * (len_max - len(s))]
892                         for s in train_sequences
893                     ]
894                 )
895             ],
896             0,
897         ).to(device)
898
899         len_max = max([len(x) for x in test_sequences])
900         self.test_input = torch.cat(
901             [
902                 torch.tensor(
903                     [
904                         [self.char2id[c] for c in s + "#" * (len_max - len(s))]
905                         for s in test_sequences
906                     ]
907                 )
908             ],
909             0,
910         ).to(device)
911
912         self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1
913
914     def batches(self, split="train", nb_to_use=-1, desc=None):
915         assert split in {"train", "test"}
916         input = self.train_input if split == "train" else self.test_input
917         if nb_to_use > 0:
918             input = input[:nb_to_use]
919         if desc is None:
920             desc = f"epoch-{split}"
921         for batch in tqdm.tqdm(
922             input.split(self.batch_size), dynamic_ncols=True, desc=desc
923         ):
924             if split == "train":
925                 last = (batch != self.filler).max(0).values.nonzero().max() + 3
926                 batch = batch[:, :last]
927             yield batch
928
929     def vocabulary_size(self):
930         return self.nb_codes
931
932     def seq2str(self, s):
933         return "".join([self.id2char[k.item()] for k in s])
934
935     def produce_results(
936         self, n_epoch, model, result_dir, logger, deterministic_synthesis
937     ):
938         with torch.autograd.no_grad():
939             t = model.training
940             model.eval()
941
942             def compute_nb_correct(input):
943                 result = input.clone()
944                 ar_mask = (result == self.space).long().cumsum(dim=1).clamp(max=1)
945                 result = (1 - ar_mask) * result + ar_mask * self.filler
946                 masked_inplace_autoregression(
947                     model,
948                     self.batch_size,
949                     result,
950                     ar_mask,
951                     deterministic_synthesis,
952                     device=self.device,
953                 )
954
955                 nb_total = input.size(0)
956                 nb_correct = (input == result).long().min(1).values.sum()
957
958                 #######################################################################
959                 # Comput predicted vs. true variable values
960
961                 nb_delta = torch.zeros(5, dtype=torch.int64)
962                 nb_missed = 0
963
964                 values_input = expr.extract_results([self.seq2str(s) for s in input])
965                 values_result = expr.extract_results([self.seq2str(s) for s in result])
966
967                 for i, r in zip(values_input, values_result):
968                     for n, vi in i.items():
969                         vr = r.get(n)
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[:1000])
989
990             logger(
991                 f"accuracy_test {n_epoch} nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
992             )
993
994             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             input = self.test_input[:10]
1006             result = input.clone()
1007             ar_mask = (result == self.space).long().cumsum(dim=1).clamp(max=1)
1008             result = (1 - ar_mask) * result + ar_mask * self.filler
1009             for n in range(result.size(0)):
1010                 logger(f"test_before {self.seq2str(result[n])}")
1011                 masked_inplace_autoregression(
1012                     model,
1013                     self.batch_size,
1014                     result,
1015                     ar_mask,
1016                     deterministic_synthesis,
1017                     device=self.device,
1018                 )
1019             correct = (1 - ar_mask) * self.space + ar_mask * input
1020             for n in range(result.size(0)):
1021                 comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else ""
1022                 logger(f"test_after  {self.seq2str(result[n])} {comment}")
1023                 logger(f"correct     {self.seq2str(correct[n])}")
1024             ##############################################################
1025
1026             model.train(t)
1027
1028
1029 ######################################################################