Skip to content

DFINEConfig

Every model + training option as one typed, frozen dataclass. Build with a size preset or construct directly; optional YAML interop via to_yaml / from_yaml.

dfine.config.DFINEConfig dataclass

DFINEConfig(size: str | None = None, task: str = 'detect', num_classes: int = 80, class_names: list[str] | None = None, imgsz: int = 640, device: str = 'cpu', remap_mscoco_category: bool = False, mask_dim: int = 256, backbone: str = 'hgnetv2_b4', backbone_pretrained: bool = True, return_idx: list[int] = (lambda: [1, 2, 3])(), freeze_at: int = -1, freeze_stem_only: bool = False, freeze_norm: bool = False, use_lab: bool = False, backbone_local_dir: str | None = None, hidden_dim: int = 256, in_channels: list[int] = (lambda: [512, 1024, 2048])(), feat_strides: list[int] = (lambda: [8, 16, 32])(), use_encoder_idx: list[int] = (lambda: [2])(), encoder_layers: int = 1, nhead: int = 8, encoder_dim_feedforward: int = 1024, encoder_dropout: float = 0.0, enc_act: str = 'gelu', encoder_expansion: float = 1.0, depth_mult: float = 1.0, encoder_act: str = 'silu', decoder_hidden_dim: int | None = None, num_queries: int = 300, decoder_dim_feedforward: int = 1024, decoder_layers: int = 6, eval_idx: int = -1, num_levels: int = 3, feat_channels: list[int] = (lambda: [256, 256, 256])(), num_points: list[int] = (lambda: [3, 6, 3])(), decoder_nhead: int = 8, decoder_offset_scale: float = 0.5, decoder_method: str = 'default', query_select_method: str = 'default', layer_scale: float = 1.0, reg_max: int = 32, reg_scale: float = 4.0, lqe_hidden_dim: int = 64, lqe_layers: int = 2, num_denoising: int = 100, label_noise_ratio: float = 0.5, box_noise_scale: float = 1.0, cost_class: float = 2.0, cost_bbox: float = 5.0, cost_giou: float = 2.0, matcher_alpha: float = 0.25, matcher_gamma: float = 2.0, loss_vfl_weight: float = 1.0, loss_bbox_weight: float = 5.0, loss_giou_weight: float = 2.0, loss_fgl_weight: float = 0.15, loss_ddf_weight: float = 1.5, focal_alpha: float = 0.75, focal_gamma: float = 2.0, aux_loss: bool = True, num_top_queries: int = 300, conf: float = 0.4, epochs: int = 72, batch: int = 32, lr: float = 0.00025, lr_backbone: float = 1.25e-05, weight_decay: float = 0.000125, zero_wd_encdec_bias: bool = False, betas: tuple[float, float] = (0.9, 0.999), clip_max_norm: float = 0.1, warmup_iters: int = 500, lr_milestones: list[int] | None = None, lr_gamma: float = 0.1, scheduler: str = 'flatcosine', ema_decay: float = 0.9999, ema_warmups: int = 1000, use_amp: bool = True, no_aug_epoch: int = 2, seed: int = 0, workers: int = 4, checkpoint_freq: int = 1, sync_bn: bool = True, find_unused_parameters: bool = False, aug_photometric: bool = True, aug_zoom_out: bool = True, aug_iou_crop: bool = True, aug_hflip: bool = True, multiscale: bool = True, base_size: int = 640, base_size_repeat: int | None = 3)

All D-FINE model + training options as one typed, frozen dataclass.

Build with a preset via :meth:preset (fills size-dependent fields) or construct directly for a fully custom architecture. Every field is overridable inline.

enable_mask_head property

enable_mask_head: bool

Whether the decoder runs the instance-mask branch (task="segment").

preset classmethod

preset(size: str, **overrides: Any) -> DFINEConfig

Build a config from a size preset, then apply inline overrides.

Parameters:

Name Type Description Default
size str

