deinferno commited on
Commit
2c9efe6
1 Parent(s): 2e1c614

Upload model, inference pipeline and example

Browse files
README.md CHANGED
@@ -1,3 +1,77 @@
1
  ---
2
  license: mit
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ language:
4
+ - en
5
+ pipeline_tag: text-to-image
6
+ tags:
7
+ - openvino
8
+ - text-to-image
9
  ---
10
+
11
+ Model Descriptions:
12
+
13
+ This repo contains OpenVino model files for [SimianLuo's LCM_Dreamshaper_v7](https://huggingface.co/SimianLuo/LCM_Dreamshaper_v7).
14
+
15
+ Generation Results:
16
+
17
+ By converting model to OpenVino format and using Intel(R) Xeon(R) Gold 5220R CPU @ 2.20GHz 24C/48T x 2 we can achieve following results compared to original PyTorch LCM.
18
+
19
+ Results time includes first compile and reshape phases and should be taken with grain of salt because benchmark was run using 2 socketed server which can underperform in those types of workload.
20
+
21
+ Number of images per batch is set to 1
22
+
23
+ |Run No.|Pytorch|OpenVino|Openvino w/reshape|
24
+ |-------|-------|--------|------------------|
25
+ |1 |15.5841|18.0010 |13.4928 |
26
+ |2 |12.4634|5.0208 |3.6855 |
27
+ |3 |12.1551|4.9462 |3.7228 |
28
+
29
+ Number of images per batch is set to 4
30
+
31
+ |Run No.|Pytorch|OpenVino|Openvino w/reshape|
32
+ |-------|-------|--------|------------------|
33
+ |1 |31.3666|33.1488 |25.7044 |
34
+ |2 |33.4797|17.7456 |12.8295 |
35
+ |3 |28.6561|17.9216 |12.7198 |
36
+
37
+
38
+ To run the model yourself, you can leverage the 🧨 Diffusers/🤗 Optimum library:
39
+ 1. Install the library:
40
+ ```
41
+ pip install diffusers transformers accelerate optimum
42
+ pip install --upgrade-strategy eager optimum[openvino]
43
+ ```
44
+
45
+ 2. Clone inference code:
46
+ ```
47
+ git clone https://huggingface.co/deinferno/LCM_Dreamshaper_v7-openvino
48
+ cd LCM_Dreamshaper_v7-openvino
49
+ ```
50
+
51
+ 2. Run the model:
52
+ ```py
53
+ from lcm_ov_pipeline import OVLatentConsistencyModelPipeline
54
+ from lcm_scheduler import LCMScheduler
55
+
56
+ model_id = "deinferno/LCM_Dreamshaper_v7-openvino"
57
+
58
+ scheduler = LCMScheduler.from_pretrained(model_id, subfolder = "scheduler")
59
+ pipe = OVLatentConsistencyModelPipeline.from_pretrained(model_id, scheduler = scheduler, compile = False) # Enable if you don't plan to reshape and recompile
60
+
61
+ prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k"
62
+
63
+ # Can be set to 1~50 steps. LCM support fast inference even <= 4 steps. Recommend: 1~8 steps.
64
+
65
+ width = 512
66
+ height = 512
67
+ num_images = 1
68
+ batch_size = 1
69
+ num_inference_steps = 4
70
+
71
+ # Reshape and recompile for inference speed
72
+
73
+ pipe.reshape(batch_size=batch_size, height=height, width=width, num_images_per_prompt=num_images)
74
+ pipe.compile()
75
+
76
+ images = pipe(prompt=prompt, width=width, height=height, num_inference_steps=num_inference_steps, guidance_scale=8.0, lcm_origin_steps=50, output_type="pil").images
77
+ ```
convert_to_openvino.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional, Tuple, OrderedDict
2
+ from transformers import CLIPTextConfig
3
+ from diffusers import UNet2DConditionModel
4
+
5
+ import torch
6
+
7
+ from optimum.exporters.onnx.model_configs import VisionOnnxConfig, NormalizedConfig, DummyVisionInputGenerator, DummyTimestepInputGenerator, DummySeq2SeqDecoderTextInputGenerator, DummySeq2SeqDecoderTextInputGenerator
8
+ from optimum.exporters.openvino import main_export
9
+ from optimum.utils.input_generators import DummyInputGenerator, DEFAULT_DUMMY_SHAPES
10
+ from optimum.utils.normalized_config import NormalizedTextConfig
11
+
12
+ # IMPORTANT: You need to specify some scheduler in downloaded model cache folder to avoid errors
13
+
14
+ class CustomDummyTimestepInputGenerator(DummyInputGenerator):
15
+ """
16
+ Generates dummy time step inputs.
17
+ """
18
+
19
+ SUPPORTED_INPUT_NAMES = (
20
+ "timestep",
21
+ "timestep_cond",
22
+ "text_embeds",
23
+ "time_ids",
24
+ )
25
+
26
+ def __init__(
27
+ self,
28
+ task: str,
29
+ normalized_config: NormalizedConfig,
30
+ batch_size: int = DEFAULT_DUMMY_SHAPES["batch_size"],
31
+ time_cond_proj_dim: int = 256,
32
+ random_batch_size_range: Optional[Tuple[int, int]] = None,
33
+ **kwargs,
34
+ ):
35
+ self.task = task
36
+ self.vocab_size = normalized_config.vocab_size
37
+ self.text_encoder_projection_dim = normalized_config.text_encoder_projection_dim
38
+ self.time_ids = 5 if normalized_config.requires_aesthetics_score else 6
39
+ if random_batch_size_range:
40
+ low, high = random_batch_size_range
41
+ self.batch_size = random.randint(low, high)
42
+ else:
43
+ self.batch_size = batch_size
44
+ self.time_cond_proj_dim = normalized_config.get("time_cond_proj_dim", time_cond_proj_dim)
45
+
46
+ def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"):
47
+ shape = [self.batch_size]
48
+
49
+ if input_name == "timestep":
50
+ return self.random_int_tensor(shape, max_value=self.vocab_size, framework=framework, dtype=int_dtype)
51
+
52
+ if input_name == "timestep_cond":
53
+ shape.append(self.time_cond_proj_dim)
54
+ return self.random_float_tensor(shape, min_value=-1.0, max_value=1.0, framework=framework, dtype=float_dtype)
55
+
56
+
57
+ shape.append(self.text_encoder_projection_dim if input_name == "text_embeds" else self.time_ids)
58
+ return self.random_float_tensor(shape, max_value=self.vocab_size, framework=framework, dtype=float_dtype)
59
+
60
+ class LCMUNetOnnxConfig(VisionOnnxConfig):
61
+ ATOL_FOR_VALIDATION = 1e-3
62
+ # The ONNX export of a CLIPText architecture, an other Stable Diffusion component, needs the Trilu
63
+ # operator support, available since opset 14
64
+ DEFAULT_ONNX_OPSET = 14
65
+
66
+ NORMALIZED_CONFIG_CLASS = NormalizedConfig.with_args(
67
+ image_size="sample_size",
68
+ num_channels="in_channels",
69
+ hidden_size="cross_attention_dim",
70
+ vocab_size="norm_num_groups",
71
+ allow_new=True,
72
+ )
73
+
74
+ DUMMY_INPUT_GENERATOR_CLASSES = (
75
+ DummyVisionInputGenerator,
76
+ CustomDummyTimestepInputGenerator,
77
+ DummySeq2SeqDecoderTextInputGenerator,
78
+ )
79
+
80
+ @property
81
+ def inputs(self) -> Dict[str, Dict[int, str]]:
82
+ common_inputs = OrderedDict({
83
+ "sample": {0: "batch_size", 1: "num_channels", 2: "height", 3: "width"},
84
+ "timestep": {0: "steps"},
85
+ "encoder_hidden_states": {0: "batch_size", 1: "sequence_length"},
86
+ "timestep_cond": {0: "batch_size"},
87
+ })
88
+
89
+ # TODO : add text_image, image and image_embeds
90
+ if getattr(self._normalized_config, "addition_embed_type", None) == "text_time":
91
+ common_inputs["text_embeds"] = {0: "batch_size"}
92
+ common_inputs["time_ids"] = {0: "batch_size"}
93
+
94
+ return common_inputs
95
+
96
+ @property
97
+ def outputs(self) -> Dict[str, Dict[int, str]]:
98
+ return {
99
+ "out_sample": {0: "batch_size", 1: "num_channels", 2: "height", 3: "width"},
100
+ }
101
+
102
+ @property
103
+ def torch_to_onnx_output_map(self) -> Dict[str, str]:
104
+ return {
105
+ "sample": "out_sample",
106
+ }
107
+
108
+ def generate_dummy_inputs(self, framework: str = "pt", **kwargs):
109
+ dummy_inputs = super().generate_dummy_inputs(framework=framework, **kwargs)
110
+ dummy_inputs["encoder_hidden_states"] = dummy_inputs["encoder_hidden_states"][0]
111
+
112
+ if getattr(self._normalized_config, "addition_embed_type", None) == "text_time":
113
+ dummy_inputs["added_cond_kwargs"] = {
114
+ "text_embeds": dummy_inputs.pop("text_embeds"),
115
+ "time_ids": dummy_inputs.pop("time_ids"),
116
+ }
117
+
118
+ return dummy_inputs
119
+
120
+ def ordered_inputs(self, model) -> Dict[str, Dict[int, str]]:
121
+ return self.inputs # Breaks order if timestep_cond involved ( so just copy original one )
122
+
123
+ model_id = "SimianLuo/LCM_Dreamshaper_v7"
124
+
125
+ text_encoder_config = CLIPTextConfig.from_pretrained(model_id, subfolder = "text_encoder")
126
+ unet_config = UNet2DConditionModel.from_pretrained(model_id, subfolder = "unet").config
127
+
128
+ unet_config.text_encoder_projection_dim = text_encoder_config.projection_dim
129
+ unet_config.requires_aesthetics_score = False
130
+
131
+ custom_onnx_configs = {
132
+ "unet": LCMUNetOnnxConfig(config = unet_config, task = "semantic-segmentation")
133
+ }
134
+
135
+ main_export(model_name_or_path = model_id, output = "./", task = "stable-diffusion", fp16 = False, int8 = False, custom_onnx_configs = custom_onnx_configs)
feature_extractor/preprocessor_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": {
3
+ "height": 224,
4
+ "width": 224
5
+ },
6
+ "do_center_crop": true,
7
+ "do_convert_rgb": true,
8
+ "do_normalize": true,
9
+ "do_rescale": true,
10
+ "do_resize": true,
11
+ "feature_extractor_type": "CLIPFeatureExtractor",
12
+ "image_mean": [
13
+ 0.48145466,
14
+ 0.4578275,
15
+ 0.40821073
16
+ ],
17
+ "image_processor_type": "CLIPImageProcessor",
18
+ "image_std": [
19
+ 0.26862954,
20
+ 0.26130258,
21
+ 0.27577711
22
+ ],
23
+ "resample": 3,
24
+ "rescale_factor": 0.00392156862745098,
25
+ "size": {
26
+ "shortest_edge": 224
27
+ }
28
+ }
lcm_ov_pipeline.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+
3
+ from pathlib import Path
4
+ from tempfile import TemporaryDirectory
5
+ from typing import List, Optional, Tuple, Union, Dict, Any, Callable, OrderedDict
6
+
7
+ import numpy as np
8
+ import openvino
9
+ import torch
10
+
11
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
12
+ from optimum.intel.openvino.modeling_diffusion import OVStableDiffusionPipeline, OVModelUnet
13
+
14
+ from diffusers import logging
15
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
16
+
17
+ class LCMOVModelUnet(OVModelUnet):
18
+ def __call__(
19
+ self,
20
+ sample: np.ndarray,
21
+ timestep: np.ndarray,
22
+ encoder_hidden_states: np.ndarray,
23
+ timestep_cond: Optional[np.ndarray] = None,
24
+ text_embeds: Optional[np.ndarray] = None,
25
+ time_ids: Optional[np.ndarray] = None,
26
+ ):
27
+ self._compile()
28
+
29
+ inputs = {
30
+ "sample": sample,
31
+ "timestep": timestep,
32
+ "encoder_hidden_states": encoder_hidden_states,
33
+ }
34
+
35
+ if timestep_cond is not None:
36
+ inputs["timestep_cond"] = timestep_cond
37
+ if text_embeds is not None:
38
+ inputs["text_embeds"] = text_embeds
39
+ if time_ids is not None:
40
+ inputs["time_ids"] = time_ids
41
+
42
+ outputs = self.request(inputs, shared_memory=True)
43
+ return list(outputs.values())
44
+
45
+ class OVLatentConsistencyModelPipeline(OVStableDiffusionPipeline):
46
+ def __init__(
47
+ self,
48
+ vae_decoder: openvino.runtime.Model,
49
+ text_encoder: openvino.runtime.Model,
50
+ unet: openvino.runtime.Model,
51
+ config: Dict[str, Any],
52
+ tokenizer: "CLIPTokenizer",
53
+ scheduler: Union["DDIMScheduler", "PNDMScheduler", "LMSDiscreteScheduler"],
54
+ feature_extractor: Optional["CLIPFeatureExtractor"] = None,
55
+ vae_encoder: Optional[openvino.runtime.Model] = None,
56
+ text_encoder_2: Optional[openvino.runtime.Model] = None,
57
+ tokenizer_2: Optional["CLIPTokenizer"] = None,
58
+ device: str = "CPU",
59
+ dynamic_shapes: bool = True,
60
+ compile: bool = True,
61
+ ov_config: Optional[Dict[str, str]] = None,
62
+ model_save_dir: Optional[Union[str, Path, TemporaryDirectory]] = None,
63
+ **kwargs,
64
+ ):
65
+ super().__init__(vae_decoder, text_encoder, unet, config, tokenizer, scheduler, feature_extractor, vae_encoder, text_encoder_2, tokenizer_2, device, dynamic_shapes, compile, ov_config, model_save_dir, **kwargs)
66
+
67
+ self.unet = LCMOVModelUnet(unet, self)
68
+
69
+ def _reshape_unet(
70
+ self,
71
+ model: openvino.runtime.Model,
72
+ batch_size: int = -1,
73
+ height: int = -1,
74
+ width: int = -1,
75
+ num_images_per_prompt: int = -1,
76
+ tokenizer_max_length: int = -1,
77
+ ):
78
+ if batch_size == -1 or num_images_per_prompt == -1:
79
+ batch_size = -1
80
+ else:
81
+ batch_size = batch_size * num_images_per_prompt
82
+
83
+ height = height // self.vae_scale_factor if height > 0 else height
84
+ width = width // self.vae_scale_factor if width > 0 else width
85
+ shapes = {}
86
+ for inputs in model.inputs:
87
+ shapes[inputs] = inputs.get_partial_shape()
88
+ if inputs.get_any_name() == "timestep":
89
+ shapes[inputs][0] = 1
90
+ elif inputs.get_any_name() == "sample":
91
+ in_channels = self.unet.config.get("in_channels", None)
92
+ if in_channels is None:
93
+ in_channels = shapes[inputs][1]
94
+ if in_channels.is_dynamic:
95
+ logger.warning(
96
+ "Could not identify `in_channels` from the unet configuration, to statically reshape the unet please provide a configuration."
97
+ )
98
+ self.is_dynamic = True
99
+
100
+ shapes[inputs] = [batch_size, in_channels, height, width]
101
+ elif inputs.get_any_name() == "timestep_cond":
102
+ shapes[inputs] = [batch_size, inputs.get_partial_shape()[1]]
103
+ elif inputs.get_any_name() == "text_embeds":
104
+ shapes[inputs] = [batch_size, self.text_encoder_2.config["projection_dim"]]
105
+ elif inputs.get_any_name() == "time_ids":
106
+ shapes[inputs] = [batch_size, inputs.get_partial_shape()[1]]
107
+ else:
108
+ shapes[inputs][0] = batch_size
109
+ shapes[inputs][1] = tokenizer_max_length
110
+ model.reshape(shapes)
111
+ return model
112
+
113
+
114
+ def _encode_prompt(
115
+ self,
116
+ prompt: Union[str, List[str]],
117
+ num_images_per_prompt: Optional[int],
118
+ prompt_embeds: Optional[np.ndarray] = None,
119
+ ):
120
+ r"""
121
+ Encodes the prompt into text encoder hidden states.
122
+
123
+ Args:
124
+ prompt (`str` or `List[str]`):
125
+ prompt to be encoded
126
+ num_images_per_prompt (`int`):
127
+ number of images that should be generated per prompt
128
+ prompt_embeds (`np.ndarray`, *optional*):
129
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
130
+ provided, text embeddings will be generated from `prompt` input argument.
131
+ """
132
+ if prompt is not None and isinstance(prompt, str):
133
+ batch_size = 1
134
+ elif prompt is not None and isinstance(prompt, list):
135
+ batch_size = len(prompt)
136
+ else:
137
+ batch_size = prompt_embeds.shape[0]
138
+
139
+ if prompt_embeds is None:
140
+ # get prompt text embeddings
141
+ text_inputs = self.tokenizer(
142
+ prompt,
143
+ padding="max_length",
144
+ max_length=self.tokenizer.model_max_length,
145
+ truncation=True,
146
+ return_tensors="np",
147
+ )
148
+ text_input_ids = text_inputs.input_ids
149
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids
150
+
151
+ if not np.array_equal(text_input_ids, untruncated_ids):
152
+ removed_text = self.tokenizer.batch_decode(
153
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
154
+ )
155
+ logger.warning(
156
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
157
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
158
+ )
159
+
160
+ prompt_embeds = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0]
161
+
162
+ bs_embed, seq_len, _ = prompt_embeds.shape
163
+
164
+ prompt_embeds = np.tile(prompt_embeds, [1, num_images_per_prompt, 1])
165
+ prompt_embeds = np.reshape(prompt_embeds, [bs_embed * num_images_per_prompt, seq_len, -1])
166
+
167
+ return prompt_embeds
168
+
169
+ def get_w_embedding(self, w, embedding_dim=512, dtype=np.float32):
170
+ """
171
+ see https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
172
+ Args:
173
+ timesteps: np.array: generate embedding vectors at these timesteps
174
+ embedding_dim: int: dimension of the embeddings to generate
175
+ dtype: data type of the generated embeddings
176
+
177
+ Returns:
178
+ embedding vectors with shape `(len(timesteps), embedding_dim)`
179
+ """
180
+ assert len(w.shape) == 1
181
+ w = w * 1000.
182
+
183
+ half_dim = embedding_dim // 2
184
+ emb = np.log(np.array(10000.)) / (half_dim - 1)
185
+ emb = np.exp(np.arange(half_dim, dtype=dtype) * -emb)
186
+ emb = w.astype(dtype)[:, None] * emb[None, :]
187
+ emb = np.concatenate([np.sin(emb), np.cos(emb)], axis=1)
188
+ if embedding_dim % 2 == 1: # zero pad
189
+ emb = np.pad(emb, (0, 1))
190
+ assert emb.shape == (w.shape[0], embedding_dim)
191
+ return emb
192
+
193
+ # Adapted from https://github.com/huggingface/optimum/blob/15b8d1eed4d83c5004d3b60f6b6f13744b358f01/optimum/pipelines/diffusers/pipeline_stable_diffusion.py#L201
194
+ def __call__(
195
+ self,
196
+ prompt: Optional[Union[str, List[str]]] = None,
197
+ height: Optional[int] = None,
198
+ width: Optional[int] = None,
199
+ num_inference_steps: int = 4,
200
+ lcm_origin_steps: int = 50,
201
+ guidance_scale: float = 7.5,
202
+ num_images_per_prompt: int = 1,
203
+ eta: float = 0.0,
204
+ generator: Optional[np.random.RandomState] = None,
205
+ latents: Optional[np.ndarray] = None,
206
+ prompt_embeds: Optional[np.ndarray] = None,
207
+ output_type: str = "pil",
208
+ return_dict: bool = True,
209
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
210
+ callback_steps: int = 1,
211
+ guidance_rescale: float = 0.0,
212
+ ):
213
+ r"""
214
+ Function invoked when calling the pipeline for generation.
215
+
216
+ Args:
217
+ prompt (`Optional[Union[str, List[str]]]`, defaults to None):
218
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
219
+ instead.
220
+ height (`Optional[int]`, defaults to None):
221
+ The height in pixels of the generated image.
222
+ width (`Optional[int]`, defaults to None):
223
+ The width in pixels of the generated image.
224
+ num_inference_steps (`int`, defaults to 4):
225
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
226
+ expense of slower inference.
227
+ lcm_origin_steps (`int`, defaults to 50):
228
+ The number of LCM Scheduler denoising steps.
229
+ guidance_scale (`float`, defaults to 7.5):
230
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
231
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
232
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
233
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
234
+ usually at the expense of lower image quality.
235
+ num_images_per_prompt (`int`, defaults to 1):
236
+ The number of images to generate per prompt.
237
+ eta (`float`, defaults to 0.0):
238
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
239
+ [`schedulers.DDIMScheduler`], will be ignored for others.
240
+ generator (`Optional[np.random.RandomState]`, defaults to `None`)::
241
+ A np.random.RandomState to make generation deterministic.
242
+ latents (`Optional[np.ndarray]`, defaults to `None`):
243
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
244
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
245
+ tensor will ge generated by sampling using the supplied random `generator`.
246
+ prompt_embeds (`Optional[np.ndarray]`, defaults to `None`):
247
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
248
+ provided, text embeddings will be generated from `prompt` input argument.
249
+ output_type (`str`, defaults to `"pil"`):
250
+ The output format of the generate image. Choose between
251
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
252
+ return_dict (`bool`, defaults to `True`):
253
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
254
+ plain tuple.
255
+ callback (Optional[Callable], defaults to `None`):
256
+ A function that will be called every `callback_steps` steps during inference. The function will be
257
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
258
+ callback_steps (`int`, defaults to 1):
259
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
260
+ called at every step.
261
+ guidance_rescale (`float`, defaults to 0.0):
262
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
263
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
264
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
265
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
266
+
267
+ Returns:
268
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
269
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
270
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
271
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
272
+ (nsfw) content, according to the `safety_checker`.
273
+ """
274
+ height = height or self.unet.config.get("sample_size", 64) * self.vae_scale_factor
275
+ width = width or self.unet.config.get("sample_size", 64) * self.vae_scale_factor
276
+
277
+ # check inputs. Raise error if not correct
278
+ self.check_inputs(
279
+ prompt, height, width, callback_steps, None, prompt_embeds, None
280
+ )
281
+
282
+ # define call parameters
283
+ if isinstance(prompt, str):
284
+ batch_size = 1
285
+ elif isinstance(prompt, list):
286
+ batch_size = len(prompt)
287
+ else:
288
+ batch_size = prompt_embeds.shape[0]
289
+
290
+ if generator is None:
291
+ generator = np.random
292
+
293
+ prompt_embeds = self._encode_prompt(
294
+ prompt,
295
+ num_images_per_prompt,
296
+ prompt_embeds=prompt_embeds,
297
+ )
298
+
299
+ # set timesteps
300
+ self.scheduler.set_timesteps(num_inference_steps, lcm_origin_steps)
301
+ timesteps = self.scheduler.timesteps
302
+
303
+ latents = self.prepare_latents(
304
+ batch_size * num_images_per_prompt,
305
+ self.unet.config.get("in_channels", 4),
306
+ height,
307
+ width,
308
+ prompt_embeds.dtype,
309
+ generator,
310
+ latents,
311
+ )
312
+
313
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
314
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
315
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
316
+ # and should be between [0, 1]
317
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
318
+ extra_step_kwargs = {}
319
+ if accepts_eta:
320
+ extra_step_kwargs["eta"] = eta
321
+
322
+ # Adapted from diffusers to extend it for other runtimes than ORT
323
+ timestep_dtype = self.unet.input_dtype.get("timestep", np.float32)
324
+
325
+ # Get Guidance Scale Embedding
326
+ w = np.tile(guidance_scale, batch_size * num_images_per_prompt)
327
+ w_embedding = self.get_w_embedding(w, embedding_dim=self.unet.config.get("time_cond_proj_dim", 256))
328
+
329
+
330
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
331
+ for i, t in enumerate(self.progress_bar(timesteps)):
332
+
333
+ # predict the noise residual
334
+ timestep = np.array([t], dtype=timestep_dtype)
335
+
336
+ noise_pred = self.unet(sample=latents, timestep=timestep, encoder_hidden_states=prompt_embeds, timestep_cond = w_embedding)[0]
337
+
338
+ # compute the previous noisy sample x_t -> x_t-1
339
+ latents, denoised = self.scheduler.step(
340
+ torch.from_numpy(noise_pred), i, t, torch.from_numpy(latents), **extra_step_kwargs, return_dict = False
341
+ )
342
+
343
+ latents, denoised = latents.numpy(), denoised.numpy()
344
+
345
+ # call the callback, if provided
346
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
347
+ if callback is not None and i % callback_steps == 0:
348
+ callback(i, t, latents)
349
+
350
+ if output_type == "latent":
351
+ image = latents
352
+ has_nsfw_concept = None
353
+ else:
354
+ denoised /= self.vae_decoder.config.get("scaling_factor", 0.18215)
355
+ # it seems likes there is a strange result for using half-precision vae decoder if batchsize>1
356
+ image = np.concatenate(
357
+ [self.vae_decoder(latent_sample=denoised[i : i + 1])[0] for i in range(latents.shape[0])]
358
+ )
359
+ image, has_nsfw_concept = self.run_safety_checker(image)
360
+
361
+ if has_nsfw_concept is None:
362
+ do_denormalize = [True] * image.shape[0]
363
+ else:
364
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
365
+
366
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
367
+
368
+ if not return_dict:
369
+ return (image, has_nsfw_concept)
370
+
371
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
lcm_scheduler.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Stanford University Team and 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
+ # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
16
+ # and https://github.com/hojonathanho/diffusion
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+
25
+ from diffusers import ConfigMixin, SchedulerMixin
26
+ from diffusers.configuration_utils import register_to_config
27
+ from diffusers.utils import BaseOutput
28
+
29
+
30
+ @dataclass
31
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
32
+ class LCMSchedulerOutput(BaseOutput):
33
+ """
34
+ Output class for the scheduler's `step` function output.
35
+
36
+ Args:
37
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
38
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
39
+ denoising loop.
40
+ pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
41
+ The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
42
+ `pred_original_sample` can be used to preview progress or for guidance.
43
+ """
44
+
45
+ prev_sample: torch.FloatTensor
46
+ denoised: Optional[torch.FloatTensor] = None
47
+
48
+
49
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
50
+ def betas_for_alpha_bar(
51
+ num_diffusion_timesteps,
52
+ max_beta=0.999,
53
+ alpha_transform_type="cosine",
54
+ ):
55
+ """
56
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
57
+ (1-beta) over time from t = [0,1].
58
+
59
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
60
+ to that part of the diffusion process.
61
+
62
+
63
+ Args:
64
+ num_diffusion_timesteps (`int`): the number of betas to produce.
65
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
66
+ prevent singularities.
67
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
68
+ Choose from `cosine` or `exp`
69
+
70
+ Returns:
71
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
72
+ """
73
+ if alpha_transform_type == "cosine":
74
+
75
+ def alpha_bar_fn(t):
76
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
77
+
78
+ elif alpha_transform_type == "exp":
79
+
80
+ def alpha_bar_fn(t):
81
+ return math.exp(t * -12.0)
82
+
83
+ else:
84
+ raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}")
85
+
86
+ betas = []
87
+ for i in range(num_diffusion_timesteps):
88
+ t1 = i / num_diffusion_timesteps
89
+ t2 = (i + 1) / num_diffusion_timesteps
90
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
91
+ return torch.tensor(betas, dtype=torch.float32)
92
+
93
+
94
+ def rescale_zero_terminal_snr(betas):
95
+ """
96
+ Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
97
+
98
+
99
+ Args:
100
+ betas (`torch.FloatTensor`):
101
+ the betas that the scheduler is being initialized with.
102
+
103
+ Returns:
104
+ `torch.FloatTensor`: rescaled betas with zero terminal SNR
105
+ """
106
+ # Convert betas to alphas_bar_sqrt
107
+ alphas = 1.0 - betas
108
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
109
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
110
+
111
+ # Store old values.
112
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
113
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
114
+
115
+ # Shift so the last timestep is zero.
116
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
117
+
118
+ # Scale so the first timestep is back to the old value.
119
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
120
+
121
+ # Convert alphas_bar_sqrt to betas
122
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
123
+ alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
124
+ alphas = torch.cat([alphas_bar[0:1], alphas])
125
+ betas = 1 - alphas
126
+
127
+ return betas
128
+
129
+
130
+ class LCMScheduler(SchedulerMixin, ConfigMixin):
131
+ """
132
+ `LCMScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with
133
+ non-Markovian guidance.
134
+
135
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
136
+ methods the library implements for all schedulers such as loading and saving.
137
+
138
+ Args:
139
+ num_train_timesteps (`int`, defaults to 1000):
140
+ The number of diffusion steps to train the model.
141
+ beta_start (`float`, defaults to 0.0001):
142
+ The starting `beta` value of inference.
143
+ beta_end (`float`, defaults to 0.02):
144
+ The final `beta` value.
145
+ beta_schedule (`str`, defaults to `"linear"`):
146
+ The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
147
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
148
+ trained_betas (`np.ndarray`, *optional*):
149
+ Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
150
+ clip_sample (`bool`, defaults to `True`):
151
+ Clip the predicted sample for numerical stability.
152
+ clip_sample_range (`float`, defaults to 1.0):
153
+ The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
154
+ set_alpha_to_one (`bool`, defaults to `True`):
155
+ Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
156
+ there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
157
+ otherwise it uses the alpha value at step 0.
158
+ steps_offset (`int`, defaults to 0):
159
+ An offset added to the inference steps. You can use a combination of `offset=1` and
160
+ `set_alpha_to_one=False` to make the last step use step 0 for the previous alpha product like in Stable
161
+ Diffusion.
162
+ prediction_type (`str`, defaults to `epsilon`, *optional*):
163
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
164
+ `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
165
+ Video](https://imagen.research.google/video/paper.pdf) paper).
166
+ thresholding (`bool`, defaults to `False`):
167
+ Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
168
+ as Stable Diffusion.
169
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
170
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
171
+ sample_max_value (`float`, defaults to 1.0):
172
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
173
+ timestep_spacing (`str`, defaults to `"leading"`):
174
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
175
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
176
+ rescale_betas_zero_snr (`bool`, defaults to `False`):
177
+ Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
178
+ dark samples instead of limiting it to samples with medium brightness. Loosely related to
179
+ [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
180
+ """
181
+
182
+ # _compatibles = [e.name for e in KarrasDiffusionSchedulers]
183
+ order = 1
184
+
185
+ @register_to_config
186
+ def __init__(
187
+ self,
188
+ num_train_timesteps: int = 1000,
189
+ beta_start: float = 0.0001,
190
+ beta_end: float = 0.02,
191
+ beta_schedule: str = "linear",
192
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
193
+ clip_sample: bool = True,
194
+ set_alpha_to_one: bool = True,
195
+ steps_offset: int = 0,
196
+ prediction_type: str = "epsilon",
197
+ thresholding: bool = False,
198
+ dynamic_thresholding_ratio: float = 0.995,
199
+ clip_sample_range: float = 1.0,
200
+ sample_max_value: float = 1.0,
201
+ timestep_spacing: str = "leading",
202
+ rescale_betas_zero_snr: bool = False,
203
+ ):
204
+ if trained_betas is not None:
205
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
206
+ elif beta_schedule == "linear":
207
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
208
+ elif beta_schedule == "scaled_linear":
209
+ # this schedule is very specific to the latent diffusion model.
210
+ self.betas = (
211
+ torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
212
+ )
213
+ elif beta_schedule == "squaredcos_cap_v2":
214
+ # Glide cosine schedule
215
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
216
+ else:
217
+ raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
218
+
219
+ # Rescale for zero SNR
220
+ if rescale_betas_zero_snr:
221
+ self.betas = rescale_zero_terminal_snr(self.betas)
222
+
223
+ self.alphas = 1.0 - self.betas
224
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
225
+
226
+ # At every step in ddim, we are looking into the previous alphas_cumprod
227
+ # For the final step, there is no previous alphas_cumprod because we are already at 0
228
+ # `set_alpha_to_one` decides whether we set this parameter simply to one or
229
+ # whether we use the final alpha of the "non-previous" one.
230
+ self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]
231
+
232
+ # standard deviation of the initial noise distribution
233
+ self.init_noise_sigma = 1.0
234
+
235
+ # setable values
236
+ self.num_inference_steps = None
237
+ self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64))
238
+
239
+ def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:
240
+ """
241
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
242
+ current timestep.
243
+
244
+ Args:
245
+ sample (`torch.FloatTensor`):
246
+ The input sample.
247
+ timestep (`int`, *optional*):
248
+ The current timestep in the diffusion chain.
249
+
250
+ Returns:
251
+ `torch.FloatTensor`:
252
+ A scaled input sample.
253
+ """
254
+ return sample
255
+
256
+ def _get_variance(self, timestep, prev_timestep):
257
+ alpha_prod_t = self.alphas_cumprod[timestep]
258
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
259
+ beta_prod_t = 1 - alpha_prod_t
260
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
261
+
262
+ variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
263
+
264
+ return variance
265
+
266
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
267
+ def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:
268
+ """
269
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
270
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
271
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
272
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
273
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
274
+
275
+ https://arxiv.org/abs/2205.11487
276
+ """
277
+ dtype = sample.dtype
278
+ batch_size, channels, height, width = sample.shape
279
+
280
+ if dtype not in (torch.float32, torch.float64):
281
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
282
+
283
+ # Flatten sample for doing quantile calculation along each image
284
+ sample = sample.reshape(batch_size, channels * height * width)
285
+
286
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
287
+
288
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
289
+ s = torch.clamp(
290
+ s, min=1, max=self.config.sample_max_value
291
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
292
+
293
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
294
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
295
+
296
+ sample = sample.reshape(batch_size, channels, height, width)
297
+ sample = sample.to(dtype)
298
+
299
+ return sample
300
+
301
+ def set_timesteps(self, num_inference_steps: int, lcm_origin_steps: int, device: Union[str, torch.device] = None):
302
+ """
303
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
304
+
305
+ Args:
306
+ num_inference_steps (`int`):
307
+ The number of diffusion steps used when generating samples with a pre-trained model.
308
+ """
309
+
310
+ if num_inference_steps > self.config.num_train_timesteps:
311
+ raise ValueError(
312
+ f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
313
+ f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
314
+ f" maximal {self.config.num_train_timesteps} timesteps."
315
+ )
316
+
317
+ self.num_inference_steps = num_inference_steps
318
+
319
+ # LCM Timesteps Setting: # Linear Spacing
320
+ c = self.config.num_train_timesteps // lcm_origin_steps
321
+ lcm_origin_timesteps = np.asarray(list(range(1, lcm_origin_steps + 1))) * c - 1 # LCM Training Steps Schedule
322
+ skipping_step = len(lcm_origin_timesteps) // num_inference_steps
323
+ timesteps = lcm_origin_timesteps[::-skipping_step][:num_inference_steps] # LCM Inference Steps Schedule
324
+
325
+ self.timesteps = torch.from_numpy(timesteps.copy()).to(device)
326
+
327
+ def get_scalings_for_boundary_condition_discrete(self, t):
328
+ self.sigma_data = 0.5 # Default: 0.5
329
+
330
+ # By dividing 0.1: This is almost a delta function at t=0.
331
+ c_skip = self.sigma_data**2 / (
332
+ (t / 0.1) ** 2 + self.sigma_data**2
333
+ )
334
+ c_out = (( t / 0.1) / ((t / 0.1) **2 + self.sigma_data**2) ** 0.5)
335
+ return c_skip, c_out
336
+
337
+
338
+ def step(
339
+ self,
340
+ model_output: torch.FloatTensor,
341
+ timeindex: int,
342
+ timestep: int,
343
+ sample: torch.FloatTensor,
344
+ eta: float = 0.0,
345
+ use_clipped_model_output: bool = False,
346
+ generator=None,
347
+ variance_noise: Optional[torch.FloatTensor] = None,
348
+ return_dict: bool = True,
349
+ ) -> Union[LCMSchedulerOutput, Tuple]:
350
+ """
351
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
352
+ process from the learned model outputs (most often the predicted noise).
353
+
354
+ Args:
355
+ model_output (`torch.FloatTensor`):
356
+ The direct output from learned diffusion model.
357
+ timestep (`float`):
358
+ The current discrete timestep in the diffusion chain.
359
+ sample (`torch.FloatTensor`):
360
+ A current instance of a sample created by the diffusion process.
361
+ eta (`float`):
362
+ The weight of noise for added noise in diffusion step.
363
+ use_clipped_model_output (`bool`, defaults to `False`):
364
+ If `True`, computes "corrected" `model_output` from the clipped predicted original sample. Necessary
365
+ because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no
366
+ clipping has happened, "corrected" `model_output` would coincide with the one provided as input and
367
+ `use_clipped_model_output` has no effect.
368
+ generator (`torch.Generator`, *optional*):
369
+ A random number generator.
370
+ variance_noise (`torch.FloatTensor`):
371
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
372
+ itself. Useful for methods such as [`CycleDiffusion`].
373
+ return_dict (`bool`, *optional*, defaults to `True`):
374
+ Whether or not to return a [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] or `tuple`.
375
+
376
+ Returns:
377
+ [`~schedulers.scheduling_utils.LCMSchedulerOutput`] or `tuple`:
378
+ If return_dict is `True`, [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] is returned, otherwise a
379
+ tuple is returned where the first element is the sample tensor.
380
+
381
+ """
382
+ if self.num_inference_steps is None:
383
+ raise ValueError(
384
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
385
+ )
386
+
387
+ # 1. get previous step value
388
+ prev_timeindex = timeindex + 1
389
+ if prev_timeindex < len(self.timesteps):
390
+ prev_timestep = self.timesteps[prev_timeindex]
391
+ else:
392
+ prev_timestep = timestep
393
+
394
+ # 2. compute alphas, betas
395
+ alpha_prod_t = self.alphas_cumprod[timestep]
396
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
397
+
398
+ beta_prod_t = 1 - alpha_prod_t
399
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
400
+
401
+ # 3. Get scalings for boundary conditions
402
+ c_skip, c_out = self.get_scalings_for_boundary_condition_discrete(timestep)
403
+
404
+ # 4. Different Parameterization:
405
+ parameterization = self.config.prediction_type
406
+
407
+ if parameterization == "epsilon": # noise-prediction
408
+ pred_x0 = (sample - beta_prod_t.sqrt() * model_output) / alpha_prod_t.sqrt()
409
+
410
+ elif parameterization == "sample": # x-prediction
411
+ pred_x0 = model_output
412
+
413
+ elif parameterization == "v_prediction": # v-prediction
414
+ pred_x0 = alpha_prod_t.sqrt() * sample - beta_prod_t.sqrt() * model_output
415
+
416
+ # 4. Denoise model output using boundary conditions
417
+ denoised = c_out * pred_x0 + c_skip * sample
418
+
419
+ # 5. Sample z ~ N(0, I), For MultiStep Inference
420
+ # Noise is not used for one-step sampling.
421
+ if len(self.timesteps) > 1:
422
+ noise = torch.randn(model_output.shape).to(model_output.device)
423
+ prev_sample = alpha_prod_t_prev.sqrt() * denoised + beta_prod_t_prev.sqrt() * noise
424
+ else:
425
+ prev_sample = denoised
426
+
427
+ if not return_dict:
428
+ return (prev_sample, denoised)
429
+
430
+ return LCMSchedulerOutput(prev_sample=prev_sample, denoised=denoised)
431
+
432
+
433
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
434
+ def add_noise(
435
+ self,
436
+ original_samples: torch.FloatTensor,
437
+ noise: torch.FloatTensor,
438
+ timesteps: torch.IntTensor,
439
+ ) -> torch.FloatTensor:
440
+ # Make sure alphas_cumprod and timestep have same device and dtype as original_samples
441
+ alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
442
+ timesteps = timesteps.to(original_samples.device)
443
+
444
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
445
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
446
+ while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
447
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
448
+
449
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
450
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
451
+ while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
452
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
453
+
454
+ noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
455
+ return noisy_samples
456
+
457
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocity
458
+ def get_velocity(
459
+ self, sample: torch.FloatTensor, noise: torch.FloatTensor, timesteps: torch.IntTensor
460
+ ) -> torch.FloatTensor:
461
+ # Make sure alphas_cumprod and timestep have same device and dtype as sample
462
+ alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)
463
+ timesteps = timesteps.to(sample.device)
464
+
465
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
466
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
467
+ while len(sqrt_alpha_prod.shape) < len(sample.shape):
468
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
469
+
470
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
471
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
472
+ while len(sqrt_one_minus_alpha_prod.shape) < len(sample.shape):
473
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
474
+
475
+ velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
476
+ return velocity
477
+
478
+ def __len__(self):
479
+ return self.config.num_train_timesteps
model_index.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "StableDiffusionPipeline",
3
+ "_diffusers_version": "0.20.2",
4
+ "_name_or_path": "SimianLuo/LCM_Dreamshaper_v7",
5
+ "feature_extractor": [
6
+ "transformers",
7
+ "CLIPImageProcessor"
8
+ ],
9
+ "requires_safety_checker": true,
10
+ "safety_checker": [
11
+ "stable_diffusion",
12
+ "StableDiffusionSafetyChecker"
13
+ ],
14
+ "scheduler": [
15
+ "diffusers",
16
+ "PNDMScheduler"
17
+ ],
18
+ "text_encoder": [
19
+ "transformers",
20
+ "CLIPTextModel"
21
+ ],
22
+ "tokenizer": [
23
+ "transformers",
24
+ "CLIPTokenizer"
25
+ ],
26
+ "unet": [
27
+ "diffusers",
28
+ "UNet2DConditionModel"
29
+ ],
30
+ "vae": [
31
+ "diffusers",
32
+ "AutoencoderKL"
33
+ ]
34
+ }
scheduler/scheduler_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "PNDMScheduler",
3
+ "_diffusers_version": "0.20.2",
4
+ "beta_end": 0.012,
5
+ "beta_schedule": "scaled_linear",
6
+ "beta_start": 0.00085,
7
+ "clip_sample": false,
8
+ "clip_sample_range": 1.0,
9
+ "dynamic_thresholding_ratio": 0.995,
10
+ "num_train_timesteps": 1000,
11
+ "prediction_type": "epsilon",
12
+ "rescale_betas_zero_snr": false,
13
+ "sample_max_value": 1.0,
14
+ "set_alpha_to_one": true,
15
+ "skip_prk_steps": false,
16
+ "steps_offset": 1,
17
+ "thresholding": false,
18
+ "timestep_spacing": "leading",
19
+ "trained_betas": null
20
+ }
text_encoder/config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/home/user/.cache/huggingface/hub/models--SimianLuo--LCM_Dreamshaper_v7/snapshots/c7f9b672c65a664af57d1de926819fd79cb26eb8/text_encoder",
3
+ "architectures": [
4
+ "CLIPTextModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 0,
8
+ "dropout": 0.0,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "quick_gelu",
11
+ "hidden_size": 768,
12
+ "initializer_factor": 1.0,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 3072,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 77,
17
+ "model_type": "clip_text_model",
18
+ "num_attention_heads": 12,
19
+ "num_hidden_layers": 12,
20
+ "pad_token_id": 1,
21
+ "projection_dim": 768,
22
+ "torch_dtype": "float32",
23
+ "transformers_version": "4.31.0",
24
+ "vocab_size": 49408
25
+ }
text_encoder/openvino_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e9e2783c544f9432ab465bc1222eae65b5fa51ebbbb5fb981633c30892dec3a4
3
+ size 492242764
text_encoder/openvino_model.xml ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer/special_tokens_map.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|startoftext|>",
3
+ "eos_token": "<|endoftext|>",
4
+ "pad_token": "<|endoftext|>",
5
+ "unk_token": "<|endoftext|>"
6
+ }
tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "49406": {
5
+ "content": "<|startoftext|>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "49407": {
13
+ "content": "<|endoftext|>",
14
+ "lstrip": false,
15
+ "normalized": true,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ }
20
+ },
21
+ "additional_special_tokens": [],
22
+ "bos_token": {
23
+ "__type": "AddedToken",
24
+ "content": "<|startoftext|>",
25
+ "lstrip": false,
26
+ "normalized": true,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "clean_up_tokenization_spaces": true,
31
+ "do_lower_case": true,
32
+ "eos_token": {
33
+ "__type": "AddedToken",
34
+ "content": "<|endoftext|>",
35
+ "lstrip": false,
36
+ "normalized": true,
37
+ "rstrip": false,
38
+ "single_word": false
39
+ },
40
+ "errors": "replace",
41
+ "model_max_length": 77,
42
+ "pad_token": "<|endoftext|>",
43
+ "tokenizer_class": "CLIPTokenizer",
44
+ "tokenizer_file": null,
45
+ "unk_token": {
46
+ "__type": "AddedToken",
47
+ "content": "<|endoftext|>",
48
+ "lstrip": false,
49
+ "normalized": true,
50
+ "rstrip": false,
51
+ "single_word": false
52
+ }
53
+ }
tokenizer/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
unet/config.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "UNet2DConditionModel",
3
+ "_diffusers_version": "0.20.2",
4
+ "_name_or_path": "/home/user/.cache/huggingface/hub/models--SimianLuo--LCM_Dreamshaper_v7/snapshots/c7f9b672c65a664af57d1de926819fd79cb26eb8/unet",
5
+ "act_fn": "silu",
6
+ "addition_embed_type": null,
7
+ "addition_embed_type_num_heads": 64,
8
+ "addition_time_embed_dim": null,
9
+ "attention_head_dim": 8,
10
+ "attention_type": "default",
11
+ "block_out_channels": [
12
+ 320,
13
+ 640,
14
+ 1280,
15
+ 1280
16
+ ],
17
+ "center_input_sample": false,
18
+ "class_embed_type": null,
19
+ "class_embeddings_concat": false,
20
+ "conv_in_kernel": 3,
21
+ "conv_out_kernel": 3,
22
+ "cross_attention_dim": 768,
23
+ "cross_attention_norm": null,
24
+ "down_block_types": [
25
+ "CrossAttnDownBlock2D",
26
+ "CrossAttnDownBlock2D",
27
+ "CrossAttnDownBlock2D",
28
+ "DownBlock2D"
29
+ ],
30
+ "downsample_padding": 1,
31
+ "dropout": 0.0,
32
+ "dual_cross_attention": false,
33
+ "encoder_hid_dim": null,
34
+ "encoder_hid_dim_type": null,
35
+ "flip_sin_to_cos": true,
36
+ "freq_shift": 0,
37
+ "in_channels": 4,
38
+ "layers_per_block": 2,
39
+ "mid_block_only_cross_attention": null,
40
+ "mid_block_scale_factor": 1,
41
+ "mid_block_type": "UNetMidBlock2DCrossAttn",
42
+ "norm_eps": 1e-05,
43
+ "norm_num_groups": 32,
44
+ "num_attention_heads": null,
45
+ "num_class_embeds": null,
46
+ "only_cross_attention": false,
47
+ "out_channels": 4,
48
+ "projection_class_embeddings_input_dim": null,
49
+ "resnet_out_scale_factor": 1.0,
50
+ "resnet_skip_time_act": false,
51
+ "resnet_time_scale_shift": "default",
52
+ "sample_size": 96,
53
+ "time_cond_proj_dim": 256,
54
+ "time_embedding_act_fn": null,
55
+ "time_embedding_dim": null,
56
+ "time_embedding_type": "positional",
57
+ "timestep_post_act": null,
58
+ "transformer_layers_per_block": 1,
59
+ "up_block_types": [
60
+ "UpBlock2D",
61
+ "CrossAttnUpBlock2D",
62
+ "CrossAttnUpBlock2D",
63
+ "CrossAttnUpBlock2D"
64
+ ],
65
+ "upcast_attention": null,
66
+ "use_linear_projection": false
67
+ }
unet/openvino_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc40724121308b865c3ffbae8c39991a2f3510e9251f3b0c59db37833628bc38
3
+ size 3438412388
unet/openvino_model.xml ADDED
The diff for this file is too large to render. See raw diff
 
