Skip to content

YOLO wrapper

YOLOBackend(arch, pretrained, num_classes=None, hyp=None)

Bases: torch.nn.Module

Ultralytics YOLO detection backend (v8/11-style head via DetectionModel).

Builds the model from a YAML spec based on arch, optionally loads pretrained weights, and stores loss hyperparameters (YoloLossParams) into self.model.args.

Parameters:

Name Type Description Default
arch str

YOLO architecture, e.g. "yolov8n", "yolo11x", optionally with "-p6" / "-p2".

required
pretrained bool

If True, load Ultralytics pretrained weights ({arch}.pt) through the public YOLO API.

required
num_classes int | None

Number of classes; when None, read from current().data_box.num_classes.

None
hyp deepvisiontools.models.yolo.yolo.YoloLossParams | None

Loss gains for Ultralytics criterion. If None, defaults are used.

None

Attributes:

Name Type Description
model ultralytics.nn.tasks.DetectionModel

Underlying Ultralytics detection model.

pad_mult int

Padding multiple inferred from arch.

Source code in src/deepvisiontools/models/yolo/yolo.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def __init__(
    self,
    arch: str,
    pretrained: bool,
    num_classes: int | None = None,
    hyp: YoloLossParams | None = None,
) -> None:
    super().__init__()

    num_classes = (
        int(num_classes)
        if num_classes is not None
        else int(current().data_box.num_classes)
    )

    self.model = DetectionModel(f"{arch}.yaml", nc=num_classes)
    self.model.float()

    if pretrained:
        pretrained_model = _load_ultralytics_pretrained_model(arch)
        self.model.load(pretrained_model)

    cast(Any, self.model).args = hyp if hyp is not None else YoloLossParams()

    # Keep a YOLO runner object because the builder later uses
    # backend._runner.model.init_criterion().
    runner = YOLO(f"{arch}.yaml")
    cast(Any, runner).model = self.model
    object.__setattr__(self, "_runner", runner)

    self.pad_mult = _stride_from_arch(arch)

forward(x, extra_args=None)

Single forward for train/eval.

Parameters:

Name Type Description Default
x Tensor

[B, 3, H, W] input batch.

required
extra_args dict | None

Reserved for backend-specific extensions.

None

Returns:

Name Type Description
Any

Raw prediction structure expected by the Ultralytics loss.

Source code in src/deepvisiontools/models/yolo/yolo.py
415
416
417
418
419
420
421
422
423
424
425
426
def forward(self, x: torch.Tensor, extra_args: None | dict = None):
    """
    Single forward for train/eval.

    Args:
        x (Tensor): `[B, 3, H, W]` input batch.
        extra_args (dict | None): Reserved for backend-specific extensions.

    Returns:
        Any: Raw prediction structure expected by the Ultralytics loss.
    """
    return self.model(x)

YOLOLoss(criterion, *, loss_factor=1.0)

Bases: deepvisiontools.models.base.basemodel.BaseLoss

Thin wrapper around the Ultralytics YOLO loss.

  • Accepts the vendor criterion (usually from backend._runner.model.init_criterion()).
  • Ensures its internal tensors and the input targets are moved to the correct device.
  • Optionally scales the total and detailed losses by loss_factor.

Parameters:

Name Type Description Default
criterion typing.Any

Ultralytics loss object.

required
loss_factor float

Global divisor applied to the total (and detailed) loss values. Defaults to 1.0.

1.0
Source code in src/deepvisiontools/models/yolo/yolo.py
740
741
742
743
def __init__(self, criterion: Any, *, loss_factor: float = 1.0):
    super().__init__()
    self.criterion = criterion
    self.loss_factor = float(loss_factor)

to(*args, **kwargs)

Move internal loss tensors (and vendor criterion if supported) to a device.

Mirrors nn.Module.to to ease integration with DeepVisionModel.to(...).

