modeling_flax_utils.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. # coding=utf-8
  2. # Copyright 2021 The Google Flax Team Authors and The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import gc
  16. import json
  17. import os
  18. import warnings
  19. from functools import partial
  20. from pickle import UnpicklingError
  21. from typing import Any, Optional, Union
  22. import flax.linen as nn
  23. import jax
  24. import jax.numpy as jnp
  25. import msgpack.exceptions
  26. from flax.core.frozen_dict import FrozenDict, unfreeze
  27. from flax.serialization import from_bytes, to_bytes
  28. from flax.traverse_util import flatten_dict, unflatten_dict
  29. from jax.random import PRNGKey
  30. from .configuration_utils import PretrainedConfig
  31. from .dynamic_module_utils import custom_object_save
  32. from .generation import FlaxGenerationMixin, GenerationConfig
  33. from .modeling_flax_pytorch_utils import load_pytorch_checkpoint_in_flax_state_dict
  34. from .utils import (
  35. FLAX_WEIGHTS_INDEX_NAME,
  36. FLAX_WEIGHTS_NAME,
  37. SAFE_WEIGHTS_INDEX_NAME,
  38. SAFE_WEIGHTS_NAME,
  39. WEIGHTS_INDEX_NAME,
  40. WEIGHTS_NAME,
  41. PushToHubMixin,
  42. add_code_sample_docstrings,
  43. add_start_docstrings_to_model_forward,
  44. cached_file,
  45. copy_func,
  46. download_url,
  47. has_file,
  48. is_offline_mode,
  49. is_remote_url,
  50. logging,
  51. replace_return_docstrings,
  52. )
  53. from .utils.hub import convert_file_size_to_int, get_checkpoint_shard_files
  54. from .utils.import_utils import is_safetensors_available
  55. if is_safetensors_available():
  56. from safetensors import safe_open
  57. from safetensors.flax import load_file as safe_load_file
  58. from safetensors.flax import save_file as safe_save_file
  59. logger = logging.get_logger(__name__)
  60. def quick_gelu(x):
  61. return x * jax.nn.sigmoid(1.702 * x)
  62. ACT2FN = {
  63. "gelu": partial(nn.gelu, approximate=False),
  64. "relu": nn.relu,
  65. "silu": nn.swish,
  66. "swish": nn.swish,
  67. "gelu_new": partial(nn.gelu, approximate=True),
  68. "quick_gelu": quick_gelu,
  69. "gelu_pytorch_tanh": partial(nn.gelu, approximate=True),
  70. "tanh": nn.tanh,
  71. }
  72. def flax_shard_checkpoint(params, max_shard_size="10GB"):
  73. """
  74. Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a
  75. given size. The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so
  76. there is no optimization made to make each sub-checkpoint as close as possible to the maximum size passed. For
  77. example, if the limit is 10GB and we have weights of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as
  78. [6GB], [6+2GB], [6+2+2GB] and not [6+2+2GB], [6+2GB], [6GB].
  79. <Tip warning={true}>
  80. If one of the model's weight is bigger that `max_shard_size`, it will end up in its own sub-checkpoint which will
  81. have a size greater than `max_shard_size`.
  82. </Tip>
  83. Args:
  84. params (`Union[Dict, FrozenDict]`): A `PyTree` of model parameters.
  85. max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`):
  86. The maximum size of each sub-checkpoint. If expressed as a string, needs to be digits followed by a unit
  87. (like `"5MB"`).
  88. """
  89. max_shard_size = convert_file_size_to_int(max_shard_size)
  90. sharded_state_dicts = []
  91. current_block = {}
  92. current_block_size = 0
  93. total_size = 0
  94. # flatten the weights to chunk
  95. weights = flatten_dict(params, sep="/")
  96. for item in weights:
  97. weight_size = weights[item].size * weights[item].dtype.itemsize
  98. # If this weight is going to tip up over the maximal size, we split.
  99. if current_block_size + weight_size > max_shard_size:
  100. sharded_state_dicts.append(current_block)
  101. current_block = {}
  102. current_block_size = 0
  103. current_block[item] = weights[item]
  104. current_block_size += weight_size
  105. total_size += weight_size
  106. # Add the last block
  107. sharded_state_dicts.append(current_block)
  108. # If we only have one shard, we return it
  109. if len(sharded_state_dicts) == 1:
  110. return {FLAX_WEIGHTS_NAME: sharded_state_dicts[0]}, None
  111. # Otherwise, let's build the index
  112. weight_map = {}
  113. shards = {}
  114. for idx, shard in enumerate(sharded_state_dicts):
  115. shard_file = FLAX_WEIGHTS_NAME.replace(".msgpack", f"-{idx + 1:05d}-of-{len(sharded_state_dicts):05d}.msgpack")
  116. shards[shard_file] = shard
  117. for weight_name in shard:
  118. weight_map[weight_name] = shard_file
  119. # Add the metadata
  120. metadata = {"total_size": total_size}
  121. index = {"metadata": metadata, "weight_map": weight_map}
  122. return shards, index
  123. class FlaxPreTrainedModel(PushToHubMixin, FlaxGenerationMixin):
  124. r"""
  125. Base class for all models.
  126. [`FlaxPreTrainedModel`] takes care of storing the configuration of the models and handles methods for loading,
  127. downloading and saving models.
  128. Class attributes (overridden by derived classes):
  129. - **config_class** ([`PretrainedConfig`]) -- A subclass of [`PretrainedConfig`] to use as configuration class
  130. for this model architecture.
  131. - **base_model_prefix** (`str`) -- A string indicating the attribute associated to the base model in derived
  132. classes of the same architecture adding modules on top of the base model.
  133. - **main_input_name** (`str`) -- The name of the principal input to the model (often `input_ids` for NLP
  134. models, `pixel_values` for vision models and `input_values` for speech models).
  135. """
  136. config_class = None
  137. base_model_prefix = ""
  138. main_input_name = "input_ids"
  139. _auto_class = None
  140. _missing_keys = set()
  141. def __init__(
  142. self,
  143. config: PretrainedConfig,
  144. module: nn.Module,
  145. input_shape: tuple = (1, 1),
  146. seed: int = 0,
  147. dtype: jnp.dtype = jnp.float32,
  148. _do_init: bool = True,
  149. ):
  150. logger.warning_once(
  151. "TensorFlow and JAX classes are deprecated and will be removed in Transformers v5. We "
  152. "recommend migrating to PyTorch classes or pinning your version of Transformers."
  153. )
  154. if config is None:
  155. raise ValueError("config cannot be None")
  156. if module is None:
  157. raise ValueError("module cannot be None")
  158. # Those are private to be exposed as typed property on derived classes.
  159. self._config = config
  160. self._module = module
  161. # Those are public as their type is generic to every derived classes.
  162. self.key = PRNGKey(seed)
  163. self.dtype = dtype
  164. self.input_shape = input_shape
  165. self.generation_config = GenerationConfig.from_model_config(config) if self.can_generate() else None
  166. # To check if the model was initialized automatically.
  167. self._is_initialized = _do_init
  168. if _do_init:
  169. # randomly initialized parameters
  170. random_params = self.init_weights(self.key, input_shape)
  171. params_shape_tree = jax.eval_shape(lambda params: params, random_params)
  172. else:
  173. init_fn = partial(self.init_weights, input_shape=input_shape)
  174. params_shape_tree = jax.eval_shape(init_fn, self.key)
  175. logger.info(
  176. "Model weights are not initialized as `_do_init` is set to `False`. "
  177. f"Make sure to call `{self.__class__.__name__}.init_weights` manually to initialize the weights."
  178. )
  179. # get the shape of the parameters
  180. self._params_shape_tree = params_shape_tree
  181. # save required_params as set
  182. self._required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys())
  183. # initialize the parameters
  184. if _do_init:
  185. self.params = random_params
  186. def init_weights(self, rng: jax.random.PRNGKey, input_shape: tuple, params: FrozenDict = None) -> dict:
  187. raise NotImplementedError(f"init method has to be implemented for {self}")
  188. def enable_gradient_checkpointing(self):
  189. raise NotImplementedError(f"gradient checkpointing method has to be implemented for {self}")
  190. @classmethod
  191. def _from_config(cls, config, **kwargs):
  192. """
  193. All context managers that the model should be initialized under go here.
  194. """
  195. return cls(config, **kwargs)
  196. @property
  197. def framework(self) -> str:
  198. """
  199. :str: Identifies that this is a Flax model.
  200. """
  201. return "flax"
  202. @property
  203. def config(self) -> PretrainedConfig:
  204. return self._config
  205. @property
  206. def module(self) -> nn.Module:
  207. return self._module
  208. @property
  209. def params(self) -> Union[dict, FrozenDict]:
  210. if not self._is_initialized:
  211. raise ValueError(
  212. "`params` cannot be accessed from model when the model is created with `_do_init=False`. "
  213. "You must call `init_weights` manually and store the params outside of the model and "
  214. "pass it explicitly where needed."
  215. )
  216. return self._params
  217. @property
  218. def required_params(self) -> set:
  219. return self._required_params
  220. @property
  221. def params_shape_tree(self) -> dict:
  222. return self._params_shape_tree
  223. @params.setter
  224. def params(self, params: Union[dict, FrozenDict]):
  225. # don't set params if the model is not initialized
  226. if not self._is_initialized:
  227. raise ValueError(
  228. "`params` cannot be set from model when the model is created with `_do_init=False`. "
  229. "You store the params outside of the model."
  230. )
  231. if isinstance(params, FrozenDict):
  232. params = unfreeze(params)
  233. param_keys = set(flatten_dict(params).keys())
  234. if len(self.required_params - param_keys) > 0:
  235. raise ValueError(
  236. "Some parameters are missing. Make sure that `params` include the following "
  237. f"parameters {self.required_params - param_keys}"
  238. )
  239. self._params = params
  240. def _cast_floating_to(self, params: Union[dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any:
  241. """
  242. Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.
  243. """
  244. # taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27
  245. def conditional_cast(param):
  246. if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating):
  247. param = param.astype(dtype)
  248. return param
  249. if mask is None:
  250. return jax.tree_util.tree_map(conditional_cast, params)
  251. flat_params = flatten_dict(params)
  252. flat_mask, _ = jax.tree_util.tree_flatten(mask)
  253. for masked, key in zip(flat_mask, sorted(flat_params.keys())):
  254. if masked:
  255. flat_params[key] = conditional_cast(flat_params[key])
  256. return unflatten_dict(flat_params)
  257. def to_bf16(self, params: Union[dict, FrozenDict], mask: Any = None):
  258. r"""
  259. Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast
  260. the `params` in place.
  261. This method can be used on TPU to explicitly convert the model parameters to bfloat16 precision to do full
  262. half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.
  263. Arguments:
  264. params (`Union[Dict, FrozenDict]`):
  265. A `PyTree` of model parameters.
  266. mask (`Union[Dict, FrozenDict]`):
  267. A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params
  268. you want to cast, and should be `False` for those you want to skip.
  269. Examples:
  270. ```python
  271. >>> from transformers import FlaxBertModel
  272. >>> # load model
  273. >>> model = FlaxBertModel.from_pretrained("google-bert/bert-base-cased")
  274. >>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision
  275. >>> model.params = model.to_bf16(model.params)
  276. >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)
  277. >>> # then pass the mask as follows
  278. >>> from flax import traverse_util
  279. >>> model = FlaxBertModel.from_pretrained("google-bert/bert-base-cased")
  280. >>> flat_params = traverse_util.flatten_dict(model.params)
  281. >>> mask = {
  282. ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
  283. ... for path in flat_params
  284. ... }
  285. >>> mask = traverse_util.unflatten_dict(mask)
  286. >>> model.params = model.to_bf16(model.params, mask)
  287. ```"""
  288. return self._cast_floating_to(params, jnp.bfloat16, mask)
  289. def to_fp32(self, params: Union[dict, FrozenDict], mask: Any = None):
  290. r"""
  291. Cast the floating-point `params` to `jax.numpy.float32`. This method can be used to explicitly convert the
  292. model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.
  293. Arguments:
  294. params (`Union[Dict, FrozenDict]`):
  295. A `PyTree` of model parameters.
  296. mask (`Union[Dict, FrozenDict]`):
  297. A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params
  298. you want to cast, and should be `False` for those you want to skip
  299. Examples:
  300. ```python
  301. >>> from transformers import FlaxBertModel
  302. >>> # Download model and configuration from huggingface.co
  303. >>> model = FlaxBertModel.from_pretrained("google-bert/bert-base-cased")
  304. >>> # By default, the model params will be in fp32, to illustrate the use of this method,
  305. >>> # we'll first cast to fp16 and back to fp32
  306. >>> model.params = model.to_f16(model.params)
  307. >>> # now cast back to fp32
  308. >>> model.params = model.to_fp32(model.params)
  309. ```"""
  310. return self._cast_floating_to(params, jnp.float32, mask)
  311. def to_fp16(self, params: Union[dict, FrozenDict], mask: Any = None):
  312. r"""
  313. Cast the floating-point `params` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the
  314. `params` in place.
  315. This method can be used on GPU to explicitly convert the model parameters to float16 precision to do full
  316. half-precision training or to save weights in float16 for inference in order to save memory and improve speed.
  317. Arguments:
  318. params (`Union[Dict, FrozenDict]`):
  319. A `PyTree` of model parameters.
  320. mask (`Union[Dict, FrozenDict]`):
  321. A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params
  322. you want to cast, and should be `False` for those you want to skip
  323. Examples:
  324. ```python
  325. >>> from transformers import FlaxBertModel
  326. >>> # load model
  327. >>> model = FlaxBertModel.from_pretrained("google-bert/bert-base-cased")
  328. >>> # By default, the model params will be in fp32, to cast these to float16
  329. >>> model.params = model.to_fp16(model.params)
  330. >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)
  331. >>> # then pass the mask as follows
  332. >>> from flax import traverse_util
  333. >>> model = FlaxBertModel.from_pretrained("google-bert/bert-base-cased")
  334. >>> flat_params = traverse_util.flatten_dict(model.params)
  335. >>> mask = {
  336. ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
  337. ... for path in flat_params
  338. ... }
  339. >>> mask = traverse_util.unflatten_dict(mask)
  340. >>> model.params = model.to_fp16(model.params, mask)
  341. ```"""
  342. return self._cast_floating_to(params, jnp.float16, mask)
  343. @classmethod
  344. def load_flax_weights(cls, resolved_archive_file):
  345. try:
  346. if resolved_archive_file.endswith(".safetensors"):
  347. state = safe_load_file(resolved_archive_file)
  348. state = unflatten_dict(state, sep=".")
  349. else:
  350. with open(resolved_archive_file, "rb") as state_f:
  351. state = from_bytes(cls, state_f.read())
  352. except (UnpicklingError, msgpack.exceptions.ExtraData) as e:
  353. try:
  354. with open(resolved_archive_file) as f:
  355. if f.read().startswith("version"):
  356. raise OSError(
  357. "You seem to have cloned a repository without having git-lfs installed. Please"
  358. " install git-lfs and run `git lfs install` followed by `git lfs pull` in the"
  359. " folder you cloned."
  360. )
  361. else:
  362. raise ValueError from e
  363. except (UnicodeDecodeError, ValueError):
  364. raise OSError(f"Unable to convert {resolved_archive_file} to Flax deserializable object. ")
  365. return state
  366. @classmethod
  367. def load_flax_sharded_weights(cls, shard_files):
  368. """
  369. This is the same as [`flax.serialization.from_bytes`]
  370. (https:lax.readthedocs.io/en/latest/_modules/flax/serialization.html#from_bytes) but for a sharded checkpoint.
  371. This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and deleted after being
  372. loaded in the model.
  373. Args:
  374. shard_files (`list[str]`:
  375. The list of shard files to load.
  376. Returns:
  377. `Dict`: A nested dictionary of the model parameters, in the expected format for flax models : `{'model':
  378. {'params': {'...'}}}`.
  379. """
  380. # Load the index
  381. state_sharded_dict = {}
  382. for shard_file in shard_files:
  383. # load using msgpack utils
  384. try:
  385. with open(shard_file, "rb") as state_f:
  386. state = from_bytes(cls, state_f.read())
  387. except (UnpicklingError, msgpack.exceptions.ExtraData) as e:
  388. with open(shard_file) as f:
  389. if f.read().startswith("version"):
  390. raise OSError(
  391. "You seem to have cloned a repository without having git-lfs installed. Please"
  392. " install git-lfs and run `git lfs install` followed by `git lfs pull` in the"
  393. " folder you cloned."
  394. )
  395. else:
  396. raise ValueError from e
  397. except (UnicodeDecodeError, ValueError):
  398. raise OSError(f"Unable to convert {shard_file} to Flax deserializable object. ")
  399. state = flatten_dict(state, sep="/")
  400. state_sharded_dict.update(state)
  401. del state
  402. gc.collect()
  403. # the state dict is unflattened to the match the format of model.params
  404. return unflatten_dict(state_sharded_dict, sep="/")
  405. @classmethod
  406. def can_generate(cls) -> bool:
  407. """
  408. Returns whether this model can generate sequences with `.generate()`. Returns:
  409. `bool`: Whether this model can generate sequences with `.generate()`.
  410. """
  411. # Detects whether `prepare_inputs_for_generation` has been overwritten, which is a requirement for generation.
  412. # Alternatively, the model can also have a custom `generate` function.
  413. if "GenerationMixin" in str(cls.prepare_inputs_for_generation) and "GenerationMixin" in str(cls.generate):
  414. return False
  415. return True
  416. @classmethod
  417. def from_pretrained(
  418. cls,
  419. pretrained_model_name_or_path: Union[str, os.PathLike],
  420. dtype: jnp.dtype = jnp.float32,
  421. *model_args,
  422. config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
  423. cache_dir: Optional[Union[str, os.PathLike]] = None,
  424. ignore_mismatched_sizes: bool = False,
  425. force_download: bool = False,
  426. local_files_only: bool = False,
  427. token: Optional[Union[str, bool]] = None,
  428. revision: str = "main",
  429. **kwargs,
  430. ):
  431. r"""
  432. Instantiate a pretrained flax model from a pre-trained model configuration.
  433. The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come
  434. pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning
  435. task.
  436. The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those
  437. weights are discarded.
  438. Parameters:
  439. pretrained_model_name_or_path (`str` or `os.PathLike`):
  440. Can be either:
  441. - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
  442. - A path to a *directory* containing model weights saved using
  443. [`~FlaxPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
  444. - A path or url to a *pt index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In this case,
  445. `from_pt` should be set to `True`.
  446. dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
  447. The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
  448. `jax.numpy.bfloat16` (on TPUs).
  449. This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
  450. specified all the computation will be performed with the given `dtype`.
  451. **Note that this only specifies the dtype of the computation and does not influence the dtype of model
  452. parameters.**
  453. If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
  454. [`~FlaxPreTrainedModel.to_bf16`].
  455. model_args (sequence of positional arguments, *optional*):
  456. All remaining positional arguments will be passed to the underlying model's `__init__` method.
  457. config (`Union[PretrainedConfig, str, os.PathLike]`, *optional*):
  458. Can be either:
  459. - an instance of a class derived from [`PretrainedConfig`],
  460. - a string or path valid as input to [`~PretrainedConfig.from_pretrained`].
  461. Configuration for the model to use instead of an automatically loaded configuration. Configuration can
  462. be automatically loaded when:
  463. - The model is a model provided by the library (loaded with the *model id* string of a pretrained
  464. model).
  465. - The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
  466. save directory.
  467. - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
  468. configuration JSON file named *config.json* is found in the directory.
  469. cache_dir (`Union[str, os.PathLike]`, *optional*):
  470. Path to a directory in which a downloaded pretrained model configuration should be cached if the
  471. standard cache should not be used.
  472. from_pt (`bool`, *optional*, defaults to `False`):
  473. Load the model weights from a PyTorch checkpoint save file (see docstring of
  474. `pretrained_model_name_or_path` argument).
  475. ignore_mismatched_sizes (`bool`, *optional*, defaults to `False`):
  476. Whether or not to raise an error if some of the weights from the checkpoint do not have the same size
  477. as the weights of the model (if for instance, you are instantiating a model with 10 labels from a
  478. checkpoint with 3 labels).
  479. force_download (`bool`, *optional*, defaults to `False`):
  480. Whether or not to force the (re-)download of the model weights and configuration files, overriding the
  481. cached versions if they exist.
  482. resume_download:
  483. Deprecated and ignored. All downloads are now resumed by default when possible.
  484. Will be removed in v5 of Transformers.
  485. proxies (`dict[str, str]`, *optional*):
  486. A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
  487. 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
  488. local_files_only(`bool`, *optional*, defaults to `False`):
  489. Whether or not to only look at local files (i.e., do not try to download the model).
  490. token (`str` or `bool`, *optional*):
  491. The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
  492. the token generated when running `hf auth login` (stored in `~/.huggingface`).
  493. revision (`str`, *optional*, defaults to `"main"`):
  494. The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
  495. git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
  496. identifier allowed by git.
  497. <Tip>
  498. To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
  499. </Tip>
  500. subfolder (`str`, *optional*, defaults to `""`):
  501. In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
  502. specify the folder name here.
  503. kwargs (remaining dictionary of keyword arguments, *optional*):
  504. Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
  505. `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
  506. automatically loaded:
  507. - If a configuration is provided with `config`, `**kwargs` will be directly passed to the
  508. underlying model's `__init__` method (we assume all relevant updates to the configuration have
  509. already been done)
  510. - If a configuration is not provided, `kwargs` will be first passed to the configuration class
  511. initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
  512. corresponds to a configuration attribute will be used to override said attribute with the
  513. supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
  514. will be passed to the underlying model's `__init__` function.
  515. Examples:
  516. ```python
  517. >>> from transformers import BertConfig, FlaxBertModel
  518. >>> # Download model and configuration from huggingface.co and cache.
  519. >>> model = FlaxBertModel.from_pretrained("google-bert/bert-base-cased")
  520. >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).
  521. >>> model = FlaxBertModel.from_pretrained("./test/saved_model/")
  522. >>> # Loading from a PyTorch checkpoint file instead of a PyTorch model (slower, for example purposes, not runnable).
  523. >>> config = BertConfig.from_json_file("./pt_model/config.json")
  524. >>> model = FlaxBertModel.from_pretrained("./pt_model/pytorch_model.bin", from_pt=True, config=config)
  525. ```"""
  526. from_pt = kwargs.pop("from_pt", False)
  527. resume_download = kwargs.pop("resume_download", None)
  528. proxies = kwargs.pop("proxies", None)
  529. use_auth_token = kwargs.pop("use_auth_token", None)
  530. trust_remote_code = kwargs.pop("trust_remote_code", None)
  531. from_pipeline = kwargs.pop("_from_pipeline", None)
  532. from_auto_class = kwargs.pop("_from_auto", False)
  533. _do_init = kwargs.pop("_do_init", True)
  534. subfolder = kwargs.pop("subfolder", "")
  535. commit_hash = kwargs.pop("_commit_hash", None)
  536. # Not relevant for Flax Models
  537. _ = kwargs.pop("adapter_kwargs", None)
  538. if use_auth_token is not None:
  539. warnings.warn(
  540. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  541. FutureWarning,
  542. )
  543. if token is not None:
  544. raise ValueError(
  545. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  546. )
  547. token = use_auth_token
  548. if trust_remote_code is True:
  549. logger.warning(
  550. "The argument `trust_remote_code` is to be used with Auto classes. It has no effect here and is"
  551. " ignored."
  552. )
  553. user_agent = {"file_type": "model", "framework": "flax", "from_auto_class": from_auto_class}
  554. if from_pipeline is not None:
  555. user_agent["using_pipeline"] = from_pipeline
  556. if is_offline_mode() and not local_files_only:
  557. logger.info("Offline mode: forcing local_files_only=True")
  558. local_files_only = True
  559. # Load config if we don't provide a configuration
  560. if not isinstance(config, PretrainedConfig):
  561. config_path = config if config is not None else pretrained_model_name_or_path
  562. config, model_kwargs = cls.config_class.from_pretrained(
  563. config_path,
  564. cache_dir=cache_dir,
  565. return_unused_kwargs=True,
  566. force_download=force_download,
  567. resume_download=resume_download,
  568. proxies=proxies,
  569. local_files_only=local_files_only,
  570. token=token,
  571. revision=revision,
  572. subfolder=subfolder,
  573. _from_auto=from_auto_class,
  574. _from_pipeline=from_pipeline,
  575. _commit_hash=commit_hash,
  576. **kwargs,
  577. )
  578. else:
  579. model_kwargs = kwargs.copy()
  580. if commit_hash is None:
  581. commit_hash = getattr(config, "_commit_hash", None)
  582. # Add the dtype to model_kwargs
  583. model_kwargs["dtype"] = dtype
  584. # This variable will flag if we're loading a sharded checkpoint. In this case the archive file is just the
  585. # index of the files.
  586. is_sharded = False
  587. # Load model
  588. if pretrained_model_name_or_path is not None:
  589. pretrained_model_name_or_path = str(pretrained_model_name_or_path)
  590. is_local = os.path.isdir(pretrained_model_name_or_path)
  591. if is_local:
  592. if os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_NAME)):
  593. # Load from a Flax checkpoint
  594. archive_file = os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_NAME)
  595. elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_INDEX_NAME)):
  596. # Load from a sharded Flax checkpoint
  597. archive_file = os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_INDEX_NAME)
  598. is_sharded = True
  599. elif is_safetensors_available() and os.path.isfile(
  600. os.path.join(pretrained_model_name_or_path, subfolder, SAFE_WEIGHTS_NAME)
  601. ):
  602. # Load from a safetensors checkpoint
  603. archive_file = os.path.join(pretrained_model_name_or_path, subfolder, SAFE_WEIGHTS_NAME)
  604. elif is_safetensors_available() and os.path.isfile(
  605. os.path.join(pretrained_model_name_or_path, SAFE_WEIGHTS_NAME)
  606. ):
  607. # Load from a safetensors checkpoint
  608. archive_file = os.path.join(pretrained_model_name_or_path, SAFE_WEIGHTS_NAME)
  609. elif from_pt and os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME)):
  610. # Load from a PyTorch checkpoint
  611. archive_file = os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME)
  612. elif from_pt and os.path.isfile(
  613. os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_INDEX_NAME)
  614. ):
  615. # Load from a sharded pytorch checkpoint
  616. archive_file = os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_INDEX_NAME)
  617. is_sharded = True
  618. # At this stage we don't have a weight file so we will raise an error.
  619. elif is_safetensors_available() and os.path.isfile(
  620. os.path.join(pretrained_model_name_or_path, SAFE_WEIGHTS_INDEX_NAME)
  621. ):
  622. # Load from a sharded safetensors checkpoint
  623. archive_file = os.path.join(pretrained_model_name_or_path, SAFE_WEIGHTS_INDEX_NAME)
  624. is_sharded = True
  625. raise NotImplementedError("Support for sharded checkpoints using safetensors is coming soon!")
  626. elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME)):
  627. raise OSError(
  628. f"Error no file named {FLAX_WEIGHTS_NAME} found in directory {pretrained_model_name_or_path} "
  629. "but there is a file for PyTorch weights. Use `from_pt=True` to load this model from those "
  630. "weights."
  631. )
  632. else:
  633. raise OSError(
  634. f"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory "
  635. f"{pretrained_model_name_or_path}."
  636. )
  637. elif os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)):
  638. archive_file = pretrained_model_name_or_path
  639. is_local = True
  640. elif is_remote_url(pretrained_model_name_or_path):
  641. filename = pretrained_model_name_or_path
  642. resolved_archive_file = download_url(pretrained_model_name_or_path)
  643. else:
  644. if from_pt:
  645. filename = WEIGHTS_NAME
  646. else:
  647. filename = FLAX_WEIGHTS_NAME
  648. try:
  649. # Load from URL or cache if already cached
  650. cached_file_kwargs = {
  651. "cache_dir": cache_dir,
  652. "force_download": force_download,
  653. "proxies": proxies,
  654. "resume_download": resume_download,
  655. "local_files_only": local_files_only,
  656. "token": token,
  657. "user_agent": user_agent,
  658. "revision": revision,
  659. "subfolder": subfolder,
  660. "_raise_exceptions_for_gated_repo": False,
  661. "_raise_exceptions_for_missing_entries": False,
  662. "_commit_hash": commit_hash,
  663. }
  664. resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs)
  665. # Maybe the checkpoint is sharded, we try to grab the index name in this case.
  666. if resolved_archive_file is None and filename == FLAX_WEIGHTS_NAME:
  667. resolved_archive_file = cached_file(
  668. pretrained_model_name_or_path, FLAX_WEIGHTS_INDEX_NAME, **cached_file_kwargs
  669. )
  670. if resolved_archive_file is not None:
  671. is_sharded = True
  672. # Maybe the checkpoint is pytorch sharded, we try to grab the pytorch index name in this case.
  673. if resolved_archive_file is None and from_pt:
  674. resolved_archive_file = cached_file(
  675. pretrained_model_name_or_path, WEIGHTS_INDEX_NAME, **cached_file_kwargs
  676. )
  677. if resolved_archive_file is not None:
  678. is_sharded = True
  679. # If we still haven't found anything, look for `safetensors`.
  680. if resolved_archive_file is None:
  681. # No support for sharded safetensors yet, so we'll raise an error if that's all we find.
  682. filename = SAFE_WEIGHTS_NAME
  683. resolved_archive_file = cached_file(
  684. pretrained_model_name_or_path, SAFE_WEIGHTS_NAME, **cached_file_kwargs
  685. )
  686. # Since we set _raise_exceptions_for_missing_entries=False, we don't get an exception but a None
  687. # result when internet is up, the repo and revision exist, but the file does not.
  688. if resolved_archive_file is None:
  689. # Otherwise, maybe there is a TF or Torch model file. We try those to give a helpful error
  690. # message.
  691. has_file_kwargs = {
  692. "revision": revision,
  693. "proxies": proxies,
  694. "token": token,
  695. "cache_dir": cache_dir,
  696. "local_files_only": local_files_only,
  697. }
  698. if has_file(pretrained_model_name_or_path, SAFE_WEIGHTS_INDEX_NAME, **has_file_kwargs):
  699. is_sharded = True
  700. raise NotImplementedError(
  701. "Support for sharded checkpoints using safetensors is coming soon!"
  702. )
  703. elif has_file(pretrained_model_name_or_path, WEIGHTS_NAME, **has_file_kwargs):
  704. raise OSError(
  705. f"{pretrained_model_name_or_path} does not appear to have a file named"
  706. f" {FLAX_WEIGHTS_NAME} but there is a file for PyTorch weights. Use `from_pt=True` to"
  707. " load this model from those weights."
  708. )
  709. elif has_file(pretrained_model_name_or_path, WEIGHTS_INDEX_NAME, **has_file_kwargs):
  710. raise OSError(
  711. f"{pretrained_model_name_or_path} does not appear to have a file named"
  712. f" {FLAX_WEIGHTS_INDEX_NAME} but there is a sharded file for PyTorch weights. Use"
  713. " `from_pt=True` to load this model from those weights."
  714. )
  715. else:
  716. raise OSError(
  717. f"{pretrained_model_name_or_path} does not appear to have a file named"
  718. f" {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
  719. )
  720. except OSError:
  721. # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted
  722. # to the original exception.
  723. raise
  724. except Exception:
  725. # For any other exception, we throw a generic error.
  726. raise OSError(
  727. f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it"
  728. " from 'https://huggingface.co/models', make sure you don't have a local directory with the"
  729. f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
  730. f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
  731. )
  732. if is_local:
  733. logger.info(f"loading weights file {archive_file}")
  734. resolved_archive_file = archive_file
  735. filename = resolved_archive_file.split(os.path.sep)[-1]
  736. else:
  737. logger.info(f"loading weights file {filename} from cache at {resolved_archive_file}")
  738. else:
  739. resolved_archive_file = None
  740. # We'll need to download and cache each checkpoint shard if the checkpoint is sharded.
  741. if is_sharded:
  742. # resolved_archive_file becomes a list of files that point to the different checkpoint shards in this case.
  743. resolved_archive_file, _ = get_checkpoint_shard_files(
  744. pretrained_model_name_or_path,
  745. resolved_archive_file,
  746. cache_dir=cache_dir,
  747. force_download=force_download,
  748. proxies=proxies,
  749. resume_download=resume_download,
  750. local_files_only=local_files_only,
  751. token=token,
  752. user_agent=user_agent,
  753. revision=revision,
  754. subfolder=subfolder,
  755. _commit_hash=commit_hash,
  756. )
  757. safetensors_from_pt = False
  758. if filename == SAFE_WEIGHTS_NAME:
  759. with safe_open(resolved_archive_file, framework="flax") as f:
  760. safetensors_metadata = f.metadata()
  761. if safetensors_metadata is None or safetensors_metadata.get("format") not in ["pt", "tf", "flax"]:
  762. raise OSError(
  763. f"The safetensors archive passed at {resolved_archive_file} does not contain the valid metadata."
  764. " Make sure you save your model with the `save_pretrained` method."
  765. )
  766. safetensors_from_pt = safetensors_metadata.get("format") == "pt"
  767. # init random models
  768. model = cls(config, *model_args, _do_init=_do_init, **model_kwargs)
  769. if from_pt or safetensors_from_pt:
  770. state = load_pytorch_checkpoint_in_flax_state_dict(model, resolved_archive_file, is_sharded)
  771. else:
  772. if is_sharded:
  773. state = cls.load_flax_sharded_weights(resolved_archive_file)
  774. else:
  775. state = cls.load_flax_weights(resolved_archive_file)
  776. # make sure all arrays are stored as jnp.arrays
  777. # NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4:
  778. # https://github.com/google/flax/issues/1261
  779. if _do_init:
  780. state = jax.tree_util.tree_map(jnp.array, state)
  781. else:
  782. # keep the params on CPU if we don't want to initialize
  783. state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.local_devices(backend="cpu")[0]), state)
  784. if "batch_stats" in state: # if flax model contains batch norm layers
  785. # if model is base model only use model_prefix key
  786. if (
  787. cls.base_model_prefix not in dict(model.params_shape_tree["params"])
  788. and cls.base_model_prefix in state["params"]
  789. ):
  790. state["params"] = state["params"][cls.base_model_prefix]
  791. state["batch_stats"] = state["batch_stats"][cls.base_model_prefix]
  792. # if model is head model and we are loading weights from base model
  793. # we initialize new params dict with base_model_prefix
  794. if (
  795. cls.base_model_prefix in dict(model.params_shape_tree["params"])
  796. and cls.base_model_prefix not in state["params"]
  797. ):
  798. state = {
  799. "params": {cls.base_model_prefix: state["params"]},
  800. "batch_stats": {cls.base_model_prefix: state["batch_stats"]},
  801. }
  802. else:
  803. # if model is base model only use model_prefix key
  804. if cls.base_model_prefix not in dict(model.params_shape_tree) and cls.base_model_prefix in state:
  805. state = state[cls.base_model_prefix]
  806. # if model is head model and we are loading weights from base model
  807. # we initialize new params dict with base_model_prefix
  808. if cls.base_model_prefix in dict(model.params_shape_tree) and cls.base_model_prefix not in state:
  809. state = {cls.base_model_prefix: state}
  810. # flatten dicts
  811. state = flatten_dict(state)
  812. random_state = flatten_dict(unfreeze(model.params if _do_init else model.params_shape_tree))
  813. missing_keys = model.required_params - set(state.keys())
  814. unexpected_keys = set(state.keys()) - model.required_params
  815. # Disabling warning when porting pytorch weights to flax, flax does not uses num_batches_tracked
  816. for unexpected_key in unexpected_keys.copy():
  817. if "num_batches_tracked" in unexpected_key[-1]:
  818. unexpected_keys.remove(unexpected_key)
  819. if missing_keys and not _do_init:
  820. logger.warning(
  821. f"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. "
  822. "Make sure to call model.init_weights to initialize the missing weights."
  823. )
  824. cls._missing_keys = missing_keys
  825. # Mismatched keys contains tuples key/shape1/shape2 of weights in the checkpoint that have a shape not
  826. # matching the weights in the model.
  827. mismatched_keys = []
  828. for key in state:
  829. if key in random_state and state[key].shape != random_state[key].shape:
  830. if ignore_mismatched_sizes:
  831. mismatched_keys.append((key, state[key].shape, random_state[key].shape))
  832. state[key] = random_state[key]
  833. else:
  834. raise ValueError(
  835. f"Trying to load the pretrained weight for {key} failed: checkpoint has shape "
  836. f"{state[key].shape} which is incompatible with the model shape {random_state[key].shape}. "
  837. "Using `ignore_mismatched_sizes=True` if you really want to load this checkpoint inside this "
  838. "model."
  839. )
  840. # add missing keys as random parameters if we are initializing
  841. if missing_keys and _do_init:
  842. for missing_key in missing_keys:
  843. state[missing_key] = random_state[missing_key]
  844. # remove unexpected keys to not be saved again
  845. for unexpected_key in unexpected_keys:
  846. del state[unexpected_key]
  847. if len(unexpected_keys) > 0:
  848. logger.warning(
  849. f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
  850. f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
  851. f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or"
  852. " with another architecture (e.g. initializing a BertForSequenceClassification model from a"
  853. " BertForPreTraining model).\n- This IS NOT expected if you are initializing"
  854. f" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly identical"
  855. " (initializing a BertForSequenceClassification model from a BertForSequenceClassification model)."
  856. )
  857. else:
  858. logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
  859. if len(missing_keys) > 0:
  860. logger.warning(
  861. f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
  862. f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
  863. " TRAIN this model on a down-stream task to be able to use it for predictions and inference."
  864. )
  865. elif len(mismatched_keys) == 0:
  866. logger.info(
  867. f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
  868. f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the checkpoint"
  869. f" was trained on, you can already use {model.__class__.__name__} for predictions without further"
  870. " training."
  871. )
  872. if len(mismatched_keys) > 0:
  873. mismatched_warning = "\n".join(
  874. [
  875. f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated"
  876. for key, shape1, shape2 in mismatched_keys
  877. ]
  878. )
  879. logger.warning(
  880. f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
  881. f" {pretrained_model_name_or_path} and are newly initialized because the shapes did not"
  882. f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be able"
  883. " to use it for predictions and inference."
  884. )
  885. # dictionary of key: dtypes for the model params
  886. param_dtypes = jax.tree_util.tree_map(lambda x: x.dtype, state)
  887. # extract keys of parameters not in jnp.float32
  888. fp16_params = [k for k in param_dtypes if param_dtypes[k] == jnp.float16]
  889. bf16_params = [k for k in param_dtypes if param_dtypes[k] == jnp.bfloat16]
  890. # raise a warning if any of the parameters are not in jnp.float32
  891. if len(fp16_params) > 0:
  892. logger.warning(
  893. f"Some of the weights of {model.__class__.__name__} were initialized in float16 precision from "
  894. f"the model checkpoint at {pretrained_model_name_or_path}:\n{fp16_params}\n"
  895. "You should probably UPCAST the model weights to float32 if this was not intended. "
  896. "See [`~FlaxPreTrainedModel.to_fp32`] for further information on how to do this."
  897. )
  898. if len(bf16_params) > 0:
  899. logger.warning(
  900. f"Some of the weights of {model.__class__.__name__} were initialized in bfloat16 precision from "
  901. f"the model checkpoint at {pretrained_model_name_or_path}:\n{bf16_params}\n"
  902. "You should probably UPCAST the model weights to float32 if this was not intended. "
  903. "See [`~FlaxPreTrainedModel.to_fp32`] for further information on how to do this."
  904. )
  905. # If it is a model with generation capabilities, attempt to load the generation config
  906. if model.can_generate():
  907. try:
  908. model.generation_config = GenerationConfig.from_pretrained(
  909. pretrained_model_name_or_path,
  910. cache_dir=cache_dir,
  911. force_download=force_download,
  912. resume_download=resume_download,
  913. proxies=proxies,
  914. local_files_only=local_files_only,
  915. token=token,
  916. revision=revision,
  917. subfolder=subfolder,
  918. _from_auto=from_auto_class,
  919. _from_pipeline=from_pipeline,
  920. **kwargs,
  921. )
  922. except OSError:
  923. logger.info(
  924. "Generation config file not found, using a generation config created from the model config."
  925. )
  926. pass
  927. if _do_init:
  928. # set correct parameters
  929. model.params = unflatten_dict(state)
  930. return model
  931. else:
  932. return model, unflatten_dict(state)
  933. def save_pretrained(
  934. self,
  935. save_directory: Union[str, os.PathLike],
  936. params=None,
  937. push_to_hub=False,
  938. max_shard_size="10GB",
  939. token: Optional[Union[str, bool]] = None,
  940. safe_serialization: bool = False,
  941. **kwargs,
  942. ):
  943. """
  944. Save a model and its configuration file to a directory, so that it can be re-loaded using the
  945. `[`~FlaxPreTrainedModel.from_pretrained`]` class method
  946. Arguments:
  947. save_directory (`str` or `os.PathLike`):
  948. Directory to which to save. Will be created if it doesn't exist.
  949. push_to_hub (`bool`, *optional*, defaults to `False`):
  950. Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
  951. repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
  952. namespace).
  953. max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`):
  954. The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
  955. lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
  956. <Tip warning={true}>
  957. If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
  958. which will be bigger than `max_shard_size`.
  959. </Tip>
  960. token (`str` or `bool`, *optional*):
  961. The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
  962. the token generated when running `hf auth login` (stored in `~/.huggingface`).
  963. kwargs (`dict[str, Any]`, *optional*):
  964. Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
  965. safe_serialization (`bool`, *optional*, defaults to `False`):
  966. Whether to save the model using `safetensors` or through msgpack.
  967. """
  968. use_auth_token = kwargs.pop("use_auth_token", None)
  969. if use_auth_token is not None:
  970. warnings.warn(
  971. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  972. FutureWarning,
  973. )
  974. if token is not None:
  975. raise ValueError(
  976. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  977. )
  978. token = use_auth_token
  979. if token is not None:
  980. kwargs["token"] = token
  981. if os.path.isfile(save_directory):
  982. logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
  983. return
  984. os.makedirs(save_directory, exist_ok=True)
  985. if push_to_hub:
  986. commit_message = kwargs.pop("commit_message", None)
  987. repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
  988. repo_id = self._create_repo(repo_id, **kwargs)
  989. files_timestamps = self._get_files_timestamps(save_directory)
  990. # get abs dir
  991. save_directory = os.path.abspath(save_directory)
  992. # save config as well
  993. self.config.architectures = [self.__class__.__name__[4:]]
  994. # If we have a custom model, we copy the file defining it in the folder and set the attributes so it can be
  995. # loaded from the Hub.
  996. if self._auto_class is not None:
  997. custom_object_save(self, save_directory, config=self.config)
  998. self.config.save_pretrained(save_directory)
  999. if self.can_generate():
  1000. self.generation_config.save_pretrained(save_directory)
  1001. # save model
  1002. weights_name = SAFE_WEIGHTS_NAME if safe_serialization else FLAX_WEIGHTS_NAME
  1003. output_model_file = os.path.join(save_directory, weights_name)
  1004. shards, index = flax_shard_checkpoint(params if params is not None else self.params, max_shard_size)
  1005. # Clean the folder from a previous save
  1006. for filename in os.listdir(save_directory):
  1007. full_filename = os.path.join(save_directory, filename)
  1008. weights_no_suffix = weights_name.replace(".bin", "").replace(".safetensors", "")
  1009. if filename.startswith(weights_no_suffix) and os.path.isfile(full_filename) and filename not in shards:
  1010. os.remove(full_filename)
  1011. if index is None:
  1012. if safe_serialization:
  1013. params = params if params is not None else self.params
  1014. flat_dict = flatten_dict(params, sep=".")
  1015. safe_save_file(flat_dict, output_model_file, metadata={"format": "flax"})
  1016. else:
  1017. with open(output_model_file, "wb") as f:
  1018. params = params if params is not None else self.params
  1019. model_bytes = to_bytes(params)
  1020. f.write(model_bytes)
  1021. else:
  1022. save_index_file = os.path.join(save_directory, FLAX_WEIGHTS_INDEX_NAME)
  1023. # Save the index as well
  1024. with open(save_index_file, "w", encoding="utf-8") as f:
  1025. content = json.dumps(index, indent=2, sort_keys=True) + "\n"
  1026. f.write(content)
  1027. logger.info(
  1028. f"The model is bigger than the maximum size per checkpoint ({max_shard_size}) and is going to be "
  1029. f"split in {len(shards)} checkpoint shards. You can find where each parameters has been saved in the "
  1030. f"index located at {save_index_file}."
  1031. )
  1032. for shard_file, shard in shards.items():
  1033. # the shard item are unflattened, to save them we need to flatten them again
  1034. with open(os.path.join(save_directory, shard_file), mode="wb") as f:
  1035. params = unflatten_dict(shard, sep="/")
  1036. shard_bytes = to_bytes(params)
  1037. f.write(shard_bytes)
  1038. logger.info(f"Model weights saved in {output_model_file}")
  1039. if push_to_hub:
  1040. self._upload_modified_files(
  1041. save_directory,
  1042. repo_id,
  1043. files_timestamps,
  1044. commit_message=commit_message,
  1045. token=token,
  1046. )
  1047. @classmethod
  1048. def register_for_auto_class(cls, auto_class="FlaxAutoModel"):
  1049. """
  1050. Register this class with a given auto class. This should only be used for custom models as the ones in the
  1051. library are already mapped with an auto class.
  1052. Args:
  1053. auto_class (`str` or `type`, *optional*, defaults to `"FlaxAutoModel"`):
  1054. The auto class to register this new model with.
  1055. """
  1056. if not isinstance(auto_class, str):
  1057. auto_class = auto_class.__name__
  1058. import transformers.models.auto as auto_module
  1059. if not hasattr(auto_module, auto_class):
  1060. raise ValueError(f"{auto_class} is not a valid auto class.")
  1061. cls._auto_class = auto_class
  1062. # To update the docstring, we need to copy the method, otherwise we change the original docstring.
  1063. FlaxPreTrainedModel.push_to_hub = copy_func(FlaxPreTrainedModel.push_to_hub)
  1064. if FlaxPreTrainedModel.push_to_hub.__doc__ is not None:
  1065. FlaxPreTrainedModel.push_to_hub.__doc__ = FlaxPreTrainedModel.push_to_hub.__doc__.format(
  1066. object="model", object_class="FlaxAutoModel", object_files="model checkpoint"
  1067. )
  1068. def overwrite_call_docstring(model_class, docstring):
  1069. # copy __call__ function to be sure docstring is changed only for this function
  1070. model_class.__call__ = copy_func(model_class.__call__)
  1071. # delete existing docstring
  1072. model_class.__call__.__doc__ = None
  1073. # set correct docstring
  1074. model_class.__call__ = add_start_docstrings_to_model_forward(docstring)(model_class.__call__)
  1075. def append_call_sample_docstring(
  1076. model_class, checkpoint, output_type, config_class, mask=None, revision=None, real_checkpoint=None
  1077. ):
  1078. model_class.__call__ = copy_func(model_class.__call__)
  1079. model_class.__call__ = add_code_sample_docstrings(
  1080. checkpoint=checkpoint,
  1081. output_type=output_type,
  1082. config_class=config_class,
  1083. model_cls=model_class.__name__,
  1084. revision=revision,
  1085. real_checkpoint=real_checkpoint,
  1086. )(model_class.__call__)
  1087. def append_replace_return_docstrings(model_class, output_type, config_class):
  1088. model_class.__call__ = copy_func(model_class.__call__)
  1089. model_class.__call__ = replace_return_docstrings(
  1090. output_type=output_type,
  1091. config_class=config_class,
  1092. )(model_class.__call__)