X-Git-Url: https://fleuret.org/cgi-bin/gitweb/gitweb.cgi?a=blobdiff_plain;f=main.py;h=35bf02c0123815b31d479df63f935839c7523b33;hb=02b0a7bb770f07f2e91f1c77b899815516087b6a;hp=c1f4dc7f0540e2dcbbdf8c71b9a3c1ca29db457b;hpb=f91736e6e56152746b3c44342748b70ad1c89888;p=picoclvr.git diff --git a/main.py b/main.py index c1f4dc7..35bf02c 100755 --- a/main.py +++ b/main.py @@ -32,7 +32,10 @@ parser = argparse.ArgumentParser( ) parser.add_argument( - "--task", type=str, default="picoclvr", help="picoclvr, mnist, maze, snake, stack" + "--task", + type=str, + default="picoclvr", + help="picoclvr, mnist, maze, snake, stack, expr", ) parser.add_argument("--log_filename", type=str, default="train.log", help=" ") @@ -117,6 +120,13 @@ parser.add_argument("--stack_nb_digits", type=int, default=3) parser.add_argument("--stack_fraction_values_for_train", type=float, default=None) +############################## +# Expr options + +parser.add_argument("--expr_nb_variables", type=int, default=5) + +parser.add_argument("--expr_sequence_length", type=int, default=30) + ###################################################################### args = parser.parse_args() @@ -159,6 +169,12 @@ default_args = { "nb_train_samples": 100000, "nb_test_samples": 1000, }, + "expr": { + "nb_epochs": 50, + "batch_size": 25, + "nb_train_samples": 250000, + "nb_test_samples": 10000, + }, } if args.task in default_args: @@ -217,9 +233,8 @@ def masked_inplace_autoregression( progress_bar_desc="autoregression", device=torch.device("cpu"), ): - # p = logits.softmax(1) - # entropy[:,s]= p.xlogy(p).sum(1) / math.log(2) batches = zip(input.split(batch_size), ar_mask.split(batch_size)) + if progress_bar_desc is not None: batches = tqdm.tqdm( batches, @@ -227,6 +242,7 @@ def masked_inplace_autoregression( desc=progress_bar_desc, total=input.size(0) // batch_size, ) + for input, ar_mask in batches: i = (ar_mask.sum(0) > 0).nonzero() if i.min() > 0: @@ -922,7 +938,7 @@ class TaskStack(Task): i = torch.logical_and(self.test_input % 2 == 1, self.test_input < 2 * nb_stacks) counts = self.test_stack_counts.flatten()[i.flatten()] counts = F.one_hot(counts).sum(0) - log_string(f"pop_stack_counts {counts}") + log_string(f"test_pop_stack_counts {counts}") self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1 @@ -995,6 +1011,142 @@ class TaskStack(Task): ###################################################################### +import expr + + +class TaskExpr(Task): + def __init__( + self, + nb_train_samples, + nb_test_samples, + nb_variables, + sequence_length, + batch_size, + device=torch.device("cpu"), + ): + self.batch_size = batch_size + self.device = device + + train_sequences = expr.generate_sequences( + nb_train_samples, + nb_variables=nb_variables, + length=2 * sequence_length, + randomize_length=True, + ) + test_sequences = expr.generate_sequences( + nb_test_samples, + nb_variables=nb_variables, + length=sequence_length, + ) + self.char2id = dict( + [ + (c, n) + for n, c in enumerate( + set("#" + "".join(train_sequences + test_sequences)) + ) + ] + ) + self.id2char = dict([(n, c) for c, n in self.char2id.items()]) + + self.filler, self.space = self.char2id["#"], self.char2id[" "] + + len_max = max([len(x) for x in train_sequences]) + self.train_input = torch.cat( + [ + torch.tensor( + [ + [self.char2id[c] for c in s + "#" * (len_max - len(s))] + for s in train_sequences + ] + ) + ], + 0, + ).to(device) + + len_max = max([len(x) for x in test_sequences]) + self.test_input = torch.cat( + [ + torch.tensor( + [ + [self.char2id[c] for c in s + "#" * (len_max - len(s))] + for s in test_sequences + ] + ) + ], + 0, + ).to(device) + + self.nb_codes = max(self.train_input.max(), self.test_input.max()) + 1 + + def batches(self, split="train", nb_to_use=-1, desc=None): + assert split in {"train", "test"} + input = self.train_input if split == "train" else self.test_input + if nb_to_use > 0: + input = input[:nb_to_use] + if desc is None: + desc = f"epoch-{split}" + for batch in tqdm.tqdm( + input.split(self.batch_size), dynamic_ncols=True, desc=desc + ): + if split == "train": + last = (batch != self.filler).max(0).values.nonzero().max() + 1 + batch = batch[:, :last] + yield batch + + def vocabulary_size(self): + return self.nb_codes + + def seq2str(self, s): + return "".join([self.id2char[k.item()] for k in s]) + + def produce_results(self, n_epoch, model): + with torch.autograd.no_grad(): + t = model.training + model.eval() + + def compute_nb_correct(input): + result = input.clone() + ar_mask = (result == self.space).long().cumsum(dim=1).clamp(max=1) + result = (1 - ar_mask) * result + ar_mask * self.filler + masked_inplace_autoregression( + model, self.batch_size, result, ar_mask, device=self.device + ) + + nb_total = input.size(0) + nb_correct = (input == result).long().min(1).values.sum() + + return nb_total, nb_correct + + test_nb_total, test_nb_correct = compute_nb_correct(self.test_input[:1000]) + + log_string( + 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}%" + ) + + ############################################################## + # Log a few generated sequences + input = self.test_input[:10] + result = input.clone() + ar_mask = (result == self.space).long().cumsum(dim=1).clamp(max=1) + result = (1 - ar_mask) * result + ar_mask * self.filler + for n in range(result.size(0)): + log_string(f"test_before {self.seq2str(result[n])}") + masked_inplace_autoregression( + model, self.batch_size, result, ar_mask, device=self.device + ) + correct = (1 - ar_mask) * self.space + ar_mask * input + for n in range(result.size(0)): + comment = "GOOD" if (result[n] - input[n]).abs().max() == 0 else "" + log_string(f"test_after {self.seq2str(result[n])} {comment}") + log_string(f"correct {self.seq2str(correct[n])}") + ############################################################## + + model.train(t) + + +###################################################################### + + def picoclvr_pruner_horizontal_green(p): return not ("green" in p and ("left" in p or "right" in p)) @@ -1068,6 +1220,16 @@ elif args.task == "stack": device=device, ) +elif args.task == "expr": + task = TaskExpr( + nb_train_samples=args.nb_train_samples, + nb_test_samples=args.nb_test_samples, + nb_variables=args.expr_nb_variables, + sequence_length=args.expr_sequence_length, + batch_size=args.batch_size, + device=device, + ) + else: raise ValueError(f"Unknown task {args.task}")