hub.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. # mypy: allow-untyped-defs
  2. import contextlib
  3. import errno
  4. import hashlib
  5. import json
  6. import os
  7. import re
  8. import shutil
  9. import sys
  10. import tempfile
  11. import uuid
  12. import warnings
  13. import zipfile
  14. from pathlib import Path
  15. from typing import Any
  16. from typing_extensions import deprecated
  17. from urllib.error import HTTPError, URLError
  18. from urllib.parse import urlparse # noqa: F401
  19. from urllib.request import Request, urlopen
  20. import torch
  21. from torch.serialization import MAP_LOCATION
  22. class _Faketqdm: # type: ignore[no-redef]
  23. def __init__(self, total=None, disable=False, unit=None, *args, **kwargs):
  24. self.total = total
  25. self.disable = disable
  26. self.n = 0
  27. # Ignore all extra *args and **kwargs lest you want to reinvent tqdm
  28. def update(self, n):
  29. if self.disable:
  30. return
  31. self.n += n
  32. if self.total is None:
  33. sys.stderr.write(f"\r{self.n:.1f} bytes")
  34. else:
  35. sys.stderr.write(f"\r{100 * self.n / float(self.total):.1f}%")
  36. sys.stderr.flush()
  37. # Don't bother implementing; use real tqdm if you want
  38. def set_description(self, *args, **kwargs):
  39. pass
  40. def write(self, s):
  41. sys.stderr.write(f"{s}\n")
  42. def close(self):
  43. self.disable = True
  44. def __enter__(self):
  45. return self
  46. def __exit__(self, exc_type, exc_val, exc_tb):
  47. if self.disable:
  48. return
  49. sys.stderr.write("\n")
  50. try:
  51. from tqdm import tqdm # If tqdm is installed use it, otherwise use the fake wrapper
  52. except ImportError:
  53. tqdm = _Faketqdm
  54. __all__ = [
  55. "download_url_to_file",
  56. "get_dir",
  57. "help",
  58. "list",
  59. "load",
  60. "load_state_dict_from_url",
  61. "set_dir",
  62. ]
  63. # matches bfd8deac from resnet18-bfd8deac.pth
  64. HASH_REGEX = re.compile(r"-([a-f0-9]*)\.")
  65. _PATH_SEP_PATTERN = re.compile(r"[/\\]")
  66. _TRUSTED_REPO_OWNERS = (
  67. "facebookresearch",
  68. "facebookincubator",
  69. "pytorch",
  70. "fairinternal",
  71. )
  72. ENV_GITHUB_TOKEN = "GITHUB_TOKEN"
  73. ENV_TORCH_HOME = "TORCH_HOME"
  74. ENV_XDG_CACHE_HOME = "XDG_CACHE_HOME"
  75. DEFAULT_CACHE_DIR = "~/.cache"
  76. VAR_DEPENDENCY = "dependencies"
  77. MODULE_HUBCONF = "hubconf.py"
  78. READ_DATA_CHUNK = 128 * 1024
  79. _hub_dir: str | None = None
  80. @contextlib.contextmanager
  81. def _add_to_sys_path(path):
  82. sys.path.insert(0, path)
  83. try:
  84. yield
  85. finally:
  86. sys.path.remove(path)
  87. # Copied from tools/shared/module_loader to be included in torch package
  88. def _import_module(name, path):
  89. import importlib.util
  90. from importlib.abc import Loader
  91. spec = importlib.util.spec_from_file_location(name, path)
  92. if spec is None:
  93. raise AssertionError(f"failed to load spec from {path}")
  94. module = importlib.util.module_from_spec(spec)
  95. if not isinstance(spec.loader, Loader):
  96. raise AssertionError(f"expected Loader, got {type(spec.loader)}")
  97. spec.loader.exec_module(module)
  98. return module
  99. def _remove_if_exists(path):
  100. if os.path.exists(path):
  101. if os.path.isfile(path):
  102. os.remove(path)
  103. else:
  104. shutil.rmtree(path)
  105. def _safe_extract_zip(zip_file, extract_to):
  106. """
  107. Safely extract a zip file, preventing zipslip attacks.
  108. Args:
  109. zip_file: ZipFile object to extract
  110. extract_to: Directory to extract to
  111. Raises:
  112. ValueError: If any archive entry contains unsafe paths
  113. """
  114. # Normalize the extraction directory path
  115. extract_to = Path(extract_to).resolve(strict=False)
  116. for member in zip_file.infolist():
  117. # Get the normalized path
  118. filename = os.path.normpath(member.filename)
  119. # Check for directory traversal attempts
  120. if filename.startswith(("/", "\\")):
  121. raise ValueError(f"Archive entry has absolute path: {member.filename}")
  122. if len(filename) >= 2 and filename[1] == ":" and filename[0].isalpha():
  123. raise ValueError(f"Archive entry has absolute path: {member.filename}")
  124. if ".." in re.split(_PATH_SEP_PATTERN, filename):
  125. raise ValueError(
  126. f"Archive entry contains directory traversal: {member.filename}"
  127. )
  128. # Construct the full extraction path and verify it's within extract_to
  129. out = (extract_to / filename).resolve(strict=False)
  130. if not out.is_relative_to(extract_to):
  131. raise ValueError(
  132. f"Archive entry escapes target directory: {member.filename}"
  133. )
  134. # Extract the member safely
  135. zip_file.extract(member, extract_to)
  136. def _git_archive_link(repo_owner, repo_name, ref):
  137. # See https://docs.github.com/en/rest/reference/repos#download-a-repository-archive-zip
  138. return f"https://github.com/{repo_owner}/{repo_name}/zipball/{ref}"
  139. def _load_attr_from_module(module, func_name):
  140. # Check if callable is defined in the module
  141. if func_name not in dir(module):
  142. return None
  143. return getattr(module, func_name)
  144. def _get_torch_home():
  145. torch_home = os.path.expanduser(
  146. os.getenv(
  147. ENV_TORCH_HOME,
  148. os.path.join(os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), "torch"),
  149. )
  150. )
  151. return torch_home
  152. def _parse_repo_info(github):
  153. if ":" in github:
  154. repo_info, ref = github.split(":")
  155. else:
  156. repo_info, ref = github, None
  157. repo_owner, repo_name = repo_info.split("/")
  158. if ref is None:
  159. # The ref wasn't specified by the user, so we need to figure out the
  160. # default branch: main or master. Our assumption is that if main exists
  161. # then it's the default branch, otherwise it's master.
  162. try:
  163. with urlopen(f"https://github.com/{repo_owner}/{repo_name}/tree/main/"):
  164. ref = "main"
  165. except HTTPError as e:
  166. if e.code == 404:
  167. ref = "master"
  168. else:
  169. raise
  170. except URLError as e:
  171. # No internet connection, need to check for cache as last resort
  172. for possible_ref in ("main", "master"):
  173. if os.path.exists(
  174. f"{get_dir()}/{repo_owner}_{repo_name}_{possible_ref}"
  175. ):
  176. ref = possible_ref
  177. break
  178. if ref is None:
  179. raise RuntimeError(
  180. "It looks like there is no internet connection and the "
  181. f"repo could not be found in the cache ({get_dir()})"
  182. ) from e
  183. return repo_owner, repo_name, ref
  184. def _read_url(url):
  185. with urlopen(url) as r:
  186. return r.read().decode(r.headers.get_content_charset("utf-8"))
  187. def _validate_not_a_forked_repo(repo_owner, repo_name, ref):
  188. # Use urlopen to avoid depending on local git.
  189. headers = {"Accept": "application/vnd.github.v3+json"}
  190. token = os.environ.get(ENV_GITHUB_TOKEN)
  191. if token is not None:
  192. headers["Authorization"] = f"token {token}"
  193. for url_prefix in (
  194. f"https://api.github.com/repos/{repo_owner}/{repo_name}/branches",
  195. f"https://api.github.com/repos/{repo_owner}/{repo_name}/tags",
  196. ):
  197. page = 0
  198. while True:
  199. page += 1
  200. url = f"{url_prefix}?per_page=100&page={page}"
  201. try:
  202. response = json.loads(_read_url(Request(url, headers=headers)))
  203. except HTTPError:
  204. # Retry without token in case it had insufficient permissions.
  205. del headers["Authorization"]
  206. response = json.loads(_read_url(Request(url, headers=headers)))
  207. # Empty response means no more data to process
  208. if not response:
  209. break
  210. for br in response:
  211. if br["name"] == ref or br["commit"]["sha"].startswith(ref):
  212. return
  213. raise ValueError(
  214. f"Cannot find {ref} in https://github.com/{repo_owner}/{repo_name}. "
  215. "If it's a commit from a forked repo, please call hub.load() with forked repo directly."
  216. )
  217. def _get_cache_or_reload(
  218. github,
  219. force_reload,
  220. trust_repo,
  221. verbose=True,
  222. skip_validation=False,
  223. ):
  224. # Setup hub_dir to save downloaded files
  225. hub_dir = get_dir()
  226. os.makedirs(hub_dir, exist_ok=True)
  227. # Parse github repo information
  228. repo_owner, repo_name, ref = _parse_repo_info(github)
  229. # Github allows branch name with slash '/',
  230. # this causes confusion with path on both Linux and Windows.
  231. # Backslash is not allowed in Github branch name so no need to
  232. # to worry about it.
  233. normalized_br = ref.replace("/", "_")
  234. # Github renames folder repo-v1.x.x to repo-1.x.x
  235. # We don't know the repo name before downloading the zip file
  236. # and inspect name from it.
  237. # To check if cached repo exists, we need to normalize folder names.
  238. owner_name_branch = "_".join([repo_owner, repo_name, normalized_br])
  239. repo_dir = os.path.join(hub_dir, owner_name_branch)
  240. # Check that the repo is in the trusted list
  241. _check_repo_is_trusted(
  242. repo_owner,
  243. repo_name,
  244. owner_name_branch,
  245. trust_repo=trust_repo,
  246. )
  247. use_cache = (not force_reload) and os.path.exists(repo_dir)
  248. if use_cache:
  249. if verbose:
  250. sys.stderr.write(f"Using cache found in {repo_dir}\n")
  251. else:
  252. # Validate the tag/branch is from the original repo instead of a forked repo
  253. if not skip_validation:
  254. _validate_not_a_forked_repo(repo_owner, repo_name, ref)
  255. cached_file = os.path.join(hub_dir, normalized_br + ".zip")
  256. _remove_if_exists(cached_file)
  257. try:
  258. url = _git_archive_link(repo_owner, repo_name, ref)
  259. sys.stdout.write(f'Downloading: "{url}" to {cached_file}\n')
  260. download_url_to_file(url, cached_file, progress=False)
  261. except HTTPError as err:
  262. if err.code == 300:
  263. # Getting a 300 Multiple Choices error likely means that the ref is both a tag and a branch
  264. # in the repo. This can be disambiguated by explicitly using refs/heads/ or refs/tags
  265. # See https://git-scm.com/book/en/v2/Git-Internals-Git-References
  266. # Here, we do the same as git: we throw a warning, and assume the user wanted the branch
  267. warnings.warn(
  268. f"The ref {ref} is ambiguous. Perhaps it is both a tag and a branch in the repo? "
  269. "Torchhub will now assume that it's a branch. "
  270. "You can disambiguate tags and branches by explicitly passing refs/heads/branch_name or "
  271. "refs/tags/tag_name as the ref. That might require using skip_validation=True.",
  272. stacklevel=2,
  273. )
  274. disambiguated_branch_ref = f"refs/heads/{ref}"
  275. url = _git_archive_link(
  276. repo_owner, repo_name, ref=disambiguated_branch_ref
  277. )
  278. download_url_to_file(url, cached_file, progress=False)
  279. else:
  280. raise
  281. with zipfile.ZipFile(cached_file) as cached_zipfile:
  282. extraced_repo_name = cached_zipfile.infolist()[0].filename
  283. extracted_repo = os.path.join(hub_dir, extraced_repo_name)
  284. _remove_if_exists(extracted_repo)
  285. # Unzip the code and rename the base folder using safe extraction
  286. _safe_extract_zip(cached_zipfile, hub_dir)
  287. _remove_if_exists(cached_file)
  288. _remove_if_exists(repo_dir)
  289. shutil.move(extracted_repo, repo_dir) # rename the repo
  290. return repo_dir
  291. def _check_repo_is_trusted(
  292. repo_owner,
  293. repo_name,
  294. owner_name_branch,
  295. trust_repo,
  296. ):
  297. hub_dir = get_dir()
  298. filepath = os.path.join(hub_dir, "trusted_list")
  299. if not os.path.exists(filepath):
  300. Path(filepath).touch()
  301. with open(filepath) as file:
  302. trusted_repos = tuple(line.strip() for line in file)
  303. # To minimize friction of introducing the new trust_repo mechanism, we consider that
  304. # if a repo was already downloaded by torchhub, then it is already trusted (even if it's not in the allowlist)
  305. trusted_repos_legacy = next(os.walk(hub_dir))[1]
  306. owner_name = "_".join([repo_owner, repo_name])
  307. is_trusted = (
  308. owner_name in trusted_repos
  309. or owner_name_branch in trusted_repos_legacy
  310. or repo_owner in _TRUSTED_REPO_OWNERS
  311. )
  312. if (trust_repo is False) or (trust_repo == "check" and not is_trusted):
  313. response = input(
  314. f"The repository {owner_name} does not belong to the list of trusted repositories and as such cannot be downloaded. "
  315. "Do you trust this repository and wish to add it to the trusted list of repositories (y/N)?"
  316. )
  317. if response.lower() in ("y", "yes"):
  318. if is_trusted:
  319. print("The repository is already trusted.")
  320. elif response.lower() in ("n", "no", ""):
  321. raise Exception("Untrusted repository.") # noqa: TRY002
  322. else:
  323. raise ValueError(f"Unrecognized response {response}.")
  324. # At this point we're sure that the user trusts the repo (or wants to trust it)
  325. if not is_trusted:
  326. with open(filepath, "a") as file:
  327. file.write(owner_name + "\n")
  328. def _check_module_exists(name):
  329. import importlib.util
  330. return importlib.util.find_spec(name) is not None
  331. def _check_dependencies(m):
  332. dependencies = _load_attr_from_module(m, VAR_DEPENDENCY)
  333. if dependencies is not None:
  334. missing_deps = [pkg for pkg in dependencies if not _check_module_exists(pkg)]
  335. if missing_deps:
  336. raise RuntimeError(f"Missing dependencies: {', '.join(missing_deps)}")
  337. def _load_entry_from_hubconf(m, model):
  338. if not isinstance(model, str):
  339. raise ValueError("Invalid input: model should be a string of function name")
  340. # Note that if a missing dependency is imported at top level of hubconf, it will
  341. # throw before this function. It's a chicken and egg situation where we have to
  342. # load hubconf to know what're the dependencies, but to import hubconf it requires
  343. # a missing package. This is fine, Python will throw proper error message for users.
  344. _check_dependencies(m)
  345. func = _load_attr_from_module(m, model)
  346. if func is None or not callable(func):
  347. raise RuntimeError(f"Cannot find callable {model} in hubconf")
  348. return func
  349. def get_dir() -> str:
  350. r"""
  351. Get the Torch Hub cache directory used for storing downloaded models & weights.
  352. If :func:`~torch.hub.set_dir` is not called, default path is ``$TORCH_HOME/hub`` where
  353. environment variable ``$TORCH_HOME`` defaults to ``$XDG_CACHE_HOME/torch``.
  354. ``$XDG_CACHE_HOME`` follows the X Design Group specification of the Linux
  355. filesystem layout, with a default value ``~/.cache`` if the environment
  356. variable is not set.
  357. """
  358. # Issue warning to move data if old env is set
  359. if os.getenv("TORCH_HUB"):
  360. warnings.warn(
  361. "TORCH_HUB is deprecated, please use env TORCH_HOME instead", stacklevel=2
  362. )
  363. if _hub_dir is not None:
  364. return _hub_dir
  365. return os.path.join(_get_torch_home(), "hub")
  366. def set_dir(d: str | os.PathLike) -> None:
  367. r"""
  368. Optionally set the Torch Hub directory used to save downloaded models & weights.
  369. Args:
  370. d (str): path to a local folder to save downloaded models & weights.
  371. """
  372. global _hub_dir
  373. _hub_dir = os.path.expanduser(d)
  374. def list(
  375. github,
  376. force_reload=False,
  377. skip_validation=False,
  378. trust_repo="check",
  379. verbose=True,
  380. ):
  381. r"""
  382. List all callable entrypoints available in the repo specified by ``github``.
  383. Args:
  384. github (str): a string with format "repo_owner/repo_name[:ref]" with an optional
  385. ref (tag or branch). If ``ref`` is not specified, the default branch is assumed to be ``main`` if
  386. it exists, and otherwise ``master``.
  387. Example: 'pytorch/vision:0.10'
  388. force_reload (bool, optional): whether to discard the existing cache and force a fresh download.
  389. Default is ``False``.
  390. skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit
  391. specified by the ``github`` argument properly belongs to the repo owner. This will make
  392. requests to the GitHub API; you can specify a non-default GitHub token by setting the
  393. ``GITHUB_TOKEN`` environment variable. Default is ``False``.
  394. trust_repo (bool or str): ``"check"``, ``True`` or ``False``.
  395. This parameter was introduced in v1.12 and helps ensuring that users
  396. only run code from repos that they trust.
  397. - If ``False``, a prompt will ask the user whether the repo should
  398. be trusted.
  399. - If ``True``, the repo will be added to the trusted list and loaded
  400. without requiring explicit confirmation.
  401. - If ``"check"``, the repo will be checked against the list of
  402. trusted repos in the cache. If it is not present in that list, the
  403. behaviour will fall back onto the ``trust_repo=False`` option.
  404. Default is ``"check"``.
  405. verbose (bool, optional): If ``False``, mute messages about hitting
  406. local caches. Note that the message about first download cannot be
  407. muted. Default is ``True``.
  408. Returns:
  409. list: The available callables entrypoint
  410. Example:
  411. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
  412. >>> entrypoints = torch.hub.list("pytorch/vision", force_reload=True)
  413. """
  414. repo_dir = _get_cache_or_reload(
  415. github,
  416. force_reload,
  417. trust_repo,
  418. verbose=verbose,
  419. skip_validation=skip_validation,
  420. )
  421. with _add_to_sys_path(repo_dir):
  422. hubconf_path = os.path.join(repo_dir, MODULE_HUBCONF)
  423. hub_module = _import_module(MODULE_HUBCONF, hubconf_path)
  424. # We take functions starts with '_' as internal helper functions
  425. entrypoints = [
  426. f
  427. for f in dir(hub_module)
  428. if callable(getattr(hub_module, f)) and not f.startswith("_")
  429. ]
  430. return entrypoints
  431. def help(github, model, force_reload=False, skip_validation=False, trust_repo="check"):
  432. r"""
  433. Show the docstring of entrypoint ``model``.
  434. Args:
  435. github (str): a string with format <repo_owner/repo_name[:ref]> with an optional
  436. ref (a tag or a branch). If ``ref`` is not specified, the default branch is assumed
  437. to be ``main`` if it exists, and otherwise ``master``.
  438. Example: 'pytorch/vision:0.10'
  439. model (str): a string of entrypoint name defined in repo's ``hubconf.py``
  440. force_reload (bool, optional): whether to discard the existing cache and force a fresh download.
  441. Default is ``False``.
  442. skip_validation (bool, optional): if ``False``, torchhub will check that the ref
  443. specified by the ``github`` argument properly belongs to the repo owner. This will make
  444. requests to the GitHub API; you can specify a non-default GitHub token by setting the
  445. ``GITHUB_TOKEN`` environment variable. Default is ``False``.
  446. trust_repo (bool or str): ``"check"``, ``True`` or ``False``.
  447. This parameter was introduced in v1.12 and helps ensuring that users
  448. only run code from repos that they trust.
  449. - If ``False``, a prompt will ask the user whether the repo should
  450. be trusted.
  451. - If ``True``, the repo will be added to the trusted list and loaded
  452. without requiring explicit confirmation.
  453. - If ``"check"``, the repo will be checked against the list of
  454. trusted repos in the cache. If it is not present in that list, the
  455. behaviour will fall back onto the ``trust_repo=False`` option.
  456. Default is ``"check"``.
  457. Example:
  458. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
  459. >>> print(torch.hub.help("pytorch/vision", "resnet18", force_reload=True))
  460. """
  461. repo_dir = _get_cache_or_reload(
  462. github,
  463. force_reload,
  464. trust_repo,
  465. verbose=True,
  466. skip_validation=skip_validation,
  467. )
  468. with _add_to_sys_path(repo_dir):
  469. hubconf_path = os.path.join(repo_dir, MODULE_HUBCONF)
  470. hub_module = _import_module(MODULE_HUBCONF, hubconf_path)
  471. entry = _load_entry_from_hubconf(hub_module, model)
  472. return entry.__doc__
  473. def load(
  474. repo_or_dir,
  475. model,
  476. *args,
  477. source="github",
  478. trust_repo="check",
  479. force_reload=False,
  480. verbose=True,
  481. skip_validation=False,
  482. **kwargs,
  483. ):
  484. r"""
  485. Load a model from a github repo or a local directory.
  486. Note: Loading a model is the typical use case, but this can also be used to
  487. for loading other objects such as tokenizers, loss functions, etc.
  488. If ``source`` is 'github', ``repo_or_dir`` is expected to be
  489. of the form ``repo_owner/repo_name[:ref]`` with an optional
  490. ref (a tag or a branch).
  491. If ``source`` is 'local', ``repo_or_dir`` is expected to be a
  492. path to a local directory.
  493. Args:
  494. repo_or_dir (str): If ``source`` is 'github',
  495. this should correspond to a github repo with format ``repo_owner/repo_name[:ref]`` with
  496. an optional ref (tag or branch), for example 'pytorch/vision:0.10'. If ``ref`` is not specified,
  497. the default branch is assumed to be ``main`` if it exists, and otherwise ``master``.
  498. If ``source`` is 'local' then it should be a path to a local directory.
  499. model (str): the name of a callable (entrypoint) defined in the
  500. repo/dir's ``hubconf.py``.
  501. *args (optional): the corresponding args for callable ``model``.
  502. source (str, optional): 'github' or 'local'. Specifies how
  503. ``repo_or_dir`` is to be interpreted. Default is 'github'.
  504. trust_repo (bool or str): ``"check"``, ``True`` or ``False``.
  505. This parameter was introduced in v1.12 and helps ensuring that users
  506. only run code from repos that they trust.
  507. - If ``False``, a prompt will ask the user whether the repo should
  508. be trusted.
  509. - If ``True``, the repo will be added to the trusted list and loaded
  510. without requiring explicit confirmation.
  511. - If ``"check"``, the repo will be checked against the list of
  512. trusted repos in the cache. If it is not present in that list, the
  513. behaviour will fall back onto the ``trust_repo=False`` option.
  514. Default is ``"check"``.
  515. force_reload (bool, optional): whether to force a fresh download of
  516. the github repo unconditionally. Does not have any effect if
  517. ``source = 'local'``. Default is ``False``.
  518. verbose (bool, optional): If ``False``, mute messages about hitting
  519. local caches. Note that the message about first download cannot be
  520. muted. Does not have any effect if ``source = 'local'``.
  521. Default is ``True``.
  522. skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit
  523. specified by the ``github`` argument properly belongs to the repo owner. This will make
  524. requests to the GitHub API; you can specify a non-default GitHub token by setting the
  525. ``GITHUB_TOKEN`` environment variable. Default is ``False``.
  526. **kwargs (optional): the corresponding kwargs for callable ``model``.
  527. Returns:
  528. The output of the ``model`` callable when called with the given
  529. ``*args`` and ``**kwargs``.
  530. Example:
  531. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
  532. >>> # from a github repo
  533. >>> repo = "pytorch/vision"
  534. >>> model = torch.hub.load(
  535. ... repo, "resnet50", weights="ResNet50_Weights.IMAGENET1K_V1"
  536. ... )
  537. >>> # from a local directory
  538. >>> path = "/some/local/path/pytorch/vision"
  539. >>> # xdoctest: +SKIP
  540. >>> model = torch.hub.load(path, "resnet50", weights="ResNet50_Weights.DEFAULT")
  541. """
  542. source = source.lower()
  543. if source not in ("github", "local"):
  544. raise ValueError(
  545. f'Unknown source: "{source}". Allowed values: "github" | "local".'
  546. )
  547. if source == "github":
  548. repo_or_dir = _get_cache_or_reload(
  549. repo_or_dir,
  550. force_reload,
  551. trust_repo,
  552. verbose=verbose,
  553. skip_validation=skip_validation,
  554. )
  555. model = _load_local(repo_or_dir, model, *args, **kwargs)
  556. return model
  557. def _load_local(hubconf_dir, model, *args, **kwargs):
  558. r"""
  559. Load a model from a local directory with a ``hubconf.py``.
  560. Args:
  561. hubconf_dir (str): path to a local directory that contains a
  562. ``hubconf.py``.
  563. model (str): name of an entrypoint defined in the directory's
  564. ``hubconf.py``.
  565. *args (optional): the corresponding args for callable ``model``.
  566. **kwargs (optional): the corresponding kwargs for callable ``model``.
  567. Returns:
  568. a single model with corresponding pretrained weights.
  569. Example:
  570. >>> # xdoctest: +SKIP("stub local path")
  571. >>> path = "/some/local/path/pytorch/vision"
  572. >>> model = _load_local(
  573. ... path,
  574. ... "resnet50",
  575. ... weights="ResNet50_Weights.IMAGENET1K_V1",
  576. ... )
  577. """
  578. with _add_to_sys_path(hubconf_dir):
  579. hubconf_path = os.path.join(hubconf_dir, MODULE_HUBCONF)
  580. hub_module = _import_module(MODULE_HUBCONF, hubconf_path)
  581. entry = _load_entry_from_hubconf(hub_module, model)
  582. model = entry(*args, **kwargs)
  583. return model
  584. def download_url_to_file(
  585. url: str,
  586. dst: str,
  587. hash_prefix: str | None = None,
  588. progress: bool = True,
  589. ) -> None:
  590. r"""Download object at the given URL to a local path.
  591. Args:
  592. url (str): URL of the object to download
  593. dst (str): Full path where object will be saved, e.g. ``/tmp/temporary_file``
  594. hash_prefix (str, optional): If not None, the SHA256 downloaded file should start with ``hash_prefix``.
  595. Default: None
  596. progress (bool, optional): whether or not to display a progress bar to stderr
  597. Default: True
  598. Example:
  599. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
  600. >>> # xdoctest: +REQUIRES(POSIX)
  601. >>> torch.hub.download_url_to_file(
  602. ... "https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth",
  603. ... "/tmp/temporary_file",
  604. ... )
  605. """
  606. # We deliberately save it in a temp file and move it after
  607. # download is complete. This prevents a local working checkpoint
  608. # being overridden by a broken download.
  609. # We deliberately do not use NamedTemporaryFile to avoid restrictive
  610. # file permissions being applied to the downloaded file.
  611. dst = os.path.expanduser(dst)
  612. for _ in range(tempfile.TMP_MAX):
  613. tmp_dst = dst + "." + uuid.uuid4().hex + ".partial"
  614. try:
  615. f = open(tmp_dst, "w+b") # noqa: SIM115
  616. except FileExistsError:
  617. continue
  618. break
  619. else:
  620. raise FileExistsError(errno.EEXIST, "No usable temporary file name found")
  621. req = Request(url, headers={"User-Agent": "torch.hub"})
  622. try:
  623. with urlopen(req) as u:
  624. meta = u.info()
  625. if hasattr(meta, "getheaders"):
  626. content_length = meta.getheaders("Content-Length")
  627. else:
  628. content_length = meta.get_all("Content-Length")
  629. file_size = None
  630. if content_length is not None and len(content_length) > 0:
  631. file_size = int(content_length[0])
  632. sha256 = hashlib.sha256() if hash_prefix is not None else None
  633. with tqdm(
  634. total=file_size,
  635. disable=not progress,
  636. unit="B",
  637. unit_scale=True,
  638. unit_divisor=1024,
  639. ) as pbar:
  640. while True:
  641. buffer = u.read(READ_DATA_CHUNK)
  642. if len(buffer) == 0:
  643. break
  644. f.write(buffer)
  645. if sha256 is not None:
  646. sha256.update(buffer)
  647. pbar.update(len(buffer))
  648. f.close()
  649. if sha256 is not None and hash_prefix is not None:
  650. digest = sha256.hexdigest()
  651. if digest[: len(hash_prefix)] != hash_prefix:
  652. raise RuntimeError(
  653. f'invalid hash value (expected "{hash_prefix}", got "{digest}")'
  654. )
  655. shutil.move(f.name, dst)
  656. finally:
  657. f.close()
  658. if os.path.exists(f.name):
  659. os.remove(f.name)
  660. # Hub used to support automatically extracts from zipfile manually compressed by users.
  661. # The legacy zip format expects only one file from torch.save() < 1.6 in the zip.
  662. # We should remove this support since zipfile is now default zipfile format for torch.save().
  663. def _is_legacy_zip_format(filename: str) -> bool:
  664. if zipfile.is_zipfile(filename):
  665. with zipfile.ZipFile(filename) as zf:
  666. infolist = zf.infolist()
  667. return len(infolist) == 1 and not infolist[0].is_dir()
  668. return False
  669. @deprecated(
  670. "Falling back to the old format < 1.6. This support will be "
  671. "deprecated in favor of default zipfile format introduced in 1.6. "
  672. "Please redo torch.save() to save it in the new zipfile format.",
  673. category=FutureWarning,
  674. )
  675. def _legacy_zip_load(
  676. filename: str,
  677. model_dir: str,
  678. map_location: MAP_LOCATION,
  679. weights_only: bool,
  680. ) -> dict[str, Any]:
  681. # Note: extractall() defaults to overwrite file if exists. No need to clean up beforehand.
  682. # We deliberately don't handle tarfile here since our legacy serialization format was in tar.
  683. # E.g. resnet18-5c106cde.pth which is widely used.
  684. with zipfile.ZipFile(filename) as f:
  685. members = f.infolist()
  686. if len(members) != 1:
  687. raise RuntimeError("Only one file(not dir) is allowed in the zipfile")
  688. # Use safe extraction to prevent zipslip attacks
  689. _safe_extract_zip(f, model_dir)
  690. extraced_name = members[0].filename
  691. extracted_file = os.path.join(model_dir, extraced_name)
  692. return torch.load(
  693. extracted_file, map_location=map_location, weights_only=weights_only
  694. )
  695. def load_state_dict_from_url(
  696. url: str,
  697. model_dir: str | None = None,
  698. map_location: MAP_LOCATION = None,
  699. progress: bool = True,
  700. check_hash: bool = False,
  701. file_name: str | None = None,
  702. weights_only: bool = False,
  703. ) -> dict[str, Any]:
  704. r"""Loads the Torch serialized object at the given URL.
  705. If downloaded file is a zip file, it will be automatically
  706. decompressed.
  707. If the object is already present in `model_dir`, it's deserialized and
  708. returned.
  709. The default value of ``model_dir`` is ``<hub_dir>/checkpoints`` where
  710. ``hub_dir`` is the directory returned by :func:`~torch.hub.get_dir`.
  711. Args:
  712. url (str): URL of the object to download
  713. model_dir (str, optional): directory in which to save the object
  714. map_location (optional): a function or a dict specifying how to remap storage locations (see torch.load)
  715. progress (bool, optional): whether or not to display a progress bar to stderr.
  716. Default: True
  717. check_hash(bool, optional): If True, the filename part of the URL should follow the naming convention
  718. ``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more
  719. digits of the SHA256 hash of the contents of the file. The hash is used to
  720. ensure unique names and to verify the contents of the file.
  721. Default: False
  722. file_name (str, optional): name for the downloaded file. Filename from ``url`` will be used if not set.
  723. weights_only(bool, optional): If True, only weights will be loaded and no complex pickled objects.
  724. Recommended for untrusted sources. See :func:`~torch.load` for more details.
  725. Example:
  726. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
  727. >>> state_dict = torch.hub.load_state_dict_from_url(
  728. ... "https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth"
  729. ... )
  730. """
  731. # Issue warning to move data if old env is set
  732. if os.getenv("TORCH_MODEL_ZOO"):
  733. warnings.warn(
  734. "TORCH_MODEL_ZOO is deprecated, please use env TORCH_HOME instead",
  735. stacklevel=2,
  736. )
  737. if model_dir is None:
  738. hub_dir = get_dir()
  739. model_dir = os.path.join(hub_dir, "checkpoints")
  740. os.makedirs(model_dir, exist_ok=True)
  741. parts = urlparse(url)
  742. filename = os.path.basename(parts.path)
  743. if file_name is not None:
  744. filename = file_name
  745. cached_file = os.path.join(model_dir, filename)
  746. if not os.path.exists(cached_file):
  747. sys.stdout.write(f'Downloading: "{url}" to {cached_file}\n')
  748. hash_prefix = None
  749. if check_hash:
  750. r = HASH_REGEX.search(filename) # r is Optional[Match[str]]
  751. hash_prefix = r.group(1) if r else None
  752. download_url_to_file(url, cached_file, hash_prefix, progress=progress)
  753. if _is_legacy_zip_format(cached_file):
  754. return _legacy_zip_load(cached_file, model_dir, map_location, weights_only)
  755. return torch.load(cached_file, map_location=map_location, weights_only=weights_only)