From: François Fleuret Date: Sat, 6 Jul 2024 05:02:15 +0000 (+0300) Subject: Update. X-Git-Url: https://fleuret.org/cgi-bin/gitweb/gitweb.cgi?a=commitdiff_plain;h=da54f88590586ec4949f8bf99bca16bc3b287097;p=culture.git Update. --- diff --git a/main.py b/main.py index 43241dd..585cbdf 100755 --- a/main.py +++ b/main.py @@ -13,7 +13,7 @@ from torch.nn import functional as F import ffutils import mygpt -import sky, reasoning, quizz_machine +import sky, reasoning, quiz_machine # world quizzes vs. culture quizzes @@ -256,7 +256,7 @@ elif args.problem == "reasoning": else: raise ValueError -quizz_machine = quizz_machine.QuizzMachine( +quiz_machine = quiz_machine.QuizMachine( problem=problem, nb_train_samples=args.nb_train_samples, nb_test_samples=args.nb_test_samples, @@ -271,7 +271,7 @@ quizz_machine = quizz_machine.QuizzMachine( log_string(f"device {device}") -vocabulary_size = quizz_machine.vocabulary_size() +vocabulary_size = quiz_machine.vocabulary_size() log_string(f"vocabulary_size {vocabulary_size}") @@ -280,8 +280,8 @@ log_string(f"vocabulary_size {vocabulary_size}") # Compute the entropy of the training tokens token_count = 0 -for input in quizz_machine.batches(split="train", desc="train-entropy"): - token_count += F.one_hot(input, num_classes=quizz_machine.vocabulary_size()).sum( +for input in quiz_machine.batches(split="train", desc="train-entropy"): + token_count += F.one_hot(input, num_classes=quiz_machine.vocabulary_size()).sum( (0, 1) ) token_probas = token_count / token_count.sum() @@ -305,11 +305,11 @@ if args.max_percents_of_test_in_train >= 0: nb_test, nb_in_train = 0, 0 for test_subset in subsets_as_tuples( - quizz_machine.batches(split="test", desc="test-check"), 25000 + quiz_machine.batches(split="test", desc="test-check"), 25000 ): in_train = set() for train_subset in subsets_as_tuples( - quizz_machine.batches(split="train", desc="train-check"), 25000 + quiz_machine.batches(split="train", desc="train-check"), 25000 ): in_train.update(test_subset.intersection(train_subset)) nb_in_train += len(in_train) @@ -326,14 +326,14 @@ if args.max_percents_of_test_in_train >= 0: ############################## -def one_epoch(model, quizz_machine): +def one_epoch(model, quiz_machine): optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate) model.train() nb_train_samples, acc_train_loss = 0, 0.0 - for input in quizz_machine.batches(split="train"): + for input in quiz_machine.batches(split="train"): input = input.to(device) if nb_train_samples % args.batch_size == 0: @@ -358,14 +358,14 @@ def one_epoch(model, quizz_machine): ###################################################################### -def run_tests(model, quizz_machine, deterministic_synthesis): +def run_tests(model, quiz_machine, deterministic_synthesis): with torch.autograd.no_grad(): model.eval() nb_test_samples, acc_test_loss = 0, 0.0 nb_samples_accumulated = 0 - for input in quizz_machine.batches(split="test"): + for input in quiz_machine.batches(split="test"): input = input.to(device) bs = model(mygpt.BracketedSequence(input)) @@ -381,7 +381,7 @@ def run_tests(model, quizz_machine, deterministic_synthesis): log_string(f"test_perplexity {n_epoch} {test_perplexity}") - model.main_test_accuracy = quizz_machine.produce_results( + model.main_test_accuracy = quiz_machine.produce_results( n_epoch=n_epoch, model=model, result_dir=args.result_dir, @@ -402,11 +402,11 @@ def valid_c_quizzes(recorded, criteria): def create_c_quizzes( models, - quizz_machine, + quiz_machine, nb_for_train=1000, nb_for_test=100, ): - recorded = [] + quizzes_and_nb_correct_records = [] nb_to_create = nb_for_train + nb_for_test @@ -418,18 +418,21 @@ def create_c_quizzes( file_name = os.path.join(args.result_dir, f"culture_c_quiz_{n_epoch:04d}_logp.dat") with open(file_name, "w") as logp_file: - while valid_c_quizzes(recorded, standard_validity).size(0) < nb_to_create: + while ( + valid_c_quizzes(quizzes_and_nb_correct_records, standard_validity).size(0) + < nb_to_create + ): # Select a model at random to generate the new quizzes model_for_generation = models[torch.randint(len(models), (1,))] - c_quizzes = quizz_machine.generate_quizzes( + c_quizzes = quiz_machine.generate_quizzes( nb_to_create, model_for_generation=model_for_generation, temperature=args.generation_temperature, ) - nb_correct, seq_logproba = quizz_machine.compute_correctness( + nb_correct, seq_logproba = quiz_machine.compute_correctness( c_quizzes, models, bidirectional_validation=args.bidirectional_validation, @@ -445,12 +448,14 @@ def create_c_quizzes( len(models) + 1, nb_correct.size(), device=c_quizzes.device ) - recorded.append((c_quizzes, nb_correct)) + quizzes_and_nb_correct_records.append((c_quizzes, nb_correct)) nv = F.one_hot(nb_correct, num_classes=len(models) + 1).sum(0) nv = " ".join([str(x.item()) for x in nv]) - nb_validated = valid_c_quizzes(recorded, standard_validity).size(0) + nb_validated = valid_c_quizzes( + quizzes_and_nb_correct_records, standard_validity + ).size(0) log_string( f"keep c_quizzes model {model_for_generation.id} kept {nv} nb_accumulated {nb_validated} / {nb_to_create}" @@ -458,10 +463,12 @@ def create_c_quizzes( # store the new c_quizzes which have been validated - new_c_quizzes = valid_c_quizzes(recorded, standard_validity) + new_c_quizzes = valid_c_quizzes(quizzes_and_nb_correct_records, standard_validity) + + quiz_machine.reverse_random_half_in_place(new_c_quizzes) - quizz_machine.store_c_quizzes(new_c_quizzes[:nb_for_train], for_train=True) - quizz_machine.store_c_quizzes(new_c_quizzes[nb_for_train:], for_train=False) + quiz_machine.store_c_quizzes(new_c_quizzes[:nb_for_train], for_train=True) + quiz_machine.store_c_quizzes(new_c_quizzes[nb_for_train:], for_train=False) # save a bunch of images to investigate what quizzes with a # certain nb of correct predictions look like @@ -473,10 +480,12 @@ def create_c_quizzes( else "" ) - q = valid_c_quizzes(recorded, criteria=lambda nb_correct: nb_correct == n)[:72] + q = valid_c_quizzes( + quizzes_and_nb_correct_records, criteria=lambda nb_correct: nb_correct == n + )[:72] if q.size(0) > 0: - quizz_machine.save_quizzes( + quiz_machine.save_quizzes( args.result_dir, f"culture_c_quiz_{n_epoch:04d}_N{n}{s}", q ) @@ -522,21 +531,21 @@ for n_epoch in range(args.nb_epochs): f"training model {weakest_model.id} main_test_accuracy {weakest_model.main_test_accuracy}" ) - one_epoch(weakest_model, quizz_machine) + one_epoch(weakest_model, quiz_machine) log_string( - f"train_set_composition w_quizzes {quizz_machine.nb_batch_w_quizzes} c_quizzes {quizz_machine.nb_batch_c_quizzes}" + f"train_set_composition w_quizzes {quiz_machine.nb_batch_w_quizzes} c_quizzes {quiz_machine.nb_batch_c_quizzes}" ) - run_tests(weakest_model, quizz_machine, deterministic_synthesis=False) + run_tests(weakest_model, quiz_machine, deterministic_synthesis=False) log_string( - f"test_set_composition w_quizzes {quizz_machine.nb_batch_w_quizzes} c_quizzes {quizz_machine.nb_batch_c_quizzes}" + f"test_set_composition w_quizzes {quiz_machine.nb_batch_w_quizzes} c_quizzes {quiz_machine.nb_batch_c_quizzes}" ) # Replace a fraction of the w_quizzes with fresh ones - quizz_machine.renew_w_quizzes(args.nb_train_samples // args.nb_gpts) + quiz_machine.renew_w_quizzes(args.nb_train_samples // args.nb_gpts) # If all the models are good enough, generate new quizzes and # re-compute the test errors @@ -544,13 +553,13 @@ for n_epoch in range(args.nb_epochs): if min([m.main_test_accuracy for m in models]) >= args.accuracy_to_make_c_quizzes: create_c_quizzes( models, - quizz_machine, + quiz_machine, nb_for_train=nb_new_c_quizzes_for_train, nb_for_test=nb_new_c_quizzes_for_test, ) for model in models: - run_tests(model, quizz_machine, deterministic_synthesis=False) + run_tests(model, quiz_machine, deterministic_synthesis=False) ###################################################################### diff --git a/quizz_machine.py b/quizz_machine.py index 92b5799..0c76239 100755 --- a/quizz_machine.py +++ b/quizz_machine.py @@ -104,7 +104,7 @@ def masked_inplace_autoregression( ###################################################################### -class QuizzMachine: +class QuizMachine: def indices_forward_and_backward(self, quizzes): i_forward = quizzes[:, 0] == self.token_forward j_forward = quizzes[:, 1 + self.prompt_len] == self.token_forward @@ -149,6 +149,11 @@ class QuizzMachine: return m * forward_to_backward + (1 - m) * backward_to_forward + def reverse_random_half_in_place(self, quizzes): + i = torch.rand(quizzes.size(0)) < 0.5 + if i.any(): + quizzes[i] = self.reverse_time(quizzes[i]) + def make_ar_mask(self, quizzes, first=False): i_forward, i_backward = self.indices_forward_and_backward(quizzes) @@ -179,20 +184,12 @@ class QuizzMachine: result = [] for prompt, answer in zip(prompts, answers): - if torch.rand(1) < 0.5: - a = [ - torch.tensor([self.token_forward]), - prompt, - torch.tensor([self.token_forward]), - answer, - ] - else: - a = [ - torch.tensor([self.token_backward]), - answer, - torch.tensor([self.token_backward]), - prompt, - ] + a = [ + torch.tensor([self.token_forward]), + prompt, + torch.tensor([self.token_forward]), + answer, + ] result.append(torch.cat(a, dim=0)[None, :]) @@ -224,11 +221,13 @@ class QuizzMachine: self.prompt_len = None self.answer_len = None - self.train_w_quizzes = self.generate_token_sequences(nb_train_samples).to( - device - ) + self.train_w_quizzes = self.generate_token_sequences(nb_train_samples) + self.reverse_random_half_in_place(self.train_w_quizzes) + self.train_w_quizzes = self.train_w_quizzes.to(device) self.test_w_quizzes = self.generate_token_sequences(nb_test_samples).to(device) + self.reverse_random_half_in_place(self.test_w_quizzes) + self.test_w_quizzes = self.test_w_quizzes.to(device) self.train_c_quizzes = [] self.test_c_quizzes = [] @@ -238,7 +237,6 @@ class QuizzMachine: result_dir, "culture_w_quizzes", self.train_w_quizzes[:72], - n_backward=self.train_w_quizzes[:72, 0] == self.token_backward, ) def save_quizzes( @@ -246,30 +244,25 @@ class QuizzMachine: result_dir, filename_prefix, quizzes, - n_backward=None, mistakes=None, ): quizzes = quizzes.clone() - forward = quizzes[quizzes[:, 0] == self.token_forward] - ib = quizzes[:, 0] == self.token_backward - backward = quizzes[ib] - assert forward.size(0) + backward.size(0) == quizzes.size(0) - quizzes[ib] = self.reverse_time(quizzes[ib]) - - if n_backward is None: - predicted_prompts = None - predicted_answers = None + n_forward = quizzes[quizzes[:, 0] == self.token_forward] + n_backward = quizzes[:, 0] == self.token_backward + backward = quizzes[n_backward] + assert n_forward.size(0) + backward.size(0) == quizzes.size(0) + quizzes[n_backward] = self.reverse_time(quizzes[n_backward]) + + predicted_prompts = n_backward.long() + predicted_answers = 1 - predicted_prompts + if mistakes is not None: + # 0/-1/+1 ~ not-to-predict / predicted wrong / predicted correct + predicted_prompts *= mistakes + predicted_answers *= mistakes else: - predicted_prompts = n_backward.long() - predicted_answers = 1 - predicted_prompts - if mistakes is not None: - # 0/-1/+1 ~ not-to-predict / predicted wrong / predicted correct - predicted_prompts *= mistakes - predicted_answers *= mistakes - else: - # 0/2 ~ not-to-predict / to predict - predicted_prompts *= 2 - predicted_answers *= 2 + # 0/2 ~ not-to-predict / to predict + predicted_prompts *= 2 + predicted_answers *= 2 self.problem.save_quizzes( result_dir, @@ -357,7 +350,7 @@ class QuizzMachine: back_input[:, 2 + self.prompt_len :] = input[ n_backward, 1 : 1 + self.answer_len ] - result[n_backward], correct[n_backward] = compute_accuracy(back_input) + _, correct[n_backward] = compute_accuracy(back_input) if log_prefix is not None: forward_nb_correct = correct[n_forward].sum() @@ -390,7 +383,6 @@ class QuizzMachine: result_dir, f"culture_prediction_{n_epoch:04d}_{model.id:02d}", quizzes=test_result[:72], - n_backward=self.test_w_quizzes[:72, 0] == self.token_backward, mistakes=test_correct[:72] * 2 - 1, ) @@ -400,7 +392,9 @@ class QuizzMachine: input = self.train_w_quizzes if for_train else self.test_w_quizzes nb = min(nb, input.size(0)) input[:-nb] = input[nb:].clone() - input[-nb:] = self.generate_token_sequences(nb).to(self.device) + fresh_w_quizzes = self.generate_token_sequences(nb) + self.reverse_random_half_in_place(fresh_w_quizzes) + input[-nb:] = fresh_w_quizzes.to(self.device) def store_c_quizzes(self, new_c_quizzes, for_train=True): if for_train: