DFINE¶
The public, backend-agnostic detector class: build from typed params, load released
weights, and predict / train / val / export.
dfine.model.DFINE ¶
DFINE(size: str | None = None, *, config: DFINEConfig | None = None, weights: str | PathLike | None = None, device: str | device | None = None, **params)
Config-first D-FINE detector with an ultralytics-style predict.
Source code in dfine/model.py
from_pretrained
classmethod
¶
Build a model matching a released checkpoint and load its weights.
name is a catalogue entry ("dfine-s", "dfine-l-obj365" ...); the
size and num_classes are taken from it. See dfine models.
Source code in dfine/model.py
load ¶
Load weights into the model, in place.
weights is either a catalogue name (downloaded + cached) or a local
.pth path. Returns self for chaining: DFINE(size="s").load("dfine-s").
Source code in dfine/model.py
predict ¶
predict(source, conf: float = 0.25, imgsz: int | None = None, mask_thresh: float = 0.5) -> list[Results]
Detect objects in source (path / PIL / array, or a list of them).
Returns one :class:~dfine.results.Results per image; boxes are in the
original pixel scale. conf drops low-scoring detections. For a
task="segment" model, each result also carries per-instance
:class:~dfine.results.Masks (original scale), thresholded at mask_thresh.
Source code in dfine/model.py
train ¶
train(train_loader=None, epochs: int | None = None, *, data: str | PathLike | None = None, batch_size: int = 4, num_workers: int = 4, augment: bool = True, remap_mscoco_category: bool = False, devices: int | None = None, val_loader=None, val_fn=None, output_dir: str = 'runs/train', use_wandb: bool = False, visualize: bool = True)
Fine-tune the model (Phase 4).
Provide the data one of two ways:
data="path/to/coco"— a standard COCO dataset root (train2017/+annotations/instances_train2017.json, optionalval2017/). The train loader (full two-phase augmentation + multi-scale) and, if present, a val loader are built for you via :func:~dfine.train.dataset.build_coco_dataloaders.batch_size,num_workers,augmentandremap_mscoco_categorytune that build (setremap_mscoco_category=Truefor stock 80-class MS-COCO ids).train_loader=...— a ready dataloader yielding(samples, targets)batches:samplesa floatBCHWimage tensor, eachtargeta dict withlabels(LongTensor) andboxes(cxcywh, normalized).
Multi-GPU: pass devices=N to train on N GPUs — this call becomes the
launcher and spawns one DDP worker per GPU (no torchrun needed); it requires
data= (in-memory loaders can't be shipped to workers). Alternatively launch
the script yourself with torchrun --nproc_per_node=N and call train(...)
without devices — each worker detects the distributed env and joins the group.
Optimizer groups, LR schedule, EMA, AMP and grad-clip all come from this
model's :class:~dfine.config.DFINEConfig. Progress is visualized like upstream
D-FINE: a live console readout plus TensorBoard scalars and a loss_curve.png
under output_dir (and W&B if use_wandb); only rank 0 writes them. Returns
self; the trained (EMA) weights replace self.model.
When a val_loader is available (passed, or auto-built from data) and no
val_fn is given, COCO metrics are computed each epoch via
:func:~dfine.train.evaluator.coco_val_fn and logged alongside the loss.
Source code in dfine/model.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 | |
val ¶
val(data: str | PathLike | None = None, *, val_loader=None, batch_size: int = 4, num_workers: int = 4, remap_mscoco_category: bool = False) -> dict[str, float]
Evaluate the model on a COCO val set and return the metrics dict.
Provide the data one of two ways (mutually exclusive):
data="path/to/coco"— a COCO root; the val loader is built fromval2017/+annotations/instances_val2017.jsonfor you.val_loader=...— a ready loader frombuild_coco_dataloader(its dataset must carry the ground-truth.coco).
Returns the 12 standard COCO metrics keyed by name (AP is the primary
mAP@[.50:.95]); see :data:~dfine.train.evaluator.COCO_STAT_NAMES. For stock
MS-COCO ground truth (sparse category ids), build the model with
remap_mscoco_category=True so predicted labels match the annotations.
Source code in dfine/model.py
export ¶
export(format: str = 'onnx', file: str | PathLike | None = None, *, imgsz: int | None = None, batch: int = 1, dynamic: bool = True, simplify: bool = False, opset: int = 16) -> Path
Export the model to a deployable graph (Phase 3).
Currently format="onnx": writes a single ONNX graph with the two-input
signature (images, orig_target_sizes) → (labels, boxes, scores) (boxes
xyxy in original scale), batch dim dynamic by default. Returns the output
:class:~pathlib.Path. Needs pip install pydfine[export].
file defaults to dfine-<size>.onnx. Use simplify=True for onnxsim,
and :func:dfine.export.tensorrt_command for a downstream trtexec engine.
Source code in dfine/model.py
predict_video ¶
predict_video(source, output: str | PathLike = 'output.mp4', conf: float = 0.25, imgsz: int | None = None, stream: bool = False, track: bool = False)
Detect objects frame-by-frame in a video.
With stream=True returns a generator of per-frame :class:Results and
writes nothing. Otherwise writes an annotated video to output (original
resolution/fps) and returns its :class:~pathlib.Path.
With track=True each frame's detections are run through a ByteTrack tracker
so boxes carry a persistent boxes.id across frames (rendered as #id and
colored per track). Needs scipy (the [track] extra).