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=2.0, alpha=0.75)
Bases: Module
Varifocal loss by Zhang et al.
https://arxiv.org/abs/2008.13367.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
gamma
|
float
|
The focusing parameter that controls how much the loss focuses on hard-to-classify examples. |
2.0
|
alpha
|
float
|
The balancing factor used to address class imbalance. |
0.75
|
Source code in ultralytics/utils/loss.py
27 28 29 30 31 |
|
forward
forward(pred_score, gt_score, label)
Compute varifocal loss between predictions and ground truth.
Source code in ultralytics/utils/loss.py
33 34 35 36 37 38 39 40 41 42 |
|
ultralytics.utils.loss.FocalLoss
FocalLoss(gamma=1.5, alpha=0.25)
Bases: Module
Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
gamma
|
float
|
The focusing parameter that controls how much the loss focuses on hard-to-classify examples. |
1.5
|
alpha
|
float
|
The balancing factor used to address class imbalance. |
0.25
|
Source code in ultralytics/utils/loss.py
54 55 56 57 58 |
|
forward
forward(pred, label)
Calculate focal loss with modulating factors for class imbalance.
Source code in ultralytics/utils/loss.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
|
ultralytics.utils.loss.DFLoss
DFLoss(reg_max=16)
Bases: Module
Criterion class for computing Distribution Focal Loss (DFL).
Source code in ultralytics/utils/loss.py
80 81 82 83 |
|
__call__
__call__(pred_dist, target)
Return sum of left and right DFL losses from https://ieeexplore.ieee.org/document/9792391.
Source code in ultralytics/utils/loss.py
85 86 87 88 89 90 91 92 93 94 95 |
|
ultralytics.utils.loss.BboxLoss
BboxLoss(reg_max=16)
Bases: Module
Criterion class for computing training losses for bounding boxes.
Source code in ultralytics/utils/loss.py
101 102 103 104 |
|
forward
forward(
pred_dist,
pred_bboxes,
anchor_points,
target_bboxes,
target_scores,
target_scores_sum,
fg_mask,
)
Compute IoU and DFL losses for bounding boxes.
Source code in ultralytics/utils/loss.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
|
ultralytics.utils.loss.RotatedBboxLoss
RotatedBboxLoss(reg_max)
Bases: BboxLoss
Criterion class for computing training losses for rotated bounding boxes.
Source code in ultralytics/utils/loss.py
126 127 128 |
|
forward
forward(
pred_dist,
pred_bboxes,
anchor_points,
target_bboxes,
target_scores,
target_scores_sum,
fg_mask,
)
Compute IoU and DFL losses for rotated bounding boxes.
Source code in ultralytics/utils/loss.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
|
ultralytics.utils.loss.KeypointLoss
KeypointLoss(sigmas)
Bases: Module
Criterion class for computing keypoint losses.
Source code in ultralytics/utils/loss.py
150 151 152 153 |
|
forward
forward(pred_kpts, gt_kpts, kpt_mask, area)
Calculate keypoint loss factor and Euclidean distance loss for keypoints.
Source code in ultralytics/utils/loss.py
155 156 157 158 159 160 161 |
|
ultralytics.utils.loss.v8DetectionLoss
v8DetectionLoss(model, tal_topk=10)
Criterion class for computing training losses for YOLOv8 object detection.
Source code in ultralytics/utils/loss.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
|
__call__
__call__(preds, batch)
Calculate the sum of the loss for box, cls and dfl multiplied by batch size.
Source code in ultralytics/utils/loss.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
|
bbox_decode
bbox_decode(anchor_points, pred_dist)
Decode predicted object bounding box coordinates from anchor points and distribution.
Source code in ultralytics/utils/loss.py
204 205 206 207 208 209 210 211 |
|
preprocess
preprocess(targets, batch_size, scale_tensor)
Preprocess targets by converting to tensor format and scaling coordinates.
Source code in ultralytics/utils/loss.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
|
ultralytics.utils.loss.v8SegmentationLoss
v8SegmentationLoss(model)
Bases: v8DetectionLoss
Criterion class for computing training losses for YOLOv8 segmentation.
Source code in ultralytics/utils/loss.py
273 274 275 276 |
|
__call__
__call__(preds, batch)
Calculate and return the combined loss for detection and segmentation.
Source code in ultralytics/utils/loss.py
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 |
|
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
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 414 415 416 417 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 |
|
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
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 |
|
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
456 457 458 459 460 461 462 463 464 |
|
__call__
__call__(preds, batch)
Calculate the total loss and detach it for pose estimation.
Source code in ultralytics/utils/loss.py
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 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 |
|
calculate_keypoints_loss
calculate_keypoints_loss(
masks,
target_gt_idx,
keypoints,
batch_idx,
stride_tensor,
target_bboxes,
pred_kpts,
)
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
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 |
|
kpts_decode
staticmethod
kpts_decode(anchor_points, pred_kpts)
Decode predicted keypoints to image coordinates.
Source code in ultralytics/utils/loss.py
532 533 534 535 536 537 538 539 |
|
ultralytics.utils.loss.v8ClassificationLoss
Criterion class for computing training losses for classification.
__call__
__call__(preds, batch)
Compute the classification loss between predictions and true labels.
Source code in ultralytics/utils/loss.py
611 612 613 614 615 616 |
|
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
622 623 624 625 626 |
|
__call__
__call__(preds, batch)
Calculate and return the loss for oriented bounding box detection.
Source code in ultralytics/utils/loss.py
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 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 |
|
bbox_decode
bbox_decode(anchor_points, pred_dist, pred_angle)
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
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 |
|
preprocess
preprocess(targets, batch_size, scale_tensor)
Preprocess targets for oriented bounding box detection.
Source code in ultralytics/utils/loss.py
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 |
|
ultralytics.utils.loss.E2EDetectLoss
E2EDetectLoss(model)
Criterion class for computing training losses for end-to-end detection.
Source code in ultralytics/utils/loss.py
738 739 740 741 |
|
__call__
__call__(preds, batch)
Calculate the sum of the loss for box, cls and dfl multiplied by batch size.
Source code in ultralytics/utils/loss.py
743 744 745 746 747 748 749 750 |
|
ultralytics.utils.loss.TVPDetectLoss
TVPDetectLoss(model)
Criterion class for computing training losses for text-visual prompt detection.
Source code in ultralytics/utils/loss.py
756 757 758 759 760 761 762 |
|
__call__
__call__(preds, batch)
Calculate the loss for text-visual prompt detection.
Source code in ultralytics/utils/loss.py
764 765 766 767 768 769 770 771 772 773 774 775 776 |
|
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
795 796 797 |
|
__call__
__call__(preds, batch)
Calculate the loss for text-visual prompt segmentation.
Source code in ultralytics/utils/loss.py
799 800 801 802 803 804 805 806 807 808 809 810 811 |
|