hub.py 30 KB

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