OSCR

Brain tumor detection on magnetic resonance imaging scans using the artificial intelligence-based You Only Look Once algorithm.

Code ↔ Paper

11 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 11 matches · 2 of them tie a paragraph to a whole file without given lines: weak matches, whose lines are not tinted
  1. [1] § Methods ↔ shenduxuexilvcai_02/ultralytics/nn/tasks.py, lines 1047 to 1114 · score 0.65 · A2C2f, C2TSSA DYT, suppressing, backbone, DFFN, thresholds · Report a mismatch
  2. [2] § Methods › C2TSSA-DYT module ↔ shenduxuexilvcai_02/ultralytics/models/sam/modules/encoders.py, lines 501 to 642 · score 0.64 · feature fusion, convolutional layer, channel dimension, fused, module, detection · Report a mismatch
  3. [3] § Methods › A2C2f-DFFN module ↔ shenduxuexilvcai_02/ultralytics/nn/extra_modules/block.py, lines 1 to 70 · score 0.59 · edge information, additive, deep, gating, DFFN, fusion · Report a mismatch
  4. [4] § Methods › C2TSSA-DYT module ↔ shenduxuexilvcai_02/ultralytics/nn/tasks.py, lines 1116 to 1175 · score 0.58 · C2TSSA DYT, A2C2f, DFFN, dynamic, global, module · Report a mismatch
  5. [5] § Experimental analyses › Visualization of results ↔ shenduxuexilvcai_02/ultralytics/models/yolo/classify/val.py, the whole file · a weak match · score 0.58 · confusion matrices, yolov8n, classification, metrics, accuracy, detections · Report a mismatch
  6. [6] § Experimental analyses › Algorithm comparison results ↔ shenduxuexilvcai_02/ultralytics/models/rtdetr/train.py, lines 14 to 102 · score 0.54 · inference speed, RT DETR, YOLO, detections · Report a mismatch
  7. [7] § Experimental analyses › Visualization of results ↔ shenduxuexilvcai_02/ultralytics/models/rtdetr/predict.py, lines 11 to 84 · score 0.52 · bounding boxes, RT DETR, confidence, scoring, accuracy, detection · Report a mismatch
  8. [8] § Experiment › Dataset › Experimental environment and hyperparameter configuration ↔ shenduxuexilvcai_02/ultralytics/engine/tuner.py, lines 70 to 112 · score 0.51 · weight decay, momentum, configuration, hyperparameter · Report a mismatch
  9. [9] § Methods ↔ shenduxuexilvcai_02/ultralytics/nn/tasks.py, lines 1047 to 1114 · score 0.51 · A2C2f, C2TSSA DYT, backbone, DFFN, modules · Report a mismatch
  10. [10] § Experiment › Dataset › Experimental environment and hyperparameter configuration ↔ shenduxuexilvcai_02/ultralytics/utils/tuner.py, the whole file · a weak match · score 0.50 · weight decay, momentum, hyperparameter, GPU, trained, models · Report a mismatch
  11. [11] § Methods › A2C2f-DFFN module ↔ shenduxuexilvcai_02/ultralytics/models/sam/modules/blocks.py, lines 877 to 974 · score 0.50 · residual connection, propagated, network, layer, global, dimensional · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 1,506 lines · 67 KB · no license · 3 matches

  1. # Ultralytics YOLO 🚀, AGPL-3.0 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 timm
  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. DSConv,
  45. DWConvTranspose2d,
  46. Focus,
  47. GhostBottleneck,
  48. GhostConv,
  49. HGBlock,
  50. HGStem,
  51. ImagePoolingAttn,
  52. Pose,
  53. RepC3,
  54. RepConv,
  55. # RepNCSPELAN4,
  56. RepVGGDW,
  57. ResNetLayer,
  58. RTDETRDecoder,
  59. SCDown,
  60. Segment,
  61. WorldDetect,
  62. v10Detect,
  63. SpatialAttention,
  64. CBAM,
  65. A2C2f
  66. )
  67. from ultralytics.nn.extra_modules import *
  68. from ultralytics.utils import DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, colorstr, emojis, yaml_load
  69. from ultralytics.utils.checks import check_requirements, check_suffix, check_yaml
  70. from ultralytics.utils.loss import (
  71. E2EDetectLoss,
  72. v8ClassificationLoss,
  73. v8DetectionLoss,
  74. v8OBBLoss,
  75. v8PoseLoss,
  76. v8SegmentationLoss,
  77. E2EFGIDetectLoss,
  78. )
  79. from ultralytics.utils.ops import make_divisible
  80. from ultralytics.utils.plotting import feature_visualization
  81. from ultralytics.utils.torch_utils import (
  82. fuse_conv_and_bn,
  83. fuse_deconv_and_bn,
  84. initialize_weights,
  85. intersect_dicts,
  86. model_info,
  87. scale_img,
  88. time_sync,
  89. get_num_params
  90. )
  91. from ultralytics.nn.backbone.convnextv2 import *
  92. from ultralytics.nn.backbone.fasternet import *
  93. from ultralytics.nn.backbone.efficientViT import *
  94. from ultralytics.nn.backbone.EfficientFormerV2 import *
  95. from ultralytics.nn.backbone.VanillaNet import *
  96. from ultralytics.nn.backbone.revcol import *
  97. from ultralytics.nn.backbone.lsknet import *
  98. from ultralytics.nn.backbone.SwinTransformer import *
  99. from ultralytics.nn.backbone.repvit import *
  100. from ultralytics.nn.backbone.CSwomTramsformer import *
  101. from ultralytics.nn.backbone.UniRepLKNet import *
  102. from ultralytics.nn.backbone.TransNext import *
  103. from ultralytics.nn.backbone.rmt import *
  104. from ultralytics.nn.backbone.pkinet import *
  105. from ultralytics.nn.backbone.mobilenetv4 import *
  106. from ultralytics.nn.backbone.starnet import *
  107. from ultralytics.nn.backbone.inceptionnext import *
  108. from ultralytics.nn.extra_modules.mobileMamba.mobilemamba import *
  109. from ultralytics.nn.backbone.MambaOut import *
  110. try:
  111. import thop
  112. except ImportError:
  113. thop = None
  114. DETECT_CLASS = (Detect, Detect_DyHead, Detect_AFPN_P2345, Detect_AFPN_P2345_Custom, Detect_AFPN_P345, Detect_AFPN_P345_Custom, Detect_Efficient, DetectAux, Detect_SEAM, Detect_MultiSEAM,
  115. Detect_DyHeadWithDCNV3, Detect_DyHeadWithDCNV4, Detect_DyHead_Prune, Detect_LSCD, Detect_TADDH, Detect_LADH, Detect_LSCSBD, Detect_LSDECD, Detect_RSCD, Detect_FGIF)
  116. V10_DETECT_CLASS = (v10Detect,)
  117. SEGMENT_CLASS = (Segment, Segment_Efficient, Segment_LSCD, Segment_TADDH, Segment_LADH, Segment_LSCSBD, Segment_LSDECD, Segment_RSCD)
  118. POSE_CLASS = (Pose, Pose_LSCD, Pose_TADDH, Pose_LADH, Pose_LSCSBD, Pose_LSDECD, Pose_RSCD)
  119. OBB_CLASS = (OBB, OBB_LSCD, OBB_TADDH, OBB_LADH, OBB_LSCSBD, OBB_LSDECD, OBB_RSCD)
  120. C3K2_CLASS = (C3k2_Faster, C3k2_ODConv, C3k2_Faster_EMA, C3k2_DBB, C3k2_DeepDBB, C3k2_WDBB, C3k2_CloAtt, C3k2_SCConv, C3k2_ScConv, C3k2_EMSC, C3k2_EMSCP, C3k2_KW, C3k2_DySnakeConv, C3k2_DCNv2, C3k2_DCNv3,
  121. C3k2_OREPA, C3k2_REPVGGOREPA, C3k2_DCNv2_Dynamic, C3k2_ContextGuided, C3k2_MSBlock, C3k2_DLKA, C3k2_EMBC, C3k2_DAttention, C3k2_Parc, C3k2_DWR, C3k2_RFAConv, C3k2_RFCBAMConv, C3k2_RFCAConv,
  122. C3k2_FocusedLinearAttention, C3k2_MLCA, C3k2_AKConv, C3k2_UniRepLKNetBlock, C3k2_DRB, C3k2_DWR_DRB, C3k2_AggregatedAtt, C3k2_DCNv4, C3k2_SWC, C3k2_iRMB, C3k2_iRMB_Cascaded, C3k2_iRMB_DRB, C3k2_iRMB_SWC,
  123. C3k2_VSS, C3k2_LVMB, C3k2_DynamicConv, C3k2_GhostDynamicConv, C3k2_RVB, C3k2_RVB_SE, C3k2_RVB_EMA, C3k2_RetBlock, C3k2_PKIModule, C3k2_FADC, C3k2_PPA, C3k2_Faster_CGLU, C3k2_Star, C3k2_Star_CAA,
  124. C3k2_KAN, C3k2_EIEM, C3k2_DEConv, C3k2_SMPCGLU, C3k2_Heat, C3k2_WTConv, C3k2_FMB, C3k2_gConv, C3k2_AdditiveBlock, C3k2_AdditiveBlock_CGLU, C3k2_MSMHSA_CGLU, C3k2_MogaBlock, C3k2_SHSA, C3k2_SHSA_CGLU,
  125. C3k2_SMAFB, C3k2_SMAFB_CGLU, C3k2_IdentityFormer, C3k2_RandomMixing, C3k2_PoolingFormer, C3k2_ConvFormer, C3k2_CaFormer, C3k2_IdentityFormerCGLU, C3k2_RandomMixingCGLU, C3k2_PoolingFormerCGLU, C3k2_ConvFormerCGLU, C3k2_CaFormerCGLU,
  126. C3k2_FFCM, C3k2_MutilScaleEdgeInformationEnhance, C3k2_SFHF, C3k2_MSM, C3k2_MutilScaleEdgeInformationSelect, C3k2_HDRAB, C3k2_RAB, C3k2_LFE, C3k2_FCA_CTA, C3k2_FCA_SFA, C3k2_IDWC, C3k2_IDWB, C3k2_PConv, C3k2_EMA,
  127. C3k2_CAMixer, C3k2_HFERB, C3k2_DTAB, C3k2_JDPM, C3k2_ETB, C3k2_FDT, C3k2_AP, C3k2_ELGCA, C3k2_ELGCACGLU, C3k2_Strip, C3k2_StripCGLU, C3k2_Kat, C3k2_Faster_KAN, C3k2_DCMB, C3k2_DCMB_KAN, C3k2_GlobalFilter, C3k2_DynamicFilter,
  128. C3k2_TSSA, C3k2_SAVSS, C3k2_MobileMamba, C3k2_MambaOut
  129. )
  130. class BaseModel(nn.Module):
  131. """The BaseModel class serves as a base class for all the models in the Ultralytics YOLO family."""
  132. def forward(self, x, *args, **kwargs):
  133. """
  134. Perform forward pass of the model for either training or inference.
  135. If x is a dict, calculates and returns the loss for training. Otherwise, returns predictions for inference.
  136. Args:
  137. x (torch.Tensor | dict): Input tensor for inference, or dict with image tensor and labels for training.
  138. *args (Any): Variable length argument list.
  139. **kwargs (Any): Arbitrary keyword arguments.
  140. Returns:
  141. (torch.Tensor): Loss if x is a dict (training), or network predictions (inference).
  142. """
  143. if isinstance(x, dict): # for cases of training and validating while training.
  144. return self.loss(x, *args, **kwargs)
  145. return self.predict(x, *args, **kwargs)
  146. def predict(self, x, profile=False, visualize=False, augment=False, embed=None):
  147. """
  148. Perform a forward pass through the network.
  149. Args:
  150. x (torch.Tensor): The input tensor to the model.
  151. profile (bool): Print the computation time of each layer if True, defaults to False.
  152. visualize (bool): Save the feature maps of the model if True, defaults to False.
  153. augment (bool): Augment image during prediction, defaults to False.
  154. embed (list, optional): A list of feature vectors/embeddings to return.
  155. Returns:
  156. (torch.Tensor): The last output of the model.
  157. """
  158. if augment:
  159. return self._predict_augment(x)
  160. return self._predict_once(x, profile, visualize, embed)
  161. def _predict_once(self, x, profile=False, visualize=False, embed=None):
  162. """
  163. Perform a forward pass through the network.
  164. Args:
  165. x (torch.Tensor): The input tensor to the model.
  166. profile (bool): Print the computation time of each layer if True, defaults to False.
  167. visualize (bool): Save the feature maps of the model if True, defaults to False.
  168. embed (list, optional): A list of feature vectors/embeddings to return.
  169. Returns:
  170. (torch.Tensor): The last output of the model.
  171. """
  172. y, dt, embeddings = [], [], [] # outputs
  173. for idx, m in enumerate(self.model):
  174. if m.f != -1: # if not from previous layer
  175. 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
  176. if profile:
  177. self._profile_one_layer(m, x, dt)
  178. if hasattr(m, 'backbone'):
  179. x = m(x)
  180. for _ in range(5 - len(x)):
  181. x.insert(0, None)
  182. for i_idx, i in enumerate(x):
  183. if i_idx in self.save:
  184. y.append(i)
  185. else:
  186. y.append(None)
  187. # print(f'layer id:{idx:>2} {m.type:>50} output shape:{", ".join([str(x_.size()) for x_ in x if x_ is not None])}')
  188. x = x[-1]
  189. else:
  190. x = m(x) # run
  191. y.append(x if m.i in self.save else None) # save output
  192. # if type(x) in {list, tuple}:
  193. # if idx == (len(self.model) - 1):
  194. # if type(x[1]) is dict:
  195. # print(f'layer id:{idx:>2} {m.type:>50} output shape:{", ".join([str(x_.size()) for x_ in x[1]["one2one"]])}')
  196. # else:
  197. # print(f'layer id:{idx:>2} {m.type:>50} output shape:{", ".join([str(x_.size()) for x_ in x[1]])}')
  198. # else:
  199. # print(f'layer id:{idx:>2} {m.type:>50} output shape:{", ".join([str(x_.size()) for x_ in x if x_ is not None])}')
  200. # elif type(x) is dict:
  201. # print(f'layer id:{idx:>2} {m.type:>50} output shape:{", ".join([str(x_.size()) for x_ in x["one2one"]])}')
  202. # else:
  203. # if not hasattr(m, 'backbone'):
  204. # print(f'layer id:{idx:>2} {m.type:>50} output shape:{x.size()}')
  205. if visualize:
  206. feature_visualization(x, m.type, m.i, save_dir=visualize)
  207. if embed and m.i in embed:
  208. embeddings.append(nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten
  209. if m.i == max(embed):
  210. return torch.unbind(torch.cat(embeddings, 1), dim=0)
  211. return x
  212. def _predict_augment(self, x):
  213. """Perform augmentations on input image x and return augmented inference."""
  214. LOGGER.warning(
  215. f"WARNING ⚠️ {self.__class__.__name__} does not support 'augment=True' prediction. "
  216. f"Reverting to single-scale prediction."
  217. )
  218. return self._predict_once(x)
  219. def _profile_one_layer(self, m, x, dt):
  220. """
  221. Profile the computation time and FLOPs of a single layer of the model on a given input. Appends the results to
  222. the provided list.
  223. Args:
  224. m (nn.Module): The layer to be profiled.
  225. x (torch.Tensor): The input data to the layer.
  226. dt (list): A list to store the computation time of the layer.
  227. Returns:
  228. None
  229. """
  230. if type(x) is tuple:
  231. x = list(x)
  232. c = m == self.model[-1] # is final layer, copy input as inplace fix
  233. if type(x) is list:
  234. try:
  235. bs = x[0].size(0)
  236. except:
  237. bs = x[0][0].size(0)
  238. else:
  239. bs = x.size(0)
  240. o = thop.profile(m, inputs=[x.copy() if c else x], verbose=False)[0] / 1E9 * 2 / bs if thop else 0 # FLOPs
  241. t = time_sync()
  242. for _ in range(10):
  243. m(x.copy() if c else x)
  244. dt.append((time_sync() - t) * 100)
  245. if m == self.model[0]:
  246. LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
  247. LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {get_num_params(m):10.0f} {m.type}')
  248. if c:
  249. LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
  250. def fuse(self, verbose=True):
  251. """
  252. Fuse the `Conv2d()` and `BatchNorm2d()` layers of the model into a single layer, in order to improve the
  253. computation efficiency.
  254. Returns:
  255. (nn.Module): The fused model is returned.
  256. """
  257. if not self.is_fused():
  258. for m in self.model.modules():
  259. if isinstance(m, (Conv, Conv2, DWConv)) and hasattr(m, "bn"):
  260. if isinstance(m, Conv2):
  261. m.fuse_convs()
  262. m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
  263. delattr(m, "bn") # remove batchnorm
  264. m.forward = m.forward_fuse # update forward
  265. if isinstance(m, ConvTranspose) and hasattr(m, "bn"):
  266. m.conv_transpose = fuse_deconv_and_bn(m.conv_transpose, m.bn)
  267. delattr(m, "bn") # remove batchnorm
  268. m.forward = m.forward_fuse # update forward
  269. if isinstance(m, RepConv):
  270. m.fuse_convs()
  271. m.forward = m.forward_fuse # update forward
  272. if isinstance(m, RepVGGDW):
  273. m.fuse()
  274. m.forward = m.forward_fuse
  275. if hasattr(m, 'switch_to_deploy'):
  276. m.switch_to_deploy()
  277. self.info(verbose=verbose)
  278. return self
  279. def is_fused(self, thresh=10):
  280. """
  281. Check if the model has less than a certain threshold of BatchNorm layers.
  282. Args:
  283. thresh (int, optional): The threshold number of BatchNorm layers. Default is 10.
  284. Returns:
  285. (bool): True if the number of BatchNorm layers in the model is less than the threshold, False otherwise.
  286. """
  287. bn = tuple(v for k, v in nn.__dict__.items() if "Norm" in k) # normalization layers, i.e. BatchNorm2d()
  288. return sum(isinstance(v, bn) for v in self.modules()) < thresh # True if < 'thresh' BatchNorm layers in model
  289. def info(self, detailed=False, verbose=True, imgsz=640):
  290. """
  291. Prints model information.
  292. Args:
  293. detailed (bool): if True, prints out detailed information about the model. Defaults to False
  294. verbose (bool): if True, prints out the model information. Defaults to False
  295. imgsz (int): the size of the image that the model will be trained on. Defaults to 640
  296. """
  297. return model_info(self, detailed=detailed, verbose=verbose, imgsz=imgsz)
  298. def _apply(self, fn):
  299. """
  300. Applies a function to all the tensors in the model that are not parameters or registered buffers.
  301. Args:
  302. fn (function): the function to apply to the model
  303. Returns:
  304. (BaseModel): An updated BaseModel object.
  305. """
  306. self = super()._apply(fn)
  307. m = self.model[-1] # Detect()
  308. if isinstance(m, DETECT_CLASS): # includes all Detect subclasses like Segment, Pose, OBB, WorldDetect
  309. m.stride = fn(m.stride)
  310. m.anchors = fn(m.anchors)
  311. m.strides = fn(m.strides)
  312. return self
  313. def load(self, weights, verbose=True):
  314. """
  315. Load the weights into the model.
  316. Args:
  317. weights (dict | torch.nn.Module): The pre-trained weights to be loaded.
  318. verbose (bool, optional): Whether to log the transfer progress. Defaults to True.
  319. """
  320. model = weights["model"] if isinstance(weights, dict) else weights # torchvision models are not dicts
  321. csd = model.float().state_dict() # checkpoint state_dict as FP32
  322. csd = intersect_dicts(csd, self.state_dict()) # intersect
  323. self.load_state_dict(csd, strict=False) # load
  324. if verbose:
  325. LOGGER.info(f"Transferred {len(csd)}/{len(self.model.state_dict())} items from pretrained weights")
  326. def loss(self, batch, preds=None):
  327. """
  328. Compute loss.
  329. Args:
  330. batch (dict): Batch to compute loss on
  331. preds (torch.Tensor | List[torch.Tensor]): Predictions.
  332. """
  333. if getattr(self, "criterion", None) is None:
  334. self.criterion = self.init_criterion()
  335. preds = self.forward(batch["img"]) if preds is None else preds
  336. return self.criterion(preds, batch)
  337. def init_criterion(self):
  338. """Initialize the loss criterion for the BaseModel."""
  339. raise NotImplementedError("compute_loss() needs to be implemented by task heads")
  340. class DetectionModel(BaseModel):
  341. """YOLOv8 detection model."""
  342. def __init__(self, cfg="yolov8n.yaml", ch=3, nc=None, verbose=True): # model, input channels, number of classes
  343. """Initialize the YOLOv8 detection model with the given config and parameters."""
  344. super().__init__()
  345. self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg) # cfg dict
  346. if self.yaml["backbone"][0][2] == "Silence":
  347. LOGGER.warning(
  348. "WARNING ⚠️ YOLOv9 `Silence` module is deprecated in favor of nn.Identity. "
  349. "Please delete local *.pt file and re-download the latest model checkpoint."
  350. )
  351. self.yaml["backbone"][0][2] = "nn.Identity"
  352. # Warehouse_Manager
  353. warehouse_manager_flag = self.yaml.get('Warehouse_Manager', False)
  354. self.warehouse_manager = None
  355. if warehouse_manager_flag:
  356. self.warehouse_manager = Warehouse_Manager(cell_num_ratio=self.yaml.get('Warehouse_Manager_Ratio', 1.0))
  357. # Define model
  358. ch = self.yaml["ch"] = self.yaml.get("ch", ch) # input channels
  359. if nc and nc != self.yaml["nc"]:
  360. LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
  361. self.yaml["nc"] = nc # override YAML value
  362. self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose, warehouse_manager=self.warehouse_manager) # model, savelist
  363. self.names = {i: f"{i}" for i in range(self.yaml["nc"])} # default names dict
  364. self.inplace = self.yaml.get("inplace", True)
  365. self.end2end = getattr(self.model[-1], "end2end", False)
  366. self.fgi = getattr(self.model[-1], "FGIF", False)
  367. if warehouse_manager_flag:
  368. self.warehouse_manager.store()
  369. self.warehouse_manager.allocate(self)
  370. self.net_update_temperature(0)
  371. # Build strides
  372. m = self.model[-1] # Detect()
  373. if isinstance(m, (DETECT_CLASS + SEGMENT_CLASS + POSE_CLASS + OBB_CLASS + V10_DETECT_CLASS)): # includes all Detect subclasses like Segment, Pose, OBB, WorldDetect
  374. s = 640 # 2x min stride
  375. m.inplace = self.inplace
  376. def _forward(x):
  377. """Performs a forward pass through the model, handling different Detect subclass types accordingly."""
  378. if isinstance(m, (DetectAux,)):
  379. return self.forward(x)[:3]
  380. if self.end2end:
  381. if self.fgi:
  382. return self.forward(x)["output_2"]
  383. else:
  384. return self.forward(x)["one2many"]
  385. return self.forward(x)[0] if isinstance(m, SEGMENT_CLASS + POSE_CLASS + OBB_CLASS) else self.forward(x)
  386. try:
  387. m.stride = torch.tensor([s / x.shape[-2] for x in _forward(torch.zeros(2, ch, s, s))]) # forward
  388. except (RuntimeError, ValueError) as e:
  389. if 'Not implemented on the CPU' in str(e) or 'Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor)' in str(e) or \
  390. 'CUDA tensor' in str(e) or 'is_cuda()' in str(e) or 'carafe_forward_impl' in str(e) or 'Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?)' in str(e):
  391. self.model.to(torch.device('cuda'))
  392. m.stride = torch.tensor([s / x.shape[-2] for x in _forward(torch.zeros(2, ch, s, s).to(torch.device('cuda')))]) # forward
  393. else:
  394. raise e
  395. self.stride = m.stride
  396. m.bias_init() # only run once
  397. else:
  398. self.stride = torch.Tensor([32]) # default stride for i.e. RTDETR
  399. # Init weights, biases
  400. initialize_weights(self)
  401. if verbose:
  402. self.info()
  403. LOGGER.info("")
  404. def _predict_augment(self, x):
  405. """Perform augmentations on input image x and return augmented inference and train outputs."""
  406. if getattr(self, "end2end", False) or self.__class__.__name__ != "DetectionModel":
  407. LOGGER.warning("WARNING ⚠️ Model does not support 'augment=True', reverting to single-scale prediction.")
  408. return self._predict_once(x)
  409. img_size = x.shape[-2:] # height, width
  410. s = [1, 0.83, 0.67] # scales
  411. f = [None, 3, None] # flips (2-ud, 3-lr)
  412. y = [] # outputs
  413. for si, fi in zip(s, f):
  414. xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
  415. yi = super().predict(xi)[0] # forward
  416. yi = self._descale_pred(yi, fi, si, img_size)
  417. y.append(yi)
  418. y = self._clip_augmented(y) # clip augmented tails
  419. return torch.cat(y, -1), None # augmented inference, train
  420. @staticmethod
  421. def _descale_pred(p, flips, scale, img_size, dim=1):
  422. """De-scale predictions following augmented inference (inverse operation)."""
  423. p[:, :4] /= scale # de-scale
  424. x, y, wh, cls = p.split((1, 1, 2, p.shape[dim] - 4), dim)
  425. if flips == 2:
  426. y = img_size[0] - y # de-flip ud
  427. elif flips == 3:
  428. x = img_size[1] - x # de-flip lr
  429. return torch.cat((x, y, wh, cls), dim)
  430. def _clip_augmented(self, y):
  431. """Clip YOLO augmented inference tails."""
  432. nl = self.model[-1].nl # number of detection layers (P3-P5)
  433. g = sum(4**x for x in range(nl)) # grid points
  434. e = 1 # exclude layer count
  435. i = (y[0].shape[-1] // g) * sum(4**x for x in range(e)) # indices
  436. y[0] = y[0][..., :-i] # large
  437. i = (y[-1].shape[-1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
  438. y[-1] = y[-1][..., i:] # small
  439. return y
  440. def init_criterion(self):
  441. """Initialize the loss criterion for the DetectionModel."""
  442. # return E2EDetectLoss(self) if getattr(self, "end2end", False) else (E2EFGIDetectLoss(self) if getattr(self, "FGIF", False) else v8DetectionLoss(self))
  443. return E2EFGIDetectLoss(self) if getattr(self, "fgi", False) else (E2EDetectLoss(self) if getattr(self, "end2end", False) else v8DetectionLoss(self))
  444. def net_update_temperature(self, temp):
  445. for m in self.modules():
  446. if hasattr(m, "update_temperature"):
  447. m.update_temperature(temp)
  448. class OBBModel(DetectionModel):
  449. """YOLOv8 Oriented Bounding Box (OBB) model."""
  450. def __init__(self, cfg="yolov8n-obb.yaml", ch=3, nc=None, verbose=True):
  451. """Initialize YOLOv8 OBB model with given config and parameters."""
  452. super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)
  453. def init_criterion(self):
  454. """Initialize the loss criterion for the model."""
  455. return v8OBBLoss(self)
  456. class SegmentationModel(DetectionModel):
  457. """YOLOv8 segmentation model."""
  458. def __init__(self, cfg="yolov8n-seg.yaml", ch=3, nc=None, verbose=True):
  459. """Initialize YOLOv8 segmentation model with given config and parameters."""
  460. super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)
  461. def init_criterion(self):
  462. """Initialize the loss criterion for the SegmentationModel."""
  463. return v8SegmentationLoss(self)
  464. class PoseModel(DetectionModel):
  465. """YOLOv8 pose model."""
  466. def __init__(self, cfg="yolov8n-pose.yaml", ch=3, nc=None, data_kpt_shape=(None, None), verbose=True):
  467. """Initialize YOLOv8 Pose model."""
  468. if not isinstance(cfg, dict):
  469. cfg = yaml_model_load(cfg) # load model YAML
  470. if any(data_kpt_shape) and list(data_kpt_shape) != list(cfg["kpt_shape"]):
  471. LOGGER.info(f"Overriding model.yaml kpt_shape={cfg['kpt_shape']} with kpt_shape={data_kpt_shape}")
  472. cfg["kpt_shape"] = data_kpt_shape
  473. super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)
  474. def init_criterion(self):
  475. """Initialize the loss criterion for the PoseModel."""
  476. return v8PoseLoss(self)
  477. class ClassificationModel(BaseModel):
  478. """YOLOv8 classification model."""
  479. def __init__(self, cfg="yolov8n-cls.yaml", ch=3, nc=None, verbose=True):
  480. """Init ClassificationModel with YAML, channels, number of classes, verbose flag."""
  481. super().__init__()
  482. self._from_yaml(cfg, ch, nc, verbose)
  483. def _from_yaml(self, cfg, ch, nc, verbose):
  484. """Set YOLOv8 model configurations and define the model architecture."""
  485. self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg) # cfg dict
  486. # Define model
  487. ch = self.yaml["ch"] = self.yaml.get("ch", ch) # input channels
  488. if nc and nc != self.yaml["nc"]:
  489. LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
  490. self.yaml["nc"] = nc # override YAML value
  491. elif not nc and not self.yaml.get("nc", None):
  492. raise ValueError("nc not specified. Must specify nc in model.yaml or function arguments.")
  493. self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose) # model, savelist
  494. self.stride = torch.Tensor([1]) # no stride constraints
  495. self.names = {i: f"{i}" for i in range(self.yaml["nc"])} # default names dict
  496. self.info()
  497. @staticmethod
  498. def reshape_outputs(model, nc):
  499. """Update a TorchVision classification model to class count 'n' if required."""
  500. name, m = list((model.model if hasattr(model, "model") else model).named_children())[-1] # last module
  501. if isinstance(m, Classify): # YOLO Classify() head
  502. if m.linear.out_features != nc:
  503. m.linear = nn.Linear(m.linear.in_features, nc)
  504. elif isinstance(m, nn.Linear): # ResNet, EfficientNet
  505. if m.out_features != nc:
  506. setattr(model, name, nn.Linear(m.in_features, nc))
  507. elif isinstance(m, nn.Sequential):
  508. types = [type(x) for x in m]
  509. if nn.Linear in types:
  510. i = len(types) - 1 - types[::-1].index(nn.Linear) # last nn.Linear index
  511. if m[i].out_features != nc:
  512. m[i] = nn.Linear(m[i].in_features, nc)
  513. elif nn.Conv2d in types:
  514. i = len(types) - 1 - types[::-1].index(nn.Conv2d) # last nn.Conv2d index
  515. if m[i].out_channels != nc:
  516. m[i] = nn.Conv2d(m[i].in_channels, nc, m[i].kernel_size, m[i].stride, bias=m[i].bias is not None)
  517. def init_criterion(self):
  518. """Initialize the loss criterion for the ClassificationModel."""
  519. return v8ClassificationLoss()
  520. class RTDETRDetectionModel(DetectionModel):
  521. """
  522. RTDETR (Real-time DEtection and Tracking using Transformers) Detection Model class.
  523. This class is responsible for constructing the RTDETR architecture, defining loss functions, and facilitating both
  524. the training and inference processes. RTDETR is an object detection and tracking model that extends from the
  525. DetectionModel base class.
  526. Attributes:
  527. cfg (str): The configuration file path or preset string. Default is 'rtdetr-l.yaml'.
  528. ch (int): Number of input channels. Default is 3 (RGB).
  529. nc (int, optional): Number of classes for object detection. Default is None.
  530. verbose (bool): Specifies if summary statistics are shown during initialization. Default is True.
  531. Methods:
  532. init_criterion: Initializes the criterion used for loss calculation.
  533. loss: Computes and returns the loss during training.
  534. predict: Performs a forward pass through the network and returns the output.
  535. """
  536. def __init__(self, cfg="rtdetr-l.yaml", ch=3, nc=None, verbose=True):
  537. """
  538. Initialize the RTDETRDetectionModel.
  539. Args:
  540. cfg (str): Configuration file name or path.
  541. ch (int): Number of input channels.
  542. nc (int, optional): Number of classes. Defaults to None.
  543. verbose (bool, optional): Print additional information during initialization. Defaults to True.
  544. """
  545. super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)
  546. def init_criterion(self):
  547. """Initialize the loss criterion for the RTDETRDetectionModel."""
  548. from ultralytics.models.utils.loss import RTDETRDetectionLoss
  549. return RTDETRDetectionLoss(nc=self.nc, use_vfl=True)
  550. def loss(self, batch, preds=None):
  551. """
  552. Compute the loss for the given batch of data.
  553. Args:
  554. batch (dict): Dictionary containing image and label data.
  555. preds (torch.Tensor, optional): Precomputed model predictions. Defaults to None.
  556. Returns:
  557. (tuple): A tuple containing the total loss and main three losses in a tensor.
  558. """
  559. if not hasattr(self, "criterion"):
  560. self.criterion = self.init_criterion()
  561. img = batch["img"]
  562. # NOTE: preprocess gt_bbox and gt_labels to list.
  563. bs = len(img)
  564. batch_idx = batch["batch_idx"]
  565. gt_groups = [(batch_idx == i).sum().item() for i in range(bs)]
  566. targets = {
  567. "cls": batch["cls"].to(img.device, dtype=torch.long).view(-1),
  568. "bboxes": batch["bboxes"].to(device=img.device),
  569. "batch_idx": batch_idx.to(img.device, dtype=torch.long).view(-1),
  570. "gt_groups": gt_groups,
  571. }
  572. preds = self.predict(img, batch=targets) if preds is None else preds
  573. dec_bboxes, dec_scores, enc_bboxes, enc_scores, dn_meta = preds if self.training else preds[1]
  574. if dn_meta is None:
  575. dn_bboxes, dn_scores = None, None
  576. else:
  577. dn_bboxes, dec_bboxes = torch.split(dec_bboxes, dn_meta["dn_num_split"], dim=2)
  578. dn_scores, dec_scores = torch.split(dec_scores, dn_meta["dn_num_split"], dim=2)
  579. dec_bboxes = torch.cat([enc_bboxes.unsqueeze(0), dec_bboxes]) # (7, bs, 300, 4)
  580. dec_scores = torch.cat([enc_scores.unsqueeze(0), dec_scores])
  581. loss = self.criterion(
  582. (dec_bboxes, dec_scores), targets, dn_bboxes=dn_bboxes, dn_scores=dn_scores, dn_meta=dn_meta
  583. )
  584. # NOTE: There are like 12 losses in RTDETR, backward with all losses but only show the main three losses.
  585. return sum(loss.values()), torch.as_tensor(
  586. [loss[k].detach() for k in ["loss_giou", "loss_class", "loss_bbox"]], device=img.device
  587. )
  588. def predict(self, x, profile=False, visualize=False, batch=None, augment=False, embed=None):
  589. """
  590. Perform a forward pass through the model.
  591. Args:
  592. x (torch.Tensor): The input tensor.
  593. profile (bool, optional): If True, profile the computation time for each layer. Defaults to False.
  594. visualize (bool, optional): If True, save feature maps for visualization. Defaults to False.
  595. batch (dict, optional): Ground truth data for evaluation. Defaults to None.
  596. augment (bool, optional): If True, perform data augmentation during inference. Defaults to False.
  597. embed (list, optional): A list of feature vectors/embeddings to return.
  598. Returns:
  599. (torch.Tensor): Model's output tensor.
  600. """
  601. y, dt, embeddings = [], [], [] # outputs
  602. for m in self.model[:-1]: # except the head part
  603. if m.f != -1: # if not from previous layer
  604. 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
  605. if profile:
  606. self._profile_one_layer(m, x, dt)
  607. x = m(x) # run
  608. y.append(x if m.i in self.save else None) # save output
  609. if visualize:
  610. feature_visualization(x, m.type, m.i, save_dir=visualize)
  611. if embed and m.i in embed:
  612. embeddings.append(nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten
  613. if m.i == max(embed):
  614. return torch.unbind(torch.cat(embeddings, 1), dim=0)
  615. head = self.model[-1]
  616. x = head([y[j] for j in head.f], batch) # head inference
  617. return x
  618. class WorldModel(DetectionModel):
  619. """YOLOv8 World Model."""
  620. def __init__(self, cfg="yolov8s-world.yaml", ch=3, nc=None, verbose=True):
  621. """Initialize YOLOv8 world model with given config and parameters."""
  622. self.txt_feats = torch.randn(1, nc or 80, 512) # features placeholder
  623. self.clip_model = None # CLIP model placeholder
  624. super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)
  625. def set_classes(self, text, batch=80, cache_clip_model=True):
  626. """Set classes in advance so that model could do offline-inference without clip model."""
  627. try:
  628. import clip
  629. except ImportError:
  630. check_requirements("git+https://github.com/ultralytics/CLIP.git")
  631. import clip
  632. if (
  633. not getattr(self, "clip_model", None) and cache_clip_model
  634. ): # for backwards compatibility of models lacking clip_model attribute
  635. self.clip_model = clip.load("ViT-B/32")[0]
  636. model = self.clip_model if cache_clip_model else clip.load("ViT-B/32")[0]
  637. device = next(model.parameters()).device
  638. text_token = clip.tokenize(text).to(device)
  639. txt_feats = [model.encode_text(token).detach() for token in text_token.split(batch)]
  640. txt_feats = txt_feats[0] if len(txt_feats) == 1 else torch.cat(txt_feats, dim=0)
  641. txt_feats = txt_feats / txt_feats.norm(p=2, dim=-1, keepdim=True)
  642. self.txt_feats = txt_feats.reshape(-1, len(text), txt_feats.shape[-1])
  643. self.model[-1].nc = len(text)
  644. def predict(self, x, profile=False, visualize=False, txt_feats=None, augment=False, embed=None):
  645. """
  646. Perform a forward pass through the model.
  647. Args:
  648. x (torch.Tensor): The input tensor.
  649. profile (bool, optional): If True, profile the computation time for each layer. Defaults to False.
  650. visualize (bool, optional): If True, save feature maps for visualization. Defaults to False.
  651. txt_feats (torch.Tensor): The text features, use it if it's given. Defaults to None.
  652. augment (bool, optional): If True, perform data augmentation during inference. Defaults to False.
  653. embed (list, optional): A list of feature vectors/embeddings to return.
  654. Returns:
  655. (torch.Tensor): Model's output tensor.
  656. """
  657. txt_feats = (self.txt_feats if txt_feats is None else txt_feats).to(device=x.device, dtype=x.dtype)
  658. if len(txt_feats) != len(x):
  659. txt_feats = txt_feats.repeat(len(x), 1, 1)
  660. ori_txt_feats = txt_feats.clone()
  661. y, dt, embeddings = [], [], [] # outputs
  662. for m in self.model: # except the head part
  663. if m.f != -1: # if not from previous layer
  664. 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
  665. if profile:
  666. self._profile_one_layer(m, x, dt)
  667. if isinstance(m, C2fAttn):
  668. x = m(x, txt_feats)
  669. elif isinstance(m, WorldDetect):
  670. x = m(x, ori_txt_feats)
  671. elif isinstance(m, ImagePoolingAttn):
  672. txt_feats = m(x, txt_feats)
  673. else:
  674. x = m(x) # run
  675. y.append(x if m.i in self.save else None) # save output
  676. if visualize:
  677. feature_visualization(x, m.type, m.i, save_dir=visualize)
  678. if embed and m.i in embed:
  679. embeddings.append(nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten
  680. if m.i == max(embed):
  681. return torch.unbind(torch.cat(embeddings, 1), dim=0)
  682. return x
  683. def loss(self, batch, preds=None):
  684. """
  685. Compute loss.
  686. Args:
  687. batch (dict): Batch to compute loss on.
  688. preds (torch.Tensor | List[torch.Tensor]): Predictions.
  689. """
  690. if not hasattr(self, "criterion"):
  691. self.criterion = self.init_criterion()
  692. if preds is None:
  693. preds = self.forward(batch["img"], txt_feats=batch["txt_feats"])
  694. return self.criterion(preds, batch)
  695. class Ensemble(nn.ModuleList):
  696. """Ensemble of models."""
  697. def __init__(self):
  698. """Initialize an ensemble of models."""
  699. super().__init__()
  700. def forward(self, x, augment=False, profile=False, visualize=False):
  701. """Function generates the YOLO network's final layer."""
  702. y = [module(x, augment, profile, visualize)[0] for module in self]
  703. # y = torch.stack(y).max(0)[0] # max ensemble
  704. # y = torch.stack(y).mean(0) # mean ensemble
  705. y = torch.cat(y, 2) # nms ensemble, y shape(B, HW, C)
  706. return y, None # inference, train output
  707. # Functions ------------------------------------------------------------------------------------------------------------
  708. @contextlib.contextmanager
  709. def temporary_modules(modules=None, attributes=None):
  710. """
  711. Context manager for temporarily adding or modifying modules in Python's module cache (`sys.modules`).
  712. This function can be used to change the module paths during runtime. It's useful when refactoring code,
  713. where you've moved a module from one location to another, but you still want to support the old import
  714. paths for backwards compatibility.
  715. Args:
  716. modules (dict, optional): A dictionary mapping old module paths to new module paths.
  717. attributes (dict, optional): A dictionary mapping old module attributes to new module attributes.
  718. Example:
  719. ```python
  720. with temporary_modules({"old.module": "new.module"}, {"old.module.attribute": "new.module.attribute"}):
  721. import old.module # this will now import new.module
  722. from old.module import attribute # this will now import new.module.attribute
  723. ```
  724. Note:
  725. The changes are only in effect inside the context manager and are undone once the context manager exits.
  726. Be aware that directly manipulating `sys.modules` can lead to unpredictable results, especially in larger
  727. applications or libraries. Use this function with caution.
  728. """
  729. if modules is None:
  730. modules = {}
  731. if attributes is None:
  732. attributes = {}
  733. import sys
  734. from importlib import import_module
  735. try:
  736. # Set attributes in sys.modules under their old name
  737. for old, new in attributes.items():
  738. old_module, old_attr = old.rsplit(".", 1)
  739. new_module, new_attr = new.rsplit(".", 1)
  740. setattr(import_module(old_module), old_attr, getattr(import_module(new_module), new_attr))
  741. # Set modules in sys.modules under their old name
  742. for old, new in modules.items():
  743. sys.modules[old] = import_module(new)
  744. yield
  745. finally:
  746. # Remove the temporary module paths
  747. for old in modules:
  748. if old in sys.modules:
  749. del sys.modules[old]
  750. class SafeClass:
  751. """A placeholder class to replace unknown classes during unpickling."""
  752. def __init__(self, *args, **kwargs):
  753. """Initialize SafeClass instance, ignoring all arguments."""
  754. pass
  755. def __call__(self, *args, **kwargs):
  756. """Run SafeClass instance, ignoring all arguments."""
  757. pass
  758. class SafeUnpickler(pickle.Unpickler):
  759. """Custom Unpickler that replaces unknown classes with SafeClass."""
  760. def find_class(self, module, name):
  761. """Attempt to find a class, returning SafeClass if not among safe modules."""
  762. safe_modules = (
  763. "torch",
  764. "collections",
  765. "collections.abc",
  766. "builtins",
  767. "math",
  768. "numpy",
  769. # Add other modules considered safe
  770. )
  771. if module in safe_modules:
  772. return super().find_class(module, name)
  773. else:
  774. return SafeClass
  775. def torch_safe_load(weight, safe_only=False):
  776. """
  777. Attempts to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised, it catches the
  778. error, logs a warning message, and attempts to install the missing module via the check_requirements() function.
  779. After installation, the function again attempts to load the model using torch.load().
  780. Args:
  781. weight (str): The file path of the PyTorch model.
  782. safe_only (bool): If True, replace unknown classes with SafeClass during loading.
  783. Example:
  784. ```python
  785. from ultralytics.nn.tasks import torch_safe_load
  786. ckpt, file = torch_safe_load("path/to/best.pt", safe_only=True)
  787. ```
  788. Returns:
  789. ckpt (dict): The loaded model checkpoint.
  790. file (str): The loaded filename
  791. """
  792. from ultralytics.utils.downloads import attempt_download_asset
  793. check_suffix(file=weight, suffix=".pt")
  794. file = attempt_download_asset(weight) # search online if missing locally
  795. try:
  796. with temporary_modules(
  797. modules={
  798. "ultralytics.yolo.utils": "ultralytics.utils",
  799. "ultralytics.yolo.v8": "ultralytics.models.yolo",
  800. "ultralytics.yolo.data": "ultralytics.data",
  801. },
  802. attributes={
  803. "ultralytics.nn.modules.block.Silence": "torch.nn.Identity", # YOLOv9e
  804. "ultralytics.nn.tasks.YOLOv10DetectionModel": "ultralytics.nn.tasks.DetectionModel", # YOLOv10
  805. "ultralytics.utils.loss.v10DetectLoss": "ultralytics.utils.loss.E2EDetectLoss", # YOLOv10
  806. },
  807. ):
  808. if safe_only:
  809. # Load via custom pickle module
  810. safe_pickle = types.ModuleType("safe_pickle")
  811. safe_pickle.Unpickler = SafeUnpickler
  812. safe_pickle.load = lambda file_obj: SafeUnpickler(file_obj).load()
  813. with open(file, "rb") as f:
  814. ckpt = torch.load(f, pickle_module=safe_pickle)
  815. else:
  816. ckpt = torch.load(file, map_location="cpu")
  817. except ModuleNotFoundError as e: # e.name is missing module name
  818. if e.name == "models":
  819. raise TypeError(
  820. emojis(
  821. f"ERROR ❌️ {weight} appears to be an Ultralytics YOLOv5 model originally trained "
  822. f"with https://github.com/ultralytics/yolov5.\nThis model is NOT forwards compatible with "
  823. f"YOLOv8 at https://github.com/ultralytics/ultralytics."
  824. f"\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to "
  825. f"run a command with an official Ultralytics model, i.e. 'yolo predict model=yolov8n.pt'"
  826. )
  827. ) from e
  828. LOGGER.warning(
  829. f"WARNING ⚠️ {weight} appears to require '{e.name}', which is not in Ultralytics requirements."
  830. f"\nAutoInstall will run now for '{e.name}' but this feature will be removed in the future."
  831. f"\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to "
  832. f"run a command with an official Ultralytics model, i.e. 'yolo predict model=yolov8n.pt'"
  833. )
  834. check_requirements(e.name) # install missing module
  835. ckpt = torch.load(file, map_location="cpu")
  836. if not isinstance(ckpt, dict):
  837. # File is likely a YOLO instance saved with i.e. torch.save(model, "saved_model.pt")
  838. LOGGER.warning(
  839. f"WARNING ⚠️ The file '{weight}' appears to be improperly saved or formatted. "
  840. f"For optimal results, use model.save('filename.pt') to correctly save YOLO models."
  841. )
  842. ckpt = {"model": ckpt.model}
  843. return ckpt, file
  844. def attempt_load_weights(weights, device=None, inplace=True, fuse=False):
  845. """Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a."""
  846. ensemble = Ensemble()
  847. for w in weights if isinstance(weights, list) else [weights]:
  848. ckpt, w = torch_safe_load(w) # load ckpt
  849. args = {**DEFAULT_CFG_DICT, **ckpt["train_args"]} if "train_args" in ckpt else None # combined args
  850. model = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model
  851. # Model compatibility updates
  852. model.args = args # attach args to model
  853. model.pt_path = w # attach *.pt file path to model
  854. model.task = guess_model_task(model)
  855. if not hasattr(model, "stride"):
  856. model.stride = torch.tensor([32.0])
  857. # Append
  858. ensemble.append(model.fuse().eval() if fuse and hasattr(model, "fuse") else model.eval()) # model in eval mode
  859. # Module updates
  860. for m in ensemble.modules():
  861. if hasattr(m, "inplace"):
  862. m.inplace = inplace
  863. elif isinstance(m, nn.Upsample) and not hasattr(m, "recompute_scale_factor"):
  864. m.recompute_scale_factor = None # torch 1.11.0 compatibility
  865. # Return model
  866. if len(ensemble) == 1:
  867. return ensemble[-1]
  868. # Return ensemble
  869. LOGGER.info(f"Ensemble created with {weights}\n")
  870. for k in "names", "nc", "yaml":
  871. setattr(ensemble, k, getattr(ensemble[0], k))
  872. ensemble.stride = ensemble[int(torch.argmax(torch.tensor([m.stride.max() for m in ensemble])))].stride
  873. assert all(ensemble[0].nc == m.nc for m in ensemble), f"Models differ in class counts {[m.nc for m in ensemble]}"
  874. return ensemble
  875. def attempt_load_one_weight(weight, device=None, inplace=True, fuse=False):
  876. """Loads a single model weights."""
  877. ckpt, weight = torch_safe_load(weight) # load ckpt
  878. args = {**DEFAULT_CFG_DICT, **(ckpt.get("train_args", {}))} # combine model and default args, preferring model args
  879. model = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model
  880. # Model compatibility updates
  881. model.args = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS} # attach args to model
  882. model.pt_path = weight # attach *.pt file path to model
  883. model.task = guess_model_task(model)
  884. if not hasattr(model, "stride"):
  885. model.stride = torch.tensor([32.0])
  886. model = model.fuse().eval() if fuse and hasattr(model, "fuse") else model.eval() # model in eval mode
  887. # Module updates
  888. for m in model.modules():
  889. if hasattr(m, "inplace"):
  890. m.inplace = inplace
  891. elif isinstance(m, nn.Upsample) and not hasattr(m, "recompute_scale_factor"):
  892. m.recompute_scale_factor = None # torch 1.11.0 compatibility
  893. # Return model and ckpt
  894. return model, ckpt
  895. def parse_model(d, ch, verbose=True, warehouse_manager=None): # model_dict, input_channels(3)
  896. """Parse a YOLO model.yaml dictionary into a PyTorch model."""
  897. import ast
  898. # Args
  899. max_channels = float("inf")
  900. nc, act, scales = (d.get(x) for x in ("nc", "activation", "scales"))
  901. depth, width, kpt_shape = (d.get(x, 1.0) for x in ("depth_multiple", "width_multiple", "kpt_shape"))
  902. if scales:
  903. scale = d.get("scale")
  904. if not scale:
  905. scale = tuple(scales.keys())[0]
  906. LOGGER.warning(f"WARNING ⚠️ no model scale passed. Assuming scale='{scale}'.")
  907. if len(scales[scale]) == 3:
  908. depth, width, max_channels = scales[scale]
  909. elif len(scales[scale]) == 4:
  910. depth, width, max_channels, threshold = scales[scale]
  911. if act:
  912. Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU()
  913. if verbose:
  914. LOGGER.info(f"{colorstr('activation:')} {act}") # print
  915. if verbose:
  916. LOGGER.info(f"\n{'':>3}{'from':>20}{'n':>3}{'params':>10} {'module':<45}{'arguments':<30}")
  917. ch = [ch]
  918. layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
  919. is_backbone = False
  920. for i, (f, n, m, args) in enumerate(d["backbone"] + d["head"]): # from, number, module, args
  921. try:
  922. if m == 'node_mode':
  923. m = d[m]
  924. if len(args) > 0:
  925. if args[0] == 'head_channel':
  926. args[0] = int(d[args[0]])
  927. t = m
  928. m = getattr(torch.nn, m[3:]) if 'nn.' in m else globals()[m] # get module
  929. except:
  930. pass
  931. for j, a in enumerate(args):
  932. if isinstance(a, str):
  933. with contextlib.suppress(ValueError):
  934. try:
  935. args[j] = locals()[a] if a in locals() else ast.literal_eval(a)
  936. except:
  937. args[j] = a
  938. n = n_ = max(round(n * depth), 1) if n > 1 else n # depth gain
  939. if m in ((
  940. Classify, Conv, ConvTranspose, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, C2fPSA, C2PSA, DWConv, Focus, BottleneckCSP,
  941. C1, C2, C2f, C3k2, RepNCSPELAN4, ELAN1, ADown, AConv, SPPELAN, C2fAttn, C3, C3TR, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d,
  942. C3x, RepC3, PSA, SCDown, C2fCIB, GSConv, GSConvns, VoVGSCSP, VoVGSCSPns, VoVGSCSPC, RCSOSA, KWConv, CSPStage, SPDConv, RepBlock,
  943. SPPF_LSKA, CSP_EDLAN, nn.Conv2d, HWD, RepNCSPELAN4, DBBNCSPELAN4, OREPANCSPELAN4, DRBNCSPELAN4, RepNCSPELAN4_CAA, V7DownSampling,
  944. DGCST, RepNCSPELAN4_CAA, SRFD, DRFD, RGCSPELAN, CSP_PTB, SimpleStem, VisionClueMerge, VSSBlock_YOLO, XSSBlock, GLSA, FeaturePyramidSharedConv,
  945. LDConv, CSP_MSCB, CSP_PMSFA, RFAConv, RFCBAMConv, RFCAConv, CSP_FreqSpatial, C2BRA, C2CGA, C2DA, C2DPB, MANet, MANet_FasterBlock, MANet_FasterCGLU,
  946. MANet_Star, PSConv, C2Pola, A2C2f, C2TSSA, A2C2f_CGLU, A2C2f_KAN, A2C2f_DFFN, RepHMS, A2C2f_FRFN, C2ASSA, C2PSA_DYT, C2TSSA_DYT, C2Pola_DYT,
  947. A2C2f_DYT, A2C2f_CGLU_DYT, A2C2f_DFFN_DYT
  948. ) + C3K2_CLASS):
  949. if args[0] == 'head_channel':
  950. args[0] = d[args[0]]
  951. c1, c2 = ch[f], args[0]
  952. if c2 != nc: # if c2 not equal to number of classes (i.e. for Classify() output)
  953. c2 = make_divisible(min(c2, max_channels) * width, 8)
  954. if m is C2fAttn:
  955. args[1] = make_divisible(min(args[1], max_channels // 2) * width, 8) # embed channels
  956. args[2] = int(
  957. max(round(min(args[2], max_channels // 2 // 32)) * width, 1) if args[2] > 1 else args[2]
  958. ) # num heads
  959. args = [c1, c2, *args[1:]]
  960. if m in (KWConv, C3k2_KW):
  961. args.insert(2, f'layer{i}')
  962. args.insert(2, warehouse_manager)
  963. if m in (DySnakeConv,):
  964. c2 = c2 * 3
  965. if m in (RepNCSPELAN4, DBBNCSPELAN4, OREPANCSPELAN4, DRBNCSPELAN4, RepNCSPELAN4_CAA):
  966. args[2] = make_divisible(min(args[2], max_channels) * width, 8)
  967. args[3] = make_divisible(min(args[3], max_channels) * width, 8)
  968. if m in ((
  969. BottleneckCSP, C1, C2, C2f, C3k2, C2fAttn, C3, C3TR, C3Ghost, C3x, RepC3, C2fPSA, C2fCIB, C2PSA, VoVGSCSP, VoVGSCSPns, VoVGSCSPC, RCSOSA,
  970. CSPStage, SPDConv, RepBlock, CSP_EDLAN, RGCSPELAN, CSP_PTB, XSSBlock, CSP_MSCB, CSP_PMSFA, CSP_FreqSpatial, C2BRA, C2CGA, C2DA, C2DPB, MANet,
  971. MANet_FasterBlock, MANet_FasterCGLU, MANet_Star, C2Pola, A2C2f, C2TSSA, A2C2f_CGLU, A2C2f_KAN, A2C2f_DFFN, A2C2f_FRFN, C2ASSA, C2PSA_DYT,
  972. C2TSSA_DYT, C2Pola_DYT, A2C2f_DYT, A2C2f_CGLU_DYT, A2C2f_DFFN_DYT
  973. ) + C3K2_CLASS):
  974. args.insert(2, n) # number of repeats
  975. n = 1
  976. if m in ((C3k2,) + C3K2_CLASS) and scale in "mlx": # for M/L/X sizes
  977. if m in (C3k2_AggregatedAtt, C3k2_MSBlock, C3k2_DAttention, C3k2_FocusedLinearAttention, C3k2_Parc, C3k2_UniRepLKNetBlock, C3k2_SMPCGLU,
  978. C3k2_Heat, C3k2_RandomMixing, C3k2_RandomMixingCGLU, C3k2_PKIModule, C3k2_FCA_CTA, C3k2_GlobalFilter, C3k2_DynamicFilter):
  979. if type(args[-1]) == bool:
  980. args[-1] = True
  981. else:
  982. args[-2] = True
  983. else:
  984. args[3] = True
  985. if m in (A2C2f,) and scale in "lx": # for L/X sizes
  986. args.extend((True, 1.2))
  987. elif m in {AIFI, AIFI_RepBN, DTAB, ETB, FDT}:
  988. args = [ch[f], *args]
  989. c2 = args[0]
  990. elif m in (HGStem, HGBlock, Ghost_HGBlock, Rep_HGBlock, Dynamic_HGBlock, EIEStem):
  991. c1, cm, c2 = ch[f], args[0], args[1]
  992. if c2 != nc: # if c2 not equal to number of classes (i.e. for Classify() output)
  993. c2 = make_divisible(min(c2, max_channels) * width, 8)
  994. cm = make_divisible(min(cm, max_channels) * width, 8)
  995. args = [c1, cm, c2, *args[2:]]
  996. if m in (HGBlock, Ghost_HGBlock, Rep_HGBlock, Dynamic_HGBlock):
  997. args.insert(4, n) # number of repeats
  998. n = 1
  999. elif m is ResNetLayer:
  1000. c2 = args[1] if args[3] else args[1] * 4
  1001. elif m is nn.BatchNorm2d:
  1002. args = [ch[f]]
  1003. elif m is Concat:
  1004. c2 = sum(ch[x] for x in f)
  1005. elif m in ((WorldDetect, ImagePoolingAttn) + DETECT_CLASS + V10_DETECT_CLASS + SEGMENT_CLASS + POSE_CLASS + OBB_CLASS):
  1006. args.append([ch[x] for x in f])
  1007. if m in SEGMENT_CLASS:
  1008. args[2] = make_divisible(min(args[2], max_channels) * width, 8)
  1009. if m in (Segment_LSCD, Segment_TADDH, Segment_LSCSBD, Segment_LSDECD, Segment_RSCD):
  1010. args[3] = make_divisible(min(args[3], max_channels) * width, 8)
  1011. if m in (Detect_LSCD, Detect_TADDH, Detect_LSCSBD, Detect_LSDECD, Detect_RSCD):
  1012. args[1] = make_divisible(min(args[1], max_channels) * width, 8)
  1013. if m in (Pose_LSCD, Pose_TADDH, Pose_LSCSBD, Pose_LSDECD, Pose_RSCD, OBB_LSCD, OBB_TADDH, OBB_LSCSBD, OBB_LSDECD, OBB_RSCD):
  1014. args[2] = make_divisible(min(args[2], max_channels) * width, 8)
  1015. elif m is RTDETRDecoder: # special case, channels arg must be passed in index 1
  1016. args.insert(1, [ch[x] for x in f])
  1017. elif m is Fusion:
  1018. args[0] = d[args[0]]
  1019. c1, c2 = [ch[x] for x in f], (sum([ch[x] for x in f]) if args[0] == 'concat' else ch[f[0]])
  1020. args = [c1, args[0]]
  1021. elif m is CBLinear:
  1022. c2 = make_divisible(min(args[0][-1], max_channels) * width, 8)
  1023. c1 = ch[f]
  1024. args = [c1, [make_divisible(min(c2_, max_channels) * width, 8) for c2_ in args[0]], *args[1:]]
  1025. elif m is CBFuse:
  1026. c2 = ch[f[-1]]
  1027. elif isinstance(m, str):
  1028. t = m
  1029. if len(args) == 2:
  1030. m = timm.create_model(m, pretrained=args[0], pretrained_cfg_overlay={'file':args[1]}, features_only=True)
  1031. elif len(args) == 1:
  1032. m = timm.create_model(m, pretrained=args[0], features_only=True)
  1033. c2 = m.feature_info.channels()
  1034. elif m in {convnextv2_atto, convnextv2_femto, convnextv2_pico, convnextv2_nano, convnextv2_tiny, convnextv2_base, convnextv2_large, convnextv2_huge,
  1035. fasternet_t0, fasternet_t1, fasternet_t2, fasternet_s, fasternet_m, fasternet_l,
  1036. EfficientViT_M0, EfficientViT_M1, EfficientViT_M2, EfficientViT_M3, EfficientViT_M4, EfficientViT_M5,
  1037. efficientformerv2_s0, efficientformerv2_s1, efficientformerv2_s2, efficientformerv2_l,
  1038. vanillanet_5, vanillanet_6, vanillanet_7, vanillanet_8, vanillanet_9, vanillanet_10, vanillanet_11, vanillanet_12, vanillanet_13, vanillanet_13_x1_5, vanillanet_13_x1_5_ada_pool,
  1039. RevCol,
  1040. lsknet_t, lsknet_s,
  1041. SwinTransformer_Tiny,
  1042. repvit_m0_9, repvit_m1_0, repvit_m1_1, repvit_m1_5, repvit_m2_3,
  1043. CSWin_tiny, CSWin_small, CSWin_base, CSWin_large,
  1044. unireplknet_a, unireplknet_f, unireplknet_p, unireplknet_n, unireplknet_t, unireplknet_s, unireplknet_b, unireplknet_l, unireplknet_xl,
  1045. transnext_micro, transnext_tiny, transnext_small, transnext_base,
  1046. RMT_T, RMT_S, RMT_B, RMT_L,
  1047. PKINET_T, PKINET_S, PKINET_B,
  1048. MobileNetV4ConvSmall, MobileNetV4ConvMedium, MobileNetV4ConvLarge, MobileNetV4HybridMedium, MobileNetV4HybridLarge,
  1049. starnet_s050, starnet_s100, starnet_s150, starnet_s1, starnet_s2, starnet_s3, starnet_s4,
  1050. inceptionnext_tiny, inceptionnext_small, inceptionnext_base, inceptionnext_base_384,
  1051. MobileMamba_T2, MobileMamba_T4, MobileMamba_S6, MobileMamba_B1, MobileMamba_B2, MobileMamba_B4,
  1052. mambaout_femto, mambaout_kobe, mambaout_tiny, mambaout_small, mambaout_base
  1053. }:
  1054. if m is RevCol:
  1055. args[1] = [make_divisible(min(k, max_channels) * width, 8) for k in args[1]]
  1056. args[2] = [max(round(k * depth), 1) for k in args[2]]
  1057. m = m(*args)
  1058. c2 = m.channel
  1059. elif m in {EMA, SpatialAttention, BiLevelRoutingAttention, BiLevelRoutingAttention_nchw,
  1060. TripletAttention, CoordAtt, CBAM, BAMBlock, LSKBlock, ScConv, LAWDS, EMSConv, EMSConvP,
  1061. SEAttention, CPCA, Partial_conv3, FocalModulation, EfficientAttention, MPCA, deformable_LKA,
  1062. EffectiveSEModule, LSKA, SegNext_Attention, DAttention, MLCA, TransNeXt_AggregatedAttention,
  1063. FocusedLinearAttention, LocalWindowAttention, ChannelAttention_HSFPN, ELA_HSFPN, CA_HSFPN, CAA_HSFPN,
  1064. DySample, CARAFE, CAA, ELA, CAFM, AFGCAttention, EUCB, EfficientChannelAttention, ContrastDrivenFeatureAggregation,
  1065. FSA, AttentiveLayer}:
  1066. c2 = ch[f]
  1067. args = [c2, *args]
  1068. # print(args)
  1069. elif m in {SimAM, SpatialGroupEnhance}:
  1070. c2 = ch[f]
  1071. args = [*args]
  1072. elif m is ContextGuidedBlock_Down:
  1073. c2 = ch[f] * 2
  1074. args = [ch[f], c2, *args]
  1075. elif m is BiFusion:
  1076. c1 = [ch[x] for x in f]
  1077. c2 = make_divisible(min(args[0], max_channels) * width, 8)
  1078. args = [c1, c2]
  1079. # --------------GOLD-YOLO--------------
  1080. elif m in {SimFusion_4in, AdvPoolFusion}:
  1081. c2 = sum(ch[x] for x in f)
  1082. elif m is SimFusion_3in:
  1083. c2 = args[0]
  1084. if c2 != nc: # if c2 not equal to number of classes (i.e. for Classify() output)
  1085. c2 = make_divisible(min(c2, max_channels) * width, 8)
  1086. args = [[ch[f_] for f_ in f], c2]
  1087. elif m is IFM:
  1088. c1 = ch[f]
  1089. c2 = sum(args[0])
  1090. args = [c1, *args]
  1091. elif m is InjectionMultiSum_Auto_pool:
  1092. c1 = ch[f[0]]
  1093. c2 = args[0]
  1094. args = [c1, *args]
  1095. elif m is PyramidPoolAgg:
  1096. c2 = args[0]
  1097. args = [sum([ch[f_] for f_ in f]), *args]
  1098. elif m is TopBasicLayer:
  1099. c2 = sum(args[1])
  1100. # --------------GOLD-YOLO--------------
  1101. # --------------ASF--------------
  1102. elif m is Zoom_cat:
  1103. c2 = sum(ch[x] for x in f)
  1104. elif m is Add:
  1105. c2 = ch[f[-1]]
  1106. elif m in {ScalSeq, DynamicScalSeq}:
  1107. c1 = [ch[x] for x in f]
  1108. c2 = make_divisible(args[0] * width, 8)
  1109. args = [c1, c2]
  1110. elif m is asf_attention_model:
  1111. args = [ch[f[-1]]]
  1112. # --------------ASF--------------
  1113. elif m is SDI:
  1114. args = [[ch[x] for x in f]]
  1115. elif m is Multiply:
  1116. c2 = ch[f[0]]
  1117. elif m is FocusFeature:
  1118. c1 = [ch[x] for x in f]
  1119. c2 = int(c1[1] * 0.5 * 3)
  1120. args = [c1, *args]
  1121. elif m is DASI:
  1122. c1 = [ch[x] for x in f]
  1123. args = [c1, c2]
  1124. elif m is CSMHSA:
  1125. c1 = [ch[x] for x in f]
  1126. c2 = ch[f[-1]]
  1127. args = [c1, c2]
  1128. elif m is CFC_CRB:
  1129. c1 = ch[f]
  1130. c2 = c1 // 2
  1131. args = [c1, *args]
  1132. elif m is SFC_G2:
  1133. c1 = [ch[x] for x in f]
  1134. c2 = c1[0]
  1135. args = [c1]
  1136. elif m in {CGAFusion, CAFMFusion, SDFM, PSFM}:
  1137. c2 = ch[f[1]]
  1138. args = [c2, *args]
  1139. elif m in {ContextGuideFusionModule}:
  1140. c1 = [ch[x] for x in f]
  1141. c2 = 2 * c1[1]
  1142. args = [c1]
  1143. # elif m in {PSA}:
  1144. # c2 = ch[f]
  1145. # args = [c2, *args]
  1146. elif m in {SBA}:
  1147. c1 = [ch[x] for x in f]
  1148. c2 = c1[-1]
  1149. args = [c1, c2]
  1150. elif m in {WaveletPool}:
  1151. c2 = ch[f] * 4
  1152. elif m in {WaveletUnPool}:
  1153. c2 = ch[f] // 4
  1154. elif m in {CSPOmniKernel}:
  1155. c2 = ch[f]
  1156. args = [c2]
  1157. elif m in {ChannelTransformer, PyramidContextExtraction}:
  1158. c1 = [ch[x] for x in f]
  1159. c2 = c1
  1160. args = [c1]
  1161. elif m in {RCM}:
  1162. c2 = ch[f]
  1163. args = [c2, *args]
  1164. elif m in {DynamicInterpolationFusion}:
  1165. c2 = ch[f[0]]
  1166. args = [[ch[x] for x in f]]
  1167. elif m in {FuseBlockMulti}:
  1168. c2 = ch[f[0]]
  1169. args = [c2]
  1170. elif m in {CrossLayerChannelAttention, CrossLayerSpatialAttention}:
  1171. c2 = [ch[x] for x in f]
  1172. args = [c2[0], *args]
  1173. elif m in {FreqFusion}:
  1174. c2 = ch[f[0]]
  1175. args = [[ch[x] for x in f], *args]
  1176. elif m in {DynamicAlignFusion}:
  1177. c2 = args[0]
  1178. args = [[ch[x] for x in f], c2]
  1179. elif m in {ConvEdgeFusion}:
  1180. c2 = make_divisible(min(args[0], max_channels) * width, 8)
  1181. args = [[ch[x] for x in f], c2]
  1182. elif m in {MutilScaleEdgeInfoGenetator}:
  1183. c1 = ch[f]
  1184. c2 = [make_divisible(min(i, max_channels) * width, 8) for i in args[0]]
  1185. args = [c1, c2]
  1186. elif m in {MultiScaleGatedAttn}:
  1187. c1 = [ch[x] for x in f]
  1188. c2 = min(c1)
  1189. args = [c1]
  1190. elif m is HyperComputeModule:
  1191. c1, c2 = ch[f], args[0]
  1192. c2 = make_divisible(min(c2, max_channels) * width, 8)
  1193. args = [c1, c2, threshold]
  1194. elif m in {WFU, MultiScalePCA, MultiScalePCA_Down}:
  1195. c1 = [ch[x] for x in f]
  1196. c2 = c1[0]
  1197. args = [c1]
  1198. elif m in {HAFB}:
  1199. c1 = [ch[x] for x in f]
  1200. c2 = make_divisible(min(args[0], max_channels) * width, 8)
  1201. args = [c1, c2, *args[1:]]
  1202. elif m in {GetIndexOutput}:
  1203. c2 = ch[f][args[0]]
  1204. else:
  1205. c2 = ch[f]
  1206. if isinstance(c2, list) and m not in {ChannelTransformer, PyramidContextExtraction, CrossLayerChannelAttention, CrossLayerSpatialAttention, MutilScaleEdgeInfoGenetator}:
  1207. is_backbone = True
  1208. m_ = m
  1209. m_.backbone = True
  1210. else:
  1211. m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
  1212. t = str(m)[8:-2].replace('__main__.', '') # module type
  1213. m_.np = sum(x.numel() for x in m_.parameters()) # number params
  1214. m_.i, m_.f, m_.type = i + 4 if is_backbone else i, f, t # attach index, 'from' index, type
  1215. if verbose:
  1216. LOGGER.info(f"{i:>3}{str(f):>20}{n_:>3}{m_.np:10.0f} {t:<45}{str(args):<30}") # print
  1217. save.extend(x % (i + 4 if is_backbone else i) for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
  1218. layers.append(m_)
  1219. if i == 0:
  1220. ch = []
  1221. if isinstance(c2, list) and m not in {ChannelTransformer, PyramidContextExtraction, CrossLayerChannelAttention, CrossLayerSpatialAttention, MutilScaleEdgeInfoGenetator}:
  1222. ch.extend(c2)
  1223. for _ in range(5 - len(ch)):
  1224. ch.insert(0, 0)
  1225. else:
  1226. ch.append(c2)
  1227. return nn.Sequential(*layers), sorted(save)
  1228. def yaml_model_load(path):
  1229. """Load a YOLOv8 model from a YAML file."""
  1230. path = Path(path)
  1231. if path.stem in (f"yolov{d}{x}6" for x in "nsmlx" for d in (5, 8)):
  1232. new_stem = re.sub(r"(\d+)([nslmx])6(.+)?$", r"\1\2-p6\3", path.stem)
  1233. LOGGER.warning(f"WARNING ⚠️ Ultralytics YOLO P6 models now use -p6 suffix. Renaming {path.stem} to {new_stem}.")
  1234. path = path.with_name(new_stem + path.suffix)
  1235. unified_path = re.sub(r"(\d+)([nslmx])(.+)?$", r"\1\3", str(path)) # i.e. yolov8x.yaml -> yolov8.yaml
  1236. unified_path = re.sub(r'(hyper-yolo)([nslmx])(.+)?$', r'\1\3', str(unified_path))
  1237. unified_path = re.sub(r'(hyper-yolot)(.+)?$', r'\1\2', str(unified_path))
  1238. yaml_file = check_yaml(unified_path, hard=False) or check_yaml(path)
  1239. d = yaml_load(yaml_file) # model dict
  1240. d["scale"] = guess_model_scale(path)
  1241. d["yaml_file"] = str(path)
  1242. return d
  1243. def guess_model_scale(model_path):
  1244. """
  1245. Takes a path to a YOLO model's YAML file as input and extracts the size character of the model's scale. The function
  1246. uses regular expression matching to find the pattern of the model scale in the YAML file name, which is denoted by
  1247. n, s, m, l, or x. The function returns the size character of the model scale as a string.
  1248. Args:
  1249. model_path (str | Path): The path to the YOLO model's YAML file.
  1250. Returns:
  1251. (str): The size character of the model's scale, which can be n, s, m, l, or x.
  1252. """
  1253. try:
  1254. if re.search(r'(hyper-yolo)([tnslmx])', Path(model_path).stem) is not None:
  1255. return re.search(r'(hyper-yolo)([tnslmx])', Path(model_path).stem).group(2)
  1256. else:
  1257. return re.search(r"yolo[v]?\d+([nslmx])", Path(model_path).stem).group(1) # n, s, m, l, or x
  1258. except AttributeError:
  1259. return ""
  1260. def guess_model_task(model):
  1261. """
  1262. Guess the task of a PyTorch model from its architecture or configuration.
  1263. Args:
  1264. model (nn.Module | dict): PyTorch model or model configuration in YAML format.
  1265. Returns:
  1266. (str): Task of the model ('detect', 'segment', 'classify', 'pose').
  1267. Raises:
  1268. SyntaxError: If the task of the model could not be determined.
  1269. """
  1270. def cfg2task(cfg):
  1271. """Guess from YAML dictionary."""
  1272. m = cfg["head"][-1][-2].lower() # output module name
  1273. if m in {"classify", "classifier", "cls", "fc"}:
  1274. return "classify"
  1275. if "detect" in m:
  1276. return "detect"
  1277. if "segment" in m:
  1278. return "segment"
  1279. if "pose" in m:
  1280. return "pose"
  1281. if "obb" in m:
  1282. return "obb"
  1283. # Guess from model cfg
  1284. if isinstance(model, dict):
  1285. try:
  1286. return cfg2task(model)
  1287. except: # noqa E722
  1288. pass
  1289. # Guess from PyTorch model
  1290. if isinstance(model, nn.Module): # PyTorch model
  1291. for x in "model.args", "model.model.args", "model.model.model.args":
  1292. try:
  1293. return eval(x)["task"]
  1294. except: # noqa E722
  1295. pass
  1296. for x in "model.yaml", "model.model.yaml", "model.model.model.yaml":
  1297. try:
  1298. return cfg2task(eval(x))
  1299. except: # noqa E722
  1300. pass
  1301. for m in model.modules():
  1302. if isinstance(m, Segment):
  1303. return "segment"
  1304. elif isinstance(m, Classify):
  1305. return "classify"
  1306. elif isinstance(m, Pose):
  1307. return "pose"
  1308. elif isinstance(m, OBB):
  1309. return "obb"
  1310. elif isinstance(m, (Detect, WorldDetect, v10Detect)):
  1311. return "detect"
  1312. # Guess from model filename
  1313. if isinstance(model, (str, Path)):
  1314. model = Path(model)
  1315. if "-seg" in model.stem or "segment" in model.parts:
  1316. return "segment"
  1317. elif "-cls" in model.stem or "classify" in model.parts:
  1318. return "classify"
  1319. elif "-pose" in model.stem or "pose" in model.parts:
  1320. return "pose"
  1321. elif "-obb" in model.stem or "obb" in model.parts:
  1322. return "obb"
  1323. elif "detect" in model.parts:
  1324. return "detect"
  1325. # Unable to determine task from model
  1326. LOGGER.warning(
  1327. "WARNING ⚠️ Unable to automatically guess model task, assuming 'task=detect'. "
  1328. "Explicitly define task for your model, i.e. 'task=detect', 'segment', 'classify','pose' or 'obb'."
  1329. )
  1330. return "detect" # assume detect

tasks.py at commit 680f06b, no license · at the source

Overview

Authors: Ronghui Zheng1, Shanshan Cai2
ORCID iDs: Shanshan Cai
  1. Clinical Oncology School of Fujian Medical University, Fujian Cancer Hospital, China
  2. Division of Biomedical and Life Sciences, Faculty of Health and Medicine, Lancaster University, UK
Journal: The Journal of international medical research, volume 54, issue 3, article 03000605261422820
Dates: received 25 August 2025; accepted 15 January 2026; published online 23 March 2026; in print March 2026
Type: Research article · Language: English
License: CC BY-NC
Identifiers: DOI 10.1177/03000605261422820 · PMID 41871206 · PMCID PMC13009808 · OpenAlex W7140132002
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: structural MRI / diffusion (modality), human (organism), other condition (population), methods / tools (subfield)
Methods: Connectivity, Machine learning
Keywords: You Only Look Once version 12 (YOLOv12n), brain tumor detection, Attention-based C2f with Frequency-domain Feed-Forward Network (A2C2f-DFFN) module, C2f with Token Statistics Self-Attention and Dynamic Tanh (C2TSSA-DYT) module, dynamic upsampling operator
MeSH: Algorithms*, Artificial Intelligence*, Brain Neoplasms*, Image Interpretation, Computer-Assisted*, Magnetic Resonance Imaging*, Detection Algorithms, Humans (* major topic)
Journal subjects: Observational Study
Topic: Brain Tumor Detection and Classification (Computer Vision and Pattern Recognition, Computer Science), according to OpenAlex
Citations: not cited yet (Europe PMC); 43 references in the paper

Abstract

Objective: To address challenges such as blurred boundaries and irregular shapes in brain tumor magnetic resonance imaging scans, we developed a lightweight detection framework to enhance automated diagnosis and meet real-time clinical requirements.

Methods: We proposed an improved You Only Look Once version 12 (YOLOv12n)-based model featuring three modules. First, the Attention-based C2f with Frequency-domain Feed-Forward Network (A2C2f-DFFN) module was incorporated into the backbone network; it combined an attention mechanism with a frequency-domain feedforward network to enhance global context modeling and detailed feature reconstruction. Second, the C2f with Token Statistics Self-Attention and Dynamic Tanh (C2TSSA-DYT) module was employed in the feature fusion neck; it utilized statistical self-attention and a dynamic Tanh activation function to improve robustness in complex backgrounds. Finally, the dynamic upsampling operator was adopted in the feature reconstruction stage; it dynamically generated sampling weights to effectively prevent boundary blurring and detail loss.

Results: On the Kaggle brain tumor dataset, our method achieved 93.2% precision, 88.4% recall, and 94.1% mean average precision at IoU threshold 0.5 (0.5), surpassing YOLOv12n and other lightweight models. It showed excellent performance in patients with glioma and pituitary tumor cases using only 6.0 Giga Floating-point Operations Per Second (GFLOPs) and 2.76 M parameters for efficient real-time inference.

Conclusion: The enhanced YOLOv12n framework proposed in this study achieved good balance between accuracy and efficiency in brain tumor detection tasks, demonstrating strong robustness, which makes it suitable for use in clinical computer-aided diagnosis systems.

Reproduced under the paper's license (CC BY-NC), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 11 matches between paragraphs and lines of code.

weilaibot/my_Brain_tumor

License: none: the authors keep all their rights
State: the link answers, verified on 30 September 2026
Evidence: files inventoried
Commit: 680f06ba0c0f718d150b85643a9f5a149369e4a0, 15 November 2025
Languages: C/C++ (416), Python (311), CUDA (82), C++ (20), Shell (13), JavaScript (2)
Size: 1,763 files, 844 scripts
Software Heritage: not archived
Found in: “Data availability”
Holds: README, environment (shenduxuexilvcai_02/pyproject.toml, shenduxuexilvcai_02/requirements.txt, shenduxuexilvcai_02/docker/Dockerfile, shenduxuexilvcai_02/ultralytics/nn/extra_modules/DCNv4_op/setup.py, shenduxuexilvcai_02/ultralytics/nn/extra_modules/mamba/setup.py, shenduxuexilvcai_02/ultralytics/nn/extra_modules/ops_dcnv3/setup.py, shenduxuexilvcai_02/ultralytics/nn/extra_modules/rational_kat_cu/setup.py, shenduxuexilvcai_02/ultralytics/nn/extra_modules/selective_scan/setup.py, shenduxuexilvcai_02/ultralytics/nn/backbone/TransNeXt/swattention_extension/setup.py, shenduxuexilvcai_02/ultralytics/nn/extra_modules/cutlass/examples/19_large_depthwise_conv2d_torch_extension/setup.py), tests, documentation
Not found: license file, CITATION.cff, continuous integration
Tools: PyTorch (187 files), NumPy (84 files), OpenCV (28 files), Pillow (16 files), pandas (14 files), Matplotlib (13 files), SciPy (7 files), Hugging Face Transformers (5 files), seaborn (3 files), PyWavelets (2 files), scikit-learn (2 files), TensorFlow (2 files)
Availability: 1 check, the latest on 30 September 2026: the link answers
  • 30 September 2026: the link answers
845 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 844 scripts, each with its path and the digest of its content;
  • 11 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

Datasets cited

Data availability

Publicly available datasets were used for this research. Code: https://github.com/weilaibot/my_Brain_tumor.git.

Reproduced under the paper's license (CC BY-NC), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 30 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 2 authors, 5 keywords, 7 MeSH terms, 18 references.

Cite

This paper

Zheng, R., & Cai, S. (2026). Brain tumor detection on magnetic resonance imaging scans using the artificial intelligence-based You Only Look Once algorithm. The Journal of international medical research, 54(3), 03000605261422820. https://doi.org/10.1177/03000605261422820

BibTeX

@article{zheng2026brain,
author = {Zheng, Ronghui and Cai, Shanshan},
title = {{Brain tumor detection on magnetic resonance imaging scans using the artificial intelligence-based You Only Look Once algorithm}},
journal = {The Journal of international medical research},
year = {2026},
month = mar,
volume = {54},
number = {3},
pages = {03000605261422820},
publisher = {SAGE Publications},
issn = {0300-0605},
doi = {10.1177/03000605261422820},
url = {https://doi.org/10.1177/03000605261422820},
pmid = {41871206},
pmcid = {PMC13009808}
}

RIS

TY - JOUR
AU - Zheng, Ronghui
AU - Cai, Shanshan
TI - Brain tumor detection on magnetic resonance imaging scans using the artificial intelligence-based You Only Look Once algorithm
T2 - The Journal of international medical research
J2 - J Int Med Res
PY - 2026
DA - 2026/03/23
VL - 54
IS - 3
SP - 03000605261422820
SN - 0300-0605
PB - SAGE Publications
DO - 10.1177/03000605261422820
UR - https://doi.org/10.1177/03000605261422820
LA - en
ER -

CSL-JSON

{
"id": "10.1177/03000605261422820",
"type": "article-journal",
"title": "Brain tumor detection on magnetic resonance imaging scans using the artificial intelligence-based You Only Look Once algorithm",
"container-title": "The Journal of international medical research",
"author": [
{
"family": "Zheng",
"given": "Ronghui"
},
{
"family": "Cai",
"given": "Shanshan"
}
],
"container-title-short": "J Int Med Res",
"volume": "54",
"issue": "3",
"page": "03000605261422820",
"DOI": "10.1177/03000605261422820",
"PMID": "41871206",
"PMCID": "PMC13009808",
"ISSN": "0300-0605",
"publisher": "SAGE Publications",
"URL": "https://doi.org/10.1177/03000605261422820",
"language": "en",
"issued": {
"date-parts": [
[
2026,
3,
23
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41598-024-66228-1 [code]
Image classification and reconstruction from low-density EEG.
Journal: Scientific reports
In common: PyWavelets, Hugging Face Transformers, OpenCV, 8 other tools, methods / tools, structural MRI / diffusion
[2] doi:10.1016/j.crmeth.2024.100964 [code]
Unifying community whole-brain imaging datasets enables robust neuron identification and reveals determinants of neuron position in C. elegans.
Journal: Cell reports methods
In common: PyWavelets, OpenCV, TensorFlow, 8 other tools, methods / tools
[3] doi:10.1038/s41467-026-72057-9 [code]
Sex-specific behavioral feedback modulates sensorimotor processing and drives flexible social behavior.
Journal: Nature communications
In common: PyWavelets, OpenCV, TensorFlow, 8 other tools
[4] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: Hugging Face Transformers, OpenCV, TensorFlow, 8 other tools
[5] doi:10.1038/s41467-026-74358-5 [code]
Brain-inspired spatial intelligence for embodied agents.
Journal: Nature communications
In common: Hugging Face Transformers, OpenCV, TensorFlow, 8 other tools
[6] doi:10.1038/s41592-026-03057-2 [code]
CREsted: modeling genomic and synthetic cell-type-specific enhancers across tissues and species.
Journal: Nature methods
In common: PyWavelets, TensorFlow, Pillow, 7 other tools, methods / tools
[7] doi:10.1002/hbm.70469 [code]
VarCoNet: A Variability-Aware Self-Supervised Framework for Functional Connectome Extraction From Resting-State fMRI.
Journal: Human brain mapping
In common: Hugging Face Transformers, OpenCV, Pillow, 7 other tools, methods / tools
[8] doi:10.1093/braincomms/fcag253 [code]
Disease detection and classification in temporal lobe epilepsy: step-wise versus simultaneous AI decision models in a multisite neuroimaging study.
Journal: Brain communications
In common: Hugging Face Transformers, OpenCV, Pillow, 7 other tools, structural MRI / diffusion
[9] doi:10.1016/j.patter.2026.101538 [code]
A multi-modal foundation model for brain disease diagnosis and medical imaging.
Journal: Patterns (New York, N.Y.)
In common: Hugging Face Transformers, OpenCV, TensorFlow, 7 other tools
[10] doi:10.1038/s41467-026-76837-1 [code]
Drug screen and machine learning predict neuroprotective agents in a preclinical human model of childhood dementia.
Journal: Nature communications
In common: Hugging Face Transformers, OpenCV, Pillow, 7 other tools, other condition

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1177/03000605261422820.svg)](https://openscicode.org/badge/doi/10.1177/03000605261422820)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1177/03000605261422820.svg
   :target: https://openscicode.org/badge/doi/10.1177/03000605261422820
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1177/03000605261422820"><img src="https://openscicode.org/badge/doi/10.1177/03000605261422820.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.