forked from OpenNMT/OpenNMT-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opts.py
344 lines (302 loc) · 16.7 KB
/
opts.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import argparse
from onmt.modules.SRU import CheckSRU
def model_opts(parser):
"""
These options are passed to the construction of the model.
Be careful with these as they will be used during translation.
"""
# Model options
parser.add_argument('-model_type', default='text',
help="Type of encoder to use. Options are [text|img].")
# Embedding Options
parser.add_argument('-word_vec_size', type=int, default=-1,
help='Word embedding for both.')
parser.add_argument('-src_word_vec_size', type=int, default=500,
help='Src word embedding sizes')
parser.add_argument('-tgt_word_vec_size', type=int, default=500,
help='Tgt word embedding sizes')
parser.add_argument('-feat_merge', type=str, default='concat',
choices=['concat', 'sum', 'mlp'],
help='Merge action for the features embeddings')
parser.add_argument('-feat_vec_size', type=int, default=-1,
help="""If specified, feature embedding sizes
will be set to this. Otherwise, feat_vec_exponent
will be used.""")
parser.add_argument('-feat_vec_exponent', type=float, default=0.7,
help="""If -feat_merge_size is not set, feature
embedding sizes will be set to N^feat_vec_exponent
where N is the number of values the feature takes.""")
parser.add_argument('-position_encoding', action='store_true',
help='Use a sin to mark relative words positions.')
parser.add_argument('-share_decoder_embeddings', action='store_true',
help='Share the word and out embeddings for decoder.')
parser.add_argument('-share_embeddings', action='store_true',
help="""Share the word embeddings between encoder
and decoder.""")
# RNN Options
parser.add_argument('-encoder_type', type=str, default='rnn',
choices=['rnn', 'brnn', 'mean', 'transformer', 'cnn'],
help="""Type of encoder layer to use.""")
parser.add_argument('-decoder_type', type=str, default='rnn',
choices=['rnn', 'transformer', 'cnn'],
help='Type of decoder layer to use.')
parser.add_argument('-layers', type=int, default=-1,
help='Number of layers in enc/dec.')
parser.add_argument('-enc_layers', type=int, default=2,
help='Number of layers in the encoder')
parser.add_argument('-dec_layers', type=int, default=2,
help='Number of layers in the decoder')
parser.add_argument('-cnn_kernel_width', type=int, default=3,
help="""Size of windows in the cnn, the kernel_size is
(cnn_kernel_width, 1) in conv layer""")
parser.add_argument('-rnn_size', type=int, default=500,
help='Size of LSTM hidden states')
parser.add_argument('-input_feed', type=int, default=1,
help="""Feed the context vector at each time step as
additional input (via concatenation with the word
embeddings) to the decoder.""")
parser.add_argument('-rnn_type', type=str, default='LSTM',
choices=['LSTM', 'GRU', 'SRU'],
action=CheckSRU,
help="""The gate type to use in the RNNs""")
# parser.add_argument('-residual', action="store_true",
# help="Add residual connections between RNN layers.")
parser.add_argument('-brnn', action=DeprecateAction,
help="Deprecated, use `encoder_type`.")
parser.add_argument('-brnn_merge', default='concat',
choices=['concat', 'sum'],
help="Merge action for the bidir hidden states")
parser.add_argument('-context_gate', type=str, default=None,
choices=['source', 'target', 'both'],
help="""Type of context gate to use.
Do not select for no context gate.""")
# Attention options
parser.add_argument('-global_attention', type=str, default='general',
choices=['dot', 'general', 'mlp'],
help="""The attention type to use:
dotprot or general (Luong) or MLP (Bahdanau)""")
# Genenerator and loss options.
parser.add_argument('-copy_attn', action="store_true",
help='Train copy attention layer.')
parser.add_argument('-copy_attn_force', action="store_true",
help='When available, train to copy.')
parser.add_argument('-coverage_attn', action="store_true",
help='Train a coverage attention layer.')
parser.add_argument('-lambda_coverage', type=float, default=1,
help='Lambda value for coverage.')
def preprocess_opts(parser):
# Dictionary Options
parser.add_argument('-src_vocab_size', type=int, default=50000,
help="Size of the source vocabulary")
parser.add_argument('-tgt_vocab_size', type=int, default=50000,
help="Size of the target vocabulary")
parser.add_argument('-src_words_min_frequency', type=int, default=0)
parser.add_argument('-tgt_words_min_frequency', type=int, default=0)
# Truncation options
parser.add_argument('-src_seq_length', type=int, default=50,
help="Maximum source sequence length")
parser.add_argument('-src_seq_length_trunc', type=int, default=0,
help="Truncate source sequence length.")
parser.add_argument('-tgt_seq_length', type=int, default=50,
help="Maximum target sequence length to keep.")
parser.add_argument('-tgt_seq_length_trunc', type=int, default=0,
help="Truncate target sequence length.")
# Data processing options
parser.add_argument('-shuffle', type=int, default=1,
help="Shuffle data")
parser.add_argument('-lower', action='store_true', help='lowercase data')
# Options most relevant to summarization
parser.add_argument('-dynamic_dict', action='store_true',
help="Create dynamic dictionaries")
parser.add_argument('-share_vocab', action='store_true',
help="Share source and target vocabulary")
def train_opts(parser):
# Model loading/saving options
parser.add_argument('-data', required=True,
help="""Path prefix to the ".train.pt" and
".valid.pt" file path from preprocess.py""")
parser.add_argument('-save_model', default='model',
help="""Model filename (the model will be saved as
<save_model>_epochN_PPL.pt where PPL is the
validation perplexity""")
parser.add_argument('-train_from', default='', type=str,
help="""If training from a checkpoint then this is the
path to the pretrained model's state_dict.""")
# GPU
parser.add_argument('-gpuid', default=[], nargs='+', type=int,
help="Use CUDA on the listed devices.")
parser.add_argument('-seed', type=int, default=-1,
help="""Random seed used for the experiments
reproducibility.""")
# Init options
parser.add_argument('-start_epoch', type=int, default=1,
help='The epoch from which to start')
parser.add_argument('-param_init', type=float, default=0.1,
help="""Parameters are initialized over uniform distribution
with support (-param_init, param_init).
Use 0 to not use initialization""")
# Pretrained word vectors
parser.add_argument('-pre_word_vecs_enc',
help="""If a valid path is specified, then this will load
pretrained word embeddings on the encoder side.
See README for specific formatting instructions.""")
parser.add_argument('-pre_word_vecs_dec',
help="""If a valid path is specified, then this will load
pretrained word embeddings on the decoder side.
See README for specific formatting instructions.""")
# Fixed word vectors
parser.add_argument('-fix_word_vecs_enc',
action='store_true',
help="Fix word embeddings on the encoder side.")
parser.add_argument('-fix_word_vecs_dec',
action='store_true',
help="Fix word embeddings on the encoder side.")
# Optimization options
parser.add_argument('-batch_size', type=int, default=64,
help='Maximum batch size')
parser.add_argument('-max_generator_batches', type=int, default=32,
help="""Maximum batches of words in a sequence to run
the generator on in parallel. Higher is faster, but
uses more memory.""")
parser.add_argument('-epochs', type=int, default=13,
help='Number of training epochs')
parser.add_argument('-optim', default='sgd',
choices=['sgd', 'adagrad', 'adadelta', 'adam'],
help="""Optimization method.""")
parser.add_argument('-max_grad_norm', type=float, default=5,
help="""If the norm of the gradient vector exceeds this,
renormalize it to have the norm equal to
max_grad_norm""")
parser.add_argument('-dropout', type=float, default=0.3,
help="Dropout probability; applied in LSTM stacks.")
parser.add_argument('-truncated_decoder', type=int, default=0,
help="""Truncated bptt.""")
# learning rate
parser.add_argument('-learning_rate', type=float, default=1.0,
help="""Starting learning rate.
Recommended settings: sgd = 1, adagrad = 0.1,
adadelta = 1, adam = 0.001""")
parser.add_argument('-learning_rate_decay', type=float, default=0.5,
help="""If update_learning_rate, decay learning rate by
this much if (i) perplexity does not decrease on the
validation set or (ii) epoch has gone past
start_decay_at""")
parser.add_argument('-start_decay_at', type=int, default=8,
help="""Start decaying every epoch after and including this
epoch""")
parser.add_argument('-start_checkpoint_at', type=int, default=0,
help="""Start checkpointing every epoch after and including
this epoch""")
parser.add_argument('-decay_method', type=str, default="",
choices=['noam'], help="Use a custom decay rate.")
parser.add_argument('-warmup_steps', type=int, default=4000,
help="""Number of warmup steps for custom decay.""")
parser.add_argument('-report_every', type=int, default=50,
help="Print stats at this interval.")
parser.add_argument('-exp_host', type=str, default="",
help="Send logs to this crayon server.")
parser.add_argument('-exp', type=str, default="",
help="Name of the experiment for logging.")
def translate_opts(parser):
parser.add_argument('-model', required=True,
help='Path to model .pt file')
parser.add_argument('-src', required=True,
help="""Source sequence to decode (one line per
sequence)""")
parser.add_argument('-src_img_dir', default="",
help='Source image directory')
parser.add_argument('-tgt',
help='True target sequence (optional)')
parser.add_argument('-output', default='pred.txt',
help="""Path to output the predictions (each line will
be the decoded sequence""")
parser.add_argument('-beam_size', type=int, default=5,
help='Beam size')
parser.add_argument('-batch_size', type=int, default=30,
help='Batch size')
parser.add_argument('-max_sent_length', type=int, default=100,
help='Maximum sentence length.')
parser.add_argument('-replace_unk', action="store_true",
help="""Replace the generated UNK tokens with the
source token that had highest attention weight. If
phrase_table is provided, it will lookup the
identified source token and give the corresponding
target token. If it is not provided(or the identified
source token does not exist in the table) then it
will copy the source token""")
parser.add_argument('-verbose', action="store_true",
help='Print scores and predictions for each sentence')
parser.add_argument('-attn_debug', action="store_true",
help='Print best attn for each word')
parser.add_argument('-dump_beam', type=str, default="",
help='File to dump beam information to.')
parser.add_argument('-n_best', type=int, default=1,
help="""If verbose is set, will output the n_best
decoded sentences""")
parser.add_argument('-gpu', type=int, default=-1,
help="Device to run on")
# Options most relevant to summarization.
parser.add_argument('-dynamic_dict', action='store_true',
help="Create dynamic dictionaries")
parser.add_argument('-share_vocab', action='store_true',
help="Share source and target vocabulary")
def add_md_help_argument(parser):
parser.add_argument('-md', action=MarkdownHelpAction,
help='print Markdown-formatted help text and exit.')
# MARKDOWN boilerplate
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class MarkdownHelpFormatter(argparse.HelpFormatter):
"""A really bare-bones argparse help formatter that generates valid markdown.
This will generate something like:
usage
# **section heading**:
## **--argument-one**
```
argument-one help text
```
"""
def _format_usage(self, usage, actions, groups, prefix):
usage_text = super(MarkdownHelpFormatter, self)._format_usage(
usage, actions, groups, prefix)
return '\n```\n%s\n```\n\n' % usage_text
def format_help(self):
self._root_section.heading = '# %s' % self._prog
return super(MarkdownHelpFormatter, self).format_help()
def start_section(self, heading):
super(MarkdownHelpFormatter, self).start_section('## **%s**' % heading)
def _format_action(self, action):
lines = []
action_header = self._format_action_invocation(action)
lines.append('### **%s** ' % action_header)
if action.help:
lines.append('')
lines.append('```')
help_text = self._expand_help(action)
lines.extend(self._split_lines(help_text, 80))
lines.append('```')
lines.extend(['', ''])
return '\n'.join(lines)
class MarkdownHelpAction(argparse.Action):
def __init__(self, option_strings,
dest=argparse.SUPPRESS, default=argparse.SUPPRESS,
**kwargs):
super(MarkdownHelpAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
**kwargs)
def __call__(self, parser, namespace, values, option_string=None):
parser.formatter_class = MarkdownHelpFormatter
parser.print_help()
parser.exit()
class DeprecateAction(argparse.Action):
def __init__(self, option_strings, dest, help=None, **kwargs):
super(DeprecateAction, self).__init__(option_strings, dest, nargs=0,
help=help, **kwargs)
def __call__(self, parser, namespace, values, flag_name):
help = self.help if self.help is not None else ""
msg = "Flag '%s' is deprecated. %s" % (flag_name, help)
raise argparse.ArgumentTypeError(msg)