Loads checkpoints from inputs and returns a model with averaged weights. Args: inputs: An iterable of string paths of checkpoints to load from. Returns: A dict of string keys mapping to various values. The 'model' key from the returned dict should correspond to an Ordered
(inputs)
| 14 | |
| 15 | |
| 16 | def average_checkpoints(inputs): |
| 17 | """Loads checkpoints from inputs and returns a model with averaged weights. |
| 18 | |
| 19 | Args: |
| 20 | inputs: An iterable of string paths of checkpoints to load from. |
| 21 | |
| 22 | Returns: |
| 23 | A dict of string keys mapping to various values. The 'model' key |
| 24 | from the returned dict should correspond to an OrderedDict mapping |
| 25 | string parameter names to torch Tensors. |
| 26 | """ |
| 27 | params_dict = collections.OrderedDict() |
| 28 | params_keys = None |
| 29 | new_state = None |
| 30 | num_models = len(inputs) |
| 31 | |
| 32 | for fpath in inputs: |
| 33 | with PathManager.open(fpath, "rb") as f: |
| 34 | state = torch.load( |
| 35 | f, |
| 36 | map_location=( |
| 37 | lambda s, _: torch.serialization.default_restore_location(s, "cpu") |
| 38 | ), |
| 39 | ) |
| 40 | # Copies over the settings from the first checkpoint |
| 41 | if new_state is None: |
| 42 | new_state = state |
| 43 | |
| 44 | model_params = state["model"] |
| 45 | |
| 46 | model_params_keys = list(model_params.keys()) |
| 47 | if params_keys is None: |
| 48 | params_keys = model_params_keys |
| 49 | elif params_keys != model_params_keys: |
| 50 | raise KeyError( |
| 51 | "For checkpoint {}, expected list of params: {}, " |
| 52 | "but found: {}".format(f, params_keys, model_params_keys) |
| 53 | ) |
| 54 | |
| 55 | for k in params_keys: |
| 56 | p = model_params[k] |
| 57 | if isinstance(p, torch.HalfTensor): |
| 58 | p = p.float() |
| 59 | if k not in params_dict: |
| 60 | params_dict[k] = p.clone() |
| 61 | # NOTE: clone() is needed in case of p is a shared parameter |
| 62 | else: |
| 63 | params_dict[k] += p |
| 64 | |
| 65 | averaged_params = collections.OrderedDict() |
| 66 | for k, v in params_dict.items(): |
| 67 | averaged_params[k] = v |
| 68 | if averaged_params[k].is_floating_point(): |
| 69 | averaged_params[k].div_(num_models) |
| 70 | else: |
| 71 | averaged_params[k] //= num_models |
| 72 | new_state["model"] = averaged_params |
| 73 | return new_state |