|
| 1 | +# Copyright 2025 The HuggingFace Team. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import importlib |
| 16 | +import os |
| 17 | +from typing import Optional, Union |
| 18 | + |
| 19 | +from huggingface_hub.utils import validate_hf_hub_args |
| 20 | + |
| 21 | +from ..configuration_utils import ConfigMixin |
| 22 | + |
| 23 | + |
| 24 | +class AutoModel(ConfigMixin): |
| 25 | + config_name = "config.json" |
| 26 | + |
| 27 | + def __init__(self, *args, **kwargs): |
| 28 | + raise EnvironmentError( |
| 29 | + f"{self.__class__.__name__} is designed to be instantiated " |
| 30 | + f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or " |
| 31 | + f"`{self.__class__.__name__}.from_pipe(pipeline)` methods." |
| 32 | + ) |
| 33 | + |
| 34 | + @classmethod |
| 35 | + @validate_hf_hub_args |
| 36 | + def from_pretrained(cls, pretrained_model_or_path: Optional[Union[str, os.PathLike]] = None, **kwargs): |
| 37 | + r""" |
| 38 | + Instantiate a pretrained PyTorch model from a pretrained model configuration. |
| 39 | +
|
| 40 | + The model is set in evaluation mode - `model.eval()` - by default, and dropout modules are deactivated. To |
| 41 | + train the model, set it back in training mode with `model.train()`. |
| 42 | +
|
| 43 | + Parameters: |
| 44 | + pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*): |
| 45 | + Can be either: |
| 46 | +
|
| 47 | + - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on |
| 48 | + the Hub. |
| 49 | + - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved |
| 50 | + with [`~ModelMixin.save_pretrained`]. |
| 51 | +
|
| 52 | + cache_dir (`Union[str, os.PathLike]`, *optional*): |
| 53 | + Path to a directory where a downloaded pretrained model configuration is cached if the standard cache |
| 54 | + is not used. |
| 55 | + torch_dtype (`str` or `torch.dtype`, *optional*): |
| 56 | + Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the |
| 57 | + dtype is automatically derived from the model's weights. |
| 58 | + force_download (`bool`, *optional*, defaults to `False`): |
| 59 | + Whether or not to force the (re-)download of the model weights and configuration files, overriding the |
| 60 | + cached versions if they exist. |
| 61 | + proxies (`Dict[str, str]`, *optional*): |
| 62 | + A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128', |
| 63 | + 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. |
| 64 | + output_loading_info (`bool`, *optional*, defaults to `False`): |
| 65 | + Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages. |
| 66 | + local_files_only(`bool`, *optional*, defaults to `False`): |
| 67 | + Whether to only load local model weights and configuration files or not. If set to `True`, the model |
| 68 | + won't be downloaded from the Hub. |
| 69 | + token (`str` or *bool*, *optional*): |
| 70 | + The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from |
| 71 | + `diffusers-cli login` (stored in `~/.huggingface`) is used. |
| 72 | + revision (`str`, *optional*, defaults to `"main"`): |
| 73 | + The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier |
| 74 | + allowed by Git. |
| 75 | + from_flax (`bool`, *optional*, defaults to `False`): |
| 76 | + Load the model weights from a Flax checkpoint save file. |
| 77 | + subfolder (`str`, *optional*, defaults to `""`): |
| 78 | + The subfolder location of a model file within a larger model repository on the Hub or locally. |
| 79 | + mirror (`str`, *optional*): |
| 80 | + Mirror source to resolve accessibility issues if you're downloading a model in China. We do not |
| 81 | + guarantee the timeliness or safety of the source, and you should refer to the mirror site for more |
| 82 | + information. |
| 83 | + device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*): |
| 84 | + A map that specifies where each submodule should go. It doesn't need to be defined for each |
| 85 | + parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the |
| 86 | + same device. Defaults to `None`, meaning that the model will be loaded on CPU. |
| 87 | +
|
| 88 | + Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For |
| 89 | + more information about each option see [designing a device |
| 90 | + map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map). |
| 91 | + max_memory (`Dict`, *optional*): |
| 92 | + A dictionary device identifier for the maximum memory. Will default to the maximum memory available for |
| 93 | + each GPU and the available CPU RAM if unset. |
| 94 | + offload_folder (`str` or `os.PathLike`, *optional*): |
| 95 | + The path to offload weights if `device_map` contains the value `"disk"`. |
| 96 | + offload_state_dict (`bool`, *optional*): |
| 97 | + If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if |
| 98 | + the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True` |
| 99 | + when there is some disk offload. |
| 100 | + low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`): |
| 101 | + Speed up model loading only loading the pretrained weights and not initializing the weights. This also |
| 102 | + tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model. |
| 103 | + Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this |
| 104 | + argument to `True` will raise an error. |
| 105 | + variant (`str`, *optional*): |
| 106 | + Load weights from a specified `variant` filename such as `"fp16"` or `"ema"`. This is ignored when |
| 107 | + loading `from_flax`. |
| 108 | + use_safetensors (`bool`, *optional*, defaults to `None`): |
| 109 | + If set to `None`, the `safetensors` weights are downloaded if they're available **and** if the |
| 110 | + `safetensors` library is installed. If set to `True`, the model is forcibly loaded from `safetensors` |
| 111 | + weights. If set to `False`, `safetensors` weights are not loaded. |
| 112 | + disable_mmap ('bool', *optional*, defaults to 'False'): |
| 113 | + Whether to disable mmap when loading a Safetensors model. This option can perform better when the model |
| 114 | + is on a network mount or hard drive, which may not handle the seeky-ness of mmap very well. |
| 115 | +
|
| 116 | + <Tip> |
| 117 | +
|
| 118 | + To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with |
| 119 | + `huggingface-cli login`. You can also activate the special |
| 120 | + ["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use this method in a |
| 121 | + firewalled environment. |
| 122 | +
|
| 123 | + </Tip> |
| 124 | +
|
| 125 | + Example: |
| 126 | +
|
| 127 | + ```py |
| 128 | + from diffusers import AutoModel |
| 129 | +
|
| 130 | + unet = AutoModel.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="unet") |
| 131 | + ``` |
| 132 | +
|
| 133 | + If you get the error message below, you need to finetune the weights for your downstream task: |
| 134 | +
|
| 135 | + ```bash |
| 136 | + Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match: |
| 137 | + - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated |
| 138 | + You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference. |
| 139 | + ``` |
| 140 | + """ |
| 141 | + cache_dir = kwargs.pop("cache_dir", None) |
| 142 | + force_download = kwargs.pop("force_download", False) |
| 143 | + proxies = kwargs.pop("proxies", None) |
| 144 | + token = kwargs.pop("token", None) |
| 145 | + local_files_only = kwargs.pop("local_files_only", False) |
| 146 | + revision = kwargs.pop("revision", None) |
| 147 | + subfolder = kwargs.pop("subfolder", None) |
| 148 | + |
| 149 | + load_config_kwargs = { |
| 150 | + "cache_dir": cache_dir, |
| 151 | + "force_download": force_download, |
| 152 | + "proxies": proxies, |
| 153 | + "token": token, |
| 154 | + "local_files_only": local_files_only, |
| 155 | + "revision": revision, |
| 156 | + "subfolder": subfolder, |
| 157 | + } |
| 158 | + |
| 159 | + config = cls.load_config(pretrained_model_or_path, **load_config_kwargs) |
| 160 | + orig_class_name = config["_class_name"] |
| 161 | + |
| 162 | + library = importlib.import_module("diffusers") |
| 163 | + |
| 164 | + model_cls = getattr(library, orig_class_name, None) |
| 165 | + if model_cls is None: |
| 166 | + raise ValueError(f"AutoModel can't find a model linked to {orig_class_name}.") |
| 167 | + |
| 168 | + kwargs = {**load_config_kwargs, **kwargs} |
| 169 | + return model_cls.from_pretrained(pretrained_model_or_path, **kwargs) |
0 commit comments