28b94d10dbc990430f1a7587b11645da14b36206
[culture.git] / quizz_machine.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 import math, os, tqdm, warnings
9
10 import torch, torchvision
11
12 from torch import nn
13 from torch.nn import functional as F
14
15 from mygpt import BracketedSequence
16
17 ######################################################################
18
19
20 def masked_inplace_autoregression(
21     model,
22     batch_size,
23     input,
24     ar_mask,
25     seq_logproba,
26     temperature,
27     deterministic_synthesis,
28     forbidden_tokens=None,
29     logit_biases=None,
30     progress_bar_desc="autoregression",
31     device=torch.device("cpu"),
32 ):
33     assert input.size() == ar_mask.size()
34
35     batches = zip(
36         input.split(batch_size),
37         ar_mask.split(batch_size),
38         seq_logproba.split(batch_size),
39     )
40
41     if progress_bar_desc is not None:
42         batches = tqdm.tqdm(
43             batches,
44             dynamic_ncols=True,
45             desc=progress_bar_desc,
46             total=(input.size(0) + batch_size - 1) // batch_size,
47         )
48
49     with torch.autograd.no_grad():
50         t = model.training
51         model.eval()
52
53         for input, ar_mask, seq_logproba in batches:
54             model.masked_inplace_autoregression(
55                 input=input,
56                 ar_mask=ar_mask,
57                 seq_logproba=seq_logproba,
58                 temperature=temperature,
59                 deterministic_synthesis=deterministic_synthesis,
60                 forbidden_tokens=forbidden_tokens,
61                 forced_biases=logit_biases,
62             )
63
64         model.train(t)
65
66
67 ######################################################################
68
69 import sky
70
71
72 class QuizzMachine:
73     def make_ar_mask(self, input):
74         b = torch.arange(input.size(1), device=input.device) > input.size(1) // 2
75         return b.long()[None, :].expand_as(input)
76
77     def __init__(
78         self,
79         nb_train_samples,
80         nb_test_samples,
81         batch_size,
82         result_dir=None,
83         logger=None,
84         device=torch.device("cpu"),
85     ):
86         super().__init__()
87
88         self.problem = sky.Sky(height=6, width=8, nb_birds=3, nb_iterations=2)
89         self.batch_size = batch_size
90         self.device = device
91
92         self.train_w_quizzes = self.problem.generate_seq(nb_train_samples).to(device)
93         self.test_w_quizzes = self.problem.generate_seq(nb_test_samples).to(device)
94
95         self.nb_codes = max(self.train_w_quizzes.max(), self.test_w_quizzes.max()) + 1
96
97         self.train_c_quizzes = []
98         self.test_c_quizzes = []
99
100         if result_dir is not None:
101             self.problem.save_quizzes(
102                 self.train_w_quizzes[:72], result_dir, f"culture_w_quizzes", logger
103             )
104
105     def batches(self, split="train", desc=None):
106         assert split in {"train", "test"}
107         if split == "train":
108             w_quizzes = self.train_w_quizzes
109             c_quizzes = self.train_c_quizzes
110         else:
111             w_quizzes = self.test_w_quizzes
112             c_quizzes = self.test_c_quizzes
113
114         if len(c_quizzes) > 0:
115             c_quizzes = torch.cat(c_quizzes, dim=0)
116             if c_quizzes.size(0) > w_quizzes.size(0) // 2:
117                 i = torch.randperm(w_quizzes.size(0))[: w_quizzes.size(0) // 2]
118                 c_quizzes = c_quizzes[i]
119
120             i = torch.randperm(w_quizzes.size(0))[
121                 : w_quizzes.size(0) - c_quizzes.size(0)
122             ]
123             w_quizzes = w_quizzes[i]
124
125             self.nb_batch_w_quizzes = w_quizzes.size(0)
126             self.nb_batch_c_quizzes = c_quizzes.size(0)
127
128             input = torch.cat([w_quizzes, c_quizzes], dim=0)
129         else:
130             input = w_quizzes
131             self.nb_batch_w_quizzes = w_quizzes.size(0)
132             self.nb_batch_c_quizzes = 0
133
134         # Shuffle
135         input = input[torch.randperm(input.size(0))]
136
137         if desc is None:
138             desc = f"epoch-{split}"
139         for batch in tqdm.tqdm(
140             input.split(self.batch_size), dynamic_ncols=True, desc=desc
141         ):
142             yield batch
143
144     def vocabulary_size(self):
145         return self.nb_codes
146
147     def produce_results(
148         self, n_epoch, model, result_dir, logger, deterministic_synthesis, nmax=1000
149     ):
150         def compute_accuracy(input, logger=None):
151             input = input[:nmax]
152             ar_mask = self.make_ar_mask(input)
153             result = input.clone() * (1 - ar_mask)
154             seq_logproba = torch.empty(input.size(0), device=self.device)
155
156             masked_inplace_autoregression(
157                 model=model,
158                 batch_size=self.batch_size,
159                 input=result,
160                 ar_mask=ar_mask,
161                 seq_logproba=seq_logproba,
162                 temperature=1.0,
163                 deterministic_synthesis=deterministic_synthesis,
164                 progress_bar_desc=None,
165                 device=self.device,
166             )
167
168             nb_total, nb_correct = (
169                 input.size(0),
170                 (input == result).long().min(dim=1).values.sum(),
171             )
172
173             return nb_total, nb_correct
174
175         train_nb_total, train_nb_correct = compute_accuracy(self.train_w_quizzes)
176
177         logger(
178             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}%"
179         )
180
181         test_nb_total, test_nb_correct = compute_accuracy(self.test_w_quizzes, logger)
182
183         logger(
184             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}%"
185         )
186
187         main_test_accuracy = test_nb_correct / test_nb_total
188         logger(f"main_test_accuracy {n_epoch} {main_test_accuracy}")
189
190         ##############################
191
192         input = self.test_w_quizzes[:96]
193         ar_mask = self.make_ar_mask(input)
194         result = input.clone() * (1 - ar_mask)
195         seq_logproba = torch.empty(input.size(0), device=self.device)
196
197         masked_inplace_autoregression(
198             model=model,
199             batch_size=self.batch_size,
200             input=result,
201             ar_mask=ar_mask,
202             seq_logproba=seq_logproba,
203             temperature=1.0,
204             deterministic_synthesis=deterministic_synthesis,
205             progress_bar_desc=None,
206             device=self.device,
207         )
208
209         self.problem.save_quizzes(
210             result[:72],
211             result_dir,
212             f"culture_prediction_{n_epoch:04d}_{model.id:02d}",
213             logger,
214         )
215
216         return main_test_accuracy
217
218     def renew_w_quizzes(self, nb, for_train=True):
219         input = self.train_w_quizzes if for_train else self.test_w_quizzes
220         nb = min(nb, input.size(0))
221         input[:-nb] = input[nb:].clone()
222         input[-nb:] = self.problem.generate_seq(nb).to(self.device)
223
224     def store_c_quizzes(self, new_c_quizzes, for_train=True):
225         if for_train:
226             self.train_c_quizzes.append(new_c_quizzes)
227         else:
228             self.test_c_quizzes.append(new_c_quizzes)
229
230     def create_c_quizzes(
231         self,
232         n_epoch,
233         result_dir,
234         logger,
235         nb,
236         model,
237         other_models,
238         min_ave_seq_logproba,
239     ):
240         ###############################################################
241         # Generate quizzes with model
242
243         c_quizzes = torch.empty(
244             nb, self.train_w_quizzes.size(1), device=self.device, dtype=torch.int64
245         )
246
247         ar_mask = torch.full(c_quizzes.size(), 1, device=self.device)
248         seq_logproba = torch.empty(ar_mask.size(0), device=self.device)
249
250         temperature = 1
251         d_temperature = 1 / 3
252
253         while True:
254             seq_logproba[...] = 0
255
256             masked_inplace_autoregression(
257                 model=model,
258                 batch_size=self.batch_size,
259                 input=c_quizzes,
260                 ar_mask=ar_mask,
261                 seq_logproba=seq_logproba,
262                 temperature=temperature,
263                 deterministic_synthesis=False,
264                 progress_bar_desc="sampling c_quizzes",
265                 device=self.device,
266             )
267
268             ave_seq_logproba = seq_logproba.mean()
269
270             logger(f"{ave_seq_logproba=} {min_ave_seq_logproba=}")
271
272             if min_ave_seq_logproba is None:
273                 break
274
275             # Oh man that's ugly
276             if ave_seq_logproba < min_ave_seq_logproba * 1.1:
277                 if d_temperature > 0:
278                     d_temperature *= -1 / 3
279                 temperature += d_temperature
280             elif ave_seq_logproba > min_ave_seq_logproba:
281                 if d_temperature < 0:
282                     d_temperature *= -1 / 3
283                 temperature += d_temperature
284             else:
285                 break
286
287             logger(f"chaging temperature to {temperature}")
288
289         ###############################################################
290         # Create the reverse quizzes
291
292         token_forward, token_backward = self.problem.direction_tokens()
293
294         l = (c_quizzes.size(1) - 1) // 2
295         direction = c_quizzes[:, l : l + 1]
296         direction = self.problem.token_forward * (
297             direction == self.problem.token_backward
298         ) + self.problem.token_backward * (direction == self.problem.token_forward)
299         reverse_c_quizzes = torch.cat(
300             [c_quizzes[:, l + 1 :], direction, c_quizzes[:, :l]], dim=1
301         )
302
303         ar_mask = self.make_ar_mask(c_quizzes)
304         seq_logproba = torch.empty(ar_mask.size(0), device=self.device)
305
306         ###############################################################
307         # Check how many of the other models can solve them in both
308         # directions
309
310         nb_correct = []
311
312         for m in other_models:
313             result = c_quizzes.clone()
314
315             masked_inplace_autoregression(
316                 model=m,
317                 batch_size=self.batch_size,
318                 input=result,
319                 ar_mask=ar_mask,
320                 seq_logproba=seq_logproba,
321                 temperature=1.0,
322                 deterministic_synthesis=True,
323                 progress_bar_desc="solving c_quizzes",
324                 device=self.device,
325             )
326
327             correct = (c_quizzes == result).long().min(dim=-1).values
328
329             reverse_result = reverse_c_quizzes.clone()
330
331             masked_inplace_autoregression(
332                 model=m,
333                 batch_size=self.batch_size,
334                 input=reverse_result,
335                 ar_mask=ar_mask,
336                 seq_logproba=seq_logproba,
337                 temperature=1.0,
338                 deterministic_synthesis=True,
339                 progress_bar_desc="solving reversed c_quizzes",
340                 device=self.device,
341             )
342
343             reverse_correct = (
344                 (reverse_c_quizzes == reverse_result).long().min(dim=-1).values
345             )
346
347             nb_correct.append((correct * reverse_correct)[None, :])
348
349         nb_correct = torch.cat(nb_correct, dim=0).sum(dim=0)
350
351         return c_quizzes, nb_correct, seq_logproba.mean()