hub.py 33 KB

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