OBB val on box-only labels crashes with an IndexError in OBBValidator._prepare_batch instead of a dataset error
Search before asking
- I have searched the Ultralytics YOLO issues and found no similar bug report.
Ultralytics YOLO Component
Val, Train
Bug
Validating an OBB model on a dataset whose labels are plain class x y w h boxes crashes with an IndexError deep in the validator instead of an error that names the problem:
File "ultralytics/models/yolo/detect/val.py", line 227, in update_metrics
pbatch = self._prepare_batch(si, batch)
File "ultralytics/models/yolo/obb/val.py", line 129, in _prepare_batch
bbox = batch["bboxes"][idx]
IndexError: The shape of the mask [10] at index 0 does not match the shape of the indexed tensor [0, 5] at index 0Root cause: for task="obb" the Format transform builds labels["bboxes"] from instances.segments (xyxyxyxy2xywhr, ultralytics/data/augment.py line 2419). Box-only labels have no segments, so every image ends up with bboxes of shape (0, 5) while cls and batch_idx still hold the real number of objects. The batch is inconsistent before it reaches the validator.
The other two task mismatches already fail early with a message:
YOLODataset.verify_labels(ultralytics/data/dataset.pyline 242) raisesValueError: Segment dataset requires equal numbers of boxes and segments ... Please supply a segment dataset, not a detect dataset.for a segment model on a detect dataset.v8OBBLoss.loss(ultralytics/utils/loss.pyline 1080) catches the same inconsistency during training and raisesTypeError: OBB dataset incorrectly formatted or not a OBB dataset. This error can occur when incorrectly training a 'OBB' model on a 'detect' dataset, i.e. 'yolo train model=yolo26n-obb.pt data=coco8.yaml'.
Only the val path is left with the raw IndexError. verify_labels already has the counts it needs, it just only checks them when self.use_segments is set.
Proposed fix: extend the existing check in verify_labels to self.use_obb, with the same wording as the segment message. This also moves the training failure from the first loss call to dataset loading, before the model and optimizer are built, and covers the mixed case where some images have polygons and others do not (today that case strips all segments with a warning and then crashes the same way). A dataset with matching polygon and box counts, such as dota8, is unaffected: yolo11n-obb.pt on dota8.yaml gives identical metrics before and after (mAP50-95 0.8106).
Environment
Ultralytics 8.4.162 (main @ 0ea465b) Python-3.13.14 torch-2.14.0+cpu CPU (Intel Xeon Processor @ 2.90GHz)
OS Linux x86_64 (glibc 2.34), Environment Docker, Install git
GPU NoneMinimal Reproducible Example
from ultralytics import YOLO
YOLO("yolo11n-obb.pt").val(data="coco8.yaml", imgsz=320, device="cpu")
# IndexError: The shape of the mask [10] at index 0 does not match the shape of the indexed tensor [0, 5] at index 0The same holds for yolo val model=yolo26n-obb.pt data=coco8.yaml. Training, YOLO("yolo11n-obb.pt").train(data="coco8.yaml", epochs=1, imgsz=64), gets the friendly TypeError from the loss instead.
Additional
With the patch below both val and train on coco8.yaml stop at dataset loading with
ValueError: OBB dataset requires equal numbers of boxes and segments, but got len(segments) = 0, len(boxes) = 17. Please supply an OBB dataset, not a detect dataset.The new test test_obb_dataset_rejects_box_only_labels builds an OBB dataset on coco8.yaml through build_yolo_dataset, needs no weights, fails on main with DID NOT RAISE ValueError and passes with the change. ruff format --check and ruff check pass on both files.
Two questions for the maintainers: is the dataset level (next to the segment check) the right place for this, or would you rather see it in OBBValidator? And is the message wording fine, or should it point at https://docs.ultralytics.com/datasets/obb like the training error does? I am happy to adjust either.
Patch
The complete change is below so that nobody has to redo it; I will open it as the PR as soon as a maintainer confirms the direction.
git diff, 2 files, +13 -3diff --git a/tests/test_python.py b/tests/test_python.py
index 2264ca6..3078d7f 100644
--- a/tests/test_python.py
+++ b/tests/test_python.py
@@ -129,6 +129,14 @@ def test_image_cache_shared_with_spawned_workers():
assert cache.buffer.is_shared()
+def test_obb_dataset_rejects_box_only_labels():
+ """Test an OBB dataset built from plain box labels fails at load time like a segment dataset does."""
+ data = check_det_dataset("coco8.yaml")
+ cfg = get_cfg(overrides={"task": "obb", "data": "coco8.yaml", "imgsz": 32})
+ with pytest.raises(ValueError, match="OBB dataset requires equal numbers of boxes and segments"):
+ data_build.build_yolo_dataset(cfg, data["val"], batch=2, data=data, mode="val")
+
+
def test_build_yolo_dataset_hyp_isolated():
"""Test dataset construction never mutates hyperparameters on the shared cfg it was built from."""
data = check_det_dataset("coco8.yaml")
diff --git a/ultralytics/data/dataset.py b/ultralytics/data/dataset.py
index 4dbb7fb..e5271c8 100644
--- a/ultralytics/data/dataset.py
+++ b/ultralytics/data/dataset.py
@@ -239,10 +239,12 @@ class YOLODataset(BaseDataset):
# Check if the dataset is all boxes or all segments
lengths = ((len(lb["cls"]), len(lb["bboxes"]), len(lb["segments"])) for lb in labels)
len_cls, len_boxes, len_segments = (sum(x) for x in zip(*lengths))
- if self.use_segments and len_boxes != len_segments:
+ if (self.use_segments or self.use_obb) and len_boxes != len_segments:
+ task = "OBB" if self.use_obb else "Segment"
raise ValueError(
- f"Segment dataset requires equal numbers of boxes and segments, but got len(segments) = "
- f"{len_segments}, len(boxes) = {len_boxes}. Please supply a segment dataset, not a detect dataset."
+ f"{task} dataset requires equal numbers of boxes and segments, but got len(segments) = "
+ f"{len_segments}, len(boxes) = {len_boxes}. Please supply {'an OBB' if self.use_obb else 'a segment'} "
+ "dataset, not a detect dataset."
)
if len_segments and len_boxes != len_segments:
LOGGER.warning(AI disclosure: I used an AI coding agent to help write this patch, the tests and this description. I have read the change and the tests myself and I will answer review comments personally.
Are you willing to submit a PR?
- Yes I'd like to help by submitting a PR!
Source: ultralytics/ultralytics