Same as :class:`Checkpointer`, but is able to handle models in detectron & detectron2 model zoo, and apply conversions for legacy models.
| 9 | |
| 10 | |
| 11 | class DetectionCheckpointer(Checkpointer): |
| 12 | """ |
| 13 | Same as :class:`Checkpointer`, but is able to handle models in detectron & detectron2 |
| 14 | model zoo, and apply conversions for legacy models. |
| 15 | """ |
| 16 | |
| 17 | def __init__(self, model, save_dir="", *, save_to_disk=None, **checkpointables): |
| 18 | is_main_process = comm.is_main_process() |
| 19 | super().__init__( |
| 20 | model, |
| 21 | save_dir, |
| 22 | save_to_disk=is_main_process if save_to_disk is None else save_to_disk, |
| 23 | **checkpointables, |
| 24 | ) |
| 25 | if hasattr(self, "path_manager"): |
| 26 | self.path_manager = PathManager |
| 27 | else: |
| 28 | # This could only happen for open source |
| 29 | # TODO remove after upgrading fvcore |
| 30 | from fvcore.common.file_io import PathManager as g_PathManager |
| 31 | |
| 32 | for handler in PathManager._path_handlers.values(): |
| 33 | try: |
| 34 | g_PathManager.register_handler(handler) |
| 35 | except KeyError: |
| 36 | pass |
| 37 | |
| 38 | def _load_file(self, filename): |
| 39 | if filename.endswith(".pkl"): |
| 40 | with PathManager.open(filename, "rb") as f: |
| 41 | data = pickle.load(f, encoding="latin1") |
| 42 | if "model" in data and "__author__" in data: |
| 43 | # file is in Detectron2 model zoo format |
| 44 | self.logger.info("Reading a file from '{}'".format(data["__author__"])) |
| 45 | return data |
| 46 | else: |
| 47 | # assume file is from Caffe2 / Detectron1 model zoo |
| 48 | if "blobs" in data: |
| 49 | # Detection models have "blobs", but ImageNet models don't |
| 50 | data = data["blobs"] |
| 51 | data = {k: v for k, v in data.items() if not k.endswith("_momentum")} |
| 52 | return {"model": data, "__author__": "Caffe2", "matching_heuristics": True} |
| 53 | |
| 54 | loaded = super()._load_file(filename) # load native pth checkpoint |
| 55 | if "model" not in loaded: |
| 56 | loaded = {"model": loaded} |
| 57 | return loaded |
| 58 | |
| 59 | def _load_model(self, checkpoint): |
| 60 | if checkpoint.get("matching_heuristics", False): |
| 61 | self._convert_ndarray_to_tensor(checkpoint["model"]) |
| 62 | # convert weights by name-matching heuristics |
| 63 | model_state_dict = self.model.state_dict() |
| 64 | align_and_update_state_dicts( |
| 65 | model_state_dict, |
| 66 | checkpoint["model"], |
| 67 | c2_conversion=checkpoint.get("__author__", None) == "Caffe2", |
| 68 | ) |
no outgoing calls