dfrevytus commited on
Commit
fcf4287
·
verified ·
1 Parent(s): 2ba6eb8

Upload 3 files

Browse files
Files changed (3) hide show
  1. average_checkpoints.py +176 -0
  2. ted2020.tgz +3 -0
  3. test.tgz +3 -0
average_checkpoints.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Facebook, Inc. and its affiliates.
3
+ #
4
+ # This source code is licensed under the MIT license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import argparse
8
+ import collections
9
+ import os
10
+ import re
11
+
12
+ import torch
13
+
14
+ from fairseq.file_io import PathManager
15
+
16
+
17
+ def average_checkpoints(inputs):
18
+ """Loads checkpoints from inputs and returns a model with averaged weights.
19
+
20
+ Args:
21
+ inputs: An iterable of string paths of checkpoints to load from.
22
+
23
+ Returns:
24
+ A dict of string keys mapping to various values. The 'model' key
25
+ from the returned dict should correspond to an OrderedDict mapping
26
+ string parameter names to torch Tensors.
27
+ """
28
+ params_dict = collections.OrderedDict()
29
+ params_keys = None
30
+ new_state = None
31
+ num_models = len(inputs)
32
+
33
+ for fpath in inputs:
34
+ with PathManager.open(fpath, "rb") as f:
35
+ state = torch.load(
36
+ f,
37
+ map_location=(
38
+ lambda s, _: torch.serialization.default_restore_location(s, "cpu")
39
+ ),
40
+ )
41
+ # Copies over the settings from the first checkpoint
42
+ if new_state is None:
43
+ new_state = state
44
+
45
+ model_params = state["model"]
46
+
47
+ model_params_keys = list(model_params.keys())
48
+ if params_keys is None:
49
+ params_keys = model_params_keys
50
+ elif params_keys != model_params_keys:
51
+ raise KeyError(
52
+ "For checkpoint {}, expected list of params: {}, "
53
+ "but found: {}".format(f, params_keys, model_params_keys)
54
+ )
55
+
56
+ for k in params_keys:
57
+ p = model_params[k]
58
+ if isinstance(p, torch.HalfTensor):
59
+ p = p.float()
60
+ if k not in params_dict:
61
+ params_dict[k] = p.clone()
62
+ # NOTE: clone() is needed in case of p is a shared parameter
63
+ else:
64
+ params_dict[k] += p
65
+
66
+ averaged_params = collections.OrderedDict()
67
+ for k, v in params_dict.items():
68
+ averaged_params[k] = v
69
+ if averaged_params[k].is_floating_point():
70
+ averaged_params[k].div_(num_models)
71
+ else:
72
+ averaged_params[k] //= num_models
73
+ new_state["model"] = averaged_params
74
+ return new_state
75
+
76
+
77
+ def last_n_checkpoints(paths, n, update_based, upper_bound=None):
78
+ assert len(paths) == 1
79
+ path = paths[0]
80
+ if update_based:
81
+ pt_regexp = re.compile(r"checkpoint_\d+_(\d+)\.pt")
82
+ else:
83
+ pt_regexp = re.compile(r"checkpoint(\d+)\.pt")
84
+ files = PathManager.ls(path)
85
+
86
+ entries = []
87
+ for f in files:
88
+ m = pt_regexp.fullmatch(f)
89
+ if m is not None:
90
+ sort_key = int(m.group(1))
91
+ if upper_bound is None or sort_key <= upper_bound:
92
+ entries.append((sort_key, m.group(0)))
93
+ if len(entries) < n:
94
+ raise Exception(
95
+ "Found {} checkpoint files but need at least {}", len(entries), n
96
+ )
97
+ return [os.path.join(path, x[1]) for x in sorted(entries, reverse=True)[:n]]
98
+
99
+
100
+ def main():
101
+ parser = argparse.ArgumentParser(
102
+ description="Tool to average the params of input checkpoints to "
103
+ "produce a new checkpoint",
104
+ )
105
+ # fmt: off
106
+ parser.add_argument('--inputs', required=True, nargs='+',
107
+ help='Input checkpoint file paths.')
108
+ parser.add_argument('--output', required=True, metavar='FILE',
109
+ help='Write the new checkpoint containing the averaged weights to this path.')
110
+ num_group = parser.add_mutually_exclusive_group()
111
+ num_group.add_argument('--num-epoch-checkpoints', type=int,
112
+ help='if set, will try to find checkpoints with names checkpoint_xx.pt in the '
113
+ 'path specified by input, and average last this many of them.')
114
+ num_group.add_argument('--num-update-checkpoints', type=int,
115
+ help='if set, will try to find checkpoints with names checkpoint_ee_xx.pt in the path specified by'
116
+ ' input, and average last this many of them.')
117
+ num_group.add_argument('--num-best-checkpoints', type=int, default=0,
118
+ help='if set, will try to find checkpoints with names checkpoint_best_ee_xx.pt in the path specified by'
119
+ ' input, and average last this many of them.')
120
+ parser.add_argument('--checkpoint-upper-bound', type=int,
121
+ help='when using --num-epoch-checkpoints, this will set an upper bound on which epoch to use, '
122
+ 'when using --num-update-checkpoints, this will set an upper bound on which update to use'
123
+ 'e.g., with --num-epoch-checkpoints=10 --checkpoint-upper-bound=50, checkpoints 41-50 would be'
124
+ ' averaged.'
125
+ 'e.g., with --num-update-checkpoints=10 --checkpoint-upper-bound=50000, checkpoints 40500-50000 would'
126
+ ' be averaged assuming --save-interval-updates 500'
127
+ )
128
+ # fmt: on
129
+ args = parser.parse_args()
130
+ print(args)
131
+
132
+ num = None
133
+ is_update_based = False
134
+ if args.num_update_checkpoints is not None:
135
+ num = args.num_update_checkpoints
136
+ is_update_based = True
137
+ elif args.num_epoch_checkpoints is not None:
138
+ num = args.num_epoch_checkpoints
139
+
140
+ assert args.checkpoint_upper_bound is None or (
141
+ args.num_epoch_checkpoints is not None
142
+ or args.num_update_checkpoints is not None
143
+ ), "--checkpoint-upper-bound requires --num-epoch-checkpoints or --num-update-checkpoints"
144
+ assert (
145
+ args.num_epoch_checkpoints is None or args.num_update_checkpoints is None
146
+ ), "Cannot combine --num-epoch-checkpoints and --num-update-checkpoints"
147
+
148
+ if num is not None:
149
+ args.inputs = last_n_checkpoints(
150
+ args.inputs,
151
+ num,
152
+ is_update_based,
153
+ upper_bound=args.checkpoint_upper_bound,
154
+ )
155
+ print("averaging checkpoints: ", args.inputs)
156
+
157
+ if args.num_best_checkpoints > 0:
158
+ args.inputs = list(
159
+ sorted(
160
+ args.inputs,
161
+ key=lambda x: float(
162
+ os.path.basename(x).split("_")[-1].replace(".pt", "")
163
+ ),
164
+ )
165
+ )
166
+ args.inputs = args.inputs[: args.num_best_checkpoints]
167
+ for path in args.inputs:
168
+ print(os.path.basename(path))
169
+ new_state = average_checkpoints(args.inputs)
170
+ with PathManager.open(args.output, "wb") as f:
171
+ torch.save(new_state, f)
172
+ print("Finished writing averaged checkpoint to {}".format(args.output))
173
+
174
+
175
+ if __name__ == "__main__":
176
+ main()
ted2020.tgz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1db6bd5a3637c2b184d640299f3bcfac111bd48bf245327470270f05830b7f0
3
+ size 28601955
test.tgz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3f7462bca396a14f380aec4e8a0451bf4b7cccde06a7e69b9ebcfb005349608
3
+ size 409600