"vscode:/vscode.git/clone" did not exist on "d50baf0c632342b9576a24352244c4235ce8b875"
pipeline_utils.py 7.33 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

23
from .utils import logging, DIFFUSERS_CACHE
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
patil-suraj's avatar
patil-suraj committed
26
from .dynamic_modules_utils import get_class_from_dynamic_module
Patrick von Platen's avatar
improve  
Patrick von Platen committed
27

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

INDEX_FILE = "diffusion_model.pt"


logger = logging.get_logger(__name__)


LOADABLE_CLASSES = {
    "diffusers": {
Patrick von Platen's avatar
Patrick von Platen committed
37
        "ModelMixin": ["save_pretrained", "from_pretrained"],
38
        "CLIPTextModel": ["save_pretrained", "from_pretrained"],  # TODO (Anton): move to transformers
Patrick von Platen's avatar
improve  
Patrick von Platen committed
39
        "GaussianDDPMScheduler": ["save_config", "from_config"],
40
        "ClassifierFreeGuidanceScheduler": ["save_config", "from_config"],
41
        "GlideDDIMScheduler": ["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"],
Patrick von Platen's avatar
Patrick von Platen committed
45
46
47
48
    },
}


Patrick von Platen's avatar
Patrick von Platen committed
49
class DiffusionPipeline(ConfigMixin):
Patrick von Platen's avatar
Patrick von Platen committed
50
51
52

    config_name = "model_index.json"

Patrick von Platen's avatar
up  
Patrick von Platen committed
53
    def register_modules(self, **kwargs):
Patrick von Platen's avatar
Patrick von Platen committed
54
55
56
        for name, module in kwargs.items():
            # retrive library
            library = module.__module__.split(".")[0]
patil-suraj's avatar
patil-suraj committed
57
58
59
60
            # 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
61
62
63
            # retrive class_name
            class_name = module.__class__.__name__

64
65
            register_dict = {name: (library, class_name)}

Patrick von Platen's avatar
Patrick von Platen committed
66
            # save model index config
67
            self.register(**register_dict)
Patrick von Platen's avatar
Patrick von Platen committed
68
69
70

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

anton-l's avatar
Style  
anton-l committed
72
        register_dict = {"_module": self.__module__.split(".")[-1] + ".py"}
73
        self.register(**register_dict)
Patrick von Platen's avatar
Patrick von Platen committed
74
75
76
77

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

78
        model_index_dict = self.config
Patrick von Platen's avatar
Patrick von Platen committed
79
        model_index_dict.pop("_class_name")
80
        model_index_dict.pop("_diffusers_version")
81
        model_index_dict.pop("_module")
Patrick von Platen's avatar
Patrick von Platen committed
82

83
        for name, (library_name, class_name) in model_index_dict.items():
Patrick von Platen's avatar
Patrick von Platen committed
84
85
            importable_classes = LOADABLE_CLASSES[library_name]

86
87
88
89
            # TODO: Suraj
            if library_name == self.__module__:
                library_name = self

Patrick von Platen's avatar
Patrick von Platen committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
            library = importlib.import_module(library_name)
            class_obj = getattr(library, class_name)
            class_candidates = {c: getattr(library, c) for c in importable_classes.keys()}

            save_method_name = None
            for class_name, class_candidate in class_candidates.items():
                if issubclass(class_obj, class_candidate):
                    save_method_name = importable_classes[class_name][0]

            save_method = getattr(getattr(self, name), save_method_name)
            save_method(os.path.join(save_directory, name))

    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
104
105
106
107
108
109
110
111
112
113
114
        r"""
            Add docstrings
        """
        cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
        force_download = kwargs.pop("force_download", False)
        resume_download = kwargs.pop("resume_download", False)
        proxies = kwargs.pop("proxies", None)
        output_loading_info = kwargs.pop("output_loading_info", False)
        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
115
        # use snapshot download here to get it working from from_pretrained
Patrick von Platen's avatar
Patrick von Platen committed
116
        if not os.path.isdir(pretrained_model_name_or_path):
117
118
119
120
121
122
123
124
125
126
            cached_folder = snapshot_download(
                pretrained_model_name_or_path,
                cache_dir=cache_dir,
                force_download=force_download,
                resume_download=resume_download,
                proxies=proxies,
                output_loading_info=output_loading_info,
                local_files_only=local_files_only,
                use_auth_token=use_auth_token,
            )
Patrick von Platen's avatar
Patrick von Platen committed
127
128
        else:
            cached_folder = pretrained_model_name_or_path
129

patil-suraj's avatar
patil-suraj committed
130
        config_dict = cls.get_config_dict(cached_folder)
131

patil-suraj's avatar
patil-suraj committed
132
133
        module = config_dict["_module"]
        class_name_ = config_dict["_class_name"]
Patrick von Platen's avatar
fix  
Patrick von Platen committed
134
        module_candidate = config_dict["_module"]
patil-suraj's avatar
patil-suraj committed
135
        module_candidate_name = module_candidate.replace(".py", "")
136

137
138
        # if we load from explicit class, let's use it
        if cls != DiffusionPipeline:
139
140
            pipeline_class = cls
        else:
141
142
            # else we need to load the correct module from the Hub
            class_name_ = config_dict["_class_name"]
Patrick von Platen's avatar
fix  
Patrick von Platen committed
143
            module = module_candidate
144
            pipeline_class = get_class_from_dynamic_module(cached_folder, module, class_name_, cached_folder)
145

146
        init_dict, _ = pipeline_class.extract_init_dict(config_dict, **kwargs)
Patrick von Platen's avatar
Patrick von Platen committed
147
148
149

        init_kwargs = {}

150
        # get all importable classes to get the load method name for custom models/components
Patrick von Platen's avatar
merge  
Patrick von Platen committed
151
        # here we enforce that custom models/components should always subclass from base classes in tansformers and diffusers
152
153
154
        all_importable_classes = {}
        for library in LOADABLE_CLASSES:
            all_importable_classes.update(LOADABLE_CLASSES[library])
155

patil-suraj's avatar
patil-suraj committed
156
        for name, (library_name, class_name) in init_dict.items():
patil-suraj's avatar
patil-suraj committed
157
158
159
160
            # 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:
                class_obj = get_class_from_dynamic_module(cached_folder, module, class_name, cached_folder)
161
162
163
                # since it's not from a library, we need to check class candidates for all importable classes
                importable_classes = all_importable_classes
                class_candidates = {c: class_obj for c in all_importable_classes}
patil-suraj's avatar
patil-suraj committed
164
165
166
            else:
                library = importlib.import_module(library_name)
                class_obj = getattr(library, class_name)
167
                importable_classes = LOADABLE_CLASSES[library_name]
patil-suraj's avatar
patil-suraj committed
168
                class_candidates = {c: getattr(library, c) for c in importable_classes.keys()}
Patrick von Platen's avatar
Patrick von Platen committed
169
170
171
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]

            load_method = getattr(class_obj, load_method_name)

Patrick von Platen's avatar
Patrick von Platen committed
177
            if os.path.isdir(os.path.join(cached_folder, name)):
178
179
180
                loaded_sub_model = load_method(os.path.join(cached_folder, name))
            else:
                loaded_sub_model = load_method(cached_folder)
Patrick von Platen's avatar
Patrick von Platen committed
181

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

184
        model = pipeline_class(**init_kwargs)
Patrick von Platen's avatar
Patrick von Platen committed
185
        return model