fastai_utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import json
  2. import os
  3. from pathlib import Path
  4. from pickle import DEFAULT_PROTOCOL, PicklingError
  5. from typing import Any
  6. from packaging import version
  7. from huggingface_hub import constants, snapshot_download
  8. from huggingface_hub.hf_api import HfApi
  9. from huggingface_hub.utils import (
  10. SoftTemporaryDirectory,
  11. get_fastai_version,
  12. get_fastcore_version,
  13. get_python_version,
  14. )
  15. from .utils import logging, validate_hf_hub_args
  16. logger = logging.get_logger(__name__)
  17. def _check_fastai_fastcore_versions(
  18. fastai_min_version: str = "2.4",
  19. fastcore_min_version: str = "1.3.27",
  20. ):
  21. """
  22. Checks that the installed fastai and fastcore versions are compatible for pickle serialization.
  23. Args:
  24. fastai_min_version (`str`, *optional*):
  25. The minimum fastai version supported.
  26. fastcore_min_version (`str`, *optional*):
  27. The minimum fastcore version supported.
  28. > [!TIP]
  29. > Raises the following error:
  30. >
  31. > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
  32. > if the fastai or fastcore libraries are not available or are of an invalid version.
  33. """
  34. if (get_fastcore_version() or get_fastai_version()) == "N/A":
  35. raise ImportError(
  36. f"fastai>={fastai_min_version} and fastcore>={fastcore_min_version} are"
  37. f" required. Currently using fastai=={get_fastai_version()} and"
  38. f" fastcore=={get_fastcore_version()}."
  39. )
  40. current_fastai_version = version.Version(get_fastai_version())
  41. current_fastcore_version = version.Version(get_fastcore_version())
  42. if current_fastai_version < version.Version(fastai_min_version):
  43. raise ImportError(
  44. "`push_to_hub_fastai` and `from_pretrained_fastai` require a"
  45. f" fastai>={fastai_min_version} version, but you are using fastai version"
  46. f" {get_fastai_version()} which is incompatible. Upgrade with `pip install"
  47. " fastai==2.5.6`."
  48. )
  49. if current_fastcore_version < version.Version(fastcore_min_version):
  50. raise ImportError(
  51. "`push_to_hub_fastai` and `from_pretrained_fastai` require a"
  52. f" fastcore>={fastcore_min_version} version, but you are using fastcore"
  53. f" version {get_fastcore_version()} which is incompatible. Upgrade with"
  54. " `pip install fastcore==1.3.27`."
  55. )
  56. def _check_fastai_fastcore_pyproject_versions(
  57. storage_folder: str,
  58. fastai_min_version: str = "2.4",
  59. fastcore_min_version: str = "1.3.27",
  60. ):
  61. """
  62. Checks that the `pyproject.toml` file in the directory `storage_folder` has fastai and fastcore versions
  63. that are compatible with `from_pretrained_fastai` and `push_to_hub_fastai`. If `pyproject.toml` does not exist
  64. or does not contain versions for fastai and fastcore, then it logs a warning.
  65. Args:
  66. storage_folder (`str`):
  67. Folder to look for the `pyproject.toml` file.
  68. fastai_min_version (`str`, *optional*):
  69. The minimum fastai version supported.
  70. fastcore_min_version (`str`, *optional*):
  71. The minimum fastcore version supported.
  72. > [!TIP]
  73. > Raises the following errors:
  74. >
  75. > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
  76. > if the `toml` module is not installed.
  77. > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
  78. > if the `pyproject.toml` indicates a lower than minimum supported version of fastai or fastcore.
  79. """
  80. try:
  81. import toml
  82. except ModuleNotFoundError:
  83. raise ImportError(
  84. "`push_to_hub_fastai` and `from_pretrained_fastai` require the toml module."
  85. " Install it with `pip install toml`."
  86. )
  87. # Checks that a `pyproject.toml`, with `build-system` and `requires` sections, exists in the repository. If so, get a list of required packages.
  88. if not os.path.isfile(f"{storage_folder}/pyproject.toml"):
  89. logger.warning(
  90. "There is no `pyproject.toml` in the repository that contains the fastai"
  91. " `Learner`. The `pyproject.toml` would allow us to verify that your fastai"
  92. " and fastcore versions are compatible with those of the model you want to"
  93. " load."
  94. )
  95. return
  96. pyproject_toml = toml.load(f"{storage_folder}/pyproject.toml")
  97. if "build-system" not in pyproject_toml.keys():
  98. logger.warning(
  99. "There is no `build-system` section in the pyproject.toml of the repository"
  100. " that contains the fastai `Learner`. The `build-system` would allow us to"
  101. " verify that your fastai and fastcore versions are compatible with those"
  102. " of the model you want to load."
  103. )
  104. return
  105. build_system_toml = pyproject_toml["build-system"]
  106. if "requires" not in build_system_toml.keys():
  107. logger.warning(
  108. "There is no `requires` section in the pyproject.toml of the repository"
  109. " that contains the fastai `Learner`. The `requires` would allow us to"
  110. " verify that your fastai and fastcore versions are compatible with those"
  111. " of the model you want to load."
  112. )
  113. return
  114. package_versions = build_system_toml["requires"]
  115. # Extracts contains fastai and fastcore versions from `pyproject.toml` if available.
  116. # If the package is specified but not the version (e.g. "fastai" instead of "fastai=2.4"), the default versions are the highest.
  117. fastai_packages = [pck for pck in package_versions if pck.startswith("fastai")]
  118. if len(fastai_packages) == 0:
  119. logger.warning("The repository does not have a fastai version specified in the `pyproject.toml`.")
  120. # fastai_version is an empty string if not specified
  121. else:
  122. fastai_version = str(fastai_packages[0]).partition("=")[2]
  123. if fastai_version != "" and version.Version(fastai_version) < version.Version(fastai_min_version):
  124. raise ImportError(
  125. "`from_pretrained_fastai` requires"
  126. f" fastai>={fastai_min_version} version but the model to load uses"
  127. f" {fastai_version} which is incompatible."
  128. )
  129. fastcore_packages = [pck for pck in package_versions if pck.startswith("fastcore")]
  130. if len(fastcore_packages) == 0:
  131. logger.warning("The repository does not have a fastcore version specified in the `pyproject.toml`.")
  132. # fastcore_version is an empty string if not specified
  133. else:
  134. fastcore_version = str(fastcore_packages[0]).partition("=")[2]
  135. if fastcore_version != "" and version.Version(fastcore_version) < version.Version(fastcore_min_version):
  136. raise ImportError(
  137. "`from_pretrained_fastai` requires"
  138. f" fastcore>={fastcore_min_version} version, but you are using fastcore"
  139. f" version {fastcore_version} which is incompatible."
  140. )
  141. README_TEMPLATE = """---
  142. tags:
  143. - fastai
  144. ---
  145. # Amazing!
  146. 🥳 Congratulations on hosting your fastai model on the Hugging Face Hub!
  147. # Some next steps
  148. 1. Fill out this model card with more information (see the template below and the [documentation here](https://huggingface.co/docs/hub/model-repos))!
  149. 2. Create a demo in Gradio or Streamlit using 🤗 Spaces ([documentation here](https://huggingface.co/docs/hub/spaces)).
  150. 3. Join the fastai community on the [Fastai Discord](https://discord.com/invite/YKrxeNn)!
  151. Greetings fellow fastlearner 🤝! Don't forget to delete this content from your model card.
  152. ---
  153. # Model card
  154. ## Model description
  155. More information needed
  156. ## Intended uses & limitations
  157. More information needed
  158. ## Training and evaluation data
  159. More information needed
  160. """
  161. PYPROJECT_TEMPLATE = f"""[build-system]
  162. requires = ["setuptools>=40.8.0", "wheel", "python={get_python_version()}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"]
  163. build-backend = "setuptools.build_meta:__legacy__"
  164. """
  165. def _create_model_card(repo_dir: Path):
  166. """
  167. Creates a model card for the repository.
  168. Args:
  169. repo_dir (`Path`):
  170. Directory where model card is created.
  171. """
  172. readme_path = repo_dir / "README.md"
  173. if not readme_path.exists():
  174. with readme_path.open("w", encoding="utf-8") as f:
  175. f.write(README_TEMPLATE)
  176. def _create_model_pyproject(repo_dir: Path):
  177. """
  178. Creates a `pyproject.toml` for the repository.
  179. Args:
  180. repo_dir (`Path`):
  181. Directory where `pyproject.toml` is created.
  182. """
  183. pyproject_path = repo_dir / "pyproject.toml"
  184. if not pyproject_path.exists():
  185. with pyproject_path.open("w", encoding="utf-8") as f:
  186. f.write(PYPROJECT_TEMPLATE)
  187. def _save_pretrained_fastai(
  188. learner,
  189. save_directory: str | Path,
  190. config: dict[str, Any] | None = None,
  191. ):
  192. """
  193. Saves a fastai learner to `save_directory` in pickle format using the default pickle protocol for the version of python used.
  194. Args:
  195. learner (`Learner`):
  196. The `fastai.Learner` you'd like to save.
  197. save_directory (`str` or `Path`):
  198. Specific directory in which you want to save the fastai learner.
  199. config (`dict`, *optional*):
  200. Configuration object. Will be uploaded as a .json file. Example: 'https://huggingface.co/espejelomar/fastai-pet-breeds-classification/blob/main/config.json'.
  201. > [!TIP]
  202. > Raises the following error:
  203. >
  204. > - [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError)
  205. > if the config file provided is not a dictionary.
  206. """
  207. _check_fastai_fastcore_versions()
  208. os.makedirs(save_directory, exist_ok=True)
  209. # if the user provides config then we update it with the fastai and fastcore versions in CONFIG_TEMPLATE.
  210. if config is not None:
  211. if not isinstance(config, dict):
  212. raise RuntimeError(f"Provided config should be a dict. Got: '{type(config)}'")
  213. path = os.path.join(save_directory, constants.CONFIG_NAME)
  214. with open(path, "w") as f:
  215. json.dump(config, f)
  216. _create_model_card(Path(save_directory))
  217. _create_model_pyproject(Path(save_directory))
  218. # learner.export saves the model in `self.path`.
  219. learner.path = Path(save_directory)
  220. os.makedirs(save_directory, exist_ok=True)
  221. try:
  222. learner.export(
  223. fname="model.pkl",
  224. pickle_protocol=DEFAULT_PROTOCOL,
  225. )
  226. except PicklingError:
  227. raise PicklingError(
  228. "You are using a lambda function, i.e., an anonymous function. `pickle`"
  229. " cannot pickle function objects and requires that all functions have"
  230. " names. One possible solution is to name the function."
  231. )
  232. @validate_hf_hub_args
  233. def from_pretrained_fastai(
  234. repo_id: str,
  235. revision: str | None = None,
  236. ):
  237. """
  238. Load pretrained fastai model from the Hub or from a local directory.
  239. Args:
  240. repo_id (`str`):
  241. The location where the pickled fastai.Learner is. It can be either of the two:
  242. - Hosted on the Hugging Face Hub. E.g.: 'espejelomar/fatai-pet-breeds-classification' or 'distilgpt2'.
  243. You can add a `revision` by appending `@` at the end of `repo_id`. E.g.: `dbmdz/bert-base-german-cased@main`.
  244. Revision is the specific model version to use. Since we use a git-based system for storing models and other
  245. artifacts on the Hugging Face Hub, it can be a branch name, a tag name, or a commit id.
  246. - Hosted locally. `repo_id` would be a directory containing the pickle and a pyproject.toml
  247. indicating the fastai and fastcore versions used to build the `fastai.Learner`. E.g.: `./my_model_directory/`.
  248. revision (`str`, *optional*):
  249. Revision at which the repo's files are downloaded. See documentation of `snapshot_download`.
  250. Returns:
  251. The `fastai.Learner` model in the `repo_id` repo.
  252. """
  253. _check_fastai_fastcore_versions()
  254. # Load the `repo_id` repo.
  255. # `snapshot_download` returns the folder where the model was stored.
  256. # `cache_dir` will be the default '/root/.cache/huggingface/hub'
  257. if not os.path.isdir(repo_id):
  258. storage_folder = snapshot_download(
  259. repo_id=repo_id,
  260. revision=revision,
  261. library_name="fastai",
  262. library_version=get_fastai_version(),
  263. )
  264. else:
  265. storage_folder = repo_id
  266. _check_fastai_fastcore_pyproject_versions(storage_folder)
  267. from fastai.learner import load_learner # type: ignore
  268. return load_learner(os.path.join(storage_folder, "model.pkl"))
  269. @validate_hf_hub_args
  270. def push_to_hub_fastai(
  271. learner,
  272. *,
  273. repo_id: str,
  274. commit_message: str = "Push FastAI model using huggingface_hub.",
  275. private: bool | None = None,
  276. token: str | None = None,
  277. config: dict | None = None,
  278. branch: str | None = None,
  279. create_pr: bool | None = None,
  280. allow_patterns: list[str] | str | None = None,
  281. ignore_patterns: list[str] | str | None = None,
  282. delete_patterns: list[str] | str | None = None,
  283. api_endpoint: str | None = None,
  284. ):
  285. """
  286. Upload learner checkpoint files to the Hub.
  287. Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
  288. `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
  289. details.
  290. Args:
  291. learner (`Learner`):
  292. The `fastai.Learner' you'd like to push to the Hub.
  293. repo_id (`str`):
  294. The repository id for your model in Hub in the format of "namespace/repo_name". The namespace can be your individual account or an organization to which you have write access (for example, 'stanfordnlp/stanza-de').
  295. commit_message (`str`, *optional*):
  296. Message to commit while pushing. Will default to :obj:`"add model"`.
  297. private (`bool`, *optional*):
  298. Whether or not the repository created should be private.
  299. If `None` (default), will default to been public except if the organization's default is private.
  300. token (`str`, *optional*):
  301. The Hugging Face account token to use as HTTP bearer authorization for remote files. If :obj:`None`, the token will be asked by a prompt.
  302. config (`dict`, *optional*):
  303. Configuration object to be saved alongside the model weights.
  304. branch (`str`, *optional*):
  305. The git branch on which to push the model. This defaults to
  306. the default branch as specified in your repository, which
  307. defaults to `"main"`.
  308. create_pr (`boolean`, *optional*):
  309. Whether or not to create a Pull Request from `branch` with that commit.
  310. Defaults to `False`.
  311. api_endpoint (`str`, *optional*):
  312. The API endpoint to use when pushing the model to the hub.
  313. allow_patterns (`list[str]` or `str`, *optional*):
  314. If provided, only files matching at least one pattern are pushed.
  315. ignore_patterns (`list[str]` or `str`, *optional*):
  316. If provided, files matching any of the patterns are not pushed.
  317. delete_patterns (`list[str]` or `str`, *optional*):
  318. If provided, remote files matching any of the patterns will be deleted from the repo.
  319. Returns:
  320. The url of the commit of your model in the given repository.
  321. > [!TIP]
  322. > Raises the following error:
  323. >
  324. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  325. > if the user is not log on to the Hugging Face Hub.
  326. """
  327. _check_fastai_fastcore_versions()
  328. api = HfApi(endpoint=api_endpoint)
  329. repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id
  330. # Push the files to the repo in a single commit
  331. with SoftTemporaryDirectory() as tmp:
  332. saved_path = Path(tmp) / repo_id
  333. _save_pretrained_fastai(learner, saved_path, config=config)
  334. return api.upload_folder(
  335. repo_id=repo_id,
  336. token=token,
  337. folder_path=saved_path,
  338. commit_message=commit_message,
  339. revision=branch,
  340. create_pr=create_pr,
  341. allow_patterns=allow_patterns,
  342. ignore_patterns=ignore_patterns,
  343. delete_patterns=delete_patterns,
  344. )