ultralytics 8.3.98__py3-none-any.whl → 8.3.99__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.
Files changed (37) hide show
  1. tests/test_python.py +56 -0
  2. ultralytics/__init__.py +3 -2
  3. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  4. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  5. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
  6. ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
  7. ultralytics/data/augment.py +101 -5
  8. ultralytics/data/dataset.py +165 -12
  9. ultralytics/engine/exporter.py +4 -3
  10. ultralytics/engine/trainer.py +16 -7
  11. ultralytics/models/__init__.py +2 -2
  12. ultralytics/models/yolo/__init__.py +3 -3
  13. ultralytics/models/yolo/detect/val.py +6 -1
  14. ultralytics/models/yolo/model.py +182 -3
  15. ultralytics/models/yolo/segment/val.py +43 -16
  16. ultralytics/models/yolo/yoloe/__init__.py +21 -0
  17. ultralytics/models/yolo/yoloe/predict.py +170 -0
  18. ultralytics/models/yolo/yoloe/train.py +355 -0
  19. ultralytics/models/yolo/yoloe/train_seg.py +141 -0
  20. ultralytics/models/yolo/yoloe/val.py +187 -0
  21. ultralytics/nn/autobackend.py +3 -2
  22. ultralytics/nn/modules/__init__.py +18 -1
  23. ultralytics/nn/modules/block.py +17 -1
  24. ultralytics/nn/modules/head.py +359 -22
  25. ultralytics/nn/tasks.py +276 -10
  26. ultralytics/nn/text_model.py +193 -0
  27. ultralytics/utils/callbacks/comet.py +3 -6
  28. ultralytics/utils/downloads.py +6 -2
  29. ultralytics/utils/loss.py +67 -6
  30. ultralytics/utils/plotting.py +1 -1
  31. ultralytics/utils/tal.py +1 -1
  32. {ultralytics-8.3.98.dist-info → ultralytics-8.3.99.dist-info}/METADATA +10 -10
  33. {ultralytics-8.3.98.dist-info → ultralytics-8.3.99.dist-info}/RECORD +37 -27
  34. {ultralytics-8.3.98.dist-info → ultralytics-8.3.99.dist-info}/WHEEL +0 -0
  35. {ultralytics-8.3.98.dist-info → ultralytics-8.3.99.dist-info}/entry_points.txt +0 -0
  36. {ultralytics-8.3.98.dist-info → ultralytics-8.3.99.dist-info}/licenses/LICENSE +0 -0
  37. {ultralytics-8.3.98.dist-info → ultralytics-8.3.99.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,141 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+
4
+ from copy import copy, deepcopy
5
+
6
+ from ultralytics.models.yolo.segment import SegmentationTrainer
7
+ from ultralytics.nn.tasks import YOLOESegModel
8
+ from ultralytics.utils import DEFAULT_CFG, RANK
9
+
10
+ from .train import YOLOETrainer, YOLOETrainerFromScratch, YOLOEVPTrainer
11
+ from .val import YOLOESegValidator
12
+
13
+
14
+ class YOLOESegTrainer(YOLOETrainer, SegmentationTrainer):
15
+ """
16
+ Trainer class for YOLOE segmentation models.
17
+
18
+ This class combines YOLOETrainer and SegmentationTrainer to provide training functionality
19
+ specifically for YOLOE segmentation models.
20
+
21
+ Attributes:
22
+ cfg (dict): Configuration dictionary with training parameters.
23
+ overrides (dict): Dictionary with parameter overrides.
24
+ _callbacks (list): List of callback functions for training events.
25
+ """
26
+
27
+ def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
28
+ """
29
+ Initialize the YOLOESegTrainer class.
30
+
31
+ This class combines YOLOETrainer and SegmentationTrainer to provide training functionality
32
+ specifically for YOLOE segmentation models.
33
+
34
+ Args:
35
+ cfg (Dict): Configuration dictionary with training parameters.
36
+ overrides (Dict, optional): Dictionary with parameter overrides.
37
+ _callbacks (List, optional): List of callback functions for training events.
38
+ """
39
+ if overrides is None:
40
+ overrides = {}
41
+ super().__init__(cfg, overrides, _callbacks)
42
+
43
+ def get_model(self, cfg=None, weights=None, verbose=True):
44
+ """
45
+ Return YOLOESegModel initialized with specified config and weights.
46
+
47
+ Args:
48
+ cfg (dict | str): Model configuration dictionary or YAML file path.
49
+ weights (str, optional): Path to pretrained weights file.
50
+ verbose (bool): Whether to display model information.
51
+
52
+ Returns:
53
+ (YOLOESegModel): Initialized YOLOE segmentation model.
54
+ """
55
+ # NOTE: This `nc` here is the max number of different text samples in one image, rather than the actual `nc`.
56
+ # NOTE: Following the official config, nc hard-coded to 80 for now.
57
+ model = YOLOESegModel(
58
+ cfg["yaml_file"] if isinstance(cfg, dict) else cfg,
59
+ ch=3,
60
+ nc=min(self.data["nc"], 80),
61
+ verbose=verbose and RANK == -1,
62
+ )
63
+ if weights:
64
+ model.load(weights)
65
+
66
+ return model
67
+
68
+ def get_validator(self):
69
+ """
70
+ Create and return a validator for YOLOE segmentation model evaluation.
71
+
72
+ Returns:
73
+ (YOLOESegValidator): Validator for YOLOE segmentation models.
74
+ """
75
+ self.loss_names = "box", "seg", "cls", "dfl"
76
+ return YOLOESegValidator(
77
+ self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks
78
+ )
79
+
80
+
81
+ class YOLOEPESegTrainer(SegmentationTrainer):
82
+ """
83
+ Fine-tune YOLOESeg model in linear probing way.
84
+
85
+ This trainer specializes in fine-tuning YOLOESeg models using a linear probing approach, which involves freezing
86
+ most of the model and only training specific layers.
87
+ """
88
+
89
+ def get_model(self, cfg=None, weights=None, verbose=True):
90
+ """
91
+ Return YOLOESegModel initialized with specified config and weights for linear probing.
92
+
93
+ Args:
94
+ cfg (dict | str): Model configuration dictionary or YAML file path.
95
+ weights (str, optional): Path to pretrained weights file.
96
+ verbose (bool): Whether to display model information.
97
+
98
+ Returns:
99
+ (YOLOESegModel): Initialized YOLOE segmentation model configured for linear probing.
100
+ """
101
+ # NOTE: This `nc` here is the max number of different text samples in one image, rather than the actual `nc`.
102
+ # NOTE: Following the official config, nc hard-coded to 80 for now.
103
+ model = YOLOESegModel(
104
+ cfg["yaml_file"] if isinstance(cfg, dict) else cfg,
105
+ ch=3,
106
+ nc=self.data["nc"],
107
+ verbose=verbose and RANK == -1,
108
+ )
109
+
110
+ del model.model[-1].savpe
111
+
112
+ assert weights is not None, "Pretrained weights must be provided for linear probing."
113
+ if weights:
114
+ model.load(weights)
115
+
116
+ model.eval()
117
+ names = list(self.data["names"].values())
118
+ # NOTE: `get_text_pe` related to text model and YOLOEDetect.reprta,
119
+ # it'd get correct results as long as loading proper pretrained weights.
120
+ tpe = model.get_text_pe(names)
121
+ model.set_classes(names, tpe)
122
+ model.model[-1].fuse(model.pe)
123
+ model.model[-1].cv3[0][2] = deepcopy(model.model[-1].cv3[0][2]).requires_grad_(True)
124
+ model.model[-1].cv3[1][2] = deepcopy(model.model[-1].cv3[1][2]).requires_grad_(True)
125
+ model.model[-1].cv3[2][2] = deepcopy(model.model[-1].cv3[2][2]).requires_grad_(True)
126
+ del model.pe
127
+ model.train()
128
+
129
+ return model
130
+
131
+
132
+ class YOLOESegTrainerFromScratch(YOLOETrainerFromScratch, YOLOESegTrainer):
133
+ """Trainer for YOLOE segmentation from scratch."""
134
+
135
+ pass
136
+
137
+
138
+ class YOLOESegVPTrainer(YOLOEVPTrainer, YOLOESegTrainerFromScratch):
139
+ """Trainer for YOLOE segmentation with VP."""
140
+
141
+ pass
@@ -0,0 +1,187 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from copy import deepcopy
4
+
5
+ import torch
6
+ from torch.nn import functional as F
7
+
8
+ from ultralytics.data import YOLOConcatDataset, build_dataloader, build_yolo_dataset
9
+ from ultralytics.data.augment import LoadVisualPrompt
10
+ from ultralytics.data.utils import check_det_dataset
11
+ from ultralytics.models.yolo.detect import DetectionValidator
12
+ from ultralytics.models.yolo.model import YOLOEModel
13
+ from ultralytics.models.yolo.segment import SegmentationValidator
14
+ from ultralytics.nn.modules.head import YOLOEDetect
15
+ from ultralytics.utils import LOGGER, TQDM
16
+ from ultralytics.utils.torch_utils import select_device, smart_inference_mode
17
+
18
+
19
+ class YOLOEDetectValidator(DetectionValidator):
20
+ """
21
+ A mixin class for YOLOE model validation that handles both text and visual prompt embeddings.
22
+
23
+ This mixin provides functionality to validate YOLOE models using either text or visual prompt embeddings.
24
+ It includes methods for extracting visual prompt embeddings from samples, preprocessing batches, and
25
+ running validation with different prompt types.
26
+
27
+ Attributes:
28
+ device (torch.device): The device on which validation is performed.
29
+ args (namespace): Configuration arguments for validation.
30
+ dataloader (DataLoader): DataLoader for validation data.
31
+ """
32
+
33
+ @smart_inference_mode()
34
+ def get_visual_pe(self, dataloader, model):
35
+ """
36
+ Extract visual prompt embeddings from training samples.
37
+
38
+ This function processes a dataloader to compute visual prompt embeddings for each class
39
+ using a YOLOE model. It normalizes the embeddings and handles cases where no samples
40
+ exist for a class.
41
+
42
+ Args:
43
+ dataloader (torch.utils.data.DataLoader): The dataloader providing training samples.
44
+ model (YOLOEModel): The YOLOE model from which to extract visual prompt embeddings.
45
+
46
+ Returns:
47
+ (torch.Tensor): Visual prompt embeddings with shape (1, num_classes, embed_dim).
48
+ """
49
+ assert isinstance(model, YOLOEModel)
50
+ names = [name.split("/")[0] for name in list(dataloader.dataset.data["names"].values())]
51
+ visual_pe = torch.zeros(len(names), model.model[-1].embed, device=self.device)
52
+ cls_visual_num = torch.zeros(len(names))
53
+
54
+ desc = "Get visual prompt embeddings from samples"
55
+
56
+ for batch in dataloader:
57
+ cls = batch["cls"].squeeze(-1).to(torch.int).unique()
58
+ count = torch.bincount(cls, minlength=len(names))
59
+ cls_visual_num += count
60
+
61
+ cls_visual_num = cls_visual_num.to(self.device)
62
+
63
+ pbar = TQDM(dataloader, total=len(dataloader), desc=desc)
64
+ for batch in pbar:
65
+ batch = self.preprocess(batch)
66
+ preds = model.get_visual_pe(batch["img"], visual=batch["visuals"]) # (B, max_n, embed_dim)
67
+
68
+ batch_idx = batch["batch_idx"]
69
+ for i in range(preds.shape[0]):
70
+ cls = batch["cls"][batch_idx == i].squeeze(-1).to(torch.int).unique(sorted=True)
71
+ pad_cls = torch.ones(preds.shape[1], device=self.device) * -1
72
+ pad_cls[: len(cls)] = cls
73
+ for c in cls:
74
+ visual_pe[c] += preds[i][pad_cls == c].sum(0) / cls_visual_num[c]
75
+
76
+ visual_pe[cls_visual_num != 0] = F.normalize(visual_pe[cls_visual_num != 0], dim=-1, p=2)
77
+ visual_pe[cls_visual_num == 0] = 0
78
+ return visual_pe.unsqueeze(0)
79
+
80
+ def preprocess(self, batch):
81
+ """Preprocess batch data, ensuring visuals are on the same device as images."""
82
+ batch = super().preprocess(batch)
83
+ if "visuals" in batch:
84
+ batch["visuals"] = batch["visuals"].to(batch["img"].device)
85
+ return batch
86
+
87
+ def get_vpe_dataloader(self, data):
88
+ """
89
+ Create a dataloader for LVIS training visual prompt samples.
90
+
91
+ This function prepares a dataloader for visual prompt embeddings (VPE) using the LVIS dataset.
92
+ It applies necessary transformations and configurations to the dataset and returns a dataloader
93
+ for validation purposes.
94
+
95
+ Args:
96
+ data (dict): Dataset configuration dictionary containing paths and settings.
97
+
98
+ Returns:
99
+ (torch.utils.data.DataLoader): The dataLoader for visual prompt samples.
100
+ """
101
+ dataset = build_yolo_dataset(
102
+ self.args,
103
+ data.get(self.args.split, data.get("val")),
104
+ self.args.batch,
105
+ data,
106
+ mode="val",
107
+ rect=False,
108
+ )
109
+ if isinstance(dataset, YOLOConcatDataset):
110
+ for d in dataset.datasets:
111
+ d.transforms.append(LoadVisualPrompt())
112
+ else:
113
+ dataset.transforms.append(LoadVisualPrompt())
114
+ return build_dataloader(
115
+ dataset,
116
+ self.args.batch,
117
+ self.args.workers,
118
+ shuffle=False,
119
+ rank=-1,
120
+ )
121
+
122
+ @smart_inference_mode()
123
+ def __call__(self, trainer=None, model=None, refer_data=None, load_vp=False):
124
+ """
125
+ Run validation on the model using either text or visual prompt embeddings.
126
+
127
+ This method validates the model using either text prompts or visual prompts, depending
128
+ on the `load_vp` flag. It supports validation during training (using a trainer object)
129
+ or standalone validation with a provided model.
130
+
131
+ Args:
132
+ trainer (object, optional): Trainer object containing the model and device.
133
+ model (YOLOEModel, optional): Model to validate. Required if `trainer` is not provided.
134
+ refer_data (str, optional): Path to reference data for visual prompts.
135
+ load_vp (bool): Whether to load visual prompts. If False, text prompts are used.
136
+
137
+ Returns:
138
+ (dict): Validation statistics containing metrics computed during validation.
139
+ """
140
+ if trainer is not None:
141
+ self.device = trainer.device
142
+ model = trainer.ema.ema
143
+ names = [name.split("/")[0] for name in list(self.dataloader.dataset.data["names"].values())]
144
+
145
+ if load_vp:
146
+ LOGGER.info("Validate using the visual prompt.")
147
+ self.args.half = False
148
+ # Directly use the same dataloader for visual embeddings extracted during training
149
+ vpe = self.get_visual_pe(self.dataloader, model)
150
+ model.set_classes(names, vpe)
151
+ else:
152
+ LOGGER.info("Validate using the text prompt.")
153
+ tpe = model.get_text_pe(names)
154
+ model.set_classes(names, tpe)
155
+ stats = super().__call__(trainer, model)
156
+ else:
157
+ if refer_data is not None:
158
+ assert load_vp, "Refer data is only used for visual prompt validation."
159
+ self.device = select_device(self.args.device)
160
+
161
+ model.eval().to(self.device)
162
+ data = check_det_dataset(refer_data or self.args.data)
163
+ names = [name.split("/")[0] for name in list(data["names"].values())]
164
+
165
+ if load_vp:
166
+ LOGGER.info("Validate using the visual prompt.")
167
+ self.args.half = False
168
+ # TODO: need to check if the names from refer data is consistent with the evaluated dataset
169
+ # could use same dataset or refer to extract visual prompt embeddings
170
+ dataloader = self.get_vpe_dataloader(data)
171
+ vpe = self.get_visual_pe(dataloader, model)
172
+ model.set_classes(names, vpe)
173
+ stats = super().__call__(model=deepcopy(model))
174
+ elif isinstance(model.model[-1], YOLOEDetect) and hasattr(model.model[-1], "lrpc"): # prompt-free
175
+ return super().__call__(trainer, model)
176
+ else:
177
+ LOGGER.info("Validate using the text prompt.")
178
+ tpe = model.get_text_pe(names)
179
+ model.set_classes(names, tpe)
180
+ stats = super().__call__(model=deepcopy(model))
181
+ return stats
182
+
183
+
184
+ class YOLOESegValidator(YOLOEDetectValidator, SegmentationValidator):
185
+ """YOLOE segmentation validator that supports both text and visual prompt embeddings."""
186
+
187
+ pass
@@ -546,7 +546,7 @@ class AutoBackend(nn.Module):
546
546
 
547
547
  self.__dict__.update(locals()) # assign all variables to self
548
548
 
549
- def forward(self, im, augment=False, visualize=False, embed=None):
549
+ def forward(self, im, augment=False, visualize=False, embed=None, **kwargs):
550
550
  """
551
551
  Runs inference on the YOLOv8 MultiBackend model.
552
552
 
@@ -555,6 +555,7 @@ class AutoBackend(nn.Module):
555
555
  augment (bool): Whether to perform data augmentation during inference. Defaults to False.
556
556
  visualize (bool): Whether to visualize the output predictions. Defaults to False.
557
557
  embed (list, optional): A list of feature vectors/embeddings to return.
558
+ **kwargs (Any): Additional keyword arguments for model configuration.
558
559
 
559
560
  Returns:
560
561
  (torch.Tensor | List[torch.Tensor]): The raw output tensor(s) from the model.
@@ -567,7 +568,7 @@ class AutoBackend(nn.Module):
567
568
 
568
569
  # PyTorch
569
570
  if self.pt or self.nn_module:
570
- y = self.model(im, augment=augment, visualize=visualize, embed=embed)
571
+ y = self.model(im, augment=augment, visualize=visualize, embed=embed, **kwargs)
571
572
 
572
573
  # TorchScript
573
574
  elif self.jit:
@@ -51,6 +51,7 @@ from .block import (
51
51
  HGBlock,
52
52
  HGStem,
53
53
  ImagePoolingAttn,
54
+ MaxSigmoidAttnBlock,
54
55
  Proto,
55
56
  RepC3,
56
57
  RepNCSPELAN4,
@@ -75,7 +76,19 @@ from .conv import (
75
76
  RepConv,
76
77
  SpatialAttention,
77
78
  )
78
- from .head import OBB, Classify, Detect, Pose, RTDETRDecoder, Segment, WorldDetect, v10Detect
79
+ from .head import (
80
+ OBB,
81
+ Classify,
82
+ Detect,
83
+ LRPCHead,
84
+ Pose,
85
+ RTDETRDecoder,
86
+ Segment,
87
+ WorldDetect,
88
+ YOLOEDetect,
89
+ YOLOESegment,
90
+ v10Detect,
91
+ )
79
92
  from .transformer import (
80
93
  AIFI,
81
94
  MLP,
@@ -143,8 +156,12 @@ __all__ = (
143
156
  "ResNetLayer",
144
157
  "OBB",
145
158
  "WorldDetect",
159
+ "YOLOEDetect",
160
+ "YOLOESegment",
146
161
  "v10Detect",
162
+ "LRPCHead",
147
163
  "ImagePoolingAttn",
164
+ "MaxSigmoidAttnBlock",
148
165
  "ContrastiveHead",
149
166
  "BNContrastiveHead",
150
167
  "RepNCSPELAN4",
@@ -771,7 +771,7 @@ class ContrastiveHead(nn.Module):
771
771
 
772
772
  class BNContrastiveHead(nn.Module):
773
773
  """
774
- Batch Norm Contrastive Head for YOLO-World using batch norm instead of l2-normalization.
774
+ Batch Norm Contrastive Head using batch norm instead of l2-normalization.
775
775
 
776
776
  Args:
777
777
  embed_dims (int): Embed dimensions of text and image features.
@@ -791,6 +791,21 @@ class BNContrastiveHead(nn.Module):
791
791
  # use -1.0 is more stable
792
792
  self.logit_scale = nn.Parameter(-1.0 * torch.ones([]))
793
793
 
794
+ def fuse(self):
795
+ """Fuse the batch normalization layer in the BNContrastiveHead module."""
796
+ del self.norm
797
+ del self.bias
798
+ del self.logit_scale
799
+ self.forward = self.forward_fuse
800
+
801
+ def forward_fuse(self, x, w):
802
+ """
803
+ Passes input out unchanged.
804
+
805
+ TODO: Update or remove?
806
+ """
807
+ return x
808
+
794
809
  def forward(self, x, w):
795
810
  """
796
811
  Forward function of contrastive learning with batch normalization.
@@ -804,6 +819,7 @@ class BNContrastiveHead(nn.Module):
804
819
  """
805
820
  x = self.norm(x)
806
821
  w = F.normalize(w, dim=-1, p=2)
822
+
807
823
  x = torch.einsum("bchw,bkc->bkhw", x, w)
808
824
  return x * self.logit_scale.exp() + self.bias
809
825