Skip to content

Segmentation Train Config

Bases: TrainConfig

Training configuration for instance segmentation models.

Extends :class:TrainConfig with segmentation-specific loss coefficients.

Attributes:

Name Type Description
mask_point_sample_ratio int

Number of points sampled per mask for point-based mask loss computation.

mask_ce_loss_coef float

Cross-entropy loss weight for mask prediction.

mask_dice_loss_coef float

Dice loss weight for mask prediction.

cls_loss_coef float

Classification loss weight. Defaults to 1.0 to match the effective pre-v1.7 value (the v1.7 TrainConfig ownership migration silently activated a dormant 5.0; this field restores the correct weight). To reproduce pre-fix segmentation behaviour pass cls_loss_coef=5.0 explicitly.

Source code in src/rfdetr/config.py
class SegmentationTrainConfig(TrainConfig):
    """Training configuration for instance segmentation models.

    Extends :class:`TrainConfig` with segmentation-specific loss coefficients.

    Attributes:
        mask_point_sample_ratio: Number of points sampled per mask for point-based
            mask loss computation.
        mask_ce_loss_coef: Cross-entropy loss weight for mask prediction.
        mask_dice_loss_coef: Dice loss weight for mask prediction.
        cls_loss_coef: Classification loss weight. Defaults to ``1.0`` to match the
            effective pre-v1.7 value (the v1.7 TrainConfig ownership migration
            silently activated a dormant ``5.0``; this field restores the correct
            weight). To reproduce pre-fix segmentation behaviour pass
            ``cls_loss_coef=5.0`` explicitly.
    """

    mask_point_sample_ratio: int = 16
    mask_ce_loss_coef: float = 5.0
    mask_dice_loss_coef: float = 5.0
    cls_loss_coef: float = 1.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