Source code in src/deepvisiontools/models/yolo/yolo.py
745
746
747
748
749
750
751
752
753
754
755
756
757
def to(self, *args, **kwargs):
    """
    Move internal loss tensors (and vendor criterion if supported) to a device.

    Mirrors `nn.Module.to` to ease integration with `DeepVisionModel.to(...)`.
    """
    super().to(*args, **kwargs)
    device = kwargs.get("device")
    if device is None and len(args) >= 1:
        device = args[0]
    if device is not None:
        self._move_criterion_tensors(device)
    return self

forward(preds, targs)

Compute the YOLO loss and return a detailed dictionary.

Parameters:

Name Type Description Default
preds typing.Any

Raw outputs from YOLOBackend.

required
targs Dict[str, Tensor]

Ultralytics-style targets with keys "batch_idx", "cls", "bboxes".

required

Returns:

Type Description
dict[str, torch.Tensor]

Dict[str, Tensor]: At minimum {"loss": total}; when the vendor returns

dict[str, torch.Tensor]

(total, detail), keys "loss_box", "loss_cls", "loss_dfl" are added.

Source code in src/deepvisiontools/models/yolo/yolo.py
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
def forward(
    self, preds: Any, targs: dict[str, torch.Tensor]
) -> dict[str, torch.Tensor]:
    """
    Compute the YOLO loss and return a detailed dictionary.

    Args:
        preds (Any): Raw outputs from `YOLOBackend`.
        targs (Dict[str, Tensor]): Ultralytics-style targets with keys
            `"batch_idx"`, `"cls"`, `"bboxes"`.

    Returns:
        Dict[str, Tensor]: At minimum `{"loss": total}`; when the vendor returns
        `(total, detail)`, keys `"loss_box"`, `"loss_cls"`, `"loss_dfl"` are added.
    """
    device = _first_tensor_device(preds)
    if device is not None:
        self._move_criterion_tensors(device)
        targs = self._align_targets_device(targs, device)

    batch_size = self._infer_batch_size(preds)
    factor = float(batch_size) * self.loss_factor

    out = self.criterion(preds, targs)

    if isinstance(out, tuple) and len(out) >= 2:
        raw_total = self._as_tensor(out[0], device)
        raw_detail = self._as_tensor(out[1], device)

        total = self._as_scalar_loss(raw_total) / factor
        detail = raw_detail / factor

        loss_dict: dict[str, torch.Tensor] = {"loss": total}

        try:
            detail_flat = detail.flatten()
            if detail_flat.numel() >= 3:
                loss_dict["loss_box"] = detail_flat[0]
                loss_dict["loss_cls"] = detail_flat[1]
                loss_dict["loss_dfl"] = detail_flat[2]
        except Exception:
            pass

        return loss_dict

    raw_loss = self._as_tensor(out, device)
    return {"loss": self._as_scalar_loss(raw_loss) / factor}

YoloLossParams(box=7.5, cls=0.5, dfl=1.5) dataclass

Loss hyperparameters (gain multipliers) for Ultralytics v8/11 detection loss.

Parameters:

Name Type Description Default
box float

IoU/box regression loss gain. Defaults to 7.5.

7.5
cls float

Classification loss gain. Defaults to 0.5.

0.5
dfl float

Distribution Focal Loss gain. Defaults to 1.5.

1.5

YOLOPost

Bases: torch.nn.Module

Decode raw YOLO outputs into BatchData[BboxData] (single-pass path) and apply un-preprocessing (de-pad to recover original input size)

Expected raw_outputs: - A Tensor of shape (B, N, 4 + C) with boxes in CXCYWH (pixels) and class scores, or - A tuple/list whose first element is that tensor (as some vendor paths emit).

Post-processing applies confidence filtering, NMS (torchvision or greedy fallback), top-k limiting (max_det), and returns boxes in XYXY with scores and labels.

preds_from_raw(prebuilt, aux=None)

Decode YOLO head prebuild into BatchData[bbox].

Parameters:

Name Type Description Default
prebuilt Tensor

[B, 4+C, N] with boxes (CXCYWH in pixels) and class scores.

required
aux dict

Extra context with: - "pred": YoloPredParams (conf, NMS IoU, max_det) - "canvas_size": (H, W) target spatial size used during preprocessing

None

Returns:

Name Type Description
BatchData deepvisiontools.data.BatchData

