|
| 1 | +# |
| 2 | +# DeepLabCut Toolbox (deeplabcut.org) |
| 3 | +# © A. & M.W. Mathis Labs |
| 4 | +# https://github.com/DeepLabCut/DeepLabCut |
| 5 | +# |
| 6 | +# Please see AUTHORS for contributors. |
| 7 | +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS |
| 8 | +# |
| 9 | +# Licensed under GNU Lesser General Public License v3.0 |
| 10 | +# |
| 11 | +"""Code to export DeepLabCut models for DLCLive inference""" |
| 12 | +import copy |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +import torch |
| 16 | + |
| 17 | +import deeplabcut.pose_estimation_pytorch.apis.utils as utils |
| 18 | +import deeplabcut.pose_estimation_pytorch.data as dlc3_data |
| 19 | +import deeplabcut.utils.auxiliaryfunctions as af |
| 20 | +from deeplabcut.pose_estimation_pytorch.runners.snapshots import Snapshot |
| 21 | +from deeplabcut.pose_estimation_pytorch.task import Task |
| 22 | + |
| 23 | + |
| 24 | +def export_model( |
| 25 | + config: str | Path, |
| 26 | + shuffle: int = 1, |
| 27 | + trainingsetindex: int = 0, |
| 28 | + snapshotindex: int | None = None, |
| 29 | + detector_snapshot_index: int | None = None, |
| 30 | + iteration: int | None = None, |
| 31 | + overwrite: bool = False, |
| 32 | + wipe_paths: bool = False, |
| 33 | + modelprefix: str | None = None, |
| 34 | +) -> None: |
| 35 | + """Export DeepLabCut models for live inference. |
| 36 | +
|
| 37 | + Saves the pytorch_config.yaml configuration, snapshot files, of the model to a |
| 38 | + directory named exported-models-pytorch within the project directory. |
| 39 | +
|
| 40 | + Args: |
| 41 | + config: Path of the project configuration file |
| 42 | + shuffle : The shuffle of the model to export. |
| 43 | + trainingsetindex: The index of the training fraction for the model you wish to |
| 44 | + export. |
| 45 | + snapshotindex: The snapshot index for the weights you wish to export. If None, |
| 46 | + uses the snapshotindex as defined in ``config.yaml``. |
| 47 | + detector_snapshot_index: Only for TD models. If defined, uses the detector with |
| 48 | + the given index for pose estimation. If None, uses the snapshotindex as |
| 49 | + defined in the project ``config.yaml``. |
| 50 | + iteration: The project iteration (active learning loop) you wish to export. If |
| 51 | + None, the iteration listed in the project config file is used. |
| 52 | + overwrite : bool, optional |
| 53 | + If the model you wish to export has already been exported, whether to |
| 54 | + overwrite. default = False |
| 55 | + wipe_paths : bool, optional |
| 56 | + Removes the actual path of your project and the init_weights from the |
| 57 | + ``pytorch_config.yaml``. |
| 58 | + modelprefix: Directory containing the deeplabcut models to use when evaluating |
| 59 | + the network. By default, the models are assumed to exist in the project |
| 60 | + folder. |
| 61 | +
|
| 62 | + Raises: |
| 63 | + ValueError: If no snapshots could be found for the shuffle. |
| 64 | + ValueError: If a top-down model is exported but no detector snapshots are found. |
| 65 | +
|
| 66 | + Examples: |
| 67 | + Export the last stored snapshot for model trained with shuffle 3: |
| 68 | + >>> import deeplabcut |
| 69 | + >>> deeplabcut.export_model( |
| 70 | + >>> "/analysis/project/reaching-task/config.yaml", |
| 71 | + >>> shuffle=3, |
| 72 | + >>> snapshotindex=-1, |
| 73 | + >>> ) |
| 74 | + """ |
| 75 | + cfg = af.read_config(str(config)) |
| 76 | + if iteration is not None: |
| 77 | + cfg["iteration"] = iteration |
| 78 | + |
| 79 | + loader = dlc3_data.DLCLoader( |
| 80 | + config=cfg, |
| 81 | + trainset_index=trainingsetindex, |
| 82 | + shuffle=shuffle, |
| 83 | + modelprefix="" if modelprefix is None else modelprefix, |
| 84 | + ) |
| 85 | + |
| 86 | + if snapshotindex is None: |
| 87 | + snapshotindex = loader.project_cfg["snapshotindex"] |
| 88 | + snapshots = utils.get_model_snapshots( |
| 89 | + snapshotindex, loader.model_folder, loader.pose_task |
| 90 | + ) |
| 91 | + |
| 92 | + if len(snapshots) == 0: |
| 93 | + raise ValueError( |
| 94 | + f"Could not find any snapshots to export in ``{loader.model_folder}`` for " |
| 95 | + f"``snapshotindex={snapshotindex}``." |
| 96 | + ) |
| 97 | + |
| 98 | + detector_snapshots = [None] |
| 99 | + if loader.pose_task == Task.TOP_DOWN: |
| 100 | + if detector_snapshot_index is None: |
| 101 | + detector_snapshot_index = loader.project_cfg["detector_snapshotindex"] |
| 102 | + detector_snapshots = utils.get_model_snapshots( |
| 103 | + detector_snapshot_index, loader.model_folder, Task.DETECT |
| 104 | + ) |
| 105 | + |
| 106 | + if len(detector_snapshots) == 0: |
| 107 | + raise ValueError( |
| 108 | + "Attempting to export a top-down pose estimation model but no detector " |
| 109 | + f"snapshots were found in ``{loader.model_folder}`` for " |
| 110 | + f"``detector_snapshot_index={detector_snapshot_index}``. You must " |
| 111 | + f"export a detector snapshot with a top-down pose estimation model." |
| 112 | + ) |
| 113 | + |
| 114 | + export_folder_name = get_export_folder_name(loader) |
| 115 | + export_dir = loader.project_path / "exported-models-pytorch" / export_folder_name |
| 116 | + export_dir.mkdir(exist_ok=True, parents=True) |
| 117 | + |
| 118 | + load_kwargs = dict(map_location="cpu", weights_only=True) |
| 119 | + for det_snapshot in detector_snapshots: |
| 120 | + detector_weights = None |
| 121 | + if det_snapshot is not None: |
| 122 | + detector_weights = torch.load(det_snapshot.path, **load_kwargs)["model"] |
| 123 | + |
| 124 | + for snapshot in snapshots: |
| 125 | + export_filename = get_export_filename(loader, snapshot, det_snapshot) |
| 126 | + export_path = export_dir / export_filename |
| 127 | + if export_path.exists() and not overwrite: |
| 128 | + continue |
| 129 | + |
| 130 | + model_cfg = copy.deepcopy(loader.model_cfg) |
| 131 | + if wipe_paths: |
| 132 | + wipe_paths_from_model_config(model_cfg) |
| 133 | + |
| 134 | + pose_weights = torch.load(snapshot.path, **load_kwargs)["model"] |
| 135 | + export_dict = dict(config=model_cfg, pose=pose_weights) |
| 136 | + if detector_weights is not None: |
| 137 | + export_dict["detector"] = detector_weights |
| 138 | + |
| 139 | + torch.save(export_dict, export_path) |
| 140 | + |
| 141 | + |
| 142 | +def get_export_folder_name(loader: dlc3_data.DLCLoader) -> str: |
| 143 | + """ |
| 144 | + Args: |
| 145 | + loader: The loader for the shuffle for which we want to export models. |
| 146 | +
|
| 147 | + Returns: |
| 148 | + The name of the folder in which exported models should be placed for a shuffle. |
| 149 | + """ |
| 150 | + return ( |
| 151 | + f"DLC_{loader.project_cfg['Task']}_{loader.model_cfg['net_type']}_" |
| 152 | + f"iteration-{loader.project_cfg['iteration']}_shuffle-{loader.shuffle}" |
| 153 | + ) |
| 154 | + |
| 155 | + |
| 156 | +def get_export_filename( |
| 157 | + loader: dlc3_data.DLCLoader, |
| 158 | + snapshot: Snapshot, |
| 159 | + detector_snapshot: Snapshot | None = None, |
| 160 | +) -> str: |
| 161 | + """ |
| 162 | + Args: |
| 163 | + loader: The loader for the shuffle for which we want to export models. |
| 164 | + snapshot: The pose model snapshot to export. |
| 165 | + detector_snapshot: The detector snapshot to export, for top-down models. |
| 166 | +
|
| 167 | + Returns: |
| 168 | + The name of the file in which the exported model should be stored. |
| 169 | + """ |
| 170 | + export_filename = get_export_folder_name(loader) |
| 171 | + if detector_snapshot is not None: |
| 172 | + export_filename += "_snapshot-detector" + detector_snapshot.uid() |
| 173 | + export_filename += "_snapshot-" + snapshot.uid() |
| 174 | + return export_filename + ".pt" |
| 175 | + |
| 176 | + |
| 177 | +def wipe_paths_from_model_config(model_cfg: dict) -> None: |
| 178 | + """ |
| 179 | + Removes all paths from the contents of the ``pytorch_config`` file. |
| 180 | +
|
| 181 | + Args: |
| 182 | + model_cfg: The model configuration to wipe. |
| 183 | + """ |
| 184 | + model_cfg["metadata"]["project_path"] = "" |
| 185 | + model_cfg["metadata"]["pose_config_path"] = "" |
| 186 | + if "weight_init" in model_cfg["train_settings"]: |
| 187 | + model_cfg["train_settings"]["weight_init"] = None |
| 188 | + if "resume_training_from" in model_cfg: |
| 189 | + model_cfg["resume_training_from"] = None |
| 190 | + if "resume_training_from" in model_cfg.get("detector", {}): |
| 191 | + model_cfg["detector"]["resume_training_from"] = None |
0 commit comments