vae_decoder/config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.20.2",
4
+ "_name_or_path": "/home/user/.cache/huggingface/hub/models--SimianLuo--LCM_Dreamshaper_v7/snapshots/c7f9b672c65a664af57d1de926819fd79cb26eb8/vae",
5
+ "act_fn": "silu",
6
+ "block_out_channels": [
7
+ 128,
8
+ 256,
9
+ 512,
10
+ 512
11
+ ],
12
+ "down_block_types": [
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D"
17
+ ],
18
+ "force_upcast": true,
19
+ "in_channels": 3,
20
+ "latent_channels": 4,
21
+ "layers_per_block": 2,
22
+ "norm_num_groups": 32,
23
+ "out_channels": 3,
24
+ "sample_size": 768,
25
+ "scaling_factor": 0.18215,
26
+ "up_block_types": [
27
+ "UpDecoderBlock2D",
28
+ "UpDecoderBlock2D",
29
+ "UpDecoderBlock2D",
30
+ "UpDecoderBlock2D"
31
+ ]
32
+ }
vae_decoder/openvino_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81a8010713a2554061d107967f6a6b301386f661684da510f6035eb379782679
3
+ size 197960932
vae_decoder/openvino_model.xml ADDED
The diff for this file is too large to render. See raw diff
 
