ultralytics 8.3.98__py3-none-any.whl → 8.3.100__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tests/test_python.py +56 -0
- ultralytics/__init__.py +3 -2
- ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
- ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
- ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
- ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
- ultralytics/data/augment.py +101 -5
- ultralytics/data/dataset.py +165 -12
- ultralytics/engine/exporter.py +5 -4
- ultralytics/engine/trainer.py +16 -7
- ultralytics/models/__init__.py +2 -2
- ultralytics/models/yolo/__init__.py +3 -3
- ultralytics/models/yolo/detect/val.py +6 -1
- ultralytics/models/yolo/model.py +183 -3
- ultralytics/models/yolo/segment/val.py +43 -16
- ultralytics/models/yolo/yoloe/__init__.py +21 -0
- ultralytics/models/yolo/yoloe/predict.py +170 -0
- ultralytics/models/yolo/yoloe/train.py +355 -0
- ultralytics/models/yolo/yoloe/train_seg.py +141 -0
- ultralytics/models/yolo/yoloe/val.py +187 -0
- ultralytics/nn/autobackend.py +17 -7
- ultralytics/nn/modules/__init__.py +18 -1
- ultralytics/nn/modules/block.py +17 -1
- ultralytics/nn/modules/head.py +359 -22
- ultralytics/nn/tasks.py +276 -10
- ultralytics/nn/text_model.py +193 -0
- ultralytics/utils/benchmarks.py +1 -0
- ultralytics/utils/callbacks/comet.py +3 -6
- ultralytics/utils/downloads.py +6 -2
- ultralytics/utils/loss.py +67 -6
- ultralytics/utils/plotting.py +1 -1
- ultralytics/utils/tal.py +1 -1
- {ultralytics-8.3.98.dist-info → ultralytics-8.3.100.dist-info}/METADATA +10 -10
- {ultralytics-8.3.98.dist-info → ultralytics-8.3.100.dist-info}/RECORD +38 -28
- {ultralytics-8.3.98.dist-info → ultralytics-8.3.100.dist-info}/WHEEL +0 -0
- {ultralytics-8.3.98.dist-info → ultralytics-8.3.100.dist-info}/entry_points.txt +0 -0
- {ultralytics-8.3.98.dist-info → ultralytics-8.3.100.dist-info}/licenses/LICENSE +0 -0
- {ultralytics-8.3.98.dist-info → ultralytics-8.3.100.dist-info}/top_level.txt +0 -0
@@ -364,29 +364,56 @@ class SegmentationValidator(DetectionValidator):
|
|
364
364
|
|
365
365
|
def eval_json(self, stats):
|
366
366
|
"""Return COCO-style object detection evaluation metrics."""
|
367
|
-
if self.args.save_json and self.is_coco and len(self.jdict):
|
368
|
-
anno_json = self.data["path"] / "annotations/instances_val2017.json" # annotations
|
367
|
+
if self.args.save_json and (self.is_lvis or self.is_coco) and len(self.jdict):
|
369
368
|
pred_json = self.save_dir / "predictions.json" # predictions
|
370
|
-
LOGGER.info(f"\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...")
|
371
|
-
try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
|
372
|
-
check_requirements("pycocotools>=2.0.6")
|
373
|
-
from pycocotools.coco import COCO # noqa
|
374
|
-
from pycocotools.cocoeval import COCOeval # noqa
|
375
369
|
|
370
|
+
anno_json = (
|
371
|
+
self.data["path"]
|
372
|
+
/ "annotations"
|
373
|
+
/ ("instances_val2017.json" if self.is_coco else f"lvis_v1_{self.args.split}.json")
|
374
|
+
) # annotations
|
375
|
+
|
376
|
+
pkg = "pycocotools" if self.is_coco else "lvis"
|
377
|
+
LOGGER.info(f"\nEvaluating {pkg} mAP using {pred_json} and {anno_json}...")
|
378
|
+
try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
|
376
379
|
for x in anno_json, pred_json:
|
377
380
|
assert x.is_file(), f"{x} file not found"
|
378
|
-
|
379
|
-
|
380
|
-
|
381
|
-
|
382
|
-
|
381
|
+
check_requirements("pycocotools>=2.0.6" if self.is_coco else "lvis>=0.5.3")
|
382
|
+
if self.is_coco:
|
383
|
+
from pycocotools.coco import COCO # noqa
|
384
|
+
from pycocotools.cocoeval import COCOeval # noqa
|
385
|
+
|
386
|
+
anno = COCO(str(anno_json)) # init annotations api
|
387
|
+
pred = anno.loadRes(str(pred_json)) # init predictions api (must pass string, not Path)
|
388
|
+
vals = [COCOeval(anno, pred, "bbox"), COCOeval(anno, pred, "segm")]
|
389
|
+
else:
|
390
|
+
from lvis import LVIS, LVISEval
|
391
|
+
|
392
|
+
anno = LVIS(str(anno_json))
|
393
|
+
pred = anno._load_json(str(pred_json))
|
394
|
+
vals = [LVISEval(anno, pred, "bbox"), LVISEval(anno, pred, "segm")]
|
395
|
+
|
396
|
+
for i, eval in enumerate(vals):
|
397
|
+
eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files] # im to eval
|
383
398
|
eval.evaluate()
|
384
399
|
eval.accumulate()
|
385
400
|
eval.summarize()
|
401
|
+
if self.is_lvis:
|
402
|
+
eval.print_results()
|
386
403
|
idx = i * 4 + 2
|
387
|
-
|
388
|
-
|
389
|
-
|
404
|
+
# update mAP50-95 and mAP50
|
405
|
+
stats[self.metrics.keys[idx + 1]], stats[self.metrics.keys[idx]] = (
|
406
|
+
eval.stats[:2] if self.is_coco else [eval.results["AP"], eval.results["AP50"]]
|
407
|
+
)
|
408
|
+
if self.is_lvis:
|
409
|
+
tag = "B" if i == 0 else "M"
|
410
|
+
stats[f"metrics/APr({tag})"] = eval.results["APr"]
|
411
|
+
stats[f"metrics/APc({tag})"] = eval.results["APc"]
|
412
|
+
stats[f"metrics/APf({tag})"] = eval.results["APf"]
|
413
|
+
|
414
|
+
if self.is_lvis:
|
415
|
+
stats["fitness"] = stats["metrics/mAP50-95(B)"]
|
416
|
+
|
390
417
|
except Exception as e:
|
391
|
-
LOGGER.warning(f"
|
418
|
+
LOGGER.warning(f"{pkg} unable to run: {e}")
|
392
419
|
return stats
|
@@ -0,0 +1,21 @@
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
|
+
|
3
|
+
from .predict import YOLOEVPDetectPredictor, YOLOEVPSegPredictor
|
4
|
+
from .train import YOLOEPEFreeTrainer, YOLOEPETrainer, YOLOETrainer, YOLOEVPTrainer
|
5
|
+
from .train_seg import YOLOEPESegTrainer, YOLOESegTrainer, YOLOESegTrainerFromScratch, YOLOESegVPTrainer
|
6
|
+
from .val import YOLOEDetectValidator, YOLOESegValidator
|
7
|
+
|
8
|
+
__all__ = [
|
9
|
+
"YOLOETrainer",
|
10
|
+
"YOLOEPETrainer",
|
11
|
+
"YOLOESegTrainer",
|
12
|
+
"YOLOEDetectValidator",
|
13
|
+
"YOLOESegValidator",
|
14
|
+
"YOLOEPESegTrainer",
|
15
|
+
"YOLOESegTrainerFromScratch",
|
16
|
+
"YOLOESegVPTrainer",
|
17
|
+
"YOLOEVPTrainer",
|
18
|
+
"YOLOEPEFreeTrainer",
|
19
|
+
"YOLOEVPDetectPredictor",
|
20
|
+
"YOLOEVPSegPredictor",
|
21
|
+
]
|
@@ -0,0 +1,170 @@
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
|
+
|
3
|
+
|
4
|
+
import numpy as np
|
5
|
+
import torch
|
6
|
+
|
7
|
+
from ultralytics.data.augment import LoadVisualPrompt
|
8
|
+
from ultralytics.models.yolo.detect import DetectionPredictor
|
9
|
+
from ultralytics.models.yolo.segment import SegmentationPredictor
|
10
|
+
|
11
|
+
|
12
|
+
class YOLOEVPDetectPredictor(DetectionPredictor):
|
13
|
+
"""
|
14
|
+
A mixin class for YOLO-EVP (Enhanced Visual Prompting) predictors.
|
15
|
+
|
16
|
+
This mixin provides common functionality for YOLO models that use visual prompting, including
|
17
|
+
model setup, prompt handling, and preprocessing transformations.
|
18
|
+
|
19
|
+
Attributes:
|
20
|
+
model (torch.nn.Module): The YOLO model for inference.
|
21
|
+
device (torch.device): Device to run the model on (CPU or CUDA).
|
22
|
+
prompts (dict): Visual prompts containing class indices and bounding boxes or masks.
|
23
|
+
|
24
|
+
Methods:
|
25
|
+
setup_model: Initialize the YOLO model and set it to evaluation mode.
|
26
|
+
set_return_vpe: Set whether to return visual prompt embeddings.
|
27
|
+
set_prompts: Set the visual prompts for the model.
|
28
|
+
pre_transform: Preprocess images and prompts before inference.
|
29
|
+
inference: Run inference with visual prompts.
|
30
|
+
"""
|
31
|
+
|
32
|
+
def setup_model(self, model, verbose=True):
|
33
|
+
"""
|
34
|
+
Sets up the model for prediction.
|
35
|
+
|
36
|
+
Args:
|
37
|
+
model (torch.nn.Module): Model to load or use.
|
38
|
+
verbose (bool): If True, provides detailed logging.
|
39
|
+
"""
|
40
|
+
super().setup_model(model, verbose=verbose)
|
41
|
+
self.done_warmup = True
|
42
|
+
|
43
|
+
def set_prompts(self, prompts):
|
44
|
+
"""
|
45
|
+
Set the visual prompts for the model.
|
46
|
+
|
47
|
+
Args:
|
48
|
+
prompts (dict): Dictionary containing class indices and bounding boxes or masks.
|
49
|
+
Must include a 'cls' key with class indices.
|
50
|
+
"""
|
51
|
+
self.prompts = prompts
|
52
|
+
|
53
|
+
def pre_transform(self, im):
|
54
|
+
"""
|
55
|
+
Preprocess images and prompts before inference.
|
56
|
+
|
57
|
+
This method applies letterboxing to the input image and transforms the visual prompts
|
58
|
+
(bounding boxes or masks) accordingly.
|
59
|
+
|
60
|
+
Args:
|
61
|
+
im (list): List containing a single input image.
|
62
|
+
|
63
|
+
Returns:
|
64
|
+
(list): Preprocessed image ready for model inference.
|
65
|
+
|
66
|
+
Raises:
|
67
|
+
ValueError: If neither valid bounding boxes nor masks are provided in the prompts.
|
68
|
+
"""
|
69
|
+
img = super().pre_transform(im)
|
70
|
+
bboxes = self.prompts.pop("bboxes", None)
|
71
|
+
masks = self.prompts.pop("masks", None)
|
72
|
+
category = self.prompts["cls"]
|
73
|
+
if len(img) == 1:
|
74
|
+
visuals = self._process_single_image(img[0].shape[:2], im[0].shape[:2], category, bboxes, masks)
|
75
|
+
self.prompts = visuals.unsqueeze(0).to(self.device) # (1, N, H, W)
|
76
|
+
else:
|
77
|
+
# NOTE: only supports bboxes as prompts for now
|
78
|
+
assert bboxes is not None, f"Expected bboxes, but got {bboxes}!"
|
79
|
+
# NOTE: needs List[np.ndarray]
|
80
|
+
assert isinstance(bboxes, list) and all(isinstance(b, np.ndarray) for b in bboxes), (
|
81
|
+
f"Expected List[np.ndarray], but got {bboxes}!"
|
82
|
+
)
|
83
|
+
assert isinstance(category, list) and all(isinstance(b, np.ndarray) for b in category), (
|
84
|
+
f"Expected List[np.ndarray], but got {category}!"
|
85
|
+
)
|
86
|
+
assert len(im) == len(category) == len(bboxes), (
|
87
|
+
f"Expected same length for all inputs, but got {len(im)}vs{len(category)}vs{len(bboxes)}!"
|
88
|
+
)
|
89
|
+
visuals = [
|
90
|
+
self._process_single_image(img[i].shape[:2], im[i].shape[:2], category[i], bboxes[i])
|
91
|
+
for i in range(len(img))
|
92
|
+
]
|
93
|
+
self.prompts = torch.nn.utils.rnn.pad_sequence(visuals, batch_first=True).to(self.device)
|
94
|
+
|
95
|
+
return img
|
96
|
+
|
97
|
+
def _process_single_image(self, dst_shape, src_shape, category, bboxes=None, masks=None):
|
98
|
+
"""
|
99
|
+
Processes a single image by resizing bounding boxes or masks and generating visuals.
|
100
|
+
|
101
|
+
Args:
|
102
|
+
dst_shape (tuple): The target shape (height, width) of the image.
|
103
|
+
src_shape (tuple): The original shape (height, width) of the image.
|
104
|
+
category (str): The category of the image for visual prompts.
|
105
|
+
bboxes (list | np.ndarray, optional): A list of bounding boxes in the format [x1, y1, x2, y2]. Defaults to None.
|
106
|
+
masks (np.ndarray, optional): A list of masks corresponding to the image. Defaults to None.
|
107
|
+
|
108
|
+
Returns:
|
109
|
+
visuals: The processed visuals for the image.
|
110
|
+
|
111
|
+
Raises:
|
112
|
+
ValueError: If neither `bboxes` nor `masks` are provided.
|
113
|
+
"""
|
114
|
+
if bboxes is not None and len(bboxes):
|
115
|
+
bboxes = np.array(bboxes, dtype=np.float32)
|
116
|
+
if bboxes.ndim == 1:
|
117
|
+
bboxes = bboxes[None, :]
|
118
|
+
# Calculate scaling factor and adjust bounding boxes
|
119
|
+
gain = min(dst_shape[0] / src_shape[0], dst_shape[1] / src_shape[1]) # gain = old / new
|
120
|
+
bboxes *= gain
|
121
|
+
bboxes[..., 0::2] += round((dst_shape[1] - src_shape[1] * gain) / 2 - 0.1)
|
122
|
+
bboxes[..., 1::2] += round((dst_shape[0] - src_shape[0] * gain) / 2 - 0.1)
|
123
|
+
elif masks is not None:
|
124
|
+
# Resize and process masks
|
125
|
+
resized_masks = super().pre_transform(masks)
|
126
|
+
masks = np.stack(resized_masks) # (N, H, W)
|
127
|
+
masks[masks == 114] = 0 # Reset padding values to 0
|
128
|
+
else:
|
129
|
+
raise ValueError("Please provide valid bboxes or masks")
|
130
|
+
|
131
|
+
# Generate visuals using the visual prompt loader
|
132
|
+
return LoadVisualPrompt().get_visuals(category, dst_shape, bboxes, masks)
|
133
|
+
|
134
|
+
def inference(self, im, *args, **kwargs):
|
135
|
+
"""
|
136
|
+
Run inference with visual prompts.
|
137
|
+
|
138
|
+
Args:
|
139
|
+
im (torch.Tensor): Input image tensor.
|
140
|
+
*args (Any): Variable length argument list.
|
141
|
+
**kwargs (Any): Arbitrary keyword arguments.
|
142
|
+
|
143
|
+
Returns:
|
144
|
+
(torch.Tensor): Model prediction results.
|
145
|
+
"""
|
146
|
+
return super().inference(im, vpe=self.prompts, *args, **kwargs)
|
147
|
+
|
148
|
+
def get_vpe(self, source):
|
149
|
+
"""
|
150
|
+
Processes the source to get the visual prompt embeddings (VPE).
|
151
|
+
|
152
|
+
Args:
|
153
|
+
source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | List | Tuple): The source
|
154
|
+
of the image to make predictions on. Accepts various types including file paths, URLs, PIL
|
155
|
+
images, numpy arrays, and torch tensors.
|
156
|
+
|
157
|
+
Returns:
|
158
|
+
(torch.Tensor): The visual prompt embeddings (VPE) from the model.
|
159
|
+
"""
|
160
|
+
self.setup_source(source)
|
161
|
+
assert len(self.dataset) == 1, "get_vpe only supports one image!"
|
162
|
+
for _, im0s, _ in self.dataset:
|
163
|
+
im = self.preprocess(im0s)
|
164
|
+
return self.model(im, vpe=self.prompts, return_vpe=True)
|
165
|
+
|
166
|
+
|
167
|
+
class YOLOEVPSegPredictor(YOLOEVPDetectPredictor, SegmentationPredictor):
|
168
|
+
"""Predictor for YOLOE VP segmentation."""
|
169
|
+
|
170
|
+
pass
|
@@ -0,0 +1,355 @@
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
|
+
|
3
|
+
import itertools
|
4
|
+
from copy import copy, deepcopy
|
5
|
+
from pathlib import Path
|
6
|
+
|
7
|
+
import torch
|
8
|
+
|
9
|
+
from ultralytics.data import YOLOConcatDataset, build_grounding, build_yolo_dataset
|
10
|
+
from ultralytics.data.augment import LoadVisualPrompt
|
11
|
+
from ultralytics.data.utils import check_det_dataset
|
12
|
+
from ultralytics.models.yolo.detect import DetectionTrainer, DetectionValidator
|
13
|
+
from ultralytics.nn.tasks import YOLOEModel
|
14
|
+
from ultralytics.utils import DEFAULT_CFG, LOGGER, RANK
|
15
|
+
from ultralytics.utils.torch_utils import de_parallel
|
16
|
+
|
17
|
+
from .val import YOLOEDetectValidator
|
18
|
+
|
19
|
+
|
20
|
+
class YOLOETrainer(DetectionTrainer):
|
21
|
+
"""A base trainer for YOLOE training."""
|
22
|
+
|
23
|
+
def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
|
24
|
+
"""
|
25
|
+
Initialize the YOLOE Trainer with specified configurations.
|
26
|
+
|
27
|
+
This method sets up the YOLOE trainer with the provided configuration and overrides, initializing
|
28
|
+
the training environment, model, and callbacks for YOLOE object detection training.
|
29
|
+
|
30
|
+
Args:
|
31
|
+
cfg (dict): Configuration dictionary with default training settings from DEFAULT_CFG.
|
32
|
+
overrides (dict, optional): Dictionary of parameter overrides for the default configuration.
|
33
|
+
_callbacks (list, optional): List of callback functions to be applied during training.
|
34
|
+
"""
|
35
|
+
if overrides is None:
|
36
|
+
overrides = {}
|
37
|
+
overrides["overlap_mask"] = False
|
38
|
+
super().__init__(cfg, overrides, _callbacks)
|
39
|
+
|
40
|
+
def get_model(self, cfg=None, weights=None, verbose=True):
|
41
|
+
"""Return YOLOEModel initialized with specified config and weights."""
|
42
|
+
# NOTE: This `nc` here is the max number of different text samples in one image, rather than the actual `nc`.
|
43
|
+
# NOTE: Following the official config, nc hard-coded to 80 for now.
|
44
|
+
model = YOLOEModel(
|
45
|
+
cfg["yaml_file"] if isinstance(cfg, dict) else cfg,
|
46
|
+
ch=3,
|
47
|
+
nc=min(self.data["nc"], 80),
|
48
|
+
verbose=verbose and RANK == -1,
|
49
|
+
)
|
50
|
+
if weights:
|
51
|
+
model.load(weights)
|
52
|
+
|
53
|
+
return model
|
54
|
+
|
55
|
+
def get_validator(self):
|
56
|
+
"""Returns a DetectionValidator for YOLO model validation."""
|
57
|
+
self.loss_names = "box", "cls", "dfl"
|
58
|
+
return YOLOEDetectValidator(
|
59
|
+
self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks
|
60
|
+
)
|
61
|
+
|
62
|
+
def build_dataset(self, img_path, mode="train", batch=None):
|
63
|
+
"""
|
64
|
+
Build YOLO Dataset.
|
65
|
+
|
66
|
+
Args:
|
67
|
+
img_path (str): Path to the folder containing images.
|
68
|
+
mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.
|
69
|
+
batch (int, optional): Size of batches, this is for `rect`.
|
70
|
+
|
71
|
+
Returns:
|
72
|
+
(Dataset): YOLO dataset configured for training or validation.
|
73
|
+
"""
|
74
|
+
gs = max(int(de_parallel(self.model).stride.max() if self.model else 0), 32)
|
75
|
+
return build_yolo_dataset(
|
76
|
+
self.args, img_path, batch, self.data, mode=mode, rect=mode == "val", stride=gs, multi_modal=mode == "train"
|
77
|
+
)
|
78
|
+
|
79
|
+
def preprocess_batch(self, batch):
|
80
|
+
"""Process batch for training, moving text features to the appropriate device."""
|
81
|
+
batch = super().preprocess_batch(batch)
|
82
|
+
return batch
|
83
|
+
|
84
|
+
|
85
|
+
class YOLOEPETrainer(DetectionTrainer):
|
86
|
+
"""Fine-tune YOLOE model in linear probing way."""
|
87
|
+
|
88
|
+
def get_model(self, cfg=None, weights=None, verbose=True):
|
89
|
+
"""
|
90
|
+
Return YOLOEModel initialized with specified config and weights.
|
91
|
+
|
92
|
+
Args:
|
93
|
+
cfg (dict | str, optional): Model configuration.
|
94
|
+
weights (str, optional): Path to pretrained weights.
|
95
|
+
verbose (bool): Whether to display model information.
|
96
|
+
|
97
|
+
Returns:
|
98
|
+
(YOLOEModel): Initialized model with frozen layers except for specific projection layers.
|
99
|
+
"""
|
100
|
+
# NOTE: This `nc` here is the max number of different text samples in one image, rather than the actual `nc`.
|
101
|
+
# NOTE: Following the official config, nc hard-coded to 80 for now.
|
102
|
+
model = YOLOEModel(
|
103
|
+
cfg["yaml_file"] if isinstance(cfg, dict) else cfg,
|
104
|
+
ch=3,
|
105
|
+
nc=self.data["nc"],
|
106
|
+
verbose=verbose and RANK == -1,
|
107
|
+
)
|
108
|
+
|
109
|
+
del model.model[-1].savpe
|
110
|
+
|
111
|
+
assert weights is not None, "Pretrained weights must be provided for linear probing."
|
112
|
+
if weights:
|
113
|
+
model.load(weights)
|
114
|
+
|
115
|
+
model.eval()
|
116
|
+
names = list(self.data["names"].values())
|
117
|
+
# NOTE: `get_text_pe` related to text model and YOLOEDetect.reprta,
|
118
|
+
# it'd get correct results as long as loading proper pretrained weights.
|
119
|
+
tpe = model.get_text_pe(names)
|
120
|
+
model.set_classes(names, tpe)
|
121
|
+
model.model[-1].fuse(model.pe) # fuse text embeddings to classify head
|
122
|
+
model.model[-1].cv3[0][2] = deepcopy(model.model[-1].cv3[0][2]).requires_grad_(True)
|
123
|
+
model.model[-1].cv3[1][2] = deepcopy(model.model[-1].cv3[1][2]).requires_grad_(True)
|
124
|
+
model.model[-1].cv3[2][2] = deepcopy(model.model[-1].cv3[2][2]).requires_grad_(True)
|
125
|
+
del model.pe
|
126
|
+
model.train()
|
127
|
+
|
128
|
+
return model
|
129
|
+
|
130
|
+
|
131
|
+
class YOLOETrainerFromScratch(YOLOETrainer):
|
132
|
+
"""Train YOLOE models from scratch."""
|
133
|
+
|
134
|
+
def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
|
135
|
+
"""
|
136
|
+
Initialize the YOLOETrainerFromScratch class.
|
137
|
+
|
138
|
+
This class extends YOLOETrainer to train YOLOE models from scratch. It inherits all functionality from
|
139
|
+
the parent class while providing specialized initialization for training without pre-trained weights.
|
140
|
+
|
141
|
+
Args:
|
142
|
+
cfg (dict, optional): Configuration dictionary with training parameters. Defaults to DEFAULT_CFG.
|
143
|
+
overrides (dict, optional): Dictionary of parameter overrides for configuration.
|
144
|
+
_callbacks (list, optional): List of callback functions to be executed during training.
|
145
|
+
|
146
|
+
Examples:
|
147
|
+
>>> from ultralytics.models.yoloe.train import YOLOETrainerFromScratch
|
148
|
+
>>> trainer = YOLOETrainerFromScratch()
|
149
|
+
>>> trainer.train()
|
150
|
+
"""
|
151
|
+
if overrides is None:
|
152
|
+
overrides = {}
|
153
|
+
super().__init__(cfg, overrides, _callbacks)
|
154
|
+
|
155
|
+
def build_dataset(self, img_path, mode="train", batch=None):
|
156
|
+
"""
|
157
|
+
Build YOLO Dataset for training or validation.
|
158
|
+
|
159
|
+
This method constructs appropriate datasets based on the mode and input paths, handling both
|
160
|
+
standard YOLO datasets and grounding datasets with different formats.
|
161
|
+
|
162
|
+
Args:
|
163
|
+
img_path (List[str] | str): Path to the folder containing images or list of paths.
|
164
|
+
mode (str): 'train' mode or 'val' mode, allowing customized augmentations for each mode.
|
165
|
+
batch (int, optional): Size of batches, used for rectangular training/validation.
|
166
|
+
|
167
|
+
Returns:
|
168
|
+
(YOLOConcatDataset | Dataset): The constructed dataset for training or validation.
|
169
|
+
"""
|
170
|
+
gs = max(int(de_parallel(self.model).stride.max() if self.model else 0), 32)
|
171
|
+
if mode != "train":
|
172
|
+
return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, rect=False, stride=gs)
|
173
|
+
datasets = [
|
174
|
+
build_yolo_dataset(self.args, im_path, batch, self.training_data[im_path], stride=gs, multi_modal=True)
|
175
|
+
if isinstance(im_path, str)
|
176
|
+
else build_grounding(self.args, im_path["img_path"], im_path["json_file"], batch, stride=gs)
|
177
|
+
for im_path in img_path
|
178
|
+
]
|
179
|
+
self.set_text_embeddings(datasets, batch) # cache text embeddings to accelerate training
|
180
|
+
return YOLOConcatDataset(datasets) if len(datasets) > 1 else datasets[0]
|
181
|
+
|
182
|
+
def set_text_embeddings(self, datasets, batch):
|
183
|
+
"""Set text embeddings for datasets to accelerate training by caching category names."""
|
184
|
+
# TODO: open up an interface to determine whether to do cache
|
185
|
+
category_names = set()
|
186
|
+
for dataset in datasets:
|
187
|
+
if not hasattr(dataset, "category_names"):
|
188
|
+
continue
|
189
|
+
category_names |= dataset.category_names
|
190
|
+
|
191
|
+
# TODO: enable to update the path or use a more general way to get the path
|
192
|
+
img_path = datasets[0].img_path
|
193
|
+
self.text_embeddings = self.generate_text_embeddings(
|
194
|
+
category_names, batch, cache_path=Path(img_path).parent / "text_embeddings.pt"
|
195
|
+
)
|
196
|
+
|
197
|
+
def preprocess_batch(self, batch):
|
198
|
+
"""Process batch for training, moving text features to the appropriate device."""
|
199
|
+
batch = super().preprocess_batch(batch)
|
200
|
+
|
201
|
+
texts = list(itertools.chain(*batch["texts"]))
|
202
|
+
txt_feats = torch.stack([self.text_embeddings[text] for text in texts]).to(self.device)
|
203
|
+
txt_feats = txt_feats.reshape(len(batch["texts"]), -1, txt_feats.shape[-1])
|
204
|
+
batch["txt_feats"] = txt_feats
|
205
|
+
return batch
|
206
|
+
|
207
|
+
def generate_text_embeddings(self, texts, batch, cache_path="embeddings.pt"):
|
208
|
+
"""
|
209
|
+
Generate text embeddings for a list of text samples.
|
210
|
+
|
211
|
+
Args:
|
212
|
+
texts (List[str]): List of text samples to encode.
|
213
|
+
batch (int): Batch size for processing.
|
214
|
+
cache_path (str | Path): Path to save/load cached embeddings.
|
215
|
+
|
216
|
+
Returns:
|
217
|
+
(dict): Dictionary mapping text samples to their embeddings.
|
218
|
+
"""
|
219
|
+
if cache_path.exists():
|
220
|
+
return torch.load(cache_path)
|
221
|
+
assert self.model is not None
|
222
|
+
txt_feats = self.model.get_text_pe(texts, batch, without_reprta=True)
|
223
|
+
txt_map = dict(zip(texts, txt_feats.squeeze(0)))
|
224
|
+
torch.save(txt_map, cache_path)
|
225
|
+
return txt_map
|
226
|
+
|
227
|
+
def get_dataset(self):
|
228
|
+
"""
|
229
|
+
Get train and validation paths from data dictionary.
|
230
|
+
|
231
|
+
Processes the data configuration to extract paths for training and validation datasets,
|
232
|
+
handling both YOLO detection datasets and grounding datasets.
|
233
|
+
|
234
|
+
Returns:
|
235
|
+
(str): Train dataset path.
|
236
|
+
(str): Validation dataset path.
|
237
|
+
|
238
|
+
Raises:
|
239
|
+
AssertionError: If train or validation datasets are not found, or if validation has multiple datasets.
|
240
|
+
"""
|
241
|
+
final_data = {}
|
242
|
+
data_yaml = self.args.data
|
243
|
+
assert data_yaml.get("train", False), "train dataset not found" # object365.yaml
|
244
|
+
assert data_yaml.get("val", False), "validation dataset not found" # lvis.yaml
|
245
|
+
data = {k: [check_det_dataset(d) for d in v.get("yolo_data", [])] for k, v in data_yaml.items()}
|
246
|
+
assert len(data["val"]) == 1, f"Only support validating on 1 dataset for now, but got {len(data['val'])}."
|
247
|
+
val_split = "minival" if "lvis" in data["val"][0]["val"] else "val"
|
248
|
+
for d in data["val"]:
|
249
|
+
if d.get("minival") is None: # for lvis dataset
|
250
|
+
continue
|
251
|
+
d["minival"] = str(d["path"] / d["minival"])
|
252
|
+
for s in ["train", "val"]:
|
253
|
+
final_data[s] = [d["train" if s == "train" else val_split] for d in data[s]]
|
254
|
+
# save grounding data if there's one
|
255
|
+
grounding_data = data_yaml[s].get("grounding_data")
|
256
|
+
if grounding_data is None:
|
257
|
+
continue
|
258
|
+
grounding_data = grounding_data if isinstance(grounding_data, list) else [grounding_data]
|
259
|
+
for g in grounding_data:
|
260
|
+
assert isinstance(g, dict), f"Grounding data should be provided in dict format, but got {type(g)}"
|
261
|
+
final_data[s] += grounding_data
|
262
|
+
# NOTE: to make training work properly, set `nc` and `names`
|
263
|
+
final_data["nc"] = data["val"][0]["nc"]
|
264
|
+
final_data["names"] = data["val"][0]["names"]
|
265
|
+
# NOTE: add path with lvis path
|
266
|
+
final_data["path"] = data["val"][0]["path"]
|
267
|
+
self.data = final_data
|
268
|
+
if self.args.single_cls: # consistent with base trainer
|
269
|
+
LOGGER.info("Overriding class names with single class.")
|
270
|
+
self.data["names"] = {0: "object"}
|
271
|
+
self.data["nc"] = 1
|
272
|
+
self.training_data = {}
|
273
|
+
for d in data["train"]:
|
274
|
+
if self.args.single_cls:
|
275
|
+
d["names"] = {0: "object"}
|
276
|
+
d["nc"] = 1
|
277
|
+
self.training_data[d["train"]] = d
|
278
|
+
return final_data["train"], final_data["val"][0]
|
279
|
+
|
280
|
+
def plot_training_labels(self):
|
281
|
+
"""Do not plot labels for YOLO-World training."""
|
282
|
+
pass
|
283
|
+
|
284
|
+
def final_eval(self):
|
285
|
+
"""
|
286
|
+
Perform final evaluation on the validation dataset.
|
287
|
+
|
288
|
+
Configures the validator with the appropriate dataset and split before running evaluation.
|
289
|
+
|
290
|
+
Returns:
|
291
|
+
(dict): Evaluation metrics.
|
292
|
+
"""
|
293
|
+
val = self.args.data["val"]["yolo_data"][0]
|
294
|
+
self.validator.args.data = val
|
295
|
+
self.validator.args.split = "minival" if isinstance(val, str) and "lvis" in val else "val"
|
296
|
+
return super().final_eval()
|
297
|
+
|
298
|
+
|
299
|
+
class YOLOEPEFreeTrainer(YOLOEPETrainer, YOLOETrainerFromScratch):
|
300
|
+
"""Train prompt-free YOLOE model."""
|
301
|
+
|
302
|
+
def get_validator(self):
|
303
|
+
"""Returns a DetectionValidator for YOLO model validation."""
|
304
|
+
self.loss_names = "box", "cls", "dfl"
|
305
|
+
return DetectionValidator(
|
306
|
+
self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks
|
307
|
+
)
|
308
|
+
|
309
|
+
def preprocess_batch(self, batch):
|
310
|
+
"""Preprocesses a batch of images for YOLOE training, adjusting formatting and dimensions as needed."""
|
311
|
+
batch = super(YOLOETrainer, self).preprocess_batch(batch)
|
312
|
+
return batch
|
313
|
+
|
314
|
+
def set_text_embeddings(self, datasets, batch):
|
315
|
+
"""No need to set text embeddings for prompt-free fine-tuning."""
|
316
|
+
pass
|
317
|
+
|
318
|
+
|
319
|
+
class YOLOEVPTrainer(YOLOETrainerFromScratch):
|
320
|
+
"""Train YOLOE model with visual prompts."""
|
321
|
+
|
322
|
+
def build_dataset(self, img_path, mode="train", batch=None):
|
323
|
+
"""
|
324
|
+
Build YOLO Dataset for training or validation with visual prompts.
|
325
|
+
|
326
|
+
Args:
|
327
|
+
img_path (List[str] | str): Path to the folder containing images or list of paths.
|
328
|
+
mode (str): 'train' mode or 'val' mode, allowing customized augmentations for each mode.
|
329
|
+
batch (int, optional): Size of batches, used for rectangular training/validation.
|
330
|
+
|
331
|
+
Returns:
|
332
|
+
(Dataset): YOLO dataset configured for training or validation, with visual prompts for training mode.
|
333
|
+
"""
|
334
|
+
dataset = super().build_dataset(img_path, mode, batch)
|
335
|
+
if isinstance(dataset, YOLOConcatDataset):
|
336
|
+
for d in dataset.datasets:
|
337
|
+
d.transforms.append(LoadVisualPrompt())
|
338
|
+
else:
|
339
|
+
dataset.transforms.append(LoadVisualPrompt())
|
340
|
+
return dataset
|
341
|
+
|
342
|
+
def _close_dataloader_mosaic(self):
|
343
|
+
"""Close mosaic augmentation and add visual prompt loading to the training dataset."""
|
344
|
+
super()._close_dataloader_mosaic()
|
345
|
+
if isinstance(self.train_loader.dataset, YOLOConcatDataset):
|
346
|
+
for d in self.train_loader.dataset.datasets:
|
347
|
+
d.transforms.append(LoadVisualPrompt())
|
348
|
+
else:
|
349
|
+
self.train_loader.dataset.transforms.append(LoadVisualPrompt())
|
350
|
+
|
351
|
+
def preprocess_batch(self, batch):
|
352
|
+
"""Preprocesses a batch of images for YOLOE training, moving visual prompts to the appropriate device."""
|
353
|
+
batch = super().preprocess_batch(batch)
|
354
|
+
batch["visuals"] = batch["visuals"].to(self.device)
|
355
|
+
return batch
|