Skip to content

Keypoint Train Config

Bases: TrainConfig

Training configuration for keypoint detection models.

Extends :class:TrainConfig with keypoint-specific loss coefficients and metric-smoothing defaults tuned for the NLL-Cholesky keypoint head, which produces noisy per-epoch OKS metrics during early fine-tuning.

Attributes:

Name Type Description
cls_loss_coef float

Classification loss weight.

keypoint_l1_loss_coef float

L1 regression loss weight for keypoint coordinates.

keypoint_findable_loss_coef float

Loss weight for the keypoint visibility head.

keypoint_visible_loss_coef float

Loss weight for the keypoint visibility score.

keypoint_nll_loss_coef float

NLL-Cholesky loss weight. Restored to 1.0 to align with the other keypoint loss terms (keypoint_l1_loss_coef, keypoint_findable_loss_coef, keypoint_visible_loss_coef). Previously set to 0.5 to dampen OKS@75 oscillation; reverted as the under-weighting was not beneficial in practice.

smooth_alpha float

EMA smoothing factor for :class:BestModelCallback metric comparison. Overrides the :class:TrainConfig default of 0.0 (disabled) to 0.5, which balances responsiveness and noise suppression for noisy keypoint mAP curves.

skip_best_epochs int

Number of epochs to skip before checkpoint selection begins. Overrides the :class:TrainConfig default of 0 to 10 because val/keypoint_map_50_95 under the NLL-Cholesky loss is noisy in early fine-tuning and can lock checkpoint selection to a transient peak.

Source code in src/rfdetr/config.py
class KeypointTrainConfig(TrainConfig):
    """Training configuration for keypoint detection models.

    Extends :class:`TrainConfig` with keypoint-specific loss coefficients and
    metric-smoothing defaults tuned for the NLL-Cholesky keypoint head, which
    produces noisy per-epoch OKS metrics during early fine-tuning.

    Attributes:
        cls_loss_coef: Classification loss weight.
        keypoint_l1_loss_coef: L1 regression loss weight for keypoint coordinates.
        keypoint_findable_loss_coef: Loss weight for the keypoint visibility head.
        keypoint_visible_loss_coef: Loss weight for the keypoint visibility score.
        keypoint_nll_loss_coef: NLL-Cholesky loss weight. Restored to ``1.0`` to
            align with the other keypoint loss terms (``keypoint_l1_loss_coef``,
            ``keypoint_findable_loss_coef``, ``keypoint_visible_loss_coef``).
            Previously set to ``0.5`` to dampen OKS@75 oscillation; reverted as
            the under-weighting was not beneficial in practice.
        smooth_alpha: EMA smoothing factor for :class:`BestModelCallback` metric
            comparison. Overrides the :class:`TrainConfig` default of ``0.0``
            (disabled) to ``0.5``, which balances responsiveness and noise
            suppression for noisy keypoint mAP curves.
        skip_best_epochs: Number of epochs to skip before checkpoint selection begins.
            Overrides the :class:`TrainConfig` default of ``0`` to ``10`` because
            ``val/keypoint_map_50_95`` under the NLL-Cholesky loss is noisy in early
            fine-tuning and can lock checkpoint selection to a transient peak.
    """

    cls_loss_coef: float = 2.0  # TODO: verify empirically before final release; ported as-is from internal recipe.
    keypoint_l1_loss_coef: float = 1
    keypoint_findable_loss_coef: float = 1
    keypoint_visible_loss_coef: float = 1
    keypoint_nll_loss_coef: float = 1.0
    smooth_alpha: float = 0.5
    skip_best_epochs: int = Field(default=10, ge=0)

Functions

expand_paths(v) classmethod

Expand and normalize dataset/output directory paths via os.fspathexpanduserrealpath.