vae_encoder/config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.20.2",
4
+ "_name_or_path": "/home/user/.cache/huggingface/hub/models--SimianLuo--LCM_Dreamshaper_v7/snapshots/c7f9b672c65a664af57d1de926819fd79cb26eb8/vae",
5
+ "act_fn": "silu",
6
+ "block_out_channels": [
7
+ 128,
8
+ 256,
9
+ 512,
10
+ 512
11
+ ],
12
+ "down_block_types": [
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D"
17
+ ],
18
+ "force_upcast": true,
19
+ "in_channels": 3,
20
+ "latent_channels": 4,
21
+ "layers_per_block": 2,
22
+ "norm_num_groups": 32,
23
+ "out_channels": 3,
24
+ "sample_size": 768,
25
+ "scaling_factor": 0.18215,
26
+ "up_block_types": [
27
+ "UpDecoderBlock2D",
28
+ "UpDecoderBlock2D",
29
+ "UpDecoderBlock2D",
30
+ "UpDecoderBlock2D"
31
+ ]
32
+ }
vae_encoder/openvino_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0198e0db626c241c992904f9a34be172e895028c7dcbb63c66ced4e8e496a8a
3
+ size 136654796
vae_encoder/openvino_model.xml ADDED
The diff for this file is too large to render. See raw diff