model.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import inspect
  3. from pathlib import Path
  4. from typing import Any, Dict, List, Union
  5. import numpy as np
  6. import torch
  7. from PIL import Image
  8. from huggingface_hub import PyTorchModelHubMixin
  9. from ultralytics.cfg import TASK2DATA, get_cfg, get_save_dir
  10. from ultralytics.engine.results import Results
  11. from ultralytics.hub import HUB_WEB_ROOT, HUBTrainingSession
  12. from ultralytics.nn.tasks import attempt_load_one_weight, guess_model_task, nn, yaml_model_load
  13. from ultralytics.utils import (
  14. ARGV,
  15. ASSETS,
  16. DEFAULT_CFG_DICT,
  17. LOGGER,
  18. RANK,
  19. SETTINGS,
  20. callbacks,
  21. checks,
  22. emojis,
  23. yaml_load,
  24. )
  25. class Model(nn.Module, PyTorchModelHubMixin, repo_url="https://github.com/ultralytics/ultralytics", pipeline_tag="object-detection", license="agpl-3.0"):
  26. """
  27. A base class for implementing YOLO models, unifying APIs across different model types.
  28. This class provides a common interface for various operations related to YOLO models, such as training,
  29. validation, prediction, exporting, and benchmarking. It handles different types of models, including those
  30. loaded from local files, Ultralytics HUB, or Triton Server.
  31. Attributes:
  32. callbacks (Dict): A dictionary of callback functions for various events during model operations.
  33. predictor (BasePredictor): The predictor object used for making predictions.
  34. model (nn.Module): The underlying PyTorch model.
  35. trainer (BaseTrainer): The trainer object used for training the model.
  36. ckpt (Dict): The checkpoint data if the model is loaded from a *.pt file.
  37. cfg (str): The configuration of the model if loaded from a *.yaml file.
  38. ckpt_path (str): The path to the checkpoint file.
  39. overrides (Dict): A dictionary of overrides for model configuration.
  40. metrics (Dict): The latest training/validation metrics.
  41. session (HUBTrainingSession): The Ultralytics HUB session, if applicable.
  42. task (str): The type of task the model is intended for.
  43. model_name (str): The name of the model.
  44. Methods:
  45. __call__: Alias for the predict method, enabling the model instance to be callable.
  46. _new: Initializes a new model based on a configuration file.
  47. _load: Loads a model from a checkpoint file.
  48. _check_is_pytorch_model: Ensures that the model is a PyTorch model.
  49. reset_weights: Resets the model's weights to their initial state.
  50. load: Loads model weights from a specified file.
  51. save: Saves the current state of the model to a file.
  52. info: Logs or returns information about the model.
  53. fuse: Fuses Conv2d and BatchNorm2d layers for optimized inference.
  54. predict: Performs object detection predictions.
  55. track: Performs object tracking.
  56. val: Validates the model on a dataset.
  57. benchmark: Benchmarks the model on various export formats.
  58. export: Exports the model to different formats.
  59. train: Trains the model on a dataset.
  60. tune: Performs hyperparameter tuning.
  61. _apply: Applies a function to the model's tensors.
  62. add_callback: Adds a callback function for an event.
  63. clear_callback: Clears all callbacks for an event.
  64. reset_callbacks: Resets all callbacks to their default functions.
  65. Examples:
  66. >>> from ultralytics import YOLO
  67. >>> model = YOLO("yolo11n.pt")
  68. >>> results = model.predict("image.jpg")
  69. >>> model.train(data="coco8.yaml", epochs=3)
  70. >>> metrics = model.val()
  71. >>> model.export(format="onnx")
  72. """
  73. def __init__(
  74. self,
  75. model: Union[str, Path] = "yolo11n.pt",
  76. task: str = None,
  77. verbose: bool = False,
  78. ) -> None:
  79. """
  80. Initializes a new instance of the YOLO model class.
  81. This constructor sets up the model based on the provided model path or name. It handles various types of
  82. model sources, including local files, Ultralytics HUB models, and Triton Server models. The method
  83. initializes several important attributes of the model and prepares it for operations like training,
  84. prediction, or export.
  85. Args:
  86. model (Union[str, Path]): Path or name of the model to load or create. Can be a local file path, a
  87. model name from Ultralytics HUB, or a Triton Server model.
  88. task (str | None): The task type associated with the YOLO model, specifying its application domain.
  89. verbose (bool): If True, enables verbose output during the model's initialization and subsequent
  90. operations.
  91. Raises:
  92. FileNotFoundError: If the specified model file does not exist or is inaccessible.
  93. ValueError: If the model file or configuration is invalid or unsupported.
  94. ImportError: If required dependencies for specific model types (like HUB SDK) are not installed.
  95. Examples:
  96. >>> model = Model("yolo11n.pt")
  97. >>> model = Model("path/to/model.yaml", task="detect")
  98. >>> model = Model("hub_model", verbose=True)
  99. """
  100. super().__init__()
  101. self.callbacks = callbacks.get_default_callbacks()
  102. self.predictor = None # reuse predictor
  103. self.model = None # model object
  104. self.trainer = None # trainer object
  105. self.ckpt = {} # if loaded from *.pt
  106. self.cfg = None # if loaded from *.yaml
  107. self.ckpt_path = None
  108. self.overrides = {} # overrides for trainer object
  109. self.metrics = None # validation/training metrics
  110. self.session = None # HUB session
  111. self.task = task # task type
  112. model = str(model).strip()
  113. # Check if Ultralytics HUB model from https://hub.ultralytics.com
  114. if self.is_hub_model(model):
  115. # Fetch model from HUB
  116. checks.check_requirements("hub-sdk>=0.0.12")
  117. session = HUBTrainingSession.create_session(model)
  118. model = session.model_file
  119. if session.train_args: # training sent from HUB
  120. self.session = session
  121. # Check if Triton Server model
  122. elif self.is_triton_model(model):
  123. self.model_name = self.model = model
  124. self.overrides["task"] = task or "detect" # set `task=detect` if not explicitly set
  125. return
  126. # Load or create new YOLO model
  127. if Path(model).suffix in {".yaml", ".yml"}:
  128. self._new(model, task=task, verbose=verbose)
  129. else:
  130. self._load(model, task=task)
  131. # Delete super().training for accessing self.model.training
  132. del self.training
  133. def __call__(
  134. self,
  135. source: Union[str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor] = None,
  136. stream: bool = False,
  137. **kwargs: Any,
  138. ) -> list:
  139. """
  140. Alias for the predict method, enabling the model instance to be callable for predictions.
  141. This method simplifies the process of making predictions by allowing the model instance to be called
  142. directly with the required arguments.
  143. Args:
  144. source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | List | Tuple): The source of
  145. the image(s) to make predictions on. Can be a file path, URL, PIL image, numpy array, PyTorch
  146. tensor, or a list/tuple of these.
  147. stream (bool): If True, treat the input source as a continuous stream for predictions.
  148. **kwargs: Additional keyword arguments to configure the prediction process.
  149. Returns:
  150. (List[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a
  151. Results object.
  152. Examples:
  153. >>> model = YOLO("yolo11n.pt")
  154. >>> results = model("https://ultralytics.com/images/bus.jpg")
  155. >>> for r in results:
  156. ... print(f"Detected {len(r)} objects in image")
  157. """
  158. return self.predict(source, stream, **kwargs)
  159. @staticmethod
  160. def is_triton_model(model: str) -> bool:
  161. """
  162. Checks if the given model string is a Triton Server URL.
  163. This static method determines whether the provided model string represents a valid Triton Server URL by
  164. parsing its components using urllib.parse.urlsplit().
  165. Args:
  166. model (str): The model string to be checked.
  167. Returns:
  168. (bool): True if the model string is a valid Triton Server URL, False otherwise.
  169. Examples:
  170. >>> Model.is_triton_model("http://localhost:8000/v2/models/yolov8n")
  171. True
  172. >>> Model.is_triton_model("yolo11n.pt")
  173. False
  174. """
  175. from urllib.parse import urlsplit
  176. url = urlsplit(model)
  177. return url.netloc and url.path and url.scheme in {"http", "grpc"}
  178. @staticmethod
  179. def is_hub_model(model: str) -> bool:
  180. """
  181. Check if the provided model is an Ultralytics HUB model.
  182. This static method determines whether the given model string represents a valid Ultralytics HUB model
  183. identifier.
  184. Args:
  185. model (str): The model string to check.
  186. Returns:
  187. (bool): True if the model is a valid Ultralytics HUB model, False otherwise.
  188. Examples:
  189. >>> Model.is_hub_model("https://hub.ultralytics.com/models/MODEL")
  190. True
  191. >>> Model.is_hub_model("yolo11n.pt")
  192. False
  193. """
  194. return model.startswith(f"{HUB_WEB_ROOT}/models/")
  195. def _new(self, cfg: str, task=None, model=None, verbose=False) -> None:
  196. """
  197. Initializes a new model and infers the task type from the model definitions.
  198. This method creates a new model instance based on the provided configuration file. It loads the model
  199. configuration, infers the task type if not specified, and initializes the model using the appropriate
  200. class from the task map.
  201. Args:
  202. cfg (str): Path to the model configuration file in YAML format.
  203. task (str | None): The specific task for the model. If None, it will be inferred from the config.
  204. model (torch.nn.Module | None): A custom model instance. If provided, it will be used instead of creating
  205. a new one.
  206. verbose (bool): If True, displays model information during loading.
  207. Raises:
  208. ValueError: If the configuration file is invalid or the task cannot be inferred.
  209. ImportError: If the required dependencies for the specified task are not installed.
  210. Examples:
  211. >>> model = Model()
  212. >>> model._new("yolov8n.yaml", task="detect", verbose=True)
  213. """
  214. cfg_dict = yaml_model_load(cfg)
  215. self.cfg = cfg
  216. self.task = task or guess_model_task(cfg_dict)
  217. self.model = (model or self._smart_load("model"))(cfg_dict, verbose=verbose and RANK == -1) # build model
  218. self.overrides["model"] = self.cfg
  219. self.overrides["task"] = self.task
  220. # Below added to allow export from YAMLs
  221. self.model.args = {**DEFAULT_CFG_DICT, **self.overrides} # combine default and model args (prefer model args)
  222. self.model.task = self.task
  223. self.model_name = cfg
  224. def _load(self, weights: str, task=None) -> None:
  225. """
  226. Loads a model from a checkpoint file or initializes it from a weights file.
  227. This method handles loading models from either .pt checkpoint files or other weight file formats. It sets
  228. up the model, task, and related attributes based on the loaded weights.
  229. Args:
  230. weights (str): Path to the model weights file to be loaded.
  231. task (str | None): The task associated with the model. If None, it will be inferred from the model.
  232. Raises:
  233. FileNotFoundError: If the specified weights file does not exist or is inaccessible.
  234. ValueError: If the weights file format is unsupported or invalid.
  235. Examples:
  236. >>> model = Model()
  237. >>> model._load("yolo11n.pt")
  238. >>> model._load("path/to/weights.pth", task="detect")
  239. """
  240. if weights.lower().startswith(("https://", "http://", "rtsp://", "rtmp://", "tcp://")):
  241. weights = checks.check_file(weights, download_dir=SETTINGS["weights_dir"]) # download and return local file
  242. weights = checks.check_model_file_from_stem(weights) # add suffix, i.e. yolov8n -> yolov8n.pt
  243. if Path(weights).suffix == ".pt":
  244. self.model, self.ckpt = attempt_load_one_weight(weights)
  245. self.task = self.model.args["task"]
  246. self.overrides = self.model.args = self._reset_ckpt_args(self.model.args)
  247. self.ckpt_path = self.model.pt_path
  248. else:
  249. weights = checks.check_file(weights) # runs in all cases, not redundant with above call
  250. self.model, self.ckpt = weights, None
  251. self.task = task or guess_model_task(weights)
  252. self.ckpt_path = weights
  253. self.overrides["model"] = weights
  254. self.overrides["task"] = self.task
  255. self.model_name = weights
  256. def _check_is_pytorch_model(self) -> None:
  257. """
  258. Checks if the model is a PyTorch model and raises a TypeError if it's not.
  259. This method verifies that the model is either a PyTorch module or a .pt file. It's used to ensure that
  260. certain operations that require a PyTorch model are only performed on compatible model types.
  261. Raises:
  262. TypeError: If the model is not a PyTorch module or a .pt file. The error message provides detailed
  263. information about supported model formats and operations.
  264. Examples:
  265. >>> model = Model("yolo11n.pt")
  266. >>> model._check_is_pytorch_model() # No error raised
  267. >>> model = Model("yolov8n.onnx")
  268. >>> model._check_is_pytorch_model() # Raises TypeError
  269. """
  270. pt_str = isinstance(self.model, (str, Path)) and Path(self.model).suffix == ".pt"
  271. pt_module = isinstance(self.model, nn.Module)
  272. if not (pt_module or pt_str):
  273. raise TypeError(
  274. f"model='{self.model}' should be a *.pt PyTorch model to run this method, but is a different format. "
  275. f"PyTorch models can train, val, predict and export, i.e. 'model.train(data=...)', but exported "
  276. f"formats like ONNX, TensorRT etc. only support 'predict' and 'val' modes, "
  277. f"i.e. 'yolo predict model=yolov8n.onnx'.\nTo run CUDA or MPS inference please pass the device "
  278. f"argument directly in your inference command, i.e. 'model.predict(source=..., device=0)'"
  279. )
  280. def reset_weights(self) -> "Model":
  281. """
  282. Resets the model's weights to their initial state.
  283. This method iterates through all modules in the model and resets their parameters if they have a
  284. 'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True,
  285. enabling them to be updated during training.
  286. Returns:
  287. (Model): The instance of the class with reset weights.
  288. Raises:
  289. AssertionError: If the model is not a PyTorch model.
  290. Examples:
  291. >>> model = Model("yolo11n.pt")
  292. >>> model.reset_weights()
  293. """
  294. self._check_is_pytorch_model()
  295. for m in self.model.modules():
  296. if hasattr(m, "reset_parameters"):
  297. m.reset_parameters()
  298. for p in self.model.parameters():
  299. p.requires_grad = True
  300. return self
  301. def load(self, weights: Union[str, Path] = "yolo11n.pt") -> "Model":
  302. """
  303. Loads parameters from the specified weights file into the model.
  304. This method supports loading weights from a file or directly from a weights object. It matches parameters by
  305. name and shape and transfers them to the model.
  306. Args:
  307. weights (Union[str, Path]): Path to the weights file or a weights object.
  308. Returns:
  309. (Model): The instance of the class with loaded weights.
  310. Raises:
  311. AssertionError: If the model is not a PyTorch model.
  312. Examples:
  313. >>> model = Model()
  314. >>> model.load("yolo11n.pt")
  315. >>> model.load(Path("path/to/weights.pt"))
  316. """
  317. self._check_is_pytorch_model()
  318. if isinstance(weights, (str, Path)):
  319. self.overrides["pretrained"] = weights # remember the weights for DDP training
  320. weights, self.ckpt = attempt_load_one_weight(weights)
  321. self.model.load(weights)
  322. return self
  323. def save(self, filename: Union[str, Path] = "saved_model.pt") -> None:
  324. """
  325. Saves the current model state to a file.
  326. This method exports the model's checkpoint (ckpt) to the specified filename. It includes metadata such as
  327. the date, Ultralytics version, license information, and a link to the documentation.
  328. Args:
  329. filename (Union[str, Path]): The name of the file to save the model to.
  330. Raises:
  331. AssertionError: If the model is not a PyTorch model.
  332. Examples:
  333. >>> model = Model("yolo11n.pt")
  334. >>> model.save("my_model.pt")
  335. """
  336. self._check_is_pytorch_model()
  337. from copy import deepcopy
  338. from datetime import datetime
  339. from ultralytics import __version__
  340. updates = {
  341. "model": deepcopy(self.model).half() if isinstance(self.model, nn.Module) else self.model,
  342. "date": datetime.now().isoformat(),
  343. "version": __version__,
  344. "license": "AGPL-3.0 License (https://ultralytics.com/license)",
  345. "docs": "https://docs.ultralytics.com",
  346. }
  347. torch.save({**self.ckpt, **updates}, filename)
  348. def info(self, detailed: bool = False, verbose: bool = True):
  349. """
  350. Logs or returns model information.
  351. This method provides an overview or detailed information about the model, depending on the arguments
  352. passed. It can control the verbosity of the output and return the information as a list.
  353. Args:
  354. detailed (bool): If True, shows detailed information about the model layers and parameters.
  355. verbose (bool): If True, prints the information. If False, returns the information as a list.
  356. Returns:
  357. (List[str]): A list of strings containing various types of information about the model, including
  358. model summary, layer details, and parameter counts. Empty if verbose is True.
  359. Raises:
  360. TypeError: If the model is not a PyTorch model.
  361. Examples:
  362. >>> model = Model("yolo11n.pt")
  363. >>> model.info() # Prints model summary
  364. >>> info_list = model.info(detailed=True, verbose=False) # Returns detailed info as a list
  365. """
  366. self._check_is_pytorch_model()
  367. return self.model.info(detailed=detailed, verbose=verbose)
  368. def fuse(self):
  369. """
  370. Fuses Conv2d and BatchNorm2d layers in the model for optimized inference.
  371. This method iterates through the model's modules and fuses consecutive Conv2d and BatchNorm2d layers
  372. into a single layer. This fusion can significantly improve inference speed by reducing the number of
  373. operations and memory accesses required during forward passes.
  374. The fusion process typically involves folding the BatchNorm2d parameters (mean, variance, weight, and
  375. bias) into the preceding Conv2d layer's weights and biases. This results in a single Conv2d layer that
  376. performs both convolution and normalization in one step.
  377. Raises:
  378. TypeError: If the model is not a PyTorch nn.Module.
  379. Examples:
  380. >>> model = Model("yolo11n.pt")
  381. >>> model.fuse()
  382. >>> # Model is now fused and ready for optimized inference
  383. """
  384. self._check_is_pytorch_model()
  385. self.model.fuse()
  386. def embed(
  387. self,
  388. source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
  389. stream: bool = False,
  390. **kwargs: Any,
  391. ) -> list:
  392. """
  393. Generates image embeddings based on the provided source.
  394. This method is a wrapper around the 'predict()' method, focusing on generating embeddings from an image
  395. source. It allows customization of the embedding process through various keyword arguments.
  396. Args:
  397. source (str | Path | int | List | Tuple | np.ndarray | torch.Tensor): The source of the image for
  398. generating embeddings. Can be a file path, URL, PIL image, numpy array, etc.
  399. stream (bool): If True, predictions are streamed.
  400. **kwargs: Additional keyword arguments for configuring the embedding process.
  401. Returns:
  402. (List[torch.Tensor]): A list containing the image embeddings.
  403. Raises:
  404. AssertionError: If the model is not a PyTorch model.
  405. Examples:
  406. >>> model = YOLO("yolo11n.pt")
  407. >>> image = "https://ultralytics.com/images/bus.jpg"
  408. >>> embeddings = model.embed(image)
  409. >>> print(embeddings[0].shape)
  410. """
  411. if not kwargs.get("embed"):
  412. kwargs["embed"] = [len(self.model.model) - 2] # embed second-to-last layer if no indices passed
  413. return self.predict(source, stream, **kwargs)
  414. def predict(
  415. self,
  416. source: Union[str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor] = None,
  417. stream: bool = False,
  418. predictor=None,
  419. **kwargs: Any,
  420. ) -> List[Results]:
  421. """
  422. Performs predictions on the given image source using the YOLO model.
  423. This method facilitates the prediction process, allowing various configurations through keyword arguments.
  424. It supports predictions with custom predictors or the default predictor method. The method handles different
  425. types of image sources and can operate in a streaming mode.
  426. Args:
  427. source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | List | Tuple): The source
  428. of the image(s) to make predictions on. Accepts various types including file paths, URLs, PIL
  429. images, numpy arrays, and torch tensors.
  430. stream (bool): If True, treats the input source as a continuous stream for predictions.
  431. predictor (BasePredictor | None): An instance of a custom predictor class for making predictions.
  432. If None, the method uses a default predictor.
  433. **kwargs: Additional keyword arguments for configuring the prediction process.
  434. Returns:
  435. (List[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a
  436. Results object.
  437. Examples:
  438. >>> model = YOLO("yolo11n.pt")
  439. >>> results = model.predict(source="path/to/image.jpg", conf=0.25)
  440. >>> for r in results:
  441. ... print(r.boxes.data) # print detection bounding boxes
  442. Notes:
  443. - If 'source' is not provided, it defaults to the ASSETS constant with a warning.
  444. - The method sets up a new predictor if not already present and updates its arguments with each call.
  445. - For SAM-type models, 'prompts' can be passed as a keyword argument.
  446. """
  447. if source is None:
  448. source = ASSETS
  449. LOGGER.warning(f"WARNING ⚠️ 'source' is missing. Using 'source={source}'.")
  450. is_cli = (ARGV[0].endswith("yolo") or ARGV[0].endswith("ultralytics")) and any(
  451. x in ARGV for x in ("predict", "track", "mode=predict", "mode=track")
  452. )
  453. custom = {"conf": 0.25, "batch": 1, "save": is_cli, "mode": "predict"} # method defaults
  454. args = {**self.overrides, **custom, **kwargs} # highest priority args on the right
  455. prompts = args.pop("prompts", None) # for SAM-type models
  456. if not self.predictor:
  457. self.predictor = (predictor or self._smart_load("predictor"))(overrides=args, _callbacks=self.callbacks)
  458. self.predictor.setup_model(model=self.model, verbose=is_cli)
  459. else: # only update args if predictor is already setup
  460. self.predictor.args = get_cfg(self.predictor.args, args)
  461. if "project" in args or "name" in args:
  462. self.predictor.save_dir = get_save_dir(self.predictor.args)
  463. if prompts and hasattr(self.predictor, "set_prompts"): # for SAM-type models
  464. self.predictor.set_prompts(prompts)
  465. return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)
  466. def track(
  467. self,
  468. source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
  469. stream: bool = False,
  470. persist: bool = False,
  471. **kwargs: Any,
  472. ) -> List[Results]:
  473. """
  474. Conducts object tracking on the specified input source using the registered trackers.
  475. This method performs object tracking using the model's predictors and optionally registered trackers. It handles
  476. various input sources such as file paths or video streams, and supports customization through keyword arguments.
  477. The method registers trackers if not already present and can persist them between calls.
  478. Args:
  479. source (Union[str, Path, int, List, Tuple, np.ndarray, torch.Tensor], optional): Input source for object
  480. tracking. Can be a file path, URL, or video stream.
  481. stream (bool): If True, treats the input source as a continuous video stream. Defaults to False.
  482. persist (bool): If True, persists trackers between different calls to this method. Defaults to False.
  483. **kwargs: Additional keyword arguments for configuring the tracking process.
  484. Returns:
  485. (List[ultralytics.engine.results.Results]): A list of tracking results, each a Results object.
  486. Raises:
  487. AttributeError: If the predictor does not have registered trackers.
  488. Examples:
  489. >>> model = YOLO("yolo11n.pt")
  490. >>> results = model.track(source="path/to/video.mp4", show=True)
  491. >>> for r in results:
  492. ... print(r.boxes.id) # print tracking IDs
  493. Notes:
  494. - This method sets a default confidence threshold of 0.1 for ByteTrack-based tracking.
  495. - The tracking mode is explicitly set in the keyword arguments.
  496. - Batch size is set to 1 for tracking in videos.
  497. """
  498. if not hasattr(self.predictor, "trackers"):
  499. from ultralytics.trackers import register_tracker
  500. register_tracker(self, persist)
  501. kwargs["conf"] = kwargs.get("conf") or 0.1 # ByteTrack-based method needs low confidence predictions as input
  502. kwargs["batch"] = kwargs.get("batch") or 1 # batch-size 1 for tracking in videos
  503. kwargs["mode"] = "track"
  504. return self.predict(source=source, stream=stream, **kwargs)
  505. def val(
  506. self,
  507. validator=None,
  508. **kwargs: Any,
  509. ):
  510. """
  511. Validates the model using a specified dataset and validation configuration.
  512. This method facilitates the model validation process, allowing for customization through various settings. It
  513. supports validation with a custom validator or the default validation approach. The method combines default
  514. configurations, method-specific defaults, and user-provided arguments to configure the validation process.
  515. Args:
  516. validator (ultralytics.engine.validator.BaseValidator | None): An instance of a custom validator class for
  517. validating the model.
  518. **kwargs: Arbitrary keyword arguments for customizing the validation process.
  519. Returns:
  520. (ultralytics.utils.metrics.DetMetrics): Validation metrics obtained from the validation process.
  521. Raises:
  522. AssertionError: If the model is not a PyTorch model.
  523. Examples:
  524. >>> model = YOLO("yolo11n.pt")
  525. >>> results = model.val(data="coco8.yaml", imgsz=640)
  526. >>> print(results.box.map) # Print mAP50-95
  527. """
  528. custom = {"rect": True} # method defaults
  529. args = {**self.overrides, **custom, **kwargs, "mode": "val"} # highest priority args on the right
  530. validator = (validator or self._smart_load("validator"))(args=args, _callbacks=self.callbacks)
  531. validator(model=self.model)
  532. self.metrics = validator.metrics
  533. return validator.metrics
  534. def benchmark(
  535. self,
  536. **kwargs: Any,
  537. ):
  538. """
  539. Benchmarks the model across various export formats to evaluate performance.
  540. This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc.
  541. It uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is
  542. configured using a combination of default configuration values, model-specific arguments, method-specific
  543. defaults, and any additional user-provided keyword arguments.
  544. Args:
  545. **kwargs: Arbitrary keyword arguments to customize the benchmarking process. These are combined with
  546. default configurations, model-specific arguments, and method defaults. Common options include:
  547. - data (str): Path to the dataset for benchmarking.
  548. - imgsz (int | List[int]): Image size for benchmarking.
  549. - half (bool): Whether to use half-precision (FP16) mode.
  550. - int8 (bool): Whether to use int8 precision mode.
  551. - device (str): Device to run the benchmark on (e.g., 'cpu', 'cuda').
  552. - verbose (bool): Whether to print detailed benchmark information.
  553. Returns:
  554. (Dict): A dictionary containing the results of the benchmarking process, including metrics for
  555. different export formats.
  556. Raises:
  557. AssertionError: If the model is not a PyTorch model.
  558. Examples:
  559. >>> model = YOLO("yolo11n.pt")
  560. >>> results = model.benchmark(data="coco8.yaml", imgsz=640, half=True)
  561. >>> print(results)
  562. """
  563. self._check_is_pytorch_model()
  564. from ultralytics.utils.benchmarks import benchmark
  565. custom = {"verbose": False} # method defaults
  566. args = {**DEFAULT_CFG_DICT, **self.model.args, **custom, **kwargs, "mode": "benchmark"}
  567. return benchmark(
  568. model=self,
  569. data=kwargs.get("data"), # if no 'data' argument passed set data=None for default datasets
  570. imgsz=args["imgsz"],
  571. half=args["half"],
  572. int8=args["int8"],
  573. device=args["device"],
  574. verbose=kwargs.get("verbose"),
  575. )
  576. def export(
  577. self,
  578. **kwargs: Any,
  579. ) -> str:
  580. """
  581. Exports the model to a different format suitable for deployment.
  582. This method facilitates the export of the model to various formats (e.g., ONNX, TorchScript) for deployment
  583. purposes. It uses the 'Exporter' class for the export process, combining model-specific overrides, method
  584. defaults, and any additional arguments provided.
  585. Args:
  586. **kwargs: Arbitrary keyword arguments to customize the export process. These are combined with
  587. the model's overrides and method defaults. Common arguments include:
  588. format (str): Export format (e.g., 'onnx', 'engine', 'coreml').
  589. half (bool): Export model in half-precision.
  590. int8 (bool): Export model in int8 precision.
  591. device (str): Device to run the export on.
  592. workspace (int): Maximum memory workspace size for TensorRT engines.
  593. nms (bool): Add Non-Maximum Suppression (NMS) module to model.
  594. simplify (bool): Simplify ONNX model.
  595. Returns:
  596. (str): The path to the exported model file.
  597. Raises:
  598. AssertionError: If the model is not a PyTorch model.
  599. ValueError: If an unsupported export format is specified.
  600. RuntimeError: If the export process fails due to errors.
  601. Examples:
  602. >>> model = YOLO("yolo11n.pt")
  603. >>> model.export(format="onnx", dynamic=True, simplify=True)
  604. 'path/to/exported/model.onnx'
  605. """
  606. self._check_is_pytorch_model()
  607. from .exporter import Exporter
  608. custom = {
  609. "imgsz": self.model.args["imgsz"],
  610. "batch": 1,
  611. "data": None,
  612. "device": None, # reset to avoid multi-GPU errors
  613. "verbose": False,
  614. } # method defaults
  615. args = {**self.overrides, **custom, **kwargs, "mode": "export"} # highest priority args on the right
  616. return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model)
  617. def train(
  618. self,
  619. trainer=None,
  620. **kwargs: Any,
  621. ):
  622. """
  623. Trains the model using the specified dataset and training configuration.
  624. This method facilitates model training with a range of customizable settings. It supports training with a
  625. custom trainer or the default training approach. The method handles scenarios such as resuming training
  626. from a checkpoint, integrating with Ultralytics HUB, and updating model and configuration after training.
  627. When using Ultralytics HUB, if the session has a loaded model, the method prioritizes HUB training
  628. arguments and warns if local arguments are provided. It checks for pip updates and combines default
  629. configurations, method-specific defaults, and user-provided arguments to configure the training process.
  630. Args:
  631. trainer (BaseTrainer | None): Custom trainer instance for model training. If None, uses default.
  632. **kwargs: Arbitrary keyword arguments for training configuration. Common options include:
  633. data (str): Path to dataset configuration file.
  634. epochs (int): Number of training epochs.
  635. batch_size (int): Batch size for training.
  636. imgsz (int): Input image size.
  637. device (str): Device to run training on (e.g., 'cuda', 'cpu').
  638. workers (int): Number of worker threads for data loading.
  639. optimizer (str): Optimizer to use for training.
  640. lr0 (float): Initial learning rate.
  641. patience (int): Epochs to wait for no observable improvement for early stopping of training.
  642. Returns:
  643. (Dict | None): Training metrics if available and training is successful; otherwise, None.
  644. Raises:
  645. AssertionError: If the model is not a PyTorch model.
  646. PermissionError: If there is a permission issue with the HUB session.
  647. ModuleNotFoundError: If the HUB SDK is not installed.
  648. Examples:
  649. >>> model = YOLO("yolo11n.pt")
  650. >>> results = model.train(data="coco8.yaml", epochs=3)
  651. """
  652. self._check_is_pytorch_model()
  653. if hasattr(self.session, "model") and self.session.model.id: # Ultralytics HUB session with loaded model
  654. if any(kwargs):
  655. LOGGER.warning("WARNING ⚠️ using HUB training arguments, ignoring local training arguments.")
  656. kwargs = self.session.train_args # overwrite kwargs
  657. checks.check_pip_update_available()
  658. overrides = yaml_load(checks.check_yaml(kwargs["cfg"])) if kwargs.get("cfg") else self.overrides
  659. custom = {
  660. # NOTE: handle the case when 'cfg' includes 'data'.
  661. "data": overrides.get("data") or DEFAULT_CFG_DICT["data"] or TASK2DATA[self.task],
  662. "model": self.overrides["model"],
  663. "task": self.task,
  664. } # method defaults
  665. args = {**overrides, **custom, **kwargs, "mode": "train"} # highest priority args on the right
  666. if args.get("resume"):
  667. args["resume"] = self.ckpt_path
  668. self.trainer = (trainer or self._smart_load("trainer"))(overrides=args, _callbacks=self.callbacks)
  669. if not args.get("resume"): # manually set model only if not resuming
  670. self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)
  671. self.model = self.trainer.model
  672. self.trainer.hub_session = self.session # attach optional HUB session
  673. self.trainer.train()
  674. # Update model and cfg after training
  675. if RANK in {-1, 0}:
  676. ckpt = self.trainer.best if self.trainer.best.exists() else self.trainer.last
  677. self.model, self.ckpt = attempt_load_one_weight(ckpt)
  678. self.overrides = self.model.args
  679. self.metrics = getattr(self.trainer.validator, "metrics", None) # TODO: no metrics returned by DDP
  680. return self.metrics
  681. def tune(
  682. self,
  683. use_ray=False,
  684. iterations=10,
  685. *args: Any,
  686. **kwargs: Any,
  687. ):
  688. """
  689. Conducts hyperparameter tuning for the model, with an option to use Ray Tune.
  690. This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method.
  691. When Ray Tune is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module.
  692. Otherwise, it uses the internal 'Tuner' class for tuning. The method combines default, overridden, and
  693. custom arguments to configure the tuning process.
  694. Args:
  695. use_ray (bool): If True, uses Ray Tune for hyperparameter tuning. Defaults to False.
  696. iterations (int): The number of tuning iterations to perform. Defaults to 10.
  697. *args: Variable length argument list for additional arguments.
  698. **kwargs: Arbitrary keyword arguments. These are combined with the model's overrides and defaults.
  699. Returns:
  700. (Dict): A dictionary containing the results of the hyperparameter search.
  701. Raises:
  702. AssertionError: If the model is not a PyTorch model.
  703. Examples:
  704. >>> model = YOLO("yolo11n.pt")
  705. >>> results = model.tune(use_ray=True, iterations=20)
  706. >>> print(results)
  707. """
  708. self._check_is_pytorch_model()
  709. if use_ray:
  710. from ultralytics.utils.tuner import run_ray_tune
  711. return run_ray_tune(self, max_samples=iterations, *args, **kwargs)
  712. else:
  713. from .tuner import Tuner
  714. custom = {} # method defaults
  715. args = {**self.overrides, **custom, **kwargs, "mode": "train"} # highest priority args on the right
  716. return Tuner(args=args, _callbacks=self.callbacks)(model=self, iterations=iterations)
  717. def _apply(self, fn) -> "Model":
  718. """
  719. Applies a function to model tensors that are not parameters or registered buffers.
  720. This method extends the functionality of the parent class's _apply method by additionally resetting the
  721. predictor and updating the device in the model's overrides. It's typically used for operations like
  722. moving the model to a different device or changing its precision.
  723. Args:
  724. fn (Callable): A function to be applied to the model's tensors. This is typically a method like
  725. to(), cpu(), cuda(), half(), or float().
  726. Returns:
  727. (Model): The model instance with the function applied and updated attributes.
  728. Raises:
  729. AssertionError: If the model is not a PyTorch model.
  730. Examples:
  731. >>> model = Model("yolo11n.pt")
  732. >>> model = model._apply(lambda t: t.cuda()) # Move model to GPU
  733. """
  734. self._check_is_pytorch_model()
  735. self = super()._apply(fn) # noqa
  736. self.predictor = None # reset predictor as device may have changed
  737. self.overrides["device"] = self.device # was str(self.device) i.e. device(type='cuda', index=0) -> 'cuda:0'
  738. return self
  739. @property
  740. def names(self) -> Dict[int, str]:
  741. """
  742. Retrieves the class names associated with the loaded model.
  743. This property returns the class names if they are defined in the model. It checks the class names for validity
  744. using the 'check_class_names' function from the ultralytics.nn.autobackend module. If the predictor is not
  745. initialized, it sets it up before retrieving the names.
  746. Returns:
  747. (Dict[int, str]): A dict of class names associated with the model.
  748. Raises:
  749. AttributeError: If the model or predictor does not have a 'names' attribute.
  750. Examples:
  751. >>> model = YOLO("yolo11n.pt")
  752. >>> print(model.names)
  753. {0: 'person', 1: 'bicycle', 2: 'car', ...}
  754. """
  755. from ultralytics.nn.autobackend import check_class_names
  756. if hasattr(self.model, "names"):
  757. return check_class_names(self.model.names)
  758. if not self.predictor: # export formats will not have predictor defined until predict() is called
  759. self.predictor = self._smart_load("predictor")(overrides=self.overrides, _callbacks=self.callbacks)
  760. self.predictor.setup_model(model=self.model, verbose=False)
  761. return self.predictor.model.names
  762. @property
  763. def device(self) -> torch.device:
  764. """
  765. Retrieves the device on which the model's parameters are allocated.
  766. This property determines the device (CPU or GPU) where the model's parameters are currently stored. It is
  767. applicable only to models that are instances of nn.Module.
  768. Returns:
  769. (torch.device): The device (CPU/GPU) of the model.
  770. Raises:
  771. AttributeError: If the model is not a PyTorch nn.Module instance.
  772. Examples:
  773. >>> model = YOLO("yolo11n.pt")
  774. >>> print(model.device)
  775. device(type='cuda', index=0) # if CUDA is available
  776. >>> model = model.to("cpu")
  777. >>> print(model.device)
  778. device(type='cpu')
  779. """
  780. return next(self.model.parameters()).device if isinstance(self.model, nn.Module) else None
  781. @property
  782. def transforms(self):
  783. """
  784. Retrieves the transformations applied to the input data of the loaded model.
  785. This property returns the transformations if they are defined in the model. The transforms
  786. typically include preprocessing steps like resizing, normalization, and data augmentation
  787. that are applied to input data before it is fed into the model.
  788. Returns:
  789. (object | None): The transform object of the model if available, otherwise None.
  790. Examples:
  791. >>> model = YOLO("yolo11n.pt")
  792. >>> transforms = model.transforms
  793. >>> if transforms:
  794. ... print(f"Model transforms: {transforms}")
  795. ... else:
  796. ... print("No transforms defined for this model.")
  797. """
  798. return self.model.transforms if hasattr(self.model, "transforms") else None
  799. def add_callback(self, event: str, func) -> None:
  800. """
  801. Adds a callback function for a specified event.
  802. This method allows registering custom callback functions that are triggered on specific events during
  803. model operations such as training or inference. Callbacks provide a way to extend and customize the
  804. behavior of the model at various stages of its lifecycle.
  805. Args:
  806. event (str): The name of the event to attach the callback to. Must be a valid event name recognized
  807. by the Ultralytics framework.
  808. func (Callable): The callback function to be registered. This function will be called when the
  809. specified event occurs.
  810. Raises:
  811. ValueError: If the event name is not recognized or is invalid.
  812. Examples:
  813. >>> def on_train_start(trainer):
  814. ... print("Training is starting!")
  815. >>> model = YOLO("yolo11n.pt")
  816. >>> model.add_callback("on_train_start", on_train_start)
  817. >>> model.train(data="coco8.yaml", epochs=1)
  818. """
  819. self.callbacks[event].append(func)
  820. def clear_callback(self, event: str) -> None:
  821. """
  822. Clears all callback functions registered for a specified event.
  823. This method removes all custom and default callback functions associated with the given event.
  824. It resets the callback list for the specified event to an empty list, effectively removing all
  825. registered callbacks for that event.
  826. Args:
  827. event (str): The name of the event for which to clear the callbacks. This should be a valid event name
  828. recognized by the Ultralytics callback system.
  829. Examples:
  830. >>> model = YOLO("yolo11n.pt")
  831. >>> model.add_callback("on_train_start", lambda: print("Training started"))
  832. >>> model.clear_callback("on_train_start")
  833. >>> # All callbacks for 'on_train_start' are now removed
  834. Notes:
  835. - This method affects both custom callbacks added by the user and default callbacks
  836. provided by the Ultralytics framework.
  837. - After calling this method, no callbacks will be executed for the specified event
  838. until new ones are added.
  839. - Use with caution as it removes all callbacks, including essential ones that might
  840. be required for proper functioning of certain operations.
  841. """
  842. self.callbacks[event] = []
  843. def reset_callbacks(self) -> None:
  844. """
  845. Resets all callbacks to their default functions.
  846. This method reinstates the default callback functions for all events, removing any custom callbacks that were
  847. previously added. It iterates through all default callback events and replaces the current callbacks with the
  848. default ones.
  849. The default callbacks are defined in the 'callbacks.default_callbacks' dictionary, which contains predefined
  850. functions for various events in the model's lifecycle, such as on_train_start, on_epoch_end, etc.
  851. This method is useful when you want to revert to the original set of callbacks after making custom
  852. modifications, ensuring consistent behavior across different runs or experiments.
  853. Examples:
  854. >>> model = YOLO("yolo11n.pt")
  855. >>> model.add_callback("on_train_start", custom_function)
  856. >>> model.reset_callbacks()
  857. # All callbacks are now reset to their default functions
  858. """
  859. for event in callbacks.default_callbacks.keys():
  860. self.callbacks[event] = [callbacks.default_callbacks[event][0]]
  861. @staticmethod
  862. def _reset_ckpt_args(args: dict) -> dict:
  863. """
  864. Resets specific arguments when loading a PyTorch model checkpoint.
  865. This static method filters the input arguments dictionary to retain only a specific set of keys that are
  866. considered important for model loading. It's used to ensure that only relevant arguments are preserved
  867. when loading a model from a checkpoint, discarding any unnecessary or potentially conflicting settings.
  868. Args:
  869. args (dict): A dictionary containing various model arguments and settings.
  870. Returns:
  871. (dict): A new dictionary containing only the specified include keys from the input arguments.
  872. Examples:
  873. >>> original_args = {"imgsz": 640, "data": "coco.yaml", "task": "detect", "batch": 16, "epochs": 100}
  874. >>> reset_args = Model._reset_ckpt_args(original_args)
  875. >>> print(reset_args)
  876. {'imgsz': 640, 'data': 'coco.yaml', 'task': 'detect'}
  877. """
  878. include = {"imgsz", "data", "task", "single_cls"} # only remember these arguments when loading a PyTorch model
  879. return {k: v for k, v in args.items() if k in include}
  880. # def __getattr__(self, attr):
  881. # """Raises error if object has no requested attribute."""
  882. # name = self.__class__.__name__
  883. # raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
  884. def _smart_load(self, key: str):
  885. """
  886. Loads the appropriate module based on the model task.
  887. This method dynamically selects and returns the correct module (model, trainer, validator, or predictor)
  888. based on the current task of the model and the provided key. It uses the task_map attribute to determine
  889. the correct module to load.
  890. Args:
  891. key (str): The type of module to load. Must be one of 'model', 'trainer', 'validator', or 'predictor'.
  892. Returns:
  893. (object): The loaded module corresponding to the specified key and current task.
  894. Raises:
  895. NotImplementedError: If the specified key is not supported for the current task.
  896. Examples:
  897. >>> model = Model(task="detect")
  898. >>> predictor = model._smart_load("predictor")
  899. >>> trainer = model._smart_load("trainer")
  900. Notes:
  901. - This method is typically used internally by other methods of the Model class.
  902. - The task_map attribute should be properly initialized with the correct mappings for each task.
  903. """
  904. try:
  905. return self.task_map[self.task][key]
  906. except Exception as e:
  907. name = self.__class__.__name__
  908. mode = inspect.stack()[1][3] # get the function name.
  909. raise NotImplementedError(
  910. emojis(f"WARNING ⚠️ '{name}' model does not support '{mode}' mode for '{self.task}' task yet.")
  911. ) from e
  912. @property
  913. def task_map(self) -> dict:
  914. """
  915. Provides a mapping from model tasks to corresponding classes for different modes.
  916. This property method returns a dictionary that maps each supported task (e.g., detect, segment, classify)
  917. to a nested dictionary. The nested dictionary contains mappings for different operational modes
  918. (model, trainer, validator, predictor) to their respective class implementations.
  919. The mapping allows for dynamic loading of appropriate classes based on the model's task and the
  920. desired operational mode. This facilitates a flexible and extensible architecture for handling
  921. various tasks and modes within the Ultralytics framework.
  922. Returns:
  923. (Dict[str, Dict[str, Any]]): A dictionary where keys are task names (str) and values are
  924. nested dictionaries. Each nested dictionary has keys 'model', 'trainer', 'validator', and
  925. 'predictor', mapping to their respective class implementations.
  926. Examples:
  927. >>> model = Model()
  928. >>> task_map = model.task_map
  929. >>> detect_class_map = task_map["detect"]
  930. >>> segment_class_map = task_map["segment"]
  931. Note:
  932. The actual implementation of this method may vary depending on the specific tasks and
  933. classes supported by the Ultralytics framework. The docstring provides a general
  934. description of the expected behavior and structure.
  935. """
  936. raise NotImplementedError("Please provide task map for your model!")
  937. def eval(self):
  938. """
  939. Sets the model to evaluation mode.
  940. This method changes the model's mode to evaluation, which affects layers like dropout and batch normalization
  941. that behave differently during training and evaluation.
  942. Returns:
  943. (Model): The model instance with evaluation mode set.
  944. Examples:
  945. >> model = YOLO("yolo11n.pt")
  946. >> model.eval()
  947. """
  948. self.model.eval()
  949. return self
  950. def __getattr__(self, name):
  951. """
  952. Enables accessing model attributes directly through the Model class.
  953. This method provides a way to access attributes of the underlying model directly through the Model class
  954. instance. It first checks if the requested attribute is 'model', in which case it returns the model from
  955. the module dictionary. Otherwise, it delegates the attribute lookup to the underlying model.
  956. Args:
  957. name (str): The name of the attribute to retrieve.
  958. Returns:
  959. (Any): The requested attribute value.
  960. Raises:
  961. AttributeError: If the requested attribute does not exist in the model.
  962. Examples:
  963. >>> model = YOLO("yolo11n.pt")
  964. >>> print(model.stride)
  965. >>> print(model.task)
  966. """
  967. return self._modules["model"] if name == "model" else getattr(self.model, name)