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 # torch.backends.cuda.matmul.allow_tf23
9 # torch.autocast(torch.bfloat16)
11 import math, sys, argparse, time, tqdm, itertools, os
13 import torch, torchvision
15 from torch.nn import functional as F
17 import mygpt, tensorstack
19 ######################################################################
21 if torch.cuda.is_available():
22 device = torch.device("cuda")
23 torch.backends.cuda.matmul.allow_tf32 = True
25 device = torch.device("cpu")
27 ######################################################################
29 parser = argparse.ArgumentParser(description="A maze shortest path solving with a GPT.")
31 parser.add_argument("--log_filename", type=str, default="train.log")
33 parser.add_argument("--result_dir", type=str, default="results_default")
35 parser.add_argument("--seed", type=int, default=0)
37 parser.add_argument("--nb_epochs", type=int, default=25)
39 parser.add_argument("--nb_train_samples", type=int, default=200000)
41 parser.add_argument("--nb_test_samples", type=int, default=50000)
43 parser.add_argument("--batch_size", type=int, default=25)
45 parser.add_argument("--optim", type=str, default="adam")
47 parser.add_argument("--learning_rate", type=float, default=1e-3)
50 "--learning_rate_schedule", type=str, default="10: 2e-4,20: 4e-5,30: 8e-6"
53 parser.add_argument("--dim_model", type=int, default=512)
55 parser.add_argument("--dim_keys", type=int, default=64)
57 parser.add_argument("--dim_hidden", type=int, default=2048)
59 parser.add_argument("--nb_heads", type=int, default=8)
61 parser.add_argument("--nb_blocks", type=int, default=12)
63 parser.add_argument("--dropout", type=float, default=0.1)
65 parser.add_argument("--deterministic_synthesis", action="store_true", default=False)
67 parser.add_argument("--random_regression_order", action="store_true", default=False)
69 parser.add_argument("--no_checkpoint", action="store_true", default=False)
71 parser.add_argument("--overwrite_results", action="store_true", default=False)
73 parser.add_argument("--checkpoint_name", type=str, default="checkpoint.pth")
75 ##############################
78 parser.add_argument("--maze_height", type=int, default=13)
80 parser.add_argument("--maze_width", type=int, default=21)
82 parser.add_argument("--maze_nb_walls", type=int, default=15)
84 ##############################
87 parser.add_argument("--oneshot", action="store_true", default=False)
89 parser.add_argument("--oneshot_input", type=str, default="head")
91 parser.add_argument("--oneshot_output", type=str, default="trace")
93 ######################################################################
95 args = parser.parse_args()
98 os.mkdir(args.result_dir)
99 except FileExistsError:
100 if not args.overwrite_results:
101 print(f"result directory {args.result_dir} already exists")
104 log_file = open(os.path.join(args.result_dir, args.log_filename), "a")
107 # torch.backends.cudnn.deterministic = True
108 # torch.backends.cudnn.benchmark = False
109 # torch.use_deterministic_algorithms(True)
110 torch.manual_seed(args.seed)
111 if torch.cuda.is_available():
112 torch.cuda.manual_seed_all(args.seed)
114 ######################################################################
118 t = time.strftime("%Y%m%d-%H:%M:%S ", time.localtime())
120 if log_file is not None:
121 log_file.write(t + s + "\n")
129 log_string(f"args.{n} {getattr(args, n)}")
131 ######################################################################
134 def generation_order(x, fixed_len):
135 if args.random_regression_order:
136 order = torch.rand(x.size(), device=x.device)
137 order[:, :fixed_len] = torch.linspace(-2, -1, fixed_len, device=order.device)
138 order = order.sort(1).indices
141 torch.arange(x.size(1), device=x.device).unsqueeze(0).expand(x.size(0), -1)
146 def reorder(x, order, back=False): # x is NxTxD1x...xDk, order is NxT'
147 u = x.reshape(x.size()[:2] + (-1,))
148 order = order.unsqueeze(-1).expand(-1, -1, u.size(-1))
151 v.scatter_(1, order, u)
153 v = u.gather(1, order)
154 v = v.reshape(v.size()[:2] + x.size()[2:])
158 def shuffle(x, fixed_len):
159 order = generation_order(x, fixed_len)
160 return reorder(x, order), order
163 ######################################################################
165 # ar_mask is a Boolean matrix of same shape as input, with 1s on the
166 # tokens that should be generated
169 def masked_inplace_autoregression(model, batch_size, input, ar_mask, order=None):
170 for input, ar_mask in zip(input.split(batch_size), ar_mask.split(batch_size)):
171 i = (ar_mask.sum(0) > 0).nonzero()
173 # Needed to initialize the model's cache
174 model(mygpt.BracketedSequence(input, 0, i.min()), order=order)
175 for s in range(i.min(), i.max() + 1):
176 output = model(mygpt.BracketedSequence(input, s, 1), order=order).x
177 logits = output[:, s]
178 if args.deterministic_synthesis:
179 t_next = logits.argmax(1)
181 dist = torch.distributions.categorical.Categorical(logits=logits)
182 t_next = dist.sample()
183 input[:, s] = ar_mask[:, s] * t_next + (1 - ar_mask[:, s]) * input[:, s]
186 ######################################################################
189 def compute_perplexity(model, split="train"):
190 with torch.autograd.no_grad():
194 nb_samples, acc_loss = 0, 0.0
196 for input in task.batches(split=split):
197 input = input.to(device)
198 input, order = shuffle(input, task.height * task.width)
199 output = model(mygpt.BracketedSequence(input), order=order).x
200 loss = F.cross_entropy(output.transpose(1, 2), input)
201 acc_loss += loss.item() * input.size(0)
202 nb_samples += input.size(0)
206 return math.exp(min(100, acc_loss / nb_samples))
209 ######################################################################
212 def oneshot_policy_loss(mazes, output, policies, height, width):
213 masks = (mazes == maze.v_empty).unsqueeze(-1)
214 targets = policies.permute(0, 2, 1) * masks
215 output = output * masks
216 return -(output.log_softmax(-1) * targets).sum() / masks.sum()
219 def oneshot_trace_loss(mazes, output, policies, height, width):
220 masks = mazes == maze.v_empty
221 targets = maze.stationary_densities(
222 mazes.view(-1, height, width), policies.view(-1, 4, height, width)
224 targets = targets * masks
225 output = output.squeeze(-1) * masks
226 return (output - targets).abs().sum() / masks.sum()
229 def oneshot(gpt, task):
233 if args.oneshot_input == "head":
234 dim_in = args.dim_model
235 elif args.oneshot_input == "deep":
236 dim_in = args.dim_model * args.nb_blocks * 2
238 raise ValueError(f"{args.oneshot_input=}")
240 if args.oneshot_output == "policy":
242 compute_loss = oneshot_policy_loss
243 elif args.oneshot_output == "trace":
245 compute_loss = oneshot_trace_loss
247 raise ValueError(f"{args.oneshot_output=}")
249 model = nn.Sequential(
250 nn.Linear(dim_in, args.dim_model),
252 nn.Linear(args.dim_model, args.dim_model),
254 nn.Linear(args.dim_model, dim_out),
257 for n_epoch in range(args.nb_epochs):
258 learning_rate = learning_rate_schedule[n_epoch]
259 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
261 acc_train_loss, nb_train_samples = 0, 0
262 for mazes, policies in task.policy_batches(split="train"):
263 x, order = shuffle(mazes, task.height * task.width)
264 x = gpt(mygpt.BracketedSequence(x), mode=args.oneshot_input, order=order).x
265 output_gpt = reorder(x, order, back=True)
266 output = model(output_gpt)
268 loss = compute_loss(mazes, output, policies, task.height, task.width)
269 acc_train_loss += loss.item() * mazes.size(0)
270 nb_train_samples += mazes.size(0)
272 optimizer.zero_grad()
276 acc_test_loss, nb_test_samples = 0, 0
277 for mazes, policies in task.policy_batches(split="test"):
278 x, order = shuffle(mazes, task.height * task.width)
279 x = gpt(mygpt.BracketedSequence(x), mode=args.oneshot_input, order=order).x
280 output_gpt = reorder(x, order, back=True)
281 output = model(output_gpt)
282 loss = compute_loss(mazes, output, policies, task.height, task.width)
283 acc_test_loss += loss.item() * mazes.size(0)
284 nb_test_samples += mazes.size(0)
287 f"diff_ce {n_epoch} train {acc_train_loss/nb_train_samples} test {acc_test_loss/nb_test_samples}"
290 # -------------------
291 mazes = task.test_input[:32, : task.height * task.width]
292 policies = task.test_policies[:32]
293 x, order = shuffle(mazes, task.height * task.width)
294 x = gpt(mygpt.BracketedSequence(x), mode=args.oneshot_input, order=order).x
295 output_gpt = reorder(x, order, back=True)
296 output = model(output_gpt)
297 if args.oneshot_output == "policy":
298 targets = policies.permute(0, 2, 1)
300 (F.one_hot(output.argmax(-1), num_classes=4) * targets).sum(-1) == 0
302 elif args.oneshot_output == "trace":
303 targets = maze.stationary_densities(
304 mazes.view(-1, task.height, task.width),
305 policies.view(-1, 4, task.height, task.width),
309 raise ValueError(f"{args.oneshot_output=}")
311 scores = scores.reshape(-1, task.height, task.width)
312 mazes = mazes.reshape(-1, task.height, task.width)
313 targets = targets.reshape(-1, task.height, task.width)
317 f"oneshot_{args.oneshot_input}_{args.oneshot_output}_{n_epoch:04d}.png",
323 # -------------------
328 ######################################################################
332 def batches(self, split="train", nb_to_use=-1, desc=None):
335 def vocabulary_size(self):
338 def produce_results(self, n_epoch, model):
342 ######################################################################
347 class TaskMaze(Task):
348 def map2seq(self, *m):
349 return torch.cat([x.flatten(1) for x in m], 1)
351 def seq2map(self, s):
352 s = s.reshape(s.size(0), -1, self.height, self.width)
353 return (s[:, k] for k in range(s.size(1)))
363 device=torch.device("cpu"),
365 self.batch_size = batch_size
370 train_mazes, train_paths, train_policies = maze.create_maze_data(
375 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-train"),
377 self.train_input = self.map2seq(train_mazes.to(device), train_paths.to(device))
378 self.train_policies = train_policies.flatten(-2).to(device)
380 test_mazes, test_paths, test_policies = maze.create_maze_data(
385 progress_bar=lambda x: tqdm.tqdm(x, dynamic_ncols=True, desc=f"data-test"),
387 self.test_input = self.map2seq(test_mazes.to(device), test_paths.to(device))
388 self.test_policies = test_policies.flatten(-2).to(device)
390 self.nb_codes = self.train_input.max() + 1
392 def batches(self, split="train", nb_to_use=-1, desc=None):
393 assert split in {"train", "test"}
394 input = self.train_input if split == "train" else self.test_input
396 input = input[:nb_to_use]
398 desc = f"epoch-{split}"
399 for batch in tqdm.tqdm(
400 input.split(self.batch_size), dynamic_ncols=True, desc=desc
404 def policy_batches(self, split="train", nb_to_use=-1, desc=None):
405 assert split in {"train", "test"}
406 input = self.train_input if split == "train" else self.test_input
407 policies = self.train_policies if split == "train" else self.test_policies
408 input = input[:, : self.height * self.width]
409 policies = policies * (input != maze.v_wall)[:, None]
412 input = input[:nb_to_use]
413 policies = policies[:nb_to_use]
416 desc = f"epoch-{split}"
417 for batch in tqdm.tqdm(
418 zip(input.split(self.batch_size), policies.split(self.batch_size)),
424 def vocabulary_size(self):
427 def compute_error(self, model, split="train", nb_to_use=-1):
428 nb_total, nb_correct = 0, 0
429 for input in task.batches(split, nb_to_use):
430 result = input.clone()
431 ar_mask = result.new_zeros(result.size())
432 ar_mask[:, self.height * self.width :] = 1
433 result *= 1 - ar_mask
434 result, order = shuffle(result, self.height * self.width)
435 masked_inplace_autoregression(
436 model, self.batch_size, result, ar_mask, order=order
438 result = reorder(result, order, back=True)
439 mazes, paths = self.seq2map(result)
440 nb_correct += maze.path_correctness(mazes, paths).long().sum()
441 nb_total += mazes.size(0)
443 return nb_total, nb_correct
445 def produce_results(self, n_epoch, model):
446 with torch.autograd.no_grad():
450 train_nb_total, train_nb_correct = self.compute_error(
451 model, "train", nb_to_use=1000
454 f"accuracy_train nb_total {train_nb_total} nb_correct {train_nb_correct} accuracy {(100.0*train_nb_correct)/train_nb_total:.02f}%"
457 test_nb_total, test_nb_correct = self.compute_error(
458 model, "test", nb_to_use=1000
461 f"accuracy_test nb_total {test_nb_total} nb_correct {test_nb_correct} accuracy {(100.0*test_nb_correct)/test_nb_total:.02f}%"
464 input = self.test_input[:32]
465 result = input.clone()
466 ar_mask = result.new_zeros(result.size())
467 ar_mask[:, self.height * self.width :] = 1
468 result *= 1 - ar_mask
469 masked_inplace_autoregression(model, self.batch_size, result, ar_mask)
471 mazes, paths = self.seq2map(input)
472 _, predicted_paths = self.seq2map(result)
474 os.path.join(args.result_dir, f"result_{n_epoch:04d}.png"),
477 predicted_paths=predicted_paths,
478 path_correct=maze.path_correctness(mazes, predicted_paths),
484 ######################################################################
486 log_string(f"device {device}")
490 nb_train_samples=args.nb_train_samples,
491 nb_test_samples=args.nb_test_samples,
492 batch_size=args.batch_size,
493 height=args.maze_height,
494 width=args.maze_width,
495 nb_walls=args.maze_nb_walls,
500 vocabulary_size = task.vocabulary_size()
502 log_string(f"vocabulary_size {vocabulary_size}")
504 ##############################
507 vocabulary_size=vocabulary_size,
508 dim_model=args.dim_model,
509 dim_keys=args.dim_keys,
510 dim_hidden=args.dim_hidden,
511 nb_heads=args.nb_heads,
512 nb_blocks=args.nb_blocks,
514 dropout=args.dropout,
519 nb_parameters = sum(p.numel() for p in model.parameters())
520 log_string(f"nb_parameters {nb_parameters} ({int(nb_parameters/1e6)}M)")
522 ######################################################################
524 nb_epochs_finished = 0
526 if args.no_checkpoint:
527 log_string(f"not trying to load checkpoint.")
531 checkpoint_name = os.path.join(args.result_dir, args.checkpoint_name)
532 checkpoint = torch.load(checkpoint_name)
533 nb_epochs_finished = checkpoint["nb_epochs_finished"]
534 model.load_state_dict(checkpoint["model_state"])
535 torch.set_rng_state(checkpoint["rng_state"])
536 if torch.cuda.is_available():
537 torch.cuda.set_rng_state(checkpoint["cuda_rng_state"])
539 log_string(f"checkpoint loaded with {nb_epochs_finished} epochs finished.")
541 except FileNotFoundError:
542 log_string("starting from scratch.")
545 log_string("error when loading the checkpoint.")
548 ######################################################################
551 for input in task.batches(split="train"):
552 token_count += F.one_hot(input, num_classes=task.vocabulary_size()).sum((0, 1))
553 token_probas = token_count / token_count.sum()
554 entropy = -torch.xlogy(token_probas, token_probas).sum()
555 train_set_perplexity = math.exp(entropy)
557 ##############################
559 if args.learning_rate_schedule == "cos":
560 learning_rate_schedule = {}
561 for n_epoch in range(args.nb_epochs):
562 u = n_epoch / args.nb_epochs * math.pi
563 learning_rate_schedule[n_epoch] = args.learning_rate * 0.5 * (1 + math.cos(u))
568 tuple(x.split(":")) for x in args.learning_rate_schedule.split(",")
572 learning_rate_schedule = {}
573 learning_rate = args.learning_rate
574 for n_epoch in range(args.nb_epochs):
576 learning_rate = u[n_epoch]
577 learning_rate_schedule[n_epoch] = learning_rate
579 log_string(f"learning_rate_schedule {learning_rate_schedule}")
581 ##############################
583 if nb_epochs_finished >= args.nb_epochs:
584 n_epoch = nb_epochs_finished
585 train_perplexity = compute_perplexity(model, split="train")
586 test_perplexity = compute_perplexity(model, split="test")
589 f"perplexity {n_epoch} train_set {train_set_perplexity} train_prediction {train_perplexity} test_prediction {test_perplexity}"
592 task.produce_results(n_epoch, model)
594 ##############################
596 for n_epoch in range(nb_epochs_finished, args.nb_epochs):
597 learning_rate = learning_rate_schedule[n_epoch]
599 log_string(f"learning_rate {learning_rate}")
601 if args.optim == "sgd":
602 optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
603 elif args.optim == "adam":
604 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
605 elif args.optim == "adamw":
606 optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
608 raise ValueError(f"{args.optim=}")
612 nb_train_samples, acc_train_loss = 0, 0.0
614 for input in task.batches(split="train"):
615 input = input.to(device)
616 input, order = shuffle(input, task.height * task.width)
617 output = model(mygpt.BracketedSequence(input), order=order).x
618 loss = F.cross_entropy(output.transpose(1, 2), input)
619 acc_train_loss += loss.item() * input.size(0)
620 nb_train_samples += input.size(0)
622 optimizer.zero_grad()
626 train_perplexity = math.exp(min(100, acc_train_loss / nb_train_samples))
627 test_perplexity = compute_perplexity(model, split="test")
630 f"perplexity {n_epoch} train_set {train_set_perplexity} train_prediction {train_perplexity} test_prediction {test_perplexity}"
633 task.produce_results(n_epoch, model)
636 "nb_epochs_finished": n_epoch + 1,
637 "model_state": model.state_dict(),
638 "rng_state": torch.get_rng_state(),
641 if torch.cuda.is_available():
642 checkpoint["cuda_rng_state"] = torch.cuda.get_rng_state()
644 checkpoint_name = os.path.join(args.result_dir, args.checkpoint_name)
645 torch.save(checkpoint, checkpoint_name)
646 log_string(f"saved checkpoint {checkpoint_name}")
648 ######################################################################
653 ######################################################################