/
arguments.py
1421 lines (1230 loc) · 75.2 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--2022 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 sockeye.utils import smart_open
from . import constants as C
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="Path to CLI arguments in yaml format "
"(as saved in Sockeye model directories as 'args.yaml'). "
"Commandline arguments have precedence over values in this file.", 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: # type: ignore
# 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 bool_str() -> Callable:
"""
Returns a method that can be used in argument parsing to check that the argument is a valid representation of
a boolean value.
:return: A method that can be used as a type in argparse.
"""
def parse(value: str):
lower_value = value.lower()
if lower_value in ["true", "yes", "1"]:
return True
elif lower_value in ["false", "no", "0"]:
return False
else:
raise argparse.ArgumentTypeError(
"Invalid value for bool argument. Use true/false, yes/no or 1/0.")
return parse
def simple_dict() -> Callable:
"""
A simple dictionary format that does not require spaces or quoting.
Format: key1:value1,key2:value2,...
Supported types: bool, int, float, str (that doesn't parse as other types).
:return: A method that can be used as a type in argparse.
"""
def parse(dict_str: str):
def _parse(value: str):
if value.lower() == "true":
return True
if value.lower() == "false":
return False
if value.isdigit() or (value.startswith('-') and value[1:].isdigit()):
return int(value)
try:
return float(value)
except:
return 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,...")
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 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_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 or "
"the source."
"Default: %(default)s.")
rerank_params.add_argument("--isometric-alpha",
required=False,
type=float_greater_or_equal(0.0),
default=0.5,
help="Alpha factor used for reranking (--isometric-[ratio/diff]) nbest list. "
"Requires optimization on dev set."
"Default: %(default)s.")
rerank_params.add_argument("--output", "-o", default=None, help="File to write output to. Default: STDOUT.")
rerank_params.add_argument("--output-best",
action="store_true",
help="Output only the best hypothesis from each nbest list.")
rerank_params.add_argument("--output-best-non-blank",
action="store_true",
help="When outputting only the best hypothesis (--output-best) and the best hypothesis "
"is a blank line, output following non-blank best from the nbest list.")
rerank_params.add_argument("--output-reference-instead-of-blank",
action="store_true",
help="When outputting only the best hypothesis (--output-best) and the best hypothesis "
"is a blank line, output the reference instead.")
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, is_for_block_lexicon: bool = False):
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.")
if not is_for_block_lexicon:
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, is_for_block_lexicon: bool = False):
lexicon_params = params.add_argument_group("I/O")
if is_for_block_lexicon:
input_help = "A text file with tokens that shall be blocked. All token must be in the model vocabulary."
else:
input_help = "Probabilistic lexicon (fast_align format) to build top-k lexicon from."
lexicon_params.add_argument("--input", "-i", required=True,
help=input_help)
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('--quiet-secondary-workers', '-qsw',
default=False,
action="store_true",
help='Suppress console logging for secondary workers in distributed training.')
logging_params.add_argument('--no-logfile',
default=False,
action="store_true",
help='Suppress file logging')
log_levels = ['INFO', 'DEBUG', 'ERROR']
logging_params.add_argument('--loglevel', '--log-level',
default='INFO',
choices=log_levels,
help='Log level. Default: %(default)s.')
logging_params.add_argument('--loglevel-secondary-workers',
default='INFO',
choices=log_levels,
help='Console log level for secondary workers. Default: %(default)s.')
def add_quantize_args(params):
params = params.add_argument_group('Quantization')
params.add_argument('--model', '-m',
required=True,
help=f'Model (directory) to quantize in place. "{C.PARAMS_BEST_NAME}" will be replaced with a '
f'quantized version and "{C.CONFIG_NAME}" will be updated with the new dtype. The '
'original files will be backed up with suffixes indicating the starting dtype (e.g., '
f'"{C.PARAMS_BEST_NAME}.{C.DTYPE_FP32}" and "{C.CONFIG_NAME}.{C.DTYPE_FP32}").')
params.add_argument('--dtype',
default=C.DTYPE_FP16,
choices=[C.DTYPE_BF16, C.DTYPE_FP16, C.DTYPE_FP32],
help='Target data type for quantization. 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('--source-factors-use-source-vocab',
required=False,
nargs='+',
type=bool_str(),
default=[],
help='List of bools signaling whether to use the source vocabulary for the source factors. '
'If empty (default) each factor has its own vocabulary.')
params.add_argument('--target-factors', '-tf',
required=False,
nargs='+',
type=regular_file(),
default=[],
help='File(s) containing additional token-parallel target-side factors. Default: %(default)s.')
params.add_argument('--target-factors-use-target-vocab',
required=False,
nargs='+',
type=bool_str(),
default=[],
help='List of bools signaling whether to use the target vocabulary for the target factors. '
'If empty (default) each factor has its own vocabulary.')
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.')
params.add_argument('--validation-target-factors', '-vtf',
required=False,
nargs='+',
type=regular_file(),
default=[],
help='File(s) containing additional token-parallel validation target side factors. '
'Default: %(default)s.')
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_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)
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=8,
help='Width of buckets in tokens. Default: %(default)s.')
params.add_argument('--bucket-scaling',
action='store_true',
help='Scale source/target buckets based on length ratio to reduce padding. Default: '
'%(default)s.')
params.add_argument(C.TRAINING_ARG_MAX_SEQ_LEN,
type=multiple_values(num_values=2, greater_or_equal=1),
default=(95, 95),
help='Maximum sequence length in tokens, not counting BOS/EOS tokens (internal max sequence '
'length is X+1). Use "x:x" to specify separate values for src&tgt. Default: %(default)s.')
def add_process_pool_args(params):
params.add_argument('--max-processes',
type=int_greater_or_equal(1),
default=1,
help='Process the shards in parallel using max-processes processes.')
def add_prepare_data_cli_args(params):
add_training_data_args(params, required=True)
add_vocab_args(params)
add_bucketing_args(params)
params.add_argument('--num-samples-per-shard',
type=int_greater_or_equal(1),
default=10000000,
help='The approximate number of samples per shard. Default: %(default)s.')
params.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.')
params.add_argument('--seed',
type=int,
default=13,
help='Random seed used that makes shard assignments deterministic. Default: %(default)s.')
params.add_argument('--output', '-o',
required=True,
help='Folder where the prepared and possibly sharded data is written to.')
add_logging_args(params)
add_process_pool_args(params)
def add_device_args(params):
device_params = params.add_argument_group("Device parameters")
device_params.add_argument('--device-id',
type=int_greater_or_equal(0),
default=0,
help='GPU to use. 0 translates to "cuda:0", etc. When running in distributed mode '
'(--dist), each process\'s device is set automatically. Default: %(default)s.')
device_params.add_argument('--use-cpu',
action='store_true',
help='Use CPU device instead of GPU.')
device_params.add_argument('--env',
help='List of environment variables to be set before importing PyTorch. Separated by '
'",", e.g. --env=OMP_NUM_THREADS=1,PYTORCH_JIT=0 etc.')
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('--target-factor-vocabs',
required=False,
nargs='+',
type=regular_file(),
default=[],
help='Existing target 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=8,
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('--ignore-extra-params',
action="store_true",
default=False,
help="Allow extra 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 decoder. Default: %(default)s. "
"'ssru_transformer' uses Simpler Simple Recurrent Units (Kim et al, 2019) "
"as replacement for self-attention layers.")
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.')
# 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-feed-forward-use-glu',
action='store_true',
default=False,
help='Use Gated Linear Units in transformer feed forward networks (Daupin et al. 2016, '
'arxiv.org/abs/1612.08083; Shazeer 2020, arxiv.org/abs/2002.05202). Default: '
'%(default)s.')
model_params.add_argument('--transformer-activation-type',
type=multiple_values(num_values=2, greater_or_equal=None, data_type=str),
default=(C.RELU, C.RELU),
help='Type of activation to use for each feed forward layer. Use "x:x" to specify '
'different values for encoder & decoder. Supported: {}. Default: '
'%(default)s.'.format(' '.join(C.TRANSFORMER_ACTIVATION_TYPES)))
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('--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}."
" 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('--target-factors-num-embed',
type=int,
nargs='+',
default=[],
help='Embedding size for additional target factors. '
'You must provide as many dimensions as '
'(validation) target factor files. Default: %(default)s.')
model_params.add_argument('--source-factors-combine', '-sfc',
choices=C.FACTORS_COMBINE_CHOICES,
default=[C.FACTORS_COMBINE_SUM],
nargs='+',
help='How to combine source factors. Can be either one value which will be applied to '
'all source factors, or a list of values. Default: %(default)s.')
model_params.add_argument('--target-factors-combine', '-tfc',
choices=C.FACTORS_COMBINE_CHOICES,
default=[C.FACTORS_COMBINE_SUM],
nargs='+',
help='How to combine target factors. Can be either one value which will be applied to '
'all target factors, or a list of values. Default: %(default)s.')
model_params.add_argument('--source-factors-share-embedding',
type=bool_str(),
nargs='+',
default=[False],
help='Share the embeddings with the source language. '
'Can be either one value which will be applied '
'to all source factors, or a list of values. Default: %(default)s.')
model_params.add_argument('--target-factors-share-embedding',
type=bool_str(),
nargs='+',
default=[False],
help='Share the embeddings with the target language. '
'Can be either one value which will be applied '
'to all target factors, or a list of values. Default: %(default)s.')
model_params.add_argument('--weight-tying-type',
default=C.WEIGHT_TYING_SRC_TRG_SOFTMAX,
choices=C.WEIGHT_TYING_TYPES,
help='The type of weight tying. source embeddings=src, target embeddings=trg, '
'target softmax weight matrix=softmax. Default: %(default)s.')
model_params.add_argument('--dtype', default=C.DTYPE_FP32, choices=[C.DTYPE_FP32, C.DTYPE_FP16],
help="Data type.")
add_clamp_to_dtype_arg(model_params)
model_params.add_argument('--amp',
action='store_true',
help='Use PyTorch automatic mixed precision (AMP) to run compatible operations in '
'float16 mode instead of float32.')
model_params.add_argument('--apex-amp',
action='store_true',
help='Use NVIDIA Apex automatic mixed precision (AMP) to run the entire model in float16 '
'mode with float32 master weights and dynamic loss scaling. This is faster than '
'PyTorch AMP with some additional risk and requires installing Apex: '
'https://github.com/NVIDIA/apex')
model_params.add_argument('--neural-vocab-selection',
type=str,
default=None,
choices=C.NVS_TYPES,
help='When enabled the model contains a neural vocabulary selection model that restricts '
'the target output vocabulary to speed up inference.'
'logit_max: predictions are made per source token and combined by max pooling.'
'eos: the prediction is based on the hidden representation of the <eos> token.')
model_params.add_argument('--neural-vocab-selection-block-loss',
action='store_true',
help='When enabled, gradients for NVS are blocked from propagating back to the encoder. '
'This means that NVS learns to work with the main model\'s representations but '
'does not influence its training.')
def add_batch_args(params, default_batch_size=4096, default_batch_type=C.BATCH_TYPE_WORD):
params.add_argument('--batch-size', '-b',
type=int_greater_or_equal(1),
default=default_batch_size,
help='Mini-batch size per process. Depending on --batch-type, this either refers to words or '
'sentences. The effective batch size (update size) is num_processes * batch_size * '
'update_interval. Default: %(default)s.')
params.add_argument('--batch-type',
type=str,
default=default_batch_type,
choices=C.BATCH_TYPES,
help='sentence: each batch contains exactly X sentences. '
'word: each batch contains approximately X target words. '
'max-word: each batch contains at most X target words. '
'Default: %(default)s.')
params.add_argument('--batch-sentences-multiple-of',
type=int,
default=8,
help='For word and max-word batching, guarantee that each batch contains a multiple of X '
'sentences. For word batching, round up or down to nearest multiple. For max-word '
'batching, always round down. Default: %(default)s.')
params.add_argument('--update-interval',
type=int,
default=1,
help='Accumulate gradients over X batches for each model update. Set a value higher than 1 to '
'simulate large batches (ex: batch_size 2560 with update_interval 4 gives effective batch '
'size 10240). Default: %(default)s.')
def add_nvs_train_parameters(params):
params.add_argument(
'--bow-task-weight',
type=float_greater_or_equal(0.0),
default=1.0,
help=
'The weight of the auxiliary Bag-of-word (BOW) loss when --neural-vocab-selection is enabled. Default %(default)s.'
)
params.add_argument(
'--bow-task-pos-weight',
type=float_greater_or_equal(0.0),
default=10,
help='The weight of the positive class (the set of words present on the target side) for the BOW loss '
'when --neural-vocab-selection is set as x * num_negative_class / num_positive_class where x is the '
'--bow-task-pos-weight. Higher values will bias more towards recall, resulting in larger vocabularies '
'at test time trading off larger vocabularies for higher translation quality. 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('--label-smoothing',
default=0.1,
type=float,
help='Smoothing constant for label smoothing. Default: %(default)s.')
train_params.add_argument('--label-smoothing-impl',
default='mxnet',
choices=['mxnet', 'fairseq', 'torch'],
help='Choose label smoothing implementation. Default: %(default)s. '
'`torch` requires PyTorch 1.10.')
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.')
add_nvs_train_parameters(train_params)
train_params.add_argument('--target-factors-weight',
type=float,
nargs='+',
default=[1.0],
help='Weights of target factor losses. If one value is given, it applies to all '
'secondary target factors. For multiple values, the number of weights given has '
'to match the number of target factors. 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(C.TRAIN_ARGS_CHECKPOINT_INTERVAL,
type=int_greater_or_equal(1),
default=4000,
help='Checkpoint and evaluate every x updates (update-interval * batches). '
'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('--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('--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('--max-num-checkpoint-not-improved',
type=int,
default=None,
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('--checkpoint-improvement-threshold',
type=float,
default=0.,
help='Improvement in <optimized-metric> over specified number of checkpoints must exceed '
'this value to be considered actual improvement. 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('--transformer-dropout-attention',
type=multiple_values(2, data_type=float),
default=(0.1, 0.1),
help='Dropout probability for multi-head attention. Use "x:x" to specify separate '
'values for encoder & decoder. Default: %(default)s.')
train_params.add_argument('--transformer-dropout-act',
type=multiple_values(2, data_type=float),
default=(0.1, 0.1),
help='Dropout probability before activation in feed-forward block. Use "x:x" to specify '
'separate values for encoder & decoder. Default: %(default)s.')
train_params.add_argument('--transformer-dropout-prepost',
type=multiple_values(2, data_type=float),
default=(0.1, 0.1),
help='Dropout probability for pre/postprocessing blocks. Use "x:x" to specify separate '
'values for encoder & decoder. Default: %(default)s.')
train_params.add_argument('--optimizer',
default=C.OPTIMIZER_ADAM,
choices=C.OPTIMIZERS,
help='SGD update rule. Default: %(default)s.')
train_params.add_argument('--optimizer-betas',
type=multiple_values(2, data_type=float),
default=(0.9, 0.999),
help='Beta1 and beta2 for Adam-like optimizers, specified "x:x". Default: %(default)s.')
train_params.add_argument('--optimizer-eps',
type=float_greater_or_equal(0),
default=1e-08,
help='Optimizer epsilon. Default: %(default)s.')
train_params.add_argument('--dist',
action='store_true',
help='Run in distributed training mode. When using this option, launch training with '
'`torchrun --nproc_per_node N -m sockeye.train`. Increasing the number of processes '
'multiplies the effective batch size (ex: batch_size 2560 with `--nproc_per_node 4` '
'gives effective batch size 10240).')
train_params.add_argument('--initial-learning-rate',
type=float,
default=0.0002,
help='Initial learning rate. Default: %(default)s.')
train_params.add_argument('--weight-decay',
type=float,
default=0.0,
help='Weight decay constant. Default: %(default)s.')
train_params.add_argument('--momentum',
type=float,
default=0.0,
help='Momentum constant. Default: %(default)s.')
train_params.add_argument('--gradient-clipping-threshold',
type=float,