diff --git a/NOTICE.yml b/NOTICE.yml index ed40409..d14f4f9 100644 --- a/NOTICE.yml +++ b/NOTICE.yml @@ -14,8 +14,14 @@ - 'tools/*.py' exclude: - 'dlccore/config/*.py' + - 'dlccore/config/pose/*.py' + - 'tests/config/pose/test_ctd_conditions.py' + - 'tests/config/pose/test_logger_config.py' + - 'tests/config/pose/test_runner_config.py' + - 'tests/config/pose/test_train_settings_config.py' - 'dlccore/deprecation.py' - - 'tests/config/*.py' + - 'tests/config/conftest.py' + - 'tests/config/test_*.py' - 'tools/update_license_headers.py' # Files ported from DeepLabCut keep the old header @@ -30,6 +36,11 @@ Licensed under GNU Lesser General Public License v3.0 include: - 'dlccore/config/*.py' + - 'dlccore/config/pose/*.py' + - 'tests/config/pose/test_ctd_conditions.py' + - 'tests/config/pose/test_logger_config.py' + - 'tests/config/pose/test_runner_config.py' + - 'tests/config/pose/test_train_settings_config.py' - 'dlccore/deprecation.py' - 'tests/config/*.py' - 'tools/update_license_headers.py' diff --git a/dlccore/config/__init__.py b/dlccore/config/__init__.py index 1f071ee..8d7ea68 100644 --- a/dlccore/config/__init__.py +++ b/dlccore/config/__init__.py @@ -32,6 +32,7 @@ "write_config", "get_yaml_loader", "get_yaml_dumper", + "pose", "versioning", "validation", "normalize_for_serialization", diff --git a/dlccore/config/pose/__init__.py b/dlccore/config/pose/__init__.py new file mode 100644 index 0000000..b81a926 --- /dev/null +++ b/dlccore/config/pose/__init__.py @@ -0,0 +1,110 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""The schema of DeepLabCut's PyTorch ``pytorch_config.yaml``. + +Reading, validating, migrating and writing only. Building a config from DeepLabCut's +architecture templates, the model zoo, and checking that augmentations can be built +(``DataConfig`` transforms) need DeepLabCut and stay there. +""" + +from dlccore.config.pose.ctd_conditions import ( + ConditionsConfig, + ConditionsFileConfig, + ConditionsModelConfig, + ConditionsShuffleConfig, +) +from dlccore.config.pose.data import ( + COCOLoaderConfig, + DataConfig, + DataLoaderType, + DataTransformationConfig, + DetectorDataConfig, + DLCLoaderConfig, + GenSamplingConfig, +) +from dlccore.config.pose.enums import ( + DatasetType, + DetectorType, + MethodType, + NetType, +) +from dlccore.config.pose.inference import ( + AutocastConfig, + CompileConfig, + EvaluationConfig, + InferenceConfig, + MultithreadingConfig, +) +from dlccore.config.pose.logger import ( + CSVLoggerConfig, + LoggerConfig, + LoggerType, + WandbLoggerConfig, +) +from dlccore.config.pose.metadata import PoseMetadata +from dlccore.config.pose.model import ( + DetectorModelConfig, + ModelConfig, +) +from dlccore.config.pose.paf_parameters import PAFParameters +from dlccore.config.pose.pose import ( + DetectorConfig, + PoseConfig, + TestConfig, +) +from dlccore.config.pose.runner import ( + OptimizerConfig, + RunnerConfig, + SchedulerConfig, + SnapshotCheckpointConfig, +) +from dlccore.config.pose.training import TrainSettingsConfig +from dlccore.config.pose.weight_init import WeightInitialization + +__all__ = [ + "AutocastConfig", + "COCOLoaderConfig", + "CSVLoggerConfig", + "CompileConfig", + "ConditionsConfig", + "ConditionsFileConfig", + "ConditionsModelConfig", + "ConditionsShuffleConfig", + "DLCLoaderConfig", + "DataConfig", + "DataLoaderType", + "DataTransformationConfig", + "DatasetType", + "DetectorConfig", + "DetectorDataConfig", + "DetectorModelConfig", + "DetectorType", + "EvaluationConfig", + "GenSamplingConfig", + "InferenceConfig", + "LoggerConfig", + "LoggerType", + "MethodType", + "ModelConfig", + "MultithreadingConfig", + "NetType", + "OptimizerConfig", + "PAFParameters", + "PoseConfig", + "PoseMetadata", + "RunnerConfig", + "SchedulerConfig", + "SnapshotCheckpointConfig", + "TestConfig", + "TrainSettingsConfig", + "WandbLoggerConfig", + "WeightInitialization", +] diff --git a/dlccore/config/pose/ctd_conditions.py b/dlccore/config/pose/ctd_conditions.py new file mode 100644 index 0000000..538d96a --- /dev/null +++ b/dlccore/config/pose/ctd_conditions.py @@ -0,0 +1,160 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Typed configuration for CTD (Conditional Top-Down) model conditions. + +Three subclasses cover the supported input forms: + +- ``ConditionsFileConfig`` — pre-computed predictions from a file (evaluation only) +- ``ConditionsModelConfig`` — fully resolved BU model (config path + snapshot path) + for live ``analyze_*`` inference +- ``ConditionsShuffleConfig`` — unresolved shuffle shorthand. At runtime: + - live inference → ``ConditionsModelConfig.resolve_from_conditions()`` + - evaluation → ``CondFromFile(config=..., shuffle=..., ...)`` + +Use ``ConditionsConfig.build()`` to normalise any raw input (str, Path, dict) into one +of these types. ``build()`` is pure (no filesystem access) and safe to call from Pydantic +validators. Resolution that requires the filesystem must go through +``ConditionsModelConfig.resolve_from_conditions()``. + +Context rules for ``inference.conditions`` / ``ctd_conditions``: + +- **Evaluation** accepts File and Shuffle (loads pre-computed BU predictions). +- **Live analyze** (``analyze_images`` / ``analyze_videos``) accepts Shuffle and Model + only. A predictions file path in the YAML is evaluation-only and is rejected by + ``resolve_from_conditions``. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Literal + +from dlccore.config import DLCBaseConfig + + +class ConditionsConfig(DLCBaseConfig): + """Base class for CTD conditions configuration. + + Use ``ConditionsConfig.build()`` to normalise any raw input into a typed subclass. + + Subclasses: + - ``ConditionsFileConfig`` — pre-computed predictions file (evaluation only) + - ``ConditionsModelConfig`` — resolved BU model (config + snapshot paths) + - ``ConditionsShuffleConfig`` — unresolved shuffle shorthand (resolve to Model + for live inference, or to ``CondFromFile`` for evaluation) + """ + + source: Literal["file", "model", "shuffle"] + + @classmethod + def build( + cls, + v: str | Path | dict | ConditionsConfig | None, + ) -> ConditionsFileConfig | ConditionsModelConfig | ConditionsShuffleConfig | None: + """Normalise any raw input into a typed conditions config. + + This method is pure — it never touches the filesystem. For shuffle + shorthand inputs it returns a ``ConditionsShuffleConfig`` (unresolved). + To obtain a fully resolved ``ConditionsModelConfig`` call + ``ConditionsModelConfig.resolve_from_conditions()`` at the point where + the project config is available. + + Args: + v: Raw input. Accepted forms: + - ``None`` or an existing ``ConditionsConfig`` → returned unchanged + - ``str`` / ``Path`` → ``ConditionsFileConfig`` + - ``dict`` with ``filepath`` → ``ConditionsFileConfig`` + - ``dict`` with ``config_path`` + ``snapshot_path`` → ``ConditionsModelConfig`` + - ``dict`` with ``shuffle`` → ``ConditionsShuffleConfig`` + + Returns: + A typed ``ConditionsConfig`` subclass, or ``None``. + """ + if v is None or isinstance(v, ConditionsConfig): + return v + if isinstance(v, (str, Path)): + return ConditionsFileConfig(filepath=Path(v)) + if isinstance(v, dict): + v = v.copy() + source = v.pop("source", None) + if source == "file" or (source is None and "filepath" in v): + return ConditionsFileConfig(**v) + if source == "shuffle" or (source is None and "shuffle" in v): + return ConditionsShuffleConfig(**v) + if source == "model" or "config_path" in v or "snapshot_path" in v: + return ConditionsModelConfig(**v) + raise ValueError( + "Cannot determine conditions source from dict. " + "Provide 'filepath' for a file source, " + "'config_path'+'snapshot_path' for a model source, " + "or 'shuffle' for a shuffle shorthand." + ) + raise TypeError(f"Cannot build a ConditionsConfig from {type(v).__name__!r}: {v!r}") + + +class ConditionsFileConfig(ConditionsConfig): + """Conditions loaded from a pre-computed predictions file (.h5, .json, .pickle). + + File-based conditions are for **evaluation only** (``load_conditions_for_evaluation`` + / ``CondFromFile``). They cannot be used for live ``analyze_images`` / + ``analyze_videos`` inference — use a shuffle or ``ConditionsModelConfig`` instead. + + Attributes: + filepath: Path to the predictions file. + """ + + source: Literal["file"] = "file" + filepath: Path + + +class ConditionsModelConfig(ConditionsConfig): + """Resolved config for a BU model (i.e. a snapshot ref for live inference). + + Attributes: + config_path: Path to the BU model's ``pytorch_config.yaml``. + snapshot_path: Path to the BU snapshot file. + scorer: Scorer name for the BU model. Used to look for pre-computed + conditions files on disk before running the model. + """ + + source: Literal["model"] = "model" + config_path: Path + snapshot_path: Path + scorer: str | None = None + + +class ConditionsShuffleConfig(ConditionsConfig): + """Unresolved shuffle shorthand for CTD conditions. + + Stores shuffle parameters without touching the filesystem. Resolve at runtime + when the project config is available: + + - Live BU inference: ``ConditionsModelConfig.resolve_from_conditions()`` + - Evaluation predictions file: ``CondFromFile(config=..., shuffle=..., ...)`` + + Attributes: + shuffle: The index of the BU shuffle to use for conditions. + config: Path to the DLC project ``config.yaml``. Optional — can be + injected later via ``resolve_from_conditions(config=...)``. + trainset_index: The TrainingsetFraction index. + modelprefix: The model prefix for the shuffle. + snapshot: Specific snapshot filename to use. Takes priority over + ``snapshot_index``. + snapshot_index: Index of the snapshot to use (default: -1, last). + """ + + source: Literal["shuffle"] = "shuffle" + shuffle: int + config: Path | None = None + trainset_index: int = 0 + modelprefix: str = "" + snapshot: str | None = None + snapshot_index: int | None = None diff --git a/dlccore/config/pose/data.py b/dlccore/config/pose/data.py new file mode 100644 index 0000000..ed84b7f --- /dev/null +++ b/dlccore/config/pose/data.py @@ -0,0 +1,151 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Data configuration classes for DeepLabCut pose estimation models.""" + +from enum import Enum +from typing import Literal + +from pydantic import ConfigDict, Field + +from dlccore.config import DLCBaseConfig +from dlccore.config.validation import Fraction, NonNegativeFloat, NonNegativeInt + + +class DataLoaderType(str, Enum): + DLCLoader = "DLCLoader" + COCOLoader = "COCOLoader" + + +class DLCLoaderConfig(DLCBaseConfig): + """Configuration for DeepLabCut Loader. + + Attributes: + type: Loader type identifier + config: Path to the DeepLabCut project config, or the project config itself + trainset_index: Index of the TrainingsetFraction for which to load data + shuffle: Index of the shuffle for which to load data + modelprefix: The modelprefix for the shuffle + """ + + type: Literal[DataLoaderType.DLCLoader] + config: str | dict + trainset_index: NonNegativeInt = 0 + shuffle: NonNegativeInt = 0 + modelprefix: str = "" + + +class COCOLoaderConfig(DLCBaseConfig): + """Configuration for COCO Loader. + + Attributes: + type: Loader type identifier + """ + + type: Literal[DataLoaderType.COCOLoader] + # TODO @deruyter92 2026-06-05: COCOLoader is never build from config, add config when needed + + +class DataTransformationConfig(DLCBaseConfig): + """Data transformation configuration. + + Attributes: + resize: Resize transformation configuration + longest_max_size: Maximum size for longest edge + hflip: Horizontal flip configuration + affine: Affine transformation configuration + random_bbox_transform: Random bbox transformation configuration + crop_sampling: Crop sampling configuration + hist_eq: Whether to apply histogram equalization + motion_blur: Whether to apply motion blur + covering: Covering/CoarseDropout transformation configuration + elastic_transform: Elastic transformation configuration + grayscale: Grayscale transformation configuration + gaussian_noise: Gaussian noise standard deviation + auto_padding: Auto padding configuration + normalize_images: Whether to normalize images + scale_to_unit_range: Whether to scale images to [0, 1] range + top_down_crop: Top-down crop configuration + collate: Collate function configuration + """ + + resize: dict | None = None + longest_max_size: int | dict | None = None + hflip: bool | float | dict | None = None + affine: dict | None = None + random_bbox_transform: dict | None = None + crop_sampling: dict | None = None + hist_eq: bool | dict | None = False + motion_blur: bool | dict | None = False + covering: bool | dict | None = None + elastic_transform: bool | dict | None = None + grayscale: bool | dict | None = None + gaussian_noise: bool | float | int | dict | None = None + auto_padding: dict | None = None + normalize_images: bool | dict | None = True + scale_to_unit_range: bool | dict | None = False + top_down_crop: dict | None = None + collate: dict | None = None + + +class GenSamplingConfig(DLCBaseConfig): + """Configuration for CTD models. + + Args: + keypoint_sigmas: The sigma for each keypoint. + keypoints_symmetry: Indices of symmetric keypoints (e.g. left/right eye) + jitter_prob: The probability of applying jitter. Jitter error is defined as + a small displacement from the GT keypoint. + swap_prob: The probability of applying a swap error. Swap error represents + a confusion between the same or similar parts which belong to different + persons. + inv_prob: The probability of applying an inversion error. Inversion error + occurs when a pose estimation model is confused between semantically + similar parts that belong to the same instance. + miss_prob: The probability of applying a miss error. Miss error represents a + large displacement from the GT keypoint position. + """ + + model_config = ConfigDict(frozen=True) + + keypoint_sigmas: NonNegativeFloat | list[NonNegativeFloat] = 0.1 + keypoints_symmetry: list[tuple[int, int]] | None = None + jitter_prob: Fraction = 0.16 + swap_prob: Fraction = 0.08 + inv_prob: Fraction = 0.03 + miss_prob: Fraction = 0.10 + + +class DetectorDataConfig(DLCBaseConfig): + """Data configuration for object-detector training (no pose-only fields).""" + + colormode: Literal["RGB"] = "RGB" + inference: DataTransformationConfig | None = None + train: DataTransformationConfig | None = None + + +class DataConfig(DLCBaseConfig): + """Complete data configuration. + + Attributes: + bbox_margin: Bounding box margin for top-down models + colormode: Color mode for images (e.g., 'RGB', 'BGR') + gen_sampling: Generation sampling configuration + inference: Inference data configuration + train: Training data configuration + loader: Data loader configuration + """ + + bbox_margin: NonNegativeInt = 25 + colormode: Literal["RGB"] = "RGB" # Docs state that it should never be changed to BGR + gen_sampling: GenSamplingConfig | None = None + inference: DataTransformationConfig | None = None + train: DataTransformationConfig | None = None + loader: DLCLoaderConfig | COCOLoaderConfig | None = Field(default=None, discriminator="type") diff --git a/dlccore/config/pose/enums.py b/dlccore/config/pose/enums.py new file mode 100644 index 0000000..85e5df6 --- /dev/null +++ b/dlccore/config/pose/enums.py @@ -0,0 +1,95 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +from __future__ import annotations + +from enum import Enum + +_LEGACY_NET_TYPE_ALIASES = { + "dlcrnet_ms5": "dlcrnet_stride16_ms5", +} +_TOP_DOWN_PREFIX = "top_down_" + + +class MethodType(str, Enum): + """Enumeration of pose estimation method types.""" + + BOTTOM_UP = "bu" + TOP_DOWN = "td" + CONDITIONAL_TOP_DOWN = "ctd" + + +class NetType(str, Enum): + """Enumeration of network architecture types as stored in configs. + + Note: + Aliases (e.g. ``top_down_resnet_50``) are user-facing names that map to + a canonical member plus an optional top-down flag. See ``alias``, + ``from_alias``, and ``available_aliases`` + """ + + RESNET_50 = "resnet_50" + RESNET_101 = "resnet_101" + + HRNET_W18 = "hrnet_w18" + HRNET_W32 = "hrnet_w32" + HRNET_W48 = "hrnet_w48" + + CSPNEXT_S = "cspnext_s" + CSPNEXT_M = "cspnext_m" + CSPNEXT_X = "cspnext_x" + + DEKR_W18 = "dekr_w18" + DEKR_W32 = "dekr_w32" + DEKR_W48 = "dekr_w48" + + CTD_COAM_W32 = "ctd_coam_w32" + CTD_COAM_W48 = "ctd_coam_w48" + CTD_COAM_W48_HUMAN = "ctd_coam_w48_human" + CTD_PRENET_HRNET_W32 = "ctd_prenet_hrnet_w32" + CTD_PRENET_HRNET_W48 = "ctd_prenet_hrnet_w48" + CTD_PRENET_RTMPOSE_S = "ctd_prenet_rtmpose_s" + CTD_PRENET_RTMPOSE_M = "ctd_prenet_rtmpose_m" + CTD_PRENET_RTMPOSE_X = "ctd_prenet_rtmpose_x" + CTD_PRENET_RTMPOSE_X_HUMAN = "ctd_prenet_rtmpose_x_human" + + DLCRNET_STRIDE16_MS5 = "dlcrnet_stride16_ms5" + DLCRNET_STRIDE32_MS5 = "dlcrnet_stride32_ms5" + + RTMPOSE_S = "rtmpose_s" + RTMPOSE_M = "rtmpose_m" + RTMPOSE_X = "rtmpose_x" + + ANIMALTOKENPOSE_BASE = "animaltokenpose_base" + + @classmethod + def from_alias(cls, label: str) -> tuple[NetType, bool]: + """Parse user-facing / legacy name → (canonical enum, top_down).""" + label = _LEGACY_NET_TYPE_ALIASES.get(label, label) + label_has_td_prefix = False + if label.startswith(_TOP_DOWN_PREFIX): + label = label.removeprefix(_TOP_DOWN_PREFIX) + label_has_td_prefix = True + return cls(label), label_has_td_prefix + + +class DetectorType(str, Enum): + """Enumeration of detector types.""" + + SSDLITE = "ssdlite" + FASTERRCNN_RESNET50_FPN_V2 = "fasterrcnn_resnet50_fpn_v2" + FASTERRCNN_MOBILENET_V3_LARGE_FPN = "fasterrcnn_mobilenet_v3_large_fpn" + + +class DatasetType(str, Enum): + """Enumeration of dataset types.""" + + # TODO @deruyter92 2026-02-05: Add other dataset types as needed. + MULTIANIMAL_IMGAUG = "multi-animal-imgaug" diff --git a/dlccore/config/pose/inference.py b/dlccore/config/pose/inference.py new file mode 100644 index 0000000..1115fe7 --- /dev/null +++ b/dlccore/config/pose/inference.py @@ -0,0 +1,110 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Inference configuration classes for DeepLabCut pose estimation models.""" + +from typing import Any, Literal + +from pydantic import Field, field_validator + +from dlccore.config import DLCBaseConfig +from dlccore.config.pose.ctd_conditions import ( + ConditionsConfig, + ConditionsFileConfig, + ConditionsModelConfig, + ConditionsShuffleConfig, +) + + +class MultithreadingConfig(DLCBaseConfig): + """Multithreading configuration for inference. + + Attributes: + enabled: Whether multithreading is enabled + queue_length: Length of the processing queue + timeout: Timeout for processing tasks + """ + + enabled: bool = True + queue_length: int = 4 + timeout: float = 30.0 + + +class CompileConfig(DLCBaseConfig): + """Model compilation configuration for inference optimization. + + Attributes: + enabled: Whether compilation is enabled + mode: Compilation mode + """ + + enabled: bool = False + backend: str = "inductor" + + +class AutocastConfig(DLCBaseConfig): + """Automatic mixed precision configuration. + + Attributes: + enabled: Whether autocast is enabled + dtype: Data type for autocast (float16, bfloat16) + """ + + enabled: bool = False + + +class EvaluationConfig(DLCBaseConfig): + """Configuration for evaluation metrics computation. + + Attributes: + pcutoff: Confidence threshold for RMSE computation. Can be: + - float: Single threshold for all bodyparts + - list[float]: One value per bodypart (and unique bodypart if any) + - dict[str, float]: Mapping bodypart names to thresholds + comparison_bodyparts: Subset of bodyparts to compute metrics for. + Can be "all", None (all bodyparts), or a list of bodypart names. + per_keypoint_evaluation: Whether to compute train and test RMSE + for each keypoint individually. + force_multi_animal: If True, use multi-animal evaluation even if + loader contains only a single animal. + """ + + mode: Literal["train", "test", "all"] = "all" + pcutoff: float | list[float] | dict[str, float] = 0.6 + comparison_bodyparts: Literal["all"] | list[str] | None = "all" + per_keypoint_evaluation: bool = False + force_multi_animal: bool = False + + +class InferenceConfig(DLCBaseConfig): + """Complete inference configuration. + + Attributes: + multithreading: Multithreading configuration + compile: Compilation configuration + autocast: Autocast configuration + conditions: Conditions for conditional models (CTD). File configs are + evaluation-only; Shuffle/Model are used for live analyze. + snapshot: Snapshot(s) to use for inference + eval: Evaluation configuration + """ + + multithreading: MultithreadingConfig = Field(default_factory=MultithreadingConfig) + compile: CompileConfig = Field(default_factory=CompileConfig) + autocast: AutocastConfig = Field(default_factory=AutocastConfig) + conditions: ConditionsModelConfig | ConditionsFileConfig | ConditionsShuffleConfig | None = None + snapshot: int | str | list[int] | None = None + eval: EvaluationConfig = Field(default_factory=EvaluationConfig) + output_dir: str | None = None + + @field_validator("conditions", mode="before") + @classmethod + def _normalize_conditions(cls, v: Any) -> Any: + return ConditionsConfig.build(v) diff --git a/dlccore/config/pose/logger.py b/dlccore/config/pose/logger.py new file mode 100644 index 0000000..ffe33e5 --- /dev/null +++ b/dlccore/config/pose/logger.py @@ -0,0 +1,121 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Logger configuration classes for DeepLabCut training runs.""" + +from __future__ import annotations + +from enum import Enum +from typing import Any, ClassVar, Literal + +from pydantic import field_validator, model_validator + +from dlccore.config import DLCBaseConfig + + +class LoggerType(str, Enum): + WandbLogger = "WandbLogger" + CSVLogger = "CSVLogger" + + +class LoggerConfig(DLCBaseConfig): + """Base configuration for all loggers. + + Attributes: + type: The type of logger to use (WandbLogger or CSVLogger) + """ + + type: str + + +class WandbLoggerConfig(LoggerConfig): # + """Configuration for Weights & Biases (wandb) logger. + + This logger tracks experiments and logs data to Weights & Biases. + Refer to: https://docs.wandb.ai/guides for more information. + + Notes: + Different config versions might have top-level WandB options instead of + wandb_kwargs. Unknown top-level fields are scooped into wandb_kwargs. + + Attributes: + type: Logger type (should be 'WandbLogger') + project_name: The name of the wandb project + run_name: The name of the wandb run + image_log_interval: How often train/test images are logged in epochs + (if None, train/test inputs are never logged) + model: The model architecture to log + train_folder: The path of the folder containing training files. + wandb_kwargs: Additional keyword arguments to pass to wandb.init + """ + + # These options are reserved since they are explicitly passed to wandb.init (from `project_name` and `run_name`) + _FORBIDDEN_WANDB_KWARGS: ClassVar[frozenset[str]] = frozenset({"project", "name"}) + + type: Literal[LoggerType.WandbLogger] + project_name: str = "deeplabcut" + run_name: str = "tmp" + image_log_interval: int | None = None + model: dict | None = None + train_folder: str | None = None + wandb_kwargs: dict | None = None + + @model_validator(mode="before") + @classmethod + def scoop_extra_wandb_kwargs(cls, data: Any) -> Any: + """Move unknown top-level keys into ``wandb_kwargs``""" + if not isinstance(data, dict): + return data + + data = dict(data) + known = set(cls.model_fields) | set(cls._alias_map()) + provided = set(data) + extras = {key: data.pop(key) for key in provided - known} + if not extras: + return data + + nested = data.get("wandb_kwargs") or {} + if not isinstance(nested, dict): + raise ValueError("wandb_kwargs must be a dictionary when provided") + + overlap = set(extras) & set(nested) + if overlap: + raise ValueError(f"Duplicate wandb.init options at top-level and in wandb_kwargs: {sorted(overlap)}") + + data["wandb_kwargs"] = {**nested, **extras} + return data + + @field_validator("wandb_kwargs") + @classmethod + def validate_wandb_kwargs(cls, v: dict | None) -> dict | None: + """Reject nested keys that collide with reserved wandb.init options.""" + if not v: + return v + if set(v) & cls._FORBIDDEN_WANDB_KWARGS: + raise ValueError( + f"wandb_kwargs cannot include any of the reserved options: {sorted(cls._FORBIDDEN_WANDB_KWARGS)}" + ) + return v + + +class CSVLoggerConfig(LoggerConfig): # + """Configuration for CSV logger. + + This logger saves training stats and metrics to a CSV file. + + Attributes: + type: Logger type (should be 'CSVLogger') + train_folder: The path of the folder containing training files. + log_filename: The name of the file in which to store training stats + """ + + type: Literal[LoggerType.CSVLogger] + train_folder: str = "" + log_filename: str = "learning_stats.csv" diff --git a/dlccore/config/pose/metadata.py b/dlccore/config/pose/metadata.py new file mode 100644 index 0000000..5355f2a --- /dev/null +++ b/dlccore/config/pose/metadata.py @@ -0,0 +1,84 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +from pathlib import Path + +from pydantic import Field +from typing_extensions import Self + +from dlccore.config import DLCBaseConfig, ProjectConfig +from dlccore.config.validation import UniqueStrList + + +# TODO @deruyter92 2026-06-08: This is duplicated from ProjectConfig. Note that field names are misaligned! +# Once field names are aligned (in v1), we should merge these ProjectConfig subsets. +class PoseMetadata(DLCBaseConfig): + project_path: Path | None = None + pose_config_path: Path | None = None + bodyparts: UniqueStrList = Field(default_factory=list) + unique_bodyparts: UniqueStrList = Field(default_factory=list, json_schema_extra={"aliases": ["uniquebodyparts"]}) + individuals: UniqueStrList = Field(default_factory=lambda: ["individual_1"]) + + # TODO @deruyter92 2026-06-09: Nullable field to support old configs with empty identity field -> fix in v1 + with_identity: bool | None = Field(default=None, json_schema_extra={"aliases": ["identity"]}) + + @property + def num_individuals(self) -> int: + return len(self.individuals) + + @property + def num_bodyparts(self) -> int: + return len(self.bodyparts) + + @property + def num_unique_bodyparts(self) -> int: + return len(self.unique_bodyparts) if self.unique_bodyparts is not None else 0 + + @classmethod + def build( + cls, + project_config: ProjectConfig | dict | Path | str, + *, + project_path: Path | str | None = None, + pose_config_path: Path | str | None = None, + bodyparts: list[str] | None = None, + unique_bodyparts: list[str] | None = None, + individuals: list[str] | None = None, + with_identity: bool | None = None, + ) -> Self: + """Get metadata from a project configuration with optional overrides""" + cfg = ProjectConfig.from_any(project_config) + + # Conversions for diverging fields in ProjectConfig + cfg_bodyparts = cfg.bodyparts_list + cfg_unique_bodyparts = cfg.uniquebodyparts + cfg_with_identity = cfg.identity + + return cls( + project_path=project_path if project_path is not None else cfg.project_path, + pose_config_path=pose_config_path if pose_config_path is not None else cfg.pose_config_path, + bodyparts=bodyparts if bodyparts is not None else cfg_bodyparts, + unique_bodyparts=unique_bodyparts if unique_bodyparts is not None else cfg_unique_bodyparts, + individuals=individuals if individuals is not None else cfg.individuals, + with_identity=with_identity if with_identity is not None else cfg_with_identity, + ) + + # NOTE @deruyter92 2026-06-12 + # This serves as a replacement for pose_estimation_pytorch.config.make_basic_project_config. + # It can safely be removed when we stop supporting that API. Prefer PoseMetadata(..) instead. + def to_dict_legacy(self) -> dict: + return dict( + project_path=self.project_path, + multianimalproject=self.num_individuals > 1, + bodyparts=self.bodyparts if self.num_individuals <= 1 else "MULTI!", + multianimalbodyparts=self.bodyparts if self.num_individuals > 1 else None, + uniquebodyparts=[], + individuals=self.individuals, + ) diff --git a/dlccore/config/pose/model.py b/dlccore/config/pose/model.py new file mode 100644 index 0000000..378b682 --- /dev/null +++ b/dlccore/config/pose/model.py @@ -0,0 +1,56 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Model configuration class for DeepLabCut pose estimation models.""" + +from pydantic import Field + +from dlccore.config import DLCBaseConfig +from dlccore.config.validation import DefaultIfNone, Fraction + + +class ModelConfig(DLCBaseConfig): + """Complete model configuration. + + Attributes: + backbone: Backbone configuration + backbone_output_channels: Number of output channels from backbone + heads: Dictionary of head configurations by name + neck: Neck configuration + pose_model: Pose model configuration + """ + + backbone: dict = Field(default_factory=dict) + heads: dict[str, dict] = Field(default_factory=dict) + backbone_output_channels: int | None = None + neck: dict | None = None + pose_model: dict | None = None + + +class DetectorModelConfig(DLCBaseConfig): + """Configuration for detector models + + Attributes: + type: Type of detector model (e.g., FasterRCNN) + freeze_bn_stats: Whether to freeze batch normalization statistics + freeze_bn_weights: Whether to freeze batch normalization weights + variant: Specific variant of the detector model + box_score_thresh: The score below which the detector discards proposals + internally. ``null`` is normalized to the default. The value is + deliberately permissive, as raising this value silently drops + detections. Note the distinction with ``bboxes_pcutoff`` in the + project config, which is the cutoff used to *plot* bounding boxes. + """ + + type: str = "" + freeze_bn_stats: bool = False + freeze_bn_weights: bool = False + variant: str | None = None + box_score_thresh: DefaultIfNone[Fraction] = 0.01 diff --git a/dlccore/config/pose/paf_parameters.py b/dlccore/config/pose/paf_parameters.py new file mode 100644 index 0000000..abcc584 --- /dev/null +++ b/dlccore/config/pose/paf_parameters.py @@ -0,0 +1,20 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +from pydantic import Field + +from dlccore.config import DLCBaseConfig +from dlccore.config.validation import NonNegativeInt + + +class PAFParameters(DLCBaseConfig): + paf_graph: list[list[NonNegativeInt]] = Field(default_factory=list) + num_limbs: NonNegativeInt = 0 + paf_edges_to_keep: list[NonNegativeInt] = Field(default_factory=list) diff --git a/dlccore/config/pose/pose.py b/dlccore/config/pose/pose.py new file mode 100644 index 0000000..f250277 --- /dev/null +++ b/dlccore/config/pose/pose.py @@ -0,0 +1,202 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Main pose configuration class for DeepLabCut pose estimation models.""" + +from __future__ import annotations + +import logging +from pathlib import Path + +from pydantic import Field, field_validator, model_validator +from typing_extensions import Self + +from dlccore.config import DLCBaseConfig, DLCVersionedConfig +from dlccore.config.validation import Fraction, NonNegativeInt, UniqueStrList +from dlccore.config.versioning import register_migration +from dlccore.config.pose.data import DataConfig, DetectorDataConfig +from dlccore.config.pose.enums import DatasetType, MethodType, NetType +from dlccore.config.pose.inference import InferenceConfig +from dlccore.config.pose.logger import ( + CSVLoggerConfig, + WandbLoggerConfig, +) +from dlccore.config.pose.metadata import PoseMetadata +from dlccore.config.pose.model import ( + DetectorModelConfig, + ModelConfig, +) +from dlccore.config.pose.runner import RunnerConfig +from dlccore.config.pose.training import TrainSettingsConfig + +logger = logging.getLogger(__name__) + + +class DetectorConfig(DLCBaseConfig): + model: DetectorModelConfig + device: str = "auto" + data: DetectorDataConfig | None = None + runner: RunnerConfig | None = None + train_settings: TrainSettingsConfig | None = None + inference: InferenceConfig = Field(default_factory=InferenceConfig) + resume_training_from: str | None = None + + +class PoseConfig(DLCVersionedConfig): + """Main configuration class for DeepLabCut pose estimation models. + + This is the top-level configuration that brings together all the different + configuration domains (project, model, data, training, etc.). + + Attributes: + net_type: Network architecture type (e.g., resnet_50, hrnet_w32, dlcrnet_stride16_ms5) + method: Method type (bu=Bottom-Up, td=Top-Down, ctd=Conditional Top-Down) + device: Device configuration (auto, cpu, cuda) + project: Project configuration (skeleton, individuals, etc.) + model: Model configuration (backbone, heads, etc.) + detector: Detector configuration (for top-down models) + data: Data configuration (loaders, transforms, etc.) + training: Training configuration (runner, optimizer, etc.) + inference: Inference configuration (multithreading, compilation, etc.) + logger: Logger configuration (e.g., WandB or CSV logger) + with_center_keypoints: Whether to include center keypoints (for DEKR models) + """ + + model: ModelConfig = Field(default_factory=ModelConfig) + net_type: NetType = NetType.RESNET_50 + method: MethodType = MethodType.BOTTOM_UP + device: str = "auto" + metadata: PoseMetadata + data: DataConfig + runner: RunnerConfig + train_settings: TrainSettingsConfig + inference: InferenceConfig = Field(default_factory=InferenceConfig) + logger: CSVLoggerConfig | WandbLoggerConfig | None = Field(default=None, discriminator="type") + with_center_keypoints: bool = False + detector: DetectorConfig | None = None + resume_training_from: str | None = None + + @field_validator("net_type", mode="before") + @classmethod + def _coerce_net_type(cls, v: object) -> NetType: + if isinstance(v, NetType): + return v + net_type, _ = NetType.from_alias(str(v)) + return net_type + + @model_validator(mode="after") + def _match_top_down_crop_to_heads(self) -> Self: + """Sets the top-down crop to the input size of heads with a fixed input size. + + Repairs configs created with DeepLabCut 3.0.1 to 3.0.3 for some RTMPose models. + See https://github.com/DeepLabCut/DeepLabCut/issues/3592 + """ + for head_name, head_cfg in self.model.heads.items(): + input_size = head_cfg.get("input_size") + if input_size is None: + continue + + input_size = tuple(input_size) + for stage in ("train", "inference"): + transforms = getattr(self.data, stage) + crop = transforms.top_down_crop if transforms is not None else None + if not crop: + continue + + crop_size = (crop.get("width"), crop.get("height")) + if crop_size != input_size: + logger.warning( + f"`data.{stage}.top_down_crop` is {crop_size[0]}x{crop_size[1]}, but the " + f"'{head_name}' head expects {input_size[0]}x{input_size[1]} inputs; using " + f"{input_size[0]}x{input_size[1]} in the loaded config only. To fix the " + f"saved config, set `data.{stage}.top_down_crop` to width: {input_size[0]} " + f"and height: {input_size[1]} in this shuffle's `pytorch_config.yaml`." + ) + crop.update(width=input_size[0], height=input_size[1]) + return self + + +class TestConfig(DLCBaseConfig): + """Configuration class for DeepLabCut test/inference settings. + + This configuration is used for downstream tracking and evaluation, containing + the essential metadata about joints and network architecture. + + Attributes: + dataset: Path to the project/dataset. + dataset_type: Type of dataset (required for downstream tracking). + num_joints: Total number of joints (bodyparts + unique bodyparts). + all_joints: List of joint indices, each as a single-element list. + all_joints_names: List of joint names. + net_type: Network architecture type. + global_scale: Global scale factor for inference. + scoremap_dir: Directory for score maps. + """ + + # TODO @deruyter92 2026-02-05: Is this additional configuration really needed? + # We could aim for using the PoseConfig class or InferenceConfig class instead. + dataset: Path = Path() + num_joints: NonNegativeInt = 0 + all_joints: list[list[NonNegativeInt]] = Field(default_factory=list) + all_joints_names: UniqueStrList = Field(default_factory=list) + net_type: NetType = NetType.RESNET_50 + dataset_type: DatasetType = DatasetType.MULTIANIMAL_IMGAUG + global_scale: Fraction = 1.0 + scoremap_dir: Path = Path() + + @classmethod + def build( + cls, + pose_config: PoseConfig | dict | Path | str, + *, + dataset_type: DatasetType = DatasetType.MULTIANIMAL_IMGAUG, + scoremap_dir: Path | str = "test", + test_config_path: Path | str | None = None, + global_scale: Fraction = 1.0, + save: bool = False, + ) -> Self: + + # Needs a validated PoseConfig + cfg = PoseConfig.from_any(pose_config) + metadata = cfg.metadata + + # Build the test config + test_config = cls( + dataset=cfg.metadata.project_path, + dataset_type=dataset_type, # required for downstream tracking + num_joints=metadata.num_bodyparts + metadata.num_unique_bodyparts, + all_joints=[[i] for i in range(metadata.num_bodyparts + metadata.num_unique_bodyparts)], + all_joints_names=metadata.bodyparts + metadata.unique_bodyparts, + net_type=cfg.net_type, + global_scale=global_scale, + scoremap_dir=scoremap_dir, + ) + + # Save if needed + if save: + if test_config_path is None: + raise ValueError("test_config_path is required to save the test config.") + test_config.to_yaml(test_config_path, overwrite=True) + + return test_config + + +@register_migration(0, 1, config_type="PoseConfig") +def migrate_pose_v0_to_v1(config: dict) -> dict: + """Migrate PoseConfig from v0 to v1.""" + # Migration logic goes here, when migrating to v1. + return config + + +@register_migration(1, 0, config_type="PoseConfig") +def migrate_pose_v1_to_v0(config: dict) -> dict: + """Migrate PoseConfig from v1 back to v0.""" + # Migration logic goes here, when migrating to v1. + return config diff --git a/dlccore/config/pose/runner.py b/dlccore/config/pose/runner.py new file mode 100644 index 0000000..cb73352 --- /dev/null +++ b/dlccore/config/pose/runner.py @@ -0,0 +1,87 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Runner configuration class for DeepLabCut pose estimation models.""" + +from typing import Any + +from dlccore.config import DLCBaseConfig + + +class OptimizerConfig(DLCBaseConfig): + """Optimizer configuration. + + Attributes: + type: Optimizer type (e.g., AdamW, SGD) + params: Optimizer parameters + """ + + type: str = "" + params: dict[str, Any] | None = None + + +class SchedulerConfig(DLCBaseConfig): + """Learning rate scheduler configuration. + + Attributes: + type: Scheduler type (e.g., LRListScheduler, CosineAnnealingLR, SequentialLR) + params: Scheduler parameters + """ + + type: str = "" + params: dict[str, Any] | None = None + + +class SnapshotCheckpointConfig(DLCBaseConfig): + """Snapshot configuration for model checkpoints. + + Attributes: + max_snapshots: Maximum number of snapshots to keep + save_epochs: Interval for saving snapshots + save_optimizer_state: Whether to save optimizer state + """ + + max_snapshots: int = 5 + save_epochs: int = 25 + save_optimizer_state: bool = False + + +class RunnerConfig(DLCBaseConfig): + """Training runner configuration. + + Attributes: + type: Runner type (e.g., PoseTrainingRunner) + gpus: GPU configuration + key_metric: Key metric for evaluation + key_metric_asc: Whether key metric should be ascending + eval_interval: Evaluation interval in epochs + optimizer: Optimizer configuration + scheduler: Scheduler configuration + snapshots: Snapshot configuration + load_scheduler_state_dict: Whether to load the scheduler state when + resuming training from a snapshot + load_weights_only: Value for torch.load() weights_only parameter + """ + + type: str = "PoseTrainingRunner" + # TODO @deruyter92: Currently different configs for device are used in + # parallel. We should probably move to only 'PoseConfig.device'. This is + # kept here for backwards compatibility. + gpus: Any | None = None + device: str = "auto" # <- unused, but present in test scripts. + key_metric: str = "test.mAP" + key_metric_asc: bool = True + eval_interval: int = 10 + optimizer: OptimizerConfig | None = None + scheduler: SchedulerConfig | None = None + snapshots: SnapshotCheckpointConfig | None = None + snapshot_prefix: str | None = None + load_scheduler_state_dict: bool = True + load_weights_only: bool | None = None diff --git a/dlccore/config/pose/training.py b/dlccore/config/pose/training.py new file mode 100644 index 0000000..dd8a25d --- /dev/null +++ b/dlccore/config/pose/training.py @@ -0,0 +1,66 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Training configuration classes for DeepLabCut pose estimation models.""" + +from typing import Any + +from pydantic import Field, field_validator + +from dlccore.config import DLCBaseConfig +from dlccore.config.validation import reject_reserved_keys +from dlccore.config.pose.weight_init import WeightInitialization + +# DataLoader arguments set by DeepLabCut, mapped to the option that controls them +_RESERVED_DATALOADER_KWARGS = { + "dataset": None, + "batch_size": "batch_size", + "shuffle": None, + "collate_fn": "data.train.collate", + "num_workers": "dataloader_workers", + "pin_memory": "dataloader_pin_memory", +} + + +class TrainSettingsConfig(DLCBaseConfig): + """Training settings configuration. + + Attributes: + batch_size: Training batch size + dataloader_workers: Number of data loader workers + dataloader_pin_memory: Whether to pin memory in data loader + dataloader_kwargs: Additional keyword arguments for the training + ``torch.utils.data.DataLoader`` (e.g. ``persistent_workers``). Arguments + that DeepLabCut sets itself are reserved and cannot be given here. Omitted + from the serialized config when empty. + display_iters: Number of iterations (batches) between loss prints, counted + within each epoch + epochs: Number of training epochs + seed: Random seed for reproducibility + weight_init: Weight initialization configuration + """ + + batch_size: int = 8 + dataloader_workers: int = 0 + dataloader_pin_memory: bool = False + # Omitted when empty to keep saved configs loadable by older DeepLabCut versions + dataloader_kwargs: dict[str, Any] | None = Field(default=None, exclude_if=lambda v: not v) + display_iters: int = 500 + epochs: int = 200 + seed: int = 42 + # @TODO @deruyter92 2026-02-13: V0 pipeline uses None for default initialization + # (with ImageNet weights). We should update this to explicit WeightInitialization. + weight_init: WeightInitialization | None = None + + @field_validator("dataloader_kwargs") + @classmethod + def validate_dataloader_kwargs(cls, v: dict[str, Any] | None) -> dict[str, Any] | None: + reject_reserved_keys(v, _RESERVED_DATALOADER_KWARGS, name="dataloader_kwargs") + return v diff --git a/dlccore/config/pose/weight_init.py b/dlccore/config/pose/weight_init.py new file mode 100644 index 0000000..bcd7e83 --- /dev/null +++ b/dlccore/config/pose/weight_init.py @@ -0,0 +1,89 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Classes to configure how to initialize model weights.""" + +from __future__ import annotations + +from pathlib import Path + +from pydantic import field_validator, model_validator +from typing_extensions import Self + +from dlccore.config import DLCBaseConfig +from dlccore.config.validation import NDArrayInt + + +class WeightInitialization(DLCBaseConfig): + """Configures weights initialization when transfer learning or fine-tuning models. + + Args: + snapshot_path: The path to the snapshot used to initialize pose model weights + when training a model. + detector_snapshot_path: The path to the snapshot used to initialize detector + weights when training a model. + dataset: Optionally, the dataset on which the snapshots were trained. Required + when fine-tuning SuperAnimal models. + with_decoder: Whether to load the decoder weights as well. + memory_replay: Only when ``with_decoder=True``. Whether to train the model with + memory replay, so that it predicts all SuperAnimal (or previous project) + bodyparts. + conversion_array: The mapping from SuperAnimal (or other project, on which the + weights were trained) to project bodyparts. Required when + `with_decoder=True`. + An array [7, 0, 1] means the project has 3 bodyparts, where the 1st bodypart + corresponds to the 8th bodypart in the pretrained model, the 2nd to the 1st + and the 3rd to the 2nd (as arrays are 0-indexed). + bodyparts: Optionally, the name of each bodypart entry in the conversion array. + """ + + snapshot_path: Path | None = None + detector_snapshot_path: Path | None = None + dataset: str | None = None + with_decoder: bool = False + memory_replay: bool = False + conversion_array: NDArrayInt | None = None + bodyparts: list[str] | None = None + + @model_validator(mode="after") + def _validate_options(self) -> Self: + if self.memory_replay and not self.with_decoder: + raise ValueError( + "You cannot train a model with memory replay if you do not keep the " + "decoder layers (``with_decoder=True``), but you passed " + "`memory_replay=True` and `with_decoder=False`. Please change your " + "WeightInitialization parameters." + ) + + if self.with_decoder and self.conversion_array is None: + raise ValueError( + "You must specify a conversion_array to initialize decoder weights (``with_decoder=True``)." + ) + + if self.bodyparts is not None and self.conversion_array is None: + raise ValueError( + "Specifying bodyparts should only be done when `with_decoder=True` and" + " the conversion array is specified." + ) + + if self.conversion_array is not None and self.bodyparts is not None: + if len(self.conversion_array) != len(self.bodyparts): + raise ValueError( + f"There must be the same number of elements in the bodyparts list " + f"and conv. array; found {self.bodyparts}, {self.conversion_array}" + ) + return self + + @field_validator("snapshot_path", "detector_snapshot_path", mode="before") + @classmethod + def _coerce_null_path(cls, v): + if v is None or v == "None": + return None + return v diff --git a/pyproject.toml b/pyproject.toml index 24747d8..73b80cb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ classifiers = [ dynamic = [ "version" ] dependencies = [ "numpy>=1.22.4", - "pydantic>=2.1,<3", + "pydantic>=2.12,<3", "ruamel-yaml>=0.16", "typing-extensions", ] @@ -39,7 +39,16 @@ packages.find.include = [ "dlccore*" ] target-version = "py310" line-length = 120 # Temporary: ported from DeepLabCut. Delete when lint is done -extend-exclude = [ "dlccore/config/*.py", "dlccore/deprecation.py", "tests/config/*.py" ] +extend-exclude = [ + "dlccore/config/*.py", + "dlccore/deprecation.py", + "tests/config/conftest.py", + "tests/config/pose/test_ctd_conditions.py", + "tests/config/pose/test_logger_config.py", + "tests/config/pose/test_runner_config.py", + "tests/config/pose/test_train_settings_config.py", + "tests/config/test_*.py", +] # Pre-commit passes file names explicitly; without this, the exclusions above are ignored force-exclude = true format.docstring-code-format = true diff --git a/tests/config/pose/test_ctd_conditions.py b/tests/config/pose/test_ctd_conditions.py new file mode 100644 index 0000000..5f144ef --- /dev/null +++ b/tests/config/pose/test_ctd_conditions.py @@ -0,0 +1,121 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Typed CTD conditions config: the schema half of DeepLabCut's ``test_ctd_conditions.py``. + +Resolving conditions against a shuffle, and evaluation loading, need DeepLabCut and stay there. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from dlccore.config.pose.ctd_conditions import ( + ConditionsConfig, + ConditionsFileConfig, + ConditionsModelConfig, + ConditionsShuffleConfig, +) +from dlccore.config.pose.inference import InferenceConfig + + +def _ctd_model_conditions_config() -> ConditionsModelConfig: + return ConditionsModelConfig( + config_path=Path("/bu/pytorch_config.yaml"), + snapshot_path=Path("/bu/snapshot-best.pt"), + scorer="DLC_resnet50", + ) + + +# --- ConditionsConfig.build --------------------------------------------------- + + +@pytest.mark.parametrize( + "raw, expected_type, check", + [ + pytest.param(None, type(None), lambda c: c is None, id="none"), + pytest.param( + "/path/to/preds.h5", + ConditionsFileConfig, + lambda c: c.filepath == Path("/path/to/preds.h5"), + id="path-str", + ), + pytest.param( + Path("/path/to/preds.json"), + ConditionsFileConfig, + lambda c: c.filepath == Path("/path/to/preds.json"), + id="path-obj", + ), + pytest.param( + {"filepath": "/preds.h5"}, + ConditionsFileConfig, + lambda c: c.filepath == Path("/preds.h5"), + id="filepath-dict", + ), + pytest.param( + {"shuffle": 3}, + ConditionsShuffleConfig, + lambda c: c.shuffle == 3, + id="shuffle-dict", + ), + pytest.param( + {"shuffle": 1, "snapshot_index": -1}, + ConditionsShuffleConfig, + lambda c: c.shuffle == 1 and c.snapshot_index == -1, + id="shuffle-snapshot-index", + ), + pytest.param( + { + "config_path": "/bu/pytorch_config.yaml", + "snapshot_path": "/bu/snapshot.pt", + }, + ConditionsModelConfig, + lambda c: c.config_path == Path("/bu/pytorch_config.yaml"), + id="model-dict", + ), + pytest.param( + {"source": "shuffle", "shuffle": 9}, + ConditionsShuffleConfig, + lambda c: c.shuffle == 9, + id="explicit-source-shuffle", + ), + ], +) +def test_conditions_config_build(raw, expected_type, check): + built = ConditionsConfig.build(raw) + assert isinstance(built, expected_type) + assert check(built) + + +def test_conditions_config_build_passthrough(): + ctd_conditions = _ctd_model_conditions_config() + assert ConditionsConfig.build(ctd_conditions) is ctd_conditions + + +def test_conditions_config_build_rejects_ambiguous_dict(): + with pytest.raises(ValueError, match="Cannot determine conditions source"): + ConditionsConfig.build({"unexpected": 1}) + + +def test_conditions_config_build_rejects_unsupported_type(): + with pytest.raises(TypeError, match="Cannot build"): + ConditionsConfig.build(42) # type: ignore[arg-type] + + +# --- InferenceConfig ---------------------------------------------------------- + + +def test_inference_config_accepts_path_string(): + """Regression: bare path strings must validate (PoseConfig / YAML file form).""" + cfg = InferenceConfig(conditions="/path/to/bu_predictions.h5") + assert isinstance(cfg.conditions, ConditionsFileConfig) + assert cfg.conditions.filepath == Path("/path/to/bu_predictions.h5") diff --git a/tests/config/pose/test_logger_config.py b/tests/config/pose/test_logger_config.py new file mode 100644 index 0000000..459fdd6 --- /dev/null +++ b/tests/config/pose/test_logger_config.py @@ -0,0 +1,85 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Tests for WandbLoggerConfig validation.""" + +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +from dlccore.config.pose.logger import LoggerType, WandbLoggerConfig + + +def test_wandb_kwargs_accepts_nested_extras() -> None: + cfg = WandbLoggerConfig.from_dict( + { + "type": LoggerType.WandbLogger, + "wandb_kwargs": { + "entity": "team", + "mode": "offline", + "tags": ["a"], + "settings": {"_service_wait": 60}, + }, + } + ) + assert cfg.wandb_kwargs["entity"] == "team" + assert cfg.wandb_kwargs["settings"] == {"_service_wait": 60} + + +def test_scoops_top_level_extras_into_wandb_kwargs() -> None: + cfg = WandbLoggerConfig.from_dict( + { + "type": LoggerType.WandbLogger, + "project_name": "proj", + "group": "group_a", + "tags": ["mytag"], + } + ) + assert cfg.project_name == "proj" + assert cfg.wandb_kwargs == {"group": "group_a", "tags": ["mytag"]} + + +def test_mixed_top_level_and_nested_wandb_kwargs() -> None: + cfg = WandbLoggerConfig.from_dict( + { + "type": LoggerType.WandbLogger, + "group": "group_a", + "wandb_kwargs": {"tags": ["mytag"], "mode": "offline", "id": "run-1"}, + } + ) + assert cfg.wandb_kwargs == { + "tags": ["mytag"], + "mode": "offline", + "id": "run-1", + "group": "group_a", + } + + +def test_rejects_duplicate_top_level_and_nested() -> None: + with pytest.raises(ValidationError, match="Duplicate wandb.init options"): + WandbLoggerConfig.from_dict( + { + "type": LoggerType.WandbLogger, + "tags": ["a"], + "wandb_kwargs": {"tags": ["b"], "mode": "offline"}, + } + ) + + +@pytest.mark.parametrize("overlap_key", ["project", "name"]) +def test_wandb_kwargs_rejects_reserved_keys(overlap_key: str) -> None: + with pytest.raises(ValidationError, match="reserved options"): + WandbLoggerConfig.from_dict( + { + "type": LoggerType.WandbLogger, + "wandb_kwargs": {overlap_key: "x", "mode": "offline"}, + } + ) diff --git a/tests/config/pose/test_runner_config.py b/tests/config/pose/test_runner_config.py new file mode 100644 index 0000000..10d3600 --- /dev/null +++ b/tests/config/pose/test_runner_config.py @@ -0,0 +1,31 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Tests for RunnerConfig validation.""" + +from __future__ import annotations + +import pytest + +from dlccore.config.pose.runner import RunnerConfig + + +@pytest.mark.parametrize("value", [True, False]) +def test_accepts_load_scheduler_state_dict(value: bool) -> None: + """Regression test for #3556: the documented key was rejected as extra.""" + cfg = RunnerConfig.from_dict({"type": "PoseTrainingRunner", "load_scheduler_state_dict": value}) + assert cfg.load_scheduler_state_dict is value + assert cfg.to_dict()["load_scheduler_state_dict"] is value + + +def test_load_scheduler_state_dict_defaults_to_true() -> None: + """The default matches the fallback used when building the training runner.""" + cfg = RunnerConfig.from_dict({"type": "PoseTrainingRunner"}) + assert cfg.load_scheduler_state_dict is True diff --git a/tests/config/pose/test_train_settings_config.py b/tests/config/pose/test_train_settings_config.py new file mode 100644 index 0000000..f64ef24 --- /dev/null +++ b/tests/config/pose/test_train_settings_config.py @@ -0,0 +1,64 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/DeepLabCut +# +# Please see AUTHORS for contributors. +# https://github.com/DeepLabCut/DeepLabCut/blob/main/AUTHORS +# +# Licensed under GNU Lesser General Public License v3.0 +# +"""Tests for TrainSettingsConfig validation.""" + +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +from dlccore.config.pose.training import TrainSettingsConfig + + +def test_dataloader_kwargs_defaults_to_none() -> None: + assert TrainSettingsConfig().dataloader_kwargs is None + + +def test_old_configs_without_dataloader_kwargs_still_validate() -> None: + cfg = TrainSettingsConfig.from_dict({"batch_size": 4, "dataloader_workers": 2}) + assert cfg.dataloader_kwargs is None + + +def test_dataloader_kwargs_accepts_extra_options() -> None: + kwargs = {"persistent_workers": True, "prefetch_factor": 4} + cfg = TrainSettingsConfig.from_dict({"dataloader_workers": 2, "dataloader_kwargs": kwargs}) + assert cfg.dataloader_kwargs == kwargs + assert cfg.to_dict(normalize=True)["dataloader_kwargs"] == kwargs + + +@pytest.mark.parametrize( + ("key", "hint"), + [ + ("num_workers", "dataloader_workers"), + ("pin_memory", "dataloader_pin_memory"), + ("batch_size", "batch_size"), + ("collate_fn", "data.train.collate"), + ], +) +def test_dataloader_kwargs_rejects_options_with_a_config_field(key: str, hint: str) -> None: + with pytest.raises(ValidationError, match=f"'{key}' \\(set via `{hint}`\\)"): + TrainSettingsConfig.from_dict({"dataloader_kwargs": {key: 1}}) + + +@pytest.mark.parametrize("key", ["dataset", "shuffle"]) +def test_dataloader_kwargs_rejects_options_managed_by_deeplabcut(key: str) -> None: + with pytest.raises(ValidationError, match=f"dataloader_kwargs cannot include reserved options: '{key}'"): + TrainSettingsConfig.from_dict({"dataloader_kwargs": {key: False}}) + + +@pytest.mark.parametrize("value", [None, {}]) +def test_empty_dataloader_kwargs_is_omitted_when_saving(tmp_path, value) -> None: + cfg = TrainSettingsConfig(dataloader_kwargs=value) + assert "dataloader_kwargs" not in cfg.to_dict() + assert "dataloader_kwargs" not in cfg.to_commented_map() + cfg.to_yaml(tmp_path / "cfg.yaml") + assert "dataloader_kwargs" not in (tmp_path / "cfg.yaml").read_text() + assert TrainSettingsConfig.from_yaml(tmp_path / "cfg.yaml").dataloader_kwargs is None