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
17 import sky, grids, quiz_machine
19 # world quizzes vs. culture quizzes
21 ######################################################################
23 if torch.cuda.is_available():
24 device = torch.device("cuda")
25 torch.backends.cuda.matmul.allow_tf32 = True
27 device = torch.device("cpu")
29 ######################################################################
31 parser = argparse.ArgumentParser(
32 description="An implementation of GPT with cache.",
33 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
36 parser.add_argument("--log_filename", type=str, default="train.log")
38 parser.add_argument("--result_dir", type=str, default=None)
40 parser.add_argument("--seed", type=int, default=0)
42 parser.add_argument("--max_percents_of_test_in_train", type=int, default=1)
44 ########################################
46 parser.add_argument("--nb_epochs", type=int, default=10000)
48 parser.add_argument("--batch_size", type=int, default=None)
50 parser.add_argument("--physical_batch_size", type=int, default=None)
52 parser.add_argument("--nb_train_samples", type=int, default=None)
54 parser.add_argument("--nb_test_samples", type=int, default=None)
56 parser.add_argument("--learning_rate", type=float, default=5e-4)
58 ########################################
60 parser.add_argument("--model", type=str, default=None)
62 parser.add_argument("--dim_model", type=int, default=None)
64 parser.add_argument("--dim_keys", type=int, default=None)
66 parser.add_argument("--dim_hidden", type=int, default=None)
68 parser.add_argument("--nb_heads", type=int, default=None)
70 parser.add_argument("--nb_blocks", type=int, default=None)
72 parser.add_argument("--dropout", type=float, default=0.1)
74 ########################################
76 parser.add_argument("--deterministic_synthesis", action="store_true", default=False)
78 parser.add_argument("--problem", type=str, default="grids")
80 parser.add_argument("--nb_threads", type=int, default=-1)
82 parser.add_argument("--nb_gpts", type=int, default=5)
84 parser.add_argument("--min_to_validate", type=int, default=None)
86 parser.add_argument("--max_to_validate", type=int, default=None)
88 parser.add_argument("--accuracy_to_make_c_quizzes", type=float, default=0.975)
90 parser.add_argument("--generation_temperature", type=float, default=2.0)
92 parser.add_argument("--deterministic_validation", action="store_true", default=False)
94 parser.add_argument("--bidirectional_validation", action="store_true", default=False)
96 parser.add_argument("--dirty_debug", action="store_true", default=False)
98 ######################################################################
100 parser.add_argument("--sky_height", type=int, default=6)
102 parser.add_argument("--sky_width", type=int, default=8)
104 parser.add_argument("--sky_nb_birds", type=int, default=3)
106 parser.add_argument("--sky_nb_iterations", type=int, default=2)
108 parser.add_argument("--sky_speed", type=int, default=3)
110 ######################################################################
112 args = parser.parse_args()
114 if args.min_to_validate is None:
115 args.min_to_validate = args.nb_gpts - 1
117 if args.max_to_validate is None:
118 args.max_to_validate = args.nb_gpts - 1
120 if args.result_dir is None:
121 args.result_dir = f"results_culture"
123 ######################################################################
128 "nb_train_samples": 100000,
129 "nb_test_samples": 10000,
132 for k, v in default_args.items():
133 if getattr(args, k) is None:
136 ######################################################################
138 default_model_args = {
176 if args.model in default_model_args:
177 for k, v in default_model_args[args.model].items():
178 if getattr(args, k) is None:
181 raise ValueError(f"Unknown model {args.model}")
183 ######################################################################
186 os.mkdir(args.result_dir)
187 except FileExistsError:
188 print(f"result directory {args.result_dir} already exists")
191 log_file = open(os.path.join(args.result_dir, args.log_filename), "a")
194 # torch.backends.cudnn.deterministic = True
195 # torch.backends.cudnn.benchmark = False
196 # torch.use_deterministic_algorithms(True)
197 torch.manual_seed(args.seed)
198 if torch.cuda.is_available():
199 torch.cuda.manual_seed_all(args.seed)
201 ######################################################################
205 t = time.strftime("%Y%m%d-%H:%M:%S ", time.localtime())
207 if log_file is not None:
208 log_file.write(t + s + "\n")
215 log_string(f"argv {' '.join(sys.argv)}")
218 log_string(f"args.{n} {getattr(args, n)}")
221 ######################################################################
224 args.nb_train_samples = 2500
225 args.nb_test_samples = 100
227 if args.physical_batch_size is None:
228 args.physical_batch_size = args.batch_size
230 assert args.batch_size % args.physical_batch_size == 0
232 assert args.nb_train_samples % args.batch_size == 0
233 assert args.nb_test_samples % args.batch_size == 0
235 if args.problem == "sky":
237 height=args.sky_height,
238 width=args.sky_width,
239 nb_birds=args.sky_nb_birds,
240 nb_iterations=args.sky_nb_iterations,
241 speed=args.sky_speed,
242 max_nb_cached_chunks=args.nb_train_samples // 100,
244 nb_threads=args.nb_threads,
246 back_accuracy = False
247 elif args.problem == "grids":
248 problem = grids.Grids(
249 max_nb_cached_chunks=args.nb_train_samples // 100,
251 nb_threads=args.nb_threads,
257 quiz_machine = quiz_machine.QuizMachine(
259 nb_train_samples=args.nb_train_samples,
260 nb_test_samples=args.nb_test_samples,
261 back_accuracy=back_accuracy,
262 batch_size=args.physical_batch_size,
263 result_dir=args.result_dir,
268 ######################################################################
270 log_string(f"device {device}")
272 vocabulary_size = quiz_machine.vocabulary_size()
274 log_string(f"vocabulary_size {vocabulary_size}")
276 ######################################################################
278 # Compute the entropy of the training tokens
281 for input in quiz_machine.batches(split="train", desc="train-entropy"):
282 token_count += F.one_hot(input, num_classes=quiz_machine.vocabulary_size()).sum(
285 token_probas = token_count / token_count.sum()
286 entropy = -torch.xlogy(token_probas, token_probas).sum()
287 train_set_perplexity = math.exp(entropy)
289 ######################################################################
290 # A bit of paranoia never hurts
292 if args.max_percents_of_test_in_train >= 0:
294 def subsets_as_tuples(batches, cs):
296 for batch in batches:
298 s.add(tuple([v.item() for v in x]))
304 nb_test, nb_in_train = 0, 0
305 for test_subset in subsets_as_tuples(
306 quiz_machine.batches(split="test", desc="test-check"), 25000
309 for train_subset in subsets_as_tuples(
310 quiz_machine.batches(split="train", desc="train-check"), 25000
312 in_train.update(test_subset.intersection(train_subset))
313 nb_in_train += len(in_train)
314 nb_test += len(test_subset)
317 f"data_check {nb_in_train*100/nb_test:.02f}% ({nb_in_train}/{nb_test}) of test samples are in the train set"
321 nb_in_train <= args.max_percents_of_test_in_train * nb_test / 100
322 ), f"More than {args.max_percents_of_test_in_train}% of test samples are in the train set"
324 ##############################
327 def one_epoch(model, quiz_machine):
328 optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)
332 nb_train_samples, acc_train_loss = 0, 0.0
334 for input in quiz_machine.batches(split="train"):
335 input = input.to(device)
337 if nb_train_samples % args.batch_size == 0:
338 optimizer.zero_grad()
340 output = model(mygpt.BracketedSequence(input)).x
341 loss = F.cross_entropy(output.transpose(1, 2), input)
342 acc_train_loss += loss.item() * input.size(0)
344 nb_train_samples += input.size(0)
348 if nb_train_samples % args.batch_size == 0:
351 train_perplexity = math.exp(min(100, acc_train_loss / nb_train_samples))
353 log_string(f"train_perplexity {n_epoch} {train_perplexity}")
356 ######################################################################
359 def run_tests(model, quiz_machine, deterministic_synthesis):
360 with torch.autograd.no_grad():
363 nb_test_samples, acc_test_loss = 0, 0.0
364 nb_samples_accumulated = 0
366 for input in quiz_machine.batches(split="test"):
367 input = input.to(device)
369 bs = model(mygpt.BracketedSequence(input))
372 loss = F.cross_entropy(output.transpose(1, 2), input)
374 acc_test_loss += loss.item() * input.size(0)
376 nb_test_samples += input.size(0)
378 test_perplexity = math.exp(min(100, acc_test_loss / nb_test_samples))
380 log_string(f"test_perplexity {n_epoch} {test_perplexity}")
382 model.main_test_accuracy = quiz_machine.produce_results(
385 result_dir=args.result_dir,
386 deterministic_synthesis=deterministic_synthesis,
390 ######################################################################
393 def standard_validity(logproba):
394 l = logproba.sort(dim=-1).values
395 return (l[:, 0] < math.log(0.5)) & (l[:, 1] > math.log(0.99))
396 # warnings.warn("TEST!!!", RuntimeWarning)
398 # return (l[:, 0] < math.log(0.99))
401 def valid_c_quizzes(recorded, criteria):
402 result = [q[criteria(lp)] for q, lp in recorded]
403 return torch.cat(result, dim=0) if len(result) > 0 else torch.tensor([])
406 ######################################################################
409 def create_c_quizzes(
415 quizzes_and_logproba_records = []
417 nb_to_create = nb_for_train + nb_for_test
419 # ------------------------------------------------------------
421 file_name = os.path.join(args.result_dir, f"culture_c_quiz_{n_epoch:04d}_logp.dat")
423 with open(file_name, "w") as logp_file:
425 valid_c_quizzes(quizzes_and_logproba_records, standard_validity).size(0)
428 # Select a model at random to generate the new quizzes
430 model_for_generation = models[torch.randint(len(models), (1,))]
432 c_quizzes = quiz_machine.generate_quizzes(
434 model_for_generation=model_for_generation,
435 temperature=args.generation_temperature,
438 c_quizzes = c_quizzes[quiz_machine.non_trivial(c_quizzes)]
440 if c_quizzes.size(0) > 0:
441 logproba = quiz_machine.logproba_solution(models, c_quizzes)
443 s = " ".join([str(x.item()) for x in l])
444 logp_file.write(s + "\n")
445 quizzes_and_logproba_records.append((c_quizzes, logproba))
447 nb_validated = valid_c_quizzes(
448 quizzes_and_logproba_records, standard_validity
452 f"keep c_quizzes model {model_for_generation.id} nb_accumulated {nb_validated} / {nb_to_create}"
455 # store the new c_quizzes which have been validated
457 new_c_quizzes = valid_c_quizzes(quizzes_and_logproba_records, standard_validity)
459 quiz_machine.reverse_random_half_in_place(new_c_quizzes)
461 quiz_machine.store_c_quizzes(new_c_quizzes[:nb_for_train], for_train=True)
462 quiz_machine.store_c_quizzes(new_c_quizzes[nb_for_train:], for_train=False)
464 # save a bunch of images to investigate what quizzes with a
465 # certain nb of correct predictions look like
467 q = new_c_quizzes[:72]
470 quiz_machine.save_quizzes(args.result_dir, f"culture_c_quiz_{n_epoch:04d}", q)
473 ######################################################################
476 def create_c_quizzes_(
482 quizzes_and_nb_correct_records = []
484 nb_to_create = nb_for_train + nb_for_test
486 # ------------------------------------------------------------
488 standard_validity = lambda nb_correct: (nb_correct >= args.min_to_validate) & (
489 nb_correct <= args.max_to_validate
492 file_name = os.path.join(args.result_dir, f"culture_c_quiz_{n_epoch:04d}_logp.dat")
494 with open(file_name, "w") as logp_file:
496 valid_c_quizzes(quizzes_and_nb_correct_records, standard_validity).size(0)
499 # Select a model at random to generate the new quizzes
501 model_for_generation = models[torch.randint(len(models), (1,))]
503 c_quizzes = quiz_machine.generate_quizzes(
505 model_for_generation=model_for_generation,
506 temperature=args.generation_temperature,
509 # if args.prediction_correctness:
512 # logproba = quiz_machine.new(quiz_machine.size(0), len(models))
513 # for q,l in zip(quizzes.split(args.batch_size), logits.split(args.batch_size)):
514 # for model in models:
515 # l[...] = F.cross_entropy(model(q))
517 c_quizzes = c_quizzes[quiz_machine.non_trivial(c_quizzes)]
519 if c_quizzes.size(0) > 0:
520 nb_correct, seq_logproba = quiz_machine.compute_correctness(
523 bidirectional_validation=args.bidirectional_validation,
524 deterministic_validation=args.deterministic_validation,
527 for n, l in zip(nb_correct, seq_logproba):
528 s = " ".join([str(x.item()) for x in l])
529 logp_file.write(f"{n} {s}\n")
532 nb_correct = torch.randint(
533 len(models) + 1, nb_correct.size(), device=c_quizzes.device
536 quizzes_and_nb_correct_records.append((c_quizzes, nb_correct))
538 nv = F.one_hot(nb_correct, num_classes=len(models) + 1).sum(0)
539 nv = " ".join([str(x.item()) for x in nv])
541 nb_validated = valid_c_quizzes(
542 quizzes_and_nb_correct_records, standard_validity
546 f"keep c_quizzes model {model_for_generation.id} kept {nv} nb_accumulated {nb_validated} / {nb_to_create}"
549 # store the new c_quizzes which have been validated
551 new_c_quizzes = valid_c_quizzes(quizzes_and_nb_correct_records, standard_validity)
553 quiz_machine.reverse_random_half_in_place(new_c_quizzes)
555 quiz_machine.store_c_quizzes(new_c_quizzes[:nb_for_train], for_train=True)
556 quiz_machine.store_c_quizzes(new_c_quizzes[nb_for_train:], for_train=False)
558 # save a bunch of images to investigate what quizzes with a
559 # certain nb of correct predictions look like
561 for n in range(len(models) + 1):
564 if n >= args.min_to_validate and n <= args.max_to_validate
569 quizzes_and_nb_correct_records, criteria=lambda nb_correct: nb_correct == n
572 quiz_machine.reverse_random_half_in_place(q)
575 quiz_machine.save_quizzes(
576 args.result_dir, f"culture_c_quiz_{n_epoch:04d}_N{n}{s}", q
580 ######################################################################
584 for k in range(args.nb_gpts):
586 vocabulary_size=vocabulary_size,
587 dim_model=args.dim_model,
588 dim_keys=args.dim_keys,
589 dim_hidden=args.dim_hidden,
590 nb_heads=args.nb_heads,
591 nb_blocks=args.nb_blocks,
593 dropout=args.dropout,
596 model.main_test_accuracy = 0.0
602 nb_parameters = sum(p.numel() for p in models[0].parameters())
603 log_string(f"nb_parameters {nb_parameters} ({int(nb_parameters/1e6)}M)")
605 ######################################################################
607 nb_new_c_quizzes_for_train = args.nb_train_samples // 50
608 nb_new_c_quizzes_for_test = args.nb_test_samples // 50
611 f"nb_new_c_quizzes_for_train {nb_new_c_quizzes_for_train} nb_new_c_quizzes_for_test {nb_new_c_quizzes_for_test}"
614 ######################################################################
617 args.accuracy_to_make_c_quizzes = 0.0
619 nb_new_c_quizzes_for_train = 100
620 nb_new_c_quizzes_for_test = 10
622 ######################################################################
624 for n_epoch in range(args.nb_epochs):
625 log_string(f"--- epoch {n_epoch} ----------------------------------------")
627 cta = " ".join([f"{float(m.main_test_accuracy):.04f}" for m in models])
628 log_string(f"current_test_accuracies {cta}")
630 ##################################################
631 # Select, improve, and eval the worst model
633 weakest_model = min(models, key=lambda m: float(m.main_test_accuracy))
636 f"training model {weakest_model.id} main_test_accuracy {weakest_model.main_test_accuracy}"
639 one_epoch(weakest_model, quiz_machine)
642 f"train_set_composition w_quizzes {quiz_machine.nb_batch_w_quizzes} c_quizzes {quiz_machine.nb_batch_c_quizzes}"
645 run_tests(weakest_model, quiz_machine, deterministic_synthesis=False)
648 f"test_set_composition w_quizzes {quiz_machine.nb_batch_w_quizzes} c_quizzes {quiz_machine.nb_batch_c_quizzes}"
651 ##################################################
652 # Replace a fraction of the w_quizzes with fresh ones
655 f"cache_w_quizzes contains {quiz_machine.problem.nb_cached_quizzes()} quizzes"
657 quiz_machine.renew_w_quizzes(args.nb_train_samples // args.nb_gpts)
659 ##################################################
660 # If all the models are good enough, generate new quizzes and
661 # re-compute the test errors
663 if min([m.main_test_accuracy for m in models]) >= args.accuracy_to_make_c_quizzes:
667 nb_for_train=nb_new_c_quizzes_for_train,
668 nb_for_test=nb_new_c_quizzes_for_test,
672 run_tests(model, quiz_machine, deterministic_synthesis=False)
675 ######################################################################