tasks.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import contextlib
  3. import pickle
  4. import re
  5. import types
  6. from copy import deepcopy
  7. from pathlib import Path
  8. import thop
  9. import torch
  10. import torch.nn as nn
  11. from ultralytics.nn.modules import (
  12. AIFI,
  13. C1,
  14. C2,
  15. C2PSA,
  16. C3,
  17. C3TR,
  18. ELAN1,
  19. OBB,
  20. PSA,
  21. SPP,
  22. SPPELAN,
  23. SPPF,
  24. AConv,
  25. ADown,
  26. Bottleneck,
  27. BottleneckCSP,
  28. C2f,
  29. C2fAttn,
  30. C2fCIB,
  31. C2fPSA,
  32. C3Ghost,
  33. C3k2,
  34. C3x,
  35. CBFuse,
  36. CBLinear,
  37. Classify,
  38. Concat,
  39. Conv,
  40. Conv2,
  41. ConvTranspose,
  42. Detect,
  43. DWConv,
  44. DWConvTranspose2d,
  45. Focus,
  46. GhostBottleneck,
  47. GhostConv,
  48. HGBlock,
  49. HGStem,
  50. ImagePoolingAttn,
  51. Index,
  52. Pose,
  53. RepC3,
  54. RepConv,
  55. RepNCSPELAN4,
  56. RepVGGDW,
  57. ResNetLayer,
  58. RTDETRDecoder,
  59. SCDown,
  60. Segment,
  61. TorchVision,
  62. WorldDetect,
  63. v10Detect,
  64. A2C2f,
  65. )
  66. from ultralytics.utils import DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, colorstr, emojis, yaml_load
  67. from ultralytics.utils.checks import check_requirements, check_suffix, check_yaml
  68. from ultralytics.utils.loss import (
  69. E2EDetectLoss,
  70. v8ClassificationLoss,
  71. v8DetectionLoss,
  72. v8OBBLoss,
  73. v8PoseLoss,
  74. v8SegmentationLoss,
  75. )
  76. from ultralytics.utils.ops import make_divisible
  77. from ultralytics.utils.plotting import feature_visualization
  78. from ultralytics.utils.torch_utils import (
  79. fuse_conv_and_bn,
  80. fuse_deconv_and_bn,
  81. initialize_weights,
  82. intersect_dicts,
  83. model_info,
  84. scale_img,
  85. time_sync,
  86. )
  87. class BaseModel(nn.Module):
  88. """The BaseModel class serves as a base class for all the models in the Ultralytics YOLO family."""
  89. def forward(self, x, *args, **kwargs):
  90. """
  91. Perform forward pass of the model for either training or inference.
  92. If x is a dict, calculates and returns the loss for training. Otherwise, returns predictions for inference.
  93. Args:
  94. x (torch.Tensor | dict): Input tensor for inference, or dict with image tensor and labels for training.
  95. *args (Any): Variable length argument list.
  96. **kwargs (Any): Arbitrary keyword arguments.
  97. Returns:
  98. (torch.Tensor): Loss if x is a dict (training), or network predictions (inference).
  99. """
  100. if isinstance(x, dict): # for cases of training and validating while training.
  101. return self.loss(x, *args, **kwargs)
  102. return self.predict(x, *args, **kwargs)
  103. def predict(self, x, profile=False, visualize=False, augment=False, embed=None):
  104. """
  105. Perform a forward pass through the network.
  106. Args:
  107. x (torch.Tensor): The input tensor to the model.
  108. profile (bool): Print the computation time of each layer if True, defaults to False.
  109. visualize (bool): Save the feature maps of the model if True, defaults to False.
  110. augment (bool): Augment image during prediction, defaults to False.
  111. embed (list, optional): A list of feature vectors/embeddings to return.
  112. Returns:
  113. (torch.Tensor): The last output of the model.
  114. """
  115. if augment:
  116. return self._predict_augment(x)
  117. return self._predict_once(x, profile, visualize, embed)
  118. def _predict_once(self, x, profile=False, visualize=False, embed=None):
  119. """
  120. Perform a forward pass through the network.
  121. Args:
  122. x (torch.Tensor): The input tensor to the model.
  123. profile (bool): Print the computation time of each layer if True, defaults to False.
  124. visualize (bool): Save the feature maps of the model if True, defaults to False.
  125. embed (list, optional): A list of feature vectors/embeddings to return.
  126. Returns:
  127. (torch.Tensor): The last output of the model.
  128. """
  129. y, dt, embeddings = [], [], [] # outputs
  130. for m in self.model:
  131. if m.f != -1: # if not from previous layer
  132. x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
  133. if profile:
  134. self._profile_one_layer(m, x, dt)
  135. x = m(x) # run
  136. y.append(x if m.i in self.save else None) # save output
  137. if visualize:
  138. feature_visualization(x, m.type, m.i, save_dir=visualize)
  139. if embed and m.i in embed:
  140. embeddings.append(nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten
  141. if m.i == max(embed):
  142. return torch.unbind(torch.cat(embeddings, 1), dim=0)
  143. return x
  144. def _predict_augment(self, x):
  145. """Perform augmentations on input image x and return augmented inference."""
  146. LOGGER.warning(
  147. f"WARNING ⚠️ {self.__class__.__name__} does not support 'augment=True' prediction. "
  148. f"Reverting to single-scale prediction."
  149. )
  150. return self._predict_once(x)
  151. def _profile_one_layer(self, m, x, dt):
  152. """
  153. Profile the computation time and FLOPs of a single layer of the model on a given input. Appends the results to
  154. the provided list.
  155. Args:
  156. m (nn.Module): The layer to be profiled.
  157. x (torch.Tensor): The input data to the layer.
  158. dt (list): A list to store the computation time of the layer.
  159. Returns:
  160. None
  161. """
  162. c = m == self.model[-1] and isinstance(x, list) # is final layer list, copy input as inplace fix
  163. flops = thop.profile(m, inputs=[x.copy() if c else x], verbose=False)[0] / 1e9 * 2 if thop else 0 # GFLOPs
  164. t = time_sync()
  165. for _ in range(10):
  166. m(x.copy() if c else x)
  167. dt.append((time_sync() - t) * 100)
  168. if m == self.model[0]:
  169. LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
  170. LOGGER.info(f"{dt[-1]:10.2f} {flops:10.2f} {m.np:10.0f} {m.type}")
  171. if c:
  172. LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
  173. def fuse(self, verbose=True):
  174. """
  175. Fuse the `Conv2d()` and `BatchNorm2d()` layers of the model into a single layer, in order to improve the
  176. computation efficiency.
  177. Returns:
  178. (nn.Module): The fused model is returned.
  179. """
  180. if not self.is_fused():
  181. for m in self.model.modules():
  182. if isinstance(m, (Conv, Conv2, DWConv)) and hasattr(m, "bn"):
  183. if isinstance(m, Conv2):
  184. m.fuse_convs()
  185. m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
  186. delattr(m, "bn") # remove batchnorm
  187. m.forward = m.forward_fuse # update forward
  188. if isinstance(m, ConvTranspose) and hasattr(m, "bn"):
  189. m.conv_transpose = fuse_deconv_and_bn(m.conv_transpose, m.bn)
  190. delattr(m, "bn") # remove batchnorm
  191. m.forward = m.forward_fuse # update forward
  192. if isinstance(m, RepConv):
  193. m.fuse_convs()
  194. m.forward = m.forward_fuse # update forward
  195. if isinstance(m, RepVGGDW):
  196. m.fuse()
  197. m.forward = m.forward_fuse
  198. self.info(verbose=verbose)
  199. return self
  200. def is_fused(self, thresh=10):
  201. """
  202. Check if the model has less than a certain threshold of BatchNorm layers.
  203. Args:
  204. thresh (int, optional): The threshold number of BatchNorm layers. Default is 10.
  205. Returns:
  206. (bool): True if the number of BatchNorm layers in the model is less than the threshold, False otherwise.
  207. """
  208. bn = tuple(v for k, v in nn.__dict__.items() if "Norm" in k) # normalization layers, i.e. BatchNorm2d()
  209. return sum(isinstance(v, bn) for v in self.modules()) < thresh # True if < 'thresh' BatchNorm layers in model
  210. def info(self, detailed=False, verbose=True, imgsz=640):
  211. """
  212. Prints model information.
  213. Args:
  214. detailed (bool): if True, prints out detailed information about the model. Defaults to False
  215. verbose (bool): if True, prints out the model information. Defaults to False
  216. imgsz (int): the size of the image that the model will be trained on. Defaults to 640
  217. """
  218. return model_info(self, detailed=detailed, verbose=verbose, imgsz=imgsz)
  219. def _apply(self, fn):
  220. """
  221. Applies a function to all the tensors in the model that are not parameters or registered buffers.
  222. Args:
  223. fn (function): the function to apply to the model
  224. Returns:
  225. (BaseModel): An updated BaseModel object.
  226. """
  227. self = super()._apply(fn)
  228. m = self.model[-1] # Detect()
  229. if isinstance(m, Detect): # includes all Detect subclasses like Segment, Pose, OBB, WorldDetect
  230. m.stride = fn(m.stride)
  231. m.anchors = fn(m.anchors)
  232. m.strides = fn(m.strides)
  233. return self
  234. def load(self, weights, verbose=True):
  235. """
  236. Load the weights into the model.
  237. Args:
  238. weights (dict | torch.nn.Module): The pre-trained weights to be loaded.
  239. verbose (bool, optional): Whether to log the transfer progress. Defaults to True.
  240. """
  241. model = weights["model"] if isinstance(weights, dict) else weights # torchvision models are not dicts
  242. csd = model.float().state_dict() # checkpoint state_dict as FP32
  243. csd = intersect_dicts(csd, self.state_dict()) # intersect
  244. self.load_state_dict(csd, strict=False) # load
  245. if verbose:
  246. LOGGER.info(f"Transferred {len(csd)}/{len(self.model.state_dict())} items from pretrained weights")
  247. def loss(self, batch, preds=None):
  248. """
  249. Compute loss.
  250. Args:
  251. batch (dict): Batch to compute loss on
  252. preds (torch.Tensor | List[torch.Tensor]): Predictions.
  253. """
  254. if getattr(self, "criterion", None) is None:
  255. self.criterion = self.init_criterion()
  256. preds = self.forward(batch["img"]) if preds is None else preds
  257. return self.criterion(preds, batch)
  258. def init_criterion(self):
  259. """Initialize the loss criterion for the BaseModel."""
  260. raise NotImplementedError("compute_loss() needs to be implemented by task heads")
  261. class DetectionModel(BaseModel):
  262. """YOLOv8 detection model."""
  263. def __init__(self, cfg="yolov8n.yaml", ch=3, nc=None, verbose=True): # model, input channels, number of classes
  264. """Initialize the YOLOv8 detection model with the given config and parameters."""
  265. super().__init__()
  266. self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg) # cfg dict
  267. if self.yaml["backbone"][0][2] == "Silence":
  268. LOGGER.warning(
  269. "WARNING ⚠️ YOLOv9 `Silence` module is deprecated in favor of nn.Identity. "
  270. "Please delete local *.pt file and re-download the latest model checkpoint."
  271. )
  272. self.yaml["backbone"][0][2] = "nn.Identity"
  273. # Define model
  274. ch = self.yaml["ch"] = self.yaml.get("ch", ch) # input channels
  275. if nc and nc != self.yaml["nc"]:
  276. LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
  277. self.yaml["nc"] = nc # override YAML value
  278. self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose) # model, savelist
  279. self.names = {i: f"{i}" for i in range(self.yaml["nc"])} # default names dict
  280. self.inplace = self.yaml.get("inplace", True)
  281. self.end2end = getattr(self.model[-1], "end2end", False)
  282. # Build strides
  283. m = self.model[-1] # Detect()
  284. if isinstance(m, Detect): # includes all Detect subclasses like Segment, Pose, OBB, WorldDetect
  285. s = 256 # 2x min stride
  286. m.inplace = self.inplace
  287. def _forward(x):
  288. """Performs a forward pass through the model, handling different Detect subclass types accordingly."""
  289. if self.end2end:
  290. return self.forward(x)["one2many"]
  291. return self.forward(x)[0] if isinstance(m, (Segment, Pose, OBB)) else self.forward(x)
  292. m.stride = torch.tensor([s / x.shape[-2] for x in _forward(torch.zeros(1, ch, s, s))]) # forward
  293. self.stride = m.stride
  294. m.bias_init() # only run once
  295. else:
  296. self.stride = torch.Tensor([32]) # default stride for i.e. RTDETR
  297. # Init weights, biases
  298. initialize_weights(self)
  299. if verbose:
  300. self.info()
  301. LOGGER.info("")
  302. def _predict_augment(self, x):
  303. """Perform augmentations on input image x and return augmented inference and train outputs."""
  304. if getattr(self, "end2end", False) or self.__class__.__name__ != "DetectionModel":
  305. LOGGER.warning("WARNING ⚠️ Model does not support 'augment=True', reverting to single-scale prediction.")
  306. return self._predict_once(x)
  307. img_size = x.shape[-2:] # height, width
  308. s = [1, 0.83, 0.67] # scales
  309. f = [None, 3, None] # flips (2-ud, 3-lr)
  310. y = [] # outputs
  311. for si, fi in zip(s, f):
  312. xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
  313. yi = super().predict(xi)[0] # forward
  314. yi = self._descale_pred(yi, fi, si, img_size)
  315. y.append(yi)
  316. y = self._clip_augmented(y) # clip augmented tails
  317. return torch.cat(y, -1), None # augmented inference, train
  318. @staticmethod
  319. def _descale_pred(p, flips, scale, img_size, dim=1):
  320. """De-scale predictions following augmented inference (inverse operation)."""
  321. p[:, :4] /= scale # de-scale
  322. x, y, wh, cls = p.split((1, 1, 2, p.shape[dim] - 4), dim)
  323. if flips == 2:
  324. y = img_size[0] - y # de-flip ud
  325. elif flips == 3:
  326. x = img_size[1] - x # de-flip lr
  327. return torch.cat((x, y, wh, cls), dim)
  328. def _clip_augmented(self, y):
  329. """Clip YOLO augmented inference tails."""
  330. nl = self.model[-1].nl # number of detection layers (P3-P5)
  331. g = sum(4**x for x in range(nl)) # grid points
  332. e = 1 # exclude layer count
  333. i = (y[0].shape[-1] // g) * sum(4**x for x in range(e)) # indices
  334. y[0] = y[0][..., :-i] # large
  335. i = (y[-1].shape[-1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
  336. y[-1] = y[-1][..., i:] # small
  337. return y
  338. def init_criterion(self):
  339. """Initialize the loss criterion for the DetectionModel."""
  340. return E2EDetectLoss(self) if getattr(self, "end2end", False) else v8DetectionLoss(self)
  341. class OBBModel(DetectionModel):
  342. """YOLOv8 Oriented Bounding Box (OBB) model."""
  343. def __init__(self, cfg="yolov8n-obb.yaml", ch=3, nc=None, verbose=True):
  344. """Initialize YOLOv8 OBB model with given config and parameters."""
  345. super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)
  346. def init_criterion(self):
  347. """Initialize the loss criterion for the model."""
  348. return v8OBBLoss(self)
  349. class SegmentationModel(DetectionModel):
  350. """YOLOv8 segmentation model."""
  351. def __init__(self, cfg="yolov8n-seg.yaml", ch=3, nc=None, verbose=True):
  352. """Initialize YOLOv8 segmentation model with given config and parameters."""
  353. super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)
  354. def init_criterion(self):
  355. """Initialize the loss criterion for the SegmentationModel."""
  356. return v8SegmentationLoss(self)
  357. class PoseModel(DetectionModel):
  358. """YOLOv8 pose model."""
  359. def __init__(self, cfg="yolov8n-pose.yaml", ch=3, nc=None, data_kpt_shape=(None, None), verbose=True):
  360. """Initialize YOLOv8 Pose model."""
  361. if not isinstance(cfg, dict):
  362. cfg = yaml_model_load(cfg) # load model YAML
  363. if any(data_kpt_shape) and list(data_kpt_shape) != list(cfg["kpt_shape"]):
  364. LOGGER.info(f"Overriding model.yaml kpt_shape={cfg['kpt_shape']} with kpt_shape={data_kpt_shape}")
  365. cfg["kpt_shape"] = data_kpt_shape
  366. super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)
  367. def init_criterion(self):
  368. """Initialize the loss criterion for the PoseModel."""
  369. return v8PoseLoss(self)
  370. class ClassificationModel(BaseModel):
  371. """YOLOv8 classification model."""
  372. def __init__(self, cfg="yolov8n-cls.yaml", ch=3, nc=None, verbose=True):
  373. """Init ClassificationModel with YAML, channels, number of classes, verbose flag."""
  374. super().__init__()
  375. self._from_yaml(cfg, ch, nc, verbose)
  376. def _from_yaml(self, cfg, ch, nc, verbose):
  377. """Set YOLOv8 model configurations and define the model architecture."""
  378. self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg) # cfg dict
  379. # Define model
  380. ch = self.yaml["ch"] = self.yaml.get("ch", ch) # input channels
  381. if nc and nc != self.yaml["nc"]:
  382. LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
  383. self.yaml["nc"] = nc # override YAML value
  384. elif not nc and not self.yaml.get("nc", None):
  385. raise ValueError("nc not specified. Must specify nc in model.yaml or function arguments.")
  386. self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose) # model, savelist
  387. self.stride = torch.Tensor([1]) # no stride constraints
  388. self.names = {i: f"{i}" for i in range(self.yaml["nc"])} # default names dict
  389. self.info()
  390. @staticmethod
  391. def reshape_outputs(model, nc):
  392. """Update a TorchVision classification model to class count 'n' if required."""
  393. name, m = list((model.model if hasattr(model, "model") else model).named_children())[-1] # last module
  394. if isinstance(m, Classify): # YOLO Classify() head
  395. if m.linear.out_features != nc:
  396. m.linear = nn.Linear(m.linear.in_features, nc)
  397. elif isinstance(m, nn.Linear): # ResNet, EfficientNet
  398. if m.out_features != nc:
  399. setattr(model, name, nn.Linear(m.in_features, nc))
  400. elif isinstance(m, nn.Sequential):
  401. types = [type(x) for x in m]
  402. if nn.Linear in types:
  403. i = len(types) - 1 - types[::-1].index(nn.Linear) # last nn.Linear index
  404. if m[i].out_features != nc:
  405. m[i] = nn.Linear(m[i].in_features, nc)
  406. elif nn.Conv2d in types:
  407. i = len(types) - 1 - types[::-1].index(nn.Conv2d) # last nn.Conv2d index
  408. if m[i].out_channels != nc:
  409. m[i] = nn.Conv2d(m[i].in_channels, nc, m[i].kernel_size, m[i].stride, bias=m[i].bias is not None)
  410. def init_criterion(self):
  411. """Initialize the loss criterion for the ClassificationModel."""
  412. return v8ClassificationLoss()
  413. class RTDETRDetectionModel(DetectionModel):
  414. """
  415. RTDETR (Real-time DEtection and Tracking using Transformers) Detection Model class.
  416. This class is responsible for constructing the RTDETR architecture, defining loss functions, and facilitating both
  417. the training and inference processes. RTDETR is an object detection and tracking model that extends from the
  418. DetectionModel base class.
  419. Attributes:
  420. cfg (str): The configuration file path or preset string. Default is 'rtdetr-l.yaml'.
  421. ch (int): Number of input channels. Default is 3 (RGB).
  422. nc (int, optional): Number of classes for object detection. Default is None.
  423. verbose (bool): Specifies if summary statistics are shown during initialization. Default is True.
  424. Methods:
  425. init_criterion: Initializes the criterion used for loss calculation.
  426. loss: Computes and returns the loss during training.
  427. predict: Performs a forward pass through the network and returns the output.
  428. """
  429. def __init__(self, cfg="rtdetr-l.yaml", ch=3, nc=None, verbose=True):
  430. """
  431. Initialize the RTDETRDetectionModel.
  432. Args:
  433. cfg (str): Configuration file name or path.
  434. ch (int): Number of input channels.
  435. nc (int, optional): Number of classes. Defaults to None.
  436. verbose (bool, optional): Print additional information during initialization. Defaults to True.
  437. """
  438. super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)
  439. def init_criterion(self):
  440. """Initialize the loss criterion for the RTDETRDetectionModel."""
  441. from ultralytics.models.utils.loss import RTDETRDetectionLoss
  442. return RTDETRDetectionLoss(nc=self.nc, use_vfl=True)
  443. def loss(self, batch, preds=None):
  444. """
  445. Compute the loss for the given batch of data.
  446. Args:
  447. batch (dict): Dictionary containing image and label data.
  448. preds (torch.Tensor, optional): Precomputed model predictions. Defaults to None.
  449. Returns:
  450. (tuple): A tuple containing the total loss and main three losses in a tensor.
  451. """
  452. if not hasattr(self, "criterion"):
  453. self.criterion = self.init_criterion()
  454. img = batch["img"]
  455. # NOTE: preprocess gt_bbox and gt_labels to list.
  456. bs = len(img)
  457. batch_idx = batch["batch_idx"]
  458. gt_groups = [(batch_idx == i).sum().item() for i in range(bs)]
  459. targets = {
  460. "cls": batch["cls"].to(img.device, dtype=torch.long).view(-1),
  461. "bboxes": batch["bboxes"].to(device=img.device),
  462. "batch_idx": batch_idx.to(img.device, dtype=torch.long).view(-1),
  463. "gt_groups": gt_groups,
  464. }
  465. preds = self.predict(img, batch=targets) if preds is None else preds
  466. dec_bboxes, dec_scores, enc_bboxes, enc_scores, dn_meta = preds if self.training else preds[1]
  467. if dn_meta is None:
  468. dn_bboxes, dn_scores = None, None
  469. else:
  470. dn_bboxes, dec_bboxes = torch.split(dec_bboxes, dn_meta["dn_num_split"], dim=2)
  471. dn_scores, dec_scores = torch.split(dec_scores, dn_meta["dn_num_split"], dim=2)
  472. dec_bboxes = torch.cat([enc_bboxes.unsqueeze(0), dec_bboxes]) # (7, bs, 300, 4)
  473. dec_scores = torch.cat([enc_scores.unsqueeze(0), dec_scores])
  474. loss = self.criterion(
  475. (dec_bboxes, dec_scores), targets, dn_bboxes=dn_bboxes, dn_scores=dn_scores, dn_meta=dn_meta
  476. )
  477. # NOTE: There are like 12 losses in RTDETR, backward with all losses but only show the main three losses.
  478. return sum(loss.values()), torch.as_tensor(
  479. [loss[k].detach() for k in ["loss_giou", "loss_class", "loss_bbox"]], device=img.device
  480. )
  481. def predict(self, x, profile=False, visualize=False, batch=None, augment=False, embed=None):
  482. """
  483. Perform a forward pass through the model.
  484. Args:
  485. x (torch.Tensor): The input tensor.
  486. profile (bool, optional): If True, profile the computation time for each layer. Defaults to False.
  487. visualize (bool, optional): If True, save feature maps for visualization. Defaults to False.
  488. batch (dict, optional): Ground truth data for evaluation. Defaults to None.
  489. augment (bool, optional): If True, perform data augmentation during inference. Defaults to False.
  490. embed (list, optional): A list of feature vectors/embeddings to return.
  491. Returns:
  492. (torch.Tensor): Model's output tensor.
  493. """
  494. y, dt, embeddings = [], [], [] # outputs
  495. for m in self.model[:-1]: # except the head part
  496. if m.f != -1: # if not from previous layer
  497. x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
  498. if profile:
  499. self._profile_one_layer(m, x, dt)
  500. x = m(x) # run
  501. y.append(x if m.i in self.save else None) # save output
  502. if visualize:
  503. feature_visualization(x, m.type, m.i, save_dir=visualize)
  504. if embed and m.i in embed:
  505. embeddings.append(nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten
  506. if m.i == max(embed):
  507. return torch.unbind(torch.cat(embeddings, 1), dim=0)
  508. head = self.model[-1]
  509. x = head([y[j] for j in head.f], batch) # head inference
  510. return x
  511. class WorldModel(DetectionModel):
  512. """YOLOv8 World Model."""
  513. def __init__(self, cfg="yolov8s-world.yaml", ch=3, nc=None, verbose=True):
  514. """Initialize YOLOv8 world model with given config and parameters."""
  515. self.txt_feats = torch.randn(1, nc or 80, 512) # features placeholder
  516. self.clip_model = None # CLIP model placeholder
  517. super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)
  518. def set_classes(self, text, batch=80, cache_clip_model=True):
  519. """Set classes in advance so that model could do offline-inference without clip model."""
  520. try:
  521. import clip
  522. except ImportError:
  523. check_requirements("git+https://github.com/ultralytics/CLIP.git")
  524. import clip
  525. if (
  526. not getattr(self, "clip_model", None) and cache_clip_model
  527. ): # for backwards compatibility of models lacking clip_model attribute
  528. self.clip_model = clip.load("ViT-B/32")[0]
  529. model = self.clip_model if cache_clip_model else clip.load("ViT-B/32")[0]
  530. device = next(model.parameters()).device
  531. text_token = clip.tokenize(text).to(device)
  532. txt_feats = [model.encode_text(token).detach() for token in text_token.split(batch)]
  533. txt_feats = txt_feats[0] if len(txt_feats) == 1 else torch.cat(txt_feats, dim=0)
  534. txt_feats = txt_feats / txt_feats.norm(p=2, dim=-1, keepdim=True)
  535. self.txt_feats = txt_feats.reshape(-1, len(text), txt_feats.shape[-1])
  536. self.model[-1].nc = len(text)
  537. def predict(self, x, profile=False, visualize=False, txt_feats=None, augment=False, embed=None):
  538. """
  539. Perform a forward pass through the model.
  540. Args:
  541. x (torch.Tensor): The input tensor.
  542. profile (bool, optional): If True, profile the computation time for each layer. Defaults to False.
  543. visualize (bool, optional): If True, save feature maps for visualization. Defaults to False.
  544. txt_feats (torch.Tensor): The text features, use it if it's given. Defaults to None.
  545. augment (bool, optional): If True, perform data augmentation during inference. Defaults to False.
  546. embed (list, optional): A list of feature vectors/embeddings to return.
  547. Returns:
  548. (torch.Tensor): Model's output tensor.
  549. """
  550. txt_feats = (self.txt_feats if txt_feats is None else txt_feats).to(device=x.device, dtype=x.dtype)
  551. if len(txt_feats) != len(x):
  552. txt_feats = txt_feats.repeat(len(x), 1, 1)
  553. ori_txt_feats = txt_feats.clone()
  554. y, dt, embeddings = [], [], [] # outputs
  555. for m in self.model: # except the head part
  556. if m.f != -1: # if not from previous layer
  557. x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
  558. if profile:
  559. self._profile_one_layer(m, x, dt)
  560. if isinstance(m, C2fAttn):
  561. x = m(x, txt_feats)
  562. elif isinstance(m, WorldDetect):
  563. x = m(x, ori_txt_feats)
  564. elif isinstance(m, ImagePoolingAttn):
  565. txt_feats = m(x, txt_feats)
  566. else:
  567. x = m(x) # run
  568. y.append(x if m.i in self.save else None) # save output
  569. if visualize:
  570. feature_visualization(x, m.type, m.i, save_dir=visualize)
  571. if embed and m.i in embed:
  572. embeddings.append(nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten
  573. if m.i == max(embed):
  574. return torch.unbind(torch.cat(embeddings, 1), dim=0)
  575. return x
  576. def loss(self, batch, preds=None):
  577. """
  578. Compute loss.
  579. Args:
  580. batch (dict): Batch to compute loss on.
  581. preds (torch.Tensor | List[torch.Tensor]): Predictions.
  582. """
  583. if not hasattr(self, "criterion"):
  584. self.criterion = self.init_criterion()
  585. if preds is None:
  586. preds = self.forward(batch["img"], txt_feats=batch["txt_feats"])
  587. return self.criterion(preds, batch)
  588. class Ensemble(nn.ModuleList):
  589. """Ensemble of models."""
  590. def __init__(self):
  591. """Initialize an ensemble of models."""
  592. super().__init__()
  593. def forward(self, x, augment=False, profile=False, visualize=False):
  594. """Function generates the YOLO network's final layer."""
  595. y = [module(x, augment, profile, visualize)[0] for module in self]
  596. # y = torch.stack(y).max(0)[0] # max ensemble
  597. # y = torch.stack(y).mean(0) # mean ensemble
  598. y = torch.cat(y, 2) # nms ensemble, y shape(B, HW, C)
  599. return y, None # inference, train output
  600. # Functions ------------------------------------------------------------------------------------------------------------
  601. @contextlib.contextmanager
  602. def temporary_modules(modules=None, attributes=None):
  603. """
  604. Context manager for temporarily adding or modifying modules in Python's module cache (`sys.modules`).
  605. This function can be used to change the module paths during runtime. It's useful when refactoring code,
  606. where you've moved a module from one location to another, but you still want to support the old import
  607. paths for backwards compatibility.
  608. Args:
  609. modules (dict, optional): A dictionary mapping old module paths to new module paths.
  610. attributes (dict, optional): A dictionary mapping old module attributes to new module attributes.
  611. Example:
  612. ```python
  613. with temporary_modules({"old.module": "new.module"}, {"old.module.attribute": "new.module.attribute"}):
  614. import old.module # this will now import new.module
  615. from old.module import attribute # this will now import new.module.attribute
  616. ```
  617. Note:
  618. The changes are only in effect inside the context manager and are undone once the context manager exits.
  619. Be aware that directly manipulating `sys.modules` can lead to unpredictable results, especially in larger
  620. applications or libraries. Use this function with caution.
  621. """
  622. if modules is None:
  623. modules = {}
  624. if attributes is None:
  625. attributes = {}
  626. import sys
  627. from importlib import import_module
  628. try:
  629. # Set attributes in sys.modules under their old name
  630. for old, new in attributes.items():
  631. old_module, old_attr = old.rsplit(".", 1)
  632. new_module, new_attr = new.rsplit(".", 1)
  633. setattr(import_module(old_module), old_attr, getattr(import_module(new_module), new_attr))
  634. # Set modules in sys.modules under their old name
  635. for old, new in modules.items():
  636. sys.modules[old] = import_module(new)
  637. yield
  638. finally:
  639. # Remove the temporary module paths
  640. for old in modules:
  641. if old in sys.modules:
  642. del sys.modules[old]
  643. class SafeClass:
  644. """A placeholder class to replace unknown classes during unpickling."""
  645. def __init__(self, *args, **kwargs):
  646. """Initialize SafeClass instance, ignoring all arguments."""
  647. pass
  648. def __call__(self, *args, **kwargs):
  649. """Run SafeClass instance, ignoring all arguments."""
  650. pass
  651. class SafeUnpickler(pickle.Unpickler):
  652. """Custom Unpickler that replaces unknown classes with SafeClass."""
  653. def find_class(self, module, name):
  654. """Attempt to find a class, returning SafeClass if not among safe modules."""
  655. safe_modules = (
  656. "torch",
  657. "collections",
  658. "collections.abc",
  659. "builtins",
  660. "math",
  661. "numpy",
  662. # Add other modules considered safe
  663. )
  664. if module in safe_modules:
  665. return super().find_class(module, name)
  666. else:
  667. return SafeClass
  668. def torch_safe_load(weight, safe_only=False):
  669. """
  670. Attempts to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised, it catches the
  671. error, logs a warning message, and attempts to install the missing module via the check_requirements() function.
  672. After installation, the function again attempts to load the model using torch.load().
  673. Args:
  674. weight (str): The file path of the PyTorch model.
  675. safe_only (bool): If True, replace unknown classes with SafeClass during loading.
  676. Example:
  677. ```python
  678. from ultralytics.nn.tasks import torch_safe_load
  679. ckpt, file = torch_safe_load("path/to/best.pt", safe_only=True)
  680. ```
  681. Returns:
  682. ckpt (dict): The loaded model checkpoint.
  683. file (str): The loaded filename
  684. """
  685. from ultralytics.utils.downloads import attempt_download_asset
  686. check_suffix(file=weight, suffix=".pt")
  687. file = attempt_download_asset(weight) # search online if missing locally
  688. try:
  689. with temporary_modules(
  690. modules={
  691. "ultralytics.yolo.utils": "ultralytics.utils",
  692. "ultralytics.yolo.v8": "ultralytics.models.yolo",
  693. "ultralytics.yolo.data": "ultralytics.data",
  694. },
  695. attributes={
  696. "ultralytics.nn.modules.block.Silence": "torch.nn.Identity", # YOLOv9e
  697. "ultralytics.nn.tasks.YOLOv10DetectionModel": "ultralytics.nn.tasks.DetectionModel", # YOLOv10
  698. "ultralytics.utils.loss.v10DetectLoss": "ultralytics.utils.loss.E2EDetectLoss", # YOLOv10
  699. },
  700. ):
  701. if safe_only:
  702. # Load via custom pickle module
  703. safe_pickle = types.ModuleType("safe_pickle")
  704. safe_pickle.Unpickler = SafeUnpickler
  705. safe_pickle.load = lambda file_obj: SafeUnpickler(file_obj).load()
  706. with open(file, "rb") as f:
  707. ckpt = torch.load(f, pickle_module=safe_pickle)
  708. else:
  709. ckpt = torch.load(file, map_location="cpu")
  710. except ModuleNotFoundError as e: # e.name is missing module name
  711. if e.name == "models":
  712. raise TypeError(
  713. emojis(
  714. f"ERROR ❌️ {weight} appears to be an Ultralytics YOLOv5 model originally trained "
  715. f"with https://github.com/ultralytics/yolov5.\nThis model is NOT forwards compatible with "
  716. f"YOLOv8 at https://github.com/ultralytics/ultralytics."
  717. f"\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to "
  718. f"run a command with an official Ultralytics model, i.e. 'yolo predict model=yolov8n.pt'"
  719. )
  720. ) from e
  721. LOGGER.warning(
  722. f"WARNING ⚠️ {weight} appears to require '{e.name}', which is not in Ultralytics requirements."
  723. f"\nAutoInstall will run now for '{e.name}' but this feature will be removed in the future."
  724. f"\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to "
  725. f"run a command with an official Ultralytics model, i.e. 'yolo predict model=yolov8n.pt'"
  726. )
  727. check_requirements(e.name) # install missing module
  728. ckpt = torch.load(file, map_location="cpu")
  729. if not isinstance(ckpt, dict):
  730. # File is likely a YOLO instance saved with i.e. torch.save(model, "saved_model.pt")
  731. LOGGER.warning(
  732. f"WARNING ⚠️ The file '{weight}' appears to be improperly saved or formatted. "
  733. f"For optimal results, use model.save('filename.pt') to correctly save YOLO models."
  734. )
  735. ckpt = {"model": ckpt.model}
  736. return ckpt, file
  737. def attempt_load_weights(weights, device=None, inplace=True, fuse=False):
  738. """Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a."""
  739. ensemble = Ensemble()
  740. for w in weights if isinstance(weights, list) else [weights]:
  741. ckpt, w = torch_safe_load(w) # load ckpt
  742. args = {**DEFAULT_CFG_DICT, **ckpt["train_args"]} if "train_args" in ckpt else None # combined args
  743. model = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model
  744. # Model compatibility updates
  745. model.args = args # attach args to model
  746. model.pt_path = w # attach *.pt file path to model
  747. model.task = guess_model_task(model)
  748. if not hasattr(model, "stride"):
  749. model.stride = torch.tensor([32.0])
  750. # Append
  751. ensemble.append(model.fuse().eval() if fuse and hasattr(model, "fuse") else model.eval()) # model in eval mode
  752. # Module updates
  753. for m in ensemble.modules():
  754. if hasattr(m, "inplace"):
  755. m.inplace = inplace
  756. elif isinstance(m, nn.Upsample) and not hasattr(m, "recompute_scale_factor"):
  757. m.recompute_scale_factor = None # torch 1.11.0 compatibility
  758. # Return model
  759. if len(ensemble) == 1:
  760. return ensemble[-1]
  761. # Return ensemble
  762. LOGGER.info(f"Ensemble created with {weights}\n")
  763. for k in "names", "nc", "yaml":
  764. setattr(ensemble, k, getattr(ensemble[0], k))
  765. ensemble.stride = ensemble[int(torch.argmax(torch.tensor([m.stride.max() for m in ensemble])))].stride
  766. assert all(ensemble[0].nc == m.nc for m in ensemble), f"Models differ in class counts {[m.nc for m in ensemble]}"
  767. return ensemble
  768. def attempt_load_one_weight(weight, device=None, inplace=True, fuse=False):
  769. """Loads a single model weights."""
  770. ckpt, weight = torch_safe_load(weight) # load ckpt
  771. args = {**DEFAULT_CFG_DICT, **(ckpt.get("train_args", {}))} # combine model and default args, preferring model args
  772. model = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model
  773. # Model compatibility updates
  774. model.args = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS} # attach args to model
  775. model.pt_path = weight # attach *.pt file path to model
  776. model.task = guess_model_task(model)
  777. if not hasattr(model, "stride"):
  778. model.stride = torch.tensor([32.0])
  779. model = model.fuse().eval() if fuse and hasattr(model, "fuse") else model.eval() # model in eval mode
  780. # Module updates
  781. for m in model.modules():
  782. if hasattr(m, "inplace"):
  783. m.inplace = inplace
  784. elif isinstance(m, nn.Upsample) and not hasattr(m, "recompute_scale_factor"):
  785. m.recompute_scale_factor = None # torch 1.11.0 compatibility
  786. # Return model and ckpt
  787. return model, ckpt
  788. def parse_model(d, ch, verbose=True): # model_dict, input_channels(3)
  789. """Parse a YOLO model.yaml dictionary into a PyTorch model."""
  790. import ast
  791. # Args
  792. legacy = True # backward compatibility for v3/v5/v8/v9 models
  793. max_channels = float("inf")
  794. nc, act, scales = (d.get(x) for x in ("nc", "activation", "scales"))
  795. depth, width, kpt_shape = (d.get(x, 1.0) for x in ("depth_multiple", "width_multiple", "kpt_shape"))
  796. if scales:
  797. scale = d.get("scale")
  798. if not scale:
  799. scale = tuple(scales.keys())[0]
  800. LOGGER.warning(f"WARNING ⚠️ no model scale passed. Assuming scale='{scale}'.")
  801. depth, width, max_channels = scales[scale]
  802. if act:
  803. Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU()
  804. if verbose:
  805. LOGGER.info(f"{colorstr('activation:')} {act}") # print
  806. if verbose:
  807. LOGGER.info(f"\n{'':>3}{'from':>20}{'n':>3}{'params':>10} {'module':<45}{'arguments':<30}")
  808. ch = [ch]
  809. layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
  810. for i, (f, n, m, args) in enumerate(d["backbone"] + d["head"]): # from, number, module, args
  811. m = getattr(torch.nn, m[3:]) if "nn." in m else globals()[m] # get module
  812. for j, a in enumerate(args):
  813. if isinstance(a, str):
  814. with contextlib.suppress(ValueError):
  815. args[j] = locals()[a] if a in locals() else ast.literal_eval(a)
  816. n = n_ = max(round(n * depth), 1) if n > 1 else n # depth gain
  817. if m in {
  818. Classify,
  819. Conv,
  820. ConvTranspose,
  821. GhostConv,
  822. Bottleneck,
  823. GhostBottleneck,
  824. SPP,
  825. SPPF,
  826. C2fPSA,
  827. C2PSA,
  828. DWConv,
  829. Focus,
  830. BottleneckCSP,
  831. C1,
  832. C2,
  833. C2f,
  834. C3k2,
  835. RepNCSPELAN4,
  836. ELAN1,
  837. ADown,
  838. AConv,
  839. SPPELAN,
  840. C2fAttn,
  841. C3,
  842. C3TR,
  843. C3Ghost,
  844. nn.ConvTranspose2d,
  845. DWConvTranspose2d,
  846. C3x,
  847. RepC3,
  848. PSA,
  849. SCDown,
  850. C2fCIB,
  851. A2C2f,
  852. }:
  853. c1, c2 = ch[f], args[0]
  854. if c2 != nc: # if c2 not equal to number of classes (i.e. for Classify() output)
  855. c2 = make_divisible(min(c2, max_channels) * width, 8)
  856. if m is C2fAttn:
  857. args[1] = make_divisible(min(args[1], max_channels // 2) * width, 8) # embed channels
  858. args[2] = int(
  859. max(round(min(args[2], max_channels // 2 // 32)) * width, 1) if args[2] > 1 else args[2]
  860. ) # num heads
  861. args = [c1, c2, *args[1:]]
  862. if m in {
  863. BottleneckCSP,
  864. C1,
  865. C2,
  866. C2f,
  867. C3k2,
  868. C2fAttn,
  869. C3,
  870. C3TR,
  871. C3Ghost,
  872. C3x,
  873. RepC3,
  874. C2fPSA,
  875. C2fCIB,
  876. C2PSA,
  877. A2C2f,
  878. }:
  879. args.insert(2, n) # number of repeats
  880. n = 1
  881. if m is C3k2: # for M/L/X sizes
  882. legacy = False
  883. if scale in "mlx":
  884. args[3] = True
  885. if m is A2C2f:
  886. legacy = False
  887. if scale in "lx": # for L/X sizes
  888. args.append(True)
  889. args.append(1.5)
  890. elif m is AIFI:
  891. args = [ch[f], *args]
  892. elif m in {HGStem, HGBlock}:
  893. c1, cm, c2 = ch[f], args[0], args[1]
  894. args = [c1, cm, c2, *args[2:]]
  895. if m is HGBlock:
  896. args.insert(4, n) # number of repeats
  897. n = 1
  898. elif m is ResNetLayer:
  899. c2 = args[1] if args[3] else args[1] * 4
  900. elif m is nn.BatchNorm2d:
  901. args = [ch[f]]
  902. elif m is Concat:
  903. c2 = sum(ch[x] for x in f)
  904. elif m in {Detect, WorldDetect, Segment, Pose, OBB, ImagePoolingAttn, v10Detect}:
  905. args.append([ch[x] for x in f])
  906. if m is Segment:
  907. args[2] = make_divisible(min(args[2], max_channels) * width, 8)
  908. if m in {Detect, Segment, Pose, OBB}:
  909. m.legacy = legacy
  910. elif m is RTDETRDecoder: # special case, channels arg must be passed in index 1
  911. args.insert(1, [ch[x] for x in f])
  912. elif m in {CBLinear, TorchVision, Index}:
  913. c2 = args[0]
  914. c1 = ch[f]
  915. args = [c1, c2, *args[1:]]
  916. elif m is CBFuse:
  917. c2 = ch[f[-1]]
  918. else:
  919. c2 = ch[f]
  920. m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
  921. t = str(m)[8:-2].replace("__main__.", "") # module type
  922. m_.np = sum(x.numel() for x in m_.parameters()) # number params
  923. m_.i, m_.f, m_.type = i, f, t # attach index, 'from' index, type
  924. if verbose:
  925. LOGGER.info(f"{i:>3}{str(f):>20}{n_:>3}{m_.np:10.0f} {t:<45}{str(args):<30}") # print
  926. save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
  927. layers.append(m_)
  928. if i == 0:
  929. ch = []
  930. ch.append(c2)
  931. return nn.Sequential(*layers), sorted(save)
  932. def yaml_model_load(path):
  933. """Load a YOLOv8 model from a YAML file."""
  934. path = Path(path)
  935. if path.stem in (f"yolov{d}{x}6" for x in "nsmlx" for d in (5, 8)):
  936. new_stem = re.sub(r"(\d+)([nslmx])6(.+)?$", r"\1\2-p6\3", path.stem)
  937. LOGGER.warning(f"WARNING ⚠️ Ultralytics YOLO P6 models now use -p6 suffix. Renaming {path.stem} to {new_stem}.")
  938. path = path.with_name(new_stem + path.suffix)
  939. unified_path = re.sub(r"(\d+)([nslmx])(.+)?$", r"\1\3", str(path)) # i.e. yolov8x.yaml -> yolov8.yaml
  940. yaml_file = check_yaml(unified_path, hard=False) or check_yaml(path)
  941. d = yaml_load(yaml_file) # model dict
  942. d["scale"] = guess_model_scale(path)
  943. d["yaml_file"] = str(path)
  944. return d
  945. def guess_model_scale(model_path):
  946. """
  947. Takes a path to a YOLO model's YAML file as input and extracts the size character of the model's scale. The function
  948. uses regular expression matching to find the pattern of the model scale in the YAML file name, which is denoted by
  949. n, s, m, l, or x. The function returns the size character of the model scale as a string.
  950. Args:
  951. model_path (str | Path): The path to the YOLO model's YAML file.
  952. Returns:
  953. (str): The size character of the model's scale, which can be n, s, m, l, or x.
  954. """
  955. try:
  956. return re.search(r"yolo[v]?\d+([nslmx])", Path(model_path).stem).group(1) # noqa, returns n, s, m, l, or x
  957. except AttributeError:
  958. return ""
  959. def guess_model_task(model):
  960. """
  961. Guess the task of a PyTorch model from its architecture or configuration.
  962. Args:
  963. model (nn.Module | dict): PyTorch model or model configuration in YAML format.
  964. Returns:
  965. (str): Task of the model ('detect', 'segment', 'classify', 'pose').
  966. Raises:
  967. SyntaxError: If the task of the model could not be determined.
  968. """
  969. def cfg2task(cfg):
  970. """Guess from YAML dictionary."""
  971. m = cfg["head"][-1][-2].lower() # output module name
  972. if m in {"classify", "classifier", "cls", "fc"}:
  973. return "classify"
  974. if "detect" in m:
  975. return "detect"
  976. if m == "segment":
  977. return "segment"
  978. if m == "pose":
  979. return "pose"
  980. if m == "obb":
  981. return "obb"
  982. # Guess from model cfg
  983. if isinstance(model, dict):
  984. with contextlib.suppress(Exception):
  985. return cfg2task(model)
  986. # Guess from PyTorch model
  987. if isinstance(model, nn.Module): # PyTorch model
  988. for x in "model.args", "model.model.args", "model.model.model.args":
  989. with contextlib.suppress(Exception):
  990. return eval(x)["task"]
  991. for x in "model.yaml", "model.model.yaml", "model.model.model.yaml":
  992. with contextlib.suppress(Exception):
  993. return cfg2task(eval(x))
  994. for m in model.modules():
  995. if isinstance(m, Segment):
  996. return "segment"
  997. elif isinstance(m, Classify):
  998. return "classify"
  999. elif isinstance(m, Pose):
  1000. return "pose"
  1001. elif isinstance(m, OBB):
  1002. return "obb"
  1003. elif isinstance(m, (Detect, WorldDetect, v10Detect)):
  1004. return "detect"
  1005. # Guess from model filename
  1006. if isinstance(model, (str, Path)):
  1007. model = Path(model)
  1008. if "-seg" in model.stem or "segment" in model.parts:
  1009. return "segment"
  1010. elif "-cls" in model.stem or "classify" in model.parts:
  1011. return "classify"
  1012. elif "-pose" in model.stem or "pose" in model.parts:
  1013. return "pose"
  1014. elif "-obb" in model.stem or "obb" in model.parts:
  1015. return "obb"
  1016. elif "detect" in model.parts:
  1017. return "detect"
  1018. # Unable to determine task from model
  1019. LOGGER.warning(
  1020. "WARNING ⚠️ Unable to automatically guess model task, assuming 'task=detect'. "
  1021. "Explicitly define task for your model, i.e. 'task=detect', 'segment', 'classify','pose' or 'obb'."
  1022. )
  1023. return "detect" # assume detect