-
Notifications
You must be signed in to change notification settings - Fork 1
/
top_esim_mnli_test.py
192 lines (158 loc) · 6.65 KB
/
top_esim_mnli_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
"""
Train the ESIM model on the preprocessed SNLI dataset.
"""
# Aurelien Coet, 2018.
from utils.utils_top_esim import train, validate, test
from vaa.model import ESIM
from vaa.model_top import TOP
from vaa.data import NLIDataset
from torch.utils.data import DataLoader
import torch.nn as nn
import matplotlib.pyplot as plt
import os
import argparse
import pickle
import sys
import json
import torch
import itertools
import matplotlib
matplotlib.use('Agg')
def main(train_file,
valid_file,
test_file,
embeddings_file,
target_dir,
hidden_size=300,
dropout=0.5,
num_classes=3,
epochs=64,
batch_size=32,
lr=0.0004,
patience=5,
max_grad_norm=10.0,
checkpoint_model0=None,
checkpoint_model1=None,
finetuning=False):
"""
Train the ESIM model on the Quora dataset.
Args:
train_file: A path to some preprocessed data that must be used
to train the model.
valid_file: A path to some preprocessed data that must be used
to validate the model.
embeddings_file: A path to some preprocessed word embeddings that
must be used to initialise the model.
target_dir: The path to a directory where the trained model must
be saved.
hidden_size: The size of the hidden layers in the model. Defaults
to 300.
dropout: The dropout rate to use in the model. Defaults to 0.5.
num_classes: The number of classes in the output of the model.
Defaults to 3.
epochs: The maximum number of epochs for training. Defaults to 64.
batch_size: The size of the batches for training. Defaults to 32.
lr: The learning rate for the optimizer. Defaults to 0.0004.
patience: The patience to use for early stopping. Defaults to 5.
checkpoint: A checkpoint from which to continue training. If None,
training starts from scratch. Defaults to None.
"""
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(20 * "=", " Preparing for training ", 20 * "=")
if not os.path.exists(target_dir):
os.makedirs(target_dir)
print("\t* Loading validation data...")
with open(valid_file, "rb") as pkl:
valid_data = NLIDataset(pickle.load(pkl))
valid_loader = DataLoader(valid_data, shuffle=False, batch_size=batch_size)
print("\t* Loading test data...")
with open(test_file, "rb") as pkl:
test_data = NLIDataset(pickle.load(pkl))
test_loader = DataLoader(test_data, shuffle=False, batch_size=batch_size)
# -------------------- Model definition ------------------- #
print("\t* Building model...")
with open(embeddings_file, "rb") as pkl:
embeddings = torch.tensor(pickle.load(pkl), dtype=torch.float)\
.to(device)
model = []
model0 = ESIM(embeddings.shape[0],
embeddings.shape[1],
hidden_size,
embeddings=embeddings,
dropout=0,
num_classes=num_classes,
device=device).to(device)
model1 = TOP(embeddings.shape[0],
embeddings.shape[1],
hidden_size,
embeddings=embeddings,
dropout=dropout,
num_classes=num_classes,
device=device).to(device)
model.append(model0)
model.append(model1)
# -------------------- Preparation for training ------------------- #
criterion = nn.CrossEntropyLoss()
start_epoch = 1
# Continuing training from a checkpoint if one was given as argument.
if checkpoint_model0:
checkpoint = torch.load(checkpoint_model0)
# start_epoch = checkpoint["epoch"] + 1
print("\t* Training will continue on existing model from epoch {}..."
.format(start_epoch))
model[0].load_state_dict(checkpoint["model"])
if checkpoint_model1:
checkpoint = torch.load(checkpoint_model1)
start_epoch = checkpoint["epoch"] + 1
print("\t* Training will continue on existing model from epoch {}..."
.format(start_epoch))
model[1].load_state_dict(checkpoint["model"])
else:
model_dict = model1.state_dict()
pretrained_dict = checkpoint["model"]
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
model_dict.update(pretrained_dict)
model1.load_state_dict(model_dict)
# Compute loss and accuracy before starting (or resuming) training.
data = test(model, valid_loader, criterion)
data.to_csv('matched_submission.csv', index=False)
data = test(model, test_loader, criterion)
data.to_csv('mismatched_submission.csv', index=False)
if __name__ == "__main__":
default_config = "../../config/testing/mnli_testing.json"
parser = argparse.ArgumentParser(
description="Train the ESIM model on quora")
parser.add_argument("--config",
default=default_config,
help="Path to a json configuration file")
script_dir = os.path.dirname(os.path.realpath(__file__))
script_dir = script_dir + '/scripts/training'
parser.add_argument("--checkpoint_model0",
default=os.path.dirname(os.path.realpath(__file__)) + '/data/checkpoints/MNLI/' +"best.pth.tar",
help="Path to a checkpoint file to resume training")
parser.add_argument("--checkpoint_model1",
default=os.path.dirname(os.path.realpath(__file__)) + '/data/checkpoints/MNLI/' +"esim_model1{}.pth.tar".format(1),
help="Path to a checkpoint file to resume training")
args = parser.parse_args()
if args.config == default_config:
config_path = os.path.join(script_dir, args.config)
else:
config_path = args.config
with open(os.path.normpath(config_path), 'r') as config_file:
config = json.load(config_file)
main(os.path.normpath(os.path.join(script_dir, config["train_data"])),
os.path.normpath(os.path.join(script_dir, config["valid_data"])),
os.path.normpath(os.path.join(script_dir, config["test_data"])),
os.path.normpath(os.path.join(script_dir, config["embeddings"])),
os.path.normpath(os.path.join(script_dir, config["target_dir"])),
config["hidden_size"],
config["dropout"],
config["num_classes"],
config["epochs"],
config["batch_size"]//2,
config["lr"],
config["patience"],
config["max_gradient_norm"],
args.checkpoint_model0,
args.checkpoint_model1,
finetuning=False)