/
arguments.py
1484 lines (1297 loc) · 80.4 KB
/
arguments.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2017, 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
"""
Defines commandline arguments for the main CLIs with reasonable defaults.
"""
import argparse
import os
import sys
import types
from typing import Any, Callable, Dict, List, Tuple, Optional
import yaml
from . import constants as C
from . import data_io
from .lr_scheduler import LearningRateSchedulerFixedStep
from . import utils
class ConfigArgumentParser(argparse.ArgumentParser):
"""
Extension of argparse.ArgumentParser supporting config files.
The option --config is added automatically and expects a YAML serialized
dictionary, similar to the return value of parse_args(). Command line
parameters have precedence over config file values. Usage should be
transparent, just substitute argparse.ArgumentParser with this class.
Extended from
https://stackoverflow.com/questions/28579661/getting-required-option-from-namespace-in-python
"""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.argument_definitions = {} # type: Dict[Tuple, Dict]
self.argument_actions = [] # type: List[Any]
self._overwrite_add_argument(self)
self.add_argument("--config", help="Config file in YAML format.", type=str)
# Note: not FileType so that we can get the path here
def _register_argument(self, _action, *args, **kwargs):
self.argument_definitions[args] = kwargs
self.argument_actions.append(_action)
def _overwrite_add_argument(self, original_object):
def _new_add_argument(this_self, *args, **kwargs):
action = this_self.original_add_argument(*args, **kwargs)
this_self.config_container._register_argument(action, *args, **kwargs)
original_object.original_add_argument = original_object.add_argument
original_object.config_container = self
original_object.add_argument = types.MethodType(_new_add_argument, original_object)
return original_object
def add_argument_group(self, *args, **kwargs):
group = super().add_argument_group(*args, **kwargs)
return self._overwrite_add_argument(group)
def parse_args(self, args=None, namespace=None) -> argparse.Namespace:
# Mini argument parser to find the config file
config_parser = argparse.ArgumentParser(add_help=False)
config_parser.add_argument("--config", type=regular_file())
config_args, _ = config_parser.parse_known_args(args=args)
initial_args = argparse.Namespace()
if config_args.config:
initial_args = load_args(config_args.config)
# Remove the 'required' flag from options loaded from config file
for action in self.argument_actions:
if action.dest in initial_args:
action.required = False
return super().parse_args(args=args, namespace=initial_args)
class StoreDeprecatedAction(argparse.Action):
def __init__(self, option_strings, dest, deprecated_dest, nargs=None, **kwargs):
super(StoreDeprecatedAction, self).__init__(option_strings, dest, **kwargs)
self.deprecated_dest = deprecated_dest
def __call__(self, parser, namespace, value, option_string=None):
setattr(namespace, self.dest, value)
setattr(namespace, self.deprecated_dest, value)
def save_args(args: argparse.Namespace, fname: str):
with open(fname, 'w') as out:
yaml.safe_dump(args.__dict__, out, default_flow_style=False)
def load_args(fname: str) -> argparse.Namespace:
with open(fname, 'r') as inp:
return argparse.Namespace(**yaml.safe_load(inp))
def regular_file() -> Callable:
"""
Returns a method that can be used in argument parsing to check the argument is a regular file or a symbolic link,
but not, e.g., a process substitution.
:return: A method that can be used as a type in argparse.
"""
def check_regular_file(value_to_check):
value_to_check = str(value_to_check)
if not os.path.isfile(value_to_check):
raise argparse.ArgumentTypeError("must exist and be a regular file.")
return value_to_check
return check_regular_file
def regular_folder() -> Callable:
"""
Returns a method that can be used in argument parsing to check the argument is a directory.
:return: A method that can be used as a type in argparse.
"""
def check_regular_directory(value_to_check):
value_to_check = str(value_to_check)
if not os.path.isdir(value_to_check):
raise argparse.ArgumentTypeError("must be a directory.")
return value_to_check
return check_regular_directory
def int_greater_or_equal(threshold: int) -> Callable:
"""
Returns a method that can be used in argument parsing to check that the int argument is greater or equal to `threshold`.
:param threshold: The threshold that we assume the cli argument value is greater or equal to.
:return: A method that can be used as a type in argparse.
"""
def check_greater_equal(value: str):
value_to_check = int(value)
if value_to_check < threshold:
raise argparse.ArgumentTypeError("must be greater or equal to %d." % threshold)
return value_to_check
return check_greater_equal
def float_greater_or_equal(threshold: float) -> Callable:
"""
Returns a method that can be used in argument parsing to check that the float argument is greater or equal to `threshold`.
:param threshold: The threshold that we assume the cli argument value is greater or equal to.
:return: A method that can be used as a type in argparse.
"""
def check_greater_equal(value: str):
value_to_check = float(value)
if value_to_check < threshold:
raise argparse.ArgumentTypeError("must be greater or equal to %f." % threshold)
return value_to_check
return check_greater_equal
def learning_schedule() -> Callable:
"""
Returns a method that can be used in argument parsing to check that the argument is a valid learning rate schedule
string.
:return: A method that can be used as a type in argparse.
"""
def parse(schedule_str):
try:
schedule = LearningRateSchedulerFixedStep.parse_schedule_str(schedule_str)
except ValueError:
raise argparse.ArgumentTypeError(
"Learning rate schedule string should have form rate1:num_updates1[,rate2:num_updates2,...]")
return schedule
return parse
def simple_dict() -> Callable:
"""
A simple dictionary format that does not require spaces or quoting.
Supported types: bool, int, float
:return: A method that can be used as a type in argparse.
"""
def parse(dict_str: str):
def _parse(value: str):
if value == "True":
return True
if value == "False":
return False
if "." in value:
return float(value)
return int(value)
_dict = dict()
try:
for entry in dict_str.split(","):
key, value = entry.split(":")
_dict[key] = _parse(value)
except ValueError:
raise argparse.ArgumentTypeError("Specify argument dictionary as key1:value1,key2:value2,..."
" Supported types: bool, int, float.")
return _dict
return parse
def multiple_values(num_values: int = 0,
greater_or_equal: Optional[float] = None,
data_type: Callable = int) -> Callable:
"""
Returns a method to be used in argument parsing to parse a string of the form "<val>:<val>[:<val>...]" into
a tuple of values of type data_type.
:param num_values: Optional number of ints required.
:param greater_or_equal: Optional constraint that all values should be greater or equal to this value.
:param data_type: Type of values. Default: int.
:return: Method for parsing.
"""
def parse(value_to_check):
if ':' in value_to_check:
expected_num_separators = num_values - 1 if num_values else 0
if expected_num_separators > 0 and (value_to_check.count(':') != expected_num_separators):
raise argparse.ArgumentTypeError("Expected either a single value or %d values separated by %s" %
(num_values, C.ARG_SEPARATOR))
values = tuple(map(data_type, value_to_check.split(C.ARG_SEPARATOR, num_values - 1)))
else:
values = tuple([data_type(value_to_check)] * num_values)
if greater_or_equal is not None:
if any((value < greater_or_equal for value in values)):
raise argparse.ArgumentTypeError("Must provide value greater or equal to %d" % greater_or_equal)
return values
return parse
def file_or_stdin() -> Callable:
"""
Returns a file descriptor from stdin or opening a file from a given path.
"""
def parse(path):
if path is None or path == "-":
return sys.stdin
else:
return data_io.smart_open(path)
return parse
def add_average_args(params):
average_params = params.add_argument_group("Averaging")
average_params.add_argument(
"inputs",
metavar="INPUT",
type=str,
nargs="+",
help="either a single model directory (automatic checkpoint selection) "
"or multiple .params files (manual checkpoint selection)")
average_params.add_argument(
"--metric",
help="Name of the metric to choose n-best checkpoints from. Default: %(default)s.",
default=C.PERPLEXITY,
choices=C.METRICS)
average_params.add_argument(
"-n",
type=int,
default=4,
help="number of checkpoints to find. Default: %(default)s.")
average_params.add_argument(
"--output", "-o", required=True, type=str, help="File to write averaged parameters to.")
average_params.add_argument(
"--strategy",
choices=C.AVERAGE_CHOICES,
default=C.AVERAGE_BEST,
help="selection method. Default: %(default)s.")
def add_extract_args(params):
extract_params = params.add_argument_group("Extracting")
extract_params.add_argument("input",
metavar="INPUT",
type=str,
help="Either a model directory (using params.best) or a specific params.x file.")
extract_params.add_argument('--names', '-n',
nargs='*',
default=[],
help='Names of parameters to be extracted.')
extract_params.add_argument('--list-all', '-l',
action='store_true',
help='List names of all available parameters.')
extract_params.add_argument('--output', '-o',
type=str,
help="File to write extracted parameters to (in .npz format).")
def add_rerank_args(params):
rerank_params = params.add_argument_group("Reranking")
rerank_params.add_argument("--reference", "-r",
type=str,
required=True,
help="File where target reference translations are stored.")
rerank_params.add_argument("--hypotheses", "-hy",
type=str,
required=True,
help="File with nbest translations, one nbest list per line,"
"in JSON format as returned by sockeye.translate with --nbest-size x.")
rerank_params.add_argument("--metric", "-m",
type=str,
required=False,
default=C.RERANK_BLEU,
choices=C.RERANK_METRICS,
help="Sentence-level metric used to compare each nbest translation to the reference."
"Default: %(default)s.")
rerank_params.add_argument("--output-best",
action="store_true",
help="Output only the best hypothesis from each nbest list.")
rerank_params.add_argument("--return-score",
action="store_true",
help="Returns the reranking scores as scores in output JSON objects.")
def add_lexicon_args(params):
lexicon_params = params.add_argument_group("Model & Top-k")
lexicon_params.add_argument("--model", "-m", required=True,
help="Model directory containing source and target vocabularies.")
lexicon_params.add_argument("-k", type=int, default=200,
help="Number of target translations to keep per source. Default: %(default)s.")
def add_lexicon_create_args(params):
lexicon_params = params.add_argument_group("I/O")
lexicon_params.add_argument("--input", "-i", required=True,
help="Probabilistic lexicon (fast_align format) to build top-k lexicon from.")
lexicon_params.add_argument("--output", "-o", required=True, help="File name to write top-k lexicon to.")
def add_lexicon_inspect_args(params):
lexicon_params = params.add_argument_group("Lexicon to inspect")
lexicon_params.add_argument("--lexicon", "-l", required=True, help="File name of top-k lexicon to inspect.")
def add_logging_args(params):
logging_params = params.add_argument_group("Logging")
logging_params.add_argument('--quiet', '-q',
default=False,
action="store_true",
help='Suppress console logging.')
logging_params.add_argument('--no-logfile',
default=False,
action="store_true",
help='Suppress file logging')
logging_params.add_argument('--loglevel',
default='INFO',
choices=['INFO', 'DEBUG'],
help='Log level. Default: %(default)s.')
def add_training_data_args(params, required=False):
params.add_argument(C.TRAINING_ARG_SOURCE, '-s',
required=required,
type=regular_file(),
help='Source side of parallel training data.')
params.add_argument('--source-factors', '-sf',
required=False,
nargs='+',
type=regular_file(),
default=[],
help='File(s) containing additional token-parallel source side factors. Default: %(default)s.')
params.add_argument(C.TRAINING_ARG_TARGET, '-t',
required=required,
type=regular_file(),
help='Target side of parallel training data.')
def add_validation_data_params(params):
params.add_argument('--validation-source', '-vs',
required=True,
type=regular_file(),
help='Source side of validation data.')
params.add_argument('--validation-source-factors', '-vsf',
required=False,
nargs='+',
type=regular_file(),
default=[],
help='File(s) containing additional token-parallel validation source side factors. '
'Default: %(default)s.')
params.add_argument('--validation-target', '-vt',
required=True,
type=regular_file(),
help='Target side of validation data.')
def add_prepared_data_args(params):
params.add_argument(C.TRAINING_ARG_PREPARED_DATA, '-d',
type=regular_folder(),
help='Prepared training data directory created through python -m sockeye.prepare_data.')
def add_monitoring_args(params):
params.add_argument('--monitor-pattern',
default=None,
type=str,
help="Pattern to match outputs/weights/gradients to monitor. '.*' monitors everything. "
"Default: %(default)s.")
params.add_argument('--monitor-stat-func',
default=C.STAT_FUNC_DEFAULT,
choices=list(C.MONITOR_STAT_FUNCS.keys()),
help="Statistics function to run on monitored outputs/weights/gradients. "
"Default: %(default)s.")
def add_training_output_args(params):
params.add_argument('--output', '-o',
required=True,
help='Folder where model & training results are written to.')
params.add_argument('--overwrite-output',
action='store_true',
help='Delete all contents of the model directory if it already exists.')
def add_training_io_args(params):
params = params.add_argument_group("Data & I/O")
# Unfortunately we must set --source/--target to not required as we either accept these parameters
# or --prepared-data which can not easily be encoded in argparse.
add_training_data_args(params, required=False)
add_prepared_data_args(params)
add_validation_data_params(params)
add_bucketing_args(params)
add_vocab_args(params)
add_training_output_args(params)
add_monitoring_args(params)
def add_bucketing_args(params):
params.add_argument('--no-bucketing',
action='store_true',
help='Disable bucketing: always unroll the graph to --max-seq-len. Default: %(default)s.')
params.add_argument('--bucket-width',
type=int_greater_or_equal(1),
default=10,
help='Width of buckets in tokens. Default: %(default)s.')
params.add_argument(C.TRAINING_ARG_MAX_SEQ_LEN,
type=multiple_values(num_values=2, greater_or_equal=1),
default=(99, 99),
help='Maximum sequence length in tokens.'
'Use "x:x" to specify separate values for src&tgt. Default: %(default)s.')
def add_prepare_data_cli_args(params):
add_training_data_args(params, required=True)
add_vocab_args(params)
add_bucketing_args(params)
add_logging_args(params)
data_prep = params.add_argument_group("Data preparation.")
data_prep.add_argument('--num-samples-per-shard',
type=int_greater_or_equal(1),
default=1000000,
help='The approximate number of samples per shard. Default: %(default)s.')
data_prep.add_argument('--min-num-shards',
default=1,
type=int_greater_or_equal(1),
help='The minimum number of shards to use, even if they would not '
'reach the desired number of samples per shard. Default: %(default)s.')
data_prep.add_argument('--seed',
type=int,
default=13,
help='Random seed used that makes shard assignments deterministic. Default: %(default)s.')
data_prep.add_argument('--output', '-o',
required=True,
help='Folder where the prepared and possibly sharded data is written to.')
def add_device_args(params):
device_params = params.add_argument_group("Device parameters")
device_params.add_argument('--device-ids', default=[-1],
help='List or number of GPUs ids to use. Default: %(default)s. '
'Use negative numbers to automatically acquire a certain number of GPUs, e.g. -5 '
'will find 5 free GPUs. '
'Use positive numbers to acquire a specific GPU id on this host. '
'(Note that automatic acquisition of GPUs assumes that all GPU processes on '
'this host are using automatic sockeye GPU acquisition).',
nargs='+', type=int)
device_params.add_argument('--use-cpu',
action='store_true',
help='Use CPU device instead of GPU.')
device_params.add_argument('--disable-device-locking',
action='store_true',
help='Just use the specified device ids without locking.')
device_params.add_argument('--lock-dir',
default="/tmp",
help='When acquiring a GPU we do file based locking so that only one Sockeye process '
'can run on the a GPU. This is the folder in which we store the file '
'locks. For locking to work correctly it is assumed all processes use the same '
'lock directory. The only requirement for the directory are file '
'write permissions.')
def add_vocab_args(params):
params.add_argument('--source-vocab',
required=False,
default=None,
help='Existing source vocabulary (JSON).')
params.add_argument('--target-vocab',
required=False,
default=None,
help='Existing target vocabulary (JSON).')
params.add_argument('--source-factor-vocabs',
required=False,
nargs='+',
type=regular_file(),
default=[],
help='Existing source factor vocabulary (-ies) (JSON).')
params.add_argument(C.VOCAB_ARG_SHARED_VOCAB,
action='store_true',
default=False,
help='Share source and target vocabulary. '
'Will be automatically turned on when using weight tying. Default: %(default)s.')
params.add_argument('--num-words',
type=multiple_values(num_values=2, greater_or_equal=0),
default=(0, 0),
help='Maximum vocabulary size. Use "x:x" to specify separate values for src&tgt. '
'A value of 0 indicates that the vocabulary unrestricted and determined from the data by '
'creating an entry for all words that occur at least --word-min-count times.'
'Default: %(default)s.')
params.add_argument('--word-min-count',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(1, 1),
help='Minimum frequency of words to be included in vocabularies. Default: %(default)s.')
params.add_argument('--pad-vocab-to-multiple-of',
type=int,
default=None,
help='Pad vocabulary to a multiple of this integer. Default: %(default)s.')
def add_model_parameters(params):
model_params = params.add_argument_group("ModelConfig")
model_params.add_argument('--params', '-p',
type=str,
default=None,
help='Initialize model parameters from file. Overrides random initializations.')
model_params.add_argument('--allow-missing-params',
action="store_true",
default=False,
help="Allow missing parameters when initializing model parameters from file. "
"Default: %(default)s.")
model_params.add_argument('--encoder',
choices=C.ENCODERS,
default=C.TRANSFORMER_TYPE,
help="Type of encoder. Default: %(default)s.")
model_params.add_argument('--decoder',
choices=C.DECODERS,
default=C.TRANSFORMER_TYPE,
help="Type of encoder. Default: %(default)s.")
model_params.add_argument('--num-layers',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(6, 6),
help='Number of layers for encoder & decoder. '
'Use "x:x" to specify separate values for encoder & decoder. Default: %(default)s.')
model_params.add_argument('--conv-embed-output-dim',
type=int_greater_or_equal(1),
default=None,
help="Project segment embeddings to this size for ConvolutionalEmbeddingEncoder. Omit to"
" avoid projection, leaving segment embeddings total size of all filters. Default:"
" %(default)s.")
model_params.add_argument('--conv-embed-max-filter-width',
type=int_greater_or_equal(1),
default=8,
help="Maximum filter width for ConvolutionalEmbeddingEncoder. Default: %(default)s.")
model_params.add_argument('--conv-embed-num-filters',
type=multiple_values(greater_or_equal=1),
default=(200, 200, 250, 250, 300, 300, 300, 300),
help="List of number of filters of each width 1..max for ConvolutionalEmbeddingEncoder. "
"Default: %(default)s.")
model_params.add_argument('--conv-embed-pool-stride',
type=int_greater_or_equal(1),
default=5,
help="Pooling stride for ConvolutionalEmbeddingEncoder. Default: %(default)s.")
model_params.add_argument('--conv-embed-num-highway-layers',
type=int_greater_or_equal(0),
default=4,
help="Number of highway layers for ConvolutionalEmbeddingEncoder. Default: %(default)s.")
model_params.add_argument('--conv-embed-add-positional-encodings',
action='store_true',
default=False,
help="Add positional encodings to final segment embeddings for"
" ConvolutionalEmbeddingEncoder. Default: %(default)s.")
# convolutional encoder/decoder arguments arguments
model_params.add_argument('--cnn-kernel-width',
type=multiple_values(num_values=2, greater_or_equal=1, data_type=int),
default=(3, 3),
help='Kernel width of the convolutional encoder and decoder. Default: %(default)s.')
model_params.add_argument('--cnn-num-hidden',
type=int_greater_or_equal(1),
default=512,
help='Number of hidden units for the convolutional encoder and decoder. '
'Default: %(default)s.')
model_params.add_argument('--cnn-activation-type',
choices=C.CNN_ACTIVATION_TYPES,
default=C.GLU,
help="Type activation to use for each convolutional layer. Default: %(default)s.")
model_params.add_argument('--cnn-positional-embedding-type',
choices=C.POSITIONAL_EMBEDDING_TYPES,
default=C.LEARNED_POSITIONAL_EMBEDDING,
help='The type of positional embedding. Default: %(default)s.')
model_params.add_argument('--cnn-project-qkv',
action='store_true',
default=False,
help="Optionally apply query, key and value projections to the source and target hidden "
"vectors before applying the attention mechanism.")
# rnn arguments
model_params.add_argument('--rnn-cell-type',
choices=C.CELL_TYPES,
default=C.LSTM_TYPE,
help='RNN cell type for encoder and decoder. Default: %(default)s.')
model_params.add_argument('--rnn-num-hidden',
type=int_greater_or_equal(1),
default=1024,
help='Number of RNN hidden units for encoder and decoder. Default: %(default)s.')
model_params.add_argument('--rnn-encoder-reverse-input',
action='store_true',
help='Reverse input sequence for RNN encoder. Default: %(default)s.')
model_params.add_argument('--rnn-decoder-state-init',
default=C.RNN_DEC_INIT_LAST,
choices=C.RNN_DEC_INIT_CHOICES,
help='How to initialize RNN decoder states. Default: %(default)s.')
model_params.add_argument('--rnn-residual-connections',
action="store_true",
default=False,
help="Add residual connections to stacked RNNs. (see Wu ETAL'16). Default: %(default)s.")
model_params.add_argument('--rnn-first-residual-layer',
type=int_greater_or_equal(2),
default=2,
help='First RNN layer to have a residual connection. Default: %(default)s.')
model_params.add_argument('--rnn-context-gating', action="store_true",
help="Enables a context gate which adaptively weighs the RNN decoder input against the "
"source context vector before each update of the decoder hidden state.")
# transformer arguments
model_params.add_argument('--transformer-model-size',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(512, 512),
help='Number of hidden units in transformer layers. '
'Use "x:x" to specify separate values for encoder & decoder. Default: %(default)s.')
model_params.add_argument('--transformer-attention-heads',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(8, 8),
help='Number of heads for all self-attention when using transformer layers. '
'Use "x:x" to specify separate values for encoder & decoder. Default: %(default)s.')
model_params.add_argument('--transformer-feed-forward-num-hidden',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(2048, 2048),
help='Number of hidden units in transformers feed forward layers. '
'Use "x:x" to specify separate values for encoder & decoder. Default: %(default)s.')
model_params.add_argument('--transformer-activation-type',
choices=C.TRANSFORMER_ACTIVATION_TYPES,
default=C.RELU,
help="Type activation to use for each feed forward layer. Default: %(default)s.")
model_params.add_argument('--transformer-positional-embedding-type',
choices=C.POSITIONAL_EMBEDDING_TYPES,
default=C.FIXED_POSITIONAL_EMBEDDING,
help='The type of positional embedding. Default: %(default)s.')
model_params.add_argument('--transformer-preprocess',
type=multiple_values(num_values=2, greater_or_equal=None, data_type=str),
default=('n', 'n'),
help='Transformer preprocess sequence for encoder and decoder. Supports three types of '
'operations: d=dropout, r=residual connection, n=layer normalization. You can '
'combine in any order, for example: "ndr". '
'Leave empty to not use any of these operations. '
'You can specify separate sequences for encoder and decoder by separating with ":" '
'For example: n:drn '
'Default: %(default)s.')
model_params.add_argument('--transformer-postprocess',
type=multiple_values(num_values=2, greater_or_equal=None, data_type=str),
default=('dr', 'dr'),
help='Transformer postprocess sequence for encoder and decoder. Supports three types of '
'operations: d=dropout, r=residual connection, n=layer normalization. You can '
'combine in any order, for example: "ndr". '
'Leave empty to not use any of these operations. '
'You can specify separate sequences for encoder and decoder by separating with ":" '
'For example: n:drn '
'Default: %(default)s.')
model_params.add_argument('--attention-based-copying', action="store_true",
help="Enables an attention-based copying mechanism. Supported only by RNN decoders. "
"This allows to explicitly declare pointers to source tokens in the target "
"sequence (format: <ptr\d+>)."
"Each pointer on the target side can point to any of the d input tokens, "
"e.g. <ptr0> points to the first source token.")
# LHUC
# TODO: The convolutional model does not support lhuc yet
model_params.add_argument('--lhuc',
nargs="+",
default=None,
choices=C.LHUC_CHOICES,
metavar="COMPONENT",
help="Use LHUC (Vilar 2018). Include an amplitude parameter to hidden units for"
" domain adaptation. Needs a pre-trained model. Valid values: {values}. Currently not"
" supported for convolutional models. Default: %(default)s.".format(
values=", ".join(C.LHUC_CHOICES)))
# embedding arguments
model_params.add_argument('--num-embed',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(None, None),
help='Embedding size for source and target tokens. '
'Use "x:x" to specify separate values for src&tgt. Default: %d.' % C.DEFAULT_NUM_EMBED)
model_params.add_argument('--source-factors-num-embed',
type=int,
nargs='+',
default=[],
help='Embedding size for additional source factors. '
'You must provide as many dimensions as '
'(validation) source factor files. Default: %(default)s.')
model_params.add_argument('--source-factors-combine', '-sfc',
choices=C.SOURCE_FACTORS_COMBINE_CHOICES,
default=C.SOURCE_FACTORS_COMBINE_CONCAT,
help='How to combine source factors. Default: %(default)s.')
# attention arguments
model_params.add_argument('--rnn-attention-type',
choices=C.ATT_TYPES,
default=C.ATT_MLP,
help='Attention model for RNN decoders. Choices: {%(choices)s}. '
'Default: %(default)s.')
model_params.add_argument('--rnn-attention-num-hidden',
default=None,
type=int,
help='Number of hidden units for attention layers. Default: equal to --rnn-num-hidden.')
model_params.add_argument('--rnn-attention-use-prev-word', action="store_true",
help="Feed the previous target embedding into the attention mechanism.")
model_params.add_argument('--rnn-scale-dot-attention',
action='store_true',
help='Optional scale before dot product. Only applicable to \'dot\' attention type. '
'[Vaswani et al, 2017]')
model_params.add_argument('--rnn-attention-coverage-type',
choices=C.COVERAGE_TYPES,
default=C.COVERAGE_COUNT,
help="Type of model for updating coverage vectors. 'count' refers to an update method "
"that accumulates attention scores. 'fertility' accumulates attention scores as well "
"but also computes a fertility value for every source word. "
"'tanh', 'sigmoid', 'relu', 'softrelu' "
"use non-linear layers with the respective activation type, and 'gru' uses a "
"GRU to update the coverage vectors. Default: %(default)s.")
model_params.add_argument('--rnn-attention-coverage-max-fertility',
type=int,
default=2,
help="Maximum fertility for individual source words. Default: %(default)s.")
model_params.add_argument('--rnn-attention-coverage-num-hidden',
type=int,
default=1,
help="Number of hidden units for coverage vectors. Default: %(default)s.")
model_params.add_argument('--rnn-attention-in-upper-layers',
action="store_true",
help="Pass the attention to the upper layers of the RNN decoder, similar "
"to GNMT paper. Only applicable if more than one layer is used.")
model_params.add_argument('--rnn-attention-mhdot-heads',
type=int, default=None,
help='Number of heads for Multi-head dot attention. Default: %(default)s.')
model_params.add_argument('--weight-tying',
action='store_true',
help='Turn on weight tying (see arxiv.org/abs/1608.05859). '
'The type of weight sharing is determined through '
'--weight-tying-type. Default: %(default)s.')
model_params.add_argument('--weight-tying-type',
default=C.WEIGHT_TYING_TRG_SOFTMAX,
choices=[C.WEIGHT_TYING_SRC_TRG_SOFTMAX,
C.WEIGHT_TYING_SRC_TRG,
C.WEIGHT_TYING_TRG_SOFTMAX],
help='The type of weight tying. source embeddings=src, target embeddings=trg, '
'target softmax weight matrix=softmax. Default: %(default)s.')
model_params.add_argument('--layer-normalization', action="store_true",
help="Adds layer normalization before non-linear activations. "
"This includes MLP attention, RNN decoder state initialization, "
"RNN decoder hidden state, and cnn layers."
"It does not normalize RNN cell activations "
"(this can be done using the '%s' or '%s' rnn-cell-type." % (C.LNLSTM_TYPE,
C.LNGLSTM_TYPE))
model_params.add_argument('--weight-normalization', action="store_true",
help="Adds weight normalization to decoder output layers "
"(and all convolutional weight matrices for CNN decoders). Default: %(default)s.")
def add_batch_args(params, default_batch_size=4096):
params.add_argument('--batch-size', '-b',
type=int_greater_or_equal(1),
default=default_batch_size,
help='Mini-batch size. Note that depending on the batch-type this either refers to '
'words or sentences.'
'Sentence: each batch contains X sentences, number of words varies. '
'Word: each batch contains (approximately) X words, number of sentences varies. '
'Default: %(default)s.')
params.add_argument("--batch-type",
type=str,
default=C.BATCH_TYPE_WORD,
choices=[C.BATCH_TYPE_SENTENCE, C.BATCH_TYPE_WORD],
help="Sentence: each batch contains X sentences, number of words varies."
"Word: each batch contains (approximately) X target words, "
"number of sentences varies. Default: %(default)s.")
def add_training_args(params):
train_params = params.add_argument_group("Training parameters")
add_batch_args(train_params)
train_params.add_argument('--decoder-only',
action='store_true',
help='Pre-train a decoder. This is currently for RNN decoders only. '
'Default: %(default)s.')
train_params.add_argument('--loss',
default=C.CROSS_ENTROPY,
choices=[C.CROSS_ENTROPY],
help='Loss to optimize. Default: %(default)s.')
train_params.add_argument('--label-smoothing',
default=0.1,
type=float,
help='Smoothing constant for label smoothing. Default: %(default)s.')
train_params.add_argument('--loss-normalization-type',
default=C.LOSS_NORM_VALID,
choices=[C.LOSS_NORM_VALID, C.LOSS_NORM_BATCH],
help='How to normalize the loss. By default loss is normalized by the number '
'of valid (non-PAD) tokens (%s).' % C.LOSS_NORM_VALID)
train_params.add_argument('--length-task',
type=str,
default=None,
choices=[C.LENGTH_TASK_RATIO, C.LENGTH_TASK_LENGTH],
help='If specified, adds an auxiliary task during training to predict source/target length ratios '
'(mean squared error loss), or absolute lengths (Poisson) loss. Default %(default)s.')
train_params.add_argument('--length-task-weight',
type=float_greater_or_equal(0.0),
default=1.0,
help='The weight of the auxiliary --length-task loss. Default %(default)s.')
train_params.add_argument('--length-task-layers',
type=int_greater_or_equal(1),
default=1,
help='Number of fully-connected layers for predicting the length ratio. Default %(default)s.')
train_params.add_argument('--metrics',
nargs='+',
default=[C.PERPLEXITY],
choices=[C.PERPLEXITY, C.ACCURACY, C.LENRATIO_MSE],
help='Names of metrics to track on training and validation data. Default: %(default)s.')
train_params.add_argument('--optimized-metric',
default=C.PERPLEXITY,
choices=C.METRICS,
help='Metric to optimize with early stopping {%(choices)s}. Default: %(default)s.')
train_params.add_argument('--min-updates',
type=int,
default=None,
help='Minimum number of updates before training can stop. Default: %(default)s.')
train_params.add_argument('--max-updates',
type=int,
default=None,
help='Maximum number of updates. Default: %(default)s.')
train_params.add_argument('--max-seconds',
type=int,
default=None,
help='Training will stop on the next checkpoint after reaching the maximum seconds. '
'Default: %(default)s.')
train_params.add_argument('--update-interval',
type=int,
default=1,
help="Number of batch gradients to accumulate before updating. Default: %(default)s.")
train_params.add_argument('--min-samples',
type=int,
default=None,
help='Minimum number of samples before training can stop. Default: %(default)s.')
train_params.add_argument('--max-samples',
type=int,
default=None,
help='Maximum number of samples. Default: %(default)s.')
train_params.add_argument(C.TRAIN_ARGS_CHECKPOINT_INTERVAL,
type=int_greater_or_equal(1),
default=4000,
help='Checkpoint and evaluate every x updates/batches. Default: %(default)s.')
train_params.add_argument(C.TRAIN_ARGS_CHECKPOINT_FREQUENCY,
type=int_greater_or_equal(1),
dest="checkpoint_interval",
deprecated_dest="checkpoint_frequency",
action=StoreDeprecatedAction,
default=argparse.SUPPRESS,
help=argparse.SUPPRESS)
train_params.add_argument('--max-num-checkpoint-not-improved',
type=int,
default=32,
help='Maximum number of checkpoints the model is allowed to not improve in '
'<optimized-metric> on validation data before training is stopped. '
'Default: %(default)s.')
train_params.add_argument('--max-checkpoints',
type=int,
default=None,
help='Maximum number of checkpoints to continue training the model '
'before training is stopped. '
'Default: %(default)s.')
train_params.add_argument('--min-num-epochs',
type=int,
default=None,
help='Minimum number of epochs (passes through the training data) '
'before training can stop. Default: %(default)s.')
train_params.add_argument('--max-num-epochs',
type=int,
default=None,
help='Maximum number of epochs (passes through the training data) Default: %(default)s.')
train_params.add_argument('--embed-dropout',
type=multiple_values(2, data_type=float),
default=(.0, .0),
help='Dropout probability for source & target embeddings. Use "x:x" to specify '
'separate values. Default: %(default)s.')
train_params.add_argument('--rnn-dropout-inputs',
type=multiple_values(2, data_type=float),
default=(.0, .0),
help='RNN variational dropout probability for encoder & decoder RNN inputs. (Gal, 2015)'
'Use "x:x" to specify separate values. Default: %(default)s.')
train_params.add_argument('--rnn-dropout-states',
type=multiple_values(2, data_type=float),
default=(.0, .0),
help='RNN variational dropout probability for encoder & decoder RNN states. (Gal, 2015)'
'Use "x:x" to specify separate values. Default: %(default)s.')
train_params.add_argument('--rnn-dropout-recurrent',
type=multiple_values(2, data_type=float),
default=(.0, .0),
help='Recurrent dropout without memory loss (Semeniuta, 2016) for encoder & decoder '
'LSTMs. Use "x:x" to specify separate values. Default: %(default)s.')
train_params.add_argument('--rnn-enc-last-hidden-concat-to-embedding',
action="store_true",
help='Concatenate the last hidden layer of the encoder to the input of the decoder, '
'instead of the previous state of the decoder. Default: %(default)s.')
train_params.add_argument('--rnn-decoder-hidden-dropout',
type=float,
default=.2,
help='Dropout probability for hidden state that combines the context with the '
'RNN hidden state in the decoder. Default: %(default)s.')
train_params.add_argument('--transformer-dropout-attention',
type=float,
default=0.1,
help='Dropout probability for multi-head attention. Default: %(default)s.')
train_params.add_argument('--transformer-dropout-act',
type=float,
default=0.1,
help='Dropout probability before activation in feed-forward block. Default: %(default)s.')
train_params.add_argument('--transformer-dropout-prepost',
type=float,
default=0.1,
help='Dropout probability for pre/postprocessing blocks. Default: %(default)s.')
train_params.add_argument('--conv-embed-dropout',
type=float,
default=.0,
help="Dropout probability for ConvolutionalEmbeddingEncoder. Default: %(default)s.")
train_params.add_argument('--cnn-hidden-dropout',
type=float,
default=.2,
help="Dropout probability for dropout between convolutional layers. Default: %(default)s.")
train_params.add_argument('--optimizer',