One BboxData per batch item, with boxes in XYXY, labels, and scores.

Source code in src/deepvisiontools/models/yolo/yolo.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
def preds_from_raw(
    self, prebuilt: torch.Tensor, aux: dict | None = None
) -> BatchData:
    """
    Decode YOLO head prebuild into `BatchData[bbox]`.

    Args:
        prebuilt (Tensor): `[B, 4+C, N]` with boxes (CXCYWH in **pixels**) and class scores.
        aux (dict, optional): Extra context with:
            - "pred": `YoloPredParams` (conf, NMS IoU, max_det)
            - "canvas_size": `(H, W)` target spatial size used during preprocessing

    Returns:
        BatchData: One `BboxData` per batch item, with boxes in XYXY, labels, and scores.
    """
    if aux is None:
        aux = {}
    prebuilt = self._ensure_prebuild(prebuilt)
    pp = cast(
        YoloPredParams | None,
        aux.get("pred", getattr(self, "default_pred_params", None)),
    )
    if pp is None:
        pp = YoloPredParams(conf_threshold=0.5, nms_iou=0.5, max_det=100)

    H, W = aux.get("canvas_size", (None, None))
    device = prebuilt.device

    # Current YOLO wrapper contract is [B, 4+C, N]
    B, D, N = prebuilt.shape
    C = D - 4

    # Convert once to [B, N, 4+C]
    pred = prebuilt.permute(0, 2, 1).contiguous()

    boxes_cxcywh = pred[..., :4]  # [B, N, 4]
    cls_scores = pred[..., 4:]  # [B, N, C]

    conf, labels = torch.max(cls_scores, dim=-1)  # [B, N], [B, N]

    # Flatten batch for vectorized thresholding + NMS
    boxes_f = boxes_cxcywh.reshape(-1, 4)  # [B*N, 4]
    conf_f = conf.reshape(-1)  # [B*N]
    labels_f = labels.reshape(-1)  # [B*N]

    image_ids = (
        torch.arange(B, device=device).unsqueeze(1).expand(B, N).reshape(-1)
    )  # [B*N]

    keep = conf_f >= float(pp.conf_threshold)
    boxes_f = boxes_f[keep]
    conf_f = conf_f[keep]
    labels_f = labels_f[keep]
    image_ids = image_ids[keep]

    out = []

    if boxes_f.numel() == 0:
        for _ in range(B):
            out.append(BboxData.empty((H, W), device=device))
        return BatchData(out, device=device)

    # CXCYWH -> XYXY
    cx, cy, w, h = boxes_f.unbind(dim=1)
    x1 = cx - 0.5 * w
    y1 = cy - 0.5 * h
    x2 = cx + 0.5 * w
    y2 = cy + 0.5 * h
    boxes_xyxy_f = torch.stack((x1, y1, x2, y2), dim=1)

    # Single global class-aware batched NMS across the whole batch.
    # Encode image id into the category id so boxes from different images
    # never suppress each other.
    try:
        from torchvision.ops import batched_nms

        nms_ids = labels_f + image_ids * int(C)
        keep_idx = batched_nms(boxes_xyxy_f, conf_f, nms_ids, float(pp.nms_iou))
    except Exception:
        # Fallback preserving class-aware, image-aware behavior
        keep_chunks = []
        for b in range(B):
            m_img = image_ids == b
            if not m_img.any():
                continue

            img_idx = torch.nonzero(m_img, as_tuple=False).squeeze(1)
            boxes_b = boxes_xyxy_f[m_img]
            conf_b = conf_f[m_img]
            labels_b = labels_f[m_img]

            for cls_id in labels_b.unique(sorted=True).tolist():
                m_cls = labels_b == cls_id
                if not m_cls.any():
                    continue
                cls_idx_local = torch.nonzero(m_cls, as_tuple=False).squeeze(1)
                keep_local = _greedy_nms(
                    boxes_b[m_cls], conf_b[m_cls], float(pp.nms_iou)
                )
                keep_chunks.append(img_idx[cls_idx_local[keep_local]])

        if len(keep_chunks) > 0:
            keep_idx = torch.cat(keep_chunks, dim=0)
            keep_idx = keep_idx[torch.argsort(conf_f[keep_idx], descending=True)]
        else:
            keep_idx = torch.empty((0,), dtype=torch.long, device=device)

    boxes_xyxy_f = boxes_xyxy_f[keep_idx]
    conf_f = conf_f[keep_idx]
    labels_f = labels_f[keep_idx]
    image_ids = image_ids[keep_idx]

    # Global score sort; then each per-image slice is already sorted by confidence
    order = torch.argsort(conf_f, descending=True)
    boxes_xyxy_f = boxes_xyxy_f[order]
    conf_f = conf_f[order]
    labels_f = labels_f[order]
    image_ids = image_ids[order]

    for b in range(B):
        m = image_ids == b
        boxes_xyxy = boxes_xyxy_f[m]
        conf_b = conf_f[m]
        labels_b = labels_f[m]

        if boxes_xyxy.shape[0] > int(pp.max_det):
            boxes_xyxy = boxes_xyxy[: int(pp.max_det)]
            conf_b = conf_b[: int(pp.max_det)]
            labels_b = labels_b[: int(pp.max_det)]

        if boxes_xyxy.shape[0] == 0:
            out.append(BboxData.empty((H, W), device=device))
            continue

        out.append(
            BboxData(
                boxes_xyxy,
                labels=labels_b,
                canvas_size=(H, W),
                boxformat="XYXY",
                scores=conf_b,
                device=device,
            )
        )

    return BatchData(out, device=device)

