session.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import shutil
  3. import threading
  4. import time
  5. from http import HTTPStatus
  6. from pathlib import Path
  7. from urllib.parse import parse_qs, urlparse
  8. import requests
  9. from ultralytics.hub.utils import HELP_MSG, HUB_WEB_ROOT, PREFIX, TQDM
  10. from ultralytics.utils import IS_COLAB, LOGGER, SETTINGS, __version__, checks, emojis
  11. from ultralytics.utils.errors import HUBModelError
  12. AGENT_NAME = f"python-{__version__}-colab" if IS_COLAB else f"python-{__version__}-local"
  13. class HUBTrainingSession:
  14. """
  15. HUB training session for Ultralytics HUB YOLO models. Handles model initialization, heartbeats, and checkpointing.
  16. Attributes:
  17. model_id (str): Identifier for the YOLO model being trained.
  18. model_url (str): URL for the model in Ultralytics HUB.
  19. rate_limits (dict): Rate limits for different API calls (in seconds).
  20. timers (dict): Timers for rate limiting.
  21. metrics_queue (dict): Queue for the model's metrics.
  22. model (dict): Model data fetched from Ultralytics HUB.
  23. """
  24. def __init__(self, identifier):
  25. """
  26. Initialize the HUBTrainingSession with the provided model identifier.
  27. Args:
  28. identifier (str): Model identifier used to initialize the HUB training session.
  29. It can be a URL string or a model key with specific format.
  30. Raises:
  31. ValueError: If the provided model identifier is invalid.
  32. ConnectionError: If connecting with global API key is not supported.
  33. ModuleNotFoundError: If hub-sdk package is not installed.
  34. """
  35. from hub_sdk import HUBClient
  36. self.rate_limits = {"metrics": 3, "ckpt": 900, "heartbeat": 300} # rate limits (seconds)
  37. self.metrics_queue = {} # holds metrics for each epoch until upload
  38. self.metrics_upload_failed_queue = {} # holds metrics for each epoch if upload failed
  39. self.timers = {} # holds timers in ultralytics/utils/callbacks/hub.py
  40. self.model = None
  41. self.model_url = None
  42. self.model_file = None
  43. self.train_args = None
  44. # Parse input
  45. api_key, model_id, self.filename = self._parse_identifier(identifier)
  46. # Get credentials
  47. active_key = api_key or SETTINGS.get("api_key")
  48. credentials = {"api_key": active_key} if active_key else None # set credentials
  49. # Initialize client
  50. self.client = HUBClient(credentials)
  51. # Load models
  52. try:
  53. if model_id:
  54. self.load_model(model_id) # load existing model
  55. else:
  56. self.model = self.client.model() # load empty model
  57. except Exception:
  58. if identifier.startswith(f"{HUB_WEB_ROOT}/models/") and not self.client.authenticated:
  59. LOGGER.warning(
  60. f"{PREFIX}WARNING ⚠️ Please log in using 'yolo login API_KEY'. "
  61. "You can find your API Key at: https://hub.ultralytics.com/settings?tab=api+keys."
  62. )
  63. @classmethod
  64. def create_session(cls, identifier, args=None):
  65. """Class method to create an authenticated HUBTrainingSession or return None."""
  66. try:
  67. session = cls(identifier)
  68. if args and not identifier.startswith(f"{HUB_WEB_ROOT}/models/"): # not a HUB model URL
  69. session.create_model(args)
  70. assert session.model.id, "HUB model not loaded correctly"
  71. return session
  72. # PermissionError and ModuleNotFoundError indicate hub-sdk not installed
  73. except (PermissionError, ModuleNotFoundError, AssertionError):
  74. return None
  75. def load_model(self, model_id):
  76. """Loads an existing model from Ultralytics HUB using the provided model identifier."""
  77. self.model = self.client.model(model_id)
  78. if not self.model.data: # then model does not exist
  79. raise ValueError(emojis("❌ The specified HUB model does not exist")) # TODO: improve error handling
  80. self.model_url = f"{HUB_WEB_ROOT}/models/{self.model.id}"
  81. if self.model.is_trained():
  82. print(emojis(f"Loading trained HUB model {self.model_url} 🚀"))
  83. url = self.model.get_weights_url("best") # download URL with auth
  84. self.model_file = checks.check_file(url, download_dir=Path(SETTINGS["weights_dir"]) / "hub" / self.model.id)
  85. return
  86. # Set training args and start heartbeats for HUB to monitor agent
  87. self._set_train_args()
  88. self.model.start_heartbeat(self.rate_limits["heartbeat"])
  89. LOGGER.info(f"{PREFIX}View model at {self.model_url} 🚀")
  90. def create_model(self, model_args):
  91. """Initializes a HUB training session with the specified model identifier."""
  92. payload = {
  93. "config": {
  94. "batchSize": model_args.get("batch", -1),
  95. "epochs": model_args.get("epochs", 300),
  96. "imageSize": model_args.get("imgsz", 640),
  97. "patience": model_args.get("patience", 100),
  98. "device": str(model_args.get("device", "")), # convert None to string
  99. "cache": str(model_args.get("cache", "ram")), # convert True, False, None to string
  100. },
  101. "dataset": {"name": model_args.get("data")},
  102. "lineage": {
  103. "architecture": {"name": self.filename.replace(".pt", "").replace(".yaml", "")},
  104. "parent": {},
  105. },
  106. "meta": {"name": self.filename},
  107. }
  108. if self.filename.endswith(".pt"):
  109. payload["lineage"]["parent"]["name"] = self.filename
  110. self.model.create_model(payload)
  111. # Model could not be created
  112. # TODO: improve error handling
  113. if not self.model.id:
  114. return None
  115. self.model_url = f"{HUB_WEB_ROOT}/models/{self.model.id}"
  116. # Start heartbeats for HUB to monitor agent
  117. self.model.start_heartbeat(self.rate_limits["heartbeat"])
  118. LOGGER.info(f"{PREFIX}View model at {self.model_url} 🚀")
  119. @staticmethod
  120. def _parse_identifier(identifier):
  121. """
  122. Parses the given identifier to determine the type of identifier and extract relevant components.
  123. The method supports different identifier formats:
  124. - A HUB model URL https://hub.ultralytics.com/models/MODEL
  125. - A HUB model URL with API Key https://hub.ultralytics.com/models/MODEL?api_key=APIKEY
  126. - A local filename that ends with '.pt' or '.yaml'
  127. Args:
  128. identifier (str): The identifier string to be parsed.
  129. Returns:
  130. (tuple): A tuple containing the API key, model ID, and filename as applicable.
  131. Raises:
  132. HUBModelError: If the identifier format is not recognized.
  133. """
  134. api_key, model_id, filename = None, None, None
  135. if Path(identifier).suffix in {".pt", ".yaml"}:
  136. filename = identifier
  137. elif identifier.startswith(f"{HUB_WEB_ROOT}/models/"):
  138. parsed_url = urlparse(identifier)
  139. model_id = Path(parsed_url.path).stem # handle possible final backslash robustly
  140. query_params = parse_qs(parsed_url.query) # dictionary, i.e. {"api_key": ["API_KEY_HERE"]}
  141. api_key = query_params.get("api_key", [None])[0]
  142. else:
  143. raise HUBModelError(f"model='{identifier} invalid, correct format is {HUB_WEB_ROOT}/models/MODEL_ID")
  144. return api_key, model_id, filename
  145. def _set_train_args(self):
  146. """
  147. Initializes training arguments and creates a model entry on the Ultralytics HUB.
  148. This method sets up training arguments based on the model's state and updates them with any additional
  149. arguments provided. It handles different states of the model, such as whether it's resumable, pretrained,
  150. or requires specific file setup.
  151. Raises:
  152. ValueError: If the model is already trained, if required dataset information is missing, or if there are
  153. issues with the provided training arguments.
  154. """
  155. if self.model.is_resumable():
  156. # Model has saved weights
  157. self.train_args = {"data": self.model.get_dataset_url(), "resume": True}
  158. self.model_file = self.model.get_weights_url("last")
  159. else:
  160. # Model has no saved weights
  161. self.train_args = self.model.data.get("train_args") # new response
  162. # Set the model file as either a *.pt or *.yaml file
  163. self.model_file = (
  164. self.model.get_weights_url("parent") if self.model.is_pretrained() else self.model.get_architecture()
  165. )
  166. if "data" not in self.train_args:
  167. # RF bug - datasets are sometimes not exported
  168. raise ValueError("Dataset may still be processing. Please wait a minute and try again.")
  169. self.model_file = checks.check_yolov5u_filename(self.model_file, verbose=False) # YOLOv5->YOLOv5u
  170. self.model_id = self.model.id
  171. def request_queue(
  172. self,
  173. request_func,
  174. retry=3,
  175. timeout=30,
  176. thread=True,
  177. verbose=True,
  178. progress_total=None,
  179. stream_response=None,
  180. *args,
  181. **kwargs,
  182. ):
  183. """Attempts to execute `request_func` with retries, timeout handling, optional threading, and progress."""
  184. def retry_request():
  185. """Attempts to call `request_func` with retries, timeout, and optional threading."""
  186. t0 = time.time() # Record the start time for the timeout
  187. response = None
  188. for i in range(retry + 1):
  189. if (time.time() - t0) > timeout:
  190. LOGGER.warning(f"{PREFIX}Timeout for request reached. {HELP_MSG}")
  191. break # Timeout reached, exit loop
  192. response = request_func(*args, **kwargs)
  193. if response is None:
  194. LOGGER.warning(f"{PREFIX}Received no response from the request. {HELP_MSG}")
  195. time.sleep(2**i) # Exponential backoff before retrying
  196. continue # Skip further processing and retry
  197. if progress_total:
  198. self._show_upload_progress(progress_total, response)
  199. elif stream_response:
  200. self._iterate_content(response)
  201. if HTTPStatus.OK <= response.status_code < HTTPStatus.MULTIPLE_CHOICES:
  202. # if request related to metrics upload
  203. if kwargs.get("metrics"):
  204. self.metrics_upload_failed_queue = {}
  205. return response # Success, no need to retry
  206. if i == 0:
  207. # Initial attempt, check status code and provide messages
  208. message = self._get_failure_message(response, retry, timeout)
  209. if verbose:
  210. LOGGER.warning(f"{PREFIX}{message} {HELP_MSG} ({response.status_code})")
  211. if not self._should_retry(response.status_code):
  212. LOGGER.warning(f"{PREFIX}Request failed. {HELP_MSG} ({response.status_code}")
  213. break # Not an error that should be retried, exit loop
  214. time.sleep(2**i) # Exponential backoff for retries
  215. # if request related to metrics upload and exceed retries
  216. if response is None and kwargs.get("metrics"):
  217. self.metrics_upload_failed_queue.update(kwargs.get("metrics"))
  218. return response
  219. if thread:
  220. # Start a new thread to run the retry_request function
  221. threading.Thread(target=retry_request, daemon=True).start()
  222. else:
  223. # If running in the main thread, call retry_request directly
  224. return retry_request()
  225. @staticmethod
  226. def _should_retry(status_code):
  227. """Determines if a request should be retried based on the HTTP status code."""
  228. retry_codes = {
  229. HTTPStatus.REQUEST_TIMEOUT,
  230. HTTPStatus.BAD_GATEWAY,
  231. HTTPStatus.GATEWAY_TIMEOUT,
  232. }
  233. return status_code in retry_codes
  234. def _get_failure_message(self, response: requests.Response, retry: int, timeout: int):
  235. """
  236. Generate a retry message based on the response status code.
  237. Args:
  238. response: The HTTP response object.
  239. retry: The number of retry attempts allowed.
  240. timeout: The maximum timeout duration.
  241. Returns:
  242. (str): The retry message.
  243. """
  244. if self._should_retry(response.status_code):
  245. return f"Retrying {retry}x for {timeout}s." if retry else ""
  246. elif response.status_code == HTTPStatus.TOO_MANY_REQUESTS: # rate limit
  247. headers = response.headers
  248. return (
  249. f"Rate limit reached ({headers['X-RateLimit-Remaining']}/{headers['X-RateLimit-Limit']}). "
  250. f"Please retry after {headers['Retry-After']}s."
  251. )
  252. else:
  253. try:
  254. return response.json().get("message", "No JSON message.")
  255. except AttributeError:
  256. return "Unable to read JSON."
  257. def upload_metrics(self):
  258. """Upload model metrics to Ultralytics HUB."""
  259. return self.request_queue(self.model.upload_metrics, metrics=self.metrics_queue.copy(), thread=True)
  260. def upload_model(
  261. self,
  262. epoch: int,
  263. weights: str,
  264. is_best: bool = False,
  265. map: float = 0.0,
  266. final: bool = False,
  267. ) -> None:
  268. """
  269. Upload a model checkpoint to Ultralytics HUB.
  270. Args:
  271. epoch (int): The current training epoch.
  272. weights (str): Path to the model weights file.
  273. is_best (bool): Indicates if the current model is the best one so far.
  274. map (float): Mean average precision of the model.
  275. final (bool): Indicates if the model is the final model after training.
  276. """
  277. weights = Path(weights)
  278. if not weights.is_file():
  279. last = weights.with_name(f"last{weights.suffix}")
  280. if final and last.is_file():
  281. LOGGER.warning(
  282. f"{PREFIX} WARNING ⚠️ Model 'best.pt' not found, copying 'last.pt' to 'best.pt' and uploading. "
  283. "This often happens when resuming training in transient environments like Google Colab. "
  284. "For more reliable training, consider using Ultralytics HUB Cloud. "
  285. "Learn more at https://docs.ultralytics.com/hub/cloud-training."
  286. )
  287. shutil.copy(last, weights) # copy last.pt to best.pt
  288. else:
  289. LOGGER.warning(f"{PREFIX} WARNING ⚠️ Model upload issue. Missing model {weights}.")
  290. return
  291. self.request_queue(
  292. self.model.upload_model,
  293. epoch=epoch,
  294. weights=str(weights),
  295. is_best=is_best,
  296. map=map,
  297. final=final,
  298. retry=10,
  299. timeout=3600,
  300. thread=not final,
  301. progress_total=weights.stat().st_size if final else None, # only show progress if final
  302. stream_response=True,
  303. )
  304. @staticmethod
  305. def _show_upload_progress(content_length: int, response: requests.Response) -> None:
  306. """
  307. Display a progress bar to track the upload progress of a file download.
  308. Args:
  309. content_length (int): The total size of the content to be downloaded in bytes.
  310. response (requests.Response): The response object from the file download request.
  311. Returns:
  312. None
  313. """
  314. with TQDM(total=content_length, unit="B", unit_scale=True, unit_divisor=1024) as pbar:
  315. for data in response.iter_content(chunk_size=1024):
  316. pbar.update(len(data))
  317. @staticmethod
  318. def _iterate_content(response: requests.Response) -> None:
  319. """
  320. Process the streamed HTTP response data.
  321. Args:
  322. response (requests.Response): The response object from the file download request.
  323. Returns:
  324. None
  325. """
  326. for _ in response.iter_content(chunk_size=1024):
  327. pass # Do nothing with data chunks