D-FINE
A detection transformer that reformulates box regression as a probability distribution over each box edge, refined across decoder layers. LibreYOLO supports it for detection and instance segmentation.
- Tasks
- detection, instance segmentation
- Sizes
- n, s, m, l, x at 640 px
- Install
pip install libreyolo- Support tier
- Core, since v1.1.0. Core trainable detectors: features follow the flagships in the same release wave.
- Licenses
- Code Apache-2.0, weights Apache-2.0. Commercial use
Install
D-FINE needs no optional extra. Everything it imports is in the base install.
pip install libreyoloAdapter fine-tuning with lora=True is the exception, and needs the lora
extra.
pip install "libreyolo[lora]"Predict
Weights download from Hugging Face on first use and are cached locally.
from libreyolo import LibreYOLO, SAMPLE_IMAGE model = LibreYOLO("LibreDFINEn.pt")result = model(SAMPLE_IMAGE, save=True) for box in result.boxes: print(box.cls, box.conf, box.xyxy)libreyolo predict model=LibreDFINEn.pt source=https://raw.githubusercontent.com/LibreYOLO/libreyolo/release/libreyolo/assets/parkour.jpg save=Truefrom libreyolo import LibreYOLO, SAMPLE_IMAGE # The -seg suffix in the filename selects the mask head, so no task# argument is needed here.model = LibreYOLO("LibreDFINEn-seg.pt")result = model(SAMPLE_IMAGE, save=True) print(result.masks.data.shape)The returned Results object is the one every family returns, so swapping in a
different detector is a one line change. A -seg filename resolves to the
segmentation task on its own, and result.masks then carries the instance
masks alongside the boxes. conf and max_det filter the query selection;
iou is accepted for API parity but has no effect, because the decoder is a set
predictor with no NMS step. See prediction for sources,
streaming and result handling.
Variants
Five sizes. They all run at the same input resolution, so the table separates them by parameter count and accuracy.
| Checkpoint | Input (px) | mAP 50-95 | Params (M) |
|---|---|---|---|
| LibreDFINEl | 640 | 60.0 | 31.24 |
| LibreDFINEm | 640 | 57.8 | 19.59 |
| LibreDFINEn | 640 | 45.8 | 3.78 |
| LibreDFINEs | 640 | 53.4 | 10.32 |
| LibreDFINEx | 640 | 61.4 | 62.62 |
COCO val2017, 500 images. Measured by the LibreYOLO benchmark harness and published on Vision Analysis, where latency across hardware and runtimes is compared and the full run records live.
Segmentation reuses the detection backbone, encoder and decoder and adds a mask
head, so a -seg checkpoint takes the same arguments as its detect sibling.
LibreYOLO's RT-DETRv4 family is written as a subclass of the D-FINE wrapper: it
inherits this decoder line and then pins its task list back to detection,
because it carries no mask head.
Train
Training starts from a published checkpoint, for both tasks.
from libreyolo import LibreYOLO model = LibreYOLO("LibreDFINEn.pt")model.train(data="my-dataset.yaml", epochs=50, imgsz=640, batch=8, lr0=2e-4)libreyolo train model=LibreDFINEn.pt data=my-dataset.yaml \ epochs=50 imgsz=640 batch=8 lr0=2e-4# Continues from published segmentation weights, mask head included.libreyolo train model=LibreDFINEn-seg.pt data=my-dataset.yaml \ task=segment epochs=50 imgsz=640# Detect weights carry no mask head, so this is an explicit transfer:# the head starts untrained and is only useful once trained. Asking for# task=segment here is what authorizes the transfer.libreyolo train model=LibreDFINEn.pt data=my-dataset.yaml \ task=segment epochs=50 imgsz=640from libreyolo import LibreYOLO model = LibreYOLO("LibreDFINEn.pt")model.train(data="my-dataset.yaml", epochs=50, lora=True)libreyolo train model=LibreDFINEn.pt data=my-dataset.yaml \ epochs=50 device=0,1 batch=16Left alone, the trainer runs 132 epochs at lr0=2e-4 with amp=True and amp_dtype="float16", a batch
of 16 and early stopping after 50 epochs without improvement. libreyolo train
starts from the same recipe for both tasks: AdamW with a flat cosine schedule,
weight_decay=1e-4, 2 warmup epochs, a gradient-norm clip of 0.1, and no
mosaic, MixUp, HSV or affine augmentation. Without name=, its runs go to
runs/train/dfine_exp. Detect weights are
a legal starting point for segmentation training, but only as an explicit
transfer, since the mask head begins untrained and would otherwise return
meaningless masks. Passing task=segment to the CLI is what authorizes it. The
Python route is narrower: LibreDFINE has to be constructed directly with
allow_detect_to_segment_transfer=True, because the LibreYOLO() factory takes
no such argument, and direct construction does not download, so the weights file
must already be on disk.
lora=True applies to detection. Segment training rejects it and points at
freeze='backbone' instead, because the mask head has not been tested with
adapters. On Apple silicon the trainer moves the whole run to CPU: the backward
pass of the Integral's binned matmul hits a Metal compilation failure. Inference
on MPS is unaffected.
See training for datasets, augmentation, multi-GPU and loggers.
Validate
val() returns a dictionary keyed by metric name, and prints per-class results
when verbose is left on.
from libreyolo import LibreYOLO model = LibreYOLO("LibreDFINEn.pt")metrics = model.val(data="my-dataset.yaml") print(metrics["metrics/mAP50-95"])print(metrics["metrics/mAP50"])libreyolo val model=LibreDFINEn.pt data=my-dataset.yamlfrom libreyolo import LibreYOLO model = LibreYOLO("LibreDFINEn-seg.pt")metrics = model.val(data="my-dataset.yaml") print(metrics["metrics/mAP50-95(M)"]) # masksprint(metrics["metrics/mAP50-95(B)"]) # boxesAgainst a -seg checkpoint the plain metrics/mAP50-95 key holds the mask
score, and the same run also reports boxes under (B) and masks under (M) so
both are available from one pass.
Export
| Task | ONNX | TorchScript | ExecuTorch | TensorRT | OpenVINO | Paddle | MNN | RKNN | ncnn | TFLite | CoreML | Core AI |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Detection | Detection to ONNX: supported | Detection to TorchScript: supported | Detection to ExecuTorch: not supported | Detection to TensorRT: supported | Detection to OpenVINO: supported | Detection to Paddle: supported | Detection to MNN: supported | Detection to RKNN: not supported | Detection to ncnn: not supported | Detection to TFLite: not supported | Detection to CoreML: not supported | Detection to Core AI: supported |
| Instance segmentation | Instance segmentation to ONNX: supported | Instance segmentation to TorchScript: supported | Instance segmentation to ExecuTorch: not supported | Instance segmentation to TensorRT: supported | Instance segmentation to OpenVINO: supported | Instance segmentation to Paddle: not supported | Instance segmentation to MNN: not supported | Instance segmentation to RKNN: not supported | Instance segmentation to ncnn: not supported | Instance segmentation to TFLite: not supported | Instance segmentation to CoreML: not supported | Instance segmentation to Core AI: not supported |
An exported artifact loads back through LibreYOLO() on its file suffix, so a
.onnx or .engine file behaves like a checkpoint and returns the same
Results. The OpenVINO, Paddle, MNN and Core AI paths export at a fixed canvas
rather than dynamic shapes. Export lists the arguments every
format accepts and the extras a few of them add.
from libreyolo import LibreYOLO model = LibreYOLO("LibreDFINEn.pt")model.export(format="onnx", imgsz=640)model.export(format="tensorrt", imgsz=640, half=True)libreyolo export model=LibreDFINEn.pt format=onnx imgsz=640libreyolo export model=LibreDFINEn.pt format=tensorrt imgsz=640 half=Truefrom libreyolo import LibreYOLO, SAMPLE_IMAGE # The factory routes on the file suffix, so an exported artifact loads# like any checkpoint and returns the same Results object.model = LibreYOLO("LibreDFINEn.onnx")result = model(SAMPLE_IMAGE) print(result.boxes.xyxy)ONNX inputs and outputs
| Tensor | images float32 [batch, 3, height, width] |
|---|---|
| Color | RGB |
| Scaling | pixel / 255 |
| Normalization | none |
| Resize | stretch to width x height (no padding, aspect ratio not kept), Pillow bilinear |
How to reproduce Pillow's bilinear resize
LibreYOLO resizes with Pillow's BILINEAR filter (Image.resize). It is not OpenCV INTER_LINEAR or INTER_AREA: when shrinking, Pillow widens the filter by the shrink factor, and OpenCV's resizes change detections and move boxes by several pixels. To reproduce it without Pillow, resize one axis, round to 8 bits, then resize the other axis and round again. Per axis, let s = in_size / out_size and f = max(s, 1). Output pixel i has center c = (i + 0.5) * s and reads source pixels j from int(c - f + 0.5) to int(c + f + 0.5) - 1, clipped to the image, each with weight max(0, 1 - |j + 0.5 - c| / f), divided by the sum of the weights. Pillow works in fixed point and picks the axis order from the image shape, so float weights can differ from it by one level on a few pixels. That does not change the results in our checks.
Square input only. Export rejects a non-square imgsz, and height and width are 640 by default.
Batch size 1 only. The graph declares a dynamic batch axis, but batches of 2 or more fail in 1.7.0.
Divide by 255 after the resize. There is no mean or std normalization.
Detection, default export
| Output | Shape | Meaning |
|---|---|---|
pred_logits | [batch, queries, nc] | One logit per query and class. Sigmoid is not applied. queries is 300 for every size. |
pred_boxes | [batch, queries, 4] | cx, cy, w, h of each query, normalized 0 to 1 of the input. The input is the whole image stretched, so these are also fractions of the original image. |
Postprocessing
- Apply sigmoid to pred_logits.
- Flatten the [queries, nc] scores and take the top 300 (max_det, 300 by default). For flat index k, the query is k // nc and the class is k % nc. One query can yield several classes.
- Keep the pairs whose score is above the confidence threshold (0.25 by default).
- Convert the query's box to x1 = cx - w / 2, y1 = cy - h / 2, x2 = cx + w / 2, y2 = cy + h / 2. Multiply x by the original image width and y by the original image height.
- There is no NMS and the iou threshold is not used. D-FINE predicts a set of boxes, and export with nms=True raises NotImplementedError.
- LibreYOLO does not clip these boxes, so an edge can sit slightly outside the image.
Instance segmentation, default export
| Output | Shape | Meaning |
|---|---|---|
pred_logits | [batch, queries, nc] | One logit per query and class. Sigmoid is not applied. queries is 300 for every size. |
pred_boxes | [batch, queries, 4] | cx, cy, w, h of each query, normalized 0 to 1 of the input. The input is the whole image stretched, so these are also fractions of the original image. |
pred_masks | [batch, queries, mask_h, mask_w] | One mask per query, sigmoid already applied. mask_h is height / 4 and mask_w is width / 4, 160 x 160 at 640 x 640. |
Postprocessing
- Apply sigmoid to pred_logits.
- Flatten the [queries, nc] scores and take the top 300 (max_det, 300 by default). For flat index k, the query is k // nc and the class is k % nc. One query can yield several classes.
- Keep the pairs whose score is above the confidence threshold (0.25 by default).
- Convert the query's box to x1 = cx - w / 2, y1 = cy - h / 2, x2 = cx + w / 2, y2 = cy + h / 2. Multiply x by the original image width and y by the original image height.
- For each kept pair, take its query's mask. Resize it with bilinear interpolation and half-pixel centers (align_corners=False, no antialiasing) to height x width, then again to the original image size.
- A pixel belongs to the mask when its value is 0.5 or more.
- Clear every mask pixel outside the box. Pixel (x, y) stays only when x1 <= x < x2 and y1 <= y < y2, in original-image pixels.
- There is no NMS and the iou threshold is not used. D-FINE predicts a set of boxes, and export with nms=True raises NotImplementedError.
- LibreYOLO does not clip the boxes of a .pt predict, so an edge can sit slightly outside the image. Its ONNX backend clips them to the image.
To check your own implementation, run the same file through LibreYOLO: LibreYOLO("model.onnx").predict("image.jpg") returns the reference results. Verified with LibreYOLO 1.7.0.
Checkpoints
Every published weight file for this family.
| File | Input (px) | Weights license |
|---|---|---|
| Detection | ||
| LibreDFINEn.pt | 640 | apache-2.0 |
| LibreDFINEs.pt | 640 | apache-2.0 |
| LibreDFINEm.pt | 640 | apache-2.0 |
| LibreDFINEl.pt | 640 | apache-2.0 |
| LibreDFINEx.pt | 640 | apache-2.0 |
| Instance segmentation | ||
| LibreDFINEn-seg.pt | 640 | apache-2.0 |
| LibreDFINEs-seg.pt | 640 | apache-2.0 |
| LibreDFINEm-seg.pt | 640 | apache-2.0 |
| LibreDFINEl-seg.pt | 640 | apache-2.0 |
| LibreDFINEx-seg.pt | 640 | apache-2.0 |
Every file above exists in the LibreYOLO org today and downloads on first use.
Licensing
Check the license on the Hugging Face repository of the specific weights you download. Every checkpoint in the LibreYOLO org carries one, and they are not always the same across a family. That repository is the authoritative source; the summary below describes what applied when this page was last verified.
This is a description of the licenses involved, not legal advice. If the answer matters commercially, read the licenses yourself and take your own counsel.
- Original work
- D-FINE, University of Science and Technology of China
- Upstream license
- Apache-2.0
- Upstream source
- github.com/Peterande/D-FINE
- LibreYOLO code
- MIT
- Weights
- Apache-2.0, republished at huggingface.co/LibreYOLO
- Interpretation
- Apache-2.0 is a permissive license, so these weights can be used in commercial and closed-source products. It asks you to keep its license text and attribution notices with any copy of the weights you redistribute, and it grants a patent license. It places no obligation on your own application code, and weights you train yourself on your own data are yours. The segmentation weights carry a second Apache-2.0 upstream, ArgoHA/D-FINE-seg, under the same terms.
The segmentation weights have a second upstream: their mask decoder, mask matching and mask loss come from ArgoHA/D-FINE-seg, also Apache-2.0, whose maintainer approved reuse with attribution.
Citation
@misc{peng2024dfine,
title={D-FINE: Redefine Regression Task in DETRs as Fine-grained Distribution Refinement},
author={Yansong Peng and Hebei Li and Peixi Wu and Yueyi Zhang and Xiaoyan Sun and Feng Wu},
year={2024},
eprint={2410.13842},
archivePrefix={arXiv},
primaryClass={cs.CV}
}Copied from the authors' citation block at github.com/Peterande/D-FINE#citation.