pipeline_utils.py 9.74 KB
Newer Older
Patrick von Platen's avatar
Patrick von Platen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# coding=utf-8
# Copyright 2022 The HuggingFace Inc. team.
# Copyright (c) 2022, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Patrick von Platen's avatar
improve  
Patrick von Platen committed
17
import importlib
18
import inspect
Patrick von Platen's avatar
Patrick von Platen committed
19
20
import os
from typing import Optional, Union
anton-l's avatar
Style  
anton-l committed
21

Patrick von Platen's avatar
up  
Patrick von Platen committed
22
from huggingface_hub import snapshot_download
23
from PIL import Image
Patrick von Platen's avatar
Patrick von Platen committed
24

Patrick von Platen's avatar
Patrick von Platen committed
25
from .configuration_utils import ConfigMixin
Patrick von Platen's avatar
Patrick von Platen committed
26
from .utils import DIFFUSERS_CACHE, logging
Patrick von Platen's avatar
improve  
Patrick von Platen committed
27

Patrick von Platen's avatar
Patrick von Platen committed
28

Patrick von Platen's avatar
Patrick von Platen committed
29
INDEX_FILE = "diffusion_pytorch_model.bin"
Patrick von Platen's avatar
Patrick von Platen committed
30
31
32
33
34
35
36


logger = logging.get_logger(__name__)


LOADABLE_CLASSES = {
    "diffusers": {
Patrick von Platen's avatar
Patrick von Platen committed
37
        "ModelMixin": ["save_pretrained", "from_pretrained"],
Patrick von Platen's avatar
Patrick von Platen committed
38
        "SchedulerMixin": ["save_config", "from_config"],
Patrick von Platen's avatar
Patrick von Platen committed
39
        "DiffusionPipeline": ["save_pretrained", "from_pretrained"],
Patrick von Platen's avatar
Patrick von Platen committed
40
41
    },
    "transformers": {
anton-l's avatar
anton-l committed
42
        "PreTrainedTokenizer": ["save_pretrained", "from_pretrained"],
43
        "PreTrainedTokenizerFast": ["save_pretrained", "from_pretrained"],
anton-l's avatar
anton-l committed
44
        "PreTrainedModel": ["save_pretrained", "from_pretrained"],
Patrick von Platen's avatar
Patrick von Platen committed
45
46
47
    },
}

48
49
50
51
ALL_IMPORTABLE_CLASSES = {}
for library in LOADABLE_CLASSES:
    ALL_IMPORTABLE_CLASSES.update(LOADABLE_CLASSES[library])

Patrick von Platen's avatar
Patrick von Platen committed
52

Patrick von Platen's avatar
Patrick von Platen committed
53
class DiffusionPipeline(ConfigMixin):
Patrick von Platen's avatar
Patrick von Platen committed
54
55
56

    config_name = "model_index.json"

Patrick von Platen's avatar
up  
Patrick von Platen committed
57
    def register_modules(self, **kwargs):
58
59
        # import it here to avoid circular import
        from diffusers import pipelines
60

Patrick von Platen's avatar
Patrick von Platen committed
61
62
63
        for name, module in kwargs.items():
            # retrive library
            library = module.__module__.split(".")[0]
64

65
66
67
68
69
            # check if the module is a pipeline module
            pipeline_file = module.__module__.split(".")[-1]
            pipeline_dir = module.__module__.split(".")[-2]
            is_pipeline_module = pipeline_file == "pipeline_" + pipeline_dir and hasattr(pipelines, pipeline_dir)

70
71
            # if library is not in LOADABLE_CLASSES, then it is a custom module.
            # Or if it's a pipeline module, then the module is inside the pipeline
72
            # folder so we set the library to module name.
73
            if library not in LOADABLE_CLASSES or is_pipeline_module:
74
                library = pipeline_dir
patil-suraj's avatar
patil-suraj committed
75

Patrick von Platen's avatar
Patrick von Platen committed
76
77
78
            # retrive class_name
            class_name = module.__class__.__name__

79
80
            register_dict = {name: (library, class_name)}

