hub_mixin.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. import inspect
  2. import json
  3. import os
  4. from collections.abc import Callable
  5. from dataclasses import Field, asdict, dataclass, is_dataclass
  6. from pathlib import Path
  7. from typing import Any, ClassVar, Protocol, TypeVar
  8. import packaging.version
  9. from . import constants
  10. from .errors import EntryNotFoundError, HfHubHTTPError
  11. from .file_download import hf_hub_download
  12. from .hf_api import HfApi
  13. from .repocard import ModelCard, ModelCardData
  14. from .utils import (
  15. SoftTemporaryDirectory,
  16. is_jsonable,
  17. is_safetensors_available,
  18. is_simple_optional_type,
  19. is_torch_available,
  20. logging,
  21. unwrap_simple_optional_type,
  22. validate_hf_hub_args,
  23. )
  24. if is_torch_available():
  25. import torch # type: ignore
  26. if is_safetensors_available():
  27. import safetensors
  28. from safetensors.torch import load_model as load_model_as_safetensor
  29. from safetensors.torch import save_model as save_model_as_safetensor
  30. logger = logging.get_logger(__name__)
  31. # Type alias for dataclass instances, copied from https://github.com/python/typeshed/blob/9f28171658b9ca6c32a7cb93fbb99fc92b17858b/stdlib/_typeshed/__init__.pyi#L349
  32. class DataclassInstance(Protocol):
  33. __dataclass_fields__: ClassVar[dict[str, Field]]
  34. # Generic variable that is either ModelHubMixin or a subclass thereof
  35. T = TypeVar("T", bound="ModelHubMixin")
  36. # Generic variable to represent an args type
  37. ARGS_T = TypeVar("ARGS_T")
  38. ENCODER_T = Callable[[ARGS_T], Any]
  39. DECODER_T = Callable[[Any], ARGS_T]
  40. CODER_T = tuple[ENCODER_T, DECODER_T]
  41. DEFAULT_MODEL_CARD = """
  42. ---
  43. # For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
  44. # Doc / guide: https://huggingface.co/docs/hub/model-cards
  45. {{ card_data }}
  46. ---
  47. This model has been pushed to the Hub using the [PytorchModelHubMixin](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) integration:
  48. - Code: {{ repo_url | default("[More Information Needed]", true) }}
  49. - Paper: {{ paper_url | default("[More Information Needed]", true) }}
  50. - Docs: {{ docs_url | default("[More Information Needed]", true) }}
  51. """
  52. @dataclass
  53. class MixinInfo:
  54. model_card_template: str
  55. model_card_data: ModelCardData
  56. docs_url: str | None = None
  57. paper_url: str | None = None
  58. repo_url: str | None = None
  59. class ModelHubMixin:
  60. """
  61. A generic mixin to integrate ANY machine learning framework with the Hub.
  62. To integrate your framework, your model class must inherit from this class. Custom logic for saving/loading models
  63. have to be overwritten in [`_from_pretrained`] and [`_save_pretrained`]. [`PyTorchModelHubMixin`] is a good example
  64. of mixin integration with the Hub. Check out our [integration guide](../guides/integrations) for more instructions.
  65. When inheriting from [`ModelHubMixin`], you can define class-level attributes. These attributes are not passed to
  66. `__init__` but to the class definition itself. This is useful to define metadata about the library integrating
  67. [`ModelHubMixin`].
  68. For more details on how to integrate the mixin with your library, checkout the [integration guide](../guides/integrations).
  69. Args:
  70. repo_url (`str`, *optional*):
  71. URL of the library repository. Used to generate model card.
  72. paper_url (`str`, *optional*):
  73. URL of the library paper. Used to generate model card.
  74. docs_url (`str`, *optional*):
  75. URL of the library documentation. Used to generate model card.
  76. model_card_template (`str`, *optional*):
  77. Template of the model card. Used to generate model card. Defaults to a generic template.
  78. language (`str` or `list[str]`, *optional*):
  79. Language supported by the library. Used to generate model card.
  80. library_name (`str`, *optional*):
  81. Name of the library integrating ModelHubMixin. Used to generate model card.
  82. license (`str`, *optional*):
  83. License of the library integrating ModelHubMixin. Used to generate model card.
  84. E.g: "apache-2.0"
  85. license_name (`str`, *optional*):
  86. Name of the library integrating ModelHubMixin. Used to generate model card.
  87. Only used if `license` is set to `other`.
  88. E.g: "coqui-public-model-license".
  89. license_link (`str`, *optional*):
  90. URL to the license of the library integrating ModelHubMixin. Used to generate model card.
  91. Only used if `license` is set to `other` and `license_name` is set.
  92. E.g: "https://coqui.ai/cpml".
  93. pipeline_tag (`str`, *optional*):
  94. Tag of the pipeline. Used to generate model card. E.g. "text-classification".
  95. tags (`list[str]`, *optional*):
  96. Tags to be added to the model card. Used to generate model card. E.g. ["computer-vision"]
  97. coders (`dict[Type, tuple[Callable, Callable]]`, *optional*):
  98. Dictionary of custom types and their encoders/decoders. Used to encode/decode arguments that are not
  99. jsonable by default. E.g. dataclasses, argparse.Namespace, OmegaConf, etc.
  100. Example:
  101. ```python
  102. >>> from huggingface_hub import ModelHubMixin
  103. # Inherit from ModelHubMixin
  104. >>> class MyCustomModel(
  105. ... ModelHubMixin,
  106. ... library_name="my-library",
  107. ... tags=["computer-vision"],
  108. ... repo_url="https://github.com/huggingface/my-cool-library",
  109. ... paper_url="https://arxiv.org/abs/2304.12244",
  110. ... docs_url="https://huggingface.co/docs/my-cool-library",
  111. ... # ^ optional metadata to generate model card
  112. ... ):
  113. ... def __init__(self, size: int = 512, device: str = "cpu"):
  114. ... # define how to initialize your model
  115. ... super().__init__()
  116. ... ...
  117. ...
  118. ... def _save_pretrained(self, save_directory: Path) -> None:
  119. ... # define how to serialize your model
  120. ... ...
  121. ...
  122. ... @classmethod
  123. ... def from_pretrained(
  124. ... cls: type[T],
  125. ... pretrained_model_name_or_path: Union[str, Path],
  126. ... *,
  127. ... force_download: bool = False,
  128. ... token: Optional[Union[str, bool]] = None,
  129. ... cache_dir: Optional[Union[str, Path]] = None,
  130. ... local_files_only: bool = False,
  131. ... revision: Optional[str] = None,
  132. ... **model_kwargs,
  133. ... ) -> T:
  134. ... # define how to deserialize your model
  135. ... ...
  136. >>> model = MyCustomModel(size=256, device="gpu")
  137. # Save model weights to local directory
  138. >>> model.save_pretrained("my-awesome-model")
  139. # Push model weights to the Hub
  140. >>> model.push_to_hub("my-awesome-model")
  141. # Download and initialize weights from the Hub
  142. >>> reloaded_model = MyCustomModel.from_pretrained("username/my-awesome-model")
  143. >>> reloaded_model.size
  144. 256
  145. # Model card has been correctly populated
  146. >>> from huggingface_hub import ModelCard
  147. >>> card = ModelCard.load("username/my-awesome-model")
  148. >>> card.data.tags
  149. ["x-custom-tag", "pytorch_model_hub_mixin", "model_hub_mixin"]
  150. >>> card.data.library_name
  151. "my-library"
  152. ```
  153. """
  154. _hub_mixin_config: dict | DataclassInstance | None = None
  155. # ^ optional config attribute automatically set in `from_pretrained`
  156. _hub_mixin_info: MixinInfo
  157. # ^ information about the library integrating ModelHubMixin (used to generate model card)
  158. _hub_mixin_inject_config: bool # whether `_from_pretrained` expects `config` or not
  159. _hub_mixin_init_parameters: dict[str, inspect.Parameter] # __init__ parameters
  160. _hub_mixin_jsonable_default_values: dict[str, Any] # default values for __init__ parameters
  161. _hub_mixin_jsonable_custom_types: tuple[type, ...] # custom types that can be encoded/decoded
  162. _hub_mixin_coders: dict[type, CODER_T] # encoders/decoders for custom types
  163. # ^ internal values to handle config
  164. def __init_subclass__(
  165. cls,
  166. *,
  167. # Generic info for model card
  168. repo_url: str | None = None,
  169. paper_url: str | None = None,
  170. docs_url: str | None = None,
  171. # Model card template
  172. model_card_template: str = DEFAULT_MODEL_CARD,
  173. # Model card metadata
  174. language: list[str] | None = None,
  175. library_name: str | None = None,
  176. license: str | None = None,
  177. license_name: str | None = None,
  178. license_link: str | None = None,
  179. pipeline_tag: str | None = None,
  180. tags: list[str] | None = None,
  181. # How to encode/decode arguments with custom type into a JSON config?
  182. coders: None
  183. | (
  184. dict[type, CODER_T]
  185. # Key is a type.
  186. # Value is a tuple (encoder, decoder).
  187. # Example: {MyCustomType: (lambda x: x.value, lambda data: MyCustomType(data))}
  188. ) = None,
  189. ) -> None:
  190. """Inspect __init__ signature only once when subclassing + handle modelcard."""
  191. super().__init_subclass__()
  192. # Will be reused when creating modelcard
  193. tags = tags or []
  194. tags.append("model_hub_mixin")
  195. # Initialize MixinInfo if not existent
  196. info = MixinInfo(model_card_template=model_card_template, model_card_data=ModelCardData())
  197. # If parent class has a MixinInfo, inherit from it as a copy
  198. if hasattr(cls, "_hub_mixin_info"):
  199. # Inherit model card template from parent class if not explicitly set
  200. if model_card_template == DEFAULT_MODEL_CARD:
  201. info.model_card_template = cls._hub_mixin_info.model_card_template
  202. # Inherit from parent model card data
  203. info.model_card_data = ModelCardData(**cls._hub_mixin_info.model_card_data.to_dict())
  204. # Inherit other info
  205. info.docs_url = cls._hub_mixin_info.docs_url
  206. info.paper_url = cls._hub_mixin_info.paper_url
  207. info.repo_url = cls._hub_mixin_info.repo_url
  208. cls._hub_mixin_info = info
  209. # Update MixinInfo with metadata
  210. if model_card_template is not None and model_card_template != DEFAULT_MODEL_CARD:
  211. info.model_card_template = model_card_template
  212. if repo_url is not None:
  213. info.repo_url = repo_url
  214. if paper_url is not None:
  215. info.paper_url = paper_url
  216. if docs_url is not None:
  217. info.docs_url = docs_url
  218. if language is not None:
  219. info.model_card_data.language = language
  220. if library_name is not None:
  221. info.model_card_data.library_name = library_name
  222. if license is not None:
  223. info.model_card_data.license = license
  224. if license_name is not None:
  225. info.model_card_data.license_name = license_name
  226. if license_link is not None:
  227. info.model_card_data.license_link = license_link
  228. if pipeline_tag is not None:
  229. info.model_card_data.pipeline_tag = pipeline_tag
  230. if tags is not None:
  231. normalized_tags = list(tags)
  232. if info.model_card_data.tags is not None:
  233. info.model_card_data.tags.extend(normalized_tags)
  234. else:
  235. info.model_card_data.tags = normalized_tags
  236. if info.model_card_data.tags is not None:
  237. info.model_card_data.tags = sorted(set(info.model_card_data.tags))
  238. # Handle encoders/decoders for args
  239. cls._hub_mixin_coders = coders or {}
  240. cls._hub_mixin_jsonable_custom_types = tuple(cls._hub_mixin_coders.keys())
  241. # Inspect __init__ signature to handle config
  242. cls._hub_mixin_init_parameters = dict(inspect.signature(cls.__init__).parameters)
  243. cls._hub_mixin_jsonable_default_values = {
  244. param.name: cls._encode_arg(param.default)
  245. for param in cls._hub_mixin_init_parameters.values()
  246. if param.default is not inspect.Parameter.empty and cls._is_jsonable(param.default)
  247. }
  248. cls._hub_mixin_inject_config = "config" in inspect.signature(cls._from_pretrained).parameters
  249. def __new__(cls: type[T], *args, **kwargs) -> T:
  250. """Create a new instance of the class and handle config.
  251. 3 cases:
  252. - If `self._hub_mixin_config` is already set, do nothing.
  253. - If `config` is passed as a dataclass, set it as `self._hub_mixin_config`.
  254. - Otherwise, build `self._hub_mixin_config` from default values and passed values.
  255. """
  256. instance = super().__new__(cls)
  257. # If `config` is already set, return early
  258. if instance._hub_mixin_config is not None:
  259. return instance
  260. # Infer passed values
  261. passed_values = {
  262. **{
  263. key: value
  264. for key, value in zip(
  265. # [1:] to skip `self` parameter
  266. list(cls._hub_mixin_init_parameters)[1:],
  267. args,
  268. )
  269. },
  270. **kwargs,
  271. }
  272. # If config passed as dataclass => set it and return early
  273. if is_dataclass(passed_values.get("config")):
  274. instance._hub_mixin_config = passed_values["config"]
  275. return instance
  276. # Otherwise, build config from default + passed values
  277. init_config = {
  278. # default values
  279. **cls._hub_mixin_jsonable_default_values,
  280. # passed values
  281. **{
  282. key: cls._encode_arg(value) # Encode custom types as jsonable value
  283. for key, value in passed_values.items()
  284. if instance._is_jsonable(value) # Only if jsonable or we have a custom encoder
  285. },
  286. }
  287. passed_config = init_config.pop("config", {})
  288. # Populate `init_config` with provided config
  289. if isinstance(passed_config, dict):
  290. init_config.update(passed_config)
  291. # Set `config` attribute and return
  292. if init_config != {}:
  293. instance._hub_mixin_config = init_config
  294. return instance
  295. @classmethod
  296. def _is_jsonable(cls, value: Any) -> bool:
  297. """Check if a value is JSON serializable."""
  298. if is_dataclass(value):
  299. return True
  300. if isinstance(value, cls._hub_mixin_jsonable_custom_types):
  301. return True
  302. return is_jsonable(value)
  303. @classmethod
  304. def _encode_arg(cls, arg: Any) -> Any:
  305. """Encode an argument into a JSON serializable format."""
  306. if is_dataclass(arg):
  307. return asdict(arg) # type: ignore[arg-type]
  308. for type_, (encoder, _) in cls._hub_mixin_coders.items():
  309. if isinstance(arg, type_):
  310. if arg is None:
  311. return None
  312. return encoder(arg)
  313. return arg
  314. @classmethod
  315. def _decode_arg(cls, expected_type: type[ARGS_T], value: Any) -> ARGS_T | None:
  316. """Decode a JSON serializable value into an argument."""
  317. if is_simple_optional_type(expected_type):
  318. if value is None:
  319. return None
  320. expected_type = unwrap_simple_optional_type(expected_type) # type: ignore
  321. # Dataclass => handle it
  322. if is_dataclass(expected_type):
  323. return _load_dataclass(expected_type, value) # type: ignore
  324. # Otherwise => check custom decoders
  325. for type_, (_, decoder) in cls._hub_mixin_coders.items():
  326. if inspect.isclass(expected_type) and issubclass(expected_type, type_):
  327. return decoder(value)
  328. # Otherwise => don't decode
  329. return value
  330. def save_pretrained(
  331. self,
  332. save_directory: str | Path,
  333. *,
  334. config: dict | DataclassInstance | None = None,
  335. repo_id: str | None = None,
  336. push_to_hub: bool = False,
  337. model_card_kwargs: dict[str, Any] | None = None,
  338. **push_to_hub_kwargs,
  339. ) -> str | None:
  340. """
  341. Save weights in local directory.
  342. Args:
  343. save_directory (`str` or `Path`):
  344. Path to directory in which the model weights and configuration will be saved.
  345. config (`dict` or `DataclassInstance`, *optional*):
  346. Model configuration specified as a key/value dictionary or a dataclass instance.
  347. push_to_hub (`bool`, *optional*, defaults to `False`):
  348. Whether or not to push your model to the Huggingface Hub after saving it.
  349. repo_id (`str`, *optional*):
  350. ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if
  351. not provided.
  352. model_card_kwargs (`dict[str, Any]`, *optional*):
  353. Additional arguments passed to the model card template to customize the model card.
  354. push_to_hub_kwargs:
  355. Additional key word arguments passed along to the [`~ModelHubMixin.push_to_hub`] method.
  356. Returns:
  357. `str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise.
  358. """
  359. save_directory = Path(save_directory)
  360. save_directory.mkdir(parents=True, exist_ok=True)
  361. # Remove config.json if already exists. After `_save_pretrained` we don't want to overwrite config.json
  362. # as it might have been saved by the custom `_save_pretrained` already. However we do want to overwrite
  363. # an existing config.json if it was not saved by `_save_pretrained`.
  364. config_path = save_directory / constants.CONFIG_NAME
  365. config_path.unlink(missing_ok=True)
  366. # save model weights/files (framework-specific)
  367. self._save_pretrained(save_directory)
  368. # save config (if provided and if not serialized yet in `_save_pretrained`)
  369. if config is None:
  370. config = self._hub_mixin_config
  371. if config is not None:
  372. if is_dataclass(config):
  373. config = asdict(config) # type: ignore[arg-type]
  374. if not config_path.exists():
  375. config_str = json.dumps(config, sort_keys=True, indent=2)
  376. config_path.write_text(config_str)
  377. # save model card
  378. model_card_path = save_directory / "README.md"
  379. model_card_kwargs = model_card_kwargs if model_card_kwargs is not None else {}
  380. if not model_card_path.exists(): # do not overwrite if already exists
  381. self.generate_model_card(**model_card_kwargs).save(save_directory / "README.md")
  382. # push to the Hub if required
  383. if push_to_hub:
  384. kwargs = push_to_hub_kwargs.copy() # soft-copy to avoid mutating input
  385. if config is not None: # kwarg for `push_to_hub`
  386. kwargs["config"] = config
  387. if repo_id is None:
  388. repo_id = save_directory.name # Defaults to `save_directory` name
  389. return self.push_to_hub(repo_id=repo_id, model_card_kwargs=model_card_kwargs, **kwargs)
  390. return None
  391. def _save_pretrained(self, save_directory: Path) -> None:
  392. """
  393. Overwrite this method in subclass to define how to save your model.
  394. Check out our [integration guide](../guides/integrations) for instructions.
  395. Args:
  396. save_directory (`str` or `Path`):
  397. Path to directory in which the model weights and configuration will be saved.
  398. """
  399. raise NotImplementedError
  400. @classmethod
  401. @validate_hf_hub_args
  402. def from_pretrained(
  403. cls: type[T],
  404. pretrained_model_name_or_path: str | Path,
  405. *,
  406. force_download: bool = False,
  407. token: str | bool | None = None,
  408. cache_dir: str | Path | None = None,
  409. local_files_only: bool = False,
  410. revision: str | None = None,
  411. **model_kwargs,
  412. ) -> T:
  413. """
  414. Download a model from the Huggingface Hub and instantiate it.
  415. Args:
  416. pretrained_model_name_or_path (`str`, `Path`):
  417. - Either the `model_id` (string) of a model hosted on the Hub, e.g. `bigscience/bloom`.
  418. - Or a path to a `directory` containing model weights saved using
  419. [`~transformers.PreTrainedModel.save_pretrained`], e.g., `../path/to/my_model_directory/`.
  420. revision (`str`, *optional*):
  421. Revision of the model on the Hub. Can be a branch name, a git tag or any commit id.
  422. Defaults to the latest commit on `main` branch.
  423. force_download (`bool`, *optional*, defaults to `False`):
  424. Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
  425. the existing cache.
  426. token (`str` or `bool`, *optional*):
  427. The token to use as HTTP bearer authorization for remote files. By default, it will use the token
  428. cached when running `hf auth login`.
  429. cache_dir (`str`, `Path`, *optional*):
  430. Path to the folder where cached files are stored.
  431. local_files_only (`bool`, *optional*, defaults to `False`):
  432. If `True`, avoid downloading the file and return the path to the local cached file if it exists.
  433. model_kwargs (`dict`, *optional*):
  434. Additional kwargs to pass to the model during initialization.
  435. """
  436. model_id = str(pretrained_model_name_or_path)
  437. config_file: str | None = None
  438. if os.path.isdir(model_id):
  439. if constants.CONFIG_NAME in os.listdir(model_id):
  440. config_file = os.path.join(model_id, constants.CONFIG_NAME)
  441. else:
  442. logger.warning(f"{constants.CONFIG_NAME} not found in {Path(model_id).resolve()}")
  443. else:
  444. try:
  445. config_file = hf_hub_download(
  446. repo_id=model_id,
  447. filename=constants.CONFIG_NAME,
  448. revision=revision,
  449. cache_dir=cache_dir,
  450. force_download=force_download,
  451. token=token,
  452. local_files_only=local_files_only,
  453. )
  454. except HfHubHTTPError as e:
  455. logger.info(f"{constants.CONFIG_NAME} not found on the HuggingFace Hub: {str(e)}")
  456. # Read config
  457. config = None
  458. if config_file is not None:
  459. with open(config_file, encoding="utf-8") as f:
  460. config = json.load(f)
  461. # Decode custom types in config
  462. for key, value in config.items():
  463. if key in cls._hub_mixin_init_parameters:
  464. expected_type = cls._hub_mixin_init_parameters[key].annotation
  465. if expected_type is not inspect.Parameter.empty:
  466. config[key] = cls._decode_arg(expected_type, value)
  467. # Populate model_kwargs from config
  468. for param in cls._hub_mixin_init_parameters.values():
  469. if param.name not in model_kwargs and param.name in config:
  470. model_kwargs[param.name] = config[param.name]
  471. # Check if `config` argument was passed at init
  472. if "config" in cls._hub_mixin_init_parameters and "config" not in model_kwargs:
  473. # Decode `config` argument if it was passed
  474. config_annotation = cls._hub_mixin_init_parameters["config"].annotation
  475. config = cls._decode_arg(config_annotation, config)
  476. # Forward config to model initialization
  477. model_kwargs["config"] = config
  478. # Inject config if `**kwargs` are expected
  479. if is_dataclass(cls):
  480. for key in cls.__dataclass_fields__:
  481. if key not in model_kwargs and key in config:
  482. model_kwargs[key] = config[key]
  483. elif any(param.kind == inspect.Parameter.VAR_KEYWORD for param in cls._hub_mixin_init_parameters.values()):
  484. for key, value in config.items(): # type: ignore[union-attr]
  485. if key not in model_kwargs:
  486. model_kwargs[key] = value
  487. # Finally, also inject if `_from_pretrained` expects it
  488. if cls._hub_mixin_inject_config and "config" not in model_kwargs:
  489. model_kwargs["config"] = config
  490. instance = cls._from_pretrained(
  491. model_id=str(model_id),
  492. revision=revision,
  493. cache_dir=cache_dir,
  494. force_download=force_download,
  495. local_files_only=local_files_only,
  496. token=token,
  497. **model_kwargs,
  498. )
  499. # Implicitly set the config as instance attribute if not already set by the class
  500. # This way `config` will be available when calling `save_pretrained` or `push_to_hub`.
  501. if config is not None and (getattr(instance, "_hub_mixin_config", None) in (None, {})):
  502. instance._hub_mixin_config = config
  503. return instance
  504. @classmethod
  505. def _from_pretrained(
  506. cls: type[T],
  507. *,
  508. model_id: str,
  509. revision: str | None,
  510. cache_dir: str | Path | None,
  511. force_download: bool,
  512. local_files_only: bool,
  513. token: str | bool | None,
  514. **model_kwargs,
  515. ) -> T:
  516. """Overwrite this method in subclass to define how to load your model from pretrained.
  517. Use [`hf_hub_download`] or [`snapshot_download`] to download files from the Hub before loading them. Most
  518. args taken as input can be directly passed to those 2 methods. If needed, you can add more arguments to this
  519. method using "model_kwargs". For example [`PyTorchModelHubMixin._from_pretrained`] takes as input a `map_location`
  520. parameter to set on which device the model should be loaded.
  521. Check out our [integration guide](../guides/integrations) for more instructions.
  522. Args:
  523. model_id (`str`):
  524. ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`).
  525. revision (`str`, *optional*):
  526. Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the
  527. latest commit on `main` branch.
  528. force_download (`bool`, *optional*, defaults to `False`):
  529. Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
  530. the existing cache.
  531. token (`str` or `bool`, *optional*):
  532. The token to use as HTTP bearer authorization for remote files. By default, it will use the token
  533. cached when running `hf auth login`.
  534. cache_dir (`str`, `Path`, *optional*):
  535. Path to the folder where cached files are stored.
  536. local_files_only (`bool`, *optional*, defaults to `False`):
  537. If `True`, avoid downloading the file and return the path to the local cached file if it exists.
  538. model_kwargs:
  539. Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method.
  540. """
  541. raise NotImplementedError
  542. @validate_hf_hub_args
  543. def push_to_hub(
  544. self,
  545. repo_id: str,
  546. *,
  547. config: dict | DataclassInstance | None = None,
  548. commit_message: str = "Push model using huggingface_hub.",
  549. private: bool | None = None,
  550. token: str | None = None,
  551. branch: str | None = None,
  552. create_pr: bool | None = None,
  553. allow_patterns: list[str] | str | None = None,
  554. ignore_patterns: list[str] | str | None = None,
  555. delete_patterns: list[str] | str | None = None,
  556. model_card_kwargs: dict[str, Any] | None = None,
  557. ) -> str:
  558. """
  559. Upload model checkpoint to the Hub.
  560. Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
  561. `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
  562. details.
  563. Args:
  564. repo_id (`str`):
  565. ID of the repository to push to (example: `"username/my-model"`).
  566. config (`dict` or `DataclassInstance`, *optional*):
  567. Model configuration specified as a key/value dictionary or a dataclass instance.
  568. commit_message (`str`, *optional*):
  569. Message to commit while pushing.
  570. private (`bool`, *optional*):
  571. Whether the repository created should be private.
  572. If `None` (default), the repo will be public unless the organization's default is private.
  573. token (`str`, *optional*):
  574. The token to use as HTTP bearer authorization for remote files. By default, it will use the token
  575. cached when running `hf auth login`.
  576. branch (`str`, *optional*):
  577. The git branch on which to push the model. This defaults to `"main"`.
  578. create_pr (`boolean`, *optional*):
  579. Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`.
  580. allow_patterns (`list[str]` or `str`, *optional*):
  581. If provided, only files matching at least one pattern are pushed.
  582. ignore_patterns (`list[str]` or `str`, *optional*):
  583. If provided, files matching any of the patterns are not pushed.
  584. delete_patterns (`list[str]` or `str`, *optional*):
  585. If provided, remote files matching any of the patterns will be deleted from the repo.
  586. model_card_kwargs (`dict[str, Any]`, *optional*):
  587. Additional arguments passed to the model card template to customize the model card.
  588. Returns:
  589. The url of the commit of your model in the given repository.
  590. """
  591. api = HfApi(token=token)
  592. repo_id = api.create_repo(repo_id=repo_id, private=private, exist_ok=True).repo_id
  593. # Push the files to the repo in a single commit
  594. with SoftTemporaryDirectory() as tmp:
  595. saved_path = Path(tmp) / repo_id
  596. self.save_pretrained(saved_path, config=config, model_card_kwargs=model_card_kwargs)
  597. return api.upload_folder(
  598. repo_id=repo_id,
  599. repo_type="model",
  600. folder_path=saved_path,
  601. commit_message=commit_message,
  602. revision=branch,
  603. create_pr=create_pr,
  604. allow_patterns=allow_patterns,
  605. ignore_patterns=ignore_patterns,
  606. delete_patterns=delete_patterns,
  607. )
  608. def generate_model_card(self, *args, **kwargs) -> ModelCard:
  609. card = ModelCard.from_template(
  610. card_data=self._hub_mixin_info.model_card_data,
  611. template_str=self._hub_mixin_info.model_card_template,
  612. repo_url=self._hub_mixin_info.repo_url,
  613. paper_url=self._hub_mixin_info.paper_url,
  614. docs_url=self._hub_mixin_info.docs_url,
  615. **kwargs,
  616. )
  617. return card
  618. class PyTorchModelHubMixin(ModelHubMixin):
  619. """
  620. Implementation of [`ModelHubMixin`] to provide model Hub upload/download capabilities to PyTorch models. The model
  621. is set in evaluation mode by default using `model.eval()` (dropout modules are deactivated). To train the model,
  622. you should first set it back in training mode with `model.train()`.
  623. See [`ModelHubMixin`] for more details on how to use the mixin.
  624. Example:
  625. ```python
  626. >>> import torch
  627. >>> import torch.nn as nn
  628. >>> from huggingface_hub import PyTorchModelHubMixin
  629. >>> class MyModel(
  630. ... nn.Module,
  631. ... PyTorchModelHubMixin,
  632. ... library_name="keras-nlp",
  633. ... repo_url="https://github.com/keras-team/keras-nlp",
  634. ... paper_url="https://arxiv.org/abs/2304.12244",
  635. ... docs_url="https://keras.io/keras_nlp/",
  636. ... # ^ optional metadata to generate model card
  637. ... ):
  638. ... def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4):
  639. ... super().__init__()
  640. ... self.param = nn.Parameter(torch.rand(hidden_size, vocab_size))
  641. ... self.linear = nn.Linear(output_size, vocab_size)
  642. ... def forward(self, x):
  643. ... return self.linear(x + self.param)
  644. >>> model = MyModel(hidden_size=256)
  645. # Save model weights to local directory
  646. >>> model.save_pretrained("my-awesome-model")
  647. # Push model weights to the Hub
  648. >>> model.push_to_hub("my-awesome-model")
  649. # Download and initialize weights from the Hub
  650. >>> model = MyModel.from_pretrained("username/my-awesome-model")
  651. >>> model.hidden_size
  652. 256
  653. ```
  654. """
  655. def __init_subclass__(cls, *args, tags: list[str] | None = None, **kwargs) -> None:
  656. tags = tags or []
  657. tags.append("pytorch_model_hub_mixin")
  658. kwargs["tags"] = tags
  659. return super().__init_subclass__(*args, **kwargs)
  660. def _save_pretrained(self, save_directory: Path) -> None:
  661. """Save weights from a Pytorch model to a local directory."""
  662. model_to_save = self.module if hasattr(self, "module") else self # type: ignore
  663. save_model_as_safetensor(model_to_save, str(save_directory / constants.SAFETENSORS_SINGLE_FILE)) # type: ignore [arg-type]
  664. @classmethod
  665. def _from_pretrained(
  666. cls,
  667. *,
  668. model_id: str,
  669. revision: str | None,
  670. cache_dir: str | Path | None,
  671. force_download: bool,
  672. local_files_only: bool,
  673. token: str | bool | None,
  674. map_location: str = "cpu",
  675. strict: bool = False,
  676. **model_kwargs,
  677. ):
  678. """Load Pytorch pretrained weights and return the loaded model."""
  679. model = cls(**model_kwargs)
  680. if os.path.isdir(model_id):
  681. print("Loading weights from local directory")
  682. model_file = os.path.join(model_id, constants.SAFETENSORS_SINGLE_FILE)
  683. return cls._load_as_safetensor(model, model_file, map_location, strict)
  684. else:
  685. try:
  686. model_file = hf_hub_download(
  687. repo_id=model_id,
  688. filename=constants.SAFETENSORS_SINGLE_FILE,
  689. revision=revision,
  690. cache_dir=cache_dir,
  691. force_download=force_download,
  692. token=token,
  693. local_files_only=local_files_only,
  694. )
  695. return cls._load_as_safetensor(model, model_file, map_location, strict)
  696. except EntryNotFoundError:
  697. model_file = hf_hub_download(
  698. repo_id=model_id,
  699. filename=constants.PYTORCH_WEIGHTS_NAME,
  700. revision=revision,
  701. cache_dir=cache_dir,
  702. force_download=force_download,
  703. token=token,
  704. local_files_only=local_files_only,
  705. )
  706. return cls._load_as_pickle(model, model_file, map_location, strict)
  707. @classmethod
  708. def _load_as_pickle(cls, model: T, model_file: str, map_location: str, strict: bool) -> T:
  709. state_dict = torch.load(model_file, map_location=torch.device(map_location), weights_only=True)
  710. model.load_state_dict(state_dict, strict=strict) # type: ignore
  711. model.eval() # type: ignore
  712. return model
  713. @classmethod
  714. def _load_as_safetensor(cls, model: T, model_file: str, map_location: str, strict: bool) -> T:
  715. if packaging.version.parse(safetensors.__version__) < packaging.version.parse("0.4.3"): # type: ignore [attr-defined]
  716. load_model_as_safetensor(model, model_file, strict=strict) # type: ignore [arg-type]
  717. if map_location != "cpu":
  718. logger.warning(
  719. "Loading model weights on other devices than 'cpu' is not supported natively in your version of safetensors."
  720. " This means that the model is loaded on 'cpu' first and then copied to the device."
  721. " This leads to a slower loading time."
  722. " Please update safetensors to version 0.4.3 or above for improved performance."
  723. )
  724. model.to(map_location) # type: ignore [attr-defined]
  725. else:
  726. safetensors.torch.load_model(model, model_file, strict=strict, device=map_location) # type: ignore [arg-type]
  727. model.eval() # type: ignore
  728. return model
  729. def _load_dataclass(datacls: type[DataclassInstance], data: dict) -> DataclassInstance:
  730. """Load a dataclass instance from a dictionary.
  731. Fields not expected by the dataclass are ignored.
  732. """
  733. return datacls(**{k: v for k, v in data.items() if k in datacls.__dataclass_fields__})