one of "n" | "s" | "m" | "l" | "x".

required
**overrides Any

any field name to override the preset value.

{}
Source code in dfine/config.py
@classmethod
def preset(cls, size: str, **overrides: Any) -> DFINEConfig:
    """Build a config from a size preset, then apply inline overrides.

    Args:
        size: one of ``"n" | "s" | "m" | "l" | "x"``.
        **overrides: any field name to override the preset value.
    """
    key = size.lower()
    if key not in SIZE_PRESETS:
        raise ValueError(f"Unknown size {size!r}; expected one of {SIZES}.")
    merged: dict[str, Any] = {"size": key, **SIZE_PRESETS[key], **overrides}
    return cls(**merged)

override

override(**changes: Any) -> DFINEConfig

Return a copy with changes applied (re-runs validation).

Source code in dfine/config.py
def override(self, **changes: Any) -> DFINEConfig:
    """Return a copy with ``changes`` applied (re-runs validation)."""
    return replace(self, **changes)

to_dict

to_dict() -> dict[str, Any]

Plain-dict view of all fields.

Source code in dfine/config.py
def to_dict(self) -> dict[str, Any]:
    """Plain-dict view of all fields."""
    return asdict(self)

from_dict classmethod

from_dict(data: dict[str, Any]) -> DFINEConfig

Construct from a dict, ignoring unknown keys.

Source code in dfine/config.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> DFINEConfig:
    """Construct from a dict, ignoring unknown keys."""
    known = {f.name for f in fields(cls)}
    kwargs = {k: v for k, v in data.items() if k in known}
    # ``betas`` is a tuple field; YAML/JSON round-trips it as a list — coerce back so
    # equality (and downstream tuple assumptions) hold exactly.
    if isinstance(kwargs.get("betas"), list):
        kwargs["betas"] = tuple(kwargs["betas"])
    return cls(**kwargs)

to_yaml

to_yaml(path: str | Path | None = None) -> str | Path

Serialize the config to YAML: return the string, or write it to path.

Round-trips through :meth:from_yaml. Tuples (e.g. betas) are written as lists so the output is plain, safe YAML.

Source code in dfine/config.py
def to_yaml(self, path: str | Path | None = None) -> str | Path:
    """Serialize the config to YAML: return the string, or write it to ``path``.

    Round-trips through :meth:`from_yaml`. Tuples (e.g. ``betas``) are written as
    lists so the output is plain, safe YAML.
    """
    yaml = self._require_yaml()
    data = {k: (list(v) if isinstance(v, tuple) else v) for k, v in self.to_dict().items()}
    text = yaml.safe_dump(data, sort_keys=False)
    if path is None:
        return text
    out = Path(path)
    out.write_text(text)
    return out

from_yaml classmethod

from_yaml(source: str | Path) -> DFINEConfig

Build a config from a YAML file path or a YAML string (unknown keys ignored).

source is a :class:~pathlib.Path, a path string ending in .yaml/.yml, or the YAML text itself. Validation runs on construction.

Source code in dfine/config.py
@classmethod
def from_yaml(cls, source: str | Path) -> DFINEConfig:
    """Build a config from a YAML file path or a YAML string (unknown keys ignored).

    ``source`` is a :class:`~pathlib.Path`, a path string ending in ``.yaml``/``.yml``,
    or the YAML text itself. Validation runs on construction.
    """
    yaml = cls._require_yaml()
    if isinstance(source, Path):
        text = source.read_text()
    elif (
        isinstance(source, str)
        and "\n" not in source
        and source.rstrip().endswith((".yaml", ".yml"))
    ):
        p = Path(source)
        if not p.exists():
            raise FileNotFoundError(f"YAML config not found: {source!r}")
        text = p.read_text()
    else:
        text = source
    data = yaml.safe_load(text)
    if not isinstance(data, dict):
        raise ValueError("from_yaml expected a YAML mapping (file path or YAML string).")
    return cls.from_dict(data)