hub.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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. _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: str | None = 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. stacklevel=2,
  241. )
  242. disambiguated_branch_ref = f"refs/heads/{ref}"
  243. url = _git_archive_link(
  244. repo_owner, repo_name, ref=disambiguated_branch_ref
  245. )
  246. download_url_to_file(url, cached_file, progress=False)
  247. else:
  248. raise
  249. with zipfile.ZipFile(cached_file) as cached_zipfile:
  250. extraced_repo_name = cached_zipfile.infolist()[0].filename
  251. extracted_repo = os.path.join(hub_dir, extraced_repo_name)
  252. _remove_if_exists(extracted_repo)
  253. # Unzip the code and rename the base folder
  254. cached_zipfile.extractall(hub_dir)
  255. _remove_if_exists(cached_file)
  256. _remove_if_exists(repo_dir)
  257. shutil.move(extracted_repo, repo_dir) # rename the repo
  258. return repo_dir
  259. def _check_repo_is_trusted(
  260. repo_owner,
  261. repo_name,
  262. owner_name_branch,
  263. trust_repo,
  264. calling_fn="load",
  265. ):
  266. hub_dir = get_dir()
  267. filepath = os.path.join(hub_dir, "trusted_list")
  268. if not os.path.exists(filepath):
  269. Path(filepath).touch()
  270. with open(filepath) as file:
  271. trusted_repos = tuple(line.strip() for line in file)
  272. # To minimize friction of introducing the new trust_repo mechanism, we consider that
  273. # if a repo was already downloaded by torchhub, then it is already trusted (even if it's not in the allowlist)
  274. trusted_repos_legacy = next(os.walk(hub_dir))[1]
  275. owner_name = "_".join([repo_owner, repo_name])
  276. is_trusted = (
  277. owner_name in trusted_repos
  278. or owner_name_branch in trusted_repos_legacy
  279. or repo_owner in _TRUSTED_REPO_OWNERS
  280. )
  281. # TODO: Remove `None` option in 2.0 and change the default to "check"
  282. if trust_repo is None:
  283. if not is_trusted:
  284. warnings.warn(
  285. "You are about to download and run code from an untrusted repository. In a future release, this won't "
  286. f"be allowed. To add the repository to your trusted list, change the command to {calling_fn}(..., "
  287. "trust_repo=False) and a command prompt will appear asking for an explicit confirmation of trust, "
  288. f"or {calling_fn}(..., trust_repo=True), which will assume that the prompt is to be answered with "
  289. f"'yes'. You can also use {calling_fn}(..., trust_repo='check') which will only prompt for "
  290. f"confirmation if the repo is not already trusted. This will eventually be the default behaviour",
  291. stacklevel=2,
  292. )
  293. return
  294. if (trust_repo is False) or (trust_repo == "check" and not is_trusted):
  295. response = input(
  296. f"The repository {owner_name} does not belong to the list of trusted repositories and as such cannot be downloaded. "
  297. "Do you trust this repository and wish to add it to the trusted list of repositories (y/N)?"
  298. )
  299. if response.lower() in ("y", "yes"):
  300. if is_trusted:
  301. print("The repository is already trusted.")
  302. elif response.lower() in ("n", "no", ""):
  303. raise Exception("Untrusted repository.") # noqa: TRY002
  304. else:
  305. raise ValueError(f"Unrecognized response {response}.")
  306. # At this point we're sure that the user trusts the repo (or wants to trust it)
  307. if not is_trusted:
  308. with open(filepath, "a") as file:
  309. file.write(owner_name + "\n")
  310. def _check_module_exists(name):
  311. import importlib.util
  312. return importlib.util.find_spec(name) is not None
  313. def _check_dependencies(m):
  314. dependencies = _load_attr_from_module(m, VAR_DEPENDENCY)
  315. if dependencies is not None:
  316. missing_deps = [pkg for pkg in dependencies if not _check_module_exists(pkg)]
  317. if missing_deps:
  318. raise RuntimeError(f"Missing dependencies: {', '.join(missing_deps)}")
  319. def _load_entry_from_hubconf(m, model):
  320. if not isinstance(model, str):
  321. raise ValueError("Invalid input: model should be a string of function name")
  322. # Note that if a missing dependency is imported at top level of hubconf, it will
  323. # throw before this function. It's a chicken and egg situation where we have to
  324. # load hubconf to know what're the dependencies, but to import hubconf it requires
  325. # a missing package. This is fine, Python will throw proper error message for users.
  326. _check_dependencies(m)
  327. func = _load_attr_from_module(m, model)
  328. if func is None or not callable(func):
  329. raise RuntimeError(f"Cannot find callable {model} in hubconf")
  330. return func
  331. def get_dir() -> str:
  332. r"""
  333. Get the Torch Hub cache directory used for storing downloaded models & weights.
  334. If :func:`~torch.hub.set_dir` is not called, default path is ``$TORCH_HOME/hub`` where
  335. environment variable ``$TORCH_HOME`` defaults to ``$XDG_CACHE_HOME/torch``.
  336. ``$XDG_CACHE_HOME`` follows the X Design Group specification of the Linux
  337. filesystem layout, with a default value ``~/.cache`` if the environment
  338. variable is not set.
  339. """
  340. # Issue warning to move data if old env is set
  341. if os.getenv("TORCH_HUB"):
  342. warnings.warn(
  343. "TORCH_HUB is deprecated, please use env TORCH_HOME instead", stacklevel=2
  344. )
  345. if _hub_dir is not None:
  346. return _hub_dir
  347. return os.path.join(_get_torch_home(), "hub")
  348. def set_dir(d: str | os.PathLike) -> None:
  349. r"""
  350. Optionally set the Torch Hub directory used to save downloaded models & weights.
  351. Args:
  352. d (str): path to a local folder to save downloaded models & weights.
  353. """
  354. global _hub_dir
  355. _hub_dir = os.path.expanduser(d)
  356. def list(
  357. github,
  358. force_reload=False,
  359. skip_validation=False,
  360. trust_repo=None,
  361. verbose=True,
  362. ):
  363. r"""
  364. List all callable entrypoints available in the repo specified by ``github``.
  365. Args:
  366. github (str): a string with format "repo_owner/repo_name[:ref]" with an optional
  367. ref (tag or branch). If ``ref`` is not specified, the default branch is assumed to be ``main`` if
  368. it exists, and otherwise ``master``.
  369. Example: 'pytorch/vision:0.10'
  370. force_reload (bool, optional): whether to discard the existing cache and force a fresh download.
  371. Default is ``False``.
  372. skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit
  373. specified by the ``github`` argument properly belongs to the repo owner. This will make
  374. requests to the GitHub API; you can specify a non-default GitHub token by setting the
  375. ``GITHUB_TOKEN`` environment variable. Default is ``False``.
  376. trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``.
  377. This parameter was introduced in v1.12 and helps ensuring that users
  378. only run code from repos that they trust.
  379. - If ``False``, a prompt will ask the user whether the repo should
  380. be trusted.
  381. - If ``True``, the repo will be added to the trusted list and loaded
  382. without requiring explicit confirmation.
  383. - If ``"check"``, the repo will be checked against the list of
  384. trusted repos in the cache. If it is not present in that list, the
  385. behaviour will fall back onto the ``trust_repo=False`` option.
  386. - If ``None``: this will raise a warning, inviting the user to set
  387. ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This
  388. is only present for backward compatibility and will be removed in
  389. v2.0.
  390. Default is ``None`` and will eventually change to ``"check"`` in v2.0.
  391. verbose (bool, optional): If ``False``, mute messages about hitting
  392. local caches. Note that the message about first download cannot be
  393. muted. Default is ``True``.
  394. Returns:
  395. list: The available callables entrypoint
  396. Example:
  397. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
  398. >>> entrypoints = torch.hub.list("pytorch/vision", force_reload=True)
  399. """
  400. repo_dir = _get_cache_or_reload(
  401. github,
  402. force_reload,
  403. trust_repo,
  404. "list",
  405. verbose=verbose,
  406. skip_validation=skip_validation,
  407. )
  408. with _add_to_sys_path(repo_dir):
  409. hubconf_path = os.path.join(repo_dir, MODULE_HUBCONF)
  410. hub_module = _import_module(MODULE_HUBCONF, hubconf_path)
  411. # We take functions starts with '_' as internal helper functions
  412. entrypoints = [
  413. f
  414. for f in dir(hub_module)
  415. if callable(getattr(hub_module, f)) and not f.startswith("_")
  416. ]
  417. return entrypoints
  418. def help(github, model, force_reload=False, skip_validation=False, trust_repo=None):
  419. r"""
  420. Show the docstring of entrypoint ``model``.
  421. Args:
  422. github (str): a string with format <repo_owner/repo_name[:ref]> with an optional
  423. ref (a tag or a branch). If ``ref`` is not specified, the default branch is assumed
  424. to be ``main`` if it exists, and otherwise ``master``.
  425. Example: 'pytorch/vision:0.10'
  426. model (str): a string of entrypoint name defined in repo's ``hubconf.py``
  427. force_reload (bool, optional): whether to discard the existing cache and force a fresh download.
  428. Default is ``False``.
  429. skip_validation (bool, optional): if ``False``, torchhub will check that the ref
  430. specified by the ``github`` argument properly belongs to the repo owner. This will make
  431. requests to the GitHub API; you can specify a non-default GitHub token by setting the
  432. ``GITHUB_TOKEN`` environment variable. Default is ``False``.
  433. trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``.
  434. This parameter was introduced in v1.12 and helps ensuring that users
  435. only run code from repos that they trust.
  436. - If ``False``, a prompt will ask the user whether the repo should
  437. be trusted.
  438. - If ``True``, the repo will be added to the trusted list and loaded
  439. without requiring explicit confirmation.
  440. - If ``"check"``, the repo will be checked against the list of
  441. trusted repos in the cache. If it is not present in that list, the
  442. behaviour will fall back onto the ``trust_repo=False`` option.
  443. - If ``None``: this will raise a warning, inviting the user to set
  444. ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This
  445. is only present for backward compatibility and will be removed in
  446. v2.0.
  447. Default is ``None`` and will eventually change to ``"check"`` in v2.0.
  448. Example:
  449. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
  450. >>> print(torch.hub.help("pytorch/vision", "resnet18", force_reload=True))
  451. """
  452. repo_dir = _get_cache_or_reload(
  453. github,
  454. force_reload,
  455. trust_repo,
  456. "help",
  457. verbose=True,
  458. skip_validation=skip_validation,
  459. )
  460. with _add_to_sys_path(repo_dir):
  461. hubconf_path = os.path.join(repo_dir, MODULE_HUBCONF)
  462. hub_module = _import_module(MODULE_HUBCONF, hubconf_path)
  463. entry = _load_entry_from_hubconf(hub_module, model)
  464. return entry.__doc__
  465. def load(
  466. repo_or_dir,
  467. model,
  468. *args,
  469. source="github",
  470. trust_repo=None,
  471. force_reload=False,
  472. verbose=True,
  473. skip_validation=False,
  474. **kwargs,
  475. ):
  476. r"""
  477. Load a model from a github repo or a local directory.
  478. Note: Loading a model is the typical use case, but this can also be used to
  479. for loading other objects such as tokenizers, loss functions, etc.
  480. If ``source`` is 'github', ``repo_or_dir`` is expected to be
  481. of the form ``repo_owner/repo_name[:ref]`` with an optional
  482. ref (a tag or a branch).
  483. If ``source`` is 'local', ``repo_or_dir`` is expected to be a
  484. path to a local directory.
  485. Args:
  486. repo_or_dir (str): If ``source`` is 'github',
  487. this should correspond to a github repo with format ``repo_owner/repo_name[:ref]`` with
  488. an optional ref (tag or branch), for example 'pytorch/vision:0.10'. If ``ref`` is not specified,
  489. the default branch is assumed to be ``main`` if it exists, and otherwise ``master``.
  490. If ``source`` is 'local' then it should be a path to a local directory.
  491. model (str): the name of a callable (entrypoint) defined in the
  492. repo/dir's ``hubconf.py``.
  493. *args (optional): the corresponding args for callable ``model``.
  494. source (str, optional): 'github' or 'local'. Specifies how
  495. ``repo_or_dir`` is to be interpreted. Default is 'github'.
  496. trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``.
  497. This parameter was introduced in v1.12 and helps ensuring that users
  498. only run code from repos that they trust.
  499. - If ``False``, a prompt will ask the user whether the repo should
  500. be trusted.
  501. - If ``True``, the repo will be added to the trusted list and loaded
  502. without requiring explicit confirmation.
  503. - If ``"check"``, the repo will be checked against the list of
  504. trusted repos in the cache. If it is not present in that list, the
  505. behaviour will fall back onto the ``trust_repo=False`` option.
  506. - If ``None``: this will raise a warning, inviting the user to set
  507. ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This
  508. is only present for backward compatibility and will be removed in
  509. v2.0.
  510. Default is ``None`` and will eventually change to ``"check"`` in v2.0.
  511. force_reload (bool, optional): whether to force a fresh download of
  512. the github repo unconditionally. Does not have any effect if
  513. ``source = 'local'``. Default is ``False``.
  514. verbose (bool, optional): If ``False``, mute messages about hitting
  515. local caches. Note that the message about first download cannot be
  516. muted. Does not have any effect if ``source = 'local'``.
  517. Default is ``True``.
  518. skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit
  519. specified by the ``github`` argument properly belongs to the repo owner. This will make
  520. requests to the GitHub API; you can specify a non-default GitHub token by setting the
  521. ``GITHUB_TOKEN`` environment variable. Default is ``False``.
  522. **kwargs (optional): the corresponding kwargs for callable ``model``.
  523. Returns:
  524. The output of the ``model`` callable when called with the given
  525. ``*args`` and ``**kwargs``.
  526. Example:
  527. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
  528. >>> # from a github repo
  529. >>> repo = "pytorch/vision"
  530. >>> model = torch.hub.load(
  531. ... repo, "resnet50", weights="ResNet50_Weights.IMAGENET1K_V1"
  532. ... )
  533. >>> # from a local directory
  534. >>> path = "/some/local/path/pytorch/vision"
  535. >>> # xdoctest: +SKIP
  536. >>> model = torch.hub.load(path, "resnet50", weights="ResNet50_Weights.DEFAULT")
  537. """
  538. source = source.lower()
  539. if source not in ("github", "local"):
  540. raise ValueError(
  541. f'Unknown source: "{source}". Allowed values: "github" | "local".'
  542. )
  543. if source == "github":
  544. repo_or_dir = _get_cache_or_reload(
  545. repo_or_dir,
  546. force_reload,
  547. trust_repo,
  548. "load",
  549. verbose=verbose,
  550. skip_validation=skip_validation,
  551. )
  552. model = _load_local(repo_or_dir, model, *args, **kwargs)
  553. return model
  554. def _load_local(hubconf_dir, model, *args, **kwargs):
  555. r"""
  556. Load a model from a local directory with a ``hubconf.py``.
  557. Args:
  558. hubconf_dir (str): path to a local directory that contains a
  559. ``hubconf.py``.
  560. model (str): name of an entrypoint defined in the directory's
  561. ``hubconf.py``.
  562. *args (optional): the corresponding args for callable ``model``.
  563. **kwargs (optional): the corresponding kwargs for callable ``model``.
  564. Returns:
  565. a single model with corresponding pretrained weights.
  566. Example:
  567. >>> # xdoctest: +SKIP("stub local path")
  568. >>> path = "/some/local/path/pytorch/vision"
  569. >>> model = _load_local(
  570. ... path,
  571. ... "resnet50",
  572. ... weights="ResNet50_Weights.IMAGENET1K_V1",
  573. ... )
  574. """
  575. with _add_to_sys_path(hubconf_dir):
  576. hubconf_path = os.path.join(hubconf_dir, MODULE_HUBCONF)
  577. hub_module = _import_module(MODULE_HUBCONF, hubconf_path)
  578. entry = _load_entry_from_hubconf(hub_module, model)
  579. model = entry(*args, **kwargs)
  580. return model
  581. def download_url_to_file(
  582. url: str,
  583. dst: str,
  584. hash_prefix: str | None = None,
  585. progress: bool = True,
  586. ) -> None:
  587. r"""Download object at the given URL to a local path.
  588. Args:
  589. url (str): URL of the object to download
  590. dst (str): Full path where object will be saved, e.g. ``/tmp/temporary_file``
  591. hash_prefix (str, optional): If not None, the SHA256 downloaded file should start with ``hash_prefix``.
  592. Default: None
  593. progress (bool, optional): whether or not to display a progress bar to stderr
  594. Default: True
  595. Example:
  596. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
  597. >>> # xdoctest: +REQUIRES(POSIX)
  598. >>> torch.hub.download_url_to_file(
  599. ... "https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth",
  600. ... "/tmp/temporary_file",
  601. ... )
  602. """
  603. # We deliberately save it in a temp file and move it after
  604. # download is complete. This prevents a local working checkpoint
  605. # being overridden by a broken download.
  606. # We deliberately do not use NamedTemporaryFile to avoid restrictive
  607. # file permissions being applied to the downloaded file.
  608. dst = os.path.expanduser(dst)
  609. for _ in range(tempfile.TMP_MAX):
  610. tmp_dst = dst + "." + uuid.uuid4().hex + ".partial"
  611. try:
  612. f = open(tmp_dst, "w+b") # noqa: SIM115
  613. except FileExistsError:
  614. continue
  615. break
  616. else:
  617. raise FileExistsError(errno.EEXIST, "No usable temporary file name found")
  618. req = Request(url, headers={"User-Agent": "torch.hub"})
  619. try:
  620. with urlopen(req) as u:
  621. meta = u.info()
  622. if hasattr(meta, "getheaders"):
  623. content_length = meta.getheaders("Content-Length")
  624. else:
  625. content_length = meta.get_all("Content-Length")
  626. file_size = None
  627. if content_length is not None and len(content_length) > 0:
  628. file_size = int(content_length[0])
  629. sha256 = hashlib.sha256() if hash_prefix is not None else None
  630. with tqdm(
  631. total=file_size,
  632. disable=not progress,
  633. unit="B",
  634. unit_scale=True,
  635. unit_divisor=1024,
  636. ) as pbar:
  637. while True:
  638. buffer = u.read(READ_DATA_CHUNK)
  639. if len(buffer) == 0:
  640. break
  641. f.write(buffer)
  642. if sha256 is not None:
  643. sha256.update(buffer)
  644. pbar.update(len(buffer))
  645. f.close()
  646. if sha256 is not None and hash_prefix is not None:
  647. digest = sha256.hexdigest()
  648. if digest[: len(hash_prefix)] != hash_prefix:
  649. raise RuntimeError(
  650. f'invalid hash value (expected "{hash_prefix}", got "{digest}")'
  651. )
  652. shutil.move(f.name, dst)
  653. finally:
  654. f.close()
  655. if os.path.exists(f.name):
  656. os.remove(f.name)
  657. # Hub used to support automatically extracts from zipfile manually compressed by users.
  658. # The legacy zip format expects only one file from torch.save() < 1.6 in the zip.
  659. # We should remove this support since zipfile is now default zipfile format for torch.save().
  660. def _is_legacy_zip_format(filename: str) -> bool:
  661. if zipfile.is_zipfile(filename):
  662. with zipfile.ZipFile(filename) as zf:
  663. infolist = zf.infolist()
  664. return len(infolist) == 1 and not infolist[0].is_dir()
  665. return False
  666. @deprecated(
  667. "Falling back to the old format < 1.6. This support will be "
  668. "deprecated in favor of default zipfile format introduced in 1.6. "
  669. "Please redo torch.save() to save it in the new zipfile format.",
  670. category=FutureWarning,
  671. )
  672. def _legacy_zip_load(
  673. filename: str,
  674. model_dir: str,
  675. map_location: MAP_LOCATION,
  676. weights_only: bool,
  677. ) -> dict[str, Any]:
  678. # Note: extractall() defaults to overwrite file if exists. No need to clean up beforehand.
  679. # We deliberately don't handle tarfile here since our legacy serialization format was in tar.
  680. # E.g. resnet18-5c106cde.pth which is widely used.
  681. with zipfile.ZipFile(filename) as f:
  682. members = f.infolist()
  683. if len(members) != 1:
  684. raise RuntimeError("Only one file(not dir) is allowed in the zipfile")
  685. f.extractall(model_dir)
  686. extraced_name = members[0].filename
  687. extracted_file = os.path.join(model_dir, extraced_name)
  688. return torch.load(
  689. extracted_file, map_location=map_location, weights_only=weights_only
  690. )
  691. def load_state_dict_from_url(
  692. url: str,
  693. model_dir: str | None = None,
  694. map_location: MAP_LOCATION = None,
  695. progress: bool = True,
  696. check_hash: bool = False,
  697. file_name: str | None = None,
  698. weights_only: bool = False,
  699. ) -> dict[str, Any]:
  700. r"""Loads the Torch serialized object at the given URL.
  701. If downloaded file is a zip file, it will be automatically
  702. decompressed.
  703. If the object is already present in `model_dir`, it's deserialized and
  704. returned.
  705. The default value of ``model_dir`` is ``<hub_dir>/checkpoints`` where
  706. ``hub_dir`` is the directory returned by :func:`~torch.hub.get_dir`.
  707. Args:
  708. url (str): URL of the object to download
  709. model_dir (str, optional): directory in which to save the object
  710. map_location (optional): a function or a dict specifying how to remap storage locations (see torch.load)
  711. progress (bool, optional): whether or not to display a progress bar to stderr.
  712. Default: True
  713. check_hash(bool, optional): If True, the filename part of the URL should follow the naming convention
  714. ``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more
  715. digits of the SHA256 hash of the contents of the file. The hash is used to
  716. ensure unique names and to verify the contents of the file.
  717. Default: False
  718. file_name (str, optional): name for the downloaded file. Filename from ``url`` will be used if not set.
  719. weights_only(bool, optional): If True, only weights will be loaded and no complex pickled objects.
  720. Recommended for untrusted sources. See :func:`~torch.load` for more details.
  721. Example:
  722. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB)
  723. >>> state_dict = torch.hub.load_state_dict_from_url(
  724. ... "https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth"
  725. ... )
  726. """
  727. # Issue warning to move data if old env is set
  728. if os.getenv("TORCH_MODEL_ZOO"):
  729. warnings.warn(
  730. "TORCH_MODEL_ZOO is deprecated, please use env TORCH_HOME instead",
  731. stacklevel=2,
  732. )
  733. if model_dir is None:
  734. hub_dir = get_dir()
  735. model_dir = os.path.join(hub_dir, "checkpoints")
  736. os.makedirs(model_dir, exist_ok=True)
  737. parts = urlparse(url)
  738. filename = os.path.basename(parts.path)
  739. if file_name is not None:
  740. filename = file_name
  741. cached_file = os.path.join(model_dir, filename)
  742. if not os.path.exists(cached_file):
  743. sys.stdout.write(f'Downloading: "{url}" to {cached_file}\n')
  744. hash_prefix = None
  745. if check_hash:
  746. r = HASH_REGEX.search(filename) # r is Optional[Match[str]]
  747. hash_prefix = r.group(1) if r else None
  748. download_url_to_file(url, cached_file, hash_prefix, progress=progress)
  749. if _is_legacy_zip_format(cached_file):
  750. return _legacy_zip_load(cached_file, model_dir, map_location, weights_only)
  751. return torch.load(cached_file, map_location=map_location, weights_only=weights_only)