tasks.py 49 KB

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