undo_preproc(preds, *, original_hw=None)

Remove padding to recover original spatial size (center-crop).

Parameters:

Name Type Description Default
preds deepvisiontools.data.BatchData

Predictions after preds_from_raw.

required
original_hw Tuple[int, int] | None

Original (H, W) before padding. If None or there are no objects, returns preds unchanged.

None

Returns:

Name Type Description
BatchData deepvisiontools.data.BatchData

Cropped predictions to original size when needed.

Source code in src/deepvisiontools/models/yolo/yolo.py
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def undo_preproc(
    self, preds: BatchData, *, original_hw: tuple[int, int] | None = None
) -> BatchData:
    """
    Remove padding to recover original spatial size (center-crop).

    Args:
        preds (BatchData): Predictions after `preds_from_raw`.
        original_hw (Tuple[int, int] | None): Original `(H, W)` before padding. If
            `None` or there are no objects, returns `preds` unchanged.

    Returns:
        BatchData: Cropped predictions to original size when needed.
    """
    if original_hw is None or preds.nb_object == 0:
        return preds
    orig_h, orig_w = original_hw
    canvas = preds.canvas_size
    if not canvas:
        return preds
    cur_h, cur_w = canvas
    if (orig_h, orig_w) == (cur_h, cur_w):
        return preds
    top = max((cur_h - orig_h) // 2, 0)
    left = max((cur_w - orig_w) // 2, 0)
    cropped = [d.crop(top, left, orig_h, orig_w) for d in preds.datas]
    return BatchData(cropped, device=preds.device)

YOLOPre(pad_multiple)

Bases: torch.nn.Module

Preprocessor for YOLO
  • Pads images to the model's stride multiple (e.g., 32/64/16) which is inferred from arch name (p2 -> 16, normal is 32 etc.).
  • When targets are provided, pads each item consistently and converts them to Ultralytics format via _targets_for_yolo (normalized CXCYWH).

Parameters:

Name Type Description Default
pad_multiple int

Padding stride multiple (e.g., 32).

required
Source code in src/deepvisiontools/models/yolo/yolo.py
675
676
677
def __init__(self, pad_multiple: int) -> None:
    super().__init__()
    self.pad_multiple = int(pad_multiple)

images_only(images)

Pad images so height/width are divisible by pad_multiple.

Parameters:

Name Type Description Default
images Tensor

[B, C, H, W].

required

Returns:

Name Type Description
Tensor torch.Tensor

Padded images on the same device/dtype.

Source code in src/deepvisiontools/models/yolo/yolo.py
679
680
681
682
683
684
685
686
687
688
689
690
def images_only(self, images: torch.Tensor) -> torch.Tensor:
    """
    Pad images so height/width are divisible by `pad_multiple`.

    Args:
        images (Tensor): `[B, C, H, W]`.

    Returns:
        Tensor: Padded images on the same device/dtype.
    """
    images, _ = _pad_to_multiple(images, self.pad_multiple)
    return images

images_targets(images, targets)

Pad images and targets, then produce Ultralytics target dict.

Parameters:

Name Type Description Default
images Tensor

[B, C, H, W].

required
targets deepvisiontools.data.BatchData

Bbox or instance mask targets aligned with images.

required

Returns:

Type Description
torch.Tensor

Tuple[Tensor, Dict[str, Tensor]]: Padded images and YOLO-ready targets:

dict[str, torch.Tensor]

{"batch_idx": [N,1], "cls": [N,1], "bboxes": [N,4]} with CXCYWH normalized.

Notes

The returned target dict is moved to the same device as images.

Source code in src/deepvisiontools/models/yolo/yolo.py
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
def images_targets(
    self, images: torch.Tensor, targets: BatchData
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
    """
    Pad images and targets, then produce Ultralytics target dict.

    Args:
        images (Tensor): `[B, C, H, W]`.
        targets (BatchData): Bbox or instance mask targets aligned with `images`.

    Returns:
        Tuple[Tensor, Dict[str, Tensor]]: Padded images and YOLO-ready targets:
        `{"batch_idx": [N,1], "cls": [N,1], "bboxes": [N,4]}` with CXCYWH normalized.

    Notes:
        The returned target dict is moved to the **same device** as `images`.
    """
    images, (left, t, r, b) = _pad_to_multiple(images, self.pad_multiple)
    if targets.nb_object > 0:
        padded = [d.pad(left, t, r, b) for d in targets.datas]
        targets = BatchData(padded, device=targets.device)
    _H, _W = images.shape[-2:]
    y = _targets_for_yolo(targets)

    # move YOLO target dict to same device as images
    img_dev = images.device
    y = {k: (v.to(img_dev) if torch.is_tensor(v) else v) for k, v in y.items()}

    return images, y

YoloPredParams(conf_threshold, nms_iou, max_det) dataclass

Bases: deepvisiontools.models.base.basemodel.BasePredParams

Post-processing (inference-time) parameters for YOLO decoding (conf threshold, max_det, nms threshold).

Parameters:

Name Type Description Default
conf_threshold float

Minimum class confidence to keep a prediction before NMS.

required
nms_iou float

IoU threshold used by NMS.

required
max_det int

Maximum number of detections to keep per image after NMS.

required
Note

These parameters are read by YOLOPost.preds_from_raw through the aux={"pred": ...} dictionary provided by DeepVisionModel and are persisted in whole-object saves.

build_yolo(*, arch='yolov8n', pretrained=True, num_classes=None, loss=None, loss_factor=1.0, hyp=None, supports_amp=True, autocast_dtype=torch.float16, device=None, use_amp=None, **extras)

Build a DeepVision YOLO detection wrapper, registered as "yolo".

This builder wraps an Ultralytics YOLO detection model inside the DeepVisionTools DeepVisionModel API. It wires YOLO-specific preprocessing, postprocessing, loss handling and prediction parameters so the model can be used with train_step, eval_step, predict, checkpointing and export helpers.

Parameters:

Name Type Description Default
arch Literal[...

YOLO detection architecture name. Supported values include YOLOv8 and YOLO11 variants, with optional -p6 or -p2 stride variants. Defaults to "yolov8n".

'yolov8n'
pretrained bool

If True, initialize the model from Ultralytics pretrained weights for the selected architecture. Defaults to True.

True
num_classes int | None

Number of detection classes. When None, it is taken from current().data_box.num_classes. Defaults to None.

None
loss typing.Any | None

Custom Ultralytics-compatible criterion. If None, the default vendor criterion is created from the internal YOLO runner. Defaults to None.

None
loss_factor float

Divisor applied to the reported YOLO losses. Useful to rescale vendor loss values. Defaults to 1.0.

1.0
hyp deepvisiontools.models.yolo.yolo.YoloLossParams | None

YOLO loss gains for box, cls and dfl losses. If None, default YoloLossParams values are used. Defaults to None.

None
supports_amp bool

Whether this backend supports autocast mixed precision. Defaults to True.

True
autocast_dtype torch.dtype

Autocast dtype used by DeepVisionModel. Defaults to torch.float16.

torch.float16
device str | torch.device | None

Device used to place the model. If None, device resolution is delegated to DeepVisionModel. Defaults to None.

None
use_amp bool | None

Force-enable or force-disable AMP. If None, the global/default DeepVisionTools AMP policy is used. Defaults to None.

None
extras typing.Any

Additional keyword arguments kept for registry/export compatibility.

{}

Returns:

Name Type Description
DeepVisionModel deepvisiontools.models.base.basemodel.DeepVisionModel

A fully wired detection model with bbox capabilities and

deepvisiontools.models.base.basemodel.DeepVisionModel

default YoloPredParams loaded from the current configuration.

Export behavior

Saved artifacts are rebuilt with pretrained=False before loading the saved state dict. This avoids downloading vendor weights again when restoring a deepvisiontools checkpoint.

Usage
import torch

from deepvisiontools.models import ModelFactory

# Minimal YOLOv8 detector
model = ModelFactory(
    name="yolo",
    arch="yolov8n",
    pretrained=True,
    num_classes=3,
)

# YOLO11 detector on a selected device
model = ModelFactory(
    name="yolo",
    arch="yolo11m",
    pretrained=True,
    num_classes=3,
    device="cuda",
    use_amp=True,
)

# Larger stride variant, useful for larger objects
model = ModelFactory(
    name="yolo",
    arch="yolov8m-p6",
    pretrained=True,
    num_classes=3,
)

# Custom YOLO loss gains
model = ModelFactory(
    name="yolo",
    arch="yolov8n",
    num_classes=3,
    hyp=YoloLossParams(box=7.5, cls=0.5, dfl=1.5),
)

# Inference returns BatchData containing BboxData items.
images = torch.randn(2, 3, 512, 512)
preds = model.predict(images)
preds.data_type == "bbox"
>>> True
Source code in src/deepvisiontools/models/yolo/yolo.py
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
@MODEL_REGISTRY.register("yolo")
def build_yolo(
    *,
    arch: Literal[
        "yolov8n",
        "yolov8m",
        "yolov8l",
        "yolov8x",
        "yolov8n-p6",
        "yolov8m-p6",
        "yolov8l-p6",
        "yolov8x-p6",
        "yolov8n-p2",
        "yolov8m-p2",
        "yolov8l-p2",
        "yolov8x-p2",
        "yolo11n",
        "yolo11m",
        "yolo11l",
        "yolo11x",
    ] = "yolov8n",
    pretrained: bool = True,
    num_classes: int | None = None,
    loss: Any | None = None,
    loss_factor: float = 1.0,
    hyp: YoloLossParams | None = None,
    supports_amp: bool = True,
    autocast_dtype: torch.dtype = torch.float16,
    device: str | torch.device | None = None,
    use_amp: bool | None = None,
    **extras: Any,
) -> DeepVisionModel:
    """
    Build a DeepVision YOLO detection wrapper, registered as `"yolo"`.

    This builder wraps an Ultralytics YOLO detection model inside the DeepVisionTools
    `DeepVisionModel` API. It wires YOLO-specific preprocessing, postprocessing,
    loss handling and prediction parameters so the model can be used with
    `train_step`, `eval_step`, `predict`, checkpointing and export helpers.

    Args:
        arch (Literal[..., optional): YOLO detection architecture name. Supported
            values include YOLOv8 and YOLO11 variants, with optional `-p6` or `-p2`
            stride variants. Defaults to `"yolov8n"`.
        pretrained (bool, optional): If True, initialize the model from Ultralytics
            pretrained weights for the selected architecture. Defaults to True.
        num_classes (int | None, optional): Number of detection classes. When None,
            it is taken from `current().data_box.num_classes`. Defaults to None.
        loss (Any | None, optional): Custom Ultralytics-compatible criterion. If None,
            the default vendor criterion is created from the internal YOLO runner.
            Defaults to None.
        loss_factor (float, optional): Divisor applied to the reported YOLO losses.
            Useful to rescale vendor loss values. Defaults to 1.0.
        hyp (YoloLossParams | None, optional): YOLO loss gains for box, cls and dfl
            losses. If None, default `YoloLossParams` values are used. Defaults to None.
        supports_amp (bool, optional): Whether this backend supports autocast mixed
            precision. Defaults to True.
        autocast_dtype (torch.dtype, optional): Autocast dtype used by
            `DeepVisionModel`. Defaults to `torch.float16`.
        device (str | torch.device | None, optional): Device used to place the model.
            If None, device resolution is delegated to `DeepVisionModel`. Defaults to None.
        use_amp (bool | None, optional): Force-enable or force-disable AMP. If None,
            the global/default DeepVisionTools AMP policy is used. Defaults to None.
        extras: Additional keyword arguments kept for registry/export compatibility.

    Returns:
        DeepVisionModel: A fully wired detection model with `bbox` capabilities and
        default `YoloPredParams` loaded from the current configuration.

    ???+ note "Export behavior"
        Saved artifacts are rebuilt with `pretrained=False` before loading the saved
        state dict. This avoids downloading vendor weights again when restoring a
        deepvisiontools checkpoint.

    ???+ example "Usage"
        ```python
        import torch

        from deepvisiontools.models import ModelFactory

        # Minimal YOLOv8 detector
        model = ModelFactory(
            name="yolo",
            arch="yolov8n",
            pretrained=True,
            num_classes=3,
        )

        # YOLO11 detector on a selected device
        model = ModelFactory(
            name="yolo",
            arch="yolo11m",
            pretrained=True,
            num_classes=3,
            device="cuda",
            use_amp=True,
        )

        # Larger stride variant, useful for larger objects
        model = ModelFactory(
            name="yolo",
            arch="yolov8m-p6",
            pretrained=True,
            num_classes=3,
        )

        # Custom YOLO loss gains
        model = ModelFactory(
            name="yolo",
            arch="yolov8n",
            num_classes=3,
            hyp=YoloLossParams(box=7.5, cls=0.5, dfl=1.5),
        )

        # Inference returns BatchData containing BboxData items.
        images = torch.randn(2, 3, 512, 512)
        preds = model.predict(images)
        preds.data_type == "bbox"
        >>> True
        ```
    """
    num_classes = (
        int(current().data_box.num_classes) if num_classes is None else int(num_classes)
    )
    if num_classes < 1:
        raise ValueError(f"num_classes must be >= 1, got {num_classes}.")

    backend = YOLOBackend(
        arch=arch,
        pretrained=pretrained,
        num_classes=num_classes,
        hyp=hyp,
    )
    pre = YOLOPre(pad_multiple=_stride_from_arch(arch))
    post = YOLOPost()

    if loss is None:
        runner = cast(Any, backend._runner)
        criterion = runner.model.init_criterion()
        loss_fn = YOLOLoss(criterion, loss_factor=loss_factor)
    else:
        loss_fn = YOLOLoss(loss, loss_factor=loss_factor)

    caps = Capabilities(
        task="bbox",
        supports_amp=supports_amp,
        requires_divisible=_stride_from_arch(arch),
        description=f"Ultralytics YOLO:{arch}",
    )

    model = DeepVisionModel(
        backend=backend,
        pre=pre,
        post=post,
        loss_fn=loss_fn,
        caps=caps,
        autocast_dtype=autocast_dtype,
        device=device,
        use_amp=use_amp,
    )

    model.pred_params = YoloPredParams.default_from_config()

    # Artifact rebuild kwargs are not the original initialization recipe.
    # They are the minimal, side-effect-free architecture recipe used before loading
    # the saved DeepVision state_dict.
    export_kwargs = {
        "arch": arch,
        "num_classes": num_classes,
        **extras,
    }
    export_kwargs["pretrained"] = False

    model.set_export_spec("yolo", export_kwargs)

    return model