forked from PaddlePaddle/Research
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.py
246 lines (210 loc) · 8.95 KB
/
run.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
from __future__ import absolute_import
import os
import argparse
from datetime import datetime
from mmpms.utils.args import str2bool
from mmpms.utils.args import parse_args
from mmpms.utils.logging import getLogger
from mmpms.utils.misc import tensor2list
from mmpms.inputters.dataset import PostResponseDataset
from mmpms.inputters.dataloader import DataLoader
from mmpms.models.mmpms import MMPMS
from mmpms.modules.generator import BeamSearch
from mmpms.engine import Engine
from mmpms.engine import evaluate
from mmpms.engine import infer
parser = argparse.ArgumentParser()
parser.add_argument("--args_file", type=str, default=None)
parser.add_argument("--use_gpu", type=str2bool, default=True)
parser.add_argument("--model_dir", type=str, default=None)
parser.add_argument("--eval", action="store_true")
parser.add_argument("--infer", action="store_true")
# Data
data_arg = parser.add_argument_group("Data")
data_arg.add_argument("--data_dir", type=str, default="./data/")
data_arg.add_argument("--vocab_file", type=str, default=None)
data_arg.add_argument("--train_file", type=str, default=None)
data_arg.add_argument("--valid_file", type=str, default=None)
data_arg.add_argument("--test_file", type=str, default=None)
parser.add_argument(
"--embed_file", type=str, default="./data/glove.840B.300d.txt")
data_arg.add_argument("--max_vocab_size", type=int, default=30000)
data_arg.add_argument("--min_len", type=int, default=3)
data_arg.add_argument("--max_len", type=int, default=30)
# Model
model_arg = parser.add_argument_group("Model")
model_arg.add_argument("--embed_dim", type=int, default=300)
model_arg.add_argument("--hidden_dim", type=int, default=1024)
model_arg.add_argument("--num_mappings", type=int, default=20)
model_arg.add_argument("--tau", type=float, default=0.67)
model_arg.add_argument("--num_layers", type=int, default=1)
model_arg.add_argument("--bidirectional", type=str2bool, default=True)
model_arg.add_argument(
"--attn_mode",
type=str,
default='mlp',
choices=['none', 'mlp', 'dot', 'general'])
model_arg.add_argument(
"--use_pretrained_embedding", type=str2bool, default=True)
model_arg.add_argument("--embed_init_scale", type=float, default=0.03)
model_arg.add_argument("--dropout", type=float, default=0.3)
# Training
train_arg = parser.add_argument_group("Train")
train_arg.add_argument("--save_dir", type=str, default="./output/")
train_arg.add_argument("--num_epochs", type=int, default=10)
train_arg.add_argument("--shuffle", type=str2bool, default=True)
train_arg.add_argument("--log_steps", type=int, default=100)
train_arg.add_argument("--valid_steps", type=int, default=500)
train_arg.add_argument("--batch_size", type=int, default=128)
# Optimization
optim_arg = parser.add_argument_group("Optim")
optim_arg.add_argument("--optimizer", type=str, default="Adam")
optim_arg.add_argument("--lr", type=float, default=0.0002)
optim_arg.add_argument("--grad_clip", type=float, default=5.0)
# Inference
infer_arg = parser.add_argument_group("Inference")
infer_arg.add_argument("--beam_size", type=int, default=10)
infer_arg.add_argument("--min_infer_len", type=int, default=3)
infer_arg.add_argument("--max_infer_len", type=int, default=30)
infer_arg.add_argument("--length_average", type=str2bool, default=False)
infer_arg.add_argument("--ignore_unk", type=str2bool, default=True)
infer_arg.add_argument("--ignore_repeat", type=str2bool, default=True)
infer_arg.add_argument("--infer_batch_size", type=int, default=64)
infer_arg.add_argument("--result_file", type=str, default="./infer.result")
def main():
args = parse_args(parser)
if args.args_file:
args.load(args.args_file)
print("Loaded args from '{}'".format(args.args_file))
args.Data.vocab_file = args.Data.vocab_file or os.path.join(
args.Data.data_dir, "vocab.json")
args.Data.train_file = args.Data.train_file or os.path.join(
args.Data.data_dir, "dial.train.pkl")
args.Data.valid_file = args.Data.valid_file or os.path.join(
args.Data.data_dir, "dial.valid.pkl")
args.Data.test_file = args.Data.test_file or os.path.join(
args.Data.data_dir, "dial.test.pkl")
print("Args:")
print(args)
print()
# Dataset Definition
dataset = PostResponseDataset(
max_vocab_size=args.max_vocab_size,
min_len=args.min_len,
max_len=args.max_len,
embed_file=args.embed_file)
dataset.load_vocab(args.vocab_file)
# Generator Definition
generator = BeamSearch(
vocab_size=dataset.vocab.size(),
beam_size=args.beam_size,
start_id=dataset.vocab.bos_id,
end_id=dataset.vocab.eos_id,
unk_id=dataset.vocab.unk_id,
min_length=args.min_infer_len,
max_length=args.max_infer_len,
length_average=args.length_average,
ignore_unk=args.ignore_unk,
ignore_repeat=args.ignore_repeat)
# Model Definition
model = MMPMS(
vocab=dataset.vocab,
generator=generator,
hparams=args.Model,
optim_hparams=args.Optim,
use_gpu=args.use_gpu)
infer_parse_dict = {
"post": lambda T: dataset.denumericalize(tensor2list(T)),
"response": lambda T: dataset.denumericalize(tensor2list(T)),
"preds": lambda T: dataset.denumericalize(tensor2list(T)),
}
if args.infer:
if args.model_dir is not None:
model.load(args.model_dir)
print("Loaded model checkpoint from '{}'".format(args.model_dir))
infer_data = dataset.load_examples(args.test_file)
infer_loader = DataLoader(
data=infer_data,
batch_size=args.infer_batch_size,
shuffle=False,
use_gpu=args.use_gpu)
print("Inference starts ...")
infer_results = infer(
model, infer_loader, infer_parse_dict, save_file=args.result_file)
elif args.eval:
if args.model_dir is not None:
model.load(args.model_dir)
print("Loaded model checkpoint from '{}'".format(args.model_dir))
eval_data = dataset.load_examples(args.test_file)
eval_loader = DataLoader(
data=eval_data,
batch_size=args.batch_size,
shuffle=False,
use_gpu=args.use_gpu)
print("Evaluation starts ...")
eval_metrics_tracker = evaluate(model, eval_loader)
print(" ".join("{}-{}".format(name.upper(), value.avg)
for name, value in eval_metrics_tracker.items()))
else:
valid_data = dataset.load_examples(args.valid_file)
valid_loader = DataLoader(
data=valid_data,
batch_size=args.batch_size,
shuffle=False,
use_gpu=args.use_gpu)
train_data = dataset.load_examples(args.train_file)
train_loader = DataLoader(
data=train_data,
batch_size=args.batch_size,
shuffle=args.shuffle,
use_gpu=args.use_gpu)
# Save Directory Definition
date_str, time_str = datetime.now().strftime("%Y%m%d-%H%M%S").split("-")
result_str = "{}-{}".format(model.__class__.__name__, time_str)
args.save_dir = os.path.join(args.save_dir, date_str, result_str)
if not os.path.exists(args.save_dir):
os.makedirs(args.save_dir)
# Logger Definition
logger = getLogger(
os.path.join(args.save_dir, "train.log"), name="mmpms")
# Save args
args_file = os.path.join(args.save_dir, "args.json")
args.save(args_file)
logger.info("Saved args to '{}'".format(args_file))
# Executor Definition
exe = Engine(
model=model,
save_dir=args.save_dir,
log_steps=args.log_steps,
valid_steps=args.valid_steps,
logger=logger)
if args.model_dir is not None:
exe.load(args.model_dir)
# Train
logger.info("Training starts ...")
exe.evaluate(valid_loader, is_save=False)
for epoch in range(args.num_epochs):
exe.train_epoch(train_iter=train_loader, valid_iter=valid_loader)
logger.info("Training done!")
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("\nExited from the program ealier!")