3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
6 # Written by Francois Fleuret <francois@fleuret.org>
8 import math, os, tqdm, warnings
10 import torch, torchvision
13 from torch.nn import functional as F
16 from mygpt import BracketedSequence
18 ######################################################################
20 # ar_mask is a tensor with 0s and 1s, of same shape as input, with
21 # 1s where tokens should be generated. The others are kept
25 def one_batch_masked_inplace_autoregression(
31 deterministic_synthesis=False,
32 forbidden_tokens=None,
35 to_generate = (ar_mask.sum(0) > 0).nonzero()
37 if to_generate.min() > 0:
39 BracketedSequence(input, 0, to_generate.min())
40 ) # Needed to initialize the model's cache
41 for s in range(to_generate.min(), to_generate.max() + 1):
42 output = model(BracketedSequence(input, s, 1)).x
46 logits = (logits / temperature).log_softmax(dim=-1)
48 if forbidden_tokens is not None:
49 logits = logits.masked_fill(forbidden_tokens, float("-inf"))
51 if forced_biases is not None:
52 logits = logits + forced_biases[None, :]
54 if deterministic_synthesis:
55 t_next = logits.argmax(-1)
57 dist = torch.distributions.categorical.Categorical(logits=logits)
58 t_next = dist.sample()
60 all_n = torch.arange(t_next.size(0))
61 seq_logproba += logits[all_n, t_next].sum(dim=-1)
63 input[:, s] = ar_mask[:, s] * t_next + (1 - ar_mask[:, s]) * input[:, s]
66 def masked_inplace_autoregression(
73 deterministic_synthesis,
74 forbidden_tokens=None,
76 progress_bar_desc=None,
77 device=torch.device("cpu"),
79 assert input.size() == ar_mask.size()
82 input.split(batch_size),
83 ar_mask.split(batch_size),
84 seq_logproba.split(batch_size),
87 if progress_bar_desc is not None:
91 desc=progress_bar_desc,
92 total=(input.size(0) + batch_size - 1) // batch_size,
95 with torch.autograd.no_grad():
99 for input, ar_mask, seq_logproba in batches:
100 one_batch_masked_inplace_autoregression(
104 seq_logproba=seq_logproba,
105 temperature=temperature,
106 deterministic_synthesis=deterministic_synthesis,
107 forbidden_tokens=forbidden_tokens,
108 forced_biases=logit_biases,
114 ######################################################################
118 def make_ar_mask(self, input):
119 b = torch.arange(input.size(1), device=input.device) > input.size(1) // 2
120 return b.long()[None, :].expand_as(input)
130 device=torch.device("cpu"),
134 self.problem = problem
135 self.batch_size = batch_size
139 self.train_w_quizzes = self.problem.generate_token_sequences(
142 self.test_w_quizzes = self.problem.generate_token_sequences(nb_test_samples).to(
146 self.nb_codes = max(self.train_w_quizzes.max(), self.test_w_quizzes.max()) + 1
148 self.train_c_quizzes = []
149 self.test_c_quizzes = []
151 if result_dir is not None:
152 self.problem.save_quizzes(
153 self.train_w_quizzes[:72], result_dir, "culture_w_quizzes"
156 def batches(self, split="train", desc=None):
157 assert split in {"train", "test"}
159 w_quizzes = self.train_w_quizzes
160 c_quizzes = self.train_c_quizzes
162 w_quizzes = self.test_w_quizzes
163 c_quizzes = self.test_c_quizzes
165 if len(c_quizzes) > 0:
166 c_quizzes = torch.cat(c_quizzes, dim=0)
167 if c_quizzes.size(0) > w_quizzes.size(0) // 2:
168 i = torch.randperm(c_quizzes.size(0))[: w_quizzes.size(0) // 2]
169 c_quizzes = c_quizzes[i]
171 i = torch.randperm(w_quizzes.size(0))[
172 : w_quizzes.size(0) - c_quizzes.size(0)
174 w_quizzes = w_quizzes[i]
176 self.nb_batch_w_quizzes = w_quizzes.size(0)
177 self.nb_batch_c_quizzes = c_quizzes.size(0)
179 input = torch.cat([w_quizzes, c_quizzes], dim=0)
182 self.nb_batch_w_quizzes = w_quizzes.size(0)
183 self.nb_batch_c_quizzes = 0
186 input = input[torch.randperm(input.size(0))]
189 desc = f"epoch-{split}"
190 for batch in tqdm.tqdm(
191 input.split(self.batch_size), dynamic_ncols=True, desc=desc
195 def vocabulary_size(self):
199 self, n_epoch, model, result_dir, deterministic_synthesis, nmax=1000
201 def compute_accuracy(input):
203 ar_mask = self.make_ar_mask(input)
204 result = input.clone() * (1 - ar_mask)
205 seq_logproba = torch.empty(input.size(0), device=self.device)
207 masked_inplace_autoregression(
209 batch_size=self.batch_size,
212 seq_logproba=seq_logproba,
214 deterministic_synthesis=deterministic_synthesis,
215 progress_bar_desc=None,
219 nb_total, nb_correct = (
221 (input == result).long().min(dim=1).values.sum(),
224 return nb_total, nb_correct
226 train_nb_total, train_nb_correct = compute_accuracy(self.train_w_quizzes)
229 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}%"
232 test_nb_total, test_nb_correct = compute_accuracy(self.test_w_quizzes)
235 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}%"
238 main_test_accuracy = test_nb_correct / test_nb_total
239 self.logger(f"main_test_accuracy {n_epoch} {main_test_accuracy}")
241 ##############################
243 input = self.test_w_quizzes[:96]
244 ar_mask = self.make_ar_mask(input)
245 result = input.clone() * (1 - ar_mask)
246 seq_logproba = torch.empty(input.size(0), device=self.device)
248 masked_inplace_autoregression(
250 batch_size=self.batch_size,
253 seq_logproba=seq_logproba,
255 deterministic_synthesis=deterministic_synthesis,
256 progress_bar_desc=None,
260 self.problem.save_quizzes(
261 result[:72], result_dir, f"culture_prediction_{n_epoch:04d}_{model.id:02d}"
264 return main_test_accuracy
266 def renew_w_quizzes(self, nb, for_train=True):
267 input = self.train_w_quizzes if for_train else self.test_w_quizzes
268 nb = min(nb, input.size(0))
269 input[:-nb] = input[nb:].clone()
270 input[-nb:] = self.problem.generate_token_sequences(nb).to(self.device)
272 def store_c_quizzes(self, new_c_quizzes, for_train=True):
274 self.train_c_quizzes.append(new_c_quizzes)
276 self.test_c_quizzes.append(new_c_quizzes)
278 def reverse_time(self, c_quizzes):
279 token_forward, token_backward = self.problem.direction_tokens()
281 l = (c_quizzes.size(1) - 1) // 2
282 direction = c_quizzes[:, l : l + 1]
283 direction = self.problem.token_forward * (
284 direction == self.problem.token_backward
285 ) + self.problem.token_backward * (direction == self.problem.token_forward)
287 return torch.cat([c_quizzes[:, l + 1 :], direction, c_quizzes[:, :l]], dim=1)
289 def compute_correctness(self, c_quizzes, models_for_validation):
290 reversed_c_quizzes = self.reverse_time(c_quizzes)
292 ar_mask = self.make_ar_mask(c_quizzes)
293 seq_logproba = torch.empty(ar_mask.size(0), device=self.device)
295 # Check how many of models can solve the quizzes in both directions
299 for model in models_for_validation:
300 result = c_quizzes.clone()
302 masked_inplace_autoregression(
304 batch_size=self.batch_size,
307 seq_logproba=seq_logproba,
309 deterministic_synthesis=True,
310 # progress_bar_desc="solving c_quizzes",
314 correct = (c_quizzes == result).long().min(dim=-1).values
316 reversed_result = reversed_c_quizzes.clone()
318 masked_inplace_autoregression(
320 batch_size=self.batch_size,
321 input=reversed_result,
323 seq_logproba=seq_logproba,
325 deterministic_synthesis=True,
326 # progress_bar_desc="solving reversed c_quizzes",
331 (reversed_c_quizzes == reversed_result).long().min(dim=-1).values
334 nb_correct += correct * reversed_correct
338 ###############################################################
340 def generate_quizzes(self, nb, model_for_generation, reverse_cleanup=False):
341 c_quizzes = torch.empty(
342 nb, self.train_w_quizzes.size(1), device=self.device, dtype=torch.int64
345 ar_mask_prompt = torch.zeros(c_quizzes.size(), device=self.device)
346 ar_mask_prompt[:, : ar_mask_prompt.size(1) // 2 + 1] = 1
347 ar_mask_solve = 1 - ar_mask_prompt
348 seq_logproba = torch.empty(ar_mask_prompt.size(0), device=self.device)
351 warnings.warn("very high temperature with reversed cleanup", RuntimeWarning)
356 # warnings.warn("noise injection", RuntimeWarning)
357 # noise_std = torch.rand(1).item()
358 # self.logger(f"{noise_std=}")
360 # mygpt.set_noise_injection(model_for_generation, noise_std)
362 masked_inplace_autoregression(
363 model=model_for_generation,
364 batch_size=self.batch_size,
366 ar_mask=ar_mask_prompt,
367 seq_logproba=seq_logproba,
368 temperature=temperature,
369 deterministic_synthesis=False,
373 # mygpt.set_noise_injection(model_for_generation, 0.0)
375 ave_seq_logproba = seq_logproba.mean()
377 masked_inplace_autoregression(
378 model=model_for_generation,
379 batch_size=self.batch_size,
381 ar_mask=ar_mask_solve,
382 seq_logproba=seq_logproba,
383 temperature=temperature,
384 deterministic_synthesis=True,
389 c_quizzes = self.reverse_time(c_quizzes)
390 masked_inplace_autoregression(
391 model=model_for_generation,
392 batch_size=self.batch_size,
394 ar_mask=ar_mask_solve,
395 seq_logproba=seq_logproba,
396 temperature=temperature,
397 deterministic_synthesis=True,
401 c_quizzes = self.reverse_time(c_quizzes)
402 masked_inplace_autoregression(
403 model=model_for_generation,
404 batch_size=self.batch_size,
406 ar_mask=ar_mask_solve,
407 seq_logproba=seq_logproba,
408 temperature=temperature,
409 deterministic_synthesis=True,
413 return c_quizzes, seq_logproba.mean()