Patrick von Platen's avatar
Patrick von Platen committed
81
            # save model index config
82
            self.register_to_config(**register_dict)
Patrick von Platen's avatar
Patrick von Platen committed
83
84
85

            # set models
            setattr(self, name, module)
86

Patrick von Platen's avatar
Patrick von Platen committed
87
88
89
    def save_pretrained(self, save_directory: Union[str, os.PathLike]):
        self.save_config(save_directory)

Patrick von Platen's avatar
Patrick von Platen committed
90
        model_index_dict = dict(self.config)
Patrick von Platen's avatar
Patrick von Platen committed
91
        model_index_dict.pop("_class_name")
92
        model_index_dict.pop("_diffusers_version")
93
        model_index_dict.pop("_module", None)
Patrick von Platen's avatar
Patrick von Platen committed
94

anton-l's avatar
anton-l committed
95
96
97
        for pipeline_component_name in model_index_dict.keys():
            sub_model = getattr(self, pipeline_component_name)
            model_cls = sub_model.__class__
Patrick von Platen's avatar
Patrick von Platen committed
98
99

            save_method_name = None
anton-l's avatar
anton-l committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
            # search for the model's base class in LOADABLE_CLASSES
            for library_name, library_classes in LOADABLE_CLASSES.items():
                library = importlib.import_module(library_name)
                for base_class, save_load_methods in library_classes.items():
                    class_candidate = getattr(library, base_class)
                    if issubclass(model_cls, class_candidate):
                        # if we found a suitable base class in LOADABLE_CLASSES then grab its save method
                        save_method_name = save_load_methods[0]
                        break
                if save_method_name is not None:
                    break

            save_method = getattr(sub_model, save_method_name)
            save_method(os.path.join(save_directory, pipeline_component_name))
Patrick von Platen's avatar
Patrick von Platen committed
114
115
116

    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
117
        r"""
Patrick von Platen's avatar
Patrick von Platen committed
118
        Add docstrings
119
120
121
122
123
124
        """
        cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
        resume_download = kwargs.pop("resume_download", False)
        proxies = kwargs.pop("proxies", None)
        local_files_only = kwargs.pop("local_files_only", False)
        use_auth_token = kwargs.pop("use_auth_token", None)
125
        revision = kwargs.pop("revision", None)
Patrick von Platen's avatar
Patrick von Platen committed
126

patil-suraj's avatar
patil-suraj committed
127
        # 1. Download the checkpoints and configs
Patrick von Platen's avatar
Patrick von Platen committed
128
        # use snapshot download here to get it working from from_pretrained
Patrick von Platen's avatar
Patrick von Platen committed
129
        if not os.path.isdir(pretrained_model_name_or_path):
130
131
132
133
134
135
136
            cached_folder = snapshot_download(
                pretrained_model_name_or_path,
                cache_dir=cache_dir,
                resume_download=resume_download,
                proxies=proxies,
                local_files_only=local_files_only,
                use_auth_token=use_auth_token,
137
                revision=revision,
138
            )
Patrick von Platen's avatar
Patrick von Platen committed
139
140
        else:
            cached_folder = pretrained_model_name_or_path
141

patil-suraj's avatar
patil-suraj committed
142
        config_dict = cls.get_config_dict(cached_folder)
143

Patrick von Platen's avatar
Patrick von Platen committed
144
        # 2. Load the pipeline class, if using custom module then load it from the hub
145
146
        # if we load from explicit class, let's use it
        if cls != DiffusionPipeline:
147
148
            pipeline_class = cls
        else:
Patrick von Platen's avatar
Patrick von Platen committed
149
150
151
            diffusers_module = importlib.import_module(cls.__module__.split(".")[0])
            pipeline_class = getattr(diffusers_module, config_dict["_class_name"])

152
153
154
155
156
157
        # some modules can be passed directly to the init
        # in this case they are already instantiated in `kwargs`
        # extract them here
        expected_modules = set(inspect.signature(pipeline_class.__init__).parameters.keys())
        passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}

