Reference for ultralytics/utils/loss.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/utils/loss.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.utils.loss.VarifocalLoss
VarifocalLoss(gamma: float = 2.0, alpha: float = 0.75)
Bases: Module
Varifocal loss by Zhang et al.
Implements the Varifocal Loss function for addressing class imbalance in object detection by focusing on hard-to-classify examples and balancing positive/negative samples.
Attributes:
Name | Type | Description |
---|---|---|
gamma |
float
|
The focusing parameter that controls how much the loss focuses on hard-to-classify examples. |
alpha |
float
|
The balancing factor used to address class imbalance. |
References
Source code in ultralytics/utils/loss.py
35 36 37 38 39 |
|
forward
forward(pred_score: Tensor, gt_score: Tensor, label: Tensor) -> torch.Tensor
Compute varifocal loss between predictions and ground truth.
Source code in ultralytics/utils/loss.py
41 42 43 44 45 46 47 48 49 50 |
|
ultralytics.utils.loss.FocalLoss
FocalLoss(gamma: float = 1.5, alpha: float = 0.25)
Bases: Module
Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5).
Implements the Focal Loss function for addressing class imbalance by down-weighting easy examples and focusing on hard negatives during training.
Attributes:
Name | Type | Description |
---|---|---|
gamma |
float
|
The focusing parameter that controls how much the loss focuses on hard-to-classify examples. |
alpha |
Tensor
|
The balancing factor used to address class imbalance. |
Source code in ultralytics/utils/loss.py
65 66 67 68 69 |
|
forward
forward(pred: Tensor, label: Tensor) -> torch.Tensor
Calculate focal loss with modulating factors for class imbalance.
Source code in ultralytics/utils/loss.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
|
ultralytics.utils.loss.DFLoss
DFLoss(reg_max: int = 16)
Bases: Module
Criterion class for computing Distribution Focal Loss (DFL).
Source code in ultralytics/utils/loss.py
92 93 94 95 |
|
__call__
__call__(pred_dist: Tensor, target: Tensor) -> torch.Tensor
Return sum of left and right DFL losses from https://ieeexplore.ieee.org/document/9792391.
Source code in ultralytics/utils/loss.py
97 98 99 100 101 102 103 104 105 106 107 |
|
ultralytics.utils.loss.BboxLoss
BboxLoss(reg_max: int = 16)
Bases: Module
Criterion class for computing training losses for bounding boxes.
Source code in ultralytics/utils/loss.py
113 114 115 116 |
|
forward
forward(
pred_dist: Tensor,
pred_bboxes: Tensor,
anchor_points: Tensor,
target_bboxes: Tensor,
target_scores: Tensor,
target_scores_sum: Tensor,
fg_mask: Tensor,
) -> tuple[torch.Tensor, torch.Tensor]
Compute IoU and DFL losses for bounding boxes.
Source code in ultralytics/utils/loss.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
|
ultralytics.utils.loss.RotatedBboxLoss
RotatedBboxLoss(reg_max: int)
Bases: BboxLoss
Criterion class for computing training losses for rotated bounding boxes.
Source code in ultralytics/utils/loss.py
147 148 149 |
|
forward
forward(
pred_dist: Tensor,
pred_bboxes: Tensor,
anchor_points: Tensor,
target_bboxes: Tensor,
target_scores: Tensor,
target_scores_sum: Tensor,
fg_mask: Tensor,
) -> tuple[torch.Tensor, torch.Tensor]
Compute IoU and DFL losses for rotated bounding boxes.
Source code in ultralytics/utils/loss.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
|
ultralytics.utils.loss.KeypointLoss
KeypointLoss(sigmas: Tensor)
Bases: Module
Criterion class for computing keypoint losses.
Source code in ultralytics/utils/loss.py
180 181 182 183 |
|
forward
forward(
pred_kpts: Tensor, gt_kpts: Tensor, kpt_mask: Tensor, area: Tensor
) -> torch.Tensor
Calculate keypoint loss factor and Euclidean distance loss for keypoints.
Source code in ultralytics/utils/loss.py
185 186 187 188 189 190 191 192 193 |
|
ultralytics.utils.loss.v8DetectionLoss
v8DetectionLoss(model, tal_topk: int = 10)
Criterion class for computing training losses for YOLOv8 object detection.
Source code in ultralytics/utils/loss.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
|
__call__
__call__(
preds: Any, batch: dict[str, Tensor]
) -> tuple[torch.Tensor, torch.Tensor]
Calculate the sum of the loss for box, cls and dfl multiplied by batch size.
Source code in ultralytics/utils/loss.py
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
|
bbox_decode
bbox_decode(anchor_points: Tensor, pred_dist: Tensor) -> torch.Tensor
Decode predicted object bounding box coordinates from anchor points and distribution.
Source code in ultralytics/utils/loss.py
236 237 238 239 240 241 242 243 |
|
preprocess
preprocess(
targets: Tensor, batch_size: int, scale_tensor: Tensor
) -> torch.Tensor
Preprocess targets by converting to tensor format and scaling coordinates.
Source code in ultralytics/utils/loss.py
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
|
ultralytics.utils.loss.v8SegmentationLoss
v8SegmentationLoss(model)
Bases: v8DetectionLoss
Criterion class for computing training losses for YOLOv8 segmentation.
Source code in ultralytics/utils/loss.py
305 306 307 308 |
|
__call__
__call__(
preds: Any, batch: dict[str, Tensor]
) -> tuple[torch.Tensor, torch.Tensor]
Calculate and return the combined loss for detection and segmentation.
Source code in ultralytics/utils/loss.py
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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
|
calculate_segmentation_loss
calculate_segmentation_loss(
fg_mask: Tensor,
masks: Tensor,
target_gt_idx: Tensor,
target_bboxes: Tensor,
batch_idx: Tensor,
proto: Tensor,
pred_masks: Tensor,
imgsz: Tensor,
overlap: bool,
) -> torch.Tensor
Calculate the loss for instance segmentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fg_mask
|
Tensor
|
A binary tensor of shape (BS, N_anchors) indicating which anchors are positive. |
required |
masks
|
Tensor
|
Ground truth masks of shape (BS, H, W) if |
required |
target_gt_idx
|
Tensor
|
Indexes of ground truth objects for each anchor of shape (BS, N_anchors). |
required |
target_bboxes
|
Tensor
|
Ground truth bounding boxes for each anchor of shape (BS, N_anchors, 4). |
required |
batch_idx
|
Tensor
|
Batch indices of shape (N_labels_in_batch, 1). |
required |
proto
|
Tensor
|
Prototype masks of shape (BS, 32, H, W). |
required |
pred_masks
|
Tensor
|
Predicted masks for each anchor of shape (BS, N_anchors, 32). |
required |
imgsz
|
Tensor
|
Size of the input image as a tensor of shape (2), i.e., (H, W). |
required |
overlap
|
bool
|
Whether the masks in |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The calculated loss for instance segmentation. |
Notes
The batch loss can be computed for improved speed at higher memory usage. For example, pred_mask can be computed as follows: pred_mask = torch.einsum('in,nhw->ihw', pred, proto) # (i, 32) @ (32, 160, 160) -> (i, 160, 160)
Source code in ultralytics/utils/loss.py
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 |
|
single_mask_loss
staticmethod
single_mask_loss(
gt_mask: Tensor, pred: Tensor, proto: Tensor, xyxy: Tensor, area: Tensor
) -> torch.Tensor
Compute the instance segmentation loss for a single image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
gt_mask
|
Tensor
|
Ground truth mask of shape (N, H, W), where N is the number of objects. |
required |
pred
|
Tensor
|
Predicted mask coefficients of shape (N, 32). |
required |
proto
|
Tensor
|
Prototype masks of shape (32, H, W). |
required |
xyxy
|
Tensor
|
Ground truth bounding boxes in xyxy format, normalized to [0, 1], of shape (N, 4). |
required |
area
|
Tensor
|
Area of each ground truth bounding box of shape (N,). |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The calculated mask loss for a single image. |
Notes
The function uses the equation pred_mask = torch.einsum('in,nhw->ihw', pred, proto) to produce the predicted masks from the prototype masks and predicted mask coefficients.
Source code in ultralytics/utils/loss.py
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 |
|
ultralytics.utils.loss.v8PoseLoss
v8PoseLoss(model)
Bases: v8DetectionLoss
Criterion class for computing training losses for YOLOv8 pose estimation.
Source code in ultralytics/utils/loss.py
488 489 490 491 492 493 494 495 496 |
|
__call__
__call__(
preds: Any, batch: dict[str, Tensor]
) -> tuple[torch.Tensor, torch.Tensor]
Calculate the total loss and detach it for pose estimation.
Source code in ultralytics/utils/loss.py
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 |
|
calculate_keypoints_loss
calculate_keypoints_loss(
masks: Tensor,
target_gt_idx: Tensor,
keypoints: Tensor,
batch_idx: Tensor,
stride_tensor: Tensor,
target_bboxes: Tensor,
pred_kpts: Tensor,
) -> tuple[torch.Tensor, torch.Tensor]
Calculate the keypoints loss for the model.
This function calculates the keypoints loss and keypoints object loss for a given batch. The keypoints loss is based on the difference between the predicted keypoints and ground truth keypoints. The keypoints object loss is a binary classification loss that classifies whether a keypoint is present or not.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
masks
|
Tensor
|
Binary mask tensor indicating object presence, shape (BS, N_anchors). |
required |
target_gt_idx
|
Tensor
|
Index tensor mapping anchors to ground truth objects, shape (BS, N_anchors). |
required |
keypoints
|
Tensor
|
Ground truth keypoints, shape (N_kpts_in_batch, N_kpts_per_object, kpts_dim). |
required |
batch_idx
|
Tensor
|
Batch index tensor for keypoints, shape (N_kpts_in_batch, 1). |
required |
stride_tensor
|
Tensor
|
Stride tensor for anchors, shape (N_anchors, 1). |
required |
target_bboxes
|
Tensor
|
Ground truth boxes in (x1, y1, x2, y2) format, shape (BS, N_anchors, 4). |
required |
pred_kpts
|
Tensor
|
Predicted keypoints, shape (BS, N_anchors, N_kpts_per_object, kpts_dim). |
required |
Returns:
Name | Type | Description |
---|---|---|
kpts_loss |
Tensor
|
The keypoints loss. |
kpts_obj_loss |
Tensor
|
The keypoints object loss. |
Source code in ultralytics/utils/loss.py
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 631 632 633 634 635 636 637 638 639 640 641 642 643 644 |
|
kpts_decode
staticmethod
kpts_decode(anchor_points: Tensor, pred_kpts: Tensor) -> torch.Tensor
Decode predicted keypoints to image coordinates.
Source code in ultralytics/utils/loss.py
564 565 566 567 568 569 570 571 |
|
ultralytics.utils.loss.v8ClassificationLoss
Criterion class for computing training losses for classification.
__call__
__call__(
preds: Any, batch: dict[str, Tensor]
) -> tuple[torch.Tensor, torch.Tensor]
Compute the classification loss between predictions and true labels.
Source code in ultralytics/utils/loss.py
650 651 652 653 654 |
|
ultralytics.utils.loss.v8OBBLoss
v8OBBLoss(model)
Bases: v8DetectionLoss
Calculates losses for object detection, classification, and box distribution in rotated YOLO models.
Source code in ultralytics/utils/loss.py
660 661 662 663 664 |
|
__call__
__call__(
preds: Any, batch: dict[str, Tensor]
) -> tuple[torch.Tensor, torch.Tensor]
Calculate and return the loss for oriented bounding box detection.
Source code in ultralytics/utils/loss.py
683 684 685 686 687 688 689 690 691 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 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 |
|
bbox_decode
bbox_decode(
anchor_points: Tensor, pred_dist: Tensor, pred_angle: Tensor
) -> torch.Tensor
Decode predicted object bounding box coordinates from anchor points and distribution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
anchor_points
|
Tensor
|
Anchor points, (h*w, 2). |
required |
pred_dist
|
Tensor
|
Predicted rotated distance, (bs, h*w, 4). |
required |
pred_angle
|
Tensor
|
Predicted angle, (bs, h*w, 1). |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Predicted rotated bounding boxes with angles, (bs, h*w, 5). |
Source code in ultralytics/utils/loss.py
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 |
|
preprocess
preprocess(
targets: Tensor, batch_size: int, scale_tensor: Tensor
) -> torch.Tensor
Preprocess targets for oriented bounding box detection.
Source code in ultralytics/utils/loss.py
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 |
|
ultralytics.utils.loss.E2EDetectLoss
E2EDetectLoss(model)
Criterion class for computing training losses for end-to-end detection.
Source code in ultralytics/utils/loss.py
778 779 780 781 |
|
__call__
__call__(
preds: Any, batch: dict[str, Tensor]
) -> tuple[torch.Tensor, torch.Tensor]
Calculate the sum of the loss for box, cls and dfl multiplied by batch size.
Source code in ultralytics/utils/loss.py
783 784 785 786 787 788 789 790 |
|
ultralytics.utils.loss.TVPDetectLoss
TVPDetectLoss(model)
Criterion class for computing training losses for text-visual prompt detection.
Source code in ultralytics/utils/loss.py
796 797 798 799 800 801 802 |
|
__call__
__call__(
preds: Any, batch: dict[str, Tensor]
) -> tuple[torch.Tensor, torch.Tensor]
Calculate the loss for text-visual prompt detection.
Source code in ultralytics/utils/loss.py
804 805 806 807 808 809 810 811 812 813 814 815 816 |
|
ultralytics.utils.loss.TVPSegmentLoss
TVPSegmentLoss(model)
Bases: TVPDetectLoss
Criterion class for computing training losses for text-visual prompt segmentation.
Source code in ultralytics/utils/loss.py
835 836 837 838 |
|
__call__
__call__(
preds: Any, batch: dict[str, Tensor]
) -> tuple[torch.Tensor, torch.Tensor]
Calculate the loss for text-visual prompt segmentation.
Source code in ultralytics/utils/loss.py
840 841 842 843 844 845 846 847 848 849 850 851 852 |
|