pipeline_utils.py 7.77 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
Patrick von Platen's avatar
Patrick von Platen committed
18
19
import os
from typing import Optional, Union
anton-l's avatar
Style  
anton-l committed
20

Patrick von Platen's avatar
up  
Patrick von Platen committed
21
from huggingface_hub import snapshot_download
Patrick von Platen's avatar
Patrick von Platen committed
22

Patrick von Platen's avatar
Patrick von Platen committed
23
from .configuration_utils import ConfigMixin
patil-suraj's avatar
patil-suraj committed
24
from .dynamic_modules_utils import get_class_from_dynamic_module
Patrick von Platen's avatar
Patrick von Platen committed
25
from .utils import DIFFUSERS_CACHE, logging
Patrick von Platen's avatar
improve  
Patrick von Platen committed
26

Patrick von Platen's avatar
Patrick von Platen committed
27
28
29
30
31
32
33
34
35

INDEX_FILE = "diffusion_model.pt"


logger = logging.get_logger(__name__)


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

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

Patrick von Platen's avatar
Patrick von Platen committed
54

Patrick von Platen's avatar
Patrick von Platen committed
55
class DiffusionPipeline(ConfigMixin):
Patrick von Platen's avatar
Patrick von Platen committed
56
57
58

    config_name = "model_index.json"

Patrick von Platen's avatar
up  
Patrick von Platen committed
59
    def register_modules(self, **kwargs):
Patrick von Platen's avatar
Patrick von Platen committed
60
61
62
        for name, module in kwargs.items():
            # retrive library
            library = module.__module__.split(".")[0]
patil-suraj's avatar
patil-suraj committed
63
64
65
66
            # if library is not in LOADABLE_CLASSES, then it is a custom module
            if library not in LOADABLE_CLASSES:
                library = module.__module__.split(".")[-1]

Patrick von Platen's avatar
Patrick von Platen committed
67
68
69
            # retrive class_name
            class_name = module.__class__.__name__

70
71
            register_dict = {name: (library, class_name)}

Patrick von Platen's avatar
Patrick von Platen committed
72
            # save model index config
73
            self.register(**register_dict)
Patrick von Platen's avatar
Patrick von Platen committed
74
75
76

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

Patrick von Platen's avatar
Patrick von Platen committed
78
        register_dict = {"_module": self.__module__.split(".")[-1]}
79
        self.register(**register_dict)
Patrick von Platen's avatar
Patrick von Platen committed
80
81
82
83

    def save_pretrained(self, save_directory: Union[str, os.PathLike]):
        self.save_config(save_directory)

84
        model_index_dict = self.config
Patrick von Platen's avatar
Patrick von Platen committed
85
        model_index_dict.pop("_class_name")
86
        model_index_dict.pop("_diffusers_version")
87
        model_index_dict.pop("_module")
Patrick von Platen's avatar
Patrick von Platen committed
88

anton-l's avatar
anton-l committed
89
90
91
        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
92
93

            save_method_name = None
anton-l's avatar
anton-l committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
            # 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
108
109
110

    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
111
        r"""
Patrick von Platen's avatar
Patrick von Platen committed
112
        Add docstrings
113
114
115
116
117
118
        """
        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)
Patrick von Platen's avatar
Patrick von Platen committed
119

patil-suraj's avatar
patil-suraj committed
120
        # 1. Download the checkpoints and configs
Patrick von Platen's avatar
Patrick von Platen committed
121
        # use snapshot download here to get it working from from_pretrained
Patrick von Platen's avatar
Patrick von Platen committed
122
        if not os.path.isdir(pretrained_model_name_or_path):
123
124
125
126
127
128
129
130
            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,
            )
Patrick von Platen's avatar
Patrick von Platen committed
131
132
        else:
            cached_folder = pretrained_model_name_or_path
133

patil-suraj's avatar
patil-suraj committed
134
        config_dict = cls.get_config_dict(cached_folder)
135

patil-suraj's avatar
patil-suraj committed
136
        # 2. Get class name and module candidates to load custom models
Patrick von Platen's avatar
Patrick von Platen committed
137
138
        module_candidate_name = config_dict["_module"]
        module_candidate = module_candidate_name + ".py"
Patrick von Platen's avatar
fix  
Patrick von Platen committed
139

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

            # (TODO - we should allow to load custom pipelines
149
            # else we need to load the correct module from the Hub
Patrick von Platen's avatar
Patrick von Platen committed
150
151
            # module = module_candidate
            # pipeline_class = get_class_from_dynamic_module(cached_folder, module, class_name_, cached_folder)
152

153
        init_dict, _ = pipeline_class.extract_init_dict(config_dict, **kwargs)
Patrick von Platen's avatar
Patrick von Platen committed
154
155
156

        init_kwargs = {}

patil-suraj's avatar
patil-suraj committed
157
        # 4. Load each module in the pipeline
patil-suraj's avatar
patil-suraj committed
158
        for name, (library_name, class_name) in init_dict.items():
patil-suraj's avatar
patil-suraj committed
159
160
161
            # if the model is not in diffusers or transformers, we need to load it from the hub
            # assumes that it's a subclass of ModelMixin
            if library_name == module_candidate_name:
patil-suraj's avatar
patil-suraj committed
162
                class_obj = get_class_from_dynamic_module(cached_folder, module_candidate, class_name, cached_folder)
163
                # since it's not from a library, we need to check class candidates for all importable classes
164
165
                importable_classes = ALL_IMPORTABLE_CLASSES
                class_candidates = {c: class_obj for c in ALL_IMPORTABLE_CLASSES.keys()}
patil-suraj's avatar
patil-suraj committed
166
            else:
patil-suraj's avatar
patil-suraj committed
167
                # else we just import it from the library.
patil-suraj's avatar
patil-suraj committed
168
169
                library = importlib.import_module(library_name)
                class_obj = getattr(library, class_name)
170
                importable_classes = LOADABLE_CLASSES[library_name]
patil-suraj's avatar
patil-suraj committed
171
                class_candidates = {c: getattr(library, c) for c in importable_classes.keys()}
172

173
174
175
176
            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
177
178
179

            load_method = getattr(class_obj, load_method_name)

patil-suraj's avatar
patil-suraj committed
180
            # check if the module is in a subdirectory
Patrick von Platen's avatar
Patrick von Platen committed
181
            if os.path.isdir(os.path.join(cached_folder, name)):
182
183
                loaded_sub_model = load_method(os.path.join(cached_folder, name))
            else:
patil-suraj's avatar
patil-suraj committed
184
                # else load from the root directory
185
                loaded_sub_model = load_method(cached_folder)
Patrick von Platen's avatar
Patrick von Platen committed
186

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

patil-suraj's avatar
patil-suraj committed
189
        # 5. Instantiate the pipeline
190
        model = pipeline_class(**init_kwargs)
Patrick von Platen's avatar
Patrick von Platen committed
191
        return model