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, sys, argparse, time, tqdm, os, datetime, warnings
10 import torch, torchvision
12 from torch.nn import functional as F
16 import sky, quizz_machine
18 # world quizzes vs. culture quizzes
20 ######################################################################
22 accuracy_to_make_c_quizzes = 0.975
23 nb_new_c_quizzes_for_train = 1000
24 nb_new_c_quizzes_for_test = 100
26 ######################################################################
28 if torch.cuda.is_available():
29 device = torch.device("cuda")
30 torch.backends.cuda.matmul.allow_tf32 = True
32 device = torch.device("cpu")
34 ######################################################################
36 parser = argparse.ArgumentParser(
37 description="An implementation of GPT with cache.",
38 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
41 parser.add_argument("--log_filename", type=str, default="train.log", help=" ")
43 parser.add_argument("--result_dir", type=str, default=None)
45 parser.add_argument("--seed", type=int, default=0)
47 parser.add_argument("--max_percents_of_test_in_train", type=int, default=1)
49 ########################################
51 parser.add_argument("--nb_epochs", type=int, default=10000)
53 parser.add_argument("--batch_size", type=int, default=None)
55 parser.add_argument("--physical_batch_size", type=int, default=None)
57 parser.add_argument("--nb_train_samples", type=int, default=None)
59 parser.add_argument("--nb_test_samples", type=int, default=None)
61 parser.add_argument("--learning_rate", type=float, default=1e-3)
63 ########################################
65 parser.add_argument("--model", type=str, default=None)
67 parser.add_argument("--dim_model", type=int, default=None)
69 parser.add_argument("--dim_keys", type=int, default=None)
71 parser.add_argument("--dim_hidden", type=int, default=None)
73 parser.add_argument("--nb_heads", type=int, default=None)
75 parser.add_argument("--nb_blocks", type=int, default=None)
77 parser.add_argument("--dropout", type=float, default=0.1)
79 ########################################
81 parser.add_argument("--deterministic_synthesis", action="store_true", default=False)
83 parser.add_argument("--nb_gpts", type=int, default=5)
85 parser.add_argument("--nb_correct_to_validate", type=int, default=4)
87 parser.add_argument("--dirty_debug", action="store_true", default=False)
89 ######################################################################
91 args = parser.parse_args()
93 if args.result_dir is None:
94 args.result_dir = f"results_culture"
96 ######################################################################
99 accuracy_to_make_c_quizzes = 0.0
100 nb_new_c_quizzes_for_train = 100
101 nb_new_c_quizzes_for_test = 10
103 ######################################################################
108 "nb_train_samples": 100000,
109 "nb_test_samples": 10000,
112 for k, v in default_args.items():
113 if getattr(args, k) is None:
116 ######################################################################
118 default_model_args = {
156 if args.model in default_model_args:
157 for k, v in default_model_args[args.model].items():
158 if getattr(args, k) is None:
161 raise ValueError(f"Unknown model {args.model}")
163 ######################################################################
166 os.mkdir(args.result_dir)
167 except FileExistsError:
168 print(f"result directory {args.result_dir} already exists")
171 log_file = open(os.path.join(args.result_dir, args.log_filename), "a")
174 # torch.backends.cudnn.deterministic = True
175 # torch.backends.cudnn.benchmark = False
176 # torch.use_deterministic_algorithms(True)
177 torch.manual_seed(args.seed)
178 if torch.cuda.is_available():
179 torch.cuda.manual_seed_all(args.seed)
181 ######################################################################
185 t = time.strftime("%Y%m%d-%H:%M:%S ", time.localtime())
187 if log_file is not None:
188 log_file.write(t + s + "\n")
195 log_string(f"argv {' '.join(sys.argv)}")
198 log_string(f"args.{n} {getattr(args, n)}")
201 ######################################################################
204 args.nb_train_samples = 2500
205 args.nb_test_samples = 100
207 if args.physical_batch_size is None:
208 args.physical_batch_size = args.batch_size
210 assert args.batch_size % args.physical_batch_size == 0
212 assert args.nb_train_samples % args.batch_size == 0
213 assert args.nb_test_samples % args.batch_size == 0
215 quizz_machine = quizz_machine.QuizzMachine(
216 problem=sky.Sky(height=6, width=8, nb_birds=3, nb_iterations=2),
217 nb_train_samples=args.nb_train_samples,
218 nb_test_samples=args.nb_test_samples,
219 batch_size=args.physical_batch_size,
220 result_dir=args.result_dir,
225 ######################################################################
227 log_string(f"device {device}")
229 vocabulary_size = quizz_machine.vocabulary_size()
231 log_string(f"vocabulary_size {vocabulary_size}")
233 ######################################################################
235 # Compute the entropy of the training tokens
238 for input in quizz_machine.batches(split="train", desc="train-entropy"):
239 token_count += F.one_hot(input, num_classes=quizz_machine.vocabulary_size()).sum(
242 token_probas = token_count / token_count.sum()
243 entropy = -torch.xlogy(token_probas, token_probas).sum()
244 train_set_perplexity = math.exp(entropy)
246 ######################################################################
247 # A bit of paranoia never hurts
249 if args.max_percents_of_test_in_train >= 0:
251 def subsets_as_tuples(batches, cs):
253 for batch in batches:
255 s.add(tuple([v.item() for v in x]))
261 nb_test, nb_in_train = 0, 0
262 for test_subset in subsets_as_tuples(
263 quizz_machine.batches(split="test", desc="test-check"), 25000
266 for train_subset in subsets_as_tuples(
267 quizz_machine.batches(split="train", desc="train-check"), 25000
269 in_train.update(test_subset.intersection(train_subset))
270 nb_in_train += len(in_train)
271 nb_test += len(test_subset)
274 f"data_check {nb_in_train*100/nb_test:.02f}% ({nb_in_train}/{nb_test}) of test samples are in the train set"
278 nb_in_train <= args.max_percents_of_test_in_train * nb_test / 100
279 ), f"More than {args.max_percents_of_test_in_train}% of test samples are in the train set"
281 ##############################
284 def one_epoch(model, quizz_machine):
285 optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)
289 nb_train_samples, acc_train_loss = 0, 0.0
291 for input in quizz_machine.batches(split="train"):
292 input = input.to(device)
294 if nb_train_samples % args.batch_size == 0:
295 optimizer.zero_grad()
297 output = model(mygpt.BracketedSequence(input)).x
298 loss = F.cross_entropy(output.transpose(1, 2), input)
299 acc_train_loss += loss.item() * input.size(0)
301 nb_train_samples += input.size(0)
305 if nb_train_samples % args.batch_size == 0:
308 train_perplexity = math.exp(min(100, acc_train_loss / nb_train_samples))
310 log_string(f"train_perplexity {n_epoch} {train_perplexity}")
313 ######################################################################
316 def run_tests(model, quizz_machine, deterministic_synthesis):
317 with torch.autograd.no_grad():
320 nb_test_samples, acc_test_loss = 0, 0.0
321 nb_samples_accumulated = 0
323 for input in quizz_machine.batches(split="test"):
324 input = input.to(device)
326 bs = model(mygpt.BracketedSequence(input))
329 loss = F.cross_entropy(output.transpose(1, 2), input)
331 acc_test_loss += loss.item() * input.size(0)
333 nb_test_samples += input.size(0)
335 main_test_accuracy = quizz_machine.produce_results(
338 result_dir=args.result_dir,
340 deterministic_synthesis=deterministic_synthesis,
343 test_perplexity = math.exp(min(100, acc_test_loss / nb_test_samples))
345 log_string(f"test_perplexity {n_epoch} {test_perplexity}")
347 model.main_test_accuracy = main_test_accuracy
350 ######################################################################
353 def create_c_quizzes(
358 min_ave_seq_logproba=None,
360 # We will store the generated quizzes for each number of
362 recorded = dict([(n, []) for n in range(len(models) + 1)])
365 sum_logits, sum_nb_c_quizzes = 0, 0
368 return sum([sum([x.size(0) for x in recorded[n]]) for n in recorded.keys()])
373 sum([x.size(0) for x in recorded[n]])
374 for n in range(args.nb_correct_to_validate, len(models))
378 while nb_validated() < nb_for_train + nb_for_test:
379 nb_to_validate = nb_for_train + nb_for_test
381 if len(model_indexes) == 0:
382 model_indexes = [i.item() for i in torch.randperm(len(models))]
384 model = models[model_indexes.pop()]
386 new_c_quizzes, nb_correct, ave_seq_logproba = quizz_machine.create_c_quizzes(
388 model_for_generation=model,
389 models_for_validation=models,
390 min_ave_seq_logproba=min_ave_seq_logproba,
392 result_dir=args.result_dir,
396 sum_logits += new_c_quizzes.size(0) * ave_seq_logproba
397 sum_nb_c_quizzes += new_c_quizzes.size(0)
400 nb_correct = torch.randint(
401 len(models) + 1, nb_correct.size(), device=new_c_quizzes.device
404 for n in range(nb_correct.max() + 1):
405 recorded[n].append(new_c_quizzes[nb_correct == n].clone())
408 f"keep c_quizzes {nb_validated()*100/nb_generated():.02f}% kept total {nb_validated()} / {nb_to_validate}"
411 # concatenate and shuffle
412 for n in recorded.keys():
413 if len(recorded[n]) > 0:
414 q = torch.cat(recorded[n], dim=0)
415 q = q[torch.randperm(q.size(0), device=q.device)]
420 new_c_quizzes = torch.cat(
421 [recorded[n] for n in range(args.nb_correct_to_validate, len(models))], dim=0
424 new_c_quizzes = new_c_quizzes[
425 torch.randperm(new_c_quizzes.size(0), device=new_c_quizzes.device)[
426 : nb_for_train + nb_for_test
430 quizz_machine.store_c_quizzes(new_c_quizzes[:nb_for_train], for_train=True)
431 quizz_machine.store_c_quizzes(new_c_quizzes[nb_for_train:], for_train=False)
433 for n in recorded.keys():
434 s = "_validated" if n >= args.nb_correct_to_validate and n < len(models) else ""
435 quizz_machine.problem.save_quizzes(
438 f"culture_c_quiz_{n_epoch:04d}_N{n}{s}",
441 return sum_logits / sum_nb_c_quizzes
444 ######################################################################
448 for k in range(args.nb_gpts):
450 vocabulary_size=vocabulary_size,
451 dim_model=args.dim_model,
452 dim_keys=args.dim_keys,
453 dim_hidden=args.dim_hidden,
454 nb_heads=args.nb_heads,
455 nb_blocks=args.nb_blocks,
457 dropout=args.dropout,
460 model.main_test_accuracy = 0.0
466 nb_parameters = sum(p.numel() for p in models[0].parameters())
467 log_string(f"nb_parameters {nb_parameters} ({int(nb_parameters/1e6)}M)")
469 ######################################################################
471 min_ave_seq_logproba = None
473 for n_epoch in range(args.nb_epochs):
474 log_string(f"--- epoch {n_epoch} ----------------------------------------")
476 a = [(model.id, float(model.main_test_accuracy)) for model in models]
477 a.sort(key=lambda p: p[0])
478 log_string(f"current accuracies {a}")
480 # select the model with lowest accuracy
481 models.sort(key=lambda model: model.main_test_accuracy)
485 f"training model {model.id} main_test_accuracy {model.main_test_accuracy}"
489 one_epoch(model, quizz_machine)
491 quizz_machine.renew_w_quizzes(args.nb_train_samples // args.nb_gpts)
494 f"train_set_composition w_quizzes {quizz_machine.nb_batch_w_quizzes} c_quizzes {quizz_machine.nb_batch_c_quizzes}"
498 run_tests(model, quizz_machine, deterministic_synthesis=False)
501 f"test_set_composition w_quizzes {quizz_machine.nb_batch_w_quizzes} c_quizzes {quizz_machine.nb_batch_c_quizzes}"
504 if min([m.main_test_accuracy for m in models]) >= accuracy_to_make_c_quizzes:
505 ave_seq_logproba = create_c_quizzes(
508 nb_for_train=nb_new_c_quizzes_for_train,
509 nb_for_test=nb_new_c_quizzes_for_test,
510 min_ave_seq_logproba=min_ave_seq_logproba,
513 # We keep the first average logits as a reference
514 # if min_ave_seq_logproba is None:
515 # min_ave_seq_logproba = ave_seq_logproba
518 # f"min_ave_seq_logproba {min_ave_seq_logproba} ave_seq_logproba {ave_seq_logproba}"
523 run_tests(model, quizz_machine, deterministic_synthesis=False)
526 ######################################################################