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 |
required |
num_classes
|
int | None
|
Number of classes; when |
None
|
hyp
|
deepvisiontools.models.yolo.yolo.YoloLossParams | None
|
Loss gains for Ultralytics criterion. If |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
model |
ultralytics.nn.tasks.DetectionModel
|
Underlying Ultralytics detection model. |
pad_mult |
int
|
Padding multiple inferred from |
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 | |
forward(x, extra_args=None)
¶
Single forward for train/eval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
|
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 | |
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
|
Source code in src/deepvisiontools/models/yolo/yolo.py
740 741 742 743 | |
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 | |
forward(preds, targs)
¶
Compute the YOLO loss and return a detailed dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
preds
|
typing.Any
|
Raw outputs from |
required |
targs
|
Dict[str, Tensor]
|
Ultralytics-style targets with keys
|
required |
Returns:
| Type | Description |
|---|---|
dict[str, torch.Tensor]
|
Dict[str, Tensor]: At minimum |
dict[str, torch.Tensor]
|
|
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 | |
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
|
|
required |
aux
|
dict
|
Extra context with:
- "pred": |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BatchData |
deepvisiontools.data.BatchData
|
One |
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 | |
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 |
required |
original_hw
|
Tuple[int, int] | None
|
Original |
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 | |
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 | |
images_only(images)
¶
Pad images so height/width are divisible by pad_multiple.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Tensor
|
|
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 | |
images_targets(images, targets)
¶
Pad images and targets, then produce Ultralytics target dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Tensor
|
|
required |
targets
|
deepvisiontools.data.BatchData
|
Bbox or instance mask targets aligned with |
required |
Returns:
| Type | Description |
|---|---|
torch.Tensor
|
Tuple[Tensor, Dict[str, Tensor]]: Padded images and YOLO-ready targets: |
dict[str, torch.Tensor]
|
|
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 | |
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 |
'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 |
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 |
None
|
supports_amp
|
bool
|
Whether this backend supports autocast mixed precision. Defaults to True. |
True
|
autocast_dtype
|
torch.dtype
|
Autocast dtype used by
|
torch.float16
|
device
|
str | torch.device | None
|
Device used to place the model.
If None, device resolution is delegated to |
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 |
deepvisiontools.models.base.basemodel.DeepVisionModel
|
default |
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 | |