158
        init_dict, _ = pipeline_class.extract_init_dict(config_dict, **kwargs)
Patrick von Platen's avatar
Patrick von Platen committed
159
160

        init_kwargs = {}
161

162
163
        # import it here to avoid circular import
        from diffusers import pipelines
164

Patrick von Platen's avatar
Patrick von Platen committed
165
        # 3. Load each module in the pipeline
patil-suraj's avatar
patil-suraj committed
166
        for name, (library_name, class_name) in init_dict.items():
167
            is_pipeline_module = hasattr(pipelines, library_name)
168
169
            loaded_sub_model = None

170
            # if the model is in a pipeline module, then we load it from the pipeline
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
            if name in passed_class_obj:
                # 1. check that passed_class_obj has correct parent class
                if not is_pipeline_module:
                    library = importlib.import_module(library_name)
                    class_obj = getattr(library, class_name)
                    importable_classes = LOADABLE_CLASSES[library_name]
                    class_candidates = {c: getattr(library, c) for c in importable_classes.keys()}

                    expected_class_obj = None
                    for class_name, class_candidate in class_candidates.items():
                        if issubclass(class_obj, class_candidate):
                            expected_class_obj = class_candidate

                    if not issubclass(passed_class_obj[name].__class__, expected_class_obj):
                        raise ValueError(
                            f"{passed_class_obj[name]} is of type: {type(passed_class_obj[name])}, but should be"
                            f" {expected_class_obj}"
                        )
                else:
                    logger.warn(
                        f"You have passed a non-standard module {passed_class_obj[name]}. We cannot verify whether it"
                        " has the correct type"
                    )

                # set passed class object
                loaded_sub_model = passed_class_obj[name]
            elif is_pipeline_module:
198
199
200
                pipeline_module = getattr(pipelines, library_name)
                class_obj = getattr(pipeline_module, class_name)
                importable_classes = ALL_IMPORTABLE_CLASSES
Patrick von Platen's avatar
Patrick von Platen committed
201
                class_candidates = {c: class_obj for c in importable_classes.keys()}
patil-suraj's avatar
patil-suraj committed
202
            else:
patil-suraj's avatar
patil-suraj committed
203
                # else we just import it from the library.
patil-suraj's avatar
patil-suraj committed
204
205
                library = importlib.import_module(library_name)
                class_obj = getattr(library, class_name)
206
                importable_classes = LOADABLE_CLASSES[library_name]
patil-suraj's avatar
patil-suraj committed
207
                class_candidates = {c: getattr(library, c) for c in importable_classes.keys()}
208

209
210
211
212
213
            if loaded_sub_model is None:
                load_method_name = None
                for class_name, class_candidate in class_candidates.items():
                    if issubclass(class_obj, class_candidate):
                        load_method_name = importable_classes[class_name][1]
Patrick von Platen's avatar
Patrick von Platen committed
214

215
                load_method = getattr(class_obj, load_method_name)
Patrick von Platen's avatar
Patrick von Platen committed
216

217
218
219
220
221
222
                # check if the module is in a subdirectory
                if os.path.isdir(os.path.join(cached_folder, name)):
                    loaded_sub_model = load_method(os.path.join(cached_folder, name))
                else:
                    # else load from the root directory
                    loaded_sub_model = load_method(cached_folder)
Patrick von Platen's avatar
Patrick von Platen committed
223

224
            init_kwargs[name] = loaded_sub_model  # UNet(...), # DiffusionSchedule(...)
Patrick von Platen's avatar
Patrick von Platen committed
225

226
        # 4. Instantiate the pipeline
227
        model = pipeline_class(**init_kwargs)
Patrick von Platen's avatar
Patrick von Platen committed
228
        return model
229
230
231
232
233
234
235
236
237
238
239
240

    @staticmethod
    def numpy_to_pil(images):
        """
        Convert a numpy image or a batch of images to a PIL image.
        """
        if images.ndim == 3:
            images = images[None, ...]
        images = (images * 255).round().astype("uint8")
        pil_images = [Image.fromarray(image) for image in images]

        return pil_images