English
art
Stable Diffusion
bigmoyan commited on
Commit
c5e9e77
1 Parent(s): 806e745
.gitattributes CHANGED
@@ -32,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ lyraSD/muse_trt/libnvinfer_plugin.so filter=lfs diff=lfs merge=lfs -text
lyraSD/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .inference import LyraSD
lyraSD/inference.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from PIL import Image
3
+ from .muse_trt import TRTStableDiffusionText2ImgPipeline
4
+ from .muse_trt import TRTStableDiffusionImg2ImgPipeline
5
+ import numpy as np
6
+
7
+
8
+ class LyraSD(object):
9
+ def __init__(self, sd_mode, engine_dir,o_height=512, o_width=512, device="cuda:0"):
10
+ self.sd_mode = sd_mode
11
+ self.device = device
12
+ self.o_height = o_height
13
+ self.o_width = o_width
14
+ if self.sd_mode == "text2img":
15
+ self.pipeline = TRTStableDiffusionText2ImgPipeline(
16
+ engine_dir = engine_dir,
17
+ o_height = o_height,
18
+ o_width = o_width,
19
+ device=device
20
+ )
21
+ elif self.sd_mode == "img2img":
22
+ self.pipeline = TRTStableDiffusionImg2ImgPipeline(
23
+ engine_dir = engine_dir,
24
+ o_height = o_height,
25
+ o_width = o_width,
26
+ device=device
27
+ )
28
+ else:
29
+ raise ValueError("Invalid sd_mode: {}".format(self.sd_mode))
30
+
31
+
32
+
33
+ def inference(self, prompt,
34
+ image=None,
35
+ save_dir="./output",
36
+ save_basename="sd-",
37
+ negative_prompts='',
38
+ strength=0.3,
39
+ height=None,
40
+ width =None,
41
+ num_images_per_prompt=1,
42
+ num_inference_steps=50,
43
+ guidance_scale=7.5,
44
+ use_super=False,
45
+ ):
46
+
47
+ if self.sd_mode=="text2img" and prompt is None:
48
+ raise ValueError("prompt must be set on text2img mode")
49
+
50
+ if self.sd_mode=="img2img" and image is None:
51
+ raise ValueError("image must be set on img2img mode")
52
+
53
+ save_basename += f"{self.sd_mode}"
54
+ if height is None:
55
+ height = self.o_height
56
+ if width is None:
57
+ width = self.o_width
58
+
59
+ # this version model doen't support batch mode.
60
+ if not isinstance(prompt, list):
61
+ prompt = [prompt]
62
+ if len(prompt) > 1:
63
+ raise ValueError("current model dosen't support multi prompts")
64
+ if self.sd_mode=="text2img":
65
+ result_image = self.pipeline(prompt=prompt, negative_prompt=negative_prompts,
66
+ num_inference_steps= num_inference_steps,
67
+ num_images_per_prompt=num_images_per_prompt,
68
+ guidance_scale=guidance_scale,
69
+ height=height,
70
+ width=width,
71
+ use_super=use_super)
72
+ elif self.sd_mode=="img2img":
73
+ result_image = self.pipeline(prompt=prompt,
74
+ image=image,
75
+ negative_prompt=negative_prompts,
76
+ strength = strength,
77
+ num_inference_steps= num_inference_steps,
78
+ num_images_per_prompt=num_images_per_prompt,
79
+ guidance_scale=guidance_scale,
80
+ height=height,
81
+ width=width,
82
+ use_super=use_super)
83
+
84
+
85
+ for i in range(result_image.shape[0]):
86
+ result_image = Image.fromarray(np.uint8(result_image[i]))
87
+ result_image.save(os.path.join(save_dir, save_basename + "-{}.jpg".format(i)))
88
+
89
+ return result_image
lyraSD/muse_trt/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes
2
+ import os
3
+
4
+ current_workdir = os.path.dirname(__file__)
5
+
6
+ ctypes.cdll.LoadLibrary(os.path.join(current_workdir, "libnvinfer_plugin.so"))
7
+
8
+ from .sd_img2img import TRTStableDiffusionImg2ImgPipeline
9
+ from .sd_text2img import TRTStableDiffusionText2ImgPipeline
10
+ from .super import SuperX4TRTInfer
lyraSD/muse_trt/libnvinfer_plugin.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:53cbcc8a47524652bb8e0399a2fbbcfc0b785f11bdc491bbb6a71e4b888ee124
3
+ size 85198184
lyraSD/muse_trt/models.py ADDED
@@ -0,0 +1,815 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""models components"""
2
+ from collections import OrderedDict
3
+ from copy import deepcopy
4
+ from typing import Any, Dict, Optional, Union
5
+
6
+ import numpy as np
7
+ import torch
8
+ from cuda import cudart
9
+ from diffusers import ControlNetModel
10
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
11
+ from torch import nn
12
+ from torch.nn import functional as F
13
+ from transformers import CLIPTextModel
14
+
15
+
16
+ class BaseModel():
17
+ def __init__(
18
+ self,
19
+ local_model_path=None,
20
+ hf_token=None,
21
+ text_maxlen=77,
22
+ embedding_dim=768,
23
+ fp16=False,
24
+ device='cuda',
25
+ verbose=True,
26
+ max_batch_size=16
27
+ ):
28
+ self.fp16 = fp16
29
+ self.device = device
30
+ self.verbose = verbose
31
+ self.hf_token = hf_token
32
+ self.local_model_path = local_model_path
33
+
34
+ # Defaults
35
+ self.text_maxlen = text_maxlen
36
+ self.embedding_dim = embedding_dim
37
+ self.min_batch = 1
38
+ self.max_batch = max_batch_size
39
+ self.min_latent_shape = 256 // 8 # min image resolution: 256x256
40
+ self.max_latent_shape = 1024 // 8 # max image resolution: 1024x1024
41
+
42
+ def get_model(self):
43
+ pass
44
+
45
+ def get_input_names(self):
46
+ pass
47
+
48
+ def get_output_names(self):
49
+ pass
50
+
51
+ def get_dynamic_axes(self):
52
+ return None
53
+
54
+ def get_sample_input(self, batch_size, image_height, image_width):
55
+ pass
56
+
57
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
58
+ return None
59
+
60
+ def get_shape_dict(self, batch_size, image_height, image_width):
61
+ return None
62
+
63
+
64
+ def check_dims(self, batch_size, image_height, image_width):
65
+ assert batch_size >= self.min_batch and batch_size <= self.max_batch
66
+ assert image_height % 8 == 0 or image_width % 8 == 0
67
+ latent_height = image_height // 8
68
+ latent_width = image_width // 8
69
+ assert latent_height >= self.min_latent_shape and latent_height <= self.max_latent_shape
70
+ assert latent_width >= self.min_latent_shape and latent_width <= self.max_latent_shape
71
+ return (latent_height, latent_width)
72
+
73
+ def get_minmax_dims(self, batch_size, image_height, image_width, static_batch, static_shape):
74
+ min_batch = batch_size if static_batch else self.min_batch
75
+ max_batch = batch_size if static_batch else self.max_batch
76
+ latent_height = image_height // 8
77
+ latent_width = image_width // 8
78
+ min_latent_height = latent_height if static_shape else self.min_latent_shape
79
+ max_latent_height = latent_height if static_shape else self.max_latent_shape
80
+ min_latent_width = latent_width if static_shape else self.min_latent_shape
81
+ max_latent_width = latent_width if static_shape else self.max_latent_shape
82
+ return (min_batch, max_batch, min_latent_height, max_latent_height, min_latent_width, max_latent_width)
83
+
84
+
85
+ class CLIP(BaseModel):
86
+ def get_model(self):
87
+ if self.hf_token is None and self.local_model_path is not None:
88
+ clip_model = CLIPTextModel.from_pretrained(
89
+ self.local_model_path, subfolder="text_encoder").to(self.device)
90
+ else:
91
+ clip_model = CLIPTextModel.from_pretrained(
92
+ "openai/clip-vit-large-patch14").to(self.device)
93
+ return clip_model
94
+
95
+ def get_input_names(self):
96
+ return ['input_ids']
97
+
98
+ def get_output_names(self):
99
+ return ['text_embeddings', 'pooler_output']
100
+
101
+ def get_dynamic_axes(self):
102
+ return {
103
+ 'input_ids': {0: 'B'},
104
+ 'text_embeddings': {0: 'B'}
105
+ }
106
+
107
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
108
+ self.check_dims(batch_size, image_height, image_width)
109
+ min_batch, max_batch, _, _, _, _ = self.get_minmax_dims(
110
+ batch_size, image_height, image_width, static_batch, static_shape)
111
+ return {
112
+ 'input_ids': [(min_batch, self.text_maxlen), (batch_size, self.text_maxlen), (max_batch, self.text_maxlen)]
113
+ }
114
+
115
+ def get_shape_dict(self, batch_size, image_height, image_width):
116
+ self.check_dims(batch_size, image_height, image_width)
117
+ return {
118
+ 'input_ids': (batch_size, self.text_maxlen),
119
+ 'text_embeddings': (batch_size, self.text_maxlen, self.embedding_dim)
120
+ }
121
+
122
+ def get_sample_input(self, batch_size, image_height, image_width):
123
+ self.check_dims(batch_size, image_height, image_width)
124
+ return torch.zeros(batch_size, self.text_maxlen, dtype=torch.int32, device=self.device)
125
+
126
+
127
+
128
+ class UNet(BaseModel):
129
+ def get_model(self):
130
+ model_opts = {'revision': 'fp16',
131
+ 'torch_dtype': torch.float16} if self.fp16 else {}
132
+ print(model_opts)
133
+ if self.hf_token is None and self.local_model_path is not None:
134
+ unet_model = UNet2DConditionModel.from_pretrained(
135
+ self.local_model_path, subfolder="unet",
136
+ **model_opts
137
+ ).to(self.device)
138
+ else:
139
+ unet_model = UNet2DConditionModel.from_pretrained(
140
+ "CompVis/stable-diffusion-v1-4",
141
+ subfolder="unet",
142
+ use_auth_token=self.hf_token,
143
+ **model_opts).to(self.device)
144
+ return unet_model
145
+
146
+ def get_input_names(self):
147
+ return ['sample', 'timestep', 'encoder_hidden_states']
148
+
149
+ def get_output_names(self):
150
+ return ['latent']
151
+
152
+ def get_dynamic_axes(self):
153
+ return {
154
+ 'sample': {0: '2B', 2: 'H', 3: 'W'},
155
+ 'encoder_hidden_states': {0: '2B'},
156
+ 'latent': {0: '2B', 2: 'H', 3: 'W'}
157
+ }
158
+
159
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
160
+ latent_height, latent_width = self.check_dims(
161
+ batch_size, image_height, image_width)
162
+ min_batch, max_batch, min_latent_height, max_latent_height, min_latent_width, max_latent_width = \
163
+ self.get_minmax_dims(batch_size, image_height,
164
+ image_width, static_batch, static_shape)
165
+ return {
166
+ 'sample': [(2*min_batch, 4, min_latent_height, min_latent_width), (2*batch_size, 4, latent_height, latent_width), (2*max_batch, 4, max_latent_height, max_latent_width)],
167
+ 'encoder_hidden_states': [(2*min_batch, self.text_maxlen, self.embedding_dim), (2*batch_size, self.text_maxlen, self.embedding_dim), (2*max_batch, self.text_maxlen, self.embedding_dim)]
168
+ }
169
+
170
+ def get_shape_dict(self, batch_size, image_height, image_width):
171
+ latent_height, latent_width = self.check_dims(
172
+ batch_size, image_height, image_width)
173
+ return {
174
+ 'sample': (2*batch_size, 4, latent_height, latent_width),
175
+ 'encoder_hidden_states': (2*batch_size, self.text_maxlen, self.embedding_dim),
176
+ 'latent': (2*batch_size, 4, latent_height, latent_width)
177
+ }
178
+
179
+ def get_sample_input(self, batch_size, image_height, image_width):
180
+ latent_height, latent_width = self.check_dims(
181
+ batch_size, image_height, image_width)
182
+ dtype = torch.float16 if self.fp16 else torch.float32
183
+ return (
184
+ torch.randn(2*batch_size, 4, latent_height, latent_width,
185
+ dtype=torch.float32, device=self.device),
186
+ torch.tensor([1.], dtype=torch.float32, device=self.device),
187
+ torch.randn(2*batch_size, self.text_maxlen,
188
+ self.embedding_dim, dtype=dtype, device=self.device)
189
+ )
190
+
191
+ class VAEEncoderModule(nn.Module):
192
+ def __init__(self, local_model_path, device) -> None:
193
+ super().__init__()
194
+ self.vae = AutoencoderKL.from_pretrained(
195
+ local_model_path, subfolder="vae"
196
+ ).to(device)
197
+
198
+ def forward(self, x):
199
+ h = self.vae.encoder(x)
200
+ moments = self.vae.quant_conv(h)
201
+ return moments
202
+
203
+
204
+ class VAEEncoder(BaseModel):
205
+ def get_model(self):
206
+ vae_encoder = VAEEncoderModule(self.local_model_path, self.device)
207
+ return vae_encoder
208
+
209
+ def get_input_names(self):
210
+ return ['images']
211
+
212
+ def get_output_names(self):
213
+ return ['latent']
214
+
215
+ def get_dynamic_axes(self):
216
+ return {
217
+ 'images': {0: 'B', 2: '8H', 3: '8W'},
218
+ 'latent': {0: 'B', 2: 'H', 3: 'W'}
219
+ }
220
+
221
+ def check_dims(self, batch_size, image_height, image_width):
222
+ assert batch_size >= self.min_batch and batch_size <= self.max_batch
223
+ assert image_height % 8 == 0 or image_width % 8 == 0
224
+ latent_height = image_height // 8
225
+ latent_width = image_width // 8
226
+ assert latent_height >= self.min_latent_shape and latent_height <= self.max_latent_shape
227
+ assert latent_width >= self.min_latent_shape and latent_width <= self.max_latent_shape
228
+ return (image_height, image_width)
229
+
230
+ def get_minmax_dims(self, batch_size, image_height, image_width, static_batch, static_shape):
231
+ min_batch = batch_size if static_batch else self.min_batch
232
+ max_batch = batch_size if static_batch else self.max_batch
233
+ min_image_height = image_height if static_shape else self.min_latent_shape
234
+ max_image_height = image_height if static_shape else self.max_latent_shape
235
+ min_image_width = image_width if static_shape else self.min_latent_shape
236
+ max_image_width = image_width if static_shape else self.max_latent_shape
237
+ return (min_batch, max_batch, min_image_height, max_image_height, min_image_width, max_image_width)
238
+
239
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
240
+ image_height, image_width = self.check_dims(
241
+ batch_size, image_height, image_width)
242
+ min_batch, max_batch, min_image_height, max_image_height, min_image_width, max_image_width = \
243
+ self.get_minmax_dims(batch_size, image_height,
244
+ image_width, static_batch, static_shape)
245
+ return {
246
+ 'images': [(min_batch, 3, min_image_height, min_image_width), (batch_size, 3, image_height, image_width), (max_batch, 3, max_image_height, max_image_width)]
247
+ }
248
+
249
+ def get_shape_dict(self, batch_size, image_height, image_width):
250
+ image_height, image_width = self.check_dims(
251
+ batch_size, image_height, image_width)
252
+ return {
253
+ 'images': (batch_size, 3, image_height, image_width),
254
+ 'latent': (batch_size, 8, image_height//8, image_width//8),
255
+ }
256
+
257
+ def get_sample_input(self, batch_size, image_height, image_width):
258
+ image_height, image_width = self.check_dims(
259
+ batch_size, image_height, image_width)
260
+ return torch.randn(batch_size, 3, image_height, image_width, dtype=torch.float32, device=self.device)
261
+
262
+ def optimize(self, onnx_graph, minimal_optimization=False):
263
+ enable_optimization = not minimal_optimization
264
+
265
+ # Decompose InstanceNormalization into primitive Ops
266
+ bRemoveInstanceNorm = enable_optimization
267
+ # Remove Cast Node to optimize Attention block
268
+ bRemoveCastNode = enable_optimization
269
+ # Insert GroupNormalization Plugin
270
+ bGroupNormPlugin = enable_optimization
271
+
272
+ opt = Optimizer(onnx_graph, verbose=self.verbose)
273
+ opt.info('VAE Encoder: original')
274
+
275
+ if bRemoveInstanceNorm:
276
+ num_instancenorm_replaced = opt.decompose_instancenorms()
277
+ opt.info('VAE Encoder: replaced ' +
278
+ str(num_instancenorm_replaced)+' InstanceNorms')
279
+
280
+ if bRemoveCastNode:
281
+ num_casts_removed = opt.remove_casts()
282
+ opt.info('VAE Encoder: removed '+str(num_casts_removed)+' casts')
283
+
284
+ opt.cleanup()
285
+ opt.info('VAE Encoder: cleanup')
286
+ opt.fold_constants()
287
+ opt.info('VAE Encoder: fold constants')
288
+ opt.infer_shapes()
289
+ opt.info('VAE Encoder: shape inference')
290
+
291
+ if bGroupNormPlugin:
292
+ num_groupnorm_inserted = opt.insert_groupnorm_plugin()
293
+ opt.info('VAE Encoder: inserted '+str(num_groupnorm_inserted) +
294
+ ' GroupNorm plugins')
295
+
296
+ onnx_opt_graph = opt.cleanup(return_onnx=True)
297
+ opt.info('VAE Encoder: final')
298
+ return onnx_opt_graph
299
+
300
+
301
+ class VAEDecoder(BaseModel):
302
+ def get_model(self):
303
+ if self.hf_token is None and self.local_model_path is not None:
304
+ vae = AutoencoderKL.from_pretrained(
305
+ self.local_model_path, subfolder="vae"
306
+ ).to(self.device)
307
+ else:
308
+ vae = AutoencoderKL.from_pretrained(
309
+ "CompVis/stable-diffusion-v1-4",
310
+ subfolder="vae",
311
+ use_auth_token=self.hf_token).to(self.device)
312
+ vae.forward = vae.decode
313
+ return vae
314
+
315
+ def get_input_names(self):
316
+ return ['latent']
317
+
318
+ def get_output_names(self):
319
+ return ['images']
320
+
321
+ def get_dynamic_axes(self):
322
+ return {
323
+ 'latent': {0: 'B', 2: 'H', 3: 'W'},
324
+ 'images': {0: 'B', 2: '8H', 3: '8W'}
325
+ }
326
+
327
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
328
+ latent_height, latent_width = self.check_dims(
329
+ batch_size, image_height, image_width)
330
+ min_batch, max_batch, min_latent_height, max_latent_height, min_latent_width, max_latent_width = \
331
+ self.get_minmax_dims(batch_size, image_height,
332
+ image_width, static_batch, static_shape)
333
+ return {
334
+ 'latent': [(min_batch, 4, min_latent_height, min_latent_width), (batch_size, 4, latent_height, latent_width), (max_batch, 4, max_latent_height, max_latent_width)]
335
+ }
336
+
337
+ def get_shape_dict(self, batch_size, image_height, image_width):
338
+ latent_height, latent_width = self.check_dims(
339
+ batch_size, image_height, image_width)
340
+ return {
341
+ 'latent': (batch_size, 4, latent_height, latent_width),
342
+ 'images': (batch_size, 3, image_height, image_width)
343
+ }
344
+
345
+ def get_sample_input(self, batch_size, image_height, image_width):
346
+ latent_height, latent_width = self.check_dims(
347
+ batch_size, image_height, image_width)
348
+ return torch.randn(batch_size, 4, latent_height, latent_width, dtype=torch.float32, device=self.device)
349
+
350
+ def optimize(self, onnx_graph, minimal_optimization=False):
351
+ enable_optimization = not minimal_optimization
352
+
353
+ # Decompose InstanceNormalization into primitive Ops
354
+ bRemoveInstanceNorm = enable_optimization
355
+ # Remove Cast Node to optimize Attention block
356
+ bRemoveCastNode = enable_optimization
357
+ # Insert GroupNormalization Plugin
358
+ bGroupNormPlugin = enable_optimization
359
+
360
+ opt = Optimizer(onnx_graph, verbose=self.verbose)
361
+ opt.info('VAE Decoder: original')
362
+
363
+ if bRemoveInstanceNorm:
364
+ num_instancenorm_replaced = opt.decompose_instancenorms()
365
+ opt.info('VAE Decoder: replaced ' +
366
+ str(num_instancenorm_replaced)+' InstanceNorms')
367
+
368
+ if bRemoveCastNode:
369
+ num_casts_removed = opt.remove_casts()
370
+ opt.info('VAE Decoder: removed '+str(num_casts_removed)+' casts')
371
+
372
+ opt.cleanup()
373
+ opt.info('VAE Decoder: cleanup')
374
+ opt.fold_constants()
375
+ opt.info('VAE Decoder: fold constants')
376
+ opt.infer_shapes()
377
+ opt.info('VAE Decoder: shape inference')
378
+
379
+ if bGroupNormPlugin:
380
+ num_groupnorm_inserted = opt.insert_groupnorm_plugin()
381
+ opt.info('VAE Decoder: inserted '+str(num_groupnorm_inserted) +
382
+ ' GroupNorm plugins')
383
+
384
+ onnx_opt_graph = opt.cleanup(return_onnx=True)
385
+ opt.info('VAE Decoder: final')
386
+ return onnx_opt_graph
387
+
388
+
389
+ class SuperModelX4(nn.Module):
390
+ def __init__(self, model_dir, scale=4, pre_pad=0):
391
+ super().__init__()
392
+ self.scale = scale
393
+ self.pre_pad = pre_pad
394
+
395
+ rrdb = RealESRGAN(model_dir=model_dir,
396
+ model_name="RealESRGAN_x4plus_anime_6B").upsampler.model
397
+ self.rrdb = rrdb.eval()
398
+
399
+ def forward(self, x):
400
+ x = x / 255.
401
+ x = F.pad(x, (0, self.pre_pad, 0, self.pre_pad), 'reflect')
402
+ x = self.rrdb(x)
403
+ _, _, h, w = x.size()
404
+ x = x[:, :, 0:h-self.pre_pad * self.scale, 0:w-self.pre_pad*self.scale]
405
+ x = x.clamp(0, 1)
406
+ x = (x * 255).round()
407
+ return x
408
+
409
+
410
+ class SuperResX4():
411
+ def __init__(
412
+ self,
413
+ local_model_path=None,
414
+ fp16=True,
415
+ device='cuda',
416
+ verbose=True,
417
+ max_batch_size=8
418
+ ):
419
+ self.fp16 = fp16
420
+ self.device = device
421
+ self.verbose = verbose
422
+ self.local_model_path = local_model_path
423
+
424
+ # Defaults
425
+ self.min_batch = 1
426
+ self.max_batch = max_batch_size
427
+ self.min_height = 64
428
+ self.max_height = 640
429
+ self.min_width = 64
430
+ self.max_width = 640
431
+
432
+ def get_model(self):
433
+ model = SuperModelX4(self.local_model_path, scale=4, pre_pad=0).to(device=self.device)
434
+ if self.fp16:
435
+ model = model.half()
436
+ return model
437
+
438
+ def get_input_names(self):
439
+ return ['input_image']
440
+
441
+ def get_output_names(self):
442
+ return ['output_image']
443
+
444
+ def get_dynamic_axes(self):
445
+ return {
446
+ 'input_image': {0: 'B', },
447
+ 'output_image': {0: 'B', }
448
+ }
449
+
450
+ def check_dims(self, batch_size, image_height, image_width):
451
+ assert batch_size >= self.min_batch and batch_size <= self.max_batch
452
+ return (image_height, image_width)
453
+
454
+ def get_minmax_dims(self, batch_size, image_height, image_width, static_batch, static_shape):
455
+ min_batch = batch_size if static_batch else self.min_batch
456
+ max_batch = batch_size if static_batch else self.max_batch
457
+ min_image_height = image_height if static_shape else self.min_height
458
+ max_image_height = image_height if static_shape else self.max_height
459
+ min_image_width = image_width if static_shape else self.min_width
460
+ max_image_width = image_width if static_shape else self.max_width
461
+ return (min_batch, max_batch, min_image_height, max_image_height, min_image_width, max_image_width)
462
+
463
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
464
+ image_height, image_width = self.check_dims(
465
+ batch_size, image_height, image_width)
466
+ min_batch, max_batch, min_image_height, max_image_height, min_image_width, max_image_width = \
467
+ self.get_minmax_dims(batch_size, image_height,
468
+ image_width, static_batch, static_shape)
469
+ return {
470
+ 'input_image': [(min_batch, 3, min_image_height, min_image_width), (batch_size, 3, image_height, image_width), (max_batch, 3, max_image_height, max_image_width)]
471
+ }
472
+
473
+ def get_shape_dict(self, batch_size, image_height, image_width):
474
+ image_height, image_width = self.check_dims(
475
+ batch_size, image_height, image_width)
476
+ return {
477
+ 'input_image': (batch_size, 3, image_height, image_width),
478
+ 'output_image': (batch_size, 3, image_height*4, image_width*4),
479
+ }
480
+
481
+ def get_sample_input(self, batch_size, image_height, image_width):
482
+ dtype = torch.float16 if self.fp16 else torch.float32
483
+ image_height, image_width = self.check_dims(
484
+ batch_size, image_height, image_width)
485
+ return torch.randn(batch_size, 3, image_height, image_width, dtype=dtype, device=self.device)
486
+
487
+ def optimize(self, onnx_graph, minimal_optimization=False):
488
+ enable_optimization = not minimal_optimization
489
+
490
+ # Decompose InstanceNormalization into primitive Ops
491
+ bRemoveInstanceNorm = enable_optimization
492
+ # Remove Cast Node to optimize Attention block
493
+ bRemoveCastNode = enable_optimization
494
+ # Insert GroupNormalization Plugin
495
+ bGroupNormPlugin = enable_optimization
496
+
497
+ opt = Optimizer(onnx_graph, verbose=self.verbose)
498
+ opt.info('SuperX4: original')
499
+
500
+ if bRemoveInstanceNorm:
501
+ num_instancenorm_replaced = opt.decompose_instancenorms()
502
+ opt.info('SuperX4: replaced ' +
503
+ str(num_instancenorm_replaced)+' InstanceNorms')
504
+
505
+ if bRemoveCastNode:
506
+ num_casts_removed = opt.remove_casts()
507
+ opt.info('SuperX4: removed '+str(num_casts_removed)+' casts')
508
+
509
+ opt.cleanup()
510
+ opt.info('SuperX4: cleanup')
511
+ opt.fold_constants()
512
+ opt.info('SuperX4: fold constants')
513
+ opt.infer_shapes()
514
+ opt.info('SuperX4: shape inference')
515
+
516
+ if bGroupNormPlugin:
517
+ num_groupnorm_inserted = opt.insert_groupnorm_plugin()
518
+ opt.info('SuperX4: inserted '+str(num_groupnorm_inserted) +
519
+ ' GroupNorm plugins')
520
+
521
+ onnx_opt_graph = opt.cleanup(return_onnx=True)
522
+ opt.info('SuperX4: final')
523
+ return onnx_opt_graph
524
+
525
+
526
+ class FusedControlNetModule(nn.Module):
527
+ def __init__(self, base_model_dir, control_model_dir, fp16=True) -> None:
528
+ super().__init__()
529
+ self.device = 'cuda:0'
530
+ self.fp16 = fp16
531
+ model_opts = {'revision': 'fp16',
532
+ 'torch_dtype': torch.float16} if self.fp16 else {}
533
+ self.base = UNet2DConditionModel.from_pretrained(
534
+ base_model_dir, subfolder="unet",
535
+ **model_opts
536
+ ).eval().to(self.device)
537
+ self.control = ControlNetModel.from_pretrained(
538
+ control_model_dir,
539
+ **model_opts
540
+ ).eval().to(self.device)
541
+
542
+ def forward(self, sample, timestep, encoder_hidden_states, controlnet_cond):
543
+ controlnet_conditioning_scale: float = 1.0
544
+ down_block_res_samples, mid_block_res_sample = self.control(
545
+ sample,
546
+ timestep,
547
+ encoder_hidden_states=encoder_hidden_states,
548
+ controlnet_cond=controlnet_cond,
549
+ return_dict=False,
550
+ )
551
+
552
+ down_block_res_samples = [
553
+ down_block_res_sample * controlnet_conditioning_scale
554
+ for down_block_res_sample in down_block_res_samples
555
+ ]
556
+ mid_block_res_sample *= controlnet_conditioning_scale
557
+
558
+ # predict the noise residual
559
+ noise_pred = self.base(
560
+ sample,
561
+ timestep,
562
+ encoder_hidden_states=encoder_hidden_states,
563
+ down_block_additional_residuals=down_block_res_samples,
564
+ mid_block_additional_residual=mid_block_res_sample,
565
+ ).sample
566
+
567
+ return noise_pred
568
+
569
+
570
+ class FusedControlNet(BaseModel):
571
+ def __init__(self, local_model_path=None, controlnet_model_path=None, hf_token=None, text_maxlen=77,
572
+ embedding_dim=768, fp16=False, device='cuda', verbose=True, max_batch_size=16):
573
+ super().__init__(local_model_path, hf_token, text_maxlen, embedding_dim, fp16, device, verbose, max_batch_size)
574
+ # if controlnet_model_path is None:
575
+ # raise ValueError("Must give controlnet_model_path for FusedControlNet to load control net")
576
+ self.controlnet_model_path = controlnet_model_path
577
+ self.min_height = 256
578
+ self.max_height = 1024
579
+ self.min_width = 256
580
+ self.max_width = 1024
581
+
582
+ def get_minmax_dims(self, batch_size, image_height, image_width, static_batch, static_shape):
583
+ r = list(super().get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape))
584
+ min_height = image_height if static_shape else self.min_height
585
+ max_height = image_height if static_shape else self.max_height
586
+ min_width = image_width if static_shape else self.min_width
587
+ max_width = image_width if static_shape else self.max_width
588
+ r.extend([min_height, max_height, min_width, max_width])
589
+ return r
590
+
591
+ def get_model(self):
592
+ model = FusedControlNetModule(
593
+ base_model_dir=self.local_model_path,
594
+ control_model_dir=self.controlnet_model_path,
595
+ fp16=self.fp16
596
+ )
597
+ return model
598
+
599
+ def get_input_names(self):
600
+ return ['sample', 'timestep', 'encoder_hidden_states', 'controlnet_cond']
601
+
602
+ def get_output_names(self):
603
+ return ['latent']
604
+
605
+ def get_dynamic_axes(self):
606
+ return {
607
+ 'sample': {0: '2B', 2: 'H', 3: 'W'},
608
+ 'encoder_hidden_states': {0: '2B'},
609
+ 'controlnet_cond': {0: '2B', 2: '8H', 3: '8W'}, # controlnet_cond is 8X sample and lantent
610
+ 'latent': {0: '2B', 2: 'H', 3: 'W'}
611
+ }
612
+
613
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
614
+ latent_height, latent_width = self.check_dims(
615
+ batch_size, image_height, image_width)
616
+ min_batch, max_batch, min_latent_height, max_latent_height, min_latent_width, max_latent_width, min_height, max_height, min_width, max_width = \
617
+ self.get_minmax_dims(batch_size, image_height,
618
+ image_width, static_batch, static_shape)
619
+ return {
620
+ 'sample': [(2*min_batch, 4, min_latent_height, min_latent_width), (2*batch_size, 4, latent_height, latent_width), (2*max_batch, 4, max_latent_height, max_latent_width)],
621
+ 'encoder_hidden_states': [(2*min_batch, self.text_maxlen, self.embedding_dim), (2*batch_size, self.text_maxlen, self.embedding_dim), (2*max_batch, self.text_maxlen, self.embedding_dim)],
622
+ 'controlnet_cond': [(2*min_batch, 3, min_height, min_width), (2*batch_size, 3, image_height, image_width), (2*max_batch, 3, max_height, max_width)]
623
+ }
624
+
625
+ def get_shape_dict(self, batch_size, image_height, image_width):
626
+ latent_height, latent_width = self.check_dims(
627
+ batch_size, image_height, image_width)
628
+ return {
629
+ 'sample': (2*batch_size, 4, latent_height, latent_width),
630
+ 'encoder_hidden_states': (2*batch_size, self.text_maxlen, self.embedding_dim),
631
+ 'controlnet_cond': (2*batch_size, 3, image_height, image_width),
632
+ 'latent': (2*batch_size, 4, latent_height, latent_width)
633
+ }
634
+
635
+ def get_sample_input(self, batch_size, image_height, image_width):
636
+ latent_height, latent_width = self.check_dims(
637
+ batch_size, image_height, image_width)
638
+ dtype = torch.float16 if self.fp16 else torch.float32
639
+ return (
640
+ torch.randn(2*batch_size, 4, latent_height, latent_width,
641
+ dtype=torch.float32, device=self.device), # sample
642
+ torch.tensor([1.], dtype=torch.float32, device=self.device), # timestep
643
+ torch.randn(2*batch_size, self.text_maxlen, # encoder_hidden_states
644
+ self.embedding_dim, dtype=dtype, device=self.device),
645
+ torch.randn(2*batch_size, 3, image_height, image_width,
646
+ dtype=torch.float32, device=self.device) # controlnet_cond
647
+ )
648
+
649
+ def optimize(self, onnx_graph, minimal_optimization=False):
650
+ class_name = self.__class__.__name__
651
+
652
+ enable_optimization = not minimal_optimization
653
+
654
+ # Decompose InstanceNormalization into primitive Ops
655
+ bRemoveInstanceNorm = enable_optimization
656
+ # Remove Cast Node to optimize Attention block
657
+ bRemoveCastNode = enable_optimization
658
+ # Remove parallel Swish ops
659
+ bRemoveParallelSwish = enable_optimization
660
+ # Adjust the bias to be the second input to the Add ops
661
+ bAdjustAddNode = enable_optimization
662
+ # Change Resize node to take size instead of scale
663
+ bResizeFix = enable_optimization
664
+
665
+ # Common override for disabling all plugins below
666
+ bDisablePlugins = minimal_optimization
667
+ # Use multi-head attention Plugin
668
+ bMHAPlugin = True
669
+ # Use multi-head cross attention Plugin
670
+ bMHCAPlugin = True
671
+ # Insert GroupNormalization Plugin
672
+ bGroupNormPlugin = True
673
+ # Insert LayerNormalization Plugin
674
+ bLayerNormPlugin = True
675
+ # Insert Split+GeLU Plugin
676
+ bSplitGeLUPlugin = True
677
+ # Replace BiasAdd+ResidualAdd+SeqLen2Spatial with plugin
678
+ bSeqLen2SpatialPlugin = True
679
+
680
+ opt = Optimizer(onnx_graph, verbose=self.verbose)
681
+ opt.info(f'{class_name}: original')
682
+
683
+ if bRemoveInstanceNorm:
684
+ num_instancenorm_replaced = opt.decompose_instancenorms()
685
+ opt.info(f'{class_name}: replaced ' +
686
+ str(num_instancenorm_replaced)+' InstanceNorms')
687
+
688
+ if bRemoveCastNode:
689
+ num_casts_removed = opt.remove_casts()
690
+ opt.info(f'{class_name}: removed '+str(num_casts_removed)+' casts')
691
+
692
+ if bRemoveParallelSwish:
693
+ num_parallel_swish_removed = opt.remove_parallel_swish()
694
+ opt.info(f'{class_name}: removed ' +
695
+ str(num_parallel_swish_removed)+' parallel swish ops')
696
+
697
+ if bAdjustAddNode:
698
+ num_adjust_add = opt.adjustAddNode()
699
+ opt.info(f'{class_name}: adjusted '+str(num_adjust_add)+' adds')
700
+
701
+ if bResizeFix:
702
+ num_resize_fix = opt.resize_fix()
703
+ opt.info(f'{class_name}: fixed '+str(num_resize_fix)+' resizes')
704
+
705
+ opt.cleanup()
706
+ opt.info(f'{class_name}: cleanup')
707
+ opt.fold_constants()
708
+ opt.info(f'{class_name}: fold constants')
709
+ opt.infer_shapes()
710
+ opt.info(f'{class_name}: shape inference')
711
+
712
+ num_heads = 8
713
+ if bMHAPlugin and not bDisablePlugins:
714
+ num_fmha_inserted = opt.insert_fmha_plugin(num_heads)
715
+ opt.info(f'{class_name}: inserted '+str(num_fmha_inserted)+' fMHA plugins')
716
+
717
+ if bMHCAPlugin and not bDisablePlugins:
718
+ props = cudart.cudaGetDeviceProperties(0)[1]
719
+ sm = props.major * 10 + props.minor
720
+ num_fmhca_inserted = opt.insert_fmhca_plugin(num_heads, sm)
721
+ opt.info(f'{class_name}: inserted '+str(num_fmhca_inserted)+' fMHCA plugins')
722
+
723
+ if bGroupNormPlugin and not bDisablePlugins:
724
+ num_groupnorm_inserted = opt.insert_groupnorm_plugin()
725
+ opt.info(f'{class_name}: inserted '+str(num_groupnorm_inserted) +
726
+ ' GroupNorm plugins')
727
+
728
+ if bLayerNormPlugin and not bDisablePlugins:
729
+ num_layernorm_inserted = opt.insert_layernorm_plugin()
730
+ opt.info(f'{class_name}: inserted '+str(num_layernorm_inserted) +
731
+ ' LayerNorm plugins')
732
+
733
+ if bSplitGeLUPlugin and not bDisablePlugins:
734
+ num_splitgelu_inserted = opt.insert_splitgelu_plugin()
735
+ opt.info(f'{class_name}: inserted '+str(num_splitgelu_inserted) +
736
+ ' SplitGeLU plugins')
737
+
738
+ if bSeqLen2SpatialPlugin and not bDisablePlugins:
739
+ num_seq2spatial_inserted = opt.insert_seq2spatial_plugin()
740
+ opt.info(f'{class_name}: inserted '+str(num_seq2spatial_inserted) +
741
+ ' SeqLen2Spatial plugins')
742
+
743
+ onnx_opt_graph = opt.cleanup(return_onnx=True)
744
+ opt.info(f'{class_name}: final')
745
+ return onnx_opt_graph
746
+
747
+
748
+ class ControlNetModule(nn.Module):
749
+ def __init__(self, control_model_dir, fp16=True) -> None:
750
+ super().__init__()
751
+ self.device = 'cuda:0'
752
+ self.fp16 = fp16
753
+ model_opts = {'revision': 'fp16',
754
+ 'torch_dtype': torch.float16} if self.fp16 else {}
755
+ self.control = ControlNetModel.from_pretrained(
756
+ control_model_dir,
757
+ **model_opts
758
+ ).eval().to(self.device)
759
+
760
+ def forward(self, sample, timestep, encoder_hidden_states, controlnet_cond):
761
+ controlnet_conditioning_scale: float = 1.0
762
+ down_block_res_samples, mid_block_res_sample = self.control(
763
+ sample,
764
+ timestep,
765
+ encoder_hidden_states=encoder_hidden_states,
766
+ controlnet_cond=controlnet_cond,
767
+ return_dict=False,
768
+ )
769
+ down_block_res_samples = [
770
+ down_block_res_sample * controlnet_conditioning_scale
771
+ for down_block_res_sample in down_block_res_samples
772
+ ]
773
+ mid_block_res_sample *= controlnet_conditioning_scale
774
+ # @vane: currently, only retun mid_blocks_res_sample: (B, 1280, height//8//8, width//8//8)
775
+ # down_block_res_samples is a tensor tuple that length is 12.
776
+ # it will be flatten to 12 nodes if we return the down_block_res_samples
777
+ return mid_block_res_sample
778
+
779
+
780
+ class ControlNet(FusedControlNet):
781
+ def __init__(self, local_model_path=None, controlnet_model_path=None, hf_token=None, text_maxlen=77,
782
+ embedding_dim=768, fp16=False, device='cuda', verbose=True, max_batch_size=16):
783
+ super().__init__(local_model_path, controlnet_model_path, hf_token,
784
+ text_maxlen, embedding_dim, fp16, device, verbose, max_batch_size)
785
+
786
+ def get_model(self):
787
+ model = ControlNetModule(
788
+ control_model_dir=self.controlnet_model_path,
789
+ fp16=self.fp16
790
+ )
791
+ return model
792
+
793
+ def get_input_names(self):
794
+ return ['sample', 'timestep', 'encoder_hidden_states', 'controlnet_cond']
795
+
796
+ def get_output_names(self):
797
+ return ['mids']
798
+
799
+ def get_dynamic_axes(self):
800
+ return {
801
+ 'sample': {0: '2B', 2: '8H', 3: '8W'},
802
+ 'encoder_hidden_states': {0: '2B'},
803
+ 'controlnet_cond': {0: '2B', 2: '16H', 3: '16W'},
804
+ 'mids': {0: '2B', 2: 'H', 3: 'W'}
805
+ }
806
+
807
+ def get_shape_dict(self, batch_size, image_height, image_width):
808
+ latent_height, latent_width = self.check_dims(
809
+ batch_size, image_height, image_width)
810
+ return {
811
+ 'sample': (2*batch_size, 4, latent_height, latent_width),
812
+ 'encoder_hidden_states': (2*batch_size, self.text_maxlen, self.embedding_dim),
813
+ 'controlnet_cond': (2*batch_size, 3, image_height, image_width),
814
+ 'mids': (2*batch_size, 1280, latent_height//8, latent_width//8)
815
+ }
lyraSD/muse_trt/sd_img2img.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ StableDiffusion Img2Img Pipeline by TensorRT.
3
+ It has included SuperResolutionX4 TensorRT Engine.
4
+
5
+ Inspired by: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py
6
+ https://developer.nvidia.com/tensorrt
7
+ """
8
+
9
+ import inspect
10
+ import os
11
+ from typing import List, Optional, Union
12
+
13
+ import numpy as np
14
+ import PIL.Image
15
+ import tensorrt as trt
16
+ import torch
17
+ import time
18
+ from diffusers import AutoencoderKL
19
+ from diffusers.schedulers import DPMSolverMultistepScheduler
20
+ from diffusers.models.vae import DiagonalGaussianDistribution
21
+ from diffusers.utils import PIL_INTERPOLATION, randn_tensor
22
+ from polygraphy import cuda
23
+ from transformers import CLIPTokenizer
24
+
25
+ from .models import CLIP, UNet, VAEDecoder, VAEEncoder
26
+ from .super import SuperX4TRTInfer
27
+ from .utilities import TRT_LOGGER, Engine
28
+
29
+
30
+ def preprocess(image):
31
+ if isinstance(image, torch.Tensor):
32
+ return image
33
+ elif isinstance(image, PIL.Image.Image):
34
+ image = [image]
35
+
36
+ if isinstance(image[0], PIL.Image.Image):
37
+ w, h = image[0].size
38
+ w, h = map(lambda x: x - x % 8, (w, h)) # resize to integer multiple of 8
39
+
40
+ image = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]))[None, :] for i in image]
41
+ image = np.concatenate(image, axis=0)
42
+ image = np.array(image).astype(np.float32) / 255.0
43
+ image = image.transpose(0, 3, 1, 2)
44
+ image = 2.0 * image - 1.0
45
+ image = torch.from_numpy(image)
46
+ elif isinstance(image[0], torch.Tensor):
47
+ image = torch.cat(image, dim=0)
48
+ return image
49
+
50
+
51
+ class TRTStableDiffusionImg2ImgPipeline:
52
+ def __init__(self, engine_dir: str, o_height: int = 1300, o_width: int = 750, device: str = 'cuda:0'):
53
+ self.device = torch.device(device)
54
+ super().__init__()
55
+ self.vae = AutoencoderKL.from_pretrained(
56
+ os.path.join(engine_dir, 'vae'),
57
+ torch_dtype=torch.float16
58
+ ).to(self.device)
59
+
60
+ self.tokenizer = CLIPTokenizer.from_pretrained(
61
+ os.path.join(engine_dir, 'tokenizer')
62
+ )
63
+ self.scheduler = DPMSolverMultistepScheduler.from_pretrained(
64
+ os.path.join(engine_dir, 'scheduler')
65
+ )
66
+
67
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
68
+ self.trt_torch_models_cls = {
69
+ 'clip': CLIP(),
70
+ 'unet_fp16': UNet(),
71
+ 'vae-encoder': VAEEncoder(),
72
+ 'vae-decoder': VAEDecoder()
73
+ }
74
+
75
+ self.engine = {}
76
+ # Build engines
77
+ for model_name, _ in self.trt_torch_models_cls.items():
78
+ engine = Engine(model_name, engine_dir)
79
+ self.engine[model_name] = engine
80
+ # Separate iteration to activate engines
81
+ for model_name, _ in self.trt_torch_models_cls.items():
82
+ self.engine[model_name].activate()
83
+ self.stream = cuda.Stream()
84
+
85
+ self.super = SuperX4TRTInfer(
86
+ engine_dir,
87
+ model_name='superx4.plan',
88
+ fp16=True,
89
+ o_height=o_height,
90
+ o_width=o_width
91
+ )
92
+
93
+ def runEngine(self, model_name, feed_dict):
94
+ engine = self.engine[model_name]
95
+ return engine.infer(feed_dict, self.stream)
96
+
97
+ def _torch_decode_latents(self, latents):
98
+ latents = 1 / self.vae.config.scaling_factor * latents
99
+ image = self.vae.decode(latents).sample
100
+ image = (image / 2 + 0.5).clamp(0, 1)
101
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
102
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
103
+ image = (image * 255).round()
104
+ return image
105
+
106
+ def _trt_decode_latents(self, latents):
107
+ latents = 1 / self.vae.config.scaling_factor * latents
108
+ sample_inp = cuda.DeviceView(
109
+ ptr=latents.data_ptr(), shape=latents.shape, dtype=np.float32)
110
+ image = self.runEngine('vae-decoder', {"latent": sample_inp})['images']
111
+ image = (image / 2 + 0.5).clamp(0, 1)
112
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
113
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
114
+ image = (image * 255).round()
115
+
116
+ return image
117
+
118
+ def prepare_extra_step_kwargs(self, generator, eta):
119
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
120
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
121
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
122
+ # and should be between [0, 1]
123
+
124
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
125
+ extra_step_kwargs = {}
126
+ if accepts_eta:
127
+ extra_step_kwargs["eta"] = eta
128
+
129
+ # check if the scheduler accepts generator
130
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
131
+ if accepts_generator:
132
+ extra_step_kwargs["generator"] = generator
133
+ return extra_step_kwargs
134
+
135
+ def get_timesteps(self, num_inference_steps, strength, device):
136
+ # get the original timestep using init_timestep
137
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
138
+
139
+ t_start = max(num_inference_steps - init_timestep, 0)
140
+ timesteps = self.scheduler.timesteps[t_start:]
141
+
142
+ return timesteps, num_inference_steps - t_start
143
+
144
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
145
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
146
+ raise ValueError(
147
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
148
+ )
149
+
150
+ image = image.to(device=device, dtype=dtype)
151
+
152
+ batch_size = batch_size * num_images_per_prompt
153
+ if isinstance(generator, list) and len(generator) != batch_size:
154
+ raise ValueError(
155
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
156
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
157
+ )
158
+
159
+ if isinstance(generator, list):
160
+ init_latents = [
161
+ self.vae.encode(image[i: i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
162
+ ]
163
+ init_latents = torch.cat(init_latents, dim=0)
164
+ else:
165
+ init_latents = self.vae.encode(image).latent_dist.sample(generator)
166
+
167
+ init_latents = self.vae.config.scaling_factor * init_latents
168
+
169
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
170
+ raise ValueError(
171
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
172
+ )
173
+ else:
174
+ init_latents = torch.cat([init_latents], dim=0)
175
+
176
+ shape = init_latents.shape
177
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
178
+
179
+ # get latents
180
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
181
+ latents = init_latents
182
+
183
+ return latents
184
+
185
+ def _default_height_width(self, height, width, image):
186
+ if isinstance(image, list):
187
+ image = image[0]
188
+
189
+ if height is None:
190
+ if isinstance(image, PIL.Image.Image):
191
+ height = image.height
192
+ elif isinstance(image, torch.Tensor):
193
+ height = image.shape[3]
194
+
195
+ height = (height // 8) * 8 # round down to nearest multiple of 8
196
+
197
+ if width is None:
198
+ if isinstance(image, PIL.Image.Image):
199
+ width = image.width
200
+ elif isinstance(image, torch.Tensor):
201
+ width = image.shape[2]
202
+
203
+ width = (width // 8) * 8 # round down to nearest multiple of 8
204
+
205
+ return height, width
206
+
207
+ def _trt_encode_prompt(self, prompt, negative_prompt, num_images_per_prompt,):
208
+ # Tokenize input
209
+ text_input_ids = self.tokenizer(
210
+ prompt,
211
+ padding="max_length",
212
+ max_length=self.tokenizer.model_max_length,
213
+ return_tensors="pt",
214
+ ).input_ids.type(torch.int32).to(self.device)
215
+
216
+ # CLIP text encoder
217
+ text_input_ids_inp = cuda.DeviceView(
218
+ ptr=text_input_ids.data_ptr(), shape=text_input_ids.shape, dtype=np.int32
219
+ )
220
+ text_embeddings = self.runEngine('clip', {"input_ids": text_input_ids_inp})['text_embeddings']
221
+
222
+ # Duplicate text embeddings for each generation per prompt
223
+ bs_embed, seq_len, _ = text_embeddings.shape
224
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
225
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
226
+
227
+ max_length = text_input_ids.shape[-1]
228
+ uncond_input_ids = self.tokenizer(
229
+ negative_prompt,
230
+ padding="max_length",
231
+ max_length=max_length,
232
+ truncation=True,
233
+ return_tensors="pt",
234
+ ).input_ids.type(torch.int32).to(self.device)
235
+ uncond_input_ids_inp = cuda.DeviceView(
236
+ ptr=uncond_input_ids.data_ptr(), shape=uncond_input_ids.shape, dtype=np.int32)
237
+ uncond_embeddings = self.runEngine('clip', {"input_ids": uncond_input_ids_inp})['text_embeddings']
238
+
239
+ # Duplicate unconditional embeddings for each generation per prompt
240
+ seq_len = uncond_embeddings.shape[1]
241
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
242
+ uncond_embeddings = uncond_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
243
+
244
+ # Concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes for classifier free guidance
245
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
246
+ text_embeddings = text_embeddings.to(dtype=torch.float16)
247
+
248
+ return text_embeddings
249
+
250
+ @torch.no_grad()
251
+ def __call__(
252
+ self,
253
+ prompt: Union[str, List[str]] = None,
254
+ image: Union[torch.Tensor, PIL.Image.Image] = None,
255
+ strength: float = 0.8,
256
+ height: Optional[int] = None,
257
+ width: Optional[int] = None,
258
+ num_inference_steps: int = 50,
259
+ guidance_scale: float = 7.5,
260
+ negative_prompt: Optional[Union[str, List[str]]] = None,
261
+ num_images_per_prompt: Optional[int] = 1,
262
+ eta: float = 0.0,
263
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
264
+ latents: Optional[torch.FloatTensor] = None,
265
+ prompt_embeds: Optional[torch.FloatTensor] = None,
266
+ use_super: bool = True,
267
+ ):
268
+ # 1. Default height and width to unet
269
+ height, width = self._default_height_width(height, width, image)
270
+
271
+ # 2. Define call parameters and Allocate the cuda buffers for TRT Engine bindings.
272
+ if prompt is not None and isinstance(prompt, str):
273
+ batch_size = 1
274
+ elif prompt is not None and isinstance(prompt, list):
275
+ batch_size = len(prompt)
276
+ else:
277
+ batch_size = prompt_embeds.shape[0]
278
+
279
+ # Allocate buffers for TensorRT engine bindings
280
+ for model_name, obj in self.trt_torch_models_cls.items():
281
+ self.engine[model_name].allocate_buffers(
282
+ shape_dict=obj.get_shape_dict(batch_size, height, width),
283
+ device=self.device
284
+ )
285
+
286
+ do_classifier_free_guidance = guidance_scale > 1.0
287
+
288
+ with trt.Runtime(TRT_LOGGER) as runtime:
289
+ torch.cuda.synchronize()
290
+
291
+ # 3. Encode input prompt. TRT Clip model.
292
+ prompt_embeds = self._trt_encode_prompt(
293
+ prompt, negative_prompt, num_images_per_prompt
294
+ )
295
+
296
+ # 4. Prepare mask, image, and controlnet_conditioning_image
297
+ image = preprocess(image)
298
+
299
+ # 5. Prepare timesteps.
300
+ self.scheduler.set_timesteps(num_inference_steps, device=self.device)
301
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, self.device)
302
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
303
+
304
+ # 6. Prepare latent variables. It will use VAE-Enoder(currently the encoder is torch model, not trt)
305
+ latents = self.prepare_latents(
306
+ image,
307
+ latent_timestep,
308
+ batch_size,
309
+ num_images_per_prompt,
310
+ prompt_embeds.dtype,
311
+ self.device,
312
+ generator,
313
+ )
314
+
315
+ # 7. Prepare extra step kwargs and Set lantens/controlnet_conditioning_image/prompt_embeds to special dtype.
316
+ # The dytpe must be equal to the following to ensure that the NAN can not be issued in trt engine.
317
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
318
+ latents = latents.to(dtype=torch.float32)
319
+ prompt_embeds = prompt_embeds.to(dtype=torch.float16)
320
+
321
+ # 8. Denoising loop
322
+ for i, t in enumerate(timesteps):
323
+ # expand the latents if we are doing classifier free guidance
324
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
325
+
326
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
327
+
328
+ # predict the noise residual
329
+
330
+ dtype = np.float16
331
+ if t.dtype != torch.float32:
332
+ timestep_float = t.float()
333
+ else:
334
+ timestep_float = t
335
+
336
+ sample_inp = cuda.DeviceView(
337
+ ptr=latent_model_input.data_ptr(), shape=latent_model_input.shape, dtype=np.float32
338
+ )
339
+ timestep_inp = cuda.DeviceView(
340
+ ptr=timestep_float.data_ptr(), shape=timestep_float.shape, dtype=np.float32
341
+ )
342
+ embeddings_inp = cuda.DeviceView(
343
+ ptr=prompt_embeds.data_ptr(), shape=prompt_embeds.shape, dtype=dtype
344
+ )
345
+
346
+ noise_pred = self.engine['unet_fp16'].infer(
347
+ {"sample": sample_inp, "timestep": timestep_inp, "encoder_hidden_states": embeddings_inp},
348
+ self.stream)['latent']
349
+ # perform guidance
350
+ if do_classifier_free_guidance:
351
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
352
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
353
+
354
+ # compute the previous noisy sample x_t -> x_t-1
355
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
356
+
357
+ # 9. Use VAE-Decoder to decode the latents
358
+ image = self._trt_decode_latents(latents)
359
+
360
+ # 10. SuperX4 Resolution, Optional.
361
+ if use_super:
362
+ image = self.super.infer(np.transpose(image.astype(np.float16), (0, 3, 1, 2)))
363
+
364
+ return image
365
+
lyraSD/muse_trt/sd_text2img.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ StableDiffusion Text2Img Pipeline by TensorRT.
3
+ It has included SuperResolutionX4 TensorRT Engine.
4
+
5
+ Inspired by: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py
6
+ https://developer.nvidia.com/tensorrt
7
+ """
8
+
9
+ import inspect
10
+ import os
11
+ from typing import List, Optional, Union
12
+
13
+ import numpy as np
14
+ import tensorrt as trt
15
+ import torch
16
+ from diffusers import AutoencoderKL
17
+ from diffusers.schedulers import DPMSolverMultistepScheduler
18
+ from diffusers.utils import PIL_INTERPOLATION, randn_tensor
19
+ from polygraphy import cuda
20
+ from transformers import CLIPTokenizer
21
+
22
+ from .models import CLIP, UNet, VAEDecoder
23
+ from .super import SuperX4TRTInfer
24
+ from .utilities import TRT_LOGGER, Engine
25
+
26
+
27
+ class TRTStableDiffusionText2ImgPipeline:
28
+ def __init__(self, engine_dir: str, o_height: int = 512, o_width: int = 512, device: str = 'cuda:0'):
29
+ self.device = torch.device(device)
30
+ super().__init__()
31
+ self.vae = AutoencoderKL.from_pretrained(
32
+ os.path.join(engine_dir, 'vae'),
33
+ torch_dtype=torch.float16
34
+ ).to(self.device)
35
+
36
+ self.tokenizer = CLIPTokenizer.from_pretrained(
37
+ os.path.join(engine_dir, 'tokenizer')
38
+ )
39
+ self.scheduler = DPMSolverMultistepScheduler.from_pretrained(
40
+ os.path.join(engine_dir, 'scheduler')
41
+ )
42
+
43
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
44
+ self.trt_torch_models_cls = {
45
+ 'clip': CLIP(),
46
+ 'unet_fp16': UNet(),
47
+ 'vae-decoder': VAEDecoder()
48
+ }
49
+
50
+ self.engine = {}
51
+ # Build engines
52
+ for model_name, _ in self.trt_torch_models_cls.items():
53
+ engine = Engine(model_name, engine_dir)
54
+ self.engine[model_name] = engine
55
+ # Separate iteration to activate engines
56
+ for model_name, _ in self.trt_torch_models_cls.items():
57
+ self.engine[model_name].activate()
58
+ self.stream = cuda.Stream()
59
+
60
+ self.super = SuperX4TRTInfer(
61
+ engine_dir,
62
+ model_name='superx4.plan',
63
+ fp16=True,
64
+ o_height=o_height,
65
+ o_width=o_width
66
+ )
67
+
68
+ def runEngine(self, model_name, feed_dict):
69
+ engine = self.engine[model_name]
70
+ return engine.infer(feed_dict, self.stream)
71
+
72
+ def _torch_decode_latents(self, latents):
73
+ latents = 1 / self.vae.config.scaling_factor * latents
74
+ image = self.vae.decode(latents).sample
75
+ image = (image / 2 + 0.5).clamp(0, 1)
76
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
77
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
78
+ image = (image * 255).round()
79
+ return image
80
+
81
+ def _trt_decode_latents(self, latents):
82
+ latents = 1 / self.vae.config.scaling_factor * latents
83
+ sample_inp = cuda.DeviceView(
84
+ ptr=latents.data_ptr(), shape=latents.shape, dtype=np.float32)
85
+ image = self.runEngine('vae-decoder', {"latent": sample_inp})['images']
86
+ image = (image / 2 + 0.5).clamp(0, 1)
87
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
88
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
89
+ image = (image * 255).round()
90
+
91
+ return image
92
+
93
+ def prepare_extra_step_kwargs(self, generator, eta):
94
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
95
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
96
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
97
+ # and should be between [0, 1]
98
+
99
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
100
+ extra_step_kwargs = {}
101
+ if accepts_eta:
102
+ extra_step_kwargs["eta"] = eta
103
+
104
+ # check if the scheduler accepts generator
105
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
106
+ if accepts_generator:
107
+ extra_step_kwargs["generator"] = generator
108
+ return extra_step_kwargs
109
+
110
+ def get_timesteps(self, num_inference_steps, strength, device):
111
+ # get the original timestep using init_timestep
112
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
113
+
114
+ t_start = max(num_inference_steps - init_timestep, 0)
115
+ timesteps = self.scheduler.timesteps[t_start:]
116
+
117
+ return timesteps, num_inference_steps - t_start
118
+
119
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
120
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
121
+ if isinstance(generator, list) and len(generator) != batch_size:
122
+ raise ValueError(
123
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
124
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
125
+ )
126
+
127
+ if latents is None:
128
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
129
+ else:
130
+ latents = latents.to(device)
131
+
132
+ # scale the initial noise by the standard deviation required by the scheduler
133
+ latents = latents * self.scheduler.init_noise_sigma
134
+ return latents
135
+
136
+ def _trt_encode_prompt(self, prompt, negative_prompt, num_images_per_prompt,):
137
+ # Tokenize input
138
+ text_input_ids = self.tokenizer(
139
+ prompt,
140
+ padding="max_length",
141
+ max_length=self.tokenizer.model_max_length,
142
+ return_tensors="pt",
143
+ ).input_ids.type(torch.int32).to(self.device)
144
+
145
+ # CLIP text encoder
146
+ text_input_ids_inp = cuda.DeviceView(
147
+ ptr=text_input_ids.data_ptr(), shape=text_input_ids.shape, dtype=np.int32
148
+ )
149
+ text_embeddings = self.runEngine('clip', {"input_ids": text_input_ids_inp})['text_embeddings']
150
+
151
+ # Duplicate text embeddings for each generation per prompt
152
+ bs_embed, seq_len, _ = text_embeddings.shape
153
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
154
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
155
+
156
+ max_length = text_input_ids.shape[-1]
157
+ uncond_input_ids = self.tokenizer(
158
+ negative_prompt,
159
+ padding="max_length",
160
+ max_length=max_length,
161
+ truncation=True,
162
+ return_tensors="pt",
163
+ ).input_ids.type(torch.int32).to(self.device)
164
+ uncond_input_ids_inp = cuda.DeviceView(
165
+ ptr=uncond_input_ids.data_ptr(), shape=uncond_input_ids.shape, dtype=np.int32)
166
+ uncond_embeddings = self.runEngine('clip', {"input_ids": uncond_input_ids_inp})['text_embeddings']
167
+
168
+ # Duplicate unconditional embeddings for each generation per prompt
169
+ seq_len = uncond_embeddings.shape[1]
170
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
171
+ uncond_embeddings = uncond_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
172
+
173
+ # Concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes for classifier free guidance
174
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
175
+ text_embeddings = text_embeddings.to(dtype=torch.float16)
176
+
177
+ return text_embeddings
178
+
179
+ @torch.no_grad()
180
+ def __call__(
181
+ self,
182
+ prompt: Union[str, List[str]] = None,
183
+ height: Optional[int] = None,
184
+ width: Optional[int] = None,
185
+ num_inference_steps: int = 50,
186
+ guidance_scale: float = 7.5,
187
+ negative_prompt: Optional[Union[str, List[str]]] = None,
188
+ num_images_per_prompt: Optional[int] = 1,
189
+ eta: float = 0.0,
190
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
191
+ latents: Optional[torch.FloatTensor] = None,
192
+ prompt_embeds: Optional[torch.FloatTensor] = None,
193
+ use_super: bool = True,
194
+ ):
195
+ # 1. Default height and width to unet
196
+ assert height is not None, "height can not be None"
197
+ assert width is not None, "width can not be None"
198
+
199
+ # 2. Define call parameters and Allocate the cuda buffers for TRT Engine bindings.
200
+ if prompt is not None and isinstance(prompt, str):
201
+ batch_size = 1
202
+ elif prompt is not None and isinstance(prompt, list):
203
+ batch_size = len(prompt)
204
+ else:
205
+ batch_size = prompt_embeds.shape[0]
206
+
207
+ # Allocate buffers for TensorRT engine bindings
208
+ for model_name, obj in self.trt_torch_models_cls.items():
209
+ self.engine[model_name].allocate_buffers(
210
+ shape_dict=obj.get_shape_dict(batch_size, height, width),
211
+ device=self.device
212
+ )
213
+
214
+ do_classifier_free_guidance = guidance_scale > 1.0
215
+
216
+ with trt.Runtime(TRT_LOGGER) as runtime:
217
+ torch.cuda.synchronize()
218
+
219
+ # 3. Encode input prompt. TRT Clip model.
220
+ prompt_embeds = self._trt_encode_prompt(
221
+ prompt, negative_prompt, num_images_per_prompt
222
+ )
223
+
224
+ # 4. Prepare timesteps.
225
+ self.scheduler.set_timesteps(num_inference_steps, device=self.device)
226
+ timesteps = self.scheduler.timesteps
227
+
228
+ # 5. Prepare latent variables. It will use VAE-Enoder(currently the encoder is torch model, not trt)
229
+ num_channels_latents = 4
230
+ latents = self.prepare_latents(
231
+ batch_size*num_images_per_prompt,
232
+ num_channels_latents,
233
+ height,
234
+ width,
235
+ prompt_embeds.dtype,
236
+ self.device,
237
+ generator,
238
+ latents
239
+ )
240
+
241
+ # 6. Prepare extra step kwargs and Set lantens/controlnet_conditioning_image/prompt_embeds to special dtype.
242
+ # The dytpe must be equal to the following to ensure that the NAN can not be issued in trt engine.
243
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
244
+ latents = latents.to(dtype=torch.float32)
245
+ prompt_embeds = prompt_embeds.to(dtype=torch.float16)
246
+
247
+ # 7. Denoising loop
248
+ for i, t in enumerate(timesteps):
249
+ # expand the latents if we are doing classifier free guidance
250
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
251
+
252
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
253
+
254
+ # predict the noise residual
255
+
256
+ dtype = np.float16
257
+ if t.dtype != torch.float32:
258
+ timestep_float = t.float()
259
+ else:
260
+ timestep_float = t
261
+
262
+ sample_inp = cuda.DeviceView(
263
+ ptr=latent_model_input.data_ptr(), shape=latent_model_input.shape, dtype=np.float32
264
+ )
265
+ timestep_inp = cuda.DeviceView(
266
+ ptr=timestep_float.data_ptr(), shape=timestep_float.shape, dtype=np.float32
267
+ )
268
+ embeddings_inp = cuda.DeviceView(
269
+ ptr=prompt_embeds.data_ptr(), shape=prompt_embeds.shape, dtype=dtype
270
+ )
271
+
272
+ noise_pred = self.engine['unet_fp16'].infer(
273
+ {"sample": sample_inp, "timestep": timestep_inp, "encoder_hidden_states": embeddings_inp},
274
+ self.stream)['latent']
275
+ # perform guidance
276
+ if do_classifier_free_guidance:
277
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
278
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
279
+
280
+ # compute the previous noisy sample x_t -> x_t-1
281
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
282
+
283
+ # 8. Use VAE-Decoder to decode the latents
284
+ image = self._trt_decode_latents(latents)
285
+
286
+ # 9. SuperX4 Resolution, Optional.
287
+ if use_super:
288
+ image = self.super.infer(np.transpose(image.astype(np.float16), (0, 3, 1, 2)))
289
+ image = np.transpose(image, (0,3,1,2))
290
+ return image
lyraSD/muse_trt/super.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""use tensorrt engine to infer, a useful pipeline"""
2
+
3
+ import os
4
+
5
+ import numpy as np
6
+ from polygraphy import cuda
7
+ from polygraphy.backend.common import bytes_from_path
8
+ from polygraphy.backend.trt import engine_from_bytes
9
+
10
+
11
+ class SuperX4TRTInfer:
12
+ def __init__(self, engine_dir,
13
+ model_name='superx4.plan',
14
+ o_height=None,
15
+ o_width=None,
16
+ fp16=True,
17
+ ) -> None:
18
+ engine_path = os.path.join(engine_dir, model_name)
19
+ self.engine = engine_from_bytes(bytes_from_path(engine_path))
20
+ self.context = self.engine.create_execution_context()
21
+
22
+ self.o_height = o_height
23
+ self.o_width = o_width
24
+ self.fp = fp16
25
+ self.dtype = np.float16 if fp16 else np.float32
26
+
27
+ self.stream = cuda.Stream()
28
+
29
+ def infer(self, x):
30
+ batch_size, channel, height, width = x.shape
31
+ if self.o_height is None or self.o_width is None:
32
+ o_height = height*4
33
+ o_width = width*4
34
+ else:
35
+ o_height = self.o_height
36
+ o_width = self.o_width
37
+
38
+ h_output = np.empty([batch_size, channel, o_height, o_width], dtype=self.dtype)
39
+
40
+ # allocate device memory
41
+ d_input = cuda.wrapper().malloc(1 * x.nbytes)
42
+ d_output = cuda.wrapper().malloc(1*h_output.nbytes)
43
+
44
+ bindings = [int(d_input), int(d_output)]
45
+
46
+ # transfer input data to device
47
+ cuda.wrapper().memcpy(d_input, x.ctypes.data, x.nbytes, cuda.MemcpyKind.HostToDevice, self.stream.ptr)
48
+
49
+ # execute model
50
+ noerror = self.context.execute_async_v2(bindings, self.stream.ptr)
51
+ if not noerror:
52
+ raise ValueError(f"ERROR: inference failed.")
53
+
54
+ # transfer predictions back
55
+ cuda.wrapper().memcpy(h_output.ctypes.data, d_output, h_output.nbytes, cuda.MemcpyKind.DeviceToHost, self.stream.ptr)
56
+ cuda.wrapper().free(d_input)
57
+ cuda.wrapper().free(d_output)
58
+
59
+ return h_output
60
+
61
+ def teardown(self):
62
+ del self.engine
63
+ self.stream.free()
64
+ del self.stream
lyraSD/muse_trt/utilities.py ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""utils components"""
2
+
3
+ from collections import OrderedDict
4
+ from copy import copy
5
+ import numpy as np
6
+ import os
7
+ import math
8
+ from PIL import Image
9
+ from polygraphy.backend.common import bytes_from_path
10
+ from polygraphy.backend.trt import CreateConfig, Profile
11
+ from polygraphy.backend.trt import engine_from_bytes, engine_from_network, network_from_onnx_path, save_engine
12
+ from polygraphy.backend.trt import util as trt_util
13
+ from polygraphy import cuda
14
+ import random
15
+ from scipy import integrate
16
+ import tensorrt as trt
17
+ import torch
18
+
19
+ TRT_LOGGER = trt.Logger(trt.Logger.WARNING)
20
+
21
+
22
+ class Engine():
23
+ def __init__(
24
+ self,
25
+ model_name,
26
+ engine_dir,
27
+ memory_pool_size=None
28
+ ):
29
+ self.engine_path = os.path.join(engine_dir, model_name+'.plan')
30
+ self.engine = None
31
+ self.context = None
32
+ self.buffers = OrderedDict()
33
+ self.tensors = OrderedDict()
34
+ self.memory_pool_size = memory_pool_size
35
+
36
+ def __del__(self):
37
+ [buf.free() for buf in self.buffers.values() if isinstance(buf, cuda.DeviceArray)]
38
+ del self.engine
39
+ del self.context
40
+ del self.buffers
41
+ del self.tensors
42
+
43
+ def build(self, onnx_path, fp16, input_profile=None, enable_preview=False):
44
+ print(f"Building TensorRT engine for {onnx_path}: {self.engine_path}")
45
+ p = Profile()
46
+ if input_profile:
47
+ for name, dims in input_profile.items():
48
+ assert len(dims) == 3
49
+ p.add(name, min=dims[0], opt=dims[1], max=dims[2])
50
+
51
+ preview_features = []
52
+ if enable_preview:
53
+ trt_version = [int(i) for i in trt.__version__.split(".")]
54
+ # FASTER_DYNAMIC_SHAPES_0805 should only be used for TRT 8.5.1 or above.
55
+ if trt_version[0] > 8 or \
56
+ (trt_version[0] == 8 and (trt_version[1] > 5 or (trt_version[1] == 5 and trt_version[2] >= 1))):
57
+ preview_features = [trt.PreviewFeature.FASTER_DYNAMIC_SHAPES_0805]
58
+
59
+ if self.memory_pool_size is not None:
60
+ memory_pool_limits = {trt.MemoryPoolType.WORKSPACE: (self.memory_pool_size*(2 ** 30))}
61
+ print(memory_pool_limits)
62
+ else:
63
+ memory_pool_limits = None
64
+ engine = engine_from_network(
65
+ network_from_onnx_path(onnx_path),
66
+ config=CreateConfig(
67
+ fp16=fp16, profiles=[p], preview_features=preview_features, memory_pool_limits=memory_pool_limits
68
+ )
69
+ )
70
+ save_engine(engine, path=self.engine_path)
71
+
72
+ def activate(self):
73
+ print(f"Loading TensorRT engine: {self.engine_path}")
74
+ self.engine = engine_from_bytes(bytes_from_path(self.engine_path))
75
+ self.context = self.engine.create_execution_context()
76
+
77
+ def allocate_buffers(self, shape_dict=None, device='cuda'):
78
+ for idx in range(trt_util.get_bindings_per_profile(self.engine)):
79
+ binding = self.engine[idx]
80
+ if shape_dict and binding in shape_dict:
81
+ shape = shape_dict[binding]
82
+ else:
83
+ shape = self.engine.get_binding_shape(binding)
84
+ dtype = trt_util.np_dtype_from_trt(self.engine.get_binding_dtype(binding))
85
+ if self.engine.binding_is_input(binding):
86
+ self.context.set_binding_shape(idx, shape)
87
+ # Workaround to convert np dtype to torch
88
+ np_type_tensor = np.empty(shape=[], dtype=dtype)
89
+ torch_type_tensor = torch.from_numpy(np_type_tensor)
90
+ tensor = torch.empty(tuple(shape), dtype=torch_type_tensor.dtype).to(device=device)
91
+ self.tensors[binding] = tensor
92
+ self.buffers[binding] = cuda.DeviceView(ptr=tensor.data_ptr(), shape=shape, dtype=dtype)
93
+
94
+ def infer(self, feed_dict, stream):
95
+ start_binding, end_binding = trt_util.get_active_profile_bindings(self.context)
96
+ # shallow copy of ordered dict
97
+ device_buffers = copy(self.buffers)
98
+ for name, buf in feed_dict.items():
99
+ assert isinstance(buf, cuda.DeviceView)
100
+ device_buffers[name] = buf
101
+ bindings = [0] * start_binding + [buf.ptr for buf in device_buffers.values()]
102
+ noerror = self.context.execute_async_v2(bindings=bindings, stream_handle=stream.ptr)
103
+ if not noerror:
104
+ raise ValueError(f"ERROR: inference failed.")
105
+
106
+ return self.tensors
107
+
108
+
109
+ class LMSDiscreteScheduler():
110
+ def __init__(
111
+ self,
112
+ device='cuda',
113
+ beta_start=0.00085,
114
+ beta_end=0.012,
115
+ num_train_timesteps=1000,
116
+ ):
117
+ self.num_train_timesteps = num_train_timesteps
118
+ self.order = 4
119
+
120
+ self.beta_start = beta_start
121
+ self.beta_end = beta_end
122
+ betas = (torch.linspace(beta_start**0.5, beta_end**0.5, self.num_train_timesteps, dtype=torch.float32) ** 2)
123
+ alphas = 1.0 - betas
124
+ self.alphas_cumprod = torch.cumprod(alphas, dim=0)
125
+
126
+ sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
127
+ sigmas = np.concatenate([sigmas[::-1], [0.0]]).astype(np.float32)
128
+ self.sigmas = torch.from_numpy(sigmas)
129
+
130
+ # standard deviation of the initial noise distribution
131
+ self.init_noise_sigma = self.sigmas.max()
132
+
133
+ self.device = device
134
+
135
+ def set_timesteps(self, steps):
136
+ self.num_inference_steps = steps
137
+
138
+ timesteps = np.linspace(0, self.num_train_timesteps - 1, steps, dtype=float)[::-1].copy()
139
+ sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
140
+ sigmas = np.interp(timesteps, np.arange(0, len(sigmas)), sigmas)
141
+ sigmas = np.concatenate([sigmas, [0.0]]).astype(np.float32)
142
+ self.sigmas = torch.from_numpy(sigmas).to(device=self.device)
143
+
144
+ # Move all timesteps to correct device beforehand
145
+ self.timesteps = torch.from_numpy(timesteps).to(device=self.device).float()
146
+ self.derivatives = []
147
+
148
+ def scale_model_input(self, sample: torch.FloatTensor, idx, *args, **kwargs) -> torch.FloatTensor:
149
+ return sample * self.latent_scales[idx]
150
+
151
+ def configure(self):
152
+ order = self.order
153
+ self.lms_coeffs = []
154
+ self.latent_scales = [1./((sigma**2 + 1) ** 0.5) for sigma in self.sigmas]
155
+
156
+ def get_lms_coefficient(order, t, current_order):
157
+ """
158
+ Compute a linear multistep coefficient.
159
+ """
160
+ def lms_derivative(tau):
161
+ prod = 1.0
162
+ for k in range(order):
163
+ if current_order == k:
164
+ continue
165
+ prod *= (tau - self.sigmas[t - k]) / (self.sigmas[t - current_order] - self.sigmas[t - k])
166
+ return prod
167
+ integrated_coeff = integrate.quad(lms_derivative, self.sigmas[t], self.sigmas[t + 1], epsrel=1e-4)[0]
168
+ return integrated_coeff
169
+
170
+ for step_index in range(self.num_inference_steps):
171
+ order = min(step_index + 1, order)
172
+ self.lms_coeffs.append([get_lms_coefficient(order, step_index, curr_order) for curr_order in range(order)])
173
+
174
+ def step(self, output, latents, idx, timestep):
175
+ # compute the previous noisy sample x_t -> x_t-1
176
+ # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
177
+ sigma = self.sigmas[idx]
178
+ pred_original_sample = latents - sigma * output
179
+ # 2. Convert to an ODE derivative
180
+ derivative = (latents - pred_original_sample) / sigma
181
+ self.derivatives.append(derivative)
182
+ if len(self.derivatives) > self.order:
183
+ self.derivatives.pop(0)
184
+ # 3. Compute previous sample based on the derivatives path
185
+ prev_sample = latents + sum(
186
+ coeff * derivative for coeff, derivative in zip(self.lms_coeffs[idx], reversed(self.derivatives))
187
+ )
188
+
189
+ return prev_sample
190
+
191
+
192
+ class DPMScheduler():
193
+ def __init__(
194
+ self,
195
+ beta_start=0.00085,
196
+ beta_end=0.012,
197
+ num_train_timesteps=1000,
198
+ solver_order=2,
199
+ predict_epsilon=True,
200
+ thresholding=False,
201
+ dynamic_thresholding_ratio=0.995,
202
+ sample_max_value=1.0,
203
+ algorithm_type="dpmsolver++",
204
+ solver_type="midpoint",
205
+ lower_order_final=True,
206
+ device='cuda',
207
+ ):
208
+ # this schedule is very specific to the latent diffusion model.
209
+ self.betas = (
210
+ torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
211
+ )
212
+
213
+ self.device = device
214
+ self.alphas = 1.0 - self.betas
215
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
216
+ # Currently we only support VP-type noise schedule
217
+ self.alpha_t = torch.sqrt(self.alphas_cumprod)
218
+ self.sigma_t = torch.sqrt(1 - self.alphas_cumprod)
219
+ self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t)
220
+
221
+ # standard deviation of the initial noise distribution
222
+ self.init_noise_sigma = 1.0
223
+
224
+ self.algorithm_type = algorithm_type
225
+ self.predict_epsilon = predict_epsilon
226
+ self.thresholding = thresholding
227
+ self.dynamic_thresholding_ratio = dynamic_thresholding_ratio
228
+ self.sample_max_value = sample_max_value
229
+ self.lower_order_final = lower_order_final
230
+
231
+ # settings for DPM-Solver
232
+ if algorithm_type not in ["dpmsolver", "dpmsolver++"]:
233
+ raise NotImplementedError(f"{algorithm_type} does is not implemented for {self.__class__}")
234
+ if solver_type not in ["midpoint", "heun"]:
235
+ raise NotImplementedError(f"{solver_type} does is not implemented for {self.__class__}")
236
+
237
+ # setable values
238
+ self.num_inference_steps = None
239
+ self.solver_order = solver_order
240
+ self.num_train_timesteps = num_train_timesteps
241
+ self.solver_type = solver_type
242
+
243
+ self.first_order_first_coef = []
244
+ self.first_order_second_coef = []
245
+
246
+ self.second_order_first_coef = []
247
+ self.second_order_second_coef = []
248
+ self.second_order_third_coef = []
249
+
250
+ self.third_order_first_coef = []
251
+ self.third_order_second_coef = []
252
+ self.third_order_third_coef = []
253
+ self.third_order_fourth_coef = []
254
+
255
+ def scale_model_input(self, sample: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
256
+ return sample
257
+
258
+ def configure(self):
259
+ lower_order_nums = 0
260
+ for step_index in range(self.num_inference_steps):
261
+ step_idx = step_index
262
+ timestep = self.timesteps[step_idx]
263
+
264
+ prev_timestep = 0 if step_idx == len(self.timesteps) - 1 else self.timesteps[step_idx + 1]
265
+
266
+ self.dpm_solver_first_order_coefs_precompute(timestep, prev_timestep)
267
+
268
+ timestep_list = [self.timesteps[step_index - 1], timestep]
269
+ self.multistep_dpm_solver_second_order_coefs_precompute(timestep_list, prev_timestep)
270
+
271
+ timestep_list = [self.timesteps[step_index - 2], self.timesteps[step_index - 1], timestep]
272
+ self.multistep_dpm_solver_third_order_coefs_precompute(timestep_list, prev_timestep)
273
+
274
+ if lower_order_nums < self.solver_order:
275
+ lower_order_nums += 1
276
+
277
+ def dpm_solver_first_order_coefs_precompute(self, timestep, prev_timestep):
278
+ lambda_t, lambda_s = self.lambda_t[prev_timestep], self.lambda_t[timestep]
279
+ alpha_t, alpha_s = self.alpha_t[prev_timestep], self.alpha_t[timestep]
280
+ sigma_t, sigma_s = self.sigma_t[prev_timestep], self.sigma_t[timestep]
281
+ h = lambda_t - lambda_s
282
+ if self.algorithm_type == "dpmsolver++":
283
+ self.first_order_first_coef.append(sigma_t / sigma_s)
284
+ self.first_order_second_coef.append(alpha_t * (torch.exp(-h) - 1.0))
285
+ elif self.algorithm_type == "dpmsolver":
286
+ self.first_order_first_coef.append(alpha_t / alpha_s)
287
+ self.first_order_second_coef.append(sigma_t * (torch.exp(h) - 1.0))
288
+
289
+ def multistep_dpm_solver_second_order_coefs_precompute(self, timestep_list, prev_timestep):
290
+ t, s0, s1 = prev_timestep, timestep_list[-1], timestep_list[-2]
291
+ lambda_t, lambda_s0, lambda_s1 = self.lambda_t[t], self.lambda_t[s0], self.lambda_t[s1]
292
+ alpha_t, alpha_s0 = self.alpha_t[t], self.alpha_t[s0]
293
+ sigma_t, sigma_s0 = self.sigma_t[t], self.sigma_t[s0]
294
+ h = lambda_t - lambda_s0
295
+ if self.algorithm_type == "dpmsolver++":
296
+ # See https://arxiv.org/abs/2211.01095 for detailed derivations
297
+ if self.solver_type == "midpoint":
298
+ self.second_order_first_coef.append(sigma_t / sigma_s0)
299
+ self.second_order_second_coef.append((alpha_t * (torch.exp(-h) - 1.0)))
300
+ self.second_order_third_coef.append(0.5 * (alpha_t * (torch.exp(-h) - 1.0)))
301
+ elif self.solver_type == "heun":
302
+ self.second_order_first_coef.append(sigma_t / sigma_s0)
303
+ self.second_order_second_coef.append((alpha_t * (torch.exp(-h) - 1.0)))
304
+ self.second_order_third_coef.append(alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0))
305
+ elif self.algorithm_type == "dpmsolver":
306
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
307
+ if self.solver_type == "midpoint":
308
+ self.second_order_first_coef.append(alpha_t / alpha_s0)
309
+ self.second_order_second_coef.append((sigma_t * (torch.exp(h) - 1.0)))
310
+ self.second_order_third_coef.append(0.5 * (sigma_t * (torch.exp(h) - 1.0)))
311
+ elif self.solver_type == "heun":
312
+ self.second_order_first_coef.append(alpha_t / alpha_s0)
313
+ self.second_order_second_coef.append((sigma_t * (torch.exp(h) - 1.0)))
314
+ self.second_order_third_coef.append((sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)))
315
+
316
+ def multistep_dpm_solver_third_order_coefs_precompute(self, timestep_list, prev_timestep):
317
+ t, s0 = prev_timestep, timestep_list[-1]
318
+ lambda_t, lambda_s0 = (
319
+ self.lambda_t[t],
320
+ self.lambda_t[s0]
321
+ )
322
+ alpha_t, alpha_s0 = self.alpha_t[t], self.alpha_t[s0]
323
+ sigma_t, sigma_s0 = self.sigma_t[t], self.sigma_t[s0]
324
+ h = lambda_t - lambda_s0
325
+ if self.algorithm_type == "dpmsolver++":
326
+ self.third_order_first_coef.append(sigma_t / sigma_s0)
327
+ self.third_order_second_coef.append(alpha_t * (torch.exp(-h) - 1.0))
328
+ self.third_order_third_coef.append(alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0))
329
+ self.third_order_fourth_coef.append(alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5))
330
+ elif self.algorithm_type == "dpmsolver":
331
+ self.third_order_first_coef.append(alpha_t / alpha_s0)
332
+ self.third_order_second_coef.append(sigma_t * (torch.exp(h) - 1.0))
333
+ self.third_order_third_coef.append(sigma_t * ((torch.exp(h) - 1.0) / h - 1.0))
334
+ self.third_order_fourth_coef.append(sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5))
335
+
336
+ def set_timesteps(self, num_inference_steps):
337
+ self.num_inference_steps = num_inference_steps
338
+ timesteps = (
339
+ np.linspace(0, self.num_train_timesteps - 1, num_inference_steps + 1)
340
+ .round()[::-1][:-1]
341
+ .copy()
342
+ .astype(np.int32)
343
+ )
344
+ self.timesteps = torch.from_numpy(timesteps).to(self.device)
345
+ self.model_outputs = [
346
+ None,
347
+ ] * self.solver_order
348
+ self.lower_order_nums = 0
349
+
350
+ def convert_model_output(
351
+ self, model_output, timestep, sample
352
+ ):
353
+ # DPM-Solver++ needs to solve an integral of the data prediction model.
354
+ if self.algorithm_type == "dpmsolver++":
355
+ if self.predict_epsilon:
356
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
357
+ x0_pred = (sample - sigma_t * model_output) / alpha_t
358
+ else:
359
+ x0_pred = model_output
360
+ if self.thresholding:
361
+ # Dynamic thresholding in https://arxiv.org/abs/2205.11487
362
+ dynamic_max_val = torch.quantile(
363
+ torch.abs(x0_pred).reshape((x0_pred.shape[0], -1)), self.dynamic_thresholding_ratio, dim=1
364
+ )
365
+ dynamic_max_val = torch.maximum(
366
+ dynamic_max_val,
367
+ self.sample_max_value * torch.ones_like(dynamic_max_val).to(dynamic_max_val.device),
368
+ )[(...,) + (None,) * (x0_pred.ndim - 1)]
369
+ x0_pred = torch.clamp(x0_pred, -dynamic_max_val, dynamic_max_val) / dynamic_max_val
370
+ return x0_pred
371
+ # DPM-Solver needs to solve an integral of the noise prediction model.
372
+ elif self.algorithm_type == "dpmsolver":
373
+ if self.predict_epsilon:
374
+ return model_output
375
+ else:
376
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
377
+ epsilon = (sample - alpha_t * model_output) / sigma_t
378
+ return epsilon
379
+
380
+ def dpm_solver_first_order_update(
381
+ self,
382
+ idx,
383
+ model_output,
384
+ sample
385
+ ):
386
+ first_coef = self.first_order_first_coef[idx]
387
+ second_coef = self.first_order_second_coef[idx]
388
+
389
+ if self.algorithm_type == "dpmsolver++":
390
+ x_t = first_coef * sample - second_coef * model_output
391
+ elif self.algorithm_type == "dpmsolver":
392
+ x_t = first_coef * sample - second_coef * model_output
393
+ return x_t
394
+
395
+ def multistep_dpm_solver_second_order_update(
396
+ self,
397
+ idx,
398
+ model_output_list,
399
+ timestep_list,
400
+ prev_timestep,
401
+ sample
402
+ ):
403
+ t, s0, s1 = prev_timestep, timestep_list[-1], timestep_list[-2]
404
+ m0, m1 = model_output_list[-1], model_output_list[-2]
405
+ lambda_t, lambda_s0, lambda_s1 = self.lambda_t[t], self.lambda_t[s0], self.lambda_t[s1]
406
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
407
+ r0 = h_0 / h
408
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
409
+
410
+ first_coef = self.second_order_first_coef[idx]
411
+ second_coef = self.second_order_second_coef[idx]
412
+ third_coef = self.second_order_third_coef[idx]
413
+
414
+ if self.algorithm_type == "dpmsolver++":
415
+ # See https://arxiv.org/abs/2211.01095 for detailed derivations
416
+ if self.solver_type == "midpoint":
417
+ x_t = (
418
+ first_coef * sample
419
+ - second_coef * D0
420
+ - third_coef * D1
421
+ )
422
+ elif self.solver_type == "heun":
423
+ x_t = (
424
+ first_coef * sample
425
+ - second_coef * D0
426
+ + third_coef * D1
427
+ )
428
+ elif self.algorithm_type == "dpmsolver":
429
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
430
+ if self.solver_type == "midpoint":
431
+ x_t = (
432
+ first_coef * sample
433
+ - second_coef * D0
434
+ - third_coef * D1
435
+ )
436
+ elif self.solver_type == "heun":
437
+ x_t = (
438
+ first_coef * sample
439
+ - second_coef * D0
440
+ - third_coef * D1
441
+ )
442
+ return x_t
443
+
444
+ def multistep_dpm_solver_third_order_update(
445
+ self,
446
+ idx,
447
+ model_output_list,
448
+ timestep_list,
449
+ prev_timestep,
450
+ sample
451
+ ):
452
+ t, s0, s1, s2 = prev_timestep, timestep_list[-1], timestep_list[-2], timestep_list[-3]
453
+ m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3]
454
+ lambda_t, lambda_s0, lambda_s1, lambda_s2 = (
455
+ self.lambda_t[t],
456
+ self.lambda_t[s0],
457
+ self.lambda_t[s1],
458
+ self.lambda_t[s2],
459
+ )
460
+ h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2
461
+ r0, r1 = h_0 / h, h_1 / h
462
+ D0 = m0
463
+ D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2)
464
+ D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1)
465
+ D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1)
466
+
467
+ first_coef = self.third_order_first_coef[idx]
468
+ second_coef = self.third_order_second_coef[idx]
469
+ third_coef = self.third_order_third_coef[idx]
470
+ fourth_coef = self.third_order_fourth_coef[idx]
471
+
472
+ if self.algorithm_type == "dpmsolver++":
473
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
474
+ x_t = (
475
+ first_coef * sample
476
+ - second_coef * D0
477
+ + third_coef * D1
478
+ - fourth_coef * D2
479
+ )
480
+ elif self.algorithm_type == "dpmsolver":
481
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
482
+ x_t = (
483
+ first_coef * sample
484
+ - second_coef * D0
485
+ - third_coef * D1
486
+ - fourth_coef * D2
487
+ )
488
+ return x_t
489
+
490
+ def step(self, output, latents, step_index, timestep):
491
+ if self.num_inference_steps is None:
492
+ raise ValueError(
493
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
494
+ )
495
+
496
+ prev_timestep = 0 if step_index == len(self.timesteps) - 1 else self.timesteps[step_index + 1]
497
+ lower_order_final = (
498
+ (step_index == len(self.timesteps) - 1) and self.lower_order_final and len(self.timesteps) < 15
499
+ )
500
+ lower_order_second = (
501
+ (step_index == len(self.timesteps) - 2) and self.lower_order_final and len(self.timesteps) < 15
502
+ )
503
+
504
+ output = self.convert_model_output(output, timestep, latents)
505
+ for i in range(self.solver_order - 1):
506
+ self.model_outputs[i] = self.model_outputs[i + 1]
507
+ self.model_outputs[-1] = output
508
+
509
+ if self.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
510
+ prev_sample = self.dpm_solver_first_order_update(step_index, output, latents)
511
+ elif self.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
512
+ timestep_list = [self.timesteps[step_index - 1], timestep]
513
+ prev_sample = self.multistep_dpm_solver_second_order_update(
514
+ step_index, self.model_outputs, timestep_list, prev_timestep, latents
515
+ )
516
+ else:
517
+ timestep_list = [self.timesteps[step_index - 2], self.timesteps[step_index - 1], timestep]
518
+ prev_sample = self.multistep_dpm_solver_third_order_update(
519
+ step_index, self.model_outputs, timestep_list, prev_timestep, latents
520
+ )
521
+
522
+ if self.lower_order_nums < self.solver_order:
523
+ self.lower_order_nums += 1
524
+
525
+ return prev_sample
526
+
527
+
528
+ def save_image(images, image_path_dir, image_name_prefix):
529
+ """
530
+ Save the generated images to png files.
531
+ """
532
+ images = ((images + 1) * 255 / 2).clamp(0, 255).detach().permute(0, 2, 3, 1).round().type(torch.uint8).cpu().numpy()
533
+ for i in range(images.shape[0]):
534
+ image_path = os.path.join(image_path_dir, image_name_prefix+str(i+1)+'-'+str(random.randint(1000, 9999))+'.png')
535
+ print(f"Saving image {i+1} / {images.shape[0]} to: {image_path}")
536
+ Image.fromarray(images[i]).save(image_path)