Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion NOTICE.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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'
1 change: 1 addition & 0 deletions dlccore/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"write_config",
"get_yaml_loader",
"get_yaml_dumper",
"pose",
"versioning",
"validation",
"normalize_for_serialization",
Expand Down
110 changes: 110 additions & 0 deletions dlccore/config/pose/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
160 changes: 160 additions & 0 deletions dlccore/config/pose/ctd_conditions.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading