CoolFace
Apppublic

declare-lab/tango2

sourceHugging Faceupdated 2y agoView on Hugging Face
92likes
modeling_utils.py778 linesDownload Raw Back to models
1# coding=utf-82# Copyright 2023 The HuggingFace Inc. team.3# Copyright (c) 2022, NVIDIA CORPORATION.  All rights reserved.4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9#     http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16 17import inspect18import os19from functools import partial20from typing import Callable, List, Optional, Tuple, Union21 22import torch23from torch import Tensor, device24 25from .. import __version__26from ..utils import (27    CONFIG_NAME,28    DIFFUSERS_CACHE,29    FLAX_WEIGHTS_NAME,30    HF_HUB_OFFLINE,31    SAFETENSORS_WEIGHTS_NAME,32    WEIGHTS_NAME,33    _add_variant,34    _get_model_file,35    is_accelerate_available,36    is_safetensors_available,37    is_torch_version,38    logging,39)40 41 42logger = logging.get_logger(__name__)43 44 45if is_torch_version(">=", "1.9.0"):46    _LOW_CPU_MEM_USAGE_DEFAULT = True47else:48    _LOW_CPU_MEM_USAGE_DEFAULT = False49 50 51if is_accelerate_available():52    import accelerate53    from accelerate.utils import set_module_tensor_to_device54    from accelerate.utils.versions import is_torch_version55 56if is_safetensors_available():57    import safetensors58 59 60def get_parameter_device(parameter: torch.nn.Module):61    try:62        return next(parameter.parameters()).device63    except StopIteration:64        # For torch.nn.DataParallel compatibility in PyTorch 1.565 66        def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:67            tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]68            return tuples69 70        gen = parameter._named_members(get_members_fn=find_tensor_attributes)71        first_tuple = next(gen)72        return first_tuple[1].device73 74 75def get_parameter_dtype(parameter: torch.nn.Module):76    try:77        return next(parameter.parameters()).dtype78    except StopIteration:79        # For torch.nn.DataParallel compatibility in PyTorch 1.580 81        def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:82            tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]83            return tuples84 85        gen = parameter._named_members(get_members_fn=find_tensor_attributes)86        first_tuple = next(gen)87        return first_tuple[1].dtype88 89 90def load_state_dict(checkpoint_file: Union[str, os.PathLike], variant: Optional[str] = None):91    """92    Reads a checkpoint file, returning properly formatted errors if they arise.93    """94    try:95        if os.path.basename(checkpoint_file) == _add_variant(WEIGHTS_NAME, variant):96            return torch.load(checkpoint_file, map_location="cpu")97        else:98            return safetensors.torch.load_file(checkpoint_file, device="cpu")99    except Exception as e:100        try:101            with open(checkpoint_file) as f:102                if f.read().startswith("version"):103                    raise OSError(104                        "You seem to have cloned a repository without having git-lfs installed. Please install "105                        "git-lfs and run `git lfs install` followed by `git lfs pull` in the folder "106                        "you cloned."107                    )108                else:109                    raise ValueError(110                        f"Unable to locate the file {checkpoint_file} which is necessary to load this pretrained "111                        "model. Make sure you have saved the model properly."112                    ) from e113        except (UnicodeDecodeError, ValueError):114            raise OSError(115                f"Unable to load weights from checkpoint file for '{checkpoint_file}' "116                f"at '{checkpoint_file}'. "117                "If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True."118            )119 120 121def _load_state_dict_into_model(model_to_load, state_dict):122    # Convert old format to new format if needed from a PyTorch state_dict123    # copy state_dict so _load_from_state_dict can modify it124    state_dict = state_dict.copy()125    error_msgs = []126 127    # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants128    # so we need to apply the function recursively.129    def load(module: torch.nn.Module, prefix=""):130        args = (state_dict, prefix, {}, True, [], [], error_msgs)131        module._load_from_state_dict(*args)132 133        for name, child in module._modules.items():134            if child is not None:135                load(child, prefix + name + ".")136 137    load(model_to_load)138 139    return error_msgs140 141 142class ModelMixin(torch.nn.Module):143    r"""144    Base class for all models.145 146    [`ModelMixin`] takes care of storing the configuration of the models and handles methods for loading, downloading147    and saving models.148 149        - **config_name** ([`str`]) -- A filename under which the model should be stored when calling150          [`~models.ModelMixin.save_pretrained`].151    """152    config_name = CONFIG_NAME153    _automatically_saved_args = ["_diffusers_version", "_class_name", "_name_or_path"]154    _supports_gradient_checkpointing = False155 156    def __init__(self):157        super().__init__()158 159    @property160    def is_gradient_checkpointing(self) -> bool:161        """162        Whether gradient checkpointing is activated for this model or not.163 164        Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint165        activations".166        """167        return any(hasattr(m, "gradient_checkpointing") and m.gradient_checkpointing for m in self.modules())168 169    def enable_gradient_checkpointing(self):170        """171        Activates gradient checkpointing for the current model.172 173        Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint174        activations".175        """176        if not self._supports_gradient_checkpointing:177            raise ValueError(f"{self.__class__.__name__} does not support gradient checkpointing.")178        self.apply(partial(self._set_gradient_checkpointing, value=True))179 180    def disable_gradient_checkpointing(self):181        """182        Deactivates gradient checkpointing for the current model.183 184        Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint185        activations".186        """187        if self._supports_gradient_checkpointing:188            self.apply(partial(self._set_gradient_checkpointing, value=False))189 190    def set_use_memory_efficient_attention_xformers(191        self, valid: bool, attention_op: Optional[Callable] = None192    ) -> None:193        # Recursively walk through all the children.194        # Any children which exposes the set_use_memory_efficient_attention_xformers method195        # gets the message196        def fn_recursive_set_mem_eff(module: torch.nn.Module):197            if hasattr(module, "set_use_memory_efficient_attention_xformers"):198                module.set_use_memory_efficient_attention_xformers(valid, attention_op)199 200            for child in module.children():201                fn_recursive_set_mem_eff(child)202 203        for module in self.children():204            if isinstance(module, torch.nn.Module):205                fn_recursive_set_mem_eff(module)206 207    def enable_xformers_memory_efficient_attention(self, attention_op: Optional[Callable] = None):208        r"""209        Enable memory efficient attention as implemented in xformers.210 211        When this option is enabled, you should observe lower GPU memory usage and a potential speed up at inference212        time. Speed up at training time is not guaranteed.213 214        Warning: When Memory Efficient Attention and Sliced attention are both enabled, the Memory Efficient Attention215        is used.216 217        Parameters:218            attention_op (`Callable`, *optional*):219                Override the default `None` operator for use as `op` argument to the220                [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention)221                function of xFormers.222 223        Examples:224 225        ```py226        >>> import torch227        >>> from diffusers import UNet2DConditionModel228        >>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp229 230        >>> model = UNet2DConditionModel.from_pretrained(231        ...     "stabilityai/stable-diffusion-2-1", subfolder="unet", torch_dtype=torch.float16232        ... )233        >>> model = model.to("cuda")234        >>> model.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)235        ```236        """237        self.set_use_memory_efficient_attention_xformers(True, attention_op)238 239    def disable_xformers_memory_efficient_attention(self):240        r"""241        Disable memory efficient attention as implemented in xformers.242        """243        self.set_use_memory_efficient_attention_xformers(False)244 245    def save_pretrained(246        self,247        save_directory: Union[str, os.PathLike],248        is_main_process: bool = True,249        save_function: Callable = None,250        safe_serialization: bool = False,251        variant: Optional[str] = None,252    ):253        """254        Save a model and its configuration file to a directory, so that it can be re-loaded using the255        `[`~models.ModelMixin.from_pretrained`]` class method.256 257        Arguments:258            save_directory (`str` or `os.PathLike`):259                Directory to which to save. Will be created if it doesn't exist.260            is_main_process (`bool`, *optional*, defaults to `True`):261                Whether the process calling this is the main process or not. Useful when in distributed training like262                TPUs and need to call this function on all processes. In this case, set `is_main_process=True` only on263                the main process to avoid race conditions.264            save_function (`Callable`):265                The function to use to save the state dictionary. Useful on distributed training like TPUs when one266                need to replace `torch.save` by another method. Can be configured with the environment variable267                `DIFFUSERS_SAVE_MODE`.268            safe_serialization (`bool`, *optional*, defaults to `False`):269                Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).270            variant (`str`, *optional*):271                If specified, weights are saved in the format pytorch_model.<variant>.bin.272        """273        if safe_serialization and not is_safetensors_available():274            raise ImportError("`safe_serialization` requires the `safetensors library: `pip install safetensors`.")275 276        if os.path.isfile(save_directory):277            logger.error(f"Provided path ({save_directory}) should be a directory, not a file")278            return279 280        os.makedirs(save_directory, exist_ok=True)281 282        model_to_save = self283 284        # Attach architecture to the config285        # Save the config286        if is_main_process:287            model_to_save.save_config(save_directory)288 289        # Save the model290        state_dict = model_to_save.state_dict()291 292        weights_name = SAFETENSORS_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME293        weights_name = _add_variant(weights_name, variant)294 295        # Save the model296        if safe_serialization:297            safetensors.torch.save_file(298                state_dict, os.path.join(save_directory, weights_name), metadata={"format": "pt"}299            )300        else:301            torch.save(state_dict, os.path.join(save_directory, weights_name))302 303        logger.info(f"Model weights saved in {os.path.join(save_directory, weights_name)}")304 305    @classmethod306    def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):307        r"""308        Instantiate a pretrained pytorch model from a pre-trained model configuration.309 310        The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train311        the model, you should first set it back in training mode with `model.train()`.312 313        The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come314        pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning315        task.316 317        The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those318        weights are discarded.319 320        Parameters:321            pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):322                Can be either:323 324                    - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.325                      Valid model ids should have an organization name, like `google/ddpm-celebahq-256`.326                    - A path to a *directory* containing model weights saved using [`~ModelMixin.save_config`], e.g.,327                      `./my_model_directory/`.328 329            cache_dir (`Union[str, os.PathLike]`, *optional*):330                Path to a directory in which a downloaded pretrained model configuration should be cached if the331                standard cache should not be used.332            torch_dtype (`str` or `torch.dtype`, *optional*):333                Override the default `torch.dtype` and load the model under this dtype. If `"auto"` is passed the dtype334                will be automatically derived from the model's weights.335            force_download (`bool`, *optional*, defaults to `False`):336                Whether or not to force the (re-)download of the model weights and configuration files, overriding the337                cached versions if they exist.338            resume_download (`bool`, *optional*, defaults to `False`):339                Whether or not to delete incompletely received files. Will attempt to resume the download if such a340                file exists.341            proxies (`Dict[str, str]`, *optional*):342                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',343                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.344            output_loading_info(`bool`, *optional*, defaults to `False`):345                Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.346            local_files_only(`bool`, *optional*, defaults to `False`):347                Whether or not to only look at local files (i.e., do not try to download the model).348            use_auth_token (`str` or *bool*, *optional*):349                The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated350                when running `diffusers-cli login` (stored in `~/.huggingface`).351            revision (`str`, *optional*, defaults to `"main"`):352                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a353                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any354                identifier allowed by git.355            from_flax (`bool`, *optional*, defaults to `False`):356                Load the model weights from a Flax checkpoint save file.357            subfolder (`str`, *optional*, defaults to `""`):358                In case the relevant files are located inside a subfolder of the model repo (either remote in359                huggingface.co or downloaded locally), you can specify the folder name here.360 361            mirror (`str`, *optional*):362                Mirror source to accelerate downloads in China. If you are from China and have an accessibility363                problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety.364                Please refer to the mirror site for more information.365            device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):366                A map that specifies where each submodule should go. It doesn't need to be refined to each367                parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the368                same device.369 370                To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For371                more information about each option see [designing a device372                map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).373            low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):374                Speed up model loading by not initializing the weights and only loading the pre-trained weights. This375                also tries to not use more than 1x model size in CPU memory (including peak memory) while loading the376                model. This is only supported when torch version >= 1.9.0. If you are using an older version of torch,377                setting this argument to `True` will raise an error.378            variant (`str`, *optional*):379                If specified load weights from `variant` filename, *e.g.* pytorch_model.<variant>.bin. `variant` is380                ignored when using `from_flax`.381            use_safetensors (`bool`, *optional* ):382                If set to `True`, the pipeline will forcibly load the models from `safetensors` weights. If set to383                `None` (the default). The pipeline will load using `safetensors` if safetensors weights are available384                *and* if `safetensors` is installed. If the to `False` the pipeline will *not* use `safetensors`.385 386        <Tip>387 388         It is required to be logged in (`huggingface-cli login`) when you want to use private or [gated389         models](https://huggingface.co/docs/hub/models-gated#gated-models).390 391        </Tip>392 393        <Tip>394 395        Activate the special ["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use396        this method in a firewalled environment.397 398        </Tip>399 400        """401        cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)402        ignore_mismatched_sizes = kwargs.pop("ignore_mismatched_sizes", False)403        force_download = kwargs.pop("force_download", False)404        from_flax = kwargs.pop("from_flax", False)405        resume_download = kwargs.pop("resume_download", False)406        proxies = kwargs.pop("proxies", None)407        output_loading_info = kwargs.pop("output_loading_info", False)408        local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)409        use_auth_token = kwargs.pop("use_auth_token", None)410        revision = kwargs.pop("revision", None)411        torch_dtype = kwargs.pop("torch_dtype", None)412        subfolder = kwargs.pop("subfolder", None)413        device_map = kwargs.pop("device_map", None)414        low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)415        variant = kwargs.pop("variant", None)416        use_safetensors = kwargs.pop("use_safetensors", None)417 418        if use_safetensors and not is_safetensors_available():419            raise ValueError(420                "`use_safetensors`=True but safetensors is not installed. Please install safetensors with `pip install safetenstors"421            )422 423        allow_pickle = False424        if use_safetensors is None:425            use_safetensors = is_safetensors_available()426            allow_pickle = True427 428        if low_cpu_mem_usage and not is_accelerate_available():429            low_cpu_mem_usage = False430            logger.warning(431                "Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"432                " environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"433                " `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"434                " install accelerate\n```\n."435            )436 437        if device_map is not None and not is_accelerate_available():438            raise NotImplementedError(439                "Loading and dispatching requires `accelerate`. Please make sure to install accelerate or set"440                " `device_map=None`. You can install accelerate with `pip install accelerate`."441            )442 443        # Check if we can handle device_map and dispatching the weights444        if device_map is not None and not is_torch_version(">=", "1.9.0"):445            raise NotImplementedError(446                "Loading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set"447                " `device_map=None`."448            )449 450        if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):451            raise NotImplementedError(452                "Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"453                " `low_cpu_mem_usage=False`."454            )455 456        if low_cpu_mem_usage is False and device_map is not None:457            raise ValueError(458                f"You cannot set `low_cpu_mem_usage` to `False` while using device_map={device_map} for loading and"459                " dispatching. Please make sure to set `low_cpu_mem_usage=True`."460            )461 462        # Load config if we don't provide a configuration463        config_path = pretrained_model_name_or_path464 465        user_agent = {466            "diffusers": __version__,467            "file_type": "model",468            "framework": "pytorch",469        }470 471        # load config472        config, unused_kwargs, commit_hash = cls.load_config(473            config_path,474            cache_dir=cache_dir,475            return_unused_kwargs=True,476            return_commit_hash=True,477            force_download=force_download,478            resume_download=resume_download,479            proxies=proxies,480            local_files_only=local_files_only,481            use_auth_token=use_auth_token,482            revision=revision,483            subfolder=subfolder,484            device_map=device_map,485            user_agent=user_agent,486            **kwargs,487        )488 489        # load model490        model_file = None491        if from_flax:492            model_file = _get_model_file(493                pretrained_model_name_or_path,494                weights_name=FLAX_WEIGHTS_NAME,495                cache_dir=cache_dir,496                force_download=force_download,497                resume_download=resume_download,498                proxies=proxies,499                local_files_only=local_files_only,500                use_auth_token=use_auth_token,501                revision=revision,502                subfolder=subfolder,503                user_agent=user_agent,504                commit_hash=commit_hash,505            )506            model = cls.from_config(config, **unused_kwargs)507 508            # Convert the weights509            from .modeling_pytorch_flax_utils import load_flax_checkpoint_in_pytorch_model510 511            model = load_flax_checkpoint_in_pytorch_model(model, model_file)512        else:513            if use_safetensors:514                try:515                    model_file = _get_model_file(516                        pretrained_model_name_or_path,517                        weights_name=_add_variant(SAFETENSORS_WEIGHTS_NAME, variant),518                        cache_dir=cache_dir,519                        force_download=force_download,520                        resume_download=resume_download,521                        proxies=proxies,522                        local_files_only=local_files_only,523                        use_auth_token=use_auth_token,524                        revision=revision,525                        subfolder=subfolder,526                        user_agent=user_agent,527                        commit_hash=commit_hash,528                    )529                except IOError as e:530                    if not allow_pickle:531                        raise e532                    pass533            if model_file is None:534                model_file = _get_model_file(535                    pretrained_model_name_or_path,536                    weights_name=_add_variant(WEIGHTS_NAME, variant),537                    cache_dir=cache_dir,538                    force_download=force_download,539                    resume_download=resume_download,540                    proxies=proxies,541                    local_files_only=local_files_only,542                    use_auth_token=use_auth_token,543                    revision=revision,544                    subfolder=subfolder,545                    user_agent=user_agent,546                    commit_hash=commit_hash,547                )548 549            if low_cpu_mem_usage:550                # Instantiate model with empty weights551                with accelerate.init_empty_weights():552                    model = cls.from_config(config, **unused_kwargs)553 554                # if device_map is None, load the state dict and move the params from meta device to the cpu555                if device_map is None:556                    param_device = "cpu"557                    state_dict = load_state_dict(model_file, variant=variant)558                    # move the params from meta device to cpu559                    missing_keys = set(model.state_dict().keys()) - set(state_dict.keys())560                    if len(missing_keys) > 0:561                        raise ValueError(562                            f"Cannot load {cls} from {pretrained_model_name_or_path} because the following keys are"563                            f" missing: \n {', '.join(missing_keys)}. \n Please make sure to pass"564                            " `low_cpu_mem_usage=False` and `device_map=None` if you want to randomly initialize"565                            " those weights or else make sure your checkpoint file is correct."566                        )567 568                    empty_state_dict = model.state_dict()569                    for param_name, param in state_dict.items():570                        accepts_dtype = "dtype" in set(571                            inspect.signature(set_module_tensor_to_device).parameters.keys()572                        )573 574                        if empty_state_dict[param_name].shape != param.shape:575                            raise ValueError(576                                f"Cannot load {pretrained_model_name_or_path} because {param_name} expected shape {empty_state_dict[param_name]}, but got {param.shape}. If you want to instead overwrite randomly initialized weights, please make sure to pass both `low_cpu_mem_usage=False` and `ignore_mismatched_sizes=True`. For more information, see also: https://github.com/huggingface/diffusers/issues/1619#issuecomment-1345604389 as an example."577                            )578 579                        if accepts_dtype:580                            set_module_tensor_to_device(581                                model, param_name, param_device, value=param, dtype=torch_dtype582                            )583                        else:584                            set_module_tensor_to_device(model, param_name, param_device, value=param)585                else:  # else let accelerate handle loading and dispatching.586                    # Load weights and dispatch according to the device_map587                    # by default the device_map is None and the weights are loaded on the CPU588                    accelerate.load_checkpoint_and_dispatch(model, model_file, device_map, dtype=torch_dtype)589 590                loading_info = {591                    "missing_keys": [],592                    "unexpected_keys": [],593                    "mismatched_keys": [],594                    "error_msgs": [],595                }596            else:597                model = cls.from_config(config, **unused_kwargs)598 599                state_dict = load_state_dict(model_file, variant=variant)600 601                model, missing_keys, unexpected_keys, mismatched_keys, error_msgs = cls._load_pretrained_model(602                    model,603                    state_dict,604                    model_file,605                    pretrained_model_name_or_path,606                    ignore_mismatched_sizes=ignore_mismatched_sizes,607                )608 609                loading_info = {610                    "missing_keys": missing_keys,611                    "unexpected_keys": unexpected_keys,612                    "mismatched_keys": mismatched_keys,613                    "error_msgs": error_msgs,614                }615 616        if torch_dtype is not None and not isinstance(torch_dtype, torch.dtype):617            raise ValueError(618                f"{torch_dtype} needs to be of type `torch.dtype`, e.g. `torch.float16`, but is {type(torch_dtype)}."619            )620        elif torch_dtype is not None:621            model = model.to(torch_dtype)622 623        model.register_to_config(_name_or_path=pretrained_model_name_or_path)624 625        # Set model in evaluation mode to deactivate DropOut modules by default626        model.eval()627        if output_loading_info:628            return model, loading_info629 630        return model631 632    @classmethod633    def _load_pretrained_model(634        cls,635        model,636        state_dict,637        resolved_archive_file,638        pretrained_model_name_or_path,639        ignore_mismatched_sizes=False,640    ):641        # Retrieve missing & unexpected_keys642        model_state_dict = model.state_dict()643        loaded_keys = list(state_dict.keys())644 645        expected_keys = list(model_state_dict.keys())646 647        original_loaded_keys = loaded_keys648 649        missing_keys = list(set(expected_keys) - set(loaded_keys))650        unexpected_keys = list(set(loaded_keys) - set(expected_keys))651 652        # Make sure we are able to load base models as well as derived models (with heads)653        model_to_load = model654 655        def _find_mismatched_keys(656            state_dict,657            model_state_dict,658            loaded_keys,659            ignore_mismatched_sizes,660        ):661            mismatched_keys = []662            if ignore_mismatched_sizes:663                for checkpoint_key in loaded_keys:664                    model_key = checkpoint_key665 666                    if (667                        model_key in model_state_dict668                        and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape669                    ):670                        mismatched_keys.append(671                            (checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape)672                        )673                        del state_dict[checkpoint_key]674            return mismatched_keys675 676        if state_dict is not None:677            # Whole checkpoint678            mismatched_keys = _find_mismatched_keys(679                state_dict,680                model_state_dict,681                original_loaded_keys,682                ignore_mismatched_sizes,683            )684            error_msgs = _load_state_dict_into_model(model_to_load, state_dict)685 686        if len(error_msgs) > 0:687            error_msg = "\n\t".join(error_msgs)688            if "size mismatch" in error_msg:689                error_msg += (690                    "\n\tYou may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method."691                )692            raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}")693 694        if len(unexpected_keys) > 0:695            logger.warning(696                f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"697                f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"698                f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task"699                " or with another architecture (e.g. initializing a BertForSequenceClassification model from a"700                " BertForPreTraining model).\n- This IS NOT expected if you are initializing"701                f" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly"702                " identical (initializing a BertForSequenceClassification model from a"703                " BertForSequenceClassification model)."704            )705        else:706            logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")707        if len(missing_keys) > 0:708            logger.warning(709                f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"710                f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"711                " TRAIN this model on a down-stream task to be able to use it for predictions and inference."712            )713        elif len(mismatched_keys) == 0:714            logger.info(715                f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"716                f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the"717                f" checkpoint was trained on, you can already use {model.__class__.__name__} for predictions"718                " without further training."719            )720        if len(mismatched_keys) > 0:721            mismatched_warning = "\n".join(722                [723                    f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated"724                    for key, shape1, shape2 in mismatched_keys725                ]726            )727            logger.warning(728                f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"729                f" {pretrained_model_name_or_path} and are newly initialized because the shapes did not"730                f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be"731                " able to use it for predictions and inference."732            )733 734        return model, missing_keys, unexpected_keys, mismatched_keys, error_msgs735 736    @property737    def device(self) -> device:738        """739        `torch.device`: The device on which the module is (assuming that all the module parameters are on the same740        device).741        """742        return get_parameter_device(self)743 744    @property745    def dtype(self) -> torch.dtype:746        """747        `torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).748        """749        return get_parameter_dtype(self)750 751    def num_parameters(self, only_trainable: bool = False, exclude_embeddings: bool = False) -> int:752        """753        Get number of (optionally, trainable or non-embeddings) parameters in the module.754 755        Args:756            only_trainable (`bool`, *optional*, defaults to `False`):757                Whether or not to return only the number of trainable parameters758 759            exclude_embeddings (`bool`, *optional*, defaults to `False`):760                Whether or not to return only the number of non-embeddings parameters761 762        Returns:763            `int`: The number of parameters.764        """765 766        if exclude_embeddings:767            embedding_param_names = [768                f"{name}.weight"769                for name, module_type in self.named_modules()770                if isinstance(module_type, torch.nn.Embedding)771            ]772            non_embedding_parameters = [773                parameter for name, parameter in self.named_parameters() if name not in embedding_param_names774            ]775            return sum(p.numel() for p in non_embedding_parameters if p.requires_grad or not only_trainable)776        else:777            return sum(p.numel() for p in self.parameters() if p.requires_grad or not only_trainable)778