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