Moved the input/output shift in the forward of the model.
[mygpt.git] / main.py
diff --git a/main.py b/main.py
index 3bf6b52..c810eef 100755 (executable)
--- a/main.py
+++ b/main.py
@@ -31,7 +31,7 @@ parser.add_argument('--seed',
                     type = int, default = 0)
 
 parser.add_argument('--nb_epochs',
-                    type = int, default = 100)
+                    type = int, default = -1)
 
 parser.add_argument('--batch_size',
                     type = int, default = 25)
@@ -69,12 +69,24 @@ parser.add_argument('--dropout',
 parser.add_argument('--synthesis_sampling',
                     action='store_true', default = True)
 
+parser.add_argument('--no_checkpoint',
+                    action='store_true', default = False)
+
 parser.add_argument('--checkpoint_name',
                     type = str, default = 'checkpoint.pth')
 
+##############################
+# picoclvr options
+
 parser.add_argument('--picoclvr_many_colors',
                     action='store_true', default = False)
 
+parser.add_argument('--picoclvr_height',
+                    type = int, default = 12)
+
+parser.add_argument('--picoclvr_width',
+                    type = int, default = 16)
+
 ######################################################################
 
 args = parser.parse_args()
@@ -101,6 +113,25 @@ for n in vars(args):
 
 ######################################################################
 
+def produce_results(
+        self,
+        model, nb_samples, nb_tokens_to_generate, starting_input = None,
+        device = 'cpu'
+):
+    results = torch.zeros(nb_samples, nb_tokens_to_generate, dtype = torch.int64, device = device)
+    for input in results.split(self.batch_size):
+        for s in tqdm.tqdm(range(input.size(1) - 1), desc = 'synth'):
+            output = model(input)
+            logits = output[:, s]
+            if args.synthesis_sampling:
+                dist = torch.distributions.categorical.Categorical(logits = logits)
+                t = dist.sample()
+            else:
+                t = logits.argmax(1)
+            input[:, s + 1] = t
+
+######################################################################
+
 class Task:
     def batches(self, split = 'train'):
         pass
@@ -118,37 +149,43 @@ import picoclvr
 class TaskPicoCLVR(Task):
 
     def __init__(self, batch_size,
-                 height = 6, width = 8, many_colors = False,
+                 height, width, many_colors = False,
                  device = torch.device('cpu')):
 
+        def generate_descr(nb):
+            descr = picoclvr.generate(
+                nb,
+                height = self.height, width = self.width,
+                many_colors = many_colors
+            )
+
+            descr = [ s.strip().split(' ') for s in descr ]
+            l = max([ len(s) for s in descr ])
+            descr = [ s + [ '<unk>' ] * (l - len(s)) for s in descr ]
+
+            return descr
+
+        self.height = height
+        self.width = width
         self.batch_size = batch_size
         self.device = device
         nb = args.data_size if args.data_size > 0 else 250000
 
-        descr = picoclvr.generate(
-            nb,
-            height = height, width = width,
-            many_colors = many_colors
-        )
-
-        # self.test_descr = descr[:nb // 5]
-        # self.train_descr = descr[nb // 5:]
-
-        descr = [ s.strip().split(' ') for s in descr ]
-        l = max([ len(s) for s in descr ])
-        descr = [ s + [ '<unk>' ] * (l - len(s)) for s in descr ]
+        self.train_descr = generate_descr((nb * 4) // 5)
+        self.test_descr = generate_descr((nb * 1) // 5)
 
+        # Build the tokenizer
         tokens = set()
-        for s in descr:
-            for t in s: tokens.add(t)
+        for d in [ self.train_descr, self.test_descr ]:
+            for s in d:
+                for t in s: tokens.add(t)
         self.token2id = dict([ (t, n) for n, t in enumerate(tokens) ])
         self.id2token = dict([ (n, t) for n, t in enumerate(tokens) ])
 
-        t = [ [ self.token2id[u] for u in s ] for s in descr ]
-        data_input = torch.tensor(t, device = self.device)
-
-        self.test_input = data_input[:nb // 5]
-        self.train_input = data_input[nb // 5:]
+        t = [ [ self.token2id[u] for u in s ] for s in self.train_descr ]
+        self.train_input = torch.tensor(t, device = self.device)
+        t = [ [ self.token2id[u] for u in s ] for s in self.test_descr ]
+        self.test_input = torch.tensor(t, device = self.device)
 
     def batches(self, split = 'train'):
         assert split in { 'train', 'test' }
@@ -180,7 +217,9 @@ class TaskPicoCLVR(Task):
 
         return ' '.join(t_primer + t_generated)
 
-    def produce_results(self, n_epoch, model, nb_tokens = 50):
+    def produce_results(self, n_epoch, model, nb_tokens = None):
+        if nb_tokens is None:
+            nb_tokens = self.height * self.width + 3
         descr = [ ]
         nb_per_primer = 8
 
@@ -194,14 +233,22 @@ class TaskPicoCLVR(Task):
             for k in range(nb_per_primer):
                 descr.append(self.generate(primer, model, nb_tokens))
 
-        img = [ picoclvr.descr2img(d) for d in descr ]
+        img = [ picoclvr.descr2img(d, height = self.height, width = self.width) for d in descr ]
         img = torch.cat(img, 0)
-        file_name = f'result_picoclvr_{n_epoch:04d}.png'
-        torchvision.utils.save_image(img / 255.,
-                                     file_name, nrow = nb_per_primer, pad_value = 0.8)
-        log_string(f'wrote {file_name}')
+        image_name = f'result_picoclvr_{n_epoch:04d}.png'
+        torchvision.utils.save_image(
+            img / 255.,
+            image_name, nrow = nb_per_primer, pad_value = 0.8
+        )
+        log_string(f'wrote {image_name}')
+
+        nb_missing = sum( [
+            x[2] for x in picoclvr.nb_missing_properties(
+                descr,
+                height = self.height, width = self.width
+            )
+        ] )
 
-        nb_missing = sum( [ x[2] for x in picoclvr.nb_missing_properties(descr) ] )
         log_string(f'nb_missing {nb_missing / len(descr):.02f}')
 
 ######################################################################
@@ -328,7 +375,7 @@ class TaskMNIST(Task):
     def produce_results(self, n_epoch, model, nb_samples = 64):
         results = torch.zeros(nb_samples, 28 * 28, dtype = torch.int64, device = self.device)
         for input in results.split(self.batch_size):
-            for s in tqdm.tqdm(range(input.size(1) - 1), desc = 'synth'):
+            for s in tqdm.tqdm(range(input.size(1)), desc = 'synth'):
                 output = model(input)
                 logits = output[:, s]
                 if args.synthesis_sampling:
@@ -336,7 +383,7 @@ class TaskMNIST(Task):
                     t = dist.sample()
                 else:
                     t = logits.argmax(1)
-                input[:, s + 1] = t
+                input[:, s] = t
 
         image_name = f'result_mnist_{n_epoch:04d}.png'
         torchvision.utils.save_image(1 - results.reshape(-1, 1, 28, 28) / 255.,
@@ -345,27 +392,21 @@ class TaskMNIST(Task):
 
 ######################################################################
 
-def check_causality(model):
-    #m = model[1:]
-    input = torch.rand(1, 5, dim_model).requires_grad_()
-    output = m(input)
-    a = torch.zeros(output.size(1), input.size(1))
-    for k in range(output.size(1)):
-        for d in range(output.size(2)):
-            g, = torch.autograd.grad(output[0, k, d], input, retain_graph = True)
-            a[k] += g.squeeze(0).pow(2).sum(1)
-    print(a)
-
-######################################################################
-
 log_string(f'device {device}')
 
 if args.data == 'wiki103':
+    nb_epochs_default = 10
     task = TaskWiki103(batch_size = args.batch_size, device = device)
 elif args.data == 'mnist':
+    nb_epochs_default = 25
     task = TaskMNIST(batch_size = args.batch_size, device = device)
 elif args.data == 'picoclvr':
-    task = TaskPicoCLVR(batch_size = args.batch_size, many_colors = args.picoclvr_many_colors, device = device)
+    nb_epochs_default = 10
+    task = TaskPicoCLVR(batch_size = args.batch_size,
+                        height = args.picoclvr_height,
+                        width = args.picoclvr_width,
+                        many_colors = args.picoclvr_many_colors,
+                        device = device)
 else:
     raise ValueError(f'Unknown dataset {args.data}.')
 
@@ -401,23 +442,37 @@ else:
 
 nb_epochs_finished = 0
 
-try:
-    checkpoint = torch.load(args.checkpoint_name, map_location = device)
-    nb_epochs_finished = checkpoint['nb_epochs_finished']
-    model.load_state_dict(checkpoint['model_state'])
-    optimizer.load_state_dict(checkpoint['optimizer_state'])
-    print(f'Checkpoint loaded with {nb_epochs_finished} epochs finished.')
+if args.no_checkpoint:
+    log_string(f'Not trying to load checkpoint.')
 
-except FileNotFoundError:
-    print('Starting from scratch.')
+else:
+    try:
+        checkpoint = torch.load(args.checkpoint_name, map_location = device)
+        nb_epochs_finished = checkpoint['nb_epochs_finished']
+        model.load_state_dict(checkpoint['model_state'])
+        optimizer.load_state_dict(checkpoint['optimizer_state'])
+        log_string(f'Checkpoint loaded with {nb_epochs_finished} epochs finished.')
+
+    except FileNotFoundError:
+        log_string('Starting from scratch.')
 
-except:
-    print('Error when loading the checkpoint.')
-    exit(1)
+    except:
+        log_string('Error when loading the checkpoint.')
+        exit(1)
 
 ######################################################################
 
-for k in range(nb_epochs_finished, args.nb_epochs):
+nb_epochs = args.nb_epochs if args.nb_epochs > 0 else nb_epochs_default
+
+token_count = 0
+for input in task.batches(split = 'train'):
+    token_count += F.one_hot(input, num_classes = task.vocabulary_size()).sum((0, 1))
+token_probas = token_count / token_count.sum()
+h = -torch.xlogy(token_probas, token_probas).sum()
+train_set_perplexity = math.exp(h)
+log_string(f'Train set perplexity {train_set_perplexity}')
+
+for k in range(nb_epochs_finished, nb_epochs):
 
     model.train()
 
@@ -426,7 +481,7 @@ for k in range(nb_epochs_finished, args.nb_epochs):
     for input in task.batches(split = 'train'):
         input = input.to(device)
         output = model(input)
-        loss = F.cross_entropy(output[:, :-1].transpose(1, 2), input[:, 1:])
+        loss = F.cross_entropy(output.transpose(1, 2), input)
         acc_train_loss += loss.item() * input.size(0)
         nb_train_samples += input.size(0)
 
@@ -450,7 +505,7 @@ for k in range(nb_epochs_finished, args.nb_epochs):
         train_perplexity = math.exp(min(100, acc_train_loss/nb_train_samples))
         test_perplexity = math.exp(min(100, acc_test_loss/nb_test_samples))
 
-        log_string(f'perplexity {k+1} train {train_perplexity} test {test_perplexity}')
+        log_string(f'perplexity {k} train {train_perplexity} test {test_perplexity}')
 
         task.produce_results(k, model)