Source code in src/rfdetr/config.py
@field_validator("dataset_dir", "output_dir", mode="before")
@classmethod
def expand_paths(cls, v: PathLikeStr | None) -> str | None:
    """Expand and normalize dataset/output directory paths via ``os.fspath`` → ``expanduser`` → ``realpath``."""
    if v is None:
        return v
    return os.path.realpath(os.path.expanduser(os.fspath(v)))

validate_batch_size(v) classmethod

Validate batch_size is a positive integer or the literal 'auto'.

Source code in src/rfdetr/config.py
@field_validator("batch_size", mode="after")
@classmethod
def validate_batch_size(cls, v: int | Literal["auto"]) -> int | Literal["auto"]:
    """Validate batch_size is a positive integer or the literal 'auto'."""
    if v == "auto":
        return v
    if v < 1:
        raise ValueError("batch_size must be >= 1, or 'auto'.")
    return v

validate_ema_headroom(v) classmethod

Validate auto_batch_ema_headroom is in (0, 1].

Source code in src/rfdetr/config.py
@field_validator("auto_batch_ema_headroom", mode="after")
@classmethod
def validate_ema_headroom(cls, v: float) -> float:
    """Validate auto_batch_ema_headroom is in (0, 1]."""
    if not (0 < v <= 1.0):
        raise ValueError("auto_batch_ema_headroom must be in (0, 1].")
    return v

validate_eval_ema_only()

eval_ema_only has no EMA model to evaluate without use_ema=True.

Source code in src/rfdetr/config.py
@model_validator(mode="after")
def validate_eval_ema_only(self) -> "TrainConfig":
    """``eval_ema_only`` has no EMA model to evaluate without ``use_ema=True``."""
    if self.eval_ema_only and not self.use_ema:
        raise ValueError("eval_ema_only=True requires use_ema=True.")
    return self

validate_lr_scheduler_kwargs()

Reject unknown lr_scheduler_kwargs keys for the managed "step" / "cosine" presets.

Managed presets consume only min_factor and lr_drop; any other key would be silently ignored, so surface it as an error (mirroring validate_optimizer_kwargs). Explicit schedulers forward their kwargs verbatim to the constructor and are left unchecked here.

Source code in src/rfdetr/config.py
@model_validator(mode="after")
def validate_lr_scheduler_kwargs(self) -> "TrainConfig":
    """Reject unknown ``lr_scheduler_kwargs`` keys for the managed ``"step"`` / ``"cosine"`` presets.

    Managed presets consume only ``min_factor`` and ``lr_drop``; any other key would be silently ignored, so surface
    it as an error (mirroring ``validate_optimizer_kwargs``). Explicit schedulers forward their kwargs verbatim to
    the constructor and are left unchecked here.
    """
    if _is_managed_scheduler_name(self.lr_scheduler):
        unknown = set(self.lr_scheduler_kwargs) - _MANAGED_SCHEDULER_KWARGS
        if unknown:
            allowed = ", ".join(sorted(_MANAGED_SCHEDULER_KWARGS))
            unknown_keys = ", ".join(sorted(unknown))
            raise ValueError(
                f"lr_scheduler_kwargs for a managed preset ({self.lr_scheduler!r}) accepts only "
                f"{{{allowed}}}; unknown key(s): {unknown_keys}."
            )
    return self

validate_lr_scheduler_name(v) classmethod

Validate a string lr_scheduler: a bare name must be a managed preset, else use a dotted path.

Source code in src/rfdetr/config.py
@field_validator("lr_scheduler", mode="after")
@classmethod
def validate_lr_scheduler_name(cls, v: str | Callable[..., SchedulerType]) -> str | Callable[..., SchedulerType]:
    """Validate a string lr_scheduler: a bare name must be a managed preset, else use a dotted path."""
    if not isinstance(v, str):
        return v
    lr_scheduler = v.strip()
    if not lr_scheduler:
        raise ValueError("lr_scheduler must be a non-empty string.")
    # Bare names must be a managed preset; dotted import paths are validated lazily at train start.
    if "." not in lr_scheduler and not _is_managed_scheduler_name(lr_scheduler):
        presets = ", ".join(sorted(_MANAGED_SCHEDULER_PRESETS))
        raise ValueError(
            f"Unknown lr_scheduler {v!r}. Bare names must be a managed preset ({presets}); "
            "use a full dotted import path (e.g. 'torch.optim.lr_scheduler.StepLR') or a callable "
            "for anything else."
        )
    return lr_scheduler

validate_optimizer_kwargs()

Reserved optimizer kwargs are only rejected for managed (short-name) optimizers.

Source code in src/rfdetr/config.py
@model_validator(mode="after")
def validate_optimizer_kwargs(self) -> "TrainConfig":
    """Reserved optimizer kwargs are only rejected for managed (short-name) optimizers."""
    if _is_managed_optimizer_name(self.optimizer):
        reserved_present = _OPTIMIZER_MANAGED_KWARGS.intersection(self.optimizer_kwargs)
        if reserved_present:
            reserved = ", ".join(sorted(reserved_present))
            raise ValueError(f"optimizer_kwargs cannot include RF-DETR-managed key(s): {reserved}.")
    return self

validate_optimizer_name(v) classmethod

Validate a string optimizer: a bare name must be a native torch.optim optimizer.

Source code in src/rfdetr/config.py
@field_validator("optimizer", mode="after")
@classmethod
def validate_optimizer_name(cls, v: str | Callable[..., Optimizer]) -> str | Callable[..., Optimizer]:
    """Validate a string optimizer: a bare name must be a native torch.optim optimizer."""
    if not isinstance(v, str):
        return v
    optimizer = v.strip()
    if not optimizer:
        raise ValueError("optimizer must be a non-empty string.")
    # Bare short names must resolve to a torch.optim optimizer (checked eagerly).
    # Dotted import paths are validated lazily at train start (the module may be optional).
    if "." not in optimizer:
        _resolve_native_optimizer(optimizer)
    return optimizer

validate_positive_intervals(v) classmethod

Validate interval fields are >= 1.

Source code in src/rfdetr/config.py
@field_validator("ema_update_interval", "eval_interval", mode="after")
@classmethod
def validate_positive_intervals(cls, v: int) -> int:
    """Validate interval fields are >= 1."""
    if v < 1:
        raise ValueError("Interval fields must be >= 1.")
    return v

validate_positive_train_steps(v) classmethod

Validate accumulation, target-effective batch, and max targets are >= 1.

Source code in src/rfdetr/config.py
@field_validator(
    "grad_accum_steps", "auto_batch_target_effective", "auto_batch_max_targets_per_image", mode="after"
)
@classmethod
def validate_positive_train_steps(cls, v: int) -> int:
    """Validate accumulation, target-effective batch, and max targets are >= 1."""
    if v < 1:
        raise ValueError(
            "grad_accum_steps, auto_batch_target_effective, and auto_batch_max_targets_per_image must be >= 1."
        )
    return v

validate_prefetch_factor(v) classmethod

Validate prefetch_factor is None or >= 1.

Source code in src/rfdetr/config.py
@field_validator("prefetch_factor", mode="after")
@classmethod
def validate_prefetch_factor(cls, v: int | None) -> int | None:
    """Validate prefetch_factor is None or >= 1."""
    if v is not None and v < 1:
        raise ValueError("prefetch_factor must be >= 1 when provided.")
    return v

validate_smooth_alpha(v) classmethod

Validate smooth_alpha is in [0.0, 1.0).

Source code in src/rfdetr/config.py
@field_validator("smooth_alpha", mode="after")
@classmethod
def validate_smooth_alpha(cls, v: float) -> float:
    """Validate smooth_alpha is in [0.0, 1.0)."""
    if not (0.0 <= v < 1.0):
        raise ValueError("smooth_alpha must be in [0.0, 1